From 92015c1a13889712d7061baadf3edbbd5c5f4362 Mon Sep 17 00:00:00 2001 From: FatBoy-DOTC Date: Mon, 15 May 2023 19:01:43 -0500 Subject: [PATCH 001/109] guards no longer ignore early exit. FSM will not run if no players are online. mobs will use translocate instead of recall power. --- src/engine/ai/MobileFSM.java | 10 ++++------ src/engine/ai/MobileFSMManager.java | 3 ++- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/engine/ai/MobileFSM.java b/src/engine/ai/MobileFSM.java index 7b9ad4e9..69846d01 100644 --- a/src/engine/ai/MobileFSM.java +++ b/src/engine/ai/MobileFSM.java @@ -331,7 +331,7 @@ public class MobileFSM { CheckForRespawn(mob); return; } - if (mob.playerAgroMap.isEmpty() && mob.isPlayerGuard == false) + if (mob.playerAgroMap.isEmpty()) //no players loaded, no need to proceed return; if (mob.isCombat() && mob.getCombatTarget() == null) { @@ -492,21 +492,19 @@ public class MobileFSM { if (mob.isPlayerGuard() && !mob.despawned) { City current = ZoneManager.getCityAtLocation(mob.getLoc()); if (current == null || current.equals(mob.getGuild().getOwnedCity()) == false || mob.playerAgroMap.isEmpty()) { - PowersBase recall = PowersManager.getPowerByToken(-1994153779); - PowersManager.useMobPower(mob, mob, recall, 40); + MovementManager.translocate(mob,mob.getBindLoc(),null); mob.setCombatTarget(null); if(mob.BehaviourType.ordinal() == Enum.MobBehaviourType.GuardCaptain.ordinal() && mob.isAlive()){ //guard captain pulls his minions home with him for (Entry minion : mob.siegeMinionMap.entrySet()) { - PowersManager.useMobPower(minion.getKey(), minion.getKey(), recall, 40); + MovementManager.translocate(minion.getKey(),mob.getBindLoc(),null); minion.getKey().setCombatTarget(null); } } } } else if(MovementUtilities.inRangeOfBindLocation(mob) == false) { - PowersBase recall = PowersManager.getPowerByToken(-1994153779); - PowersManager.useMobPower(mob, mob, recall, 40); + MovementManager.translocate(mob,mob.getBindLoc(),null); mob.setCombatTarget(null); } } diff --git a/src/engine/ai/MobileFSMManager.java b/src/engine/ai/MobileFSMManager.java index f8b0fd52..3073e877 100644 --- a/src/engine/ai/MobileFSMManager.java +++ b/src/engine/ai/MobileFSMManager.java @@ -8,6 +8,7 @@ package engine.ai; +import engine.gameManager.SessionManager; import engine.gameManager.ZoneManager; import engine.objects.Mob; import engine.objects.Zone; @@ -88,7 +89,7 @@ public class MobileFSMManager { for (Mob mob : zone.zoneMobSet) { try { - if (mob != null) + if (mob != null && SessionManager.getActivePlayerCharacterCount() > 0) MobileFSM.DetermineAction(mob); } catch (Exception e) { Logger.error("Mob: " + mob.getName() + " UUID: " + mob.getObjectUUID() + " ERROR: " + e); From 8916d9b4f0a9e230c9753518e24560bed5962b8e Mon Sep 17 00:00:00 2001 From: MagicBot Date: Wed, 17 May 2023 15:11:26 -0400 Subject: [PATCH 002/109] Begin try-with-resources cleanup. --- src/discord/Database.java | 107 +++++++++++++------------------------- 1 file changed, 35 insertions(+), 72 deletions(-) diff --git a/src/discord/Database.java b/src/discord/Database.java index c5ef40f2..62888856 100644 --- a/src/discord/Database.java +++ b/src/discord/Database.java @@ -54,15 +54,13 @@ public class Database { public boolean updateAccountPassword(String discordAccountID, String newPassword) { try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), - ConfigManager.MB_DATABASE_PASS.getValue())) { - - CallableStatement updatePassword = connection.prepareCall("call discordUpdatePassword(?, ?)"); + ConfigManager.MB_DATABASE_PASS.getValue()); + PreparedStatement updateStatement = connection.prepareStatement("call discordUpdatePassword(?, ?)")) { - updatePassword.setString(1, discordAccountID); - updatePassword.setString(2, newPassword); + updateStatement.setString(1, discordAccountID); + updateStatement.setString(2, newPassword); - updatePassword.executeUpdate(); - updatePassword.close(); + updateStatement.executeUpdate(); return true; } catch (SQLException e) { @@ -75,15 +73,13 @@ public class Database { public boolean updateAccountStatus(String discordAccountID, Enum.AccountStatus accountStatus) { try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), - ConfigManager.MB_DATABASE_PASS.getValue())) { + ConfigManager.MB_DATABASE_PASS.getValue()); + PreparedStatement updateStatement = connection.prepareStatement("update obj_account set `status` = ? where `discordAccount` = ?")) { - PreparedStatement updateAccountStatus = connection.prepareCall("update obj_account set `status` = ? where `discordAccount` = ?"); + updateStatement.setString(1, accountStatus.name()); + updateStatement.setString(2, discordAccountID); - updateAccountStatus.setString(1, accountStatus.name()); - updateAccountStatus.setString(2, discordAccountID); - - updateAccountStatus.executeUpdate(); - updateAccountStatus.close(); + updateStatement.executeUpdate(); return true; } catch (SQLException e) { @@ -98,14 +94,13 @@ public class Database { try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), ConfigManager.MB_DATABASE_PASS.getValue())) { - CallableStatement registerAccount = connection.prepareCall("call discordAccountRegister(?, ?, ?)"); + PreparedStatement registerStatement = connection.prepareStatement("call discordAccountRegister(?, ?, ?)"); - registerAccount.setString(1, discordAccountID); - registerAccount.setString(2, discordUserName); - registerAccount.setString(3, discordPassword); + registerStatement.setString(1, discordAccountID); + registerStatement.setString(2, discordUserName); + registerStatement.setString(3, discordPassword); - registerAccount.execute(); - registerAccount.close(); + registerStatement.execute(); return true; } catch (SQLException e) { @@ -123,11 +118,11 @@ public class Database { String queryString = "SELECT * FROM obj_account where discordAccount = ?"; try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), - ConfigManager.MB_DATABASE_PASS.getValue())) { + ConfigManager.MB_DATABASE_PASS.getValue()); + PreparedStatement accountQuery = connection.prepareStatement(queryString);) { // Discord account name based lookup - PreparedStatement accountQuery = connection.prepareStatement(queryString); accountQuery.setString(1, discordAccountID); ResultSet rs = accountQuery.executeQuery(); @@ -169,11 +164,8 @@ public class Database { String queryString = "SELECT * FROM dyn_trash_detail;"; try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), - ConfigManager.MB_DATABASE_PASS.getValue())) { - - // Discord account name based lookup - - PreparedStatement trashQuery = connection.prepareStatement(queryString); + ConfigManager.MB_DATABASE_PASS.getValue()); + PreparedStatement trashQuery = connection.prepareStatement(queryString)) { ResultSet rs = trashQuery.executeQuery(); @@ -195,15 +187,11 @@ public class Database { public String getTrashList() { String outString = ""; - String queryString = "SELECT DISTINCT `characterName` FROM dyn_trash_detail;"; int counter = 0; try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), - ConfigManager.MB_DATABASE_PASS.getValue())) { - - // Discord account name based lookup - - PreparedStatement trashQuery = connection.prepareStatement(queryString); + ConfigManager.MB_DATABASE_PASS.getValue()); + PreparedStatement trashQuery = connection.prepareStatement("SELECT DISTINCT `characterName` FROM dyn_trash_detail;")) { ResultSet rs = trashQuery.executeQuery(); @@ -234,14 +222,9 @@ public class Database { int trashCount = 0; - String queryString = "SELECT count(distinct characterName) FROM dyn_trash_detail;"; - try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), - ConfigManager.MB_DATABASE_PASS.getValue())) { - - // Discord account name based lookup - - PreparedStatement trashQuery = connection.prepareStatement(queryString); + ConfigManager.MB_DATABASE_PASS.getValue()); + PreparedStatement trashQuery = connection.prepareStatement("SELECT count(distinct characterName) FROM dyn_trash_detail;")) { ResultSet rs = trashQuery.executeQuery(); @@ -259,23 +242,17 @@ public class Database { public void setAdminEventAsRead(int adminEvent) { - String queryString = "UPDATE dyn_admin_log SET `SentFlag` = 1 WHERE `entry` = ? "; - try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), - ConfigManager.MB_DATABASE_PASS.getValue())) { - - PreparedStatement updateAdminEvent = connection.prepareCall(queryString); + ConfigManager.MB_DATABASE_PASS.getValue()); + PreparedStatement updateAdminEvent = connection.prepareStatement("UPDATE dyn_admin_log SET `SentFlag` = 1 WHERE `entry` = ? ")) { updateAdminEvent.setInt(1, adminEvent); updateAdminEvent.executeUpdate(); - updateAdminEvent.close(); - return; } catch (SQLException e) { Logger.error(e.toString()); online = false; - return; } } @@ -283,14 +260,11 @@ public class Database { public HashMap getAdminEvents() { HashMap outMap = new HashMap<>(); - String queryString = "SELECT * from dyn_admin_log where `SentFlag` = 0"; try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), - ConfigManager.MB_DATABASE_PASS.getValue())) { - - // Discord Admin Log lookup of unreported events + ConfigManager.MB_DATABASE_PASS.getValue()); + PreparedStatement adminLogQuery = connection.prepareStatement("SELECT * from dyn_admin_log where `SentFlag` = 0")) { - PreparedStatement adminLogQuery = connection.prepareStatement(queryString); ResultSet rs = adminLogQuery.executeQuery(); String workString; @@ -311,14 +285,10 @@ public class Database { public String getTrashFile() { String outString = "machineID : count\n"; - String queryString = "SELECT * FROM dyn_trash;"; try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), - ConfigManager.MB_DATABASE_PASS.getValue())) { - - // Discord account name based lookup - - PreparedStatement trashQuery = connection.prepareStatement(queryString); + ConfigManager.MB_DATABASE_PASS.getValue()); + PreparedStatement trashQuery = connection.prepareStatement("SELECT * FROM dyn_trash;")) { ResultSet rs = trashQuery.executeQuery(); @@ -346,14 +316,10 @@ public class Database { else searchString = accountName + "%#%"; - queryString = "SELECT * FROM obj_account where `acct_uname` LIKE ?"; - try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), - ConfigManager.MB_DATABASE_PASS.getValue())) { - - // Discord account name based lookup + ConfigManager.MB_DATABASE_PASS.getValue()); + PreparedStatement nameQuery = connection.prepareStatement("SELECT * FROM obj_account where `acct_uname` LIKE ?")) { - PreparedStatement nameQuery = connection.prepareStatement(queryString); nameQuery.setString(1, searchString); ResultSet rs = nameQuery.executeQuery(); @@ -394,10 +360,9 @@ public class Database { String popString = ""; try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), - ConfigManager.MB_DATABASE_PASS.getValue())) { + ConfigManager.MB_DATABASE_PASS.getValue()); + PreparedStatement getPopString = connection.prepareStatement("CALL GET_POPULATION_STRING()");) { - // Discord account name based lookup - CallableStatement getPopString = connection.prepareCall("CALL GET_POPULATION_STRING()"); ResultSet rs = getPopString.executeQuery(); if (rs.next()) @@ -414,11 +379,9 @@ public class Database { public void invalidateLoginCache(String discordAccountID) { try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), - ConfigManager.MB_DATABASE_PASS.getValue())) { - - String queryString = "INSERT IGNORE INTO login_cachelist (`UID`) SELECT `UID` from `obj_account` WHERE `discordAccount` = ?"; + ConfigManager.MB_DATABASE_PASS.getValue()); + PreparedStatement invalidateAccounts = connection.prepareStatement("INSERT IGNORE INTO login_cachelist (`UID`) SELECT `UID` from `obj_account` WHERE `discordAccount` = ?")) { - PreparedStatement invalidateAccounts = connection.prepareStatement(queryString); invalidateAccounts.setString(1, discordAccountID); invalidateAccounts.executeUpdate(); From 8a8136b8e8b5d838e245d021e10105c4d1927991 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Wed, 17 May 2023 15:18:47 -0400 Subject: [PATCH 003/109] Unused methods. --- src/engine/db/handlers/dbCityHandler.java | 7 ----- src/engine/db/handlers/dbNPCHandler.java | 35 ----------------------- 2 files changed, 42 deletions(-) diff --git a/src/engine/db/handlers/dbCityHandler.java b/src/engine/db/handlers/dbCityHandler.java index 13101ffe..0eb319bc 100644 --- a/src/engine/db/handlers/dbCityHandler.java +++ b/src/engine/db/handlers/dbCityHandler.java @@ -186,11 +186,4 @@ public class dbCityHandler extends dbHandlerBase { return (executeUpdate() > 0); } - public boolean DELETE_CITY(final City city) { - - prepareCallable("DELETE FROM `object` WHERE `UID` = ? AND `type` = 'city'"); - setInt(1, city.getObjectUUID()); - return (executeUpdate() != 0); - } - } diff --git a/src/engine/db/handlers/dbNPCHandler.java b/src/engine/db/handlers/dbNPCHandler.java index bd3b539e..49b4b082 100644 --- a/src/engine/db/handlers/dbNPCHandler.java +++ b/src/engine/db/handlers/dbNPCHandler.java @@ -75,18 +75,6 @@ public class dbNPCHandler extends dbHandlerBase { return getLargeObjectList(); } - public ArrayList GET_ALL_NPCS() { - prepareCallable("SELECT `obj_npc`.*, `object`.`parent` FROM `object` INNER JOIN `obj_npc` ON `obj_npc`.`UID` = `object`.`UID`;"); - - return getObjectList(); - } - - public ArrayList GET_NPCS_BY_BUILDING(final int buildingID) { - prepareCallable("SELECT `obj_npc`.*, `object`.`parent` FROM `obj_npc` INNER JOIN `object` ON `obj_npc`.`UID` = `object`.`UID` WHERE `npc_buildingID` = ? LIMIT 3"); - setInt(1, buildingID); - return getObjectList(); - } - public NPC GET_NPC(final int objectUUID) { prepareCallable("SELECT `obj_npc`.*, `object`.`parent` FROM `object` INNER JOIN `obj_npc` ON `obj_npc`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?;"); setLong(1, (long) objectUUID); @@ -142,8 +130,6 @@ public class dbNPCHandler extends dbHandlerBase { public boolean updateUpgradeTime(NPC npc, DateTime upgradeDateTime) { - - try { prepareCallable("UPDATE obj_npc SET upgradeDate=? " @@ -163,27 +149,6 @@ public class dbNPCHandler extends dbHandlerBase { return true; } - public boolean UPDATE_BUY_PROFIT(NPC npc,float percent) { - prepareCallable("UPDATE `obj_npc` SET `npc_buyPercent`=? WHERE `UID`=?"); - setFloat(1, percent); - setLong(2, npc.getObjectUUID()); - return (executeUpdate() > 0); - } - - public boolean UPDATE_SELL_PROFIT(NPC npc,float percent) { - prepareCallable("UPDATE `obj_npc` SET `npc_sellPercent`=? WHERE `UID`=?"); - setFloat(1, percent); - setLong(2, npc.getObjectUUID()); - return (executeUpdate() > 0); - } - - public boolean UPDATE_SLOT(NPC npc,int slot) { - prepareCallable("UPDATE `obj_npc` SET `npc_slot`=? WHERE `UID`=?"); - setFloat(1, slot); - setLong(2, npc.getObjectUUID()); - return (executeUpdate() > 0); - } - public boolean UPDATE_MOBBASE(NPC npc, int mobBaseID) { prepareCallable("UPDATE `obj_npc` SET `npc_raceID`=? WHERE `UID`=?"); setLong(1, mobBaseID); From 86539771e240913e600b83e9ff2b094b5f807e73 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Wed, 17 May 2023 16:38:08 -0400 Subject: [PATCH 004/109] Unused method. --- .../handlers/dbBuildingLocationHandler.java | 5 -- src/engine/db/handlers/dbMobHandler.java | 11 +-- src/engine/db/handlers/dbRealmHandler.java | 78 +++++++++---------- 3 files changed, 41 insertions(+), 53 deletions(-) diff --git a/src/engine/db/handlers/dbBuildingLocationHandler.java b/src/engine/db/handlers/dbBuildingLocationHandler.java index 2c642e83..7a24bfcc 100644 --- a/src/engine/db/handlers/dbBuildingLocationHandler.java +++ b/src/engine/db/handlers/dbBuildingLocationHandler.java @@ -28,9 +28,4 @@ public class dbBuildingLocationHandler extends dbHandlerBase { return getObjectList(); } - public ArrayList LOAD_ALL_BUILDING_LOCATIONS() { - prepareCallable("SELECT * FROM `static_building_location`;"); - return getObjectList(); - } - } diff --git a/src/engine/db/handlers/dbMobHandler.java b/src/engine/db/handlers/dbMobHandler.java index 004d8de8..aea15d00 100644 --- a/src/engine/db/handlers/dbMobHandler.java +++ b/src/engine/db/handlers/dbMobHandler.java @@ -80,8 +80,6 @@ public class dbMobHandler extends dbHandlerBase { public void LOAD_PATROL_POINTS(Mob captain) { - - prepareCallable("SELECT * FROM `dyn_guards` WHERE `captainUID` = ?"); setInt(1,captain.getObjectUUID()); @@ -89,31 +87,26 @@ public class dbMobHandler extends dbHandlerBase { ResultSet rs = executeQuery(); //shrines cached in rs for easy cache on creation. - while (rs.next()) { + + while (rs.next()) { int mobBaseID = rs.getInt("mobBaseID"); String name = rs.getString("name"); Mob toCreate = Mob.createGuardMob(captain, captain.getGuild(), captain.getParentZone(), captain.building.getLoc(), captain.getLevel(),name); if (toCreate == null) return; - // toCreate.despawn(); if (toCreate != null) { - toCreate.setTimeToSpawnSiege(System.currentTimeMillis() + MBServerStatics.FIFTEEN_MINUTES); toCreate.setDeathTime(System.currentTimeMillis()); - } } - } catch (SQLException e) { Logger.error( e.toString()); } finally { closeCallable(); } - - } public boolean ADD_TO_GUARDS(final long captainUID, final int mobBaseID, final String name, final int slot) { diff --git a/src/engine/db/handlers/dbRealmHandler.java b/src/engine/db/handlers/dbRealmHandler.java index 932d6425..c11147c6 100644 --- a/src/engine/db/handlers/dbRealmHandler.java +++ b/src/engine/db/handlers/dbRealmHandler.java @@ -24,50 +24,50 @@ public class dbRealmHandler extends dbHandlerBase { } - public ConcurrentHashMap LOAD_ALL_REALMS() { - - ConcurrentHashMap realmList; - Realm thisRealm; - - realmList = new ConcurrentHashMap<>(); - int recordsRead = 0; - - prepareCallable("SELECT * FROM obj_realm"); - - try { - ResultSet rs = executeQuery(); - - while (rs.next()) { - - recordsRead++; - thisRealm = new Realm(rs); - realmList.put(thisRealm.getRealmID(), thisRealm); - } - - Logger.info( "read: " + recordsRead + " cached: " + realmList.size()); - - } catch (SQLException e) { - Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); - } catch (UnknownHostException ex) { + public ConcurrentHashMap LOAD_ALL_REALMS() { + + ConcurrentHashMap realmList; + Realm thisRealm; + + realmList = new ConcurrentHashMap<>(); + int recordsRead = 0; + + prepareCallable("SELECT * FROM obj_realm"); + + try { + ResultSet rs = executeQuery(); + + while (rs.next()) { + + recordsRead++; + thisRealm = new Realm(rs); + realmList.put(thisRealm.getRealmID(), thisRealm); + } + + Logger.info("read: " + recordsRead + " cached: " + realmList.size()); + + } catch (SQLException e) { + Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); + } catch (UnknownHostException ex) { java.util.logging.Logger.getLogger(dbRealmHandler.class.getName()).log(Level.SEVERE, null, ex); } finally { - closeCallable(); - } - return realmList; - } - + closeCallable(); + } + return realmList; + } + public void REALM_UPDATE(Realm realm) { - prepareCallable("CALL realm_UPDATE(?,?,?,?)"); - - setInt(1, realm.getRealmID()); - setInt(2, (realm.getRulingCity() == null) ? 0 : realm.getRulingCity().getObjectUUID()); - setInt(3, realm.getCharterType()); + prepareCallable("CALL realm_UPDATE(?,?,?,?)"); + + setInt(1, realm.getRealmID()); + setInt(2, (realm.getRulingCity() == null) ? 0 : realm.getRulingCity().getObjectUUID()); + setInt(3, realm.getCharterType()); if (realm.ruledSince != null) setLocalDateTime(4, realm.ruledSince); - else - setNULL(4, java.sql.Types.DATE); - - executeUpdate(); + else + setNULL(4, java.sql.Types.DATE); + + executeUpdate(); } } From ba0a7d35cb4ef073c4939e4d6f0f810d01a528f9 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Thu, 18 May 2023 07:54:04 -0400 Subject: [PATCH 005/109] Error logging added. --- src/engine/db/handlers/dbRunegateHandler.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/engine/db/handlers/dbRunegateHandler.java b/src/engine/db/handlers/dbRunegateHandler.java index 86d1c575..c0cc5b01 100644 --- a/src/engine/db/handlers/dbRunegateHandler.java +++ b/src/engine/db/handlers/dbRunegateHandler.java @@ -13,6 +13,7 @@ import engine.Enum; import engine.gameManager.DbManager; import engine.objects.Building; import engine.objects.Portal; +import org.pmw.tinylog.Logger; import java.sql.ResultSet; import java.sql.SQLException; @@ -62,6 +63,7 @@ public class dbRunegateHandler extends dbHandlerBase { } } catch (SQLException e) { + Logger.error("Exception while loading runegate portals: " + e); } finally { closeCallable(); } From 4c4a909798ed300b06f10b537946b21910099f89 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Thu, 18 May 2023 07:54:04 -0400 Subject: [PATCH 006/109] Error logging added. --- src/engine/db/handlers/dbRunegateHandler.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/engine/db/handlers/dbRunegateHandler.java b/src/engine/db/handlers/dbRunegateHandler.java index 86d1c575..c0cc5b01 100644 --- a/src/engine/db/handlers/dbRunegateHandler.java +++ b/src/engine/db/handlers/dbRunegateHandler.java @@ -13,6 +13,7 @@ import engine.Enum; import engine.gameManager.DbManager; import engine.objects.Building; import engine.objects.Portal; +import org.pmw.tinylog.Logger; import java.sql.ResultSet; import java.sql.SQLException; @@ -62,6 +63,7 @@ public class dbRunegateHandler extends dbHandlerBase { } } catch (SQLException e) { + Logger.error("Exception while loading runegate portals: " + e); } finally { closeCallable(); } From 90fe93d3f0cd4385bbc0fb86606bbf131dcc6755 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Thu, 18 May 2023 08:10:54 -0400 Subject: [PATCH 007/109] Renamed for context. --- src/engine/server/login/LoginServerMsgHandler.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/engine/server/login/LoginServerMsgHandler.java b/src/engine/server/login/LoginServerMsgHandler.java index 3fd17ed5..54434e8b 100644 --- a/src/engine/server/login/LoginServerMsgHandler.java +++ b/src/engine/server/login/LoginServerMsgHandler.java @@ -449,9 +449,9 @@ public class LoginServerMsgHandler implements NetMsgHandler { Account account = session.getAccount(); account.setLastCharIDUsed(gameServerIPRequestMessage.getCharacterUUID()); - GameServerIPResponseMsg gsiprm = new GameServerIPResponseMsg(); + GameServerIPResponseMsg gameServerIPResponseMsg = new GameServerIPResponseMsg(); - if (!conn.sendMsg(gsiprm)) { + if (!conn.sendMsg(gameServerIPResponseMsg)) { Logger.error("Failed to send message"); this.KickToLogin(MBServerStatics.LOGINERROR_UNABLE_TO_LOGIN, "Unable to send GameServerIPResponseMsg to client.", conn); } From 4e863811a153b86376c50f78ec35a726da5902e8 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Thu, 18 May 2023 08:19:59 -0400 Subject: [PATCH 008/109] Removed unused methods. --- src/engine/db/handlers/dbBuildingHandler.java | 138 +----------------- 1 file changed, 3 insertions(+), 135 deletions(-) diff --git a/src/engine/db/handlers/dbBuildingHandler.java b/src/engine/db/handlers/dbBuildingHandler.java index 68eb1ba0..4b282281 100644 --- a/src/engine/db/handlers/dbBuildingHandler.java +++ b/src/engine/db/handlers/dbBuildingHandler.java @@ -16,11 +16,9 @@ import engine.Enum.TaxType; import engine.gameManager.DbManager; import engine.math.Vector3fImmutable; import engine.objects.*; -import engine.server.MBServerStatics; import org.joda.time.DateTime; import org.pmw.tinylog.Logger; -import java.awt.geom.Line2D; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDateTime; @@ -36,34 +34,6 @@ public class dbBuildingHandler extends dbHandlerBase { this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); } - public Building CREATE_BUILDING(Building b) { - try { - b = this.addBuilding(b); - b.setObjectTypeMask(MBServerStatics.MASK_BUILDING); - } catch (Exception e) { - Logger.error(e); - b = null; - } - return b; - } - - /* - * - * @param worldServerID - * @param OwnerUUID - * @param name - * @param meshUUID - * @param meshScale - * @param currentHP - * @param protectionState - * @param currentGold - * @param rank - * @param upgradeDate - * @param blueprintUUID - * @param w - * @param rotY - * @return - */ public Building CREATE_BUILDING(int parentZoneID, int OwnerUUID, String name, int meshUUID, Vector3fImmutable location, float meshScale, int currentHP, ProtectionState protectionState, int currentGold, int rank, @@ -104,9 +74,11 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (Exception e) { Logger.error("CREATE_BUILDING", e.getMessage()); return null; + } finally { + closeCallable(); } - return toCreate; + return toCreate; } public boolean DELETE_FROM_DATABASE(final Building b) { @@ -120,11 +92,6 @@ public class dbBuildingHandler extends dbHandlerBase { return getLargeObjectList(); } - public ArrayList GET_ALL_BUILDINGS() { - prepareCallable("SELECT `obj_building`.*, `object`.`parent` FROM `object` INNER JOIN `obj_building` ON `obj_building`.`UID` = `object`.`UID`;"); - return getLargeObjectList(); - } - public Building GET_BUILDINGBYUUID(int uuid) { if (uuid == 0) return null; @@ -186,56 +153,12 @@ public class dbBuildingHandler extends dbHandlerBase { return executeUpdate(); } - private Building addBuilding(Building toAdd) { - prepareCallable("CALL `building_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"); - setLong(1, toAdd.getParentZoneID()); - setLong(2, toAdd.getOwnerUUID()); - setString(3, toAdd.getName()); - setInt(4, toAdd.getMeshUUID()); - setFloat(5, toAdd.getStatLat()); - setFloat(6, toAdd.getStatAlt()); - setFloat(7, toAdd.getStatLon()); - setFloat(8, toAdd.getMeshScale().x); - setInt(9, (int) toAdd.getHealth()); - setString(10, toAdd.getProtectionState().name()); - setInt(11, toAdd.getStrongboxValue()); - setInt(12, toAdd.getRank()); - - // Write Joda DateTime to database - // *** Refactor : Wrap this logic in our - // own override setDateTime() ? - if (toAdd.getUpgradeDateTime() != null) - setLocalDateTime(13, toAdd.getUpgradeDateTime()); - else - setNULL(13, java.sql.Types.DATE); - - setInt(14, toAdd.getBlueprintUUID()); - setFloat(15, toAdd.getw()); - setFloat(16, toAdd.getRot().y); - - int objectUUID = (int) getUUID(); - - if (objectUUID > 0) - return GET_BUILDINGBYUUID(objectUUID); - return null; - - } - private boolean removeFromBuildings(final Building b) { prepareCallable("DELETE FROM `object` WHERE `UID` = ?"); setLong(1, b.getObjectUUID()); return (executeUpdate() > 0); } - public boolean ClaimAsset(final long SetBuildingID, int newowner, int OldOwner) { - - prepareCallable("UPDATE `obj_building` SET `ownerUUID`=? WHERE `UID`=? and `ownerUUID`= ?"); - setInt(1, newowner); - setLong(2, SetBuildingID); - setLong(3, OldOwner); - return (executeUpdate() > 0); - } - public boolean CHANGE_NAME(Building b, String newName) { prepareCallable("UPDATE `obj_building` SET `name`=? WHERE `UID`=?"); setString(1, newName); @@ -460,61 +383,6 @@ public class dbBuildingHandler extends dbHandlerBase { return (executeUpdate() > 0); } - public boolean ADD_TO_COLLIDE(final long parentUID, final float startX, final float startY, final float endX, final float endY) { - prepareCallable("INSERT INTO `static_building_colliders` (`MeshID`, `startX`,`startY`, `endX`, `endY`) VALUES (?,?,?,?,?)"); - setLong(1, parentUID); - setFloat(2, startX); - setFloat(3, startY); - setFloat(4, endX); - setFloat(5, endY); - return (executeUpdate() > 0); - } - - public ArrayList GET_COLLIDERS(final long meshID) { - ArrayList colliders = new ArrayList<>(); - prepareCallable("SELECT * FROM `static_building_colliders` WHERE `MeshID`=? AND `doorID` =0"); - setLong(1, meshID); - try { - ResultSet rs = executeQuery(); - while (rs.next()) { - int startX = rs.getInt("startX"); - int startY = rs.getInt("startY"); - int endX = rs.getInt("endX"); - int endY = rs.getInt("endY"); - colliders.add(new Line2D.Float(startX,startY,endX,endY)); - } - - rs.close(); - } catch (SQLException e) { - Logger.error("dbBuildingHandler.GET_COLLIDERS", e); - } finally { - closeCallable(); - } - return colliders; - } - - public ArrayList GET_DOOR_COLLIDERS(final long meshID) { - ArrayList colliders = new ArrayList<>(); - prepareCallable("SELECT * FROM `static_building_colliders` WHERE `MeshID`=? AND `doorID` <> 0"); - setLong(1, meshID); - try { - ResultSet rs = executeQuery(); - while (rs.next()) { - int startX = rs.getInt("startX"); - int startY = rs.getInt("startY"); - int endX = rs.getInt("endX"); - int endY = rs.getInt("endY"); - colliders.add(new Line2D.Float(startX,startY,endX,endY)); - } - - rs.close(); - } catch (SQLException e) { - Logger.error("dbBuildingHandler.GET_COLLIDERS", e); - } finally { - closeCallable(); - } - return colliders; - } public HashMap> LOAD_BUILDING_REGIONS() { HashMap> regions; From ac42a9cd8fe1ae94c37ea491f47259aa28025296 Mon Sep 17 00:00:00 2001 From: FatBoy-DOTC Date: Thu, 18 May 2023 19:48:37 -0500 Subject: [PATCH 009/109] removed treb override in MobileFSM.DetermineAction --- src/engine/ai/MobileFSM.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/engine/ai/MobileFSM.java b/src/engine/ai/MobileFSM.java index 69846d01..4b6e99ce 100644 --- a/src/engine/ai/MobileFSM.java +++ b/src/engine/ai/MobileFSM.java @@ -305,11 +305,6 @@ public class MobileFSM { public static void DetermineAction(Mob mob) { if (mob == null) return; - if (mob.despawned && mob.getMobBase().getLoadID() == 13171) { - //trebuchet spawn handler - CheckForRespawn(mob); - return; - } if (mob.despawned && mob.isPlayerGuard) { //override for guards if(mob.BehaviourType.ordinal() == Enum.MobBehaviourType.GuardMinion.ordinal()){ From 932daa730a7ab3bc0a150dc1d955ee5d6152c365 Mon Sep 17 00:00:00 2001 From: FatBoy-DOTC Date: Thu, 18 May 2023 19:54:54 -0500 Subject: [PATCH 010/109] guards use highbred City._playerMemory.size() and Mob.playerAgroMap to go to sleep --- src/engine/ai/MobileFSM.java | 10 +++++++--- src/engine/objects/City.java | 2 +- src/engine/objects/Mob.java | 2 ++ 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/engine/ai/MobileFSM.java b/src/engine/ai/MobileFSM.java index 4b6e99ce..65c1b08c 100644 --- a/src/engine/ai/MobileFSM.java +++ b/src/engine/ai/MobileFSM.java @@ -305,6 +305,13 @@ public class MobileFSM { public static void DetermineAction(Mob mob) { if (mob == null) return; + if (mob.playerAgroMap.isEmpty() && !mob.isPlayerGuard) + //no players loaded, no need to proceed + return; + else{ + if(mob.isPlayerGuard && mob.guardedCity._playerMemory.size() < 1 && mob.playerAgroMap.isEmpty()) + return; + } if (mob.despawned && mob.isPlayerGuard) { //override for guards if(mob.BehaviourType.ordinal() == Enum.MobBehaviourType.GuardMinion.ordinal()){ @@ -326,9 +333,6 @@ public class MobileFSM { CheckForRespawn(mob); return; } - if (mob.playerAgroMap.isEmpty()) - //no players loaded, no need to proceed - return; if (mob.isCombat() && mob.getCombatTarget() == null) { mob.setCombat(false); UpdateStateMsg rwss = new UpdateStateMsg(); diff --git a/src/engine/objects/City.java b/src/engine/objects/City.java index dbb31856..084ab55d 100644 --- a/src/engine/objects/City.java +++ b/src/engine/objects/City.java @@ -87,7 +87,7 @@ public class City extends AbstractWorldObject { // Players who have entered the city (used for adding and removing affects) - private final HashSet _playerMemory = new HashSet<>(); + public final HashSet _playerMemory = new HashSet<>(); public volatile boolean protectionEnforced = true; private String hash; diff --git a/src/engine/objects/Mob.java b/src/engine/objects/Mob.java index 2106344b..5a62cecd 100644 --- a/src/engine/objects/Mob.java +++ b/src/engine/objects/Mob.java @@ -99,6 +99,7 @@ public class Mob extends AbstractIntelligenceAgent { private DeferredPowerJob weaponPower; private DateTime upgradeDateTime = null; private boolean lootSync = false; + public City guardedCity; /** * No Id Constructor @@ -806,6 +807,7 @@ public class Mob extends AbstractIntelligenceAgent { mob.npcOwner = guardCaptain; mob.spawnTime = (int)(-2.500 * guardCaptain.building.getRank() + 22.5) * 60; mob.BehaviourType = Enum.MobBehaviourType.GuardMinion; + mob.guardedCity = guardCaptain.guardedCity; mob.parentZone = parent; parent.zoneMobSet.add(mob); return mob; From 9b5573c2100b08ac39c604215227636e3d2bef02 Mon Sep 17 00:00:00 2001 From: FatBoy-DOTC Date: Thu, 18 May 2023 19:59:39 -0500 Subject: [PATCH 011/109] guards get Mob.guardedCity assigned to --- src/engine/ai/MobileFSM.java | 1 + src/engine/objects/Mob.java | 1 + 2 files changed, 2 insertions(+) diff --git a/src/engine/ai/MobileFSM.java b/src/engine/ai/MobileFSM.java index 65c1b08c..c43cc826 100644 --- a/src/engine/ai/MobileFSM.java +++ b/src/engine/ai/MobileFSM.java @@ -310,6 +310,7 @@ public class MobileFSM { return; else{ if(mob.isPlayerGuard && mob.guardedCity._playerMemory.size() < 1 && mob.playerAgroMap.isEmpty()) + //guards use aggro map and players in their local city zone return; } if (mob.despawned && mob.isPlayerGuard) { diff --git a/src/engine/objects/Mob.java b/src/engine/objects/Mob.java index 5a62cecd..db848361 100644 --- a/src/engine/objects/Mob.java +++ b/src/engine/objects/Mob.java @@ -1989,6 +1989,7 @@ public class Mob extends AbstractIntelligenceAgent { else { this.BehaviourType = MobBehaviourType.GuardCaptain; this.spawnTime = 900; + this.guardedCity = ZoneManager.getCityAtLocation(this.bindLoc); } this.deathTime = 0; From 3c5ffed35280aec3f7ec01ed5b48f7e209b9f762 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Fri, 19 May 2023 07:57:20 -0400 Subject: [PATCH 012/109] Popstring to trywithresources --- src/discord/Database.java | 2 +- .../handlers/StatusRequestHandler.java | 2 +- .../db/handlers/dbCSSessionHandler.java | 21 ------------ src/engine/gameManager/SimulationManager.java | 34 ++++++++++++++----- 4 files changed, 27 insertions(+), 32 deletions(-) diff --git a/src/discord/Database.java b/src/discord/Database.java index 62888856..c5175cab 100644 --- a/src/discord/Database.java +++ b/src/discord/Database.java @@ -355,7 +355,7 @@ public class Database { return discordAccounts; } - public String getPopulationSTring() { + public String getPopulationString() { String popString = ""; diff --git a/src/discord/handlers/StatusRequestHandler.java b/src/discord/handlers/StatusRequestHandler.java index 473ca172..1ea836c6 100644 --- a/src/discord/handlers/StatusRequestHandler.java +++ b/src/discord/handlers/StatusRequestHandler.java @@ -29,7 +29,7 @@ public class StatusRequestHandler { outString += "OFFLINE\n"; if (Database.online == true) - outString += MagicBot.database.getPopulationSTring(); + outString += MagicBot.database.getPopulationString(); else outString += "Database offline: no population data."; diff --git a/src/engine/db/handlers/dbCSSessionHandler.java b/src/engine/db/handlers/dbCSSessionHandler.java index d76aa810..0fb5f1d4 100644 --- a/src/engine/db/handlers/dbCSSessionHandler.java +++ b/src/engine/db/handlers/dbCSSessionHandler.java @@ -36,27 +36,6 @@ public class dbCSSessionHandler extends dbHandlerBase { setString(5, machineID); return (executeUpdate() != 0); } - // This method returns population metrics from the database - - public String GET_POPULATION_STRING() { - - String outString = null; - - // Set up call to stored procedure - prepareCallable("CALL GET_POPULATION_STRING()"); - - try { - - // Evaluate database ordinal and return enum - outString = getString("popstring"); - - } catch (Exception e) { - Logger.error( "Failure in stored procedure:" + e.getMessage()); - } finally { - closeCallable(); - } - return outString; - } public boolean DELETE_UNUSED_CSSESSION(String secKey) { prepareCallable("DELETE FROM `dyn_session` WHERE `secretKey`=? && `characterID` IS NULL"); diff --git a/src/engine/gameManager/SimulationManager.java b/src/engine/gameManager/SimulationManager.java index ffb00a5d..478369e2 100644 --- a/src/engine/gameManager/SimulationManager.java +++ b/src/engine/gameManager/SimulationManager.java @@ -10,12 +10,17 @@ package engine.gameManager; import engine.Enum; import engine.Enum.GameObjectType; +import engine.db.archive.DataWarehouse; import engine.objects.AbstractGameObject; import engine.objects.City; import engine.objects.PlayerCharacter; import engine.objects.Runegate; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; import java.time.Duration; import java.time.Instant; import java.util.Collection; @@ -40,7 +45,7 @@ public enum SimulationManager { + RUNEGATE_PULSE; private long _updatePulseTime = System.currentTimeMillis() + UPDATE_PULSE; private long _flightPulseTime = System.currentTimeMillis() + FlIGHT_PULSE; - + public static Duration executionTime = Duration.ofNanos(1); public static Duration executionMax = Duration.ofNanos(1); @@ -49,15 +54,26 @@ public enum SimulationManager { // don't allow instantiation. } - public static String getPopulationString() { - String outString; - String newLine = System.getProperty("line.separator"); - outString = "[LUA_POPULATION()]" + newLine; - outString += DbManager.CSSessionQueries.GET_POPULATION_STRING(); - return outString; - } + public static String getPopulationString() { + + String popString = ""; + + try (Connection connection = DataWarehouse.connectionPool.getConnection(); + PreparedStatement getPopString = connection.prepareStatement("CALL GET_POPULATION_STRING()");) { + + ResultSet rs = getPopString.executeQuery(); + + if (rs.next()) + popString = rs.getString("popstring"); - /* + } catch (SQLException e) { + Logger.error(e.toString()); + } + + return popString; + } + + /* * Update the simulation. *** Important: Whatever you do in here, do it damn * quick! */ From 0e4490576ae0c67dd2b61b92d5755e39f063499d Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sat, 20 May 2023 09:39:23 -0400 Subject: [PATCH 013/109] Game uses hikaricp for all connection pooling. Connection count set dynamically. --- src/engine/db/archive/BaneRecord.java | 37 +++++------ src/engine/db/archive/CharacterRecord.java | 19 +++--- src/engine/db/archive/CityRecord.java | 5 +- src/engine/db/archive/DataWarehouse.java | 37 ++--------- src/engine/db/archive/GuildRecord.java | 15 ++--- src/engine/db/archive/MineRecord.java | 3 +- src/engine/db/archive/PvpRecord.java | 31 ++++----- src/engine/db/archive/RealmRecord.java | 3 +- src/engine/db/handlers/dbHandlerBase.java | 2 +- src/engine/gameManager/DbManager.java | 56 +++++++++-------- src/engine/gameManager/SimulationManager.java | 3 +- src/engine/server/login/LoginServer.java | 39 ++---------- src/engine/server/world/WorldServer.java | 2 +- src/engine/workthreads/HourlyJobThread.java | 1 - src/engine/workthreads/PurgeOprhans.java | 4 +- .../workthreads/WarehousePushThread.java | 63 ++++++++++--------- 16 files changed, 136 insertions(+), 184 deletions(-) diff --git a/src/engine/db/archive/BaneRecord.java b/src/engine/db/archive/BaneRecord.java index 51209f06..27f6507f 100644 --- a/src/engine/db/archive/BaneRecord.java +++ b/src/engine/db/archive/BaneRecord.java @@ -10,6 +10,7 @@ package engine.db.archive; import engine.Enum; +import engine.gameManager.DbManager; import engine.objects.Bane; import engine.objects.City; import engine.workthreads.WarehousePushThread; @@ -134,9 +135,9 @@ public class BaneRecord extends DataRecord { DateTime outDateTime = null; - try (Connection connection = DataWarehouse.connectionPool.getConnection(); - PreparedStatement statement = buildDateTimeQueryStatement(connection, city); - ResultSet rs = statement.executeQuery()) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement statement = buildDateTimeQueryStatement(connection, city); + ResultSet rs = statement.executeQuery()) { while (rs.next()) { @@ -145,7 +146,7 @@ public class BaneRecord extends DataRecord { } } catch (SQLException e) { - Logger.error( e.toString()); + Logger.error(e.toString()); } return outDateTime; @@ -166,13 +167,13 @@ public class BaneRecord extends DataRecord { if (bane == null) return; - try (Connection connection = DataWarehouse.connectionPool.getConnection(); - PreparedStatement statement = buildUpdateLiveDateStatement(connection, bane, dateTime)) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement statement = buildUpdateLiveDateStatement(connection, bane, dateTime)) { statement.execute(); } catch (SQLException e) { - Logger.error( e.toString()); + Logger.error(e.toString()); } } @@ -203,8 +204,8 @@ public class BaneRecord extends DataRecord { public static void updateResolution(Bane bane, RecordEventType eventType) { - try (Connection connection = DataWarehouse.connectionPool.getConnection(); - PreparedStatement statement = buildUpdateResolutionStatement(connection, bane, eventType)) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement statement = buildUpdateResolutionStatement(connection, bane, eventType)) { statement.execute(); @@ -223,9 +224,9 @@ public class BaneRecord extends DataRecord { dividerString = "--------------------------------" + newLine; queryString = "CALL `baneHistory`()"; - try (Connection connection = DataWarehouse.connectionPool.getConnection(); - PreparedStatement statement = connection.prepareCall(queryString); - ResultSet rs = statement.executeQuery()) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement statement = connection.prepareCall(queryString); + ResultSet rs = statement.executeQuery()) { while (rs.next()) { @@ -253,9 +254,9 @@ public class BaneRecord extends DataRecord { WarehousePushThread.baneDelta = 0; - try (Connection localConnection = DataWarehouse.connectionPool.getConnection(); - PreparedStatement statement = localConnection.prepareStatement(queryString, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); // Make this an updatable result set as we'll reset the dirty flag as we go along - ResultSet rs = statement.executeQuery()) { + try (Connection localConnection = DbManager.getConnection(); + PreparedStatement statement = localConnection.prepareStatement(queryString, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); // Make this an updatable result set as we'll reset the dirty flag as we go along + ResultSet rs = statement.executeQuery()) { while (rs.next()) { @@ -338,13 +339,13 @@ public class BaneRecord extends DataRecord { public void write() { - try (Connection connection = DataWarehouse.connectionPool.getConnection(); - PreparedStatement statement = buildBaneInsertStatement(connection)) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement statement = buildBaneInsertStatement(connection)) { statement.execute(); } catch (SQLException e) { - Logger.error( e.toString()); + Logger.error(e.toString()); } } diff --git a/src/engine/db/archive/CharacterRecord.java b/src/engine/db/archive/CharacterRecord.java index b1c6e3b5..157c6d71 100644 --- a/src/engine/db/archive/CharacterRecord.java +++ b/src/engine/db/archive/CharacterRecord.java @@ -10,6 +10,7 @@ package engine.db.archive; import engine.Enum; +import engine.gameManager.DbManager; import engine.objects.Guild; import engine.objects.PlayerCharacter; import engine.workthreads.WarehousePushThread; @@ -109,13 +110,13 @@ public class CharacterRecord extends DataRecord { public static void advanceKillCounter(PlayerCharacter player) { - try (Connection connection = DataWarehouse.connectionPool.getConnection(); + try (Connection connection = DbManager.getConnection(); PreparedStatement statement = buildKillCounterStatement(connection, player)) { statement.execute(); } catch (SQLException e) { - Logger.error( e.toString()); + Logger.error(e.toString()); } } @@ -136,13 +137,13 @@ public class CharacterRecord extends DataRecord { public static void advanceDeathCounter(PlayerCharacter player) { - try (Connection connection = DataWarehouse.connectionPool.getConnection(); + try (Connection connection = DbManager.getConnection(); PreparedStatement statement = buildDeathCounterStatement(connection, player)) { statement.execute(); } catch (SQLException e) { - Logger.error( e.toString()); + Logger.error(e.toString()); } } @@ -163,13 +164,13 @@ public class CharacterRecord extends DataRecord { public static void updatePromotionClass(PlayerCharacter player) { - try (Connection connection = DataWarehouse.connectionPool.getConnection(); + try (Connection connection = DbManager.getConnection(); PreparedStatement statement = buildUpdatePromotionStatement(connection, player)) { statement.execute(); } catch (SQLException e) { - Logger.error( e.toString()); + Logger.error(e.toString()); } } @@ -197,7 +198,7 @@ public class CharacterRecord extends DataRecord { WarehousePushThread.charDelta = 0; - try (Connection localConnection = DataWarehouse.connectionPool.getConnection(); + try (Connection localConnection = DbManager.getConnection(); PreparedStatement statement = localConnection.prepareStatement(queryString, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); // Make this an updatable result set as we'll reset the dirty flag as we go along ResultSet rs = statement.executeQuery()) { @@ -263,13 +264,13 @@ public class CharacterRecord extends DataRecord { public void write() { - try (Connection connection = DataWarehouse.connectionPool.getConnection(); + try (Connection connection = DbManager.getConnection(); PreparedStatement statement = buildCharacterInsertStatement(connection, this.player)) { statement.execute(); } catch (SQLException e) { - Logger.error( "Error writing character record " + e.toString()); + Logger.error("Error writing character record " + e.toString()); } } diff --git a/src/engine/db/archive/CityRecord.java b/src/engine/db/archive/CityRecord.java index 50b123e0..785cf405 100644 --- a/src/engine/db/archive/CityRecord.java +++ b/src/engine/db/archive/CityRecord.java @@ -10,6 +10,7 @@ package engine.db.archive; import engine.Enum; +import engine.gameManager.DbManager; import engine.objects.City; import engine.workthreads.WarehousePushThread; @@ -126,8 +127,8 @@ public class CityRecord extends DataRecord { public void write() { - try (Connection connection = DataWarehouse.connectionPool.getConnection(); - PreparedStatement statement = this.buildCityInsertStatement(connection)) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement statement = this.buildCityInsertStatement(connection)) { statement.execute(); diff --git a/src/engine/db/archive/DataWarehouse.java b/src/engine/db/archive/DataWarehouse.java index 5483e18b..9236a38c 100644 --- a/src/engine/db/archive/DataWarehouse.java +++ b/src/engine/db/archive/DataWarehouse.java @@ -12,6 +12,7 @@ package engine.db.archive; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import engine.gameManager.ConfigManager; +import engine.gameManager.DbManager; import engine.util.Hasher; import org.pmw.tinylog.Logger; @@ -27,14 +28,13 @@ public class DataWarehouse implements Runnable { public static final Hasher hasher = new Hasher("Cthulhu Owns Joo"); private static final LinkedBlockingQueue recordQueue = new LinkedBlockingQueue<>(); - public static HikariDataSource connectionPool = null; public static HikariDataSource remoteConnectionPool = null; public DataWarehouse() { Logger.info("Configuring local Database Connection Pool..."); - configureConnectionPool(); + DbManager.configureConnectionPool(); // If WarehousePush is disabled // then early exit @@ -72,11 +72,7 @@ public class DataWarehouse implements Runnable { String queryString; String hashString; - try { - connection = DataWarehouse.connectionPool.getConnection(); - } catch (SQLException e) { - e.printStackTrace(); - } + connection = DbManager.getConnection(); if (connection == null) { Logger.error("Null connection when writing zone hash."); @@ -140,11 +136,7 @@ public class DataWarehouse implements Runnable { String queryString; ResultSet resultSet; - try { - connection = DataWarehouse.connectionPool.getConnection(); - } catch (SQLException e) { - e.printStackTrace(); - } + connection = DbManager.getConnection(); if (connection == null) { Logger.error("Null connection during char record lookup"); @@ -282,27 +274,6 @@ public class DataWarehouse implements Runnable { } } - private static void configureConnectionPool() { - - HikariConfig config = new HikariConfig(); - - config.setMaximumPoolSize(10); - - config.setJdbcUrl("jdbc:mysql://" + ConfigManager.MB_DATABASE_ADDRESS.getValue() + - ":" + ConfigManager.MB_DATABASE_PORT.getValue() + "/" + - ConfigManager.MB_DATABASE_NAME.getValue()); - config.setUsername(ConfigManager.MB_DATABASE_USER.getValue()); - config.setPassword( ConfigManager.MB_DATABASE_PASS.getValue()); - config.addDataSourceProperty("characterEncoding", "utf8"); - config.addDataSourceProperty("cachePrepStmts", "true"); - config.addDataSourceProperty("prepStmtCacheSize", "250"); - config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); - - connectionPool = new HikariDataSource(config); // setup the connection pool - - Logger.info("Local warehouse database connection configured"); - } - private static void configureRemoteConnectionPool() { HikariConfig config = new HikariConfig(); diff --git a/src/engine/db/archive/GuildRecord.java b/src/engine/db/archive/GuildRecord.java index c68a3cb3..ec141cea 100644 --- a/src/engine/db/archive/GuildRecord.java +++ b/src/engine/db/archive/GuildRecord.java @@ -11,6 +11,7 @@ package engine.db.archive; import engine.Enum; import engine.Enum.RecordEventType; +import engine.gameManager.DbManager; import engine.objects.Guild; import engine.workthreads.WarehousePushThread; @@ -164,16 +165,16 @@ public class GuildRecord extends DataRecord { public void write() { - try (Connection connection = DataWarehouse.connectionPool.getConnection(); - PreparedStatement statement = this.buildGuildInsertStatement(connection)) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement statement = this.buildGuildInsertStatement(connection)) { - statement.execute(); + statement.execute(); - } catch (SQLException e) { - e.printStackTrace(); - } + } catch (SQLException e) { + e.printStackTrace(); + } - } + } private PreparedStatement buildGuildInsertStatement(Connection connection) throws SQLException { diff --git a/src/engine/db/archive/MineRecord.java b/src/engine/db/archive/MineRecord.java index 69621ba8..dbc236c0 100644 --- a/src/engine/db/archive/MineRecord.java +++ b/src/engine/db/archive/MineRecord.java @@ -10,6 +10,7 @@ package engine.db.archive; import engine.Enum; +import engine.gameManager.DbManager; import engine.objects.AbstractCharacter; import engine.objects.Mine; import engine.objects.PlayerCharacter; @@ -131,7 +132,7 @@ public class MineRecord extends DataRecord { public void write() { - try (Connection connection = DataWarehouse.connectionPool.getConnection(); + try (Connection connection = DbManager.getConnection(); PreparedStatement statement = this.buildMineInsertStatement(connection)) { statement.execute(); diff --git a/src/engine/db/archive/PvpRecord.java b/src/engine/db/archive/PvpRecord.java index a3199127..56734977 100644 --- a/src/engine/db/archive/PvpRecord.java +++ b/src/engine/db/archive/PvpRecord.java @@ -9,6 +9,7 @@ package engine.db.archive; +import engine.gameManager.DbManager; import engine.gameManager.ZoneManager; import engine.math.Vector3fImmutable; import engine.objects.Guild; @@ -90,19 +91,19 @@ public class PvpRecord extends DataRecord { LinkedList outList = new LinkedList<>(); - try (Connection connection = DataWarehouse.connectionPool.getConnection(); - PreparedStatement statement = buildHistoryStatement(connection, charUUID, historyType); - ResultSet rs = statement.executeQuery()) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement statement = buildHistoryStatement(connection, charUUID, historyType); + ResultSet rs = statement.executeQuery()) { while (rs.next()) { switch (historyType) { - case KILLS: - outList.add((int) DataWarehouse.hasher.decrypt(rs.getString("victim_id"))[0]); - break; - case DEATHS: - outList.add((int) DataWarehouse.hasher.decrypt(rs.getString("char_id"))[0]); - break; + case KILLS: + outList.add((int) DataWarehouse.hasher.decrypt(rs.getString("victim_id"))[0]); + break; + case DEATHS: + outList.add((int) DataWarehouse.hasher.decrypt(rs.getString("char_id"))[0]); + break; } } } catch (SQLException e) { @@ -132,9 +133,9 @@ public class PvpRecord extends DataRecord { outString = "[LUA_PVP() DATA WAREHOUSE]" + newLine; dividerString = "--------------------------------" + newLine; - try (Connection connection = DataWarehouse.connectionPool.getConnection(); - PreparedStatement statement = buildLuaHistoryQueryStatement(connection, charUUID); - ResultSet rs = statement.executeQuery()) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement statement = buildLuaHistoryQueryStatement(connection, charUUID); + ResultSet rs = statement.executeQuery()) { while (rs.next()) { @@ -293,13 +294,13 @@ public class PvpRecord extends DataRecord { public void write() { - try (Connection connection = DataWarehouse.connectionPool.getConnection(); - PreparedStatement statement = buildPvPInsertStatement(connection)) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement statement = buildPvPInsertStatement(connection)) { statement.execute(); } catch (SQLException e) { - Logger.error( e.toString()); + Logger.error(e.toString()); } // Warehouse record for this pvp event written if code path reaches here. diff --git a/src/engine/db/archive/RealmRecord.java b/src/engine/db/archive/RealmRecord.java index 556eebe2..957858e5 100644 --- a/src/engine/db/archive/RealmRecord.java +++ b/src/engine/db/archive/RealmRecord.java @@ -10,6 +10,7 @@ package engine.db.archive; import engine.Enum; +import engine.gameManager.DbManager; import engine.objects.Realm; import engine.workthreads.WarehousePushThread; @@ -128,7 +129,7 @@ public class RealmRecord extends DataRecord { public void write() { - try (Connection connection = DataWarehouse.connectionPool.getConnection(); + try (Connection connection = DbManager.getConnection(); PreparedStatement statement = this.buildRealmInsertStatement(connection)) { statement.execute(); diff --git a/src/engine/db/handlers/dbHandlerBase.java b/src/engine/db/handlers/dbHandlerBase.java index 2531d854..726d9494 100644 --- a/src/engine/db/handlers/dbHandlerBase.java +++ b/src/engine/db/handlers/dbHandlerBase.java @@ -34,7 +34,7 @@ public abstract class dbHandlerBase { protected final void prepareCallable(final String sql) { try { - this.cs.set((CallableStatement) DbManager.getConn().prepareCall(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)); + this.cs.set((CallableStatement) DbManager.getConnection().prepareCall(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)); } catch (SQLException e) { Logger.error("DbManager.getConn", e); Logger.error("SQL Error number: " + e.getErrorCode()); diff --git a/src/engine/gameManager/DbManager.java b/src/engine/gameManager/DbManager.java index c89099e2..d0778236 100644 --- a/src/engine/gameManager/DbManager.java +++ b/src/engine/gameManager/DbManager.java @@ -8,11 +8,12 @@ package engine.gameManager; +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; import engine.Enum; import engine.Enum.GameObjectType; import engine.db.handlers.*; import engine.objects.*; -import engine.pooling.ConnectionPool; import engine.server.MBServerStatics; import engine.util.Hasher; import org.pmw.tinylog.Logger; @@ -26,28 +27,14 @@ import java.util.concurrent.ConcurrentHashMap; public enum DbManager { DBMANAGER; - private static ConnectionPool connPool; + private static HikariDataSource connectionPool = null; + public static Hasher hasher; //Local Object Caching private static final EnumMap> objectCache = new EnumMap<>(GameObjectType.class); - public static boolean configureDatabaseLayer() { - - boolean worked = true; - - try { - DbManager.connPool = new ConnectionPool(); - DbManager.connPool.fill(10); - DBMANAGER.hasher = new Hasher(); - } catch (Exception e ) { - e.printStackTrace(); - worked = false; - } - return worked; - } - public static AbstractGameObject getObject(GameObjectType objectType, int objectUUID) { AbstractGameObject outObject = null; @@ -87,9 +74,6 @@ public enum DbManager { return outObject; } - public static int getPoolSize(){ - return connPool.getPoolSize(); - } public static boolean inCache(GameObjectType gameObjectType, int uuid) { @@ -227,7 +211,7 @@ public enum DbManager { } public static PreparedStatement prepareStatement(String sql) throws SQLException { - return getConn().prepareStatement(sql, 1); + return getConnection().prepareStatement(sql, 1); } // Omg refactor this out, somebody! @@ -259,15 +243,12 @@ public enum DbManager { * @return the conn */ //XXX I think we have a severe resource leak here! No one is putting the connections back! - public static Connection getConn() { - Connection conn = DbManager.connPool.get(); + public static Connection getConnection() { try { - if (!conn.isClosed()) - DbManager.connPool.put(conn); + return DbManager.connectionPool.getConnection(); } catch (SQLException e) { - Logger.error( e.toString()); + throw new RuntimeException(e); } - return conn; } public static final dbAccountHandler AccountQueries = new dbAccountHandler(); @@ -312,4 +293,25 @@ public enum DbManager { public static final dbHeightMapHandler HeightMapQueries = new dbHeightMapHandler(); public static final dbRunegateHandler RunegateQueries = new dbRunegateHandler(); + + public static void configureConnectionPool() { + + HikariConfig config = new HikariConfig(); + + config.setMaximumPoolSize(Runtime.getRuntime().availableProcessors() * 2); + + config.setJdbcUrl("jdbc:mysql://" + ConfigManager.MB_DATABASE_ADDRESS.getValue() + + ":" + ConfigManager.MB_DATABASE_PORT.getValue() + "/" + + ConfigManager.MB_DATABASE_NAME.getValue()); + config.setUsername(ConfigManager.MB_DATABASE_USER.getValue()); + config.setPassword(ConfigManager.MB_DATABASE_PASS.getValue()); + config.addDataSourceProperty("characterEncoding", "utf8"); + config.addDataSourceProperty("cachePrepStmts", "true"); + config.addDataSourceProperty("prepStmtCacheSize", "250"); + config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); + + connectionPool = new HikariDataSource(config); // setup the connection pool + + Logger.info("Local warehouse database connection configured"); + } } diff --git a/src/engine/gameManager/SimulationManager.java b/src/engine/gameManager/SimulationManager.java index 478369e2..9cff43a1 100644 --- a/src/engine/gameManager/SimulationManager.java +++ b/src/engine/gameManager/SimulationManager.java @@ -10,7 +10,6 @@ package engine.gameManager; import engine.Enum; import engine.Enum.GameObjectType; -import engine.db.archive.DataWarehouse; import engine.objects.AbstractGameObject; import engine.objects.City; import engine.objects.PlayerCharacter; @@ -58,7 +57,7 @@ public enum SimulationManager { String popString = ""; - try (Connection connection = DataWarehouse.connectionPool.getConnection(); + try (Connection connection = DbManager.getConnection(); PreparedStatement getPopString = connection.prepareStatement("CALL GET_POPULATION_STRING()");) { ResultSet rs = getPopString.executeQuery(); diff --git a/src/engine/server/login/LoginServer.java b/src/engine/server/login/LoginServer.java index 2933e51d..dfa35aa9 100644 --- a/src/engine/server/login/LoginServer.java +++ b/src/engine/server/login/LoginServer.java @@ -9,8 +9,6 @@ package engine.server.login; -import com.zaxxer.hikari.HikariConfig; -import com.zaxxer.hikari.HikariDataSource; import engine.Enum; import engine.gameManager.*; import engine.job.JobScheduler; @@ -52,7 +50,6 @@ public class LoginServer { // Instance variables private VersionInfoMsg versionInfoMessage; - public static HikariDataSource connectionPool = null; public static int population = 0; public static boolean worldServerRunning = false; public static boolean loginServerRunning = false; @@ -172,9 +169,6 @@ public class LoginServer { this.versionInfoMessage = new VersionInfoMsg(ConfigManager.MB_MAJOR_VER.getValue(), ConfigManager.MB_MINOR_VER.getValue()); - Logger.info("Initializing Database Pool"); - initDatabasePool(); - Logger.info("Initializing Database layer"); initDatabaseLayer(); @@ -229,12 +223,12 @@ public class LoginServer { // Try starting a GOM <-> DB connection. try { - Logger.info("Configuring GameObjectManager to use Database: '" + Logger.info("Configuring Magicbane to use Database: '" + ConfigManager.MB_DATABASE_NAME.getValue() + "' on " + ConfigManager.MB_DATABASE_ADDRESS.getValue() + ':' + ConfigManager.MB_DATABASE_PORT.getValue()); - DbManager.configureDatabaseLayer(); + DbManager.configureConnectionPool(); } catch (Exception e) { Logger.error(e.getMessage()); @@ -365,33 +359,12 @@ public class LoginServer { } - private void initDatabasePool() { - - HikariConfig config = new HikariConfig(); - - config.setMaximumPoolSize(33); // (16 cores 1 spindle) - - config.setJdbcUrl("jdbc:mysql://" + ConfigManager.MB_DATABASE_ADDRESS.getValue() + - ":" + ConfigManager.MB_DATABASE_PORT.getValue() + "/" + - ConfigManager.MB_DATABASE_NAME.getValue()); - config.setUsername(ConfigManager.MB_DATABASE_USER.getValue()); - config.setPassword(ConfigManager.MB_DATABASE_PASS.getValue()); - config.addDataSourceProperty("characterEncoding", "utf8"); - config.addDataSourceProperty("cachePrepStmts", "true"); - config.addDataSourceProperty("prepStmtCacheSize", "250"); - config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); - - connectionPool = new HikariDataSource(config); // setup the connection pool - - Logger.info("local database connection configured"); - } - public void invalidateCacheList() { int objectUUID; String objectType; - try (Connection connection = connectionPool.getConnection(); + try (Connection connection = DbManager.getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT * FROM `login_cachelist`"); ResultSet rs = statement.executeQuery()) { @@ -400,7 +373,7 @@ public class LoginServer { objectUUID = rs.getInt("UID"); objectType = rs.getString("type"); - Logger.info("INVALIDATED : " + objectType + " UUID: " + objectUUID); + Logger.info("INVALIDATED : " + objectType + " UUID: " + objectUUID); switch (objectType) { @@ -424,7 +397,7 @@ public class LoginServer { // clear the db table - try (Connection connection = connectionPool.getConnection(); + try (Connection connection = DbManager.getConnection(); PreparedStatement statement = connection.prepareStatement("DELETE FROM `login_cachelist`")) { statement.execute(); @@ -447,7 +420,7 @@ public class LoginServer { // query data warehouse for unresolved bane with this character - try (Connection connection = connectionPool.getConnection(); + try (Connection connection = DbManager.getConnection(); PreparedStatement statement = buildQueryActiveBaneStatement(connection, playerCharacter); ResultSet rs = statement.executeQuery()) { diff --git a/src/engine/server/world/WorldServer.java b/src/engine/server/world/WorldServer.java index 3aa843d2..98658e53 100644 --- a/src/engine/server/world/WorldServer.java +++ b/src/engine/server/world/WorldServer.java @@ -471,7 +471,7 @@ public class WorldServer { + ConfigManager.MB_DATABASE_ADDRESS.getValue() + ':' + ConfigManager.MB_DATABASE_PORT.getValue()); - DbManager.configureDatabaseLayer(); + DbManager.configureConnectionPool(); } catch (Exception e) { Logger.error(e.getMessage()); diff --git a/src/engine/workthreads/HourlyJobThread.java b/src/engine/workthreads/HourlyJobThread.java index fe363244..dbf17e0c 100644 --- a/src/engine/workthreads/HourlyJobThread.java +++ b/src/engine/workthreads/HourlyJobThread.java @@ -284,7 +284,6 @@ public class HourlyJobThread implements Runnable { Logger.info(WorldServer.getUptimeString()); Logger.info(SimulationManager.getPopulationString()); Logger.info(MessageDispatcher.getNetstatString()); - Logger.info("Connection Pool Size: " + DbManager.getPoolSize()); Logger.info(PurgeOprhans.recordsDeleted.toString() + "orphaned items deleted"); } } diff --git a/src/engine/workthreads/PurgeOprhans.java b/src/engine/workthreads/PurgeOprhans.java index c75f4d69..dc33c17c 100644 --- a/src/engine/workthreads/PurgeOprhans.java +++ b/src/engine/workthreads/PurgeOprhans.java @@ -8,7 +8,7 @@ package engine.workthreads; -import engine.db.archive.DataWarehouse; +import engine.gameManager.DbManager; import org.pmw.tinylog.Logger; import java.sql.Connection; @@ -46,7 +46,7 @@ public class PurgeOprhans implements Runnable { // Member variable declaration try ( - Connection connection = DataWarehouse.connectionPool.getConnection(); + Connection connection = DbManager.getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT * from `object` where `type` = 'item' AND `parent` IS NULL", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = statement.executeQuery()) { diff --git a/src/engine/workthreads/WarehousePushThread.java b/src/engine/workthreads/WarehousePushThread.java index 39757da5..da920ecb 100644 --- a/src/engine/workthreads/WarehousePushThread.java +++ b/src/engine/workthreads/WarehousePushThread.java @@ -18,6 +18,7 @@ package engine.workthreads; import engine.Enum; import engine.db.archive.*; import engine.gameManager.ConfigManager; +import engine.gameManager.DbManager; import org.pmw.tinylog.Logger; import java.sql.*; @@ -153,9 +154,9 @@ public class WarehousePushThread implements Runnable { public static boolean pushMineRecords() { - try (Connection localConnection = DataWarehouse.connectionPool.getConnection(); - PreparedStatement statement = MineRecord.buildMineQueryStatement(localConnection); - ResultSet rs = statement.executeQuery()) { + try (Connection localConnection = DbManager.getConnection(); + PreparedStatement statement = MineRecord.buildMineQueryStatement(localConnection); + ResultSet rs = statement.executeQuery()) { while (rs.next()) { pushMineRecord(rs); @@ -164,7 +165,7 @@ public class WarehousePushThread implements Runnable { return true; } catch (SQLException e) { - Logger.error( "Error with local DB connection: " + e.toString()); + Logger.error("Error with local DB connection: " + e.toString()); e.printStackTrace(); return false; } @@ -172,9 +173,9 @@ public class WarehousePushThread implements Runnable { public static boolean pushCharacterRecords() { - try (Connection localConnection = DataWarehouse.connectionPool.getConnection(); - PreparedStatement statement = CharacterRecord.buildCharacterQueryStatement(localConnection); - ResultSet rs = statement.executeQuery()) { + try (Connection localConnection = DbManager.getConnection(); + PreparedStatement statement = CharacterRecord.buildCharacterQueryStatement(localConnection); + ResultSet rs = statement.executeQuery()) { while (rs.next()) { pushCharacterRecord(rs); @@ -183,7 +184,7 @@ public class WarehousePushThread implements Runnable { return true; } catch (SQLException e) { - Logger.error( "Error with local DB connection: " + e.toString()); + Logger.error("Error with local DB connection: " + e.toString()); e.printStackTrace(); return false; } @@ -191,9 +192,9 @@ public class WarehousePushThread implements Runnable { private static boolean pushGuildRecords() { - try (Connection localConnection = DataWarehouse.connectionPool.getConnection(); - PreparedStatement statement = GuildRecord.buildGuildQueryStatement(localConnection); - ResultSet rs = statement.executeQuery()) { + try (Connection localConnection = DbManager.getConnection(); + PreparedStatement statement = GuildRecord.buildGuildQueryStatement(localConnection); + ResultSet rs = statement.executeQuery()) { while (rs.next()) { pushGuildRecord(rs); @@ -238,9 +239,9 @@ public class WarehousePushThread implements Runnable { private static boolean pushBaneRecords() { - try (Connection localConnection = DataWarehouse.connectionPool.getConnection(); - PreparedStatement statement = BaneRecord.buildBaneQueryStatement(localConnection); - ResultSet rs = statement.executeQuery()) { + try (Connection localConnection = DbManager.getConnection(); + PreparedStatement statement = BaneRecord.buildBaneQueryStatement(localConnection); + ResultSet rs = statement.executeQuery()) { while (rs.next()) { pushBaneRecord(rs); @@ -271,9 +272,9 @@ public class WarehousePushThread implements Runnable { private static boolean pushCityRecords() { - try (Connection localConnection = DataWarehouse.connectionPool.getConnection(); - PreparedStatement statement = CityRecord.buildCityQueryStatement(localConnection); - ResultSet rs = statement.executeQuery()) { + try (Connection localConnection = DbManager.getConnection(); + PreparedStatement statement = CityRecord.buildCityQueryStatement(localConnection); + ResultSet rs = statement.executeQuery()) { while (rs.next()) { pushCityRecord(rs); @@ -282,7 +283,7 @@ public class WarehousePushThread implements Runnable { return true; } catch (SQLException e) { - Logger.error( "Error with local DB connection: " + e.toString()); + Logger.error("Error with local DB connection: " + e.toString()); e.printStackTrace(); return false; } @@ -290,9 +291,9 @@ public class WarehousePushThread implements Runnable { private static boolean pushPvpRecords() { - try (Connection localConnection = DataWarehouse.connectionPool.getConnection(); - PreparedStatement statement = PvpRecord.buildPvpQueryStatement(localConnection); - ResultSet rs = statement.executeQuery()) { + try (Connection localConnection = DbManager.getConnection(); + PreparedStatement statement = PvpRecord.buildPvpQueryStatement(localConnection); + ResultSet rs = statement.executeQuery()) { while (rs.next()) { @@ -323,9 +324,9 @@ public class WarehousePushThread implements Runnable { private static boolean pushRealmRecords() { - try (Connection localConnection = DataWarehouse.connectionPool.getConnection(); - PreparedStatement statement = RealmRecord.buildRealmQueryStatement(localConnection); - ResultSet rs = statement.executeQuery()) { + try (Connection localConnection = DbManager.getConnection(); + PreparedStatement statement = RealmRecord.buildRealmQueryStatement(localConnection); + ResultSet rs = statement.executeQuery()) { while (rs.next()) { @@ -335,7 +336,7 @@ public class WarehousePushThread implements Runnable { return true; } catch (SQLException e) { - Logger.error( "Error with local DB connection: " + e.toString()); + Logger.error("Error with local DB connection: " + e.toString()); e.printStackTrace(); return false; } @@ -392,9 +393,9 @@ public class WarehousePushThread implements Runnable { queryString = "SELECT * FROM `warehouse_index`"; - try (Connection localConnection = DataWarehouse.connectionPool.getConnection(); - CallableStatement statement = localConnection.prepareCall(queryString); - ResultSet rs = statement.executeQuery()) { + try (Connection localConnection = DbManager.getConnection(); + CallableStatement statement = localConnection.prepareCall(queryString); + ResultSet rs = statement.executeQuery()) { while (rs.next()) { charIndex = rs.getInt("charIndex"); @@ -417,14 +418,14 @@ public class WarehousePushThread implements Runnable { private static boolean updateWarehouseIndex() { - try (Connection connection = DataWarehouse.connectionPool.getConnection(); - PreparedStatement statement = WarehousePushThread.buildIndexUpdateStatement(connection)) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement statement = WarehousePushThread.buildIndexUpdateStatement(connection)) { statement.execute(); return true; } catch (SQLException e) { - Logger.error( e.toString()); + Logger.error(e.toString()); return false; } } From 553ac01e933aac82a47034679ef8492a7976aafc Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sat, 20 May 2023 09:43:46 -0400 Subject: [PATCH 014/109] Using baseline for debugging. --- src/engine/gameManager/DbManager.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/engine/gameManager/DbManager.java b/src/engine/gameManager/DbManager.java index d0778236..9348363f 100644 --- a/src/engine/gameManager/DbManager.java +++ b/src/engine/gameManager/DbManager.java @@ -298,7 +298,7 @@ public enum DbManager { HikariConfig config = new HikariConfig(); - config.setMaximumPoolSize(Runtime.getRuntime().availableProcessors() * 2); + config.setMaximumPoolSize(10); config.setJdbcUrl("jdbc:mysql://" + ConfigManager.MB_DATABASE_ADDRESS.getValue() + ":" + ConfigManager.MB_DATABASE_PORT.getValue() + "/" + @@ -312,6 +312,6 @@ public enum DbManager { connectionPool = new HikariDataSource(config); // setup the connection pool - Logger.info("Local warehouse database connection configured"); + Logger.info("Database connection pool configured"); } } From b4b7b08d47d40915ccf8cbe7c84373361a0ebde7 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sat, 20 May 2023 09:51:35 -0400 Subject: [PATCH 015/109] Unused method removed. --- src/engine/powers/EffectsBase.java | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/src/engine/powers/EffectsBase.java b/src/engine/powers/EffectsBase.java index bccb1ac7..c517a298 100644 --- a/src/engine/powers/EffectsBase.java +++ b/src/engine/powers/EffectsBase.java @@ -182,22 +182,6 @@ public class EffectsBase { this.isSuffix = true; // getFailConditions(); } - - - public static EffectsBase createNoDbEffectsBase(EffectsBase copyEffect, int newToken, String IDString){ - EffectsBase cachedEffectsBase = new EffectsBase(copyEffect,newToken,IDString); - - if (cachedEffectsBase == null) - return null; - - //add to Lists. - PowersManager.effectsBaseByIDString.put(cachedEffectsBase.IDString, cachedEffectsBase); - PowersManager.effectsBaseByToken.put(cachedEffectsBase.token, cachedEffectsBase); - - return cachedEffectsBase; - } - - public static ArrayList getAllEffectsBase() { PreparedStatementShared ps = null; From 55d9a3516c1a0b1b722790edaefe6a60b5cd2731 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sat, 20 May 2023 09:54:37 -0400 Subject: [PATCH 016/109] Bonus code removed and replaced with a db call actually used. --- .../db/handlers/dbEffectsBaseHandler.java | 186 +++--------------- src/engine/gameManager/PowersManager.java | 3 +- src/engine/powers/EffectsBase.java | 76 ------- 3 files changed, 27 insertions(+), 238 deletions(-) diff --git a/src/engine/db/handlers/dbEffectsBaseHandler.java b/src/engine/db/handlers/dbEffectsBaseHandler.java index 9e360278..95735e15 100644 --- a/src/engine/db/handlers/dbEffectsBaseHandler.java +++ b/src/engine/db/handlers/dbEffectsBaseHandler.java @@ -9,173 +9,37 @@ package engine.db.handlers; -public class dbEffectsBaseHandler extends dbHandlerBase { - - public dbEffectsBaseHandler() { - - } - - - - public boolean CreateEffectBase(int token, String IDString,String name,int flags){ - prepareCallable("INSERT INTO `wpak_static_power_effectbase` (`token`,`IDString`,`name`,`flags`) VALUES (?,?,?,?)"); - setInt(1,token); - setString(2,IDString); - setString(3,name); - setInt(4,flags); - - return (executeUpdate() > 0); - } - - public boolean CreateEffectBaseRAW(String IDString,String type,String detail){ - prepareCallable("INSERT INTO `wpak_effect_effectbase_raw` (`token`,`IDString`,`name`,`flags`) VALUES (?,?,?,?)"); - setString(1,IDString); - setString(2,type); - setString(3,detail); - - return (executeUpdate() > 0); - } - - public boolean CreateEffectSource(String IDString,String source){ - prepareCallable("INSERT INTO `wpak_static_power_sourcetype` (`IDString`,`source`) VALUES (?,?)"); - - setString(1,IDString); - setString(2,source); - - return (executeUpdate() > 0); - } - - public boolean CreateEffectSourceRAW(String IDString,String type,String detail){ - prepareCallable("INSERT INTO `wpak_effect_source_raw` (`effectID`,`type`, `text`) VALUES (?,?,?)"); - - setString(1,IDString); - setString(2,type); - setString(3,detail); - - return (executeUpdate() > 0); - } - - public boolean CreateEffectCondition(String IDString,String powerOrEffect,String type,float amount,float ramp,byte useAddFormula,String damageType1,String damageType2,String damageType3){ - prepareCallable("INSERT INTO `wpak_static_power_failcondition` (`IDString`,`powerOrEffect`,`type`,`amount`,`ramp`,`useAddFormula`,`damageType1`,`damageType2`,`damageType3`) VALUES (?,?,?,?,?,?,?,?,?)"); - setString(1,IDString); - setString(2,powerOrEffect); - setString(3,type); - setFloat(4,amount); - setFloat(5,ramp); - setByte(6,useAddFormula); - setString(7,damageType1); - setString(8,damageType2); - setString(9,damageType3); - - return (executeUpdate() > 0); - } - - public boolean CreateEffectConditionRAW(String IDString,String type,String detail){ - prepareCallable("INSERT INTO `wpak_effect_condition_raw` (`effectID`,`type`, `text`) VALUES (?,?,?)"); - setString(1,IDString); - setString(2,type); - setString(3,detail); - return (executeUpdate() > 0); - } - - public boolean CreateEffectMod(String IDString,String modType,float minMod,float maxMod,float percentMod,float ramp,byte useRampAdd,String type,String string1,String string2){ - prepareCallable("INSERT INTO `wpak_static_power_effectmod` (`IDString`,`modType`,`minMod`,`maxMod`,`percentMod`,`ramp`,`useRampAdd`,`type`,`string1`,`string2`) VALUES (?,?,?,?,?,?,?,?,?,?)"); - setString(1, IDString); - setString(2, modType); - setFloat(3, minMod); - setFloat(4, maxMod); - setFloat(5, percentMod); - setFloat(6, ramp); - setByte(7, useRampAdd); - setString(8, type); - setString(9, string1); - setString(10, string2); - - return (executeUpdate() > 0); - } - - public boolean CreateEffectModRAW(String IDString,String type,String detail){ - prepareCallable("INSERT INTO `wpak_effect_mod_raw` (`effectID`,`type`, `text`) VALUES (?,?,?)"); - setString(1,IDString); - setString(2,type); - setString(3,detail); - - return (executeUpdate() > 0); - } - - - public boolean CreatePowerPowerAction(String IDString,String type,String effectID,String effectID2,String deferredPowerID,float levelCap,float levelCapRamp,String damageType,int numIterations,String effectSourceToRemove,String trackFilter,int maxTrack,int mobID,int mobLevel,int simpleDamage,String transferFromType,String transferToType,float transferAmount,float transferRamp,float transferEfficiency,float transferEfficiencyRamp,int flags){ - prepareCallable("INSERT INTO `wpak_static_power_poweraction` (`IDString`,`type`,`effectID`,`effectID2`,`deferredPowerID`,`levelCap`,`levelCapRamp`,`damageType`,`numIterations`,`effectSourceToRemove`,`trackFilter`,`maxTrack`,`mobID`,`mobLevel`,`simpleDamage`,`transferFromType`,`transferToType`,`transferAmount`,`transferRamp`,`transferEfficiency`,`transferEfficiencyRamp`,`flags`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); - - setString(1,IDString); - setString(2,type); - setString(3,effectID); - setString(4,effectID2); - setString(5,deferredPowerID); - setFloat(6,levelCap); - setFloat(7,levelCapRamp); - setString(8,damageType); - setInt(9,numIterations); - setString(10,effectSourceToRemove); - setString(11,trackFilter); - setInt(12,maxTrack); - setInt(13,mobID); - setInt(14,mobLevel); - setInt(15,simpleDamage); - setString(16,transferFromType); - setString(17,transferToType); - setFloat(18,transferAmount); - setFloat(19,transferRamp); - setFloat(20,transferEfficiency); - setFloat(21,transferEfficiencyRamp); - setInt(22,flags); - - return (executeUpdate() > 0); - } - - public boolean CreatePowerPowerActionRAW(String IDString,String type,String detail){ - prepareCallable("INSERT INTO `wpak_effect_poweraction_raw` (`effectID`,`type`, `text`) VALUES (?,?,?)"); - - setString(1,IDString); - setString(2,type); - setString(3,detail); +import engine.objects.PreparedStatementShared; +import engine.powers.EffectsBase; +import org.pmw.tinylog.Logger; - return (executeUpdate() > 0); - } - - public boolean ClearAllEffectBase(){ - prepareCallable("DELETE from `wpak_static_power_effectbase`"); - executeUpdate(); - - prepareCallable(" DELETE from `wpak_static_power_sourcetype` "); - executeUpdate(); +import java.sql.ResultSet; +import java.util.ArrayList; - prepareCallable(" DELETE from `wpak_static_power_failcondition` WHERE `powerOrEffect` = ?"); - setString(1,"Effect"); - executeUpdate(); - - prepareCallable(" DELETE from `wpak_static_power_effectmod` "); - executeUpdate(); +public class dbEffectsBaseHandler extends dbHandlerBase { - return true; + public dbEffectsBaseHandler() { } - public boolean ResetIncrement(){ - prepareCallable("ALTER TABLE `wpak_static_power_effectbase` AUTO_INCREMENT = 1"); - executeUpdate(); - prepareCallable("ALTER TABLE `wpak_static_power_sourcetype` AUTO_INCREMENT = 1"); - executeUpdate(); - - prepareCallable("ALTER TABLE `wpak_static_power_failcondition` AUTO_INCREMENT = 1"); - executeUpdate(); - - prepareCallable("ALTER TABLE `wpak_static_power_effectmod` AUTO_INCREMENT = 1"); - executeUpdate(); - - - return true; + public static ArrayList getAllEffectsBase() { + PreparedStatementShared ps = null; + ArrayList out = new ArrayList<>(); + try { + ps = new PreparedStatementShared("SELECT * FROM static_power_effectbase ORDER BY `IDString` DESC"); + ResultSet rs = ps.executeQuery(); + while (rs.next()) { + EffectsBase toAdd = new EffectsBase(rs); + out.add(toAdd); + } + rs.close(); + } catch (Exception e) { + Logger.error(e); + } finally { + ps.release(); + } + //testHash(out); + return out; } - } diff --git a/src/engine/gameManager/PowersManager.java b/src/engine/gameManager/PowersManager.java index 5b08f06d..57af50ae 100644 --- a/src/engine/gameManager/PowersManager.java +++ b/src/engine/gameManager/PowersManager.java @@ -11,6 +11,7 @@ package engine.gameManager; import engine.Enum.*; import engine.InterestManagement.HeightMap; import engine.InterestManagement.WorldGrid; +import engine.db.handlers.dbEffectsBaseHandler; import engine.job.AbstractJob; import engine.job.AbstractScheduleJob; import engine.job.JobContainer; @@ -111,7 +112,7 @@ public enum PowersManager { public static void InitializePowers() { // Add EffectsBase - ArrayList ebList = EffectsBase.getAllEffectsBase(); + ArrayList ebList = dbEffectsBaseHandler.getAllEffectsBase(); for (EffectsBase eb : ebList) { PowersManager.effectsBaseByToken.put(eb.getToken(), eb); diff --git a/src/engine/powers/EffectsBase.java b/src/engine/powers/EffectsBase.java index c517a298..19bd9ebc 100644 --- a/src/engine/powers/EffectsBase.java +++ b/src/engine/powers/EffectsBase.java @@ -183,82 +183,6 @@ public class EffectsBase { // getFailConditions(); } - public static ArrayList getAllEffectsBase() { - PreparedStatementShared ps = null; - ArrayList out = new ArrayList<>(); - try { - ps = new PreparedStatementShared("SELECT * FROM static_power_effectbase ORDER BY `IDString` DESC"); - ResultSet rs = ps.executeQuery(); - while (rs.next()) { - EffectsBase toAdd = new EffectsBase(rs); - out.add(toAdd); - } - rs.close(); - } catch (Exception e) { - Logger.error(e); - } finally { - ps.release(); - } - //testHash(out); - return out; - } - - public static ArrayList getAllLiveEffectsBase() { - PreparedStatementShared ps = null; - ArrayList out = new ArrayList<>(); - try { - ps = new PreparedStatementShared("SELECT * FROM static_power_effectbase_24 ORDER BY `IDString` DESC"); - ResultSet rs = ps.executeQuery(); - while (rs.next()) { - EffectsBase toAdd = new EffectsBase(rs); - out.add(toAdd); - } - rs.close(); - } catch (Exception e) { - Logger.error(e); - } finally { - ps.release(); - } - //testHash(out); - return out; - } - - //private static void testHash(ArrayList effs) { - // int valid = 0, invalid = 0; - // for (EffectsBase eff : effs) { - // String ids = eff.getIDString(); - // int tok = eff.getToken(); - // if (ids.length() != 8 || ids.startsWith("PRE-") || ids.startsWith("SUF-") || ids.endsWith("X") || !ids.substring(3,4).equals("-")) - // continue; - // - //// if ((tok > 1 || tok < 0) && ids.length() == 8) { - // int out = Hash(ids); - // if (out != tok) { - // System.out.println(ids + ": " + Integer.toHexString(out) + "(" + out + ")"); - // invalid++; - // } else - // valid++; - //// } - // } - // System.out.println("valid: " + valid + ", invalid: " + invalid); - //} - - //private static int Hash(String IDString) { - // char[] val = IDString.toCharArray(); - // int out = 360; - // out ^= val[0]; - // out ^= (val[1] << 5); - // out ^= (val[2] << 10); - // out ^= (val[4] << 23); - // out ^= (val[5] << 19); - // out ^= (val[6] << 15); - // out ^= (val[7] << 26); - // out ^= (val[7] >> 6); - // out ^= 17; - // return out; - //} - - public static void getFailConditions(HashMap effects) { PreparedStatementShared ps = null; try { From 8bafb32e95bb7da3eb94b5dcbae168cd31e5b142 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sat, 20 May 2023 10:00:38 -0400 Subject: [PATCH 017/109] Method refactored to use try-with-resources --- .../db/handlers/dbEffectsBaseHandler.java | 33 ++++++++++--------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/src/engine/db/handlers/dbEffectsBaseHandler.java b/src/engine/db/handlers/dbEffectsBaseHandler.java index 95735e15..f6a86848 100644 --- a/src/engine/db/handlers/dbEffectsBaseHandler.java +++ b/src/engine/db/handlers/dbEffectsBaseHandler.java @@ -9,11 +9,14 @@ package engine.db.handlers; -import engine.objects.PreparedStatementShared; +import engine.gameManager.DbManager; import engine.powers.EffectsBase; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; +import java.sql.SQLException; import java.util.ArrayList; public class dbEffectsBaseHandler extends dbHandlerBase { @@ -22,24 +25,24 @@ public class dbEffectsBaseHandler extends dbHandlerBase { } - public static ArrayList getAllEffectsBase() { - PreparedStatementShared ps = null; - ArrayList out = new ArrayList<>(); - try { - ps = new PreparedStatementShared("SELECT * FROM static_power_effectbase ORDER BY `IDString` DESC"); - ResultSet rs = ps.executeQuery(); + + ArrayList effectList = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement prepareStatement = connection.prepareStatement("SELECT * FROM static_power_effectbase ORDER BY `IDString` DESC")) { + + ResultSet rs = prepareStatement.executeQuery(); + while (rs.next()) { EffectsBase toAdd = new EffectsBase(rs); - out.add(toAdd); + effectList.add(toAdd); } - rs.close(); - } catch (Exception e) { - Logger.error(e); - } finally { - ps.release(); + } catch (SQLException e) { + Logger.error(e.toString()); } - //testHash(out); - return out; + + return effectList; } + } From 27ac58518cd3cd6115d17885d211ade305ebaa72 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sat, 20 May 2023 10:01:40 -0400 Subject: [PATCH 018/109] Method refactored to use try-with-resources --- src/engine/db/handlers/dbEffectsBaseHandler.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/engine/db/handlers/dbEffectsBaseHandler.java b/src/engine/db/handlers/dbEffectsBaseHandler.java index f6a86848..f7cf2bac 100644 --- a/src/engine/db/handlers/dbEffectsBaseHandler.java +++ b/src/engine/db/handlers/dbEffectsBaseHandler.java @@ -35,8 +35,8 @@ public class dbEffectsBaseHandler extends dbHandlerBase { ResultSet rs = prepareStatement.executeQuery(); while (rs.next()) { - EffectsBase toAdd = new EffectsBase(rs); - effectList.add(toAdd); + EffectsBase effectBase = new EffectsBase(rs); + effectList.add(effectBase); } } catch (SQLException e) { Logger.error(e.toString()); From 0a31043bc9d3b1f9f0a64e6ccf5f250c1d756587 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sat, 20 May 2023 10:21:07 -0400 Subject: [PATCH 019/109] Method refactored to use try-with-resources --- .../db/handlers/dbEffectsBaseHandler.java | 254 +++++++++++++++++ src/engine/gameManager/PowersManager.java | 2 +- .../AbstractEffectModifier.java | 263 +----------------- .../ItemNameEffectModifier.java | 2 +- 4 files changed, 261 insertions(+), 260 deletions(-) diff --git a/src/engine/db/handlers/dbEffectsBaseHandler.java b/src/engine/db/handlers/dbEffectsBaseHandler.java index f7cf2bac..b2452eb9 100644 --- a/src/engine/db/handlers/dbEffectsBaseHandler.java +++ b/src/engine/db/handlers/dbEffectsBaseHandler.java @@ -9,8 +9,11 @@ package engine.db.handlers; +import engine.Enum; import engine.gameManager.DbManager; +import engine.gameManager.PowersManager; import engine.powers.EffectsBase; +import engine.powers.effectmodifiers.*; import org.pmw.tinylog.Logger; import java.sql.Connection; @@ -18,6 +21,7 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; +import java.util.HashSet; public class dbEffectsBaseHandler extends dbHandlerBase { @@ -45,4 +49,254 @@ public class dbEffectsBaseHandler extends dbHandlerBase { return effectList; } + public static void cacheAllEffectModifiers() { + + String IDString; + AbstractEffectModifier abstractEffectModifier = null; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement prepareStatement = connection.prepareStatement("SELECT * FROM static_power_effectmod")) { + + ResultSet rs = prepareStatement.executeQuery(); + + while (rs.next()) { + + IDString = rs.getString("IDString"); + EffectsBase effectBase = PowersManager.getEffectByIDString(IDString); + Enum.ModType modifier = Enum.ModType.GetModType(rs.getString("modType")); + + //combine item prefix and suffix effect modifiers + + abstractEffectModifier = getCombinedModifiers(abstractEffectModifier, rs, effectBase, modifier); + + if (abstractEffectModifier != null) { + + if (EffectsBase.modifiersMap.containsKey(effectBase.getIDString()) == false) + EffectsBase.modifiersMap.put(effectBase.getIDString(), new HashSet<>()); + + EffectsBase.modifiersMap.get(effectBase.getIDString()).add(abstractEffectModifier); + + } + + } + + } catch (Exception e) { + Logger.error(e); + } + + } + + private static AbstractEffectModifier getCombinedModifiers(AbstractEffectModifier abstractEffectModifier, ResultSet rs, EffectsBase effectBase, Enum.ModType modifier) throws SQLException { + switch (modifier) { + case AdjustAboveDmgCap: + abstractEffectModifier = new AdjustAboveDmgCapEffectModifier(rs); + break; + case Ambidexterity: + abstractEffectModifier = new AmbidexterityEffectModifier(rs); + break; + case AnimOverride: + break; + case ArmorPiercing: + abstractEffectModifier = new ArmorPiercingEffectModifier(rs); + break; + case AttackDelay: + abstractEffectModifier = new AttackDelayEffectModifier(rs); + break; + case Attr: + abstractEffectModifier = new AttributeEffectModifier(rs); + break; + case BlackMantle: + abstractEffectModifier = new BlackMantleEffectModifier(rs); + break; + case BladeTrails: + abstractEffectModifier = new BladeTrailsEffectModifier(rs); + break; + case Block: + abstractEffectModifier = new BlockEffectModifier(rs); + break; + case BlockedPowerType: + abstractEffectModifier = new BlockedPowerTypeEffectModifier(rs); + break; + case CannotAttack: + abstractEffectModifier = new CannotAttackEffectModifier(rs); + break; + case CannotCast: + abstractEffectModifier = new CannotCastEffectModifier(rs); + break; + case CannotMove: + abstractEffectModifier = new CannotMoveEffectModifier(rs); + break; + case CannotTrack: + abstractEffectModifier = new CannotTrackEffectModifier(rs); + break; + case Charmed: + abstractEffectModifier = new CharmedEffectModifier(rs); + break; + case ConstrainedAmbidexterity: + abstractEffectModifier = new ConstrainedAmbidexterityEffectModifier(rs); + break; + case DamageCap: + abstractEffectModifier = new DamageCapEffectModifier(rs); + break; + case DamageShield: + abstractEffectModifier = new DamageShieldEffectModifier(rs); + break; + case DCV: + abstractEffectModifier = new DCVEffectModifier(rs); + break; + case Dodge: + abstractEffectModifier = new DodgeEffectModifier(rs); + break; + case DR: + abstractEffectModifier = new DREffectModifier(rs); + break; + case Durability: + abstractEffectModifier = new DurabilityEffectModifier(rs); + break; + case ExclusiveDamageCap: + abstractEffectModifier = new ExclusiveDamageCapEffectModifier(rs); + break; + case Fade: + abstractEffectModifier = new FadeEffectModifier(rs); + break; + case Fly: + abstractEffectModifier = new FlyEffectModifier(rs); + break; + case Health: + abstractEffectModifier = new HealthEffectModifier(rs); + break; + case HealthFull: + abstractEffectModifier = new HealthFullEffectModifier(rs); + break; + case HealthRecoverRate: + abstractEffectModifier = new HealthRecoverRateEffectModifier(rs); + break; + case IgnoreDamageCap: + abstractEffectModifier = new IgnoreDamageCapEffectModifier(rs); + break; + case IgnorePassiveDefense: + abstractEffectModifier = new IgnorePassiveDefenseEffectModifier(rs); + break; + case ImmuneTo: + abstractEffectModifier = new ImmuneToEffectModifier(rs); + break; + case ImmuneToAttack: + abstractEffectModifier = new ImmuneToAttackEffectModifier(rs); + break; + case ImmuneToPowers: + abstractEffectModifier = new ImmuneToPowersEffectModifier(rs); + break; + case Invisible: + abstractEffectModifier = new InvisibleEffectModifier(rs); + break; + case ItemName: + abstractEffectModifier = new ItemNameEffectModifier(rs); + if (((ItemNameEffectModifier) abstractEffectModifier).name.isEmpty()) + break; + if (effectBase != null) + effectBase.setName((((ItemNameEffectModifier) abstractEffectModifier).name)); + break; + case Mana: + abstractEffectModifier = new ManaEffectModifier(rs); + break; + case ManaFull: + abstractEffectModifier = new ManaFullEffectModifier(rs); + break; + case ManaRecoverRate: + abstractEffectModifier = new ManaRecoverRateEffectModifier(rs); + break; + case MaxDamage: + abstractEffectModifier = new MaxDamageEffectModifier(rs); + break; + case MeleeDamageModifier: + abstractEffectModifier = new MeleeDamageEffectModifier(rs); + break; + case MinDamage: + abstractEffectModifier = new MinDamageEffectModifier(rs); + break; + case NoMod: + abstractEffectModifier = new NoModEffectModifier(rs); + break; + case OCV: + abstractEffectModifier = new OCVEffectModifier(rs); + break; + case Parry: + abstractEffectModifier = new ParryEffectModifier(rs); + break; + case PassiveDefense: + abstractEffectModifier = new PassiveDefenseEffectModifier(rs); + case PowerCost: + abstractEffectModifier = new PowerCostEffectModifier(rs); + break; + case PowerCostHealth: + abstractEffectModifier = new PowerCostHealthEffectModifier(rs); + break; + case PowerDamageModifier: + abstractEffectModifier = new PowerDamageEffectModifier(rs); + break; + case ProtectionFrom: + abstractEffectModifier = new ProtectionFromEffectModifier(rs); + break; + case Resistance: + abstractEffectModifier = new ResistanceEffectModifier(rs); + break; + case ScaleHeight: + abstractEffectModifier = new ScaleHeightEffectModifier(rs); + break; + case ScaleWidth: + abstractEffectModifier = new ScaleWidthEffectModifier(rs); + break; + case ScanRange: + abstractEffectModifier = new ScanRangeEffectModifier(rs); + break; + case SeeInvisible: + abstractEffectModifier = new SeeInvisibleEffectModifier(rs); + break; + case Silenced: + abstractEffectModifier = new SilencedEffectModifier(rs); + break; + case Skill: + abstractEffectModifier = new SkillEffectModifier(rs); + break; + case Slay: + abstractEffectModifier = new SlayEffectModifier(rs); + break; + case Speed: + abstractEffectModifier = new SpeedEffectModifier(rs); + break; + case SpireBlock: + abstractEffectModifier = new SpireBlockEffectModifier(rs); + break; + case Stamina: + abstractEffectModifier = new StaminaEffectModifier(rs); + break; + case StaminaFull: + abstractEffectModifier = new StaminaFullEffectModifier(rs); + break; + case StaminaRecoverRate: + abstractEffectModifier = new StaminaRecoverRateEffectModifier(rs); + break; + case Stunned: + abstractEffectModifier = new StunnedEffectModifier(rs); + break; + case Value: + abstractEffectModifier = new ValueEffectModifier(rs); + if (effectBase != null) { + ValueEffectModifier valueEffect = (ValueEffectModifier) abstractEffectModifier; + effectBase.setValue(valueEffect.minMod); + } + break; + case WeaponProc: + abstractEffectModifier = new WeaponProcEffectModifier(rs); + break; + case WeaponRange: + abstractEffectModifier = new WeaponRangeEffectModifier(rs); + break; + case WeaponSpeed: + abstractEffectModifier = new WeaponSpeedEffectModifier(rs); + break; + + } + return abstractEffectModifier; + } } diff --git a/src/engine/gameManager/PowersManager.java b/src/engine/gameManager/PowersManager.java index 57af50ae..eeaf9c47 100644 --- a/src/engine/gameManager/PowersManager.java +++ b/src/engine/gameManager/PowersManager.java @@ -124,7 +124,7 @@ public enum PowersManager { EffectsBase.getFailConditions(PowersManager.effectsBaseByIDString); // Add Modifiers to Effects - AbstractEffectModifier.getAllEffectModifiers(); + dbEffectsBaseHandler.cacheAllEffectModifiers(); // Add Source Types to Effects PowersManager.addAllSourceTypes(); diff --git a/src/engine/powers/effectmodifiers/AbstractEffectModifier.java b/src/engine/powers/effectmodifiers/AbstractEffectModifier.java index 6a8f385d..464141d9 100644 --- a/src/engine/powers/effectmodifiers/AbstractEffectModifier.java +++ b/src/engine/powers/effectmodifiers/AbstractEffectModifier.java @@ -11,17 +11,15 @@ package engine.powers.effectmodifiers; import engine.Enum.ModType; import engine.Enum.SourceType; -import engine.gameManager.DbManager; -import engine.gameManager.PowersManager; import engine.jobs.AbstractEffectJob; -import engine.objects.*; +import engine.objects.AbstractCharacter; +import engine.objects.AbstractWorldObject; +import engine.objects.Building; +import engine.objects.Item; import engine.powers.EffectsBase; -import org.pmw.tinylog.Logger; import java.sql.ResultSet; import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashSet; public abstract class AbstractEffectModifier { @@ -30,7 +28,7 @@ public abstract class AbstractEffectModifier { protected int UUID; protected String IDString; protected String effectType; - protected float minMod; + public float minMod; protected float maxMod; protected float percentMod; protected float ramp; @@ -60,257 +58,6 @@ public abstract class AbstractEffectModifier { this.string2 = rs.getString("string2"); } - public static ArrayList getAllEffectModifiers() { - PreparedStatementShared ps = null; - ArrayList out = new ArrayList<>(); - try { - ps = new PreparedStatementShared("SELECT * FROM static_power_effectmod"); - ResultSet rs = ps.executeQuery(); - String IDString; - AbstractEffectModifier aem = null; - while (rs.next()) { - IDString = rs.getString("IDString"); - int token = DbManager.hasher.SBStringHash(IDString); - - EffectsBase eb = PowersManager.getEffectByIDString(IDString); - - ModType modifier = ModType.GetModType(rs.getString("modType")); - - //combine item prefix and suffix effect modifiers - switch (modifier){ - case AdjustAboveDmgCap: - aem = new AdjustAboveDmgCapEffectModifier(rs); - break; - case Ambidexterity: - aem = new AmbidexterityEffectModifier(rs); - break; - case AnimOverride: - break; - case ArmorPiercing: - aem = new ArmorPiercingEffectModifier(rs); - break; - case AttackDelay: - aem = new AttackDelayEffectModifier(rs); - break; - case Attr: - aem = new AttributeEffectModifier(rs); - break; - case BlackMantle: - aem = new BlackMantleEffectModifier(rs); - break; - case BladeTrails: - aem = new BladeTrailsEffectModifier(rs); - break; - case Block: - aem = new BlockEffectModifier(rs); - break; - case BlockedPowerType: - aem = new BlockedPowerTypeEffectModifier(rs); - break; - case CannotAttack: - aem = new CannotAttackEffectModifier(rs); - break; - case CannotCast: - aem = new CannotCastEffectModifier(rs); - break; - case CannotMove: - aem = new CannotMoveEffectModifier(rs); - break; - case CannotTrack: - aem = new CannotTrackEffectModifier(rs); - break; - case Charmed: - aem = new CharmedEffectModifier(rs); - break; - case ConstrainedAmbidexterity: - aem = new ConstrainedAmbidexterityEffectModifier(rs); - break; - case DamageCap: - aem = new DamageCapEffectModifier(rs); - break; - case DamageShield: - aem = new DamageShieldEffectModifier(rs); - break; - case DCV: - aem = new DCVEffectModifier(rs); - break; - case Dodge: - aem = new DodgeEffectModifier(rs); - break; - case DR: - aem = new DREffectModifier(rs); - break; - case Durability: - aem = new DurabilityEffectModifier(rs); - break; - case ExclusiveDamageCap: - aem = new ExclusiveDamageCapEffectModifier(rs); - break; - case Fade: - aem = new FadeEffectModifier(rs); - break; - case Fly: - aem = new FlyEffectModifier(rs); - break; - case Health: - aem = new HealthEffectModifier(rs); - break; - case HealthFull: - aem = new HealthFullEffectModifier(rs); - break; - case HealthRecoverRate: - aem = new HealthRecoverRateEffectModifier(rs); - break; - case IgnoreDamageCap: - aem = new IgnoreDamageCapEffectModifier(rs); - break; - case IgnorePassiveDefense: - aem = new IgnorePassiveDefenseEffectModifier(rs); - break; - case ImmuneTo: - aem = new ImmuneToEffectModifier(rs); - break; - case ImmuneToAttack: - aem = new ImmuneToAttackEffectModifier(rs); - break; - case ImmuneToPowers: - aem = new ImmuneToPowersEffectModifier(rs); - break; - case Invisible: - aem = new InvisibleEffectModifier(rs); - break; - case ItemName: - aem = new ItemNameEffectModifier(rs); - if ((((ItemNameEffectModifier)aem).name.isEmpty())) - break; - if (eb != null) - eb.setName((((ItemNameEffectModifier)aem).name)); - break; - case Mana: - aem = new ManaEffectModifier(rs); - break; - case ManaFull: - aem = new ManaFullEffectModifier(rs); - break; - case ManaRecoverRate: - aem = new ManaRecoverRateEffectModifier(rs); - break; - case MaxDamage: - aem = new MaxDamageEffectModifier(rs); - break; - case MeleeDamageModifier: - aem = new MeleeDamageEffectModifier(rs); - break; - case MinDamage: - aem = new MinDamageEffectModifier(rs); - break; - case NoMod: - aem = new NoModEffectModifier(rs); - break; - case OCV: - aem = new OCVEffectModifier(rs); - break; - case Parry: - aem = new ParryEffectModifier(rs); - break; - case PassiveDefense: - aem = new PassiveDefenseEffectModifier(rs); - case PowerCost: - aem = new PowerCostEffectModifier(rs); - break; - case PowerCostHealth: - aem = new PowerCostHealthEffectModifier(rs); - break; - case PowerDamageModifier: - aem = new PowerDamageEffectModifier(rs); - break; - case ProtectionFrom: - aem = new ProtectionFromEffectModifier(rs); - break; - case Resistance: - aem = new ResistanceEffectModifier(rs); - break; - case ScaleHeight: - aem = new ScaleHeightEffectModifier(rs); - break; - case ScaleWidth: - aem = new ScaleWidthEffectModifier(rs); - break; - case ScanRange: - aem = new ScanRangeEffectModifier(rs); - break; - case SeeInvisible: - aem = new SeeInvisibleEffectModifier(rs); - break; - case Silenced: - aem = new SilencedEffectModifier(rs); - break; - case Skill: - aem = new SkillEffectModifier(rs); - break; - case Slay: - aem = new SlayEffectModifier(rs); - break; - case Speed: - aem = new SpeedEffectModifier(rs); - break; - case SpireBlock: - aem = new SpireBlockEffectModifier(rs); - break; - case Stamina: - aem = new StaminaEffectModifier(rs); - break; - case StaminaFull: - aem = new StaminaFullEffectModifier(rs); - break; - case StaminaRecoverRate: - aem = new StaminaRecoverRateEffectModifier(rs); - break; - case Stunned: - aem = new StunnedEffectModifier(rs); - break; - case Value: - aem = new ValueEffectModifier(rs); - if (eb != null){ - ValueEffectModifier valueEffect = (ValueEffectModifier)aem; - eb.setValue(valueEffect.minMod); - } - break; - case WeaponProc: - aem = new WeaponProcEffectModifier(rs); - break; - case WeaponRange: - aem = new WeaponRangeEffectModifier(rs); - break; - case WeaponSpeed: - aem = new WeaponSpeedEffectModifier(rs); - break; - - } - - if (aem != null){ - - - if (EffectsBase.modifiersMap.containsKey(eb.getIDString()) == false) - EffectsBase.modifiersMap.put(eb.getIDString(), new HashSet<>()); - EffectsBase.modifiersMap.get(eb.getIDString()).add(aem); - - } - } - rs.close(); - } catch (Exception e) { - Logger.error( e); - } finally { - ps.release(); - } - return out; - } - - - - - - public int getUUID() { return this.UUID; diff --git a/src/engine/powers/effectmodifiers/ItemNameEffectModifier.java b/src/engine/powers/effectmodifiers/ItemNameEffectModifier.java index 16b91db3..e7d6c9c1 100644 --- a/src/engine/powers/effectmodifiers/ItemNameEffectModifier.java +++ b/src/engine/powers/effectmodifiers/ItemNameEffectModifier.java @@ -21,7 +21,7 @@ import java.sql.SQLException; public class ItemNameEffectModifier extends AbstractEffectModifier { - String name = ""; + public String name = ""; public ItemNameEffectModifier(ResultSet rs) throws SQLException { super(rs); From c04bd92c23ff95dfdfc34ba223ad678f4f488a32 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sat, 20 May 2023 10:30:34 -0400 Subject: [PATCH 020/109] Leak detection threshold set to 5s. --- src/engine/gameManager/DbManager.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/engine/gameManager/DbManager.java b/src/engine/gameManager/DbManager.java index 9348363f..661cee8f 100644 --- a/src/engine/gameManager/DbManager.java +++ b/src/engine/gameManager/DbManager.java @@ -309,6 +309,7 @@ public enum DbManager { config.addDataSourceProperty("cachePrepStmts", "true"); config.addDataSourceProperty("prepStmtCacheSize", "250"); config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); + config.addDataSourceProperty("leakDetectionThreshold", "5000"); connectionPool = new HikariDataSource(config); // setup the connection pool From e7fa9cc4940e57fd530b520ef3c1e127117273ee Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sat, 20 May 2023 10:43:54 -0400 Subject: [PATCH 021/109] Unused methods removed. --- src/engine/db/handlers/dbHandlerBase.java | 25 ----------------------- 1 file changed, 25 deletions(-) diff --git a/src/engine/db/handlers/dbHandlerBase.java b/src/engine/db/handlers/dbHandlerBase.java index 726d9494..3aee7f4c 100644 --- a/src/engine/db/handlers/dbHandlerBase.java +++ b/src/engine/db/handlers/dbHandlerBase.java @@ -303,31 +303,6 @@ public abstract class dbHandlerBase { } catch (SQLException e) {} } - protected final void getColumNames(ResultSet rs) throws SQLException { - ResultSetMetaData rsmd = rs.getMetaData(); - int numColumns = rsmd.getColumnCount(); - String out = "Column names for resultSet: "; - for (int i=1; i AbstractGameObject getObjectSingle(int id) { return getObjectSingle(id, false, true); } From 82498e8e5aba9628e9b65bc0e9333499ad4a00ef Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sat, 20 May 2023 10:51:25 -0400 Subject: [PATCH 022/109] Threadlocal hikari connection defined. --- src/engine/db/handlers/dbCityHandler.java | 12 +-- src/engine/db/handlers/dbHandlerBase.java | 77 ++++++++----------- src/engine/db/handlers/dbShrineHandler.java | 12 +-- .../db/handlers/dbWarehouseHandler.java | 12 +-- 4 files changed, 51 insertions(+), 62 deletions(-) diff --git a/src/engine/db/handlers/dbCityHandler.java b/src/engine/db/handlers/dbCityHandler.java index 0eb319bc..8759582d 100644 --- a/src/engine/db/handlers/dbCityHandler.java +++ b/src/engine/db/handlers/dbCityHandler.java @@ -49,27 +49,27 @@ public class dbCityHandler extends dbHandlerBase { try { boolean work = execute(); if (work) { - ResultSet rs = this.cs.get().getResultSet(); + ResultSet rs = this.callableStatement.get().getResultSet(); while (rs.next()) { addObject(list, rs); } rs.close(); } else { - Logger.info("City Placement Failed: " + this.cs.get().toString()); + Logger.info("City Placement Failed: " + this.callableStatement.get().toString()); return list; //city creation failure } - while (this.cs.get().getMoreResults()) { - ResultSet rs = this.cs.get().getResultSet(); + while (this.callableStatement.get().getMoreResults()) { + ResultSet rs = this.callableStatement.get().getResultSet(); while (rs.next()) { addObject(list, rs); } rs.close(); } } catch (SQLException e) { - Logger.info("City Placement Failed, SQLException: " + this.cs.get().toString() + e.toString()); + Logger.info("City Placement Failed, SQLException: " + this.callableStatement.get().toString() + e.toString()); return list; //city creation failure } catch (UnknownHostException e) { - Logger.info("City Placement Failed, UnknownHostException: " + this.cs.get().toString()); + Logger.info("City Placement Failed, UnknownHostException: " + this.callableStatement.get().toString()); return list; //city creation failure } finally { closeCallable(); diff --git a/src/engine/db/handlers/dbHandlerBase.java b/src/engine/db/handlers/dbHandlerBase.java index 3aee7f4c..b23c6bb3 100644 --- a/src/engine/db/handlers/dbHandlerBase.java +++ b/src/engine/db/handlers/dbHandlerBase.java @@ -30,28 +30,22 @@ public abstract class dbHandlerBase { */ protected Class localClass = null; protected GameObjectType localObjectType; - protected final ThreadLocal cs = new ThreadLocal<>(); + protected final ThreadLocal callableStatement = new ThreadLocal<>(); + protected final ThreadLocal connection = new ThreadLocal<>(); protected final void prepareCallable(final String sql) { try { - this.cs.set((CallableStatement) DbManager.getConnection().prepareCall(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)); + this.connection.set(DbManager.getConnection()); + this.callableStatement.set(this.connection.get().prepareCall(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)); } catch (SQLException e) { Logger.error("DbManager.getConn", e); Logger.error("SQL Error number: " + e.getErrorCode()); } } - protected final void setDate(int parameterIndex, Date value) { - try { - this.cs.get().setDate(parameterIndex, value); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - protected final void setInt(int parameterIndex, int value) { try { - this.cs.get().setInt(parameterIndex, value); + this.callableStatement.get().setInt(parameterIndex, value); } catch (SQLException e) { Logger.error("SQL Error number: " + e.getErrorCode()); } @@ -59,7 +53,7 @@ public abstract class dbHandlerBase { protected final void setLong(int parameterIndex, long value) { try { - this.cs.get().setLong(parameterIndex, value); + this.callableStatement.get().setLong(parameterIndex, value); } catch (SQLException e) { Logger.error("SQL Error number: " + e.getErrorCode()); } @@ -67,7 +61,7 @@ public abstract class dbHandlerBase { protected final void setFloat(int parameterIndex, float value) { try { - this.cs.get().setFloat(parameterIndex, value); + this.callableStatement.get().setFloat(parameterIndex, value); } catch (SQLException e) { Logger.error("SQL Error number: " + e.getErrorCode()); } @@ -75,7 +69,7 @@ public abstract class dbHandlerBase { protected final void setShort(int parameterIndex, short value) { try { - this.cs.get().setShort(parameterIndex, value); + this.callableStatement.get().setShort(parameterIndex, value); } catch (SQLException e) { Logger.error("SQL Error number: " + e.getErrorCode()); } @@ -83,15 +77,7 @@ public abstract class dbHandlerBase { protected final void setString(int parameterIndex, String value) { try { - this.cs.get().setString(parameterIndex, value); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - - protected final void setBytes(int parameterIndex, byte[] value) { - try { - this.cs.get().setBytes(parameterIndex, value); + this.callableStatement.get().setString(parameterIndex, value); } catch (SQLException e) { Logger.error("SQL Error number: " + e.getErrorCode()); } @@ -99,7 +85,7 @@ public abstract class dbHandlerBase { protected final void setByte(int parameterIndex, byte value) { try { - this.cs.get().setByte(parameterIndex, value); + this.callableStatement.get().setByte(parameterIndex, value); } catch (SQLException e) { Logger.error("SQL Error number: " + e.getErrorCode()); } @@ -107,7 +93,7 @@ public abstract class dbHandlerBase { protected final void setBoolean(int parameterIndex, boolean value) { try { - this.cs.get().setBoolean(parameterIndex, value); + this.callableStatement.get().setBoolean(parameterIndex, value); } catch (SQLException e) { Logger.error("SQL Error number: " + e.getErrorCode()); } @@ -115,7 +101,7 @@ public abstract class dbHandlerBase { protected final void setNULL(int parameterIndex, int type) { try { - this.cs.get().setNull(parameterIndex, type); + this.callableStatement.get().setNull(parameterIndex, type); } catch (SQLException e) { Logger.error("SQL Error number: " + e.getErrorCode()); } @@ -124,7 +110,7 @@ public abstract class dbHandlerBase { protected final void setLocalDateTime(int parameterIndex, LocalDateTime localDateTime) { try { - this.cs.get().setTimestamp(parameterIndex, Timestamp.valueOf(localDateTime)); + this.callableStatement.get().setTimestamp(parameterIndex, Timestamp.valueOf(localDateTime)); } catch (SQLException e) { Logger.error("SQL Error number: " + e.getErrorCode()); } @@ -132,7 +118,7 @@ public abstract class dbHandlerBase { protected final void setTimeStamp(int parameterIndex, long time) { try { - this.cs.get().setTimestamp(parameterIndex, new java.sql.Timestamp(time)); + this.callableStatement.get().setTimestamp(parameterIndex, new java.sql.Timestamp(time)); } catch (SQLException e) { Logger.error("SQL Error number: " + e.getErrorCode()); } @@ -140,7 +126,7 @@ public abstract class dbHandlerBase { protected final boolean execute() { try { - return this.cs.get().execute(); + return this.callableStatement.get().execute(); } catch (SQLException e) { Logger.error("SQL Error number: " + e.getErrorCode()); logSQLCommand(); @@ -150,7 +136,7 @@ public abstract class dbHandlerBase { protected final ResultSet executeQuery() { try { - return this.cs.get().executeQuery(); + return this.callableStatement.get().executeQuery(); } catch (SQLException e) { Logger.error("SQL Error number: " + e.getErrorCode()); logSQLCommand(); @@ -164,7 +150,7 @@ public abstract class dbHandlerBase { protected final int executeUpdate(boolean close) { try { - return this.cs.get().executeUpdate(); + return this.callableStatement.get().executeUpdate(); } catch (SQLException e) { Logger.error("SQL Error number: " + e.getErrorCode()); logSQLCommand(); @@ -177,7 +163,7 @@ public abstract class dbHandlerBase { protected final void logSQLCommand() { try { - Logger.error("Failed SQL Command: " + this.cs.get().toString()); + Logger.error("Failed SQL Command: " + this.callableStatement.get().toString()); } catch (Exception e) { } @@ -273,8 +259,8 @@ public abstract class dbHandlerBase { protected final int insertGetUUID() { int key = 0; try { - this.cs.get().executeUpdate(); - ResultSet rs = this.cs.get().getGeneratedKeys(); + this.callableStatement.get().executeUpdate(); + ResultSet rs = this.callableStatement.get().getGeneratedKeys(); if (rs.next()) key = rs.getInt(1); } catch (SQLException e) { @@ -309,7 +295,7 @@ public abstract class dbHandlerBase { protected AbstractGameObject getObjectSingle(int id, boolean forceFromDB, boolean storeInCache) { - if (cs.get() == null){ + if (callableStatement.get() == null) { return null; } @@ -324,9 +310,9 @@ public abstract class dbHandlerBase { try { if (MBServerStatics.DB_ENABLE_QUERY_OUTPUT) - Logger.info( "[GetObjectList] Executing query:" + cs.get().toString()); + Logger.info("[GetObjectList] Executing query:" + callableStatement.get().toString()); - ResultSet rs = cs.get().executeQuery(); + ResultSet rs = callableStatement.get().executeQuery(); if (rs.next()) { out = localClass.getConstructor(ResultSet.class).newInstance(rs); @@ -356,8 +342,11 @@ public abstract class dbHandlerBase { protected void closeCallable() { try { - if (this.cs.get() != null) - this.cs.get().close(); + if (this.callableStatement.get() != null) + this.callableStatement.get().close(); + + this.connection.get().close(); + } catch (SQLException e) {} } @@ -376,20 +365,20 @@ public abstract class dbHandlerBase { ArrayList out = new ArrayList<>(listSize); - if (this.cs.get() == null) + if (this.callableStatement.get() == null) return out; try { - CallableStatement css = this.cs.get(); + CallableStatement css = this.callableStatement.get(); if (css != null) - query = this.cs.get().toString(); + query = this.callableStatement.get().toString(); if (MBServerStatics.DB_ENABLE_QUERY_OUTPUT) Logger.info( "[GetObjectList] Executing query:" + query); - ResultSet rs = this.cs.get().executeQuery(); + ResultSet rs = this.callableStatement.get().executeQuery(); while (rs.next()) { @@ -424,7 +413,7 @@ public abstract class dbHandlerBase { protected HashSet getIntegerList(final int columnNumber) { if (MBServerStatics.DB_ENABLE_QUERY_OUTPUT) - Logger.info("[GetIntegerList] Executing query:" + this.cs.toString()); + Logger.info("[GetIntegerList] Executing query:" + this.callableStatement.toString()); HashSet out = new HashSet<>(); diff --git a/src/engine/db/handlers/dbShrineHandler.java b/src/engine/db/handlers/dbShrineHandler.java index 3d5eb30b..fbf23eff 100644 --- a/src/engine/db/handlers/dbShrineHandler.java +++ b/src/engine/db/handlers/dbShrineHandler.java @@ -67,27 +67,27 @@ public class dbShrineHandler extends dbHandlerBase { try { boolean work = execute(); if (work) { - ResultSet rs = this.cs.get().getResultSet(); + ResultSet rs = this.callableStatement.get().getResultSet(); while (rs.next()) { addObject(list, rs); } rs.close(); } else { - Logger.info("Shrine Creation Failed: " + this.cs.get().toString()); + Logger.info("Shrine Creation Failed: " + this.callableStatement.get().toString()); return list; //city creation failure } - while (this.cs.get().getMoreResults()) { - ResultSet rs = this.cs.get().getResultSet(); + while (this.callableStatement.get().getMoreResults()) { + ResultSet rs = this.callableStatement.get().getResultSet(); while (rs.next()) { addObject(list, rs); } rs.close(); } } catch (SQLException e) { - Logger.info("Shrine Creation Failed, SQLException: " + this.cs.get().toString() + e.toString()); + Logger.info("Shrine Creation Failed, SQLException: " + this.callableStatement.get().toString() + e.toString()); return list; //city creation failure } catch (UnknownHostException e) { - Logger.info("Shrine Creation Failed, UnknownHostException: " + this.cs.get().toString()); + Logger.info("Shrine Creation Failed, UnknownHostException: " + this.callableStatement.get().toString()); return list; //city creation failure } finally { closeCallable(); diff --git a/src/engine/db/handlers/dbWarehouseHandler.java b/src/engine/db/handlers/dbWarehouseHandler.java index f859cfaa..d16f451e 100644 --- a/src/engine/db/handlers/dbWarehouseHandler.java +++ b/src/engine/db/handlers/dbWarehouseHandler.java @@ -84,27 +84,27 @@ public class dbWarehouseHandler extends dbHandlerBase { try { boolean work = execute(); if (work) { - ResultSet rs = this.cs.get().getResultSet(); + ResultSet rs = this.callableStatement.get().getResultSet(); while (rs.next()) { addObject(list, rs); } rs.close(); } else { - Logger.info("Warehouse Creation Failed: " + this.cs.get().toString()); + Logger.info("Warehouse Creation Failed: " + this.callableStatement.get().toString()); return list; //city creation failure } - while (this.cs.get().getMoreResults()) { - ResultSet rs = this.cs.get().getResultSet(); + while (this.callableStatement.get().getMoreResults()) { + ResultSet rs = this.callableStatement.get().getResultSet(); while (rs.next()) { addObject(list, rs); } rs.close(); } } catch (SQLException e) { - Logger.info("Warehouse Creation Failed, SQLException: " + this.cs.get().toString() + e.toString()); + Logger.info("Warehouse Creation Failed, SQLException: " + this.callableStatement.get().toString() + e.toString()); return list; //city creation failure } catch (UnknownHostException e) { - Logger.info("Warehouse Creation Failed, UnknownHostException: " + this.cs.get().toString()); + Logger.info("Warehouse Creation Failed, UnknownHostException: " + this.callableStatement.get().toString()); return list; //city creation failure } finally { closeCallable(); From 563b54de14a681be8e7180da7bddd4e792d43939 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sat, 20 May 2023 16:33:40 -0400 Subject: [PATCH 023/109] Unused methods removed --- src/engine/db/handlers/dbItemHandler.java | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/src/engine/db/handlers/dbItemHandler.java b/src/engine/db/handlers/dbItemHandler.java index 6a2e14f3..b473a75e 100644 --- a/src/engine/db/handlers/dbItemHandler.java +++ b/src/engine/db/handlers/dbItemHandler.java @@ -69,18 +69,6 @@ public class dbItemHandler extends dbHandlerBase { return null; } - public boolean DELETE_ITEM(final Item item) { - prepareCallable("DELETE FROM `object` WHERE `UID`=? && `type`='item' limit 1"); - setLong(1, (long) item.getObjectUUID()); - return (executeUpdate() > 0); - } - - public boolean DELETE_ITEM(final int itemUUID) { - prepareCallable("DELETE FROM `object` WHERE `UID`=? && `type`='item' limit 1"); - setLong(1, (long) itemUUID); - return (executeUpdate() > 0); - } - public String GET_OWNER(int ownerID) { prepareCallable("SELECT `type` FROM `object` WHERE `UID`=?"); setLong(1, (long) ownerID); From c86ad3f2f65525d55a4eb2a7473fdc238e6537b7 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sat, 20 May 2023 17:35:44 -0400 Subject: [PATCH 024/109] Begin refactor to remove abstraction. --- src/engine/db/handlers/dbAccountHandler.java | 258 ++++++++++++------- src/engine/db/handlers/dbHandlerBase.java | 19 +- 2 files changed, 177 insertions(+), 100 deletions(-) diff --git a/src/engine/db/handlers/dbAccountHandler.java b/src/engine/db/handlers/dbAccountHandler.java index cab89c03..f94f9fab 100644 --- a/src/engine/db/handlers/dbAccountHandler.java +++ b/src/engine/db/handlers/dbAccountHandler.java @@ -17,6 +17,8 @@ import engine.objects.Account; import engine.objects.PlayerCharacter; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; @@ -28,44 +30,65 @@ public class dbAccountHandler extends dbHandlerBase { this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); } - public Account GET_ACCOUNT(int id) { - if (id == 0) + public Account GET_ACCOUNT(int accountID) { + + Account account; + + if (accountID == 0) return null; - Account account = (Account) DbManager.getFromCache(GameObjectType.Account, id); + + account = (Account) DbManager.getFromCache(GameObjectType.Account, accountID); + if (account != null) return account; - prepareCallable("SELECT * FROM `obj_account` WHERE `UID`=?"); - setLong(1, (long) id); + try (Connection connection = DbManager.getConnection(); + PreparedStatement accountQuery = connection.prepareStatement("SELECT * FROM `obj_account` WHERE `UID`=?")) { + + accountQuery.setLong(1, accountID); - Account ac = null; - ac = (Account) getObjectSingle(id); + ResultSet rs = accountQuery.executeQuery(); + account = (Account) getObjectFromRs(rs); - if (ac != null) - ac.runAfterLoad(); + } catch (SQLException e) { + Logger.error(e); + } + + if (account != null) + account.runAfterLoad(); - return ac; + return account; } public void WRITE_ADMIN_LOG(String adminName, String logEntry) { - prepareCallable("INSERT INTO dyn_admin_log(`dateTime`, `charName`, `eventString`)" - + " VALUES (?, ?, ?)"); - setTimeStamp(1, System.currentTimeMillis()); - setString(2, adminName); - setString(3, logEntry); - executeUpdate(); + try (Connection connection = DbManager.getConnection(); + PreparedStatement accountQuery = connection.prepareStatement("INSERT INTO dyn_admin_log(`dateTime`, `charName`, `eventString`)" + + " VALUES (?, ?, ?)")) { + accountQuery.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis())); + accountQuery.setString(2, adminName); + accountQuery.setString(3, logEntry); + + accountQuery.execute(); + + } catch (SQLException e) { + Logger.error(e); + } } public void SET_TRASH(String machineID) { - prepareCallable("INSERT INTO dyn_trash(`machineID`, `count`)" - + " VALUES (?, 1) ON DUPLICATE KEY UPDATE `count` = `count` + 1;"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO dyn_trash(`machineID`, `count`)" + + " VALUES (?, 1) ON DUPLICATE KEY UPDATE `count` = `count` + 1;")) { - setTimeStamp(4, System.currentTimeMillis()); - setString(1, machineID); - executeUpdate(); + preparedStatement.setString(1, machineID); + preparedStatement.execute(); + + } catch (SQLException e) { + Logger.error(e); + } } @@ -73,39 +96,47 @@ public class dbAccountHandler extends dbHandlerBase { ArrayList machineList = new ArrayList<>(); - prepareCallable("select `machineID` from `dyn_trash`"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement accountQuery = connection.prepareStatement("select `machineID` from `dyn_trash`")) { - try { - ResultSet rs = executeQuery(); - while (rs.next()) { + ResultSet rs = accountQuery.executeQuery(); + + while (rs.next()) machineList.add(rs.getString(1)); - } + } catch (SQLException e) { - Logger.error( e); - } finally { - closeCallable(); + Logger.error(e); } return machineList; } - public boolean DELETE_VAULT_FOR_ACCOUNT(final int accountID) { - prepareCallable("DELETE FROM `object` WHERE `parent`=? && `type`='item'"); - setLong(1, (long) accountID); - return (executeUpdate() > 0); + public void DELETE_VAULT_FOR_ACCOUNT(final int accountID) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `object` WHERE `parent`=? && `type`='item'")) { + + preparedStatement.setLong(1, accountID); + preparedStatement.execute(); + + } catch (SQLException e) { + Logger.error(e); + } + } public ArrayList GET_ALL_CHARS_FOR_MACHINE(String machineID) { ArrayList trashList = new ArrayList<>(); - prepareCallable("select DISTINCT UID from object \n" + - "where parent IN (select AccountID from dyn_login_history " + - " WHERE`machineID`=?)"); - setString(1, machineID); + try (Connection connection = DbManager.getConnection(); + PreparedStatement accountQuery = connection.prepareStatement("select DISTINCT UID from object \n" + + "where parent IN (select AccountID from dyn_login_history " + + " WHERE`machineID`=?)")) { + + accountQuery.setString(1, machineID); + ResultSet rs = accountQuery.executeQuery(); - try { - ResultSet rs = executeQuery(); while (rs.next()) { PlayerCharacter trashPlayer; @@ -115,52 +146,75 @@ public class dbAccountHandler extends dbHandlerBase { trashPlayer = PlayerCharacter.getPlayerCharacter(playerID); if (trashPlayer == null) - continue;; + continue; if (trashPlayer.isDeleted() == false) trashList.add(trashPlayer); } + } catch (SQLException e) { - Logger.error( e); - } finally { - closeCallable(); + Logger.error(e); } - return trashList; + + return trashList; } public void CLEAR_TRASH_TABLE() { - prepareCallable("DELETE FROM dyn_trash"); - executeUpdate(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM dyn_trash")) { + + preparedStatement.execute(); + + } catch (SQLException e) { + Logger.error(e); + } + } public void CREATE_SINGLE(String accountName, String password) { - prepareCallable("CALL singleAccountCreate(?,?)"); - setString(1, accountName); - setString(2, password); - executeUpdate(); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL singleAccountCreate(?,?)")) { + + preparedStatement.setString(1, accountName); + preparedStatement.setString(2, password); + + preparedStatement.execute(); + + } catch (SQLException e) { + Logger.error(e); + } + } public Account GET_ACCOUNT(String uname) { + Account account = null; + if (Account.AccountsMap.get(uname) != null) return this.GET_ACCOUNT(Account.AccountsMap.get(uname)); - prepareCallable("SELECT * FROM `obj_account` WHERE `acct_uname`=?"); - setString(1, uname); - ArrayList temp = getObjectList(); + try (Connection connection = DbManager.getConnection(); + PreparedStatement accountQuery = connection.prepareStatement("SELECT * FROM `obj_account` WHERE `acct_uname`=?")) { - if (temp.isEmpty()) - return null; + accountQuery.setString(1, uname); - if (temp.get(0) != null){ - temp.get(0).runAfterLoad(); + ResultSet rs = accountQuery.executeQuery(); + account = (Account) getObjectFromRs(rs); + + } catch (SQLException e) { + Logger.error(e); + } + + if (account != null) { + account.runAfterLoad(); if (ConfigManager.serverType.equals(Enum.ServerType.LOGINSERVER)) - Account.AccountsMap.put(uname, temp.get(0).getObjectUUID()); + Account.AccountsMap.put(uname, account.getObjectUUID()); } - return temp.get(0); + return account; } public void SET_ACCOUNT_LOGIN(final Account acc, String playerName, final String ip, final String machineID) { @@ -168,55 +222,61 @@ public class dbAccountHandler extends dbHandlerBase { if (acc.getObjectUUID() == 0 || ip == null || ip.length() == 0) return; - prepareCallable("INSERT INTO dyn_login_history(`AccountID`, `accountName`, `characterName`, `ip`, `machineID`, `timeStamp`)" - + " VALUES (?, ?, ?, ?, ?, ?)"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO dyn_login_history(`AccountID`, `accountName`, `characterName`, `ip`, `machineID`, `timeStamp`)" + + " VALUES (?, ?, ?, ?, ?, ?)")) { - setInt(1, acc.getObjectUUID()); - setString(2, acc.getUname()); - setString(3, playerName); - setString(4, ip); - setString(5, machineID); - setTimeStamp(6, System.currentTimeMillis()); - executeUpdate(); - } + preparedStatement.setInt(1, acc.getObjectUUID()); + preparedStatement.setString(2, acc.getUname()); + preparedStatement.setString(3, playerName); + preparedStatement.setString(4, ip); + preparedStatement.setString(5, machineID); + preparedStatement.setTimestamp(6, new java.sql.Timestamp(System.currentTimeMillis())); - public String SET_PROPERTY(final Account a, String name, Object new_value) { - prepareCallable("CALL account_SETPROP(?,?,?)"); - setLong(1, (long) a.getObjectUUID()); - setString(2, name); - setString(3, String.valueOf(new_value)); - return getResult(); - } + preparedStatement.execute(); - public String SET_PROPERTY(final Account a, String name, Object new_value, Object old_value) { - prepareCallable("CALL account_GETSETPROP(?,?,?,?)"); - setLong(1, (long) a.getObjectUUID()); - setString(2, name); - setString(3, String.valueOf(new_value)); - setString(4, String.valueOf(old_value)); - return getResult(); - } + } catch (SQLException e) { + Logger.error(e); + } + } public void updateDatabase(final Account acc) { - prepareCallable("UPDATE `obj_account` SET `acct_passwd`=?, " - + " `acct_lastCharUID`=?, `acct_salt`=?, `discordAccount`=?, " + - " status = ? WHERE `UID`=?"); - - setString(1, acc.getPasswd()); - setInt(2, acc.getLastCharIDUsed()); - setString(3, acc.getSalt()); - setString(4, acc.discordAccount); - setString(5, acc.status.name()); - setInt(6, acc.getObjectUUID()); - executeUpdate(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_account` SET `acct_passwd`=?, " + + " `acct_lastCharUID`=?, `acct_salt`=?, `discordAccount`=?, " + + " status = ? WHERE `UID`=?")) { + + preparedStatement.setString(1, acc.getPasswd()); + preparedStatement.setInt(2, acc.getLastCharIDUsed()); + preparedStatement.setString(3, acc.getSalt()); + preparedStatement.setString(4, acc.discordAccount); + preparedStatement.setString(5, acc.status.name()); + preparedStatement.setInt(6, acc.getObjectUUID()); + + preparedStatement.execute(); + + } catch (SQLException e) { + Logger.error(e); + } + } public void INVALIDATE_LOGIN_CACHE(long accountUID, String objectType) { - prepareCallable("INSERT IGNORE INTO login_cachelist (`UID`, `type`) VALUES(?,?);"); - setLong(1, accountUID); - setString(2, objectType); - executeUpdate(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT IGNORE INTO login_cachelist (`UID`, `type`) VALUES(?,?);")) { + + preparedStatement.setLong(1, accountUID); + preparedStatement.setString(2, objectType); + + preparedStatement.execute(); + + } catch (SQLException e) { + Logger.error(e); + } + } } diff --git a/src/engine/db/handlers/dbHandlerBase.java b/src/engine/db/handlers/dbHandlerBase.java index b23c6bb3..67271be3 100644 --- a/src/engine/db/handlers/dbHandlerBase.java +++ b/src/engine/db/handlers/dbHandlerBase.java @@ -286,7 +286,24 @@ public abstract class dbHandlerBase { String errorMsg = rs.getString("errormsg"); Logger.error("SQLError: errorNum: " + errorNum + ", errorMsg: " + errorMsg); logSQLCommand(); - } catch (SQLException e) {} + } catch (SQLException e) { + } + } + + protected AbstractGameObject getObjectFromRs(ResultSet rs) { + + AbstractGameObject abstractGameObject = null; + + try { + if (rs.next()) { + abstractGameObject = localClass.getConstructor(ResultSet.class).newInstance(rs); + DbManager.addToCache(abstractGameObject); + } + } catch (Exception e) { + Logger.error(e); + } + + return abstractGameObject; } protected AbstractGameObject getObjectSingle(int id) { From bffe953c3fc885327488f1fd66fabb97cf59baf0 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sat, 20 May 2023 17:51:21 -0400 Subject: [PATCH 025/109] Refactor to remove abstraction. --- src/engine/db/handlers/dbBaneHandler.java | 101 ++++++++++------------ 1 file changed, 48 insertions(+), 53 deletions(-) diff --git a/src/engine/db/handlers/dbBaneHandler.java b/src/engine/db/handlers/dbBaneHandler.java index 2748095e..08794bc5 100644 --- a/src/engine/db/handlers/dbBaneHandler.java +++ b/src/engine/db/handlers/dbBaneHandler.java @@ -9,6 +9,7 @@ package engine.db.handlers; +import engine.gameManager.DbManager; import engine.objects.Bane; import engine.objects.Building; import engine.objects.City; @@ -16,10 +17,10 @@ import engine.objects.PlayerCharacter; import org.joda.time.DateTime; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Level; public class dbBaneHandler extends dbHandlerBase { @@ -29,78 +30,63 @@ public class dbBaneHandler extends dbHandlerBase { public boolean CREATE_BANE(City city, PlayerCharacter owner, Building stone) { - prepareCallable("INSERT INTO `dyn_banes` (`cityUUID`, `ownerUUID`, `stoneUUID`, `placementDate`) VALUES(?,?,?,?)"); - setLong(1, (long) city.getObjectUUID()); - setLong(2, (long) owner.getObjectUUID()); - setLong(3, (long) stone.getObjectUUID()); - setTimeStamp(4, System.currentTimeMillis()); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_banes` (`cityUUID`, `ownerUUID`, `stoneUUID`, `placementDate`) VALUES(?,?,?,?)")) { - return (executeUpdate() > 0); + preparedStatement.setLong(1, city.getObjectUUID()); + preparedStatement.setLong(2, owner.getObjectUUID()); + preparedStatement.setLong(3, stone.getObjectUUID()); + preparedStatement.setTimestamp(4, new java.sql.Timestamp(System.currentTimeMillis())); + preparedStatement.execute(); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + + return true; } public Bane LOAD_BANE(int cityUUID) { - Bane newBane = null; - - try { + Bane bane = null; - prepareCallable("SELECT * from dyn_banes WHERE `dyn_banes`.`cityUUID` = ?"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * from dyn_banes WHERE `dyn_banes`.`cityUUID` = ?")) { - setLong(1, (long) cityUUID); - ResultSet rs = executeQuery(); + preparedStatement.setLong(1, cityUUID); + ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { - newBane = new Bane(rs); - Bane.addBane(newBane); + bane = new Bane(rs); + Bane.addBane(bane); } - } catch (SQLException ex) { - java.util.logging.Logger.getLogger(dbBaneHandler.class.getName()).log(Level.SEVERE, null, ex); - } finally { - closeCallable(); + } catch (SQLException e) { + Logger.error(e); } - return newBane; + return bane; } - public ConcurrentHashMap LOAD_ALL_BANES() { - - ConcurrentHashMap baneList; - Bane thisBane; - - baneList = new ConcurrentHashMap<>(); - - int recordsRead = 0; - - prepareCallable("SELECT * FROM dyn_banes"); - - try { - ResultSet rs = executeQuery(); - while (rs.next()) { + public boolean SET_BANE_TIME(DateTime toSet, int cityUUID) { - recordsRead++; - thisBane = new Bane(rs); - baneList.put(thisBane.getCityUUID(), thisBane); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_banes` SET `liveDate`=? WHERE `cityUUID`=?")) { - } + preparedStatement.setTimestamp(1, new java.sql.Timestamp(toSet.getMillis())); + preparedStatement.setLong(2, cityUUID); - Logger.info("read: " + recordsRead + " cached: " + baneList.size()); + preparedStatement.execute(); } catch (SQLException e) { - Logger.error( e.toString()); - } finally { - closeCallable(); + Logger.error(e); + return false; } - return baneList; - } - public boolean SET_BANE_TIME(DateTime toSet, int cityUUID) { - prepareCallable("UPDATE `dyn_banes` SET `liveDate`=? WHERE `cityUUID`=?"); - setTimeStamp(1, toSet.getMillis()); - setLong(2, cityUUID); - return (executeUpdate() > 0); + return true; } public boolean REMOVE_BANE(Bane bane) { @@ -108,8 +94,17 @@ public class dbBaneHandler extends dbHandlerBase { if (bane == null) return false; - prepareCallable("DELETE FROM `dyn_banes` WHERE `cityUUID` = ?"); - setLong(1, (long) bane.getCity().getObjectUUID()); - return (executeUpdate() > 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_banes` WHERE `cityUUID` = ?")) { + + preparedStatement.setLong(1, bane.getCity().getObjectUUID()); + preparedStatement.execute(); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + return true; + } } From 7e511f590dc68461bdbfa8ff332a005afe02fbcd Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sat, 20 May 2023 19:02:56 -0400 Subject: [PATCH 026/109] Created getObjectsFromRs() --- .../db/handlers/dbBaseClassHandler.java | 60 ++++++++++++++++--- src/engine/db/handlers/dbHandlerBase.java | 28 +++++++++ .../db/handlers/dbPlayerCharacterHandler.java | 53 ---------------- 3 files changed, 79 insertions(+), 62 deletions(-) diff --git a/src/engine/db/handlers/dbBaseClassHandler.java b/src/engine/db/handlers/dbBaseClassHandler.java index 3ae0f098..ce4e1d41 100644 --- a/src/engine/db/handlers/dbBaseClassHandler.java +++ b/src/engine/db/handlers/dbBaseClassHandler.java @@ -13,7 +13,12 @@ import engine.Enum; import engine.Enum.GameObjectType; import engine.gameManager.DbManager; import engine.objects.BaseClass; +import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.ArrayList; public class dbBaseClassHandler extends dbHandlerBase { @@ -27,24 +32,61 @@ public class dbBaseClassHandler extends dbHandlerBase { if (id == 0) return null; + BaseClass baseClass = (BaseClass) DbManager.getFromCache(GameObjectType.BaseClass, id); + if (baseClass != null) return baseClass; + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `obj_account` WHERE `UID`=?")) { + + preparedStatement.setLong(1, id); + + ResultSet rs = preparedStatement.executeQuery(); + baseClass = (BaseClass) getObjectFromRs(rs); + + } catch (SQLException e) { + Logger.error(e); + } - prepareCallable("SELECT * FROM `static_rune_baseclass` WHERE `ID` = ?;"); - setInt(1, id); - return (BaseClass) getObjectSingle(id); + return baseClass; } public ArrayList GET_BASECLASS_FOR_RACE(final int id) { - prepareCallable("SELECT b.* FROM `static_rune_baseclass` b, `static_rune_racebaseclass` r WHERE b.`ID` = r.`BaseClassID` && r.`RaceID` = ?"); - setInt(1, id); - return getObjectList(); + + ArrayList baseClasses = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT b.* FROM `static_rune_baseclass` b, `static_rune_racebaseclass` r WHERE b.`ID` = r.`BaseClassID` && r.`RaceID` = ?")) { + + preparedStatement.setInt(1, id); + + ResultSet rs = preparedStatement.executeQuery(); + baseClasses = getObjectsFromRs(rs, 20); + + } catch (SQLException e) { + Logger.error(e); + } + + return baseClasses; } - public ArrayList GET_ALL_BASE_CLASSES(){ - prepareCallable("SELECT * FROM `static_rune_baseclass`;"); - return getObjectList(); + public ArrayList GET_ALL_BASE_CLASSES() { + + ArrayList baseClasses = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_baseclass`;")) { + + ResultSet rs = preparedStatement.executeQuery(); + baseClasses = getObjectsFromRs(rs, 20); + + } catch (SQLException e) { + Logger.error(e); + } + + return baseClasses; + } } diff --git a/src/engine/db/handlers/dbHandlerBase.java b/src/engine/db/handlers/dbHandlerBase.java index 67271be3..53eea3c2 100644 --- a/src/engine/db/handlers/dbHandlerBase.java +++ b/src/engine/db/handlers/dbHandlerBase.java @@ -297,6 +297,7 @@ public abstract class dbHandlerBase { try { if (rs.next()) { abstractGameObject = localClass.getConstructor(ResultSet.class).newInstance(rs); + DbManager.addToCache(abstractGameObject); } } catch (Exception e) { @@ -306,6 +307,33 @@ public abstract class dbHandlerBase { return abstractGameObject; } + protected ArrayList getObjectsFromRs(ResultSet rs, int listSize) { + + ArrayList objectList = new ArrayList<>(listSize); + + try { + while (rs.next()) { + + int id = rs.getInt(1); + + if (DbManager.inCache(localObjectType, id)) { + objectList.add((T) DbManager.getFromCache(localObjectType, id)); + } else { + AbstractGameObject toAdd = localClass.getConstructor(ResultSet.class).newInstance(rs); + DbManager.addToCache(toAdd); + objectList.add((T) toAdd); + + if (toAdd != null && toAdd instanceof AbstractWorldObject) + ((AbstractWorldObject) toAdd).runAfterLoad(); + } + } + } catch (Exception e) { + Logger.error(e); + } + return objectList; + + } + protected AbstractGameObject getObjectSingle(int id) { return getObjectSingle(id, false, true); } diff --git a/src/engine/db/handlers/dbPlayerCharacterHandler.java b/src/engine/db/handlers/dbPlayerCharacterHandler.java index 1fb8e394..3dfeb6ae 100644 --- a/src/engine/db/handlers/dbPlayerCharacterHandler.java +++ b/src/engine/db/handlers/dbPlayerCharacterHandler.java @@ -76,22 +76,6 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { } } - public static boolean DELETE_CHARACTER_IGNORE(final PlayerCharacter pc, final ArrayList toDelete) { - - return false; - } - - public ArrayList GET_ALL_PLAYERCHARACTERS() { - prepareCallable("SELECT * FROM `obj_character`"); - return getObjectList(); - } - - public ArrayList GET_CHARACTERS_FOR_ACCOUNT(final int id, boolean forceFromDB) { - prepareCallable("SELECT `obj_character`.*, `object`.`parent` FROM `object` INNER JOIN `obj_character` ON `obj_character`.`UID` = `object`.`UID` WHERE `object`.`parent`=? && `obj_character`.`char_isActive`='1';"); - setLong(1, (long) id); - return getObjectList(10, forceFromDB); - } - public ArrayList GET_CHARACTERS_FOR_ACCOUNT(final int id) { prepareCallable("SELECT `obj_character`.*, `object`.`parent` FROM `object` INNER JOIN `obj_character` ON `obj_character`.`UID` = `object`.`UID` WHERE `object`.`parent`=? && `obj_character`.`char_isActive`='1';"); setLong(1, (long) id); @@ -111,22 +95,6 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { * and cached. * */ - public String GET_FIRST_NAME(final int objectUUID) { - prepareCallable("SELECT `char_firstname` from `obj_character` WHERE `UID` = ? LIMIT 1"); - setLong(1, (long) objectUUID); - String firstName = ""; - try { - ResultSet rs = executeQuery(); - if (rs.next()) { - firstName = rs.getString("char_firstname"); - } - } catch (SQLException e) { - Logger.error( e); - } finally { - closeCallable(); - } - return firstName; - } public ConcurrentHashMap GET_IGNORE_LIST(final int objectUUID, final boolean skipActiveCheck) { ConcurrentHashMap out = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW); @@ -165,20 +133,6 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { return (PlayerCharacter) getObjectSingle(objectUUID); } - public boolean INSERT_CHARACTER_IGNORE(final PlayerCharacter pc, final ArrayList toAdd) { - boolean allWorked = true; - prepareCallable("INSERT INTO `dyn_character_ignore` (`characterUID`, `ignoringUID`) VALUES (?, ?)"); - setLong(1, (long) pc.getObjectUUID()); - for (int id : toAdd) { - setLong(2, (long) id); - if (executeUpdate(false) == 0) { - allWorked = false; - } - } - closeCallable(); - return allWorked; - } - public boolean IS_CHARACTER_NAME_UNIQUE(final String firstName) { boolean unique = true; prepareCallable("SELECT `char_firstname` FROM `obj_character` WHERE `char_isActive`=1 && `char_firstname`=?"); @@ -247,13 +201,6 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { return (executeUpdate() != 0); } - public boolean UPDATE_CHARACTER_STAT(final PlayerCharacter pc, String stat, short amount) { - prepareCallable("UPDATE `obj_character` SET `" + stat + "`=? WHERE `UID`=?"); - setInt(1, pc.getExp()); - setLong(2, (long) pc.getObjectUUID()); - return (executeUpdate() != 0); - } - public boolean UPDATE_CHARACTER_STATS(final PlayerCharacter pc) { prepareCallable("UPDATE `obj_character` SET `char_strMod`=?, `char_dexMod`=?, `char_conMod`=?, `char_intMod`=?, `char_spiMod`=? WHERE `UID`=?"); setInt(1, pc.getStrMod()); From 4daee03f0da63186937c6556b0d81c793904bfaa Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sat, 20 May 2023 19:09:28 -0400 Subject: [PATCH 027/109] Refactored to remove abstraction. --- src/engine/db/handlers/dbAccountHandler.java | 6 ++-- .../db/handlers/dbBlueprintHandler.java | 31 +++++++++---------- 2 files changed, 18 insertions(+), 19 deletions(-) diff --git a/src/engine/db/handlers/dbAccountHandler.java b/src/engine/db/handlers/dbAccountHandler.java index f94f9fab..577c264e 100644 --- a/src/engine/db/handlers/dbAccountHandler.java +++ b/src/engine/db/handlers/dbAccountHandler.java @@ -196,11 +196,11 @@ public class dbAccountHandler extends dbHandlerBase { return this.GET_ACCOUNT(Account.AccountsMap.get(uname)); try (Connection connection = DbManager.getConnection(); - PreparedStatement accountQuery = connection.prepareStatement("SELECT * FROM `obj_account` WHERE `acct_uname`=?")) { + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `obj_account` WHERE `acct_uname`=?")) { - accountQuery.setString(1, uname); + preparedStatement.setString(1, uname); - ResultSet rs = accountQuery.executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); account = (Account) getObjectFromRs(rs); } catch (SQLException e) { diff --git a/src/engine/db/handlers/dbBlueprintHandler.java b/src/engine/db/handlers/dbBlueprintHandler.java index 7ecd4dfe..194ca9fe 100644 --- a/src/engine/db/handlers/dbBlueprintHandler.java +++ b/src/engine/db/handlers/dbBlueprintHandler.java @@ -1,8 +1,11 @@ package engine.db.handlers; +import engine.gameManager.DbManager; import engine.objects.Blueprint; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; @@ -22,10 +25,10 @@ public class dbBlueprintHandler extends dbHandlerBase { int doorNum; int recordsRead = 0; - prepareCallable("SELECT * FROM static_building_doors ORDER BY doorMeshUUID ASC"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_building_doors ORDER BY doorMeshUUID ASC")) { - try { - ResultSet rs = executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { @@ -35,13 +38,11 @@ public class dbBlueprintHandler extends dbHandlerBase { doorInfo.put(doorUUID, doorNum); } - Logger.info( "read: " + recordsRead + " cached: " + doorInfo.size()); - } catch (SQLException e) { - Logger.error("LoadAllDoorNumbers: " + e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); + Logger.error(e); } + + Logger.info("read: " + recordsRead + " cached: " + doorInfo.size()); return doorInfo; } @@ -53,10 +54,10 @@ public class dbBlueprintHandler extends dbHandlerBase { blueprints = new HashMap<>(); int recordsRead = 0; - prepareCallable("SELECT * FROM static_building_blueprint"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `obj_account` WHERE `acct_uname`=?")) { - try { - ResultSet rs = executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { @@ -74,13 +75,11 @@ public class dbBlueprintHandler extends dbHandlerBase { } - Logger.info( "read: " + recordsRead + " cached: " + blueprints.size()); - } catch (SQLException e) { - Logger.error("LoadAllBlueprints: " + e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); + Logger.error(e); } + + Logger.info("read: " + recordsRead + " cached: " + blueprints.size()); return blueprints; } } From a683eb6290d27472c67b26546c87150756730a27 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sat, 20 May 2023 19:14:01 -0400 Subject: [PATCH 028/109] Refactored to remove abstraction. --- .../db/handlers/dbBlueprintHandler.java | 2 +- src/engine/db/handlers/dbBoonHandler.java | 52 +++++++++---------- src/engine/objects/Boon.java | 2 +- 3 files changed, 28 insertions(+), 28 deletions(-) diff --git a/src/engine/db/handlers/dbBlueprintHandler.java b/src/engine/db/handlers/dbBlueprintHandler.java index 194ca9fe..46d36ef7 100644 --- a/src/engine/db/handlers/dbBlueprintHandler.java +++ b/src/engine/db/handlers/dbBlueprintHandler.java @@ -55,7 +55,7 @@ public class dbBlueprintHandler extends dbHandlerBase { int recordsRead = 0; try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `obj_account` WHERE `acct_uname`=?")) { + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_building_blueprint")) { ResultSet rs = preparedStatement.executeQuery(); diff --git a/src/engine/db/handlers/dbBoonHandler.java b/src/engine/db/handlers/dbBoonHandler.java index ca7b6db1..02951d4a 100644 --- a/src/engine/db/handlers/dbBoonHandler.java +++ b/src/engine/db/handlers/dbBoonHandler.java @@ -9,9 +9,12 @@ package engine.db.handlers; +import engine.gameManager.DbManager; import engine.objects.Boon; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; @@ -20,32 +23,29 @@ public class dbBoonHandler extends dbHandlerBase { public dbBoonHandler() { } - - - public ArrayList GET_BOON_AMOUNTS_FOR_ITEMBASEUUID(int itemBaseUUID){ - - ArrayListboons = new ArrayList<>(); - Boon thisBoon; - prepareCallable("SELECT * FROM `static_item_boons` WHERE `itemBaseID` = ?"); - setInt(1, itemBaseUUID); - - try { - ResultSet rs = executeQuery(); - - while (rs.next()) { - - - thisBoon = new Boon(rs); - boons.add(thisBoon); + + + public ArrayList GET_BOON_AMOUNTS_FOR_ITEMBASE(int itemBaseUUID) { + + ArrayList boons = new ArrayList<>(); + Boon thisBoon; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_item_boons` WHERE `itemBaseID` = ?")) { + + preparedStatement.setInt(1, itemBaseUUID); + + ResultSet rs = preparedStatement.executeQuery(); + + while (rs.next()) { + thisBoon = new Boon(rs); + boons.add(thisBoon); + } + + } catch (SQLException e) { + Logger.error(e); } - - - - } catch (SQLException e) { - Logger.error("GetBoonAmountsForItembaseUUID: " + e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); + + return boons; } - return boons; -} } diff --git a/src/engine/objects/Boon.java b/src/engine/objects/Boon.java index 3c3bcb6d..29908b05 100644 --- a/src/engine/objects/Boon.java +++ b/src/engine/objects/Boon.java @@ -55,7 +55,7 @@ public class Boon { public static void HandleBoonListsForItemBase(int itemBaseID){ ArrayList boons = null; - boons = DbManager.BoonQueries.GET_BOON_AMOUNTS_FOR_ITEMBASEUUID(itemBaseID); + boons = DbManager.BoonQueries.GET_BOON_AMOUNTS_FOR_ITEMBASE(itemBaseID); if (boons != null) GetBoonsForItemBase.put(itemBaseID, boons); } From 962649c0f24d4f46401f98e6f004151cd33646b2 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sat, 20 May 2023 19:34:02 -0400 Subject: [PATCH 029/109] Db methods moved to db system. --- src/engine/db/handlers/dbSkillReqHandler.java | 64 +++++++++++++++++-- src/engine/gameManager/PowersManager.java | 7 +- src/engine/powers/PowersBase.java | 53 --------------- 3 files changed, 61 insertions(+), 63 deletions(-) diff --git a/src/engine/db/handlers/dbSkillReqHandler.java b/src/engine/db/handlers/dbSkillReqHandler.java index b0e16f90..6025b7c6 100644 --- a/src/engine/db/handlers/dbSkillReqHandler.java +++ b/src/engine/db/handlers/dbSkillReqHandler.java @@ -9,9 +9,14 @@ package engine.db.handlers; +import engine.objects.PreparedStatementShared; import engine.objects.SkillReq; +import engine.powers.PowersBase; +import org.pmw.tinylog.Logger; +import java.sql.ResultSet; import java.util.ArrayList; +import java.util.HashMap; public class dbSkillReqHandler extends dbHandlerBase { @@ -20,16 +25,61 @@ public class dbSkillReqHandler extends dbHandlerBase { this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); } + public static ArrayList getAllPowersBase() { + PreparedStatementShared ps = null; + ArrayList out = new ArrayList<>(); + try { + ps = new PreparedStatementShared("SELECT * FROM static_power_powerbase"); + ResultSet rs = ps.executeQuery(); + while (rs.next()) { + PowersBase toAdd = new PowersBase(rs); + out.add(toAdd); + } + rs.close(); + } catch (Exception e) { + Logger.error(e.toString()); + } finally { + ps.release(); + } + return out; + } + + public static void getFailConditions(HashMap powers) { + PreparedStatementShared ps = null; + try { + ps = new PreparedStatementShared("SELECT IDString, type FROM static_power_failcondition where powerOrEffect = 'Power'"); + ResultSet rs = ps.executeQuery(); + String type, IDString; + PowersBase pb; + while (rs.next()) { + type = rs.getString("type"); + IDString = rs.getString("IDString"); + pb = powers.get(IDString); + if (pb != null) { + switch (type) { + case "CastSpell": + pb.cancelOnCastSpell = true; + break; + case "TakeDamage": + pb.cancelOnTakeDamage = true; + break; + } + } else { + Logger.error("null power for Grief " + IDString); + } + } + rs.close(); + } catch (Exception e) { + Logger.error(e.toString()); + } finally { + ps.release(); + } + } + public ArrayList GET_REQS_FOR_RUNE(final int objectUUID) { prepareCallable("SELECT * FROM `static_skill_skillreq` WHERE `runeID`=?"); setInt(1, objectUUID); return getObjectList(); } - - public SkillReq GET_REQS_BY_SKILLID(int skillID) { - prepareCallable("SELECT * FROM `static_skill_skillreq` WHERE `skillID` = ?"); - setInt(1,skillID); - int objectUUID = (int) getUUID(); - return (SkillReq) this.getObjectSingle(objectUUID); - } + } diff --git a/src/engine/gameManager/PowersManager.java b/src/engine/gameManager/PowersManager.java index eeaf9c47..59a4aa36 100644 --- a/src/engine/gameManager/PowersManager.java +++ b/src/engine/gameManager/PowersManager.java @@ -12,6 +12,7 @@ import engine.Enum.*; import engine.InterestManagement.HeightMap; import engine.InterestManagement.WorldGrid; import engine.db.handlers.dbEffectsBaseHandler; +import engine.db.handlers.dbSkillReqHandler; import engine.job.AbstractJob; import engine.job.AbstractScheduleJob; import engine.job.JobContainer; @@ -100,7 +101,7 @@ public enum PowersManager { public static void InitializeLoginPowers() { // get all PowersBase - ArrayList pbList = PowersBase.getAllPowersBase(); + ArrayList pbList = dbSkillReqHandler.getAllPowersBase(); for (PowersBase pb : pbList) { if (pb.getToken() != 0) @@ -137,7 +138,7 @@ public enum PowersManager { // AbstractPowerAction.loadValidItemFlags(PowersManager.powerActionsByIDString); // get all PowersBase - ArrayList pbList = PowersBase.getAllPowersBase(); + ArrayList pbList = dbSkillReqHandler.getAllPowersBase(); for (PowersBase pb : pbList) { if (pb.getToken() != 0) { PowersManager.powersBaseByIDString.put(pb.getIDString(), pb); @@ -148,7 +149,7 @@ public enum PowersManager { // Add Power Prereqs PowerPrereq.getAllPowerPrereqs(PowersManager.powersBaseByIDString); // Add Fail Conditions - PowersBase.getFailConditions(PowersManager.powersBaseByIDString); + dbSkillReqHandler.getFailConditions(PowersManager.powersBaseByIDString); // Add Actions Base ActionsBase.getActionsBase(PowersManager.powersBaseByIDString, PowersManager.powerActionsByIDString); diff --git a/src/engine/powers/PowersBase.java b/src/engine/powers/PowersBase.java index 89e4aa37..ca24eb06 100644 --- a/src/engine/powers/PowersBase.java +++ b/src/engine/powers/PowersBase.java @@ -11,13 +11,11 @@ package engine.powers; import engine.Enum.PowerCategoryType; import engine.Enum.PowerTargetType; -import engine.objects.PreparedStatementShared; import org.pmw.tinylog.Logger; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; -import java.util.HashMap; public class PowersBase { @@ -340,57 +338,6 @@ public class PowersBase { this.monsterTypeRestrictions.add(ct); } - public static ArrayList getAllPowersBase() { - PreparedStatementShared ps = null; - ArrayList out = new ArrayList<>(); - try { - ps = new PreparedStatementShared("SELECT * FROM static_power_powerbase"); - ResultSet rs = ps.executeQuery(); - while (rs.next()) { - PowersBase toAdd = new PowersBase(rs); - out.add(toAdd); - } - rs.close(); - } catch (Exception e) { - Logger.error( e.toString()); - } finally { - ps.release(); - } - return out; - } - - - public static void getFailConditions(HashMap powers) { - PreparedStatementShared ps = null; - try { - ps = new PreparedStatementShared("SELECT IDString, type FROM static_power_failcondition where powerOrEffect = 'Power'"); - ResultSet rs = ps.executeQuery(); - String type, IDString; PowersBase pb; - while (rs.next()) { - type = rs.getString("type"); - IDString = rs.getString("IDString"); - pb = powers.get(IDString); - if (pb != null) { - switch (type) { - case "CastSpell": - pb.cancelOnCastSpell = true; - break; - case "TakeDamage": - pb.cancelOnTakeDamage = true; - break; - } - }else{ - Logger.error("null power for Grief " + IDString); - } - } - rs.close(); - } catch (Exception e) { - Logger.error( e.toString()); - } finally { - ps.release(); - } - } - public String getName() { return this.name; From 5b3dfbcc215be7937272afd58eac337c6eaa0f3e Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sat, 20 May 2023 19:58:47 -0400 Subject: [PATCH 030/109] Refactor to remove abstraction --- src/engine/db/handlers/dbAccountHandler.java | 6 +- src/engine/db/handlers/dbBuildingHandler.java | 76 ++++++++++++------- 2 files changed, 51 insertions(+), 31 deletions(-) diff --git a/src/engine/db/handlers/dbAccountHandler.java b/src/engine/db/handlers/dbAccountHandler.java index 577c264e..49d625bc 100644 --- a/src/engine/db/handlers/dbAccountHandler.java +++ b/src/engine/db/handlers/dbAccountHandler.java @@ -43,11 +43,11 @@ public class dbAccountHandler extends dbHandlerBase { return account; try (Connection connection = DbManager.getConnection(); - PreparedStatement accountQuery = connection.prepareStatement("SELECT * FROM `obj_account` WHERE `UID`=?")) { + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `obj_account` WHERE `UID`=?")) { - accountQuery.setLong(1, accountID); + preparedStatement.setLong(1, accountID); - ResultSet rs = accountQuery.executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); account = (Account) getObjectFromRs(rs); } catch (SQLException e) { diff --git a/src/engine/db/handlers/dbBuildingHandler.java b/src/engine/db/handlers/dbBuildingHandler.java index 4b282281..252c3c45 100644 --- a/src/engine/db/handlers/dbBuildingHandler.java +++ b/src/engine/db/handlers/dbBuildingHandler.java @@ -19,6 +19,8 @@ import engine.objects.*; import org.joda.time.DateTime; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDateTime; @@ -40,25 +42,25 @@ public class dbBuildingHandler extends dbHandlerBase { DateTime upgradeDate, int blueprintUUID, float w, float rotY) { Building toCreate = null; - try { - prepareCallable("CALL `building_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,? ,? ,?, ?);"); - - setInt(1, parentZoneID); - setInt(2, OwnerUUID); - setString(3, name); - setInt(4, meshUUID); - setFloat(5, location.x); - setFloat(6, location.y); - setFloat(7, location.z); - setFloat(8, meshScale); - setInt(9, currentHP); - setString(10, protectionState.name()); - setInt(11, currentGold); - setInt(12, rank); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL `building_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,? ,? ,?, ?);")) { + + preparedStatement.setInt(1, parentZoneID); + preparedStatement.setInt(2, OwnerUUID); + preparedStatement.setString(3, name); + preparedStatement.setInt(4, meshUUID); + preparedStatement.setFloat(5, location.x); + preparedStatement.setFloat(6, location.y); + preparedStatement.setFloat(7, location.z); + preparedStatement.setFloat(8, meshScale); + preparedStatement.setInt(9, currentHP); + preparedStatement.setString(10, protectionState.name()); + preparedStatement.setInt(11, currentGold); + preparedStatement.setInt(12, rank); if (upgradeDate != null) - setTimeStamp(13, upgradeDate.getMillis()); + preparedStatement.setTimestamp(13, new java.sql.Timestamp(upgradeDate.getMillis())); else setNULL(13, java.sql.Types.DATE); @@ -66,16 +68,15 @@ public class dbBuildingHandler extends dbHandlerBase { setFloat(15, w); setFloat(16, rotY); - int objectUUID = (int) getUUID(); + ResultSet rs = preparedStatement.executeQuery(); + + int objectUUID = (int) rs.getLong("UID"); if (objectUUID > 0) toCreate = GET_BUILDINGBYUUID(objectUUID); - } catch (Exception e) { - Logger.error("CREATE_BUILDING", e.getMessage()); - return null; - } finally { - closeCallable(); + } catch (SQLException e) { + throw new RuntimeException(e); } return toCreate; @@ -93,6 +94,7 @@ public class dbBuildingHandler extends dbHandlerBase { } public Building GET_BUILDINGBYUUID(int uuid) { + if (uuid == 0) return null; @@ -101,11 +103,19 @@ public class dbBuildingHandler extends dbHandlerBase { if (building != null) return building; - prepareCallable("SELECT `obj_building`.*, `object`.`parent` FROM `object` INNER JOIN `obj_building` ON `obj_building`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?;"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_building`.*, `object`.`parent` FROM `object` INNER JOIN `obj_building` ON `obj_building`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?;")) { + + preparedStatement.setLong(1, (long) uuid); - setLong(1, (long) uuid); - return (Building) getObjectSingle(uuid); + ResultSet rs = preparedStatement.executeQuery(); + building = (Building) getObjectFromRs(rs); + } catch (SQLException e) { + Logger.error(e); + } + + return building; } public Building GET_BUILDING_BY_MESH(final int meshID) { @@ -154,9 +164,19 @@ public class dbBuildingHandler extends dbHandlerBase { } private boolean removeFromBuildings(final Building b) { - prepareCallable("DELETE FROM `object` WHERE `UID` = ?"); - setLong(1, b.getObjectUUID()); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `object` WHERE `UID` = ?")) { + + preparedStatement.setLong(1, b.getObjectUUID()); + preparedStatement.execute(); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + + return true; } public boolean CHANGE_NAME(Building b, String newName) { From 2e42cbed06652e728c26077abccc9e5f85e56786 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sat, 20 May 2023 20:40:52 -0400 Subject: [PATCH 031/109] Refactor to remove abstraction --- src/engine/db/handlers/dbBuildingHandler.java | 268 ++++++++++++------ 1 file changed, 189 insertions(+), 79 deletions(-) diff --git a/src/engine/db/handlers/dbBuildingHandler.java b/src/engine/db/handlers/dbBuildingHandler.java index 252c3c45..d73abecf 100644 --- a/src/engine/db/handlers/dbBuildingHandler.java +++ b/src/engine/db/handlers/dbBuildingHandler.java @@ -88,9 +88,22 @@ public class dbBuildingHandler extends dbHandlerBase { } public ArrayList GET_ALL_BUILDINGS_FOR_ZONE(Zone zone) { - prepareCallable("SELECT `obj_building`.*, `object`.`parent` FROM `object` INNER JOIN `obj_building` ON `obj_building`.`UID` = `object`.`UID` WHERE `object`.`parent` = ?;"); - setLong(1, zone.getObjectUUID()); - return getLargeObjectList(); + + ArrayList buildings = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_building`.*, `object`.`parent` FROM `object` INNER JOIN `obj_building` ON `obj_building`.`UID` = `object`.`UID` WHERE `object`.`parent` = ?;")) { + + preparedStatement.setLong(1, zone.getObjectUUID()); + + ResultSet rs = preparedStatement.executeQuery(); + buildings = getObjectsFromRs(rs, 2000); + + } catch (SQLException e) { + Logger.error(e); + } + + return buildings; } public Building GET_BUILDINGBYUUID(int uuid) { @@ -119,48 +132,69 @@ public class dbBuildingHandler extends dbHandlerBase { } public Building GET_BUILDING_BY_MESH(final int meshID) { - Building toReturn = null; - prepareCallable("CALL building_GETBYMESH(?)"); - setInt(1, meshID); - try { - ResultSet rs = executeQuery(); + + Building building = null; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL building_GETBYMESH(?)")) { + + preparedStatement.setInt(1, meshID); + + ResultSet rs = preparedStatement.executeQuery(); + if (rs.next()) - toReturn = new Building(rs); - rs.close(); + building = new Building(rs); + } catch (SQLException e) { Logger.error("Building", e); return null; - } finally { - closeCallable(); } - return toReturn; + return building; } public String SET_PROPERTY(final Building b, String name, Object new_value) { - prepareCallable("CALL building_SETPROP(?,?,?)"); - setLong(1, b.getObjectUUID()); - setString(2, name); - setString(3, String.valueOf(new_value)); - return getResult(); - } - public String SET_PROPERTY(final Building b, String name, Object new_value, Object old_value) { - prepareCallable("CALL building_GETSETPROP(?,?,?,?)"); - setLong(1, b.getObjectUUID()); - setString(2, name); - setString(3, String.valueOf(new_value)); - setString(4, String.valueOf(old_value)); - return getResult(); + String result = ""; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL building_SETPROP(?,?,?)")) { + + preparedStatement.setLong(1, b.getObjectUUID()); + preparedStatement.setString(2, name); + preparedStatement.setString(3, String.valueOf(new_value)); + + ResultSet rs = preparedStatement.executeQuery(); + result = rs.getString("result"); + ; + + } catch (SQLException e) { + Logger.error(e); + } + + return result; } public int MOVE_BUILDING(long buildingID, long parentID, float locX, float locY, float locZ) { - prepareCallable("UPDATE `object` INNER JOIN `obj_building` On `object`.`UID` = `obj_building`.`UID` SET `object`.`parent`=?, `obj_building`.`locationX`=?, `obj_building`.`locationY`=?, `obj_building`.`locationZ`=? WHERE `obj_building`.`UID`=?;"); - setLong(1, parentID); - setFloat(2, locX); - setFloat(3, locY); - setFloat(4, locZ); - setLong(5, buildingID); - return executeUpdate(); + + int rowCount; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `object` INNER JOIN `obj_building` On `object`.`UID` = `obj_building`.`UID` SET `object`.`parent`=?, `obj_building`.`locationX`=?, `obj_building`.`locationY`=?, `obj_building`.`locationZ`=? WHERE `obj_building`.`UID`=?;")) { + + preparedStatement.setLong(1, parentID); + preparedStatement.setFloat(2, locX); + preparedStatement.setFloat(3, locY); + preparedStatement.setFloat(4, locZ); + preparedStatement.setLong(5, buildingID); + + rowCount = preparedStatement.executeUpdate(); + + } catch (SQLException e) { + Logger.error(e); + return 0; + } + + return rowCount; } private boolean removeFromBuildings(final Building b) { @@ -180,85 +214,161 @@ public class dbBuildingHandler extends dbHandlerBase { } public boolean CHANGE_NAME(Building b, String newName) { - prepareCallable("UPDATE `obj_building` SET `name`=? WHERE `UID`=?"); - setString(1, newName); - setLong(2, b.getObjectUUID()); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_building` SET `name`=? WHERE `UID`=?")) { + + preparedStatement.setString(1, newName); + preparedStatement.setLong(2, b.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } public boolean SET_RESERVE(Building b, int reserveAmount) { - prepareCallable("UPDATE `obj_building` SET `reserve`=? WHERE `UID`=?"); - setInt(1, reserveAmount); - setLong(2, b.getObjectUUID()); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_building` SET `reserve`=? WHERE `UID`=?")) { + + preparedStatement.setInt(1, reserveAmount); + preparedStatement.setLong(2, b.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } //CAS update to rank public boolean CHANGE_RANK(final long buildingID, int newRank) { - prepareCallable("UPDATE `obj_building` SET `rank`=? WHERE `UID`=?"); - setInt(1, newRank); - setLong(2, buildingID); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_building` SET `rank`=? WHERE `UID`=?")) { + + preparedStatement.setInt(1, newRank); + preparedStatement.setLong(2, buildingID); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } public boolean UPDATE_BUILDING_HEALTH(final long buildingID, int NewHealth) { - prepareCallable("UPDATE `obj_building` SET `currentHP`=? WHERE `UID`=?"); - setInt(1, NewHealth); - setLong(2, buildingID); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_building` SET `currentHP`=? WHERE `UID`=?")) { + + preparedStatement.setInt(1, NewHealth); + preparedStatement.setLong(2, buildingID); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } public boolean UPDATE_BUILDING_ALTITUDE(final long buildingID, float newAltitude) { - prepareCallable("UPDATE `obj_building` SET `locationY`=? WHERE `UID`=?"); - setFloat(1, newAltitude); - setLong(2, buildingID); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_building` SET `locationY`=? WHERE `UID`=?")) { + + preparedStatement.setFloat(1, newAltitude); + preparedStatement.setLong(2, buildingID); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } public boolean UPDATE_PROTECTIONSTATE(final long buildingUUID, ProtectionState protectionState) { - try { - prepareCallable("UPDATE `obj_building` SET `protectionState`=? WHERE `UID`=?"); - setString(1, protectionState.name()); - setLong(2, buildingUUID); - return (executeUpdate() > 0); - } catch (Exception e) { - Logger.error(e.toString()); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_building` SET `protectionState`=? WHERE `UID`=?")) { + + preparedStatement.setString(1, protectionState.name()); + preparedStatement.setLong(2, buildingUUID); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); return false; } + } public boolean UPDATE_DOOR_LOCK(final int buildingUUID, int doorFlags) { - try { - prepareCallable("UPDATE obj_building SET doorState = ? WHERE UID = ?"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE obj_building SET doorState = ? WHERE UID = ?")) { - setInt(1, doorFlags); - setInt(2, buildingUUID); + preparedStatement.setInt(1, doorFlags); + preparedStatement.setInt(2, buildingUUID); - executeUpdate(); - return true; - } catch (Exception e) { + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); return false; } + } public boolean ADD_TO_FRIENDS_LIST(final long buildingID, final long friendID, final long guildID, final int friendType) { - prepareCallable("INSERT INTO `dyn_building_friends` (`buildingUID`, `playerUID`,`guildUID`, `friendType`) VALUES (?,?,?,?)"); - setLong(1, buildingID); - setLong(2, friendID); - setLong(3, guildID); - setInt(4, friendType); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_building_friends` (`buildingUID`, `playerUID`,`guildUID`, `friendType`) VALUES (?,?,?,?)")) { + + preparedStatement.setLong(1, buildingID); + preparedStatement.setLong(2, friendID); + preparedStatement.setLong(3, guildID); + preparedStatement.setInt(4, friendType); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } public boolean REMOVE_FROM_FRIENDS_LIST(final long buildingID, long friendID, long guildID, int friendType) { - prepareCallable("DELETE FROM `dyn_building_friends` WHERE `buildingUID`=? AND `playerUID`=? AND `guildUID` =? AND `friendType` = ?"); - setLong(1, buildingID); - setLong(2, friendID); - setLong(3,guildID); - setInt(4, friendType); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_building_friends` WHERE `buildingUID`=? AND `playerUID`=? AND `guildUID` =? AND `friendType` = ?")) { + + preparedStatement.setLong(1, buildingID); + preparedStatement.setLong(2, friendID); + preparedStatement.setLong(3, guildID); + preparedStatement.setInt(4, friendType); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } public boolean REMOVE_FROM_CONDEMNED_LIST(final long buildingID, long friendID, long guildID, int friendType) { From daa5764bfb317b8752dee1f8c82c45aa2f3b1f1a Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sat, 20 May 2023 21:18:32 -0400 Subject: [PATCH 032/109] Refactor to remove abstraction --- src/engine/db/handlers/dbBuildingHandler.java | 96 ++++++++++++------- 1 file changed, 64 insertions(+), 32 deletions(-) diff --git a/src/engine/db/handlers/dbBuildingHandler.java b/src/engine/db/handlers/dbBuildingHandler.java index d73abecf..e55c35b5 100644 --- a/src/engine/db/handlers/dbBuildingHandler.java +++ b/src/engine/db/handlers/dbBuildingHandler.java @@ -165,7 +165,7 @@ public class dbBuildingHandler extends dbHandlerBase { ResultSet rs = preparedStatement.executeQuery(); result = rs.getString("result"); - ; + } catch (SQLException e) { Logger.error(e); @@ -372,30 +372,65 @@ public class dbBuildingHandler extends dbHandlerBase { } public boolean REMOVE_FROM_CONDEMNED_LIST(final long buildingID, long friendID, long guildID, int friendType) { - prepareCallable("DELETE FROM `dyn_building_condemned` WHERE `buildingUID`=? AND `playerUID`=? AND `guildUID` =? AND `friendType` = ?"); - setLong(1, buildingID); - setLong(2, friendID); - setLong(3,guildID); - setInt(4, friendType); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_building_condemned` WHERE `buildingUID`=? AND `playerUID`=? AND `guildUID` =? AND `friendType` = ?")) { + + preparedStatement.setLong(1, buildingID); + preparedStatement.setLong(2, friendID); + preparedStatement.setLong(3, guildID); + preparedStatement.setInt(4, friendType); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } public void CLEAR_FRIENDS_LIST(final long buildingID) { - prepareCallable("DELETE FROM `dyn_building_friends` WHERE `buildingUID`=?"); - setLong(1, buildingID); - executeUpdate(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_building_friends` WHERE `buildingUID`=?")) { + + preparedStatement.setLong(1, buildingID); + preparedStatement.execute(); + + } catch (SQLException e) { + Logger.error(e); + } + } public void CLEAR_CONDEMNED_LIST(final long buildingID) { - prepareCallable("DELETE FROM `dyn_building_condemned` WHERE `buildingUID`=?"); - setLong(1, buildingID); - executeUpdate(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_building_condemned` WHERE `buildingUID`=?")) { + + preparedStatement.setLong(1, buildingID); + preparedStatement.execute(); + + } catch (SQLException e) { + Logger.error(e); + } + } public boolean CLEAR_PATROL(final long buildingID) { - prepareCallable("DELETE FROM `dyn_building_patrol_points` WHERE `buildingUID`=?"); - setLong(1, buildingID); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_building_patrol_points` WHERE `buildingUID`=?")) { + + preparedStatement.setLong(1, buildingID); + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } public void LOAD_ALL_FRIENDS_FOR_BUILDING(Building building) { @@ -403,30 +438,27 @@ public class dbBuildingHandler extends dbHandlerBase { if (building == null) return; - prepareCallable("SELECT * FROM `dyn_building_friends` WHERE `buildingUID` = ?"); - setInt(1,building.getObjectUUID()); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_building_friends` WHERE `buildingUID` = ?")) { - try { - ResultSet rs = executeQuery(); + preparedStatement.setInt(1, building.getObjectUUID()); + ResultSet rs = preparedStatement.executeQuery(); - //shrines cached in rs for easy cache on creation. while (rs.next()) { BuildingFriends friend = new BuildingFriends(rs); - switch(friend.getFriendType()){ - case 7: - building.getFriends().put(friend.getPlayerUID(), friend); - break; - case 8: - case 9: - building.getFriends().put(friend.getGuildUID(), friend); - break; + switch (friend.getFriendType()) { + case 7: + building.getFriends().put(friend.getPlayerUID(), friend); + break; + case 8: + case 9: + building.getFriends().put(friend.getGuildUID(), friend); + break; } } } catch (SQLException e) { - Logger.error("LOAD friends for building: " + e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); + Logger.error(e); } } From 7b9788bfa95aae2d77e3492ff9ba566067d6eb49 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sun, 21 May 2023 08:16:27 -0400 Subject: [PATCH 033/109] Refactor to remove abstraction --- src/engine/db/handlers/dbBuildingHandler.java | 1281 +++++++++-------- 1 file changed, 654 insertions(+), 627 deletions(-) diff --git a/src/engine/db/handlers/dbBuildingHandler.java b/src/engine/db/handlers/dbBuildingHandler.java index e55c35b5..ef564c47 100644 --- a/src/engine/db/handlers/dbBuildingHandler.java +++ b/src/engine/db/handlers/dbBuildingHandler.java @@ -27,813 +27,840 @@ import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; import java.util.HashMap; -import java.util.concurrent.ConcurrentHashMap; public class dbBuildingHandler extends dbHandlerBase { - public dbBuildingHandler() { - this.localClass = Building.class; - this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); - } + public dbBuildingHandler() { + this.localClass = Building.class; + this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); + } - public Building CREATE_BUILDING(int parentZoneID, int OwnerUUID, String name, int meshUUID, - Vector3fImmutable location, float meshScale, int currentHP, - ProtectionState protectionState, int currentGold, int rank, - DateTime upgradeDate, int blueprintUUID, float w, float rotY) { + public Building CREATE_BUILDING(int parentZoneID, int OwnerUUID, String name, int meshUUID, + Vector3fImmutable location, float meshScale, int currentHP, + ProtectionState protectionState, int currentGold, int rank, + DateTime upgradeDate, int blueprintUUID, float w, float rotY) { - Building toCreate = null; + Building toCreate = null; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("CALL `building_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,? ,? ,?, ?);")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL `building_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,? ,? ,?, ?);")) { - preparedStatement.setInt(1, parentZoneID); - preparedStatement.setInt(2, OwnerUUID); - preparedStatement.setString(3, name); - preparedStatement.setInt(4, meshUUID); - preparedStatement.setFloat(5, location.x); - preparedStatement.setFloat(6, location.y); - preparedStatement.setFloat(7, location.z); - preparedStatement.setFloat(8, meshScale); - preparedStatement.setInt(9, currentHP); - preparedStatement.setString(10, protectionState.name()); - preparedStatement.setInt(11, currentGold); - preparedStatement.setInt(12, rank); + preparedStatement.setInt(1, parentZoneID); + preparedStatement.setInt(2, OwnerUUID); + preparedStatement.setString(3, name); + preparedStatement.setInt(4, meshUUID); + preparedStatement.setFloat(5, location.x); + preparedStatement.setFloat(6, location.y); + preparedStatement.setFloat(7, location.z); + preparedStatement.setFloat(8, meshScale); + preparedStatement.setInt(9, currentHP); + preparedStatement.setString(10, protectionState.name()); + preparedStatement.setInt(11, currentGold); + preparedStatement.setInt(12, rank); - if (upgradeDate != null) - preparedStatement.setTimestamp(13, new java.sql.Timestamp(upgradeDate.getMillis())); - else - setNULL(13, java.sql.Types.DATE); + if (upgradeDate != null) + preparedStatement.setTimestamp(13, new java.sql.Timestamp(upgradeDate.getMillis())); + else + setNULL(13, java.sql.Types.DATE); - setInt(14, blueprintUUID); - setFloat(15, w); - setFloat(16, rotY); + setInt(14, blueprintUUID); + setFloat(15, w); + setFloat(16, rotY); - ResultSet rs = preparedStatement.executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); - int objectUUID = (int) rs.getLong("UID"); + int objectUUID = (int) rs.getLong("UID"); - if (objectUUID > 0) - toCreate = GET_BUILDINGBYUUID(objectUUID); + if (objectUUID > 0) + toCreate = GET_BUILDINGBYUUID(objectUUID); - } catch (SQLException e) { - throw new RuntimeException(e); - } + } catch (SQLException e) { + throw new RuntimeException(e); + } - return toCreate; - } + return toCreate; + } - public boolean DELETE_FROM_DATABASE(final Building b) { + public boolean DELETE_FROM_DATABASE(final Building b) { - return removeFromBuildings(b); - } + return removeFromBuildings(b); + } - public ArrayList GET_ALL_BUILDINGS_FOR_ZONE(Zone zone) { + public ArrayList GET_ALL_BUILDINGS_FOR_ZONE(Zone zone) { - ArrayList buildings = new ArrayList<>(); + ArrayList buildings = new ArrayList<>(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_building`.*, `object`.`parent` FROM `object` INNER JOIN `obj_building` ON `obj_building`.`UID` = `object`.`UID` WHERE `object`.`parent` = ?;")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_building`.*, `object`.`parent` FROM `object` INNER JOIN `obj_building` ON `obj_building`.`UID` = `object`.`UID` WHERE `object`.`parent` = ?;")) { - preparedStatement.setLong(1, zone.getObjectUUID()); + preparedStatement.setLong(1, zone.getObjectUUID()); - ResultSet rs = preparedStatement.executeQuery(); - buildings = getObjectsFromRs(rs, 2000); + ResultSet rs = preparedStatement.executeQuery(); + buildings = getObjectsFromRs(rs, 2000); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return buildings; - } + return buildings; + } - public Building GET_BUILDINGBYUUID(int uuid) { + public Building GET_BUILDINGBYUUID(int uuid) { - if (uuid == 0) - return null; + if (uuid == 0) + return null; - Building building = (Building) DbManager.getFromCache(Enum.GameObjectType.Building, uuid); + Building building = (Building) DbManager.getFromCache(Enum.GameObjectType.Building, uuid); - if (building != null) - return building; + if (building != null) + return building; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_building`.*, `object`.`parent` FROM `object` INNER JOIN `obj_building` ON `obj_building`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?;")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_building`.*, `object`.`parent` FROM `object` INNER JOIN `obj_building` ON `obj_building`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?;")) { - preparedStatement.setLong(1, (long) uuid); + preparedStatement.setLong(1, uuid); - ResultSet rs = preparedStatement.executeQuery(); - building = (Building) getObjectFromRs(rs); + ResultSet rs = preparedStatement.executeQuery(); + building = (Building) getObjectFromRs(rs); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return building; - } + return building; + } - public Building GET_BUILDING_BY_MESH(final int meshID) { + public Building GET_BUILDING_BY_MESH(final int meshID) { - Building building = null; + Building building = null; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("CALL building_GETBYMESH(?)")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL building_GETBYMESH(?)")) { - preparedStatement.setInt(1, meshID); + preparedStatement.setInt(1, meshID); - ResultSet rs = preparedStatement.executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); - if (rs.next()) - building = new Building(rs); + if (rs.next()) + building = new Building(rs); - } catch (SQLException e) { - Logger.error("Building", e); - return null; - } - return building; - } + } catch (SQLException e) { + Logger.error("Building", e); + return null; + } + return building; + } - public String SET_PROPERTY(final Building b, String name, Object new_value) { + public String SET_PROPERTY(final Building b, String name, Object new_value) { - String result = ""; + String result = ""; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("CALL building_SETPROP(?,?,?)")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL building_SETPROP(?,?,?)")) { - preparedStatement.setLong(1, b.getObjectUUID()); - preparedStatement.setString(2, name); - preparedStatement.setString(3, String.valueOf(new_value)); + preparedStatement.setLong(1, b.getObjectUUID()); + preparedStatement.setString(2, name); + preparedStatement.setString(3, String.valueOf(new_value)); - ResultSet rs = preparedStatement.executeQuery(); - result = rs.getString("result"); + ResultSet rs = preparedStatement.executeQuery(); + result = rs.getString("result"); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return result; - } + return result; + } - public int MOVE_BUILDING(long buildingID, long parentID, float locX, float locY, float locZ) { + public int MOVE_BUILDING(long buildingID, long parentID, float locX, float locY, float locZ) { - int rowCount; + int rowCount; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `object` INNER JOIN `obj_building` On `object`.`UID` = `obj_building`.`UID` SET `object`.`parent`=?, `obj_building`.`locationX`=?, `obj_building`.`locationY`=?, `obj_building`.`locationZ`=? WHERE `obj_building`.`UID`=?;")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `object` INNER JOIN `obj_building` On `object`.`UID` = `obj_building`.`UID` SET `object`.`parent`=?, `obj_building`.`locationX`=?, `obj_building`.`locationY`=?, `obj_building`.`locationZ`=? WHERE `obj_building`.`UID`=?;")) { - preparedStatement.setLong(1, parentID); - preparedStatement.setFloat(2, locX); - preparedStatement.setFloat(3, locY); - preparedStatement.setFloat(4, locZ); - preparedStatement.setLong(5, buildingID); + preparedStatement.setLong(1, parentID); + preparedStatement.setFloat(2, locX); + preparedStatement.setFloat(3, locY); + preparedStatement.setFloat(4, locZ); + preparedStatement.setLong(5, buildingID); - rowCount = preparedStatement.executeUpdate(); + rowCount = preparedStatement.executeUpdate(); - } catch (SQLException e) { - Logger.error(e); - return 0; - } + } catch (SQLException e) { + Logger.error(e); + return 0; + } - return rowCount; - } + return rowCount; + } - private boolean removeFromBuildings(final Building b) { + private boolean removeFromBuildings(final Building b) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `object` WHERE `UID` = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `object` WHERE `UID` = ?")) { - preparedStatement.setLong(1, b.getObjectUUID()); - preparedStatement.execute(); + preparedStatement.setLong(1, b.getObjectUUID()); + preparedStatement.execute(); - } catch (SQLException e) { - Logger.error(e); - return false; - } + } catch (SQLException e) { + Logger.error(e); + return false; + } - return true; - } + return true; + } - public boolean CHANGE_NAME(Building b, String newName) { + public boolean CHANGE_NAME(Building b, String newName) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_building` SET `name`=? WHERE `UID`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_building` SET `name`=? WHERE `UID`=?")) { - preparedStatement.setString(1, newName); - preparedStatement.setLong(2, b.getObjectUUID()); + preparedStatement.setString(1, newName); + preparedStatement.setLong(2, b.getObjectUUID()); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - return false; - } + } catch (SQLException e) { + Logger.error(e); + return false; + } - } + } - public boolean SET_RESERVE(Building b, int reserveAmount) { + public boolean SET_RESERVE(Building b, int reserveAmount) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_building` SET `reserve`=? WHERE `UID`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_building` SET `reserve`=? WHERE `UID`=?")) { - preparedStatement.setInt(1, reserveAmount); - preparedStatement.setLong(2, b.getObjectUUID()); + preparedStatement.setInt(1, reserveAmount); + preparedStatement.setLong(2, b.getObjectUUID()); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - return false; - } + } catch (SQLException e) { + Logger.error(e); + return false; + } - } + } - //CAS update to rank - public boolean CHANGE_RANK(final long buildingID, int newRank) { + //CAS update to rank + public boolean CHANGE_RANK(final long buildingID, int newRank) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_building` SET `rank`=? WHERE `UID`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_building` SET `rank`=? WHERE `UID`=?")) { - preparedStatement.setInt(1, newRank); - preparedStatement.setLong(2, buildingID); + preparedStatement.setInt(1, newRank); + preparedStatement.setLong(2, buildingID); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - return false; - } + } catch (SQLException e) { + Logger.error(e); + return false; + } - } + } - public boolean UPDATE_BUILDING_HEALTH(final long buildingID, int NewHealth) { + public boolean UPDATE_BUILDING_HEALTH(final long buildingID, int NewHealth) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_building` SET `currentHP`=? WHERE `UID`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_building` SET `currentHP`=? WHERE `UID`=?")) { - preparedStatement.setInt(1, NewHealth); - preparedStatement.setLong(2, buildingID); + preparedStatement.setInt(1, NewHealth); + preparedStatement.setLong(2, buildingID); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - return false; - } + } catch (SQLException e) { + Logger.error(e); + return false; + } - } + } - public boolean UPDATE_BUILDING_ALTITUDE(final long buildingID, float newAltitude) { + public boolean UPDATE_BUILDING_ALTITUDE(final long buildingID, float newAltitude) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_building` SET `locationY`=? WHERE `UID`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_building` SET `locationY`=? WHERE `UID`=?")) { - preparedStatement.setFloat(1, newAltitude); - preparedStatement.setLong(2, buildingID); + preparedStatement.setFloat(1, newAltitude); + preparedStatement.setLong(2, buildingID); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - return false; - } + } catch (SQLException e) { + Logger.error(e); + return false; + } - } + } - public boolean UPDATE_PROTECTIONSTATE(final long buildingUUID, ProtectionState protectionState) { + public boolean UPDATE_PROTECTIONSTATE(final long buildingUUID, ProtectionState protectionState) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_building` SET `protectionState`=? WHERE `UID`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_building` SET `protectionState`=? WHERE `UID`=?")) { - preparedStatement.setString(1, protectionState.name()); - preparedStatement.setLong(2, buildingUUID); + preparedStatement.setString(1, protectionState.name()); + preparedStatement.setLong(2, buildingUUID); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - return false; - } + } catch (SQLException e) { + Logger.error(e); + return false; + } - } + } - public boolean UPDATE_DOOR_LOCK(final int buildingUUID, int doorFlags) { + public boolean UPDATE_DOOR_LOCK(final int buildingUUID, int doorFlags) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE obj_building SET doorState = ? WHERE UID = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE obj_building SET doorState = ? WHERE UID = ?")) { - preparedStatement.setInt(1, doorFlags); - preparedStatement.setInt(2, buildingUUID); + preparedStatement.setInt(1, doorFlags); + preparedStatement.setInt(2, buildingUUID); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - return false; - } + } catch (SQLException e) { + Logger.error(e); + return false; + } - } + } - public boolean ADD_TO_FRIENDS_LIST(final long buildingID, final long friendID, final long guildID, final int friendType) { + public boolean ADD_TO_FRIENDS_LIST(final long buildingID, final long friendID, final long guildID, final int friendType) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_building_friends` (`buildingUID`, `playerUID`,`guildUID`, `friendType`) VALUES (?,?,?,?)")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_building_friends` (`buildingUID`, `playerUID`,`guildUID`, `friendType`) VALUES (?,?,?,?)")) { - preparedStatement.setLong(1, buildingID); - preparedStatement.setLong(2, friendID); - preparedStatement.setLong(3, guildID); - preparedStatement.setInt(4, friendType); + preparedStatement.setLong(1, buildingID); + preparedStatement.setLong(2, friendID); + preparedStatement.setLong(3, guildID); + preparedStatement.setInt(4, friendType); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - return false; - } + } catch (SQLException e) { + Logger.error(e); + return false; + } - } + } - public boolean REMOVE_FROM_FRIENDS_LIST(final long buildingID, long friendID, long guildID, int friendType) { + public boolean REMOVE_FROM_FRIENDS_LIST(final long buildingID, long friendID, long guildID, int friendType) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_building_friends` WHERE `buildingUID`=? AND `playerUID`=? AND `guildUID` =? AND `friendType` = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_building_friends` WHERE `buildingUID`=? AND `playerUID`=? AND `guildUID` =? AND `friendType` = ?")) { - preparedStatement.setLong(1, buildingID); - preparedStatement.setLong(2, friendID); - preparedStatement.setLong(3, guildID); - preparedStatement.setInt(4, friendType); + preparedStatement.setLong(1, buildingID); + preparedStatement.setLong(2, friendID); + preparedStatement.setLong(3, guildID); + preparedStatement.setInt(4, friendType); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - return false; - } + } catch (SQLException e) { + Logger.error(e); + return false; + } - } + } - public boolean REMOVE_FROM_CONDEMNED_LIST(final long buildingID, long friendID, long guildID, int friendType) { + public boolean REMOVE_FROM_CONDEMNED_LIST(final long buildingID, long friendID, long guildID, int friendType) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_building_condemned` WHERE `buildingUID`=? AND `playerUID`=? AND `guildUID` =? AND `friendType` = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_building_condemned` WHERE `buildingUID`=? AND `playerUID`=? AND `guildUID` =? AND `friendType` = ?")) { - preparedStatement.setLong(1, buildingID); - preparedStatement.setLong(2, friendID); - preparedStatement.setLong(3, guildID); - preparedStatement.setInt(4, friendType); + preparedStatement.setLong(1, buildingID); + preparedStatement.setLong(2, friendID); + preparedStatement.setLong(3, guildID); + preparedStatement.setInt(4, friendType); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - return false; - } + } catch (SQLException e) { + Logger.error(e); + return false; + } - } + } - public void CLEAR_FRIENDS_LIST(final long buildingID) { + public void CLEAR_FRIENDS_LIST(final long buildingID) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_building_friends` WHERE `buildingUID`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_building_friends` WHERE `buildingUID`=?")) { - preparedStatement.setLong(1, buildingID); - preparedStatement.execute(); + preparedStatement.setLong(1, buildingID); + preparedStatement.execute(); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - } + } - public void CLEAR_CONDEMNED_LIST(final long buildingID) { + public void CLEAR_CONDEMNED_LIST(final long buildingID) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_building_condemned` WHERE `buildingUID`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_building_condemned` WHERE `buildingUID`=?")) { - preparedStatement.setLong(1, buildingID); - preparedStatement.execute(); + preparedStatement.setLong(1, buildingID); + preparedStatement.execute(); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - } + } - public boolean CLEAR_PATROL(final long buildingID) { + public boolean CLEAR_PATROL(final long buildingID) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_building_patrol_points` WHERE `buildingUID`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_building_patrol_points` WHERE `buildingUID`=?")) { - preparedStatement.setLong(1, buildingID); - return (preparedStatement.executeUpdate() > 0); + preparedStatement.setLong(1, buildingID); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - return false; - } + } catch (SQLException e) { + Logger.error(e); + return false; + } - } + } - public void LOAD_ALL_FRIENDS_FOR_BUILDING(Building building) { + public void LOAD_ALL_FRIENDS_FOR_BUILDING(Building building) { - if (building == null) - return; + if (building == null) + return; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_building_friends` WHERE `buildingUID` = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_building_friends` WHERE `buildingUID` = ?")) { - preparedStatement.setInt(1, building.getObjectUUID()); - ResultSet rs = preparedStatement.executeQuery(); + preparedStatement.setInt(1, building.getObjectUUID()); + ResultSet rs = preparedStatement.executeQuery(); - while (rs.next()) { - BuildingFriends friend = new BuildingFriends(rs); - switch (friend.getFriendType()) { - case 7: - building.getFriends().put(friend.getPlayerUID(), friend); - break; - case 8: - case 9: - building.getFriends().put(friend.getGuildUID(), friend); - break; - } - } + while (rs.next()) { + BuildingFriends friend = new BuildingFriends(rs); + switch (friend.getFriendType()) { + case 7: + building.getFriends().put(friend.getPlayerUID(), friend); + break; + case 8: + case 9: + building.getFriends().put(friend.getGuildUID(), friend); + break; + } + } - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - } + } - public void LOAD_ALL_CONDEMNED_FOR_BUILDING(Building building) { + public void LOAD_ALL_CONDEMNED_FOR_BUILDING(Building building) { - if (building == null) - return; + if (building == null) + return; - prepareCallable("SELECT * FROM `dyn_building_condemned` WHERE `buildingUID` = ?"); - setInt(1,building.getObjectUUID()); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_building_condemned` WHERE `buildingUID` = ?")) { - try { - ResultSet rs = executeQuery(); + preparedStatement.setInt(1, building.getObjectUUID()); + ResultSet rs = preparedStatement.executeQuery(); - //shrines cached in rs for easy cache on creation. - while (rs.next()) { - Condemned condemn = new Condemned(rs); - switch(condemn.getFriendType()){ - case 2: - building.getCondemned().put(condemn.getPlayerUID(), condemn); - break; - case 4: - case 5: - building.getCondemned().put(condemn.getGuildUID(), condemn); - break; - } - } + while (rs.next()) { + Condemned condemned = new Condemned(rs); + switch (condemned.getFriendType()) { + case 2: + building.getCondemned().put(condemned.getPlayerUID(), condemned); + break; + case 4: + case 5: + building.getCondemned().put(condemned.getGuildUID(), condemned); + break; + } + } - } catch (SQLException e) { - Logger.error("LOAD Condemned for building: " + e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); - } + } catch (SQLException e) { + Logger.error(e); + } + } - } + public ArrayList LOAD_PATROL_POINTS(Building building) { - public ArrayList LOAD_PATROL_POINTS(Building building) { - if (building == null) - return null; - ArrayList patrolPoints = new ArrayList<>(); + if (building == null) + return null; + ArrayList patrolPoints = new ArrayList<>(); - prepareCallable("SELECT * FROM `dyn_building_patrol_points` WHERE `buildingUID` = ?"); - setInt(1,building.getObjectUUID()); - - try { - ResultSet rs = executeQuery(); - - //shrines cached in rs for easy cache on creation. - while (rs.next()) { - float x1 = rs.getFloat("patrolX"); - float y1 = rs.getFloat("patrolY"); - float z1 = rs.getFloat("patrolZ"); - Vector3fImmutable patrolPoint = new Vector3fImmutable(x1,y1,z1); - patrolPoints.add(patrolPoint); - } - - } catch (SQLException e) { - Logger.error("LOAD Patrol Points for building: " + e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); - } - - return patrolPoints; - - } - - public boolean ADD_TO_CONDEMNLIST(final long parentUID, final long playerUID, final long guildID, final int friendType) { - prepareCallable("INSERT INTO `dyn_building_condemned` (`buildingUID`, `playerUID`,`guildUID`, `friendType`) VALUES (?,?,?,?)"); - setLong(1, parentUID); - setLong(2, playerUID); - setLong(3, guildID); - setInt(4, friendType); - return (executeUpdate() > 0); - } - - public boolean ADD_TO_PATROL(final long parentUID, final Vector3fImmutable patrolPoint) { - prepareCallable("INSERT INTO `dyn_building_patrol_points` (`buildingUID`, `patrolX`,`patrolY`, `patrolZ`) VALUES (?,?,?,?)"); - setLong(1, parentUID); - setFloat(2, (int)patrolPoint.x); - setFloat(3, (int)patrolPoint.y); - setFloat(4, (int)patrolPoint.z); - return (executeUpdate() > 0); - } - - public HashMap> LOAD_BUILDING_REGIONS() { - - HashMap> regions; - BuildingRegions thisRegions; - - - regions = new HashMap<>(); - int recordsRead = 0; - - prepareCallable("SELECT * FROM static_building_regions"); - - try { - ResultSet rs = executeQuery(); - - while (rs.next()) { - - recordsRead++; - thisRegions = new BuildingRegions(rs); - if (regions.get(thisRegions.getBuildingID()) == null){ - ArrayList regionsList = new ArrayList<>(); - regionsList.add(thisRegions); - regions.put(thisRegions.getBuildingID(), regionsList); - } - else{ - ArrayListregionsList = regions.get(thisRegions.getBuildingID()); - regionsList.add(thisRegions); - regions.put(thisRegions.getBuildingID(), regionsList); - } - } - - Logger.info( "read: " + recordsRead + " cached: " + regions.size()); - - } catch (SQLException e) { - Logger.error(": " + e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); - } - return regions; - } - - public HashMap LOAD_MESH_BOUNDS() { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_building_patrol_points` WHERE `buildingUID` = ?")) { - HashMap meshBoundsMap; - MeshBounds meshBounds; + preparedStatement.setInt(1, building.getObjectUUID()); - meshBoundsMap = new HashMap<>(); - int recordsRead = 0; - prepareCallable("SELECT * FROM static_mesh_bounds"); - - try { - ResultSet rs = executeQuery(); - - while (rs.next()) { - - recordsRead++; - meshBounds = new MeshBounds(rs); - - meshBoundsMap.put(meshBounds.meshID, meshBounds); - - } - - Logger.info( "read: " + recordsRead + " cached: " + meshBoundsMap.size()); - - } catch (SQLException e) { - Logger.error("LoadMeshBounds: " + e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); - } - return meshBoundsMap; - } - - public HashMap> LOAD_ALL_STATIC_COLLIDERS() { - - HashMap> colliders; - StaticColliders thisColliders; - - - colliders = new HashMap<>(); - int recordsRead = 0; - - prepareCallable("SELECT * FROM static_building_colliders"); - - try { - ResultSet rs = executeQuery(); - - while (rs.next()) { - - recordsRead++; - thisColliders = new StaticColliders(rs); - if (colliders.get(thisColliders.getMeshID()) == null){ - ArrayList colliderList = new ArrayList<>(); - colliderList.add(thisColliders); - colliders.put(thisColliders.getMeshID(), colliderList); - } - else{ - ArrayListcolliderList = colliders.get(thisColliders.getMeshID()); - colliderList.add(thisColliders); - colliders.put(thisColliders.getMeshID(), colliderList); - } - - - } - - Logger.info( "read: " + recordsRead + " cached: " + colliders.size()); - - } catch (SQLException e) { - Logger.error("LoadAllBlueprints: " + e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); - } - return colliders; - } - - // This public class inserted here as it's a generic utility function - // with no other good place for it. If you find a good home for it - // feel free to move it. - - - public final DbObjectType GET_UID_ENUM(long object_UID) { - - DbObjectType storedEnum = DbObjectType.INVALID; - String typeString; - - if (object_UID == 0) - return storedEnum; - - // Set up call to stored procedure - prepareCallable("CALL object_UID_ENUM(?)"); - setLong(1, object_UID); - - try { - - // Evaluate database ordinal and return enum - storedEnum = DbObjectType.valueOf(getString("type").toUpperCase()); - - } catch (Exception e) { - storedEnum = DbObjectType.INVALID; - Logger.error("UID_ENUM ", "Orphaned Object? Lookup failed for UID: " + object_UID); - } finally { - closeCallable(); - } - return storedEnum; - } - - public ConcurrentHashMap GET_FRIENDS(final long buildingID) { - ConcurrentHashMap friendsList = new ConcurrentHashMap<>(); - prepareCallable("SELECT * FROM `dyn_building_friends` WHERE `buildingUID`=?"); - setLong(1, buildingID); - try { - ResultSet rs = executeQuery(); - while (rs.next()) { - int friendType = rs.getInt("friendType"); - switch (friendType) { - case 7: - friendsList.put(rs.getInt("playerUID"), 7); - break; - case 8: - friendsList.put(rs.getInt("guildUID"), 8); - break; - case 9: - friendsList.put(rs.getInt("guildUID"), 9); - } - } - - rs.close(); - } catch (SQLException e) { - Logger.error("dbBuildingHandler.GET_FRIENDS_GUILD_IC", e); - } finally { - closeCallable(); - } - return friendsList; - } - - public boolean updateBuildingRank(final Building b, int Rank) { - - prepareCallable("UPDATE `obj_building` SET `rank`=?," - + "`upgradeDate`=?, `meshUUID`=?, `currentHP`=? " - + "WHERE `UID` = ?"); - - setInt(1, Rank); - setNULL(2, java.sql.Types.DATE); - setInt(3, b.getBlueprint().getMeshForRank(Rank)); - setInt(4, b.getBlueprint().getMaxHealth(Rank)); - setInt(5, b.getObjectUUID()); - return (executeUpdate() > 0); - } - - public boolean updateReverseKOS(final Building b, boolean reverse) { - - prepareCallable("UPDATE `obj_building` SET `reverseKOS`=? " - + "WHERE `UID` = ?"); - setBoolean(1, reverse); - setInt(2, b.getObjectUUID()); - return (executeUpdate() > 0); - } + ResultSet rs = preparedStatement.executeQuery(); - public boolean updateActiveCondemn(final Condemned condemn, boolean active) { + while (rs.next()) { + float x1 = rs.getFloat("patrolX"); + float y1 = rs.getFloat("patrolY"); + float z1 = rs.getFloat("patrolZ"); + Vector3fImmutable patrolPoint = new Vector3fImmutable(x1, y1, z1); + patrolPoints.add(patrolPoint); + } - prepareCallable("UPDATE `dyn_building_condemned` SET `active`=? " - + "WHERE`buildingUID` = ? AND `playerUID` = ? AND `guildUID` = ? AND `friendType` = ?"); - setBoolean(1, active); - setInt(2, condemn.getParent()); - setInt(3, condemn.getPlayerUID()); - setInt(4, condemn.getGuildUID()); - setInt(5, condemn.getFriendType()); - return (executeUpdate() > 0); - } + } catch (SQLException e) { + Logger.error(e); + } - public boolean updateBuildingOwner(final Building building, int ownerUUID) { + return patrolPoints; - prepareCallable("UPDATE `obj_building` SET `ownerUUID`=? " - + " WHERE `UID` = ?"); + } - setInt(1, ownerUUID); - setInt(2, building.getObjectUUID()); - return (executeUpdate() > 0); - } + public boolean ADD_TO_CONDEMNLIST(final long parentUID, final long playerUID, final long guildID, final int friendType) { - public boolean updateBuildingUpgradeTime(LocalDateTime upgradeDateTime, Building toUpgrade, int costToUpgrade) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_building_condemned` (`buildingUID`, `playerUID`,`guildUID`, `friendType`) VALUES (?,?,?,?)")) { - prepareCallable("UPDATE obj_building SET upgradeDate=?, currentGold=? " - + "WHERE UID = ?"); + preparedStatement.setLong(1, parentUID); + preparedStatement.setLong(2, playerUID); + preparedStatement.setLong(3, guildID); + preparedStatement.setInt(4, friendType); - if (upgradeDateTime == null) - setNULL(1, java.sql.Types.DATE); - else - setTimeStamp(1, upgradeDateTime.atZone(ZoneId.systemDefault()) - .toInstant().toEpochMilli()); + return (preparedStatement.executeUpdate() > 0); - setInt(2, toUpgrade.getStrongboxValue() - costToUpgrade); - setInt(3, toUpgrade.getObjectUUID()); - return (executeUpdate() > 0); - } - - public boolean updateMaintDate(Building building) { - - prepareCallable("UPDATE obj_building SET maintDate=? " - + "WHERE UID = ?"); - - if (building.maintDateTime == null) - setNULL(1, java.sql.Types.DATE); - else - setLocalDateTime(1, building.maintDateTime); + } catch (SQLException e) { + Logger.error(e); + return false; + } - setInt(2, building.getObjectUUID()); + } - return (executeUpdate() > 0); - } + public boolean ADD_TO_PATROL(final long parentUID, final Vector3fImmutable patrolPoint) { - public boolean addTaxes(Building building, TaxType taxType, int amount, boolean enforceKOS){ - prepareCallable("UPDATE obj_building SET taxType=?, taxAmount = ?, enforceKOS = ? " - + "WHERE UID = ?"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_building_patrol_points` (`buildingUID`, `patrolX`,`patrolY`, `patrolZ`) VALUES (?,?,?,?)")) { - setString(1, taxType.name()); - setInt(2, amount); - setBoolean(3, enforceKOS); - setInt(4, building.getObjectUUID()); + preparedStatement.setLong(1, parentUID); + preparedStatement.setFloat(2, (int) patrolPoint.x); + preparedStatement.setFloat(3, (int) patrolPoint.y); + preparedStatement.setFloat(4, (int) patrolPoint.z); - return (executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } + } catch (SQLException e) { + Logger.error(e); + return false; + } - public boolean removeTaxes(Building building){ - prepareCallable("UPDATE obj_building SET taxType=?, taxAmount = ?, enforceKOS = ?, taxDate = ? " - + "WHERE UID = ?"); + } - setString(1, TaxType.NONE.name()); - setInt(2, 0); - setBoolean(3, false); - setNULL(4, java.sql.Types.DATE); - setInt(5, building.getObjectUUID()); + public HashMap> LOAD_BUILDING_REGIONS() { + HashMap> regionList = new HashMap<>(); + BuildingRegions buildingRegions; + int recordsRead = 0; + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_building_regions")) { - return (executeUpdate() > 0); + ResultSet rs = preparedStatement.executeQuery(); - } + while (rs.next()) { - public boolean acceptTaxes(Building building) { + recordsRead++; + buildingRegions = new BuildingRegions(rs); - prepareCallable("UPDATE obj_building SET taxDate=? " - + "WHERE UID = ?"); + if (regionList.get(buildingRegions.getBuildingID()) == null) { + ArrayList regionsList = new ArrayList<>(); + regionsList.add(buildingRegions); + regionList.put(buildingRegions.getBuildingID(), regionsList); + } else { + ArrayList regionsList = regionList.get(buildingRegions.getBuildingID()); + regionsList.add(buildingRegions); + regionList.put(buildingRegions.getBuildingID(), regionsList); + } + } - setTimeStamp(1, DateTime.now().plusDays(7).getMillis()); - setInt(2, building.getObjectUUID()); + } catch (SQLException e) { + Logger.error(e); + return null; + } - return (executeUpdate() > 0); - } + Logger.info("read: " + recordsRead + " cached: " + regionList.size()); + return regionList; + } + public HashMap LOAD_MESH_BOUNDS() { + HashMap meshBoundsMap = new HashMap<>(); + MeshBounds meshBounds; + int recordsRead = 0; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_mesh_bounds")) { + + ResultSet rs = preparedStatement.executeQuery(); + + while (rs.next()) { + recordsRead++; + meshBounds = new MeshBounds(rs); + meshBoundsMap.put(meshBounds.meshID, meshBounds); + } + + } catch (SQLException e) { + Logger.error(e); + } + + Logger.info("read: " + recordsRead + " cached: " + meshBoundsMap.size()); + return meshBoundsMap; + } + + public HashMap> LOAD_ALL_STATIC_COLLIDERS() { + + HashMap> colliders = new HashMap<>(); + StaticColliders thisColliders; + int recordsRead = 0; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_building_colliders")) { + + ResultSet rs = preparedStatement.executeQuery(); + + while (rs.next()) { + + recordsRead++; + thisColliders = new StaticColliders(rs); + + if (colliders.get(thisColliders.getMeshID()) == null) { + ArrayList colliderList = new ArrayList<>(); + colliderList.add(thisColliders); + colliders.put(thisColliders.getMeshID(), colliderList); + } else { + ArrayList colliderList = colliders.get(thisColliders.getMeshID()); + colliderList.add(thisColliders); + colliders.put(thisColliders.getMeshID(), colliderList); + } + } + + } catch (SQLException e) { + Logger.error(e); + } + + Logger.info("read: " + recordsRead + " cached: " + colliders.size()); + return colliders; + } + + // This public class inserted here as it's a generic utility function + // with no other good place for it. If you find a good home for it + // feel free to move it. - + + public final DbObjectType GET_UID_ENUM(long object_UID) { + + DbObjectType storedEnum = DbObjectType.INVALID; + + if (object_UID == 0) + return storedEnum; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `type` FROM `object` WHERE `object`.`UID` = n LIMIT 1;")) { + + preparedStatement.setLong(1, object_UID); + + ResultSet rs = preparedStatement.executeQuery(); + + if (rs.next()) + storedEnum = DbObjectType.valueOf(getString("type").toUpperCase()); + + } catch (SQLException e) { + Logger.error("Building", e); + return DbObjectType.INVALID; + } + + return storedEnum; + } + + public boolean updateBuildingRank(final Building b, int Rank) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_building` SET `rank`=?," + + "`upgradeDate`=?, `meshUUID`=?, `currentHP`=? " + + "WHERE `UID` = ?")) { + + preparedStatement.setInt(1, Rank); + preparedStatement.setNull(2, java.sql.Types.DATE); + preparedStatement.setInt(3, b.getBlueprint().getMeshForRank(Rank)); + preparedStatement.setInt(4, b.getBlueprint().getMaxHealth(Rank)); + preparedStatement.setInt(5, b.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } + + public boolean updateReverseKOS(final Building b, boolean reverse) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_building` SET `reverseKOS`=? WHERE `UID` = ?")) { + + preparedStatement.setBoolean(1, reverse); + preparedStatement.setInt(2, b.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + + } + + public boolean updateActiveCondemn(final Condemned condemn, boolean active) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_building_condemned` SET `active`=? " + + "WHERE`buildingUID` = ? AND `playerUID` = ? AND `guildUID` = ? AND `friendType` = ?")) { + + preparedStatement.setBoolean(1, active); + preparedStatement.setInt(2, condemn.getParent()); + preparedStatement.setInt(3, condemn.getPlayerUID()); + preparedStatement.setInt(4, condemn.getGuildUID()); + preparedStatement.setInt(5, condemn.getFriendType()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + + } + + public boolean updateBuildingOwner(final Building building, int ownerUUID) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_building` SET `ownerUUID`=? " + + " WHERE `UID` = ?")) { + + preparedStatement.setInt(1, ownerUUID); + preparedStatement.setInt(2, building.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + + } + + public boolean updateBuildingUpgradeTime(LocalDateTime upgradeDateTime, Building toUpgrade, int costToUpgrade) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE obj_building SET upgradeDate=?, currentGold=? " + + "WHERE UID = ?")) { + + if (upgradeDateTime == null) + preparedStatement.setNull(1, java.sql.Types.DATE); + else + preparedStatement.setTimestamp(1, new java.sql.Timestamp(upgradeDateTime.atZone(ZoneId.systemDefault()) + .toInstant().toEpochMilli())); + + preparedStatement.setInt(2, toUpgrade.getStrongboxValue() - costToUpgrade); + preparedStatement.setInt(3, toUpgrade.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } + + public boolean updateMaintDate(Building building) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE obj_building SET maintDate=? " + + "WHERE UID = ?")) { + + if (building.maintDateTime == null) + preparedStatement.setNull(1, java.sql.Types.DATE); + else + preparedStatement.setTimestamp(1, new java.sql.Timestamp(building.maintDateTime.atZone(ZoneId.systemDefault()) + .toInstant().toEpochMilli())); + preparedStatement.setInt(2, building.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } + + public boolean addTaxes(Building building, TaxType taxType, int amount, boolean enforceKOS) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE obj_building SET taxType=?, taxAmount = ?, enforceKOS = ? " + + "WHERE UID = ?")) { + + preparedStatement.setString(1, taxType.name()); + preparedStatement.setInt(2, amount); + preparedStatement.setBoolean(3, enforceKOS); + preparedStatement.setInt(4, building.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + + } + + public boolean removeTaxes(Building building) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE obj_building SET taxType=?, taxAmount = ?, enforceKOS = ?, taxDate = ? " + + "WHERE UID = ?")) { + + preparedStatement.setString(1, TaxType.NONE.name()); + preparedStatement.setInt(2, 0); + preparedStatement.setBoolean(3, false); + preparedStatement.setNull(4, java.sql.Types.DATE); + preparedStatement.setInt(5, building.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } + + public boolean acceptTaxes(Building building) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE obj_building SET taxDate=? " + + "WHERE UID = ?")) { + + preparedStatement.setTimestamp(1, new java.sql.Timestamp(DateTime.now().plusDays(7).getMillis())); + preparedStatement.setInt(2, building.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } } From e4ef0021e80e76d411d41a9746076d7d0ba333ee Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sun, 21 May 2023 08:36:39 -0400 Subject: [PATCH 034/109] Refactor to remove abstraction --- .../handlers/dbBuildingLocationHandler.java | 30 ++++-- .../db/handlers/dbHeightMapHandler.java | 48 ++++----- src/engine/db/handlers/dbItemBaseHandler.java | 100 ++++++++---------- 3 files changed, 88 insertions(+), 90 deletions(-) diff --git a/src/engine/db/handlers/dbBuildingLocationHandler.java b/src/engine/db/handlers/dbBuildingLocationHandler.java index 7a24bfcc..bd89fad0 100644 --- a/src/engine/db/handlers/dbBuildingLocationHandler.java +++ b/src/engine/db/handlers/dbBuildingLocationHandler.java @@ -9,8 +9,14 @@ package engine.db.handlers; +import engine.gameManager.DbManager; import engine.objects.BuildingLocation; +import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.ArrayList; public class dbBuildingLocationHandler extends dbHandlerBase { @@ -21,11 +27,23 @@ public class dbBuildingLocationHandler extends dbHandlerBase { } public ArrayList LOAD_BUILDING_LOCATIONS() { - prepareCallable("select * from static_building_location " + - "where type = 6 or type = 8 " + - "GROUP BY buildingID, slot " + - "ORDER BY buildingID, slot ASC;"); - return getObjectList(); - } + ArrayList buildingLocations = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("select * from static_building_location " + + "where type = 6 or type = 8 " + + "GROUP BY buildingID, slot " + + "ORDER BY buildingID, slot ASC;")) { + + ResultSet rs = preparedStatement.executeQuery(); + buildingLocations = getObjectsFromRs(rs, 20); + + } catch (SQLException e) { + Logger.error(e); + return buildingLocations; + } + + return buildingLocations; + } } diff --git a/src/engine/db/handlers/dbHeightMapHandler.java b/src/engine/db/handlers/dbHeightMapHandler.java index 1ea5d54c..eec0bfbc 100644 --- a/src/engine/db/handlers/dbHeightMapHandler.java +++ b/src/engine/db/handlers/dbHeightMapHandler.java @@ -1,47 +1,43 @@ package engine.db.handlers; import engine.InterestManagement.HeightMap; +import engine.gameManager.DbManager; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class dbHeightMapHandler extends dbHandlerBase { - public dbHeightMapHandler() { + public dbHeightMapHandler() { - } + } - public void LOAD_ALL_HEIGHTMAPS() { + public void LOAD_ALL_HEIGHTMAPS() { - HeightMap thisHeightmap; + HeightMap thisHeightmap; + HeightMap.heightMapsCreated = 0; - int recordsRead = 0; - int worthlessDupes = 0; + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_zone_heightmap INNER JOIN static_zone_size ON static_zone_size.loadNum = static_zone_heightmap.zoneLoadID")) { - HeightMap.heightMapsCreated = 0; + ResultSet rs = preparedStatement.executeQuery(); - prepareCallable("SELECT * FROM static_zone_heightmap INNER JOIN static_zone_size ON static_zone_size.loadNum = static_zone_heightmap.zoneLoadID"); + while (rs.next()) { + thisHeightmap = new HeightMap(rs); - try { - ResultSet rs = executeQuery(); + if (thisHeightmap.getHeightmapImage() == null) { + Logger.info("Imagemap for " + thisHeightmap.getHeightMapID() + " was null"); + continue; + } + } - while (rs.next()) { - - recordsRead++; - thisHeightmap = new HeightMap(rs); - - if (thisHeightmap.getHeightmapImage() == null) { - Logger.info( "Imagemap for " + thisHeightmap.getHeightMapID() + " was null"); - continue; - } - } - } catch (SQLException e) { - Logger.error("LoadAllHeightMaps: " + e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); - } - } + } catch (SQLException e) { + Logger.error(e); + } + } } diff --git a/src/engine/db/handlers/dbItemBaseHandler.java b/src/engine/db/handlers/dbItemBaseHandler.java index 0b6911d6..a2f6b793 100644 --- a/src/engine/db/handlers/dbItemBaseHandler.java +++ b/src/engine/db/handlers/dbItemBaseHandler.java @@ -9,10 +9,13 @@ package engine.db.handlers; +import engine.gameManager.DbManager; import engine.objects.BootySetEntry; import engine.objects.ItemBase; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; @@ -26,23 +29,20 @@ public class dbItemBaseHandler extends dbHandlerBase { public void LOAD_BAKEDINSTATS(ItemBase itemBase) { - try { - prepareCallable("SELECT * FROM `static_item_bakedinstat` WHERE `itemID` = ?"); - setInt(1, itemBase.getUUID()); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_item_bakedinstat` WHERE `itemID` = ?")) { - ResultSet rs = executeQuery(); + preparedStatement.setInt(1, itemBase.getUUID()); + ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { - if (rs.getBoolean("fromUse")) itemBase.getUsedStats().put(rs.getInt("token"), rs.getInt("numTrains")); else itemBase.getBakedInStats().put(rs.getInt("token"), rs.getInt("numTrains")); } } catch (SQLException e) { - Logger.error( e.toString()); - } finally { - closeCallable(); + Logger.error(e); } } @@ -50,27 +50,24 @@ public class dbItemBaseHandler extends dbHandlerBase { ArrayList tempList = new ArrayList<>(); ArrayList tempListOff = new ArrayList<>(); - try { - prepareCallable("SELECT * FROM `static_itembase_animations` WHERE `itemBaseUUID` = ?"); - setInt(1, itemBase.getUUID()); - ResultSet rs = executeQuery(); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_itembase_animations` WHERE `itemBaseUUID` = ?")) { + + preparedStatement.setInt(1, itemBase.getUUID()); + ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { int animation = rs.getInt("animation"); - boolean rightHand = rs.getBoolean("rightHand"); if (rightHand) tempList.add(animation); else tempListOff.add(animation); - } } catch (SQLException e) { - Logger.error( e.toString()); - } finally { - closeCallable(); + Logger.error(e); } itemBase.setAnimations(tempList); @@ -80,44 +77,37 @@ public class dbItemBaseHandler extends dbHandlerBase { public void LOAD_ALL_ITEMBASES() { ItemBase itemBase; - int recordsRead = 0; - prepareCallable("SELECT * FROM static_itembase"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_itembase")) { - try { - ResultSet rs = executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { - recordsRead++; itemBase = new ItemBase(rs); - - // Add ItemBase to internal cache - ItemBase.addToCache(itemBase); } - Logger.info( "read: " + recordsRead + "cached: " + ItemBase.getUUIDCache().size()); - } catch (SQLException e) { - Logger.error( e.toString()); - } finally { - closeCallable(); + Logger.error(e); } + + Logger.info("read: " + recordsRead + "cached: " + ItemBase.getUUIDCache().size()); } public HashMap> LOAD_RUNES_FOR_NPC_AND_MOBS() { HashMap> runeSets = new HashMap<>(); - int runeSetID; + int runeSetID; int runeBaseID; int recordsRead = 0; - prepareCallable("SELECT * FROM static_npc_runeSet"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_npc_runeSet")) { - try { - ResultSet rs = executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { @@ -126,25 +116,23 @@ public class dbItemBaseHandler extends dbHandlerBase { runeSetID = rs.getInt("runeSet"); runeBaseID = rs.getInt("runeBase"); - if (runeSets.get(runeSetID) == null){ + if (runeSets.get(runeSetID) == null) { ArrayList runeList = new ArrayList<>(); runeList.add(runeBaseID); runeSets.put(runeSetID, runeList); - } - else{ - ArrayListruneList = runeSets.get(runeSetID); + } else { + ArrayList runeList = runeSets.get(runeSetID); runeList.add(runeSetID); runeSets.put(runeSetID, runeList); } } - Logger.info("read: " + recordsRead + " cached: " + runeSets.size()); - } catch (SQLException e) { - Logger.error( e.toString()); - } finally { - closeCallable(); + Logger.error(e); + return runeSets; } + + Logger.info("read: " + recordsRead + " cached: " + runeSets.size()); return runeSets; } @@ -152,14 +140,13 @@ public class dbItemBaseHandler extends dbHandlerBase { HashMap> bootySets = new HashMap<>(); BootySetEntry bootySetEntry; - int bootySetID; - + int bootySetID; int recordsRead = 0; - prepareCallable("SELECT * FROM static_npc_bootySet"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_npc_bootySet")) { - try { - ResultSet rs = executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { @@ -168,25 +155,22 @@ public class dbItemBaseHandler extends dbHandlerBase { bootySetID = rs.getInt("bootySet"); bootySetEntry = new BootySetEntry(rs); - if (bootySets.get(bootySetID) == null){ + if (bootySets.get(bootySetID) == null) { ArrayList bootyList = new ArrayList<>(); bootyList.add(bootySetEntry); bootySets.put(bootySetID, bootyList); - } - else{ - ArrayListbootyList = bootySets.get(bootySetID); + } else { + ArrayList bootyList = bootySets.get(bootySetID); bootyList.add(bootySetEntry); bootySets.put(bootySetID, bootyList); } } - - Logger.info("read: " + recordsRead + " cached: " + bootySets.size()); - } catch (SQLException e) { - Logger.error( e.toString()); - } finally { - closeCallable(); + Logger.error(e); + return bootySets; } + + Logger.info("read: " + recordsRead + " cached: " + bootySets.size()); return bootySets; } } From ea2140559bf129b1348ea7fb390f24a94ec7882f Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sun, 21 May 2023 08:39:19 -0400 Subject: [PATCH 035/109] Bonus Code removed. --- src/engine/db/handlers/dbItemHandler.java | 113 +--------------------- 1 file changed, 3 insertions(+), 110 deletions(-) diff --git a/src/engine/db/handlers/dbItemHandler.java b/src/engine/db/handlers/dbItemHandler.java index b473a75e..ab9c9902 100644 --- a/src/engine/db/handlers/dbItemHandler.java +++ b/src/engine/db/handlers/dbItemHandler.java @@ -11,9 +11,9 @@ package engine.db.handlers; import engine.Enum.ItemContainerType; import engine.Enum.ItemType; -import engine.Enum.OwnerType; -import engine.objects.*; -import org.pmw.tinylog.Logger; +import engine.objects.AbstractCharacter; +import engine.objects.CharacterItemManager; +import engine.objects.Item; import java.util.ArrayList; import java.util.HashSet; @@ -128,15 +128,6 @@ public class dbItemHandler extends dbHandlerBase { return (Item) getObjectSingle(id); } - public Item GET_GOLD_FOR_PLAYER(final int playerID, final int goldID, int worldID) { - prepareCallable("SELECT `obj_item`.*, `object`.`parent`, `object`.`type` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE `object`.`parent`=? AND `obj_item`.`item_itembaseID`=?;"); - setInt(1, playerID); - setInt(2, goldID); - int objectUUID = (int) getUUID(); - return (Item) getObjectSingle(objectUUID); - - } - public ArrayList GET_ITEMS_FOR_ACCOUNT(final int accountId) { prepareCallable("SELECT `obj_item`.*, `object`.`parent`, `object`.`type` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE `object`.`parent`=?;"); setLong(1, (long) accountId); @@ -155,13 +146,6 @@ public class dbItemHandler extends dbHandlerBase { return getLargeObjectList(); } - public ArrayList GET_ITEMS_FOR_PLAYER_AND_ACCOUNT(final int playerID, final int accountID) { - prepareCallable("SELECT `obj_item`.*, `object`.`parent`, `object`.`type` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE (`object`.`parent`=? OR `object`.`parent`=?)"); - setLong(1, (long) playerID); - setLong(2, (long) accountID); - return getLargeObjectList(); - } - public boolean MOVE_GOLD(final Item from, final Item to, final int amt) { int newFromAmt = from.getNumOfItems() - amt; int newToAmt = to.getNumOfItems() + amt; @@ -192,37 +176,12 @@ public class dbItemHandler extends dbHandlerBase { return worked; } - public Item PURCHASE_ITEM_FROM_VENDOR(final PlayerCharacter pc, final ItemBase ib) { - Item item = null; - byte charges = 0; - charges = (byte) ib.getNumCharges(); - short durability = (short) ib.getDurability(); - - Item temp = new Item(ib, pc.getObjectUUID(), - OwnerType.PlayerCharacter, charges, charges, durability, durability, - true, false,ItemContainerType.INVENTORY, (byte) 0, - new ArrayList<>(),""); - try { - item = this.ADD_ITEM(temp); - } catch (Exception e) { - Logger.error(e); - } - return item; - } - public HashSet GET_ITEMS_FOR_VENDOR(final int vendorID) { prepareCallable("SELECT ID FROM static_itembase WHERE vendorType = ?"); setInt(1, vendorID); return getIntegerList(1); } - public ArrayList GET_ITEMS_FOR_VENDOR_FORGING(final int npcID) { - prepareCallable("SELECT `obj_item`.*, `object`.`parent` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE `object`.`parent`=? AND `obj_item`.`item_container` =?"); - setLong(1, (long) npcID); - setString(2, "forge"); - return getObjectList(); - } - public String SET_PROPERTY(final Item i, String name, Object new_value) { prepareCallable("CALL item_SETPROP(?,?,?)"); setLong(1, (long) i.getObjectUUID()); @@ -284,33 +243,6 @@ public class dbItemHandler extends dbHandlerBase { } - //Update an item except ownership - public boolean UPDATE_DATABASE(final Item item) { - prepareCallable("UPDATE `obj_item` SET `item_itembaseID`=?, `item_chargesRemaining`=?, `item_durabilityCurrent`=?, `item_durabilityMax`=?, `item_numberOfItems`=? WHERE `UID`=?"); - setInt(1, item.getItemBaseID()); - setInt(2, item.getChargesRemaining()); - setInt(3, item.getDurabilityCurrent()); - setInt(4, item.getDurabilityMax()); - setInt(5, item.getNumOfItems()); - setLong(6, (long) item.getObjectUUID()); - return (executeUpdate() != 0); - } - - public boolean UPDATE_ROLL_COMPLETE(final Item item) { - prepareCallable("UPDATE `obj_item` SET `item_container` = ?, `item_dateToUpgrade` = ? WHERE `UID` = ?"); - setString(1, "forge"); - setLong(2, 0L); - setLong(3, (long) item.getObjectUUID()); - return (executeUpdate() != 0); - } - - public boolean SET_DATE_TO_UPGRADE(final Item item, long date) { - prepareCallable("UPDATE `obj_item` SET `item_dateToUPGRADE` = ? WHERE `UID` = ?"); - setLong(1, date); - setLong(2, (long) item.getObjectUUID()); - return (executeUpdate() != 0); - } - public boolean UPDATE_FORGE_TO_INVENTORY(final Item item) { prepareCallable("UPDATE `obj_item` SET `item_container` = ? WHERE `UID` = ? AND `item_container` = 'forge';"); setString(1, "inventory"); @@ -346,37 +278,6 @@ public class dbItemHandler extends dbHandlerBase { return (executeUpdate() != 0); } - /** - * Attempts to update the value of two Gold items simultaneously. - * - * @param value New gold quantity for this item - * @param otherGold Other Gold item being modified - * @param valueOtherGold New quantity of gold for other item - * @return True on success - */ - public boolean UPDATE_GOLD(Item gold, int value, Item otherGold, int valueOtherGold) { - - if (gold.getItemBase().getType().equals(ItemType.GOLD) == false) - return false; - - if (otherGold.getItemBase().getType().equals(ItemType.GOLD) == false) - return false; - - int firstOld = gold.getNumOfItems(); - int secondOld = gold.getNumOfItems(); - - prepareCallable("UPDATE `obj_item` SET `item_numberOfItems` = CASE WHEN `UID`=? AND `item_numberOfItems`=? THEN ? WHEN `UID`=? AND `item_numberOfItems`=? THEN ? END WHERE `UID` IN (?, ?);"); - setLong(1, (long) gold.getObjectUUID()); - setInt(2, firstOld); - setInt(3, value); - setLong(4, (long) otherGold.getObjectUUID()); - setInt(5, secondOld); - setInt(6, valueOtherGold); - setLong(7, (long) gold.getObjectUUID()); - setLong(8, (long) otherGold.getObjectUUID()); - return (executeUpdate() != 0); - } - public boolean UPDATE_REMAINING_CHARGES(final Item item) { prepareCallable("UPDATE `obj_item` SET `item_chargesRemaining` = ? WHERE `UID` = ?"); setInt(1, item.getChargesRemaining()); @@ -407,12 +308,4 @@ public class dbItemHandler extends dbHandlerBase { return (executeUpdate() != 0); } - public boolean UPDATE_FLAGS(Item item, int flags) { - prepareCallable("UPDATE `obj_item` SET `item_flags`=? WHERE `UID` = ?"); - setInt(1, flags); - setLong(2, (long) item.getObjectUUID()); - return (executeUpdate() != 0); - } - - } From a70c981b47cb1040787dc6404e13f36166e0e90a Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sun, 21 May 2023 08:57:53 -0400 Subject: [PATCH 036/109] Refactor to remove abstraction. --- src/engine/db/handlers/dbItemHandler.java | 146 ++++++++++++++-------- 1 file changed, 95 insertions(+), 51 deletions(-) diff --git a/src/engine/db/handlers/dbItemHandler.java b/src/engine/db/handlers/dbItemHandler.java index ab9c9902..5245b77d 100644 --- a/src/engine/db/handlers/dbItemHandler.java +++ b/src/engine/db/handlers/dbItemHandler.java @@ -11,10 +11,16 @@ package engine.db.handlers; import engine.Enum.ItemContainerType; import engine.Enum.ItemType; +import engine.gameManager.DbManager; import engine.objects.AbstractCharacter; import engine.objects.CharacterItemManager; import engine.objects.Item; +import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.ArrayList; import java.util.HashSet; @@ -27,52 +33,77 @@ public class dbItemHandler extends dbHandlerBase { } public Item ADD_ITEM(Item toAdd) { - prepareCallable("CALL `item_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?,?);"); - setInt(1, toAdd.getOwnerID()); - setInt(2, toAdd.getItemBaseID()); - setInt(3, toAdd.getChargesRemaining()); - setInt(4, toAdd.getDurabilityCurrent()); - setInt(5, toAdd.getDurabilityMax()); - if (toAdd.getNumOfItems() < 1) - setInt(6, 1); - else - setInt(6, toAdd.getNumOfItems()); - switch (toAdd.containerType) { - case INVENTORY: - setString(7, "inventory"); - break; - case EQUIPPED: - setString(7, "equip"); - break; - case BANK: - setString(7, "bank"); - break; - case VAULT: - setString(7, "vault"); - break; - case FORGE: - setString(7, "forge"); - break; + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL `item_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?,?);")) { + + preparedStatement.setInt(1, toAdd.getOwnerID()); + preparedStatement.setInt(2, toAdd.getItemBaseID()); + preparedStatement.setInt(3, toAdd.getChargesRemaining()); + preparedStatement.setInt(4, toAdd.getDurabilityCurrent()); + preparedStatement.setInt(5, toAdd.getDurabilityMax()); + + if (toAdd.getNumOfItems() < 1) + preparedStatement.setInt(6, 1); + else + preparedStatement.setInt(6, toAdd.getNumOfItems()); + + switch (toAdd.containerType) { + case INVENTORY: + preparedStatement.setString(7, "inventory"); + break; + case EQUIPPED: + preparedStatement.setString(7, "equip"); + break; + case BANK: + preparedStatement.setString(7, "bank"); + break; + case VAULT: + preparedStatement.setString(7, "vault"); + break; + case FORGE: + preparedStatement.setString(7, "forge"); + break; default: - setString(7, "none"); //Shouldn't be here + preparedStatement.setString(7, "none"); //Shouldn't be here break; - } + } + + preparedStatement.setByte(8, toAdd.getEquipSlot()); + preparedStatement.setInt(9, toAdd.getFlags()); + preparedStatement.setString(10, toAdd.getCustomName()); - setByte(8, toAdd.getEquipSlot()); - setInt(9, toAdd.getFlags()); - setString(10, toAdd.getCustomName()); - int objectUUID = (int) getUUID(); + ResultSet rs = preparedStatement.executeQuery(); + + int objectUUID = (int) rs.getLong("UID"); + + if (objectUUID > 0) + return GET_ITEM(objectUUID); + + } catch (SQLException e) { + Logger.error(e); + } - if (objectUUID > 0) - return GET_ITEM(objectUUID); return null; } public String GET_OWNER(int ownerID) { - prepareCallable("SELECT `type` FROM `object` WHERE `UID`=?"); - setLong(1, (long) ownerID); - return getString("type"); + + String ownerType = ""; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `type` FROM `object` WHERE `UID`=?")) { + + preparedStatement.setInt(1, ownerID); + + ResultSet rs = preparedStatement.executeQuery(); + ownerType = rs.getString("type"); + + } catch (SQLException e) { + Logger.error(e); + } + + return ownerType; } public boolean DO_TRADE(HashSet from1, HashSet from2, @@ -81,35 +112,48 @@ public class dbItemHandler extends dbHandlerBase { AbstractCharacter ac1 = man1.getOwner(); AbstractCharacter ac2 = man2.getOwner(); + if (ac1 == null || ac2 == null || inventoryGold1 == null || inventoryGold2 == null) return false; - prepareCallable("CALL `item_TRADE`(?, ?, ?, ?, ?, ?, ?, ?)"); - setString(1, formatTradeString(from1)); - setLong(2, (long) ac1.getObjectUUID()); - setString(3, formatTradeString(from2)); - setLong(4, (long) ac2.getObjectUUID()); - setInt(5, goldFrom1); - setLong(6, (long) inventoryGold1.getObjectUUID()); - setInt(7, goldFrom2); - setLong(8, (long) inventoryGold2.getObjectUUID()); - return worked(); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL `item_TRADE`(?, ?, ?, ?, ?, ?, ?, ?)")) { + + preparedStatement.setString(1, formatTradeString(from1)); + preparedStatement.setLong(2, (long) ac1.getObjectUUID()); + preparedStatement.setString(3, formatTradeString(from2)); + preparedStatement.setLong(4, (long) ac2.getObjectUUID()); + preparedStatement.setInt(5, goldFrom1); + preparedStatement.setLong(6, (long) inventoryGold1.getObjectUUID()); + preparedStatement.setInt(7, goldFrom2); + preparedStatement.setLong(8, (long) inventoryGold2.getObjectUUID()); + + ResultSet rs = preparedStatement.executeQuery(); + + return rs.getBoolean("result"); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } private static String formatTradeString(HashSet list) { int size = list.size(); String ret = ""; + if (size == 0) return ret; + boolean start = true; + for (int i : list) { - if (start){ + if (start) { ret += i; start = false; - } - else - ret += "," + i; + } else + ret += "," + i; } return ret; } From 6be3ca41f8ec9cd1519fb5f5ca887a900a9e1578 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sun, 21 May 2023 14:39:57 -0400 Subject: [PATCH 037/109] Refactor to remove abstraction. --- src/engine/db/handlers/dbItemHandler.java | 386 +++++++++++++++------- 1 file changed, 275 insertions(+), 111 deletions(-) diff --git a/src/engine/db/handlers/dbItemHandler.java b/src/engine/db/handlers/dbItemHandler.java index 5245b77d..e57ed854 100644 --- a/src/engine/db/handlers/dbItemHandler.java +++ b/src/engine/db/handlers/dbItemHandler.java @@ -89,18 +89,19 @@ public class dbItemHandler extends dbHandlerBase { public String GET_OWNER(int ownerID) { - String ownerType = ""; + String ownerType; try (Connection connection = DbManager.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement("SELECT `type` FROM `object` WHERE `UID`=?")) { preparedStatement.setInt(1, ownerID); - ResultSet rs = preparedStatement.executeQuery(); + ownerType = rs.getString("type"); } catch (SQLException e) { Logger.error(e); + return ""; } return ownerType; @@ -112,6 +113,7 @@ public class dbItemHandler extends dbHandlerBase { AbstractCharacter ac1 = man1.getOwner(); AbstractCharacter ac2 = man2.getOwner(); + boolean worked = false; if (ac1 == null || ac2 == null || inventoryGold1 == null || inventoryGold2 == null) return false; @@ -130,12 +132,14 @@ public class dbItemHandler extends dbHandlerBase { ResultSet rs = preparedStatement.executeQuery(); - return rs.getBoolean("result"); + if (rs.next()) + worked = rs.getBoolean("result"); } catch (SQLException e) { Logger.error(e); return false; } + return worked; } private static String formatTradeString(HashSet list) { @@ -159,139 +163,254 @@ public class dbItemHandler extends dbHandlerBase { } public ArrayList GET_EQUIPPED_ITEMS(final int targetId) { - prepareCallable("SELECT `obj_item`.*, `object`.`parent`, `object`.`type` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE `object`.`parent`=? && `obj_item`.`item_container`='equip';"); - setLong(1, (long) targetId); - return getObjectList(); + + ArrayList itemList; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_item`.*, `object`.`parent`, `object`.`type` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE `object`.`parent`=? && `obj_item`.`item_container`='equip';")) { + + preparedStatement.setLong(1, (long) targetId); + ResultSet rs = preparedStatement.executeQuery(); + + itemList = getObjectsFromRs(rs, 50); + + } catch (SQLException e) { + Logger.error(e); + return null; + } + + return itemList; } - public Item GET_ITEM(final int id) { + public Item GET_ITEM(final int itemUUID) { + Item item; - prepareCallable("SELECT `obj_item`.*, `object`.`parent`, `object`.`type` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE `object`.`UID`=?;"); - setLong(1, (long) id); - return (Item) getObjectSingle(id); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_item`.*, `object`.`parent`, `object`.`type` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE `object`.`UID`=?;")) { + + preparedStatement.setLong(1, itemUUID); + ResultSet rs = preparedStatement.executeQuery(); + + item = (Item) getObjectFromRs(rs); + + } catch (SQLException e) { + Logger.error(e); + return null; + } + return item; } public ArrayList GET_ITEMS_FOR_ACCOUNT(final int accountId) { - prepareCallable("SELECT `obj_item`.*, `object`.`parent`, `object`.`type` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE `object`.`parent`=?;"); - setLong(1, (long) accountId); - return getObjectList(); + + ArrayList itemList; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_item`.*, `object`.`parent`, `object`.`type` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE `object`.`parent`=?;")) { + + preparedStatement.setLong(1, (long) accountId); + ResultSet rs = preparedStatement.executeQuery(); + + itemList = getObjectsFromRs(rs, 100); + + } catch (SQLException e) { + Logger.error(e); + return null; + } + return itemList; } public ArrayList GET_ITEMS_FOR_NPC(final int npcId) { - prepareCallable("SELECT `obj_item`.*, `object`.`parent`, `object`.`type` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE `object`.`parent`=?"); - setLong(1, (long) npcId); - return getObjectList(); + + ArrayList itemList; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_item`.*, `object`.`parent`, `object`.`type` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE `object`.`parent`=?;")) { + + preparedStatement.setLong(1, npcId); + ResultSet rs = preparedStatement.executeQuery(); + + itemList = getObjectsFromRs(rs, 20); + + } catch (SQLException e) { + Logger.error(e); + return null; + } + return itemList; } public ArrayList GET_ITEMS_FOR_PC(final int id) { - prepareCallable("SELECT `obj_item`.*, `object`.`parent`, `object`.`type` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE `object`.`parent`=?"); - setLong(1, (long) id); - return getLargeObjectList(); + + ArrayList itemList; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_item`.*, `object`.`parent`, `object`.`type` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE `object`.`parent`=?")) { + + preparedStatement.setLong(1, (long) id); + ResultSet rs = preparedStatement.executeQuery(); + + itemList = getObjectsFromRs(rs, 100); + + } catch (SQLException e) { + Logger.error(e); + return null; + } + return itemList; } public boolean MOVE_GOLD(final Item from, final Item to, final int amt) { - int newFromAmt = from.getNumOfItems() - amt; - int newToAmt = to.getNumOfItems() + amt; - prepareCallable("UPDATE `obj_item` SET `item_numberOfItems` = CASE WHEN `UID`=? THEN ? WHEN `UID`=? THEN ? END WHERE `UID` IN (?, ?);"); - setLong(1, (long) from.getObjectUUID()); - setInt(2, newFromAmt); - setLong(3, (long) to.getObjectUUID()); - setInt(4, newToAmt); - setLong(5, (long) from.getObjectUUID()); - setLong(6, (long) to.getObjectUUID()); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_numberOfItems` = CASE WHEN `UID`=? THEN ? WHEN `UID`=? THEN ? END WHERE `UID` IN (?, ?);")) { + + int newFromAmt = from.getNumOfItems() - amt; + int newToAmt = to.getNumOfItems() + amt; + + preparedStatement.setLong(1, (long) from.getObjectUUID()); + preparedStatement.setInt(2, newFromAmt); + preparedStatement.setLong(3, (long) to.getObjectUUID()); + preparedStatement.setInt(4, newToAmt); + preparedStatement.setLong(5, (long) from.getObjectUUID()); + preparedStatement.setLong(6, (long) to.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } public boolean ORPHAN_INVENTORY(final HashSet inventory) { + boolean worked = true; + for (Item item : inventory) { if (item.getItemBase().getType().equals(ItemType.GOLD)) continue; - prepareCallable("UPDATE `obj_item` LEFT JOIN `object` ON `object`.`UID` = `obj_item`.`UID` SET `object`.`parent`=NULL, `obj_item`.`item_container`='none' WHERE `object`.`UID`=?;"); - setLong(1, (long) item.getObjectUUID()); - if (executeUpdate() == 0) - worked = false; - else - item.zeroItem(); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` LEFT JOIN `object` ON `object`.`UID` = `obj_item`.`UID` SET `object`.`parent`=NULL, `obj_item`.`item_container`='none' WHERE `object`.`UID`=?;")) { + + preparedStatement.setLong(1, (long) item.getObjectUUID()); + worked = (preparedStatement.executeUpdate() > 0); + + if (worked) + item.zeroItem(); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } return worked; } public HashSet GET_ITEMS_FOR_VENDOR(final int vendorID) { - prepareCallable("SELECT ID FROM static_itembase WHERE vendorType = ?"); - setInt(1, vendorID); - return getIntegerList(1); - } - public String SET_PROPERTY(final Item i, String name, Object new_value) { - prepareCallable("CALL item_SETPROP(?,?,?)"); - setLong(1, (long) i.getObjectUUID()); - setString(2, name); - setString(3, String.valueOf(new_value)); - return getResult(); - } + HashSet itemSet = new HashSet<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT ID FROM static_itembase WHERE vendorType = ?")) { + + preparedStatement.setInt(1, vendorID); + + ResultSet rs = preparedStatement.executeQuery(); - public String SET_PROPERTY(final Item i, String name, Object new_value, Object old_value) { - prepareCallable("CALL item_GETSETPROP(?,?,?,?)"); - setLong(1, (long) i.getObjectUUID()); - setString(2, name); - setString(3, String.valueOf(new_value)); - setString(4, String.valueOf(old_value)); - return getResult(); + while (rs.next()) + itemSet.add(rs.getInt(1)); + + } catch (SQLException e) { + Logger.error(e); + return itemSet; + } + + return itemSet; } //Used to transfer a single item between owners or equip or vault or bank or inventory public boolean UPDATE_OWNER(final Item item, int newOwnerID, boolean ownerNPC, boolean ownerPlayer, boolean ownerAccount, ItemContainerType containerType, int slot) { - prepareCallable("CALL `item_TRANSFER_OWNER`(?, ?, ?, ? )"); - setLong(1, (long) item.getObjectUUID()); - if (newOwnerID != 0) - setLong(2, (long) newOwnerID); - else - setNULL(2, java.sql.Types.BIGINT); - - switch (containerType) { - case INVENTORY: - setString(3, "inventory"); - break; - case EQUIPPED: - setString(3, "equip"); - break; - case BANK: - setString(3, "bank"); - break; - case VAULT: - setString(3, "vault"); - break; - case FORGE: - setString(3, "forge"); - break; - default: - setString(3, "none"); //Shouldn't be here - break; + boolean worked = false; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL `item_TRANSFER_OWNER`(?, ?, ?, ? )")) { + + preparedStatement.setLong(1, item.getObjectUUID()); + + if (newOwnerID != 0) + preparedStatement.setLong(2, newOwnerID); + else + preparedStatement.setNull(2, java.sql.Types.BIGINT); + + switch (containerType) { + case INVENTORY: + preparedStatement.setString(3, "inventory"); + break; + case EQUIPPED: + preparedStatement.setString(3, "equip"); + break; + case BANK: + preparedStatement.setString(3, "bank"); + break; + case VAULT: + preparedStatement.setString(3, "vault"); + break; + case FORGE: + preparedStatement.setString(3, "forge"); + break; + default: + preparedStatement.setString(3, "none"); //Shouldn't be here + break; + } + preparedStatement.setInt(4, slot); + ResultSet rs = preparedStatement.executeQuery(); + + if (rs.next()) + worked = rs.getBoolean("result"); + + } catch (SQLException e) { + Logger.error(e); + return false; } - setInt(4, slot); - return worked(); + return worked; } public boolean SET_DURABILITY(final Item item, int value) { - prepareCallable("UPDATE `obj_item` SET `item_durabilityCurrent`=? WHERE `UID`=? AND `item_durabilityCurrent`=?"); - setInt(1, value); - setLong(2, (long) item.getObjectUUID()); - setInt(3, (int) item.getDurabilityCurrent()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_durabilityCurrent`=? WHERE `UID`=? AND `item_durabilityCurrent`=?")) { + + preparedStatement.setInt(1, value); + preparedStatement.setLong(2, (long) item.getObjectUUID()); + preparedStatement.setInt(3, (int) item.getDurabilityCurrent()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean UPDATE_FORGE_TO_INVENTORY(final Item item) { - prepareCallable("UPDATE `obj_item` SET `item_container` = ? WHERE `UID` = ? AND `item_container` = 'forge';"); - setString(1, "inventory"); - setLong(2, (long) item.getObjectUUID()); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_container` = ? WHERE `UID` = ? AND `item_container` = 'forge';")) { + + preparedStatement.setString(1, "inventory"); + preparedStatement.setLong(2, (long) item.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } /** @@ -313,43 +432,88 @@ public class dbItemHandler extends dbHandlerBase { */ public boolean UPDATE_GOLD(final Item item, int newValue, int oldValue) { - if (item.getItemBase().getType().equals(ItemType.GOLD) == false) + if (!item.getItemBase().getType().equals(ItemType.GOLD)) + return false; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_numberOfItems`=? WHERE `UID`=?")) { + + preparedStatement.setInt(1, newValue); + preparedStatement.setLong(2, (long) item.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); return false; + } - prepareCallable("UPDATE `obj_item` SET `item_numberOfItems`=? WHERE `UID`=?"); - setInt(1, newValue); - setLong(2, (long) item.getObjectUUID()); - return (executeUpdate() != 0); } public boolean UPDATE_REMAINING_CHARGES(final Item item) { - prepareCallable("UPDATE `obj_item` SET `item_chargesRemaining` = ? WHERE `UID` = ?"); - setInt(1, item.getChargesRemaining()); - setLong(2, (long) item.getObjectUUID()); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_chargesRemaining` = ? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, item.getChargesRemaining()); + preparedStatement.setLong(2, (long) item.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } // This is necessary because default number of items is 1. // When we create gold, we want it to start at 0 quantity. public boolean ZERO_ITEM_STACK(Item item) { - prepareCallable("UPDATE `obj_item` SET `item_numberOfItems`=0 WHERE `UID` = ?"); - setLong(1, (long) item.getObjectUUID()); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_numberOfItems`=0 WHERE `UID` = ?")) { + + preparedStatement.setLong(1, (long) item.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean UPDATE_FLAGS(Item item) { - prepareCallable("UPDATE `obj_item` SET `item_flags`=? WHERE `UID` = ?"); - setInt(1, item.getFlags()); - setLong(2, (long) item.getObjectUUID()); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_flags`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, item.getFlags()); + preparedStatement.setLong(2, (long) item.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean UPDATE_VALUE(Item item,int value) { - prepareCallable("UPDATE `obj_item` SET `item_value`=? WHERE `UID` = ?"); - setInt(1, value); - setLong(2, (long) item.getObjectUUID()); - return (executeUpdate() != 0); - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_value`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, value); + preparedStatement.setLong(2, (long) item.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } } From f299fcaffc65479fe373cb3461862be6d27db8dd Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sun, 21 May 2023 15:10:27 -0400 Subject: [PATCH 038/109] Refactor to remove abstraction. --- src/engine/db/handlers/dbAccountHandler.java | 20 +-- .../db/handlers/dbCharacterPowerHandler.java | 135 +++++++++++++----- src/engine/db/handlers/dbKitHandler.java | 8 -- 3 files changed, 107 insertions(+), 56 deletions(-) diff --git a/src/engine/db/handlers/dbAccountHandler.java b/src/engine/db/handlers/dbAccountHandler.java index 49d625bc..850e4eac 100644 --- a/src/engine/db/handlers/dbAccountHandler.java +++ b/src/engine/db/handlers/dbAccountHandler.java @@ -63,14 +63,14 @@ public class dbAccountHandler extends dbHandlerBase { public void WRITE_ADMIN_LOG(String adminName, String logEntry) { try (Connection connection = DbManager.getConnection(); - PreparedStatement accountQuery = connection.prepareStatement("INSERT INTO dyn_admin_log(`dateTime`, `charName`, `eventString`)" + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO dyn_admin_log(`dateTime`, `charName`, `eventString`)" + " VALUES (?, ?, ?)")) { - accountQuery.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis())); - accountQuery.setString(2, adminName); - accountQuery.setString(3, logEntry); + preparedStatement.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis())); + preparedStatement.setString(2, adminName); + preparedStatement.setString(3, logEntry); - accountQuery.execute(); + preparedStatement.execute(); } catch (SQLException e) { Logger.error(e); @@ -97,9 +97,9 @@ public class dbAccountHandler extends dbHandlerBase { ArrayList machineList = new ArrayList<>(); try (Connection connection = DbManager.getConnection(); - PreparedStatement accountQuery = connection.prepareStatement("select `machineID` from `dyn_trash`")) { + PreparedStatement preparedStatement = connection.prepareStatement("select `machineID` from `dyn_trash`")) { - ResultSet rs = accountQuery.executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) machineList.add(rs.getString(1)); @@ -130,12 +130,12 @@ public class dbAccountHandler extends dbHandlerBase { ArrayList trashList = new ArrayList<>(); try (Connection connection = DbManager.getConnection(); - PreparedStatement accountQuery = connection.prepareStatement("select DISTINCT UID from object \n" + + PreparedStatement preparedStatement = connection.prepareStatement("select DISTINCT UID from object \n" + "where parent IN (select AccountID from dyn_login_history " + " WHERE`machineID`=?)")) { - accountQuery.setString(1, machineID); - ResultSet rs = accountQuery.executeQuery(); + preparedStatement.setString(1, machineID); + ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { diff --git a/src/engine/db/handlers/dbCharacterPowerHandler.java b/src/engine/db/handlers/dbCharacterPowerHandler.java index 31a64f8a..cbed4c38 100644 --- a/src/engine/db/handlers/dbCharacterPowerHandler.java +++ b/src/engine/db/handlers/dbCharacterPowerHandler.java @@ -16,6 +16,8 @@ import engine.objects.PlayerCharacter; import engine.server.MBServerStatics; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.concurrent.ConcurrentHashMap; @@ -28,86 +30,143 @@ public class dbCharacterPowerHandler extends dbHandlerBase { } public CharacterPower ADD_CHARACTER_POWER(CharacterPower toAdd) { + + CharacterPower characterPower = null; + if (CharacterPower.getOwner(toAdd) == null || toAdd.getPower() == null) { Logger.error("dbCharacterSkillHandler.ADD_Power", toAdd.getObjectUUID() + " missing owner or powersBase"); return null; } - prepareCallable("INSERT INTO `dyn_character_power` (`CharacterID`, `powersBaseToken`, `trains`) VALUES (?, ?, ?);"); - setLong(1, (long)CharacterPower.getOwner(toAdd).getObjectUUID()); - setInt(2, toAdd.getPower().getToken()); - setInt(3, toAdd.getTrains()); - int powerID = insertGetUUID(); - return GET_CHARACTER_POWER(powerID); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_power` (`CharacterID`, `powersBaseToken`, `trains`) VALUES (?, ?, ?);")) { + + preparedStatement.setLong(1, CharacterPower.getOwner(toAdd).getObjectUUID()); + preparedStatement.setInt(2, toAdd.getPower().getToken()); + preparedStatement.setInt(3, toAdd.getTrains()); + preparedStatement.executeUpdate(); + ResultSet rs = preparedStatement.getGeneratedKeys(); + + if (rs.next()) + characterPower = GET_CHARACTER_POWER(rs.getInt(1)); + + } catch (SQLException e) { + Logger.error(e); + return null; + } + return characterPower; } public int DELETE_CHARACTER_POWER(final int objectUUID) { - prepareCallable("DELETE FROM `dyn_character_power` WHERE `UID` = ?"); - setLong(1, (long)objectUUID); - return executeUpdate(); + + int rowCount = 0; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_character_power` WHERE `UID` = ?")) { + + preparedStatement.setLong(1, objectUUID); + rowCount = preparedStatement.executeUpdate(); + + } catch (SQLException e) { + Logger.error(e); + } + + return rowCount; } public CharacterPower GET_CHARACTER_POWER(int objectUUID) { - CharacterPower cp = (CharacterPower) DbManager.getFromCache(Enum.GameObjectType.CharacterPower, objectUUID); - if (cp != null) - return cp; - prepareCallable("SELECT * FROM `dyn_character_power` WHERE `UID` = ?"); - setLong(1, (long)objectUUID); - return (CharacterPower) getObjectSingle(objectUUID); + CharacterPower characterPower = (CharacterPower) DbManager.getFromCache(Enum.GameObjectType.CharacterPower, objectUUID); + + if (characterPower != null) + return characterPower; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_character_power` WHERE `UID` = ?")) { + + preparedStatement.setLong(1, objectUUID); + ResultSet rs = preparedStatement.executeQuery(); + characterPower = (CharacterPower) getObjectFromRs(rs); + + } catch (SQLException e) { + Logger.error(e); + } + + return characterPower; } public ConcurrentHashMap GET_POWERS_FOR_CHARACTER(PlayerCharacter pc) { + ConcurrentHashMap powers = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW); int objectUUID = pc.getObjectUUID(); - prepareCallable("SELECT * FROM `dyn_character_power` WHERE CharacterID = ?"); - setLong(1, (long)objectUUID); - ResultSet rs = executeQuery(); - try { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_character_power` WHERE CharacterID = ?")) { + + preparedStatement.setLong(1, (long) objectUUID); + ResultSet rs = preparedStatement.executeQuery(); + while (rs.next()) { CharacterPower cp = new CharacterPower(rs, pc); if (cp.getPower() != null) powers.put(cp.getPower().getToken(), cp); } - rs.close(); + } catch (SQLException e) { - Logger.error("CharacterPower.getCharacterPowerForCharacter", "Exception:" + e.getMessage()); - } finally { - closeCallable(); + Logger.error(e); } + return powers; } - public void UPDATE_TRAINS(final CharacterPower pow) { + public void UPDATE_TRAINS(final CharacterPower characterPower) { + //skip update if nothing changed - if (!pow.isTrained()) + + if (!characterPower.isTrained()) return; - prepareCallable("UPDATE `dyn_character_power` SET `trains`=? WHERE `UID`=?"); - setShort(1, (short)pow.getTrains()); - setInt(2, pow.getObjectUUID()); - executeUpdate(); - pow.setTrained(false); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_character_power` SET `trains`=? WHERE `UID`=?")) { + + preparedStatement.setShort(1, (short) characterPower.getTrains()); + preparedStatement.setInt(2, characterPower.getObjectUUID()); + + preparedStatement.execute(); + + } catch (SQLException e) { + Logger.error(e); + } + + characterPower.setTrained(false); } public void updateDatabase(final CharacterPower pow) { + if (pow.getPower() == null) { - Logger.error( "Failed to find powersBase for Power " + pow.getObjectUUID()); + Logger.error("Failed to find powersBase for Power " + pow.getObjectUUID()); return; } + if (CharacterPower.getOwner(pow) == null) { - Logger.error( "Failed to find owner for Power " + pow.getObjectUUID()); + Logger.error("Failed to find owner for Power " + pow.getObjectUUID()); return; } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_character_power` SET `PowersBaseToken`=?, `CharacterID`=?, `trains`=? WHERE `UID`=?")) { + + preparedStatement.setInt(1, pow.getPower().getToken()); + preparedStatement.setInt(2, CharacterPower.getOwner(pow).getObjectUUID()); + preparedStatement.setShort(3, (short) pow.getTrains()); + preparedStatement.setInt(4, pow.getObjectUUID()); + preparedStatement.execute(); + + } catch (SQLException e) { + Logger.error(e); + } - prepareCallable("UPDATE `dyn_character_power` SET `PowersBaseToken`=?, `CharacterID`=?, `trains`=? WHERE `UID`=?"); - setInt(1, pow.getPower().getToken()); - setInt(2, CharacterPower.getOwner(pow).getObjectUUID()); - setShort(3, (short)pow.getTrains()); - setInt(4, pow.getObjectUUID()); - executeUpdate(); pow.setTrained(false); } } diff --git a/src/engine/db/handlers/dbKitHandler.java b/src/engine/db/handlers/dbKitHandler.java index b558ec82..c0fa92ac 100644 --- a/src/engine/db/handlers/dbKitHandler.java +++ b/src/engine/db/handlers/dbKitHandler.java @@ -20,14 +20,6 @@ public class dbKitHandler extends dbHandlerBase { this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); } - public ArrayList GET_KITS_FOR_RACE_AND_BASECLASS(int raceID, int baseClassID) { - prepareCallable("SELECT vk.* FROM `static_rune_validkit` vk, `static_rune_racebaseclass` rbc WHERE rbc.`RaceID` = ? " - + "&& rbc.`BaseClassID` = ? && rbc.`ID` = vk.`RaceBaseClassesID`"); - setInt(1, raceID); - setInt(2, baseClassID); - return getObjectList(); - } - public ArrayList GET_ALL_KITS() { prepareCallable("SELECT * FROM `static_rune_validkit`"); From 0924fa2bdbb93a3f889a63156316b2c7017598cc Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sun, 21 May 2023 15:28:50 -0400 Subject: [PATCH 039/109] Refactor to remove abstraction. --- src/engine/db/handlers/dbBuildingHandler.java | 2 +- .../db/handlers/dbCharacterRuneHandler.java | 110 ++++++++++++++---- src/engine/db/handlers/dbItemHandler.java | 2 +- 3 files changed, 88 insertions(+), 26 deletions(-) diff --git a/src/engine/db/handlers/dbBuildingHandler.java b/src/engine/db/handlers/dbBuildingHandler.java index ef564c47..e247109f 100644 --- a/src/engine/db/handlers/dbBuildingHandler.java +++ b/src/engine/db/handlers/dbBuildingHandler.java @@ -96,7 +96,7 @@ public class dbBuildingHandler extends dbHandlerBase { preparedStatement.setLong(1, zone.getObjectUUID()); ResultSet rs = preparedStatement.executeQuery(); - buildings = getObjectsFromRs(rs, 2000); + buildings = getObjectsFromRs(rs, 1000); } catch (SQLException e) { Logger.error(e); diff --git a/src/engine/db/handlers/dbCharacterRuneHandler.java b/src/engine/db/handlers/dbCharacterRuneHandler.java index 868774f8..d905f0e2 100644 --- a/src/engine/db/handlers/dbCharacterRuneHandler.java +++ b/src/engine/db/handlers/dbCharacterRuneHandler.java @@ -12,7 +12,12 @@ package engine.db.handlers; import engine.Enum; import engine.gameManager.DbManager; import engine.objects.CharacterRune; +import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.ArrayList; public class dbCharacterRuneHandler extends dbHandlerBase { @@ -23,41 +28,98 @@ public class dbCharacterRuneHandler extends dbHandlerBase { } public CharacterRune ADD_CHARACTER_RUNE(final CharacterRune toAdd) { - prepareCallable("INSERT INTO `dyn_character_rune` (`CharacterID`, `RuneBaseID`) VALUES (?, ?);"); - setLong(1, (long)toAdd.getPlayerID()); - setInt(2, toAdd.getRuneBaseID()); - int runeID = insertGetUUID(); - return GET_CHARACTER_RUNE(runeID); + + CharacterRune characterRune = null; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_rune` (`CharacterID`, `RuneBaseID`) VALUES (?, ?);")) { + + preparedStatement.setLong(1, toAdd.getPlayerID()); + preparedStatement.setInt(2, toAdd.getRuneBaseID()); + + preparedStatement.executeUpdate(); + ResultSet rs = preparedStatement.getGeneratedKeys(); + + if (rs.next()) + characterRune = GET_CHARACTER_RUNE(rs.getInt(1)); + + } catch (SQLException e) { + Logger.error(e); + } + + return characterRune; } public CharacterRune GET_CHARACTER_RUNE(int runeID) { - CharacterRune charRune = (CharacterRune) DbManager.getFromCache(Enum.GameObjectType.CharacterRune, runeID); - if (charRune != null) - return charRune; - prepareCallable("SELECT * FROM `dyn_character_rune` WHERE `UID`=?"); - setInt(1, runeID); - return (CharacterRune) getObjectSingle(runeID); + CharacterRune characterRune = (CharacterRune) DbManager.getFromCache(Enum.GameObjectType.CharacterRune, runeID); + + if (characterRune != null) + return characterRune; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_character_rune` WHERE `UID`=?")) { + + preparedStatement.setInt(1, runeID); + ResultSet rs = preparedStatement.executeQuery(); + + characterRune = (CharacterRune) getObjectFromRs(rs); + + } catch (SQLException e) { + Logger.error(e); + } + + return characterRune; } + public boolean DELETE_CHARACTER_RUNE(final CharacterRune characterRune) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_character_rune` WHERE `UID`=?;")) { + + preparedStatement.setLong(1, characterRune.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } - public boolean DELETE_CHARACTER_RUNE(final CharacterRune cr) { - prepareCallable("DELETE FROM `dyn_character_rune` WHERE `UID`=?;"); - setLong(1, (long)cr.getObjectUUID()); - return (executeUpdate() != 0); } public ArrayList GET_RUNES_FOR_CHARACTER(final int characterId) { - prepareCallable("SELECT * FROM `dyn_character_rune` WHERE `CharacterID` = ?"); - setInt(1, characterId); - return getObjectList(); + + ArrayList characterRunes = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_character_rune` WHERE `CharacterID` = ?")) { + + preparedStatement.setInt(1, characterId); + + ResultSet rs = preparedStatement.executeQuery(); + characterRunes = getObjectsFromRs(rs, 10); + + } catch (SQLException e) { + Logger.error(e); + } + return characterRunes; } - public void updateDatabase(final CharacterRune cr) { - prepareCallable("UPDATE `dyn_character_rune` SET `CharacterID`=?, `RuneBaseID`=? WHERE `UID` = ?"); - setInt(1, cr.getPlayerID()); - setInt(2, cr.getRuneBaseID()); - setLong(3, (long) cr.getObjectUUID()); - executeUpdate(); + public void updateDatabase(final CharacterRune characterRune) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_character_rune` SET `CharacterID`=?, `RuneBaseID`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, characterRune.getPlayerID()); + preparedStatement.setInt(2, characterRune.getRuneBaseID()); + preparedStatement.setLong(3, (long) characterRune.getObjectUUID()); + + preparedStatement.execute(); + + } catch (SQLException e) { + Logger.error(e); + } } + } diff --git a/src/engine/db/handlers/dbItemHandler.java b/src/engine/db/handlers/dbItemHandler.java index e57ed854..bd61223b 100644 --- a/src/engine/db/handlers/dbItemHandler.java +++ b/src/engine/db/handlers/dbItemHandler.java @@ -172,7 +172,7 @@ public class dbItemHandler extends dbHandlerBase { preparedStatement.setLong(1, (long) targetId); ResultSet rs = preparedStatement.executeQuery(); - itemList = getObjectsFromRs(rs, 50); + itemList = getObjectsFromRs(rs, 10); } catch (SQLException e) { Logger.error(e); From ca5cfed82f43a1172d81a136a49137807640a0cb Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sun, 21 May 2023 15:48:55 -0400 Subject: [PATCH 040/109] Refactor to remove abstraction. --- .../db/handlers/dbCharacterSkillHandler.java | 160 ++++++++++++------ src/engine/db/handlers/dbItemBaseHandler.java | 2 +- 2 files changed, 111 insertions(+), 51 deletions(-) diff --git a/src/engine/db/handlers/dbCharacterSkillHandler.java b/src/engine/db/handlers/dbCharacterSkillHandler.java index e4a93779..d2e4909e 100644 --- a/src/engine/db/handlers/dbCharacterSkillHandler.java +++ b/src/engine/db/handlers/dbCharacterSkillHandler.java @@ -17,6 +17,8 @@ import engine.objects.PlayerCharacter; import engine.server.MBServerStatics; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.concurrent.ConcurrentHashMap; @@ -29,88 +31,146 @@ public class dbCharacterSkillHandler extends dbHandlerBase { } public CharacterSkill ADD_SKILL(CharacterSkill toAdd) { + + CharacterSkill characterSkill = null; + if (CharacterSkill.GetOwner(toAdd) == null || toAdd.getSkillsBase() == null) { Logger.error("dbCharacterSkillHandler.ADD_SKILL", toAdd.getObjectUUID() + " missing owner or skillsBase"); return null; } - prepareCallable("INSERT INTO `dyn_character_skill` (`CharacterID`, `skillsBaseID`, `trains`) VALUES (?, ?, ?);"); - setLong(1, (long)CharacterSkill.GetOwner(toAdd).getObjectUUID()); - setInt(2, toAdd.getSkillsBase().getObjectUUID()); - setInt(3, toAdd.getNumTrains()); - int skillID = insertGetUUID(); - return GET_SKILL(skillID); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_skill` (`CharacterID`, `skillsBaseID`, `trains`) VALUES (?, ?, ?);")) { + + preparedStatement.setLong(1, CharacterSkill.GetOwner(toAdd).getObjectUUID()); + preparedStatement.setInt(2, toAdd.getSkillsBase().getObjectUUID()); + preparedStatement.setInt(3, toAdd.getNumTrains()); + + preparedStatement.executeUpdate(); + ResultSet rs = preparedStatement.getGeneratedKeys(); + + if (rs.next()) + characterSkill = GET_SKILL(rs.getInt(1)); + + } catch (SQLException e) { + Logger.error(e); + } + return characterSkill; } public boolean DELETE_SKILL(final int objectUUID) { - prepareCallable("DELETE FROM `dyn_character_skill` WHERE `UID` = ?"); - setLong(1, (long)objectUUID); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_character_skill` WHERE `UID` = ?")) { + + preparedStatement.setLong(1, objectUUID); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public CharacterSkill GET_SKILL(final int objectUUID) { - CharacterSkill skill = (CharacterSkill) DbManager.getFromCache(Enum.GameObjectType.CharacterSkill, objectUUID); - if (skill != null) - return skill; - prepareCallable("SELECT * FROM `dyn_character_skill` WHERE `UID` = ?"); - setInt(1, objectUUID); - return (CharacterSkill) getObjectSingle(objectUUID); + + CharacterSkill characterSkill = (CharacterSkill) DbManager.getFromCache(Enum.GameObjectType.CharacterSkill, objectUUID); + + if (characterSkill != null) + return characterSkill; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_character_skill` WHERE `UID` = ?")) { + + preparedStatement.setInt(1, objectUUID); + ResultSet rs = preparedStatement.executeQuery(); + + characterSkill = (CharacterSkill) getObjectFromRs(rs); + + } catch (SQLException e) { + Logger.error(e); + } + return characterSkill; } public ConcurrentHashMap GET_SKILLS_FOR_CHARACTER(final AbstractCharacter ac) { - ConcurrentHashMap skills = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW); + + ConcurrentHashMap characterSkills = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW); + if (ac == null || (!(ac.getObjectType().equals(Enum.GameObjectType.PlayerCharacter)))) - return skills; - PlayerCharacter pc = (PlayerCharacter) ac; - int objectUUID = pc.getObjectUUID(); - - prepareCallable("SELECT * FROM `dyn_character_skill` WHERE `CharacterID` = ?"); - setInt(1, objectUUID); - try { - ResultSet rs = executeQuery(); + return characterSkills; + + PlayerCharacter playerCharacter = (PlayerCharacter) ac; + int characterId = playerCharacter.getObjectUUID(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_character_skill` WHERE `CharacterID` = ?")) { + + preparedStatement.setInt(1, characterId); + + ResultSet rs = preparedStatement.executeQuery(); + while (rs.next()) { - CharacterSkill cs = new CharacterSkill(rs, pc); + CharacterSkill cs = new CharacterSkill(rs, playerCharacter); if (cs.getSkillsBase() != null) - skills.put(cs.getSkillsBase().getName(), cs); + characterSkills.put(cs.getSkillsBase().getName(), cs); } - rs.close(); + } catch (SQLException e) { - Logger.error("CharacterSkill.getCharacterSkillForCharacter", e); - } finally { - closeCallable(); + Logger.error(e); } - return skills; + + return characterSkills; } - public void UPDATE_TRAINS(final CharacterSkill cs) { - if (!cs.isTrained()) + public void UPDATE_TRAINS(final CharacterSkill characterSkill) { + + if (!characterSkill.isTrained()) return; - prepareCallable("UPDATE `dyn_character_skill` SET `trains`=? WHERE `UID` = ?"); - setShort(1, (short)cs.getNumTrains()); - setLong(2, (long)cs.getObjectUUID()); - if (executeUpdate() != 0) - cs.syncTrains(); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_character_skill` SET `trains`=? WHERE `UID` = ?")) { + + preparedStatement.setShort(1, (short) characterSkill.getNumTrains()); + preparedStatement.setLong(2, (long) characterSkill.getObjectUUID()); + + if (preparedStatement.executeUpdate() != 0) + characterSkill.syncTrains(); + + } catch (SQLException e) { + Logger.error(e); + } } - public void updateDatabase(final CharacterSkill cs) { - if (cs.getSkillsBase() == null) { - Logger.error("Failed to find skillsBase for Skill " + cs.getObjectUUID()); + public void updateDatabase(final CharacterSkill characterSkill) { + + if (characterSkill.getSkillsBase() == null) { + Logger.error("Failed to find skillsBase for Skill " + characterSkill.getObjectUUID()); return; } - if (CharacterSkill.GetOwner(cs) == null) { - Logger.error("Failed to find owner for Skill " + cs.getObjectUUID()); + + if (CharacterSkill.GetOwner(characterSkill) == null) { + Logger.error("Failed to find owner for Skill " + characterSkill.getObjectUUID()); return; } - prepareCallable("UPDATE `dyn_character_skill` SET `skillsBaseID`=?, `CharacterID`=?, `trains`=? WHERE `UID`=?"); - setInt(1, cs.getSkillsBase().getObjectUUID()); - setInt(2, CharacterSkill.GetOwner(cs).getObjectUUID()); - setShort(3, (short)cs.getNumTrains()); - setLong(4, (long)cs.getObjectUUID()); - if (executeUpdate() != 0) - cs.syncTrains(); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_character_skill` SET `skillsBaseID`=?, `CharacterID`=?, `trains`=? WHERE `UID`=?")) { + + preparedStatement.setInt(1, characterSkill.getSkillsBase().getObjectUUID()); + preparedStatement.setInt(2, CharacterSkill.GetOwner(characterSkill).getObjectUUID()); + preparedStatement.setShort(3, (short) characterSkill.getNumTrains()); + preparedStatement.setLong(4, (long) characterSkill.getObjectUUID()); + + if (preparedStatement.executeUpdate() != 0) + characterSkill.syncTrains(); + + } catch (SQLException e) { + Logger.error(e); + } + } } diff --git a/src/engine/db/handlers/dbItemBaseHandler.java b/src/engine/db/handlers/dbItemBaseHandler.java index a2f6b793..ac824efc 100644 --- a/src/engine/db/handlers/dbItemBaseHandler.java +++ b/src/engine/db/handlers/dbItemBaseHandler.java @@ -94,7 +94,7 @@ public class dbItemBaseHandler extends dbHandlerBase { Logger.error(e); } - Logger.info("read: " + recordsRead + "cached: " + ItemBase.getUUIDCache().size()); + Logger.info("read: " + recordsRead + " cached: " + ItemBase.getUUIDCache().size()); } public HashMap> LOAD_RUNES_FOR_NPC_AND_MOBS() { From e203945ea3e028f36f68e8051570ccf4cc2fb5e8 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sun, 21 May 2023 15:55:15 -0400 Subject: [PATCH 041/109] Static method moved to manager singleton. --- src/engine/gameManager/ZoneManager.java | 29 ++++++++++++++++++++++++ src/engine/objects/City.java | 27 ---------------------- src/engine/server/world/WorldServer.java | 2 +- 3 files changed, 30 insertions(+), 28 deletions(-) diff --git a/src/engine/gameManager/ZoneManager.java b/src/engine/gameManager/ZoneManager.java index eab3393e..f4e2f434 100644 --- a/src/engine/gameManager/ZoneManager.java +++ b/src/engine/gameManager/ZoneManager.java @@ -9,6 +9,8 @@ package engine.gameManager; import engine.Enum; +import engine.db.archive.CityRecord; +import engine.db.archive.DataWarehouse; import engine.math.Bounds; import engine.math.Vector2f; import engine.math.Vector3f; @@ -423,4 +425,31 @@ public enum ZoneManager { treeBounds.release(); return validLocation; } + + public static void loadCities(Zone zone) { + + ArrayList cities = DbManager.CityQueries.GET_CITIES_BY_ZONE(zone.getObjectUUID()); + + for (City city : cities) { + + city.setParent(zone); + city.setObjectTypeMask(MBServerStatics.MASK_CITY); + city.setLoc(city.getLoc()); // huh? + +//not player city, must be npc city.. + + if (!zone.isPlayerCity()) + zone.setNPCCity(true); + + if ((ConfigManager.serverType.equals(Enum.ServerType.WORLDSERVER)) && (city.getHash() == null)) { + + city.setHash(); + + if (DataWarehouse.recordExists(Enum.DataRecordType.CITY, city.getObjectUUID()) == false) { + CityRecord cityRecord = CityRecord.borrow(city, Enum.RecordEventType.CREATE); + DataWarehouse.pushToWarehouse(cityRecord); + } + } + } + } } diff --git a/src/engine/objects/City.java b/src/engine/objects/City.java index 084ab55d..4286c96c 100644 --- a/src/engine/objects/City.java +++ b/src/engine/objects/City.java @@ -746,33 +746,6 @@ public class City extends AbstractWorldObject { return open; } - public static void loadCities(Zone zone) { - - ArrayList cities = DbManager.CityQueries.GET_CITIES_BY_ZONE(zone.getObjectUUID()); - - for (City city : cities) { - - city.setParent(zone); - city.setObjectTypeMask(MBServerStatics.MASK_CITY); - city.setLoc(city.location); - - //not player city, must be npc city.. - if (!zone.isPlayerCity()) - zone.setNPCCity(true); - - if ((ConfigManager.serverType.equals(ServerType.WORLDSERVER)) && (city.hash == null)) { - - city.setHash(); - - if (DataWarehouse.recordExists(Enum.DataRecordType.CITY, city.getObjectUUID()) == false) { - CityRecord cityRecord = CityRecord.borrow(city, Enum.RecordEventType.CREATE); - DataWarehouse.pushToWarehouse(cityRecord); - } - } - } - } - - @Override public void updateDatabase() { diff --git a/src/engine/server/world/WorldServer.java b/src/engine/server/world/WorldServer.java index 98658e53..276fd9ec 100644 --- a/src/engine/server/world/WorldServer.java +++ b/src/engine/server/world/WorldServer.java @@ -572,7 +572,7 @@ public class WorldServer { //Handle cities - City.loadCities(zone); + ZoneManager.loadCities(zone); ZoneManager.populateWorldZones(zone); } catch (Exception e) { From 4d08857de1dc6e02d3f2529fefccbfbeafb5c117 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sun, 21 May 2023 17:00:17 -0400 Subject: [PATCH 042/109] Refactor to remove abstraction --- src/engine/db/handlers/dbCityHandler.java | 381 +++++++++++++--------- src/engine/objects/City.java | 5 +- 2 files changed, 220 insertions(+), 166 deletions(-) diff --git a/src/engine/db/handlers/dbCityHandler.java b/src/engine/db/handlers/dbCityHandler.java index 8759582d..9097e005 100644 --- a/src/engine/db/handlers/dbCityHandler.java +++ b/src/engine/db/handlers/dbCityHandler.java @@ -17,173 +17,228 @@ import engine.objects.City; import engine.objects.Zone; import org.pmw.tinylog.Logger; -import java.net.UnknownHostException; -import java.sql.ResultSet; -import java.sql.SQLException; +import java.sql.*; import java.time.LocalDateTime; import java.util.ArrayList; public class dbCityHandler extends dbHandlerBase { - public dbCityHandler() { - this.localClass = City.class; - this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); - } - - public ArrayList CREATE_CITY(int ownerID, int parentZoneID, int realmID, float xCoord, float yCoord, float zCoord, float rotation, float W, String name, LocalDateTime established) { - prepareCallable("CALL `city_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)"); - LocalDateTime upgradeTime = LocalDateTime.now().plusHours(2); - setLong(1, (long) ownerID); //objectUUID of owning player - setLong(2, (long) parentZoneID); //objectUUID of parent (continent) zone - setLong(3, (long) realmID); //objectUUID of realm city belongs in - setFloat(4, xCoord); //xOffset from parentZone center - setFloat(5, yCoord); //yOffset from parentZone center - setFloat(6, zCoord); //zOffset from parentZone center - setString(7, name); //city name - setLocalDateTime(8, established); - setFloat(9, rotation); - setFloat(10, W); - setLocalDateTime(11, upgradeTime); - ArrayList list = new ArrayList<>(); - - try { - boolean work = execute(); - if (work) { - ResultSet rs = this.callableStatement.get().getResultSet(); - while (rs.next()) { - addObject(list, rs); - } - rs.close(); - } else { - Logger.info("City Placement Failed: " + this.callableStatement.get().toString()); - return list; //city creation failure - } - while (this.callableStatement.get().getMoreResults()) { - ResultSet rs = this.callableStatement.get().getResultSet(); - while (rs.next()) { - addObject(list, rs); - } - rs.close(); - } - } catch (SQLException e) { - Logger.info("City Placement Failed, SQLException: " + this.callableStatement.get().toString() + e.toString()); - return list; //city creation failure - } catch (UnknownHostException e) { - Logger.info("City Placement Failed, UnknownHostException: " + this.callableStatement.get().toString()); - return list; //city creation failure - } finally { - closeCallable(); - } - return list; - } - - public static void addObject(ArrayList list, ResultSet rs) throws SQLException, UnknownHostException { - String type = rs.getString("type"); - switch (type) { - case "zone": - Zone zone = new Zone(rs); - DbManager.addToCache(zone); - list.add(zone); - break; - case "building": - Building building = new Building(rs); - DbManager.addToCache(building); - list.add(building); - break; - case "city": - City city = new City(rs); - DbManager.addToCache(city); - list.add(city); - break; - } - } - - public ArrayList GET_CITIES_BY_ZONE(final int objectUUID) { - prepareCallable("SELECT `obj_city`.*, `object`.`parent` FROM `obj_city` INNER JOIN `object` ON `object`.`UID` = `obj_city`.`UID` WHERE `object`.`parent`=?;"); - setLong(1, (long) objectUUID); - - return getObjectList(); - } - - public City GET_CITY(final int cityId) { - City city = (City) DbManager.getFromCache(Enum.GameObjectType.City, cityId); - if (city != null) - return city; - prepareCallable("SELECT `obj_city`.*, `object`.`parent` FROM `obj_city` INNER JOIN `object` ON `object`.`UID` = `obj_city`.`UID` WHERE `object`.`UID`=?;"); - setLong(1, (long) cityId); - city = (City) getObjectSingle(cityId); - return city; - } - - public String SET_PROPERTY(final City c, String name, Object new_value) { - prepareCallable("CALL city_SETPROP(?,?,?)"); - setLong(1, (long) c.getObjectUUID()); - setString(2, name); - setString(3, String.valueOf(new_value)); - return getResult(); - } - - public String SET_PROPERTY(final City c, String name, Object new_value, Object old_value) { - prepareCallable("CALL city_GETSETPROP(?,?,?,?)"); - setLong(1, (long) c.getObjectUUID()); - setString(2, name); - setString(3, String.valueOf(new_value)); - setString(4, String.valueOf(old_value)); - return getResult(); - } - - public boolean updateforceRename(City city, boolean value) { - - prepareCallable("UPDATE `obj_city` SET `forceRename`=?" - + " WHERE `UID` = ?"); - setByte(1, (value == true) ? (byte) 1 : (byte) 0); - setInt(2, city.getObjectUUID()); - return (executeUpdate() > 0); - } - - public boolean updateOpenCity(City city, boolean value) { - - prepareCallable("UPDATE `obj_city` SET `open`=?" - + " WHERE `UID` = ?"); - setByte(1, (value == true) ? (byte) 1 : (byte) 0); - setInt(2, city.getObjectUUID()); - return (executeUpdate() > 0); - } - - public boolean updateTOL(City city, int tolID) { - - prepareCallable("UPDATE `obj_city` SET `treeOfLifeUUID`=?" - + " WHERE `UID` = ?"); - setInt(1,tolID); - setInt(2, city.getObjectUUID()); - return (executeUpdate() > 0); - } - - public boolean renameCity(City city, String name) { - - prepareCallable("UPDATE `obj_city` SET `name`=?" - + " WHERE `UID` = ?"); - setString(1, name); - setInt(2, city.getObjectUUID()); - return (executeUpdate() > 0); - } - - public boolean updateSiegesWithstood(City city, int value) { - - prepareCallable("UPDATE `obj_city` SET `siegesWithstood`=?" - + " WHERE `UID` = ?"); - setInt(1, value); - setInt(2, city.getObjectUUID()); - return (executeUpdate() > 0); - } - - public boolean updateRealmTaxDate(City city, LocalDateTime localDateTime) { - - prepareCallable("UPDATE `obj_city` SET `realmTaxDate` =?" - + " WHERE `UID` = ?"); - setLocalDateTime(1, localDateTime); - setInt(2,city.getObjectUUID()); - return (executeUpdate() > 0); - } + public dbCityHandler() { + this.localClass = City.class; + this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); + } + + public static void addObject(ArrayList list, ResultSet rs) throws SQLException { + String type = rs.getString("type"); + switch (type) { + case "zone": + Zone zone = new Zone(rs); + DbManager.addToCache(zone); + list.add(zone); + break; + case "building": + Building building = new Building(rs); + DbManager.addToCache(building); + list.add(building); + break; + case "city": + City city = new City(rs); + DbManager.addToCache(city); + list.add(city); + break; + } + } + + public ArrayList CREATE_CITY(int ownerID, int parentZoneID, int realmID, float xCoord, float yCoord, float zCoord, float rotation, float W, String name, LocalDateTime established) { + + LocalDateTime upgradeTime = LocalDateTime.now().plusHours(2); + ArrayList objectList = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL `city_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)")) { + + preparedStatement.setLong(1, ownerID); //objectUUID of owning player + preparedStatement.setLong(2, parentZoneID); //objectUUID of parent (continent) zone + preparedStatement.setLong(3, realmID); //objectUUID of realm city belongs in + preparedStatement.setFloat(4, xCoord); //xOffset from parentZone center + preparedStatement.setFloat(5, yCoord); //yOffset from parentZone center + preparedStatement.setFloat(6, zCoord); //zOffset from parentZone center + preparedStatement.setString(7, name); //city name + preparedStatement.setTimestamp(8, Timestamp.valueOf(established)); + preparedStatement.setFloat(9, rotation); + preparedStatement.setFloat(10, W); + preparedStatement.setTimestamp(11, Timestamp.valueOf(upgradeTime)); + + boolean work = execute(); + + if (work) { + ResultSet rs = preparedStatement.getResultSet(); + while (rs.next()) { + addObject(objectList, rs); + } + rs.close(); + } else { + Logger.info("City Placement Failed: " + preparedStatement); + return objectList; //city creation failure + } + while (preparedStatement.getMoreResults()) { + ResultSet rs = preparedStatement.getResultSet(); + while (rs.next()) { + addObject(objectList, rs); + } + rs.close(); + } + } catch (SQLException e) { + Logger.error(e); + } + + return objectList; + } + + public ArrayList GET_CITIES_BY_ZONE(final int objectUUID) { + + ArrayList cityList = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_city`.*, `object`.`parent` FROM `obj_city` INNER JOIN `object` ON `object`.`UID` = `obj_city`.`UID` WHERE `object`.`parent`=?;")) { + + preparedStatement.setLong(1, objectUUID); + + ResultSet rs = preparedStatement.executeQuery(); + cityList = getObjectsFromRs(rs, 100); + + } catch (SQLException e) { + Logger.error(e); + } + + return cityList; + } + + public City GET_CITY(final int cityId) { + + City city = (City) DbManager.getFromCache(Enum.GameObjectType.City, cityId); + + if (city != null) + return city; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_city`.*, `object`.`parent` FROM `obj_city` INNER JOIN `object` ON `object`.`UID` = `obj_city`.`UID` WHERE `object`.`UID`=?;")) { + + preparedStatement.setLong(1, cityId); + + ResultSet rs = preparedStatement.executeQuery(); + city = (City) getObjectFromRs(rs); + + } catch (SQLException e) { + Logger.error(e); + } + + return city; + } + + public boolean updateforceRename(City city, boolean value) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_city` SET `forceRename`=?" + + " WHERE `UID` = ?")) { + + preparedStatement.setByte(1, (value == true) ? (byte) 1 : (byte) 0); + preparedStatement.setInt(2, city.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } + + public boolean updateOpenCity(City city, boolean value) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_city` SET `open`=?" + + " WHERE `UID` = ?")) { + + preparedStatement.setByte(1, (value == true) ? (byte) 1 : (byte) 0); + preparedStatement.setInt(2, city.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } + + public boolean updateTOL(City city, int tolID) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_city` SET `treeOfLifeUUID`=?" + + " WHERE `UID` = ?")) { + + preparedStatement.setInt(1, tolID); + preparedStatement.setInt(2, city.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + + } + + public boolean renameCity(City city, String name) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_city` SET `name`=?" + + " WHERE `UID` = ?")) { + + preparedStatement.setString(1, name); + preparedStatement.setInt(2, city.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + + } + + public boolean updateSiegesWithstood(City city, int value) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_city` SET `name`=?" + + " WHERE `UID` = ?")) { + + preparedStatement.setInt(1, value); + preparedStatement.setInt(2, city.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + + } + + public boolean updateRealmTaxDate(City city, LocalDateTime localDateTime) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_city` SET `realmTaxDate` =?" + + " WHERE `UID` = ?")) { + + preparedStatement.setTimestamp(1, Timestamp.valueOf(localDateTime)); + preparedStatement.setInt(2, city.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } } diff --git a/src/engine/objects/City.java b/src/engine/objects/City.java index 4286c96c..30cb5a6c 100644 --- a/src/engine/objects/City.java +++ b/src/engine/objects/City.java @@ -34,7 +34,6 @@ import engine.workthreads.DestroyCityThread; import engine.workthreads.TransferCityThread; import org.pmw.tinylog.Logger; -import java.net.UnknownHostException; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDateTime; @@ -98,9 +97,9 @@ public class City extends AbstractWorldObject { * ResultSet Constructor */ - public City(ResultSet rs) throws SQLException, UnknownHostException { + public City(ResultSet rs) throws SQLException { super(rs); - try{ + try { this.cityName = rs.getString("name"); this.motto = rs.getString("motto"); this.isNpc = rs.getByte("isNpc"); From ea5cbf3f0cb70b3b6378ef7a673e52e06f0c5a60 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sun, 21 May 2023 17:20:09 -0400 Subject: [PATCH 043/109] Refactor to remove abstraction --- src/engine/db/handlers/dbContractHandler.java | 138 ++++++++++-------- src/engine/objects/Contract.java | 4 +- 2 files changed, 77 insertions(+), 65 deletions(-) diff --git a/src/engine/db/handlers/dbContractHandler.java b/src/engine/db/handlers/dbContractHandler.java index f8b41433..893dbcf4 100644 --- a/src/engine/db/handlers/dbContractHandler.java +++ b/src/engine/db/handlers/dbContractHandler.java @@ -16,9 +16,10 @@ import engine.objects.ItemBase; import engine.objects.MobEquipment; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.util.ArrayList; public class dbContractHandler extends dbHandlerBase { @@ -28,48 +29,37 @@ public class dbContractHandler extends dbHandlerBase { } public Contract GET_CONTRACT(final int objectUUID) { + Contract contract = (Contract) DbManager.getFromCache(Enum.GameObjectType.Contract, objectUUID); + if (contract != null) return contract; + if (objectUUID == 0) return null; - prepareCallable("SELECT * FROM `static_npc_contract` WHERE `ID` = ?"); - setInt(1, objectUUID); - return (Contract) getObjectSingle(objectUUID); - } - public ArrayList GET_CONTRACT_BY_RACE(final int objectUUID) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_building`.*, `object`.`parent` FROM `object` INNER JOIN `obj_building` ON `obj_building`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?;")) { - ArrayList contracts = new ArrayList<>(); + preparedStatement.setInt(1, objectUUID); - prepareCallable("SELECT * FROM static_npc_contract WHERE `mobbaseID` =?;"); - setLong(1, objectUUID); - - try { - ResultSet rs = executeQuery(); - - //shrines cached in rs for easy cache on creation. - while (rs.next()) { - Contract contract = new Contract(rs); - if (contract != null) - contracts.add(contract); - } + ResultSet rs = preparedStatement.executeQuery(); + contract = (Contract) getObjectFromRs(rs); } catch (SQLException e) { - Logger.error( e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); + Logger.error(e); } - return contracts; + return contract; } - public void GET_GENERIC_INVENTORY(final Contract contract) { + public void LOAD_CONTRACT_INVENTORY(final Contract contract) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_inventoryset` WHERE `inventorySet` = ?;")) { - prepareCallable("SELECT * FROM `static_npc_inventoryset` WHERE `inventorySet` = ?;"); - setInt(1, contract.inventorySet); + preparedStatement.setInt(1, contract.inventorySet); - try { - ResultSet rs = executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { @@ -102,56 +92,78 @@ public class dbContractHandler extends dbHandlerBase { } } } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode() + ' ' + e.getMessage()); - } finally { - closeCallable(); + Logger.error(e); } } - public void GET_SELL_LISTS(final Contract con) { - prepareCallable("SELECT * FROM `static_npc_contract_selltype` WHERE `contractID` = ?;"); - setInt(1, con.getObjectUUID()); - try { - ResultSet rs = executeQuery(); - ArrayList item = con.getBuyItemType(); - ArrayList skill = con.getBuySkillToken(); - ArrayList unknown = con.getBuyUnknownToken(); + public void LOAD_SELL_LIST_FOR_CONTRACT(final Contract contract) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_contract_selltype` WHERE `contractID` = ?;")) { + + preparedStatement.setInt(1, contract.getObjectUUID()); + + ResultSet rs = preparedStatement.executeQuery(); + while (rs.next()) { + int type = rs.getInt("type"); int value = rs.getInt("value"); - if (type == 1) { - item.add(value); - } else if (type == 2) { - skill.add(value); - } else if (type == 3) { - unknown.add(value); + + switch (type) { + case 1: + contract.getBuyItemType().add(value); + break; + case 2: + contract.getBuySkillToken().add(value); + break; + case 3: + contract.getBuyUnknownToken().add(value); + break; } } } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode() + ' ' + e.getMessage()); - } finally { - closeCallable(); + Logger.error(e); } } public boolean updateAllowedBuildings(final Contract con, final long slotbitvalue) { - prepareCallable("UPDATE `static_npc_contract` SET `allowedBuildingTypeID`=? WHERE `contractID`=?"); - setLong(1, slotbitvalue); - setInt(2, con.getContractID()); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `static_npc_contract` SET `allowedBuildingTypeID`=? WHERE `contractID`=?")) { + + preparedStatement.setLong(1, slotbitvalue); + preparedStatement.setInt(2, con.getContractID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean updateDatabase(final Contract con) { - prepareCallable("UPDATE `static_npc_contract` SET `contractID`=?, `name`=?, " - + "`mobbaseID`=?, `classID`=?, vendorDialog=?, iconID=?, allowedBuildingTypeID=? WHERE `ID`=?"); - setInt(1, con.getContractID()); - setString(2, con.getName()); - setInt(3, con.getMobbaseID()); - setInt(4, con.getClassID()); - setInt(5, (con.getVendorDialog() != null) ? con.getVendorDialog().getObjectUUID() : 0); - setInt(6, con.getIconID()); - setInt(8, con.getObjectUUID()); - setLong(7, con.getAllowedBuildings().toLong()); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `static_npc_contract` SET `contractID`=?, `name`=?, " + + "`mobbaseID`=?, `classID`=?, vendorDialog=?, iconID=?, allowedBuildingTypeID=? WHERE `ID`=?")) { + + preparedStatement.setInt(1, con.getContractID()); + preparedStatement.setString(2, con.getName()); + preparedStatement.setInt(3, con.getMobbaseID()); + preparedStatement.setInt(4, con.getClassID()); + preparedStatement.setInt(5, (con.getVendorDialog() != null) ? con.getVendorDialog().getObjectUUID() : 0); + preparedStatement.setInt(6, con.getIconID()); + preparedStatement.setInt(8, con.getObjectUUID()); + preparedStatement.setLong(7, con.getAllowedBuildings().toLong()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } } diff --git a/src/engine/objects/Contract.java b/src/engine/objects/Contract.java index c31f59af..2fb2626d 100644 --- a/src/engine/objects/Contract.java +++ b/src/engine/objects/Contract.java @@ -138,8 +138,8 @@ public class Contract extends AbstractGameObject { //Specify if trainer, merchant, banker, etc via classID private void setBools() { - DbManager.ContractQueries.GET_GENERIC_INVENTORY(this); - DbManager.ContractQueries.GET_SELL_LISTS(this); + DbManager.ContractQueries.LOAD_CONTRACT_INVENTORY(this); + DbManager.ContractQueries.LOAD_SELL_LIST_FOR_CONTRACT(this); this.isTrainer = this.classID > 2499 && this.classID < 3050 || this.classID == 2028; From 82d80ebc4d833d184a5a60ab50e8990ec4ec0372 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sun, 21 May 2023 17:27:45 -0400 Subject: [PATCH 044/109] Refactor to remove abstraction --- .../db/handlers/dbCSSessionHandler.java | 96 +++++++++++++------ 1 file changed, 68 insertions(+), 28 deletions(-) diff --git a/src/engine/db/handlers/dbCSSessionHandler.java b/src/engine/db/handlers/dbCSSessionHandler.java index 0fb5f1d4..f14def21 100644 --- a/src/engine/db/handlers/dbCSSessionHandler.java +++ b/src/engine/db/handlers/dbCSSessionHandler.java @@ -17,6 +17,8 @@ import engine.util.StringUtils; import org.pmw.tinylog.Logger; import java.net.InetAddress; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -28,52 +30,90 @@ public class dbCSSessionHandler extends dbHandlerBase { } public boolean ADD_CSSESSION(String secKey, Account acc, InetAddress inet, String machineID) { - prepareCallable("INSERT INTO `dyn_session` (`secretKey`, `accountID`, `discordAccount`, `sessionIP`, machineID) VALUES (?,?,?,INET_ATON(?),?)"); - setString(1, secKey); - setLong(2, acc.getObjectUUID()); - setString(3, acc.discordAccount); - setString(4, StringUtils.InetAddressToClientString(inet)); - setString(5, machineID); - return (executeUpdate() != 0); - } + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_session` (`secretKey`, `accountID`, `discordAccount`, `sessionIP`, machineID) VALUES (?,?,?,INET_ATON(?),?)")) { + + preparedStatement.setString(1, secKey); + preparedStatement.setLong(2, acc.getObjectUUID()); + preparedStatement.setString(3, acc.discordAccount); + preparedStatement.setString(4, StringUtils.InetAddressToClientString(inet)); + preparedStatement.setString(5, machineID); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + + } public boolean DELETE_UNUSED_CSSESSION(String secKey) { - prepareCallable("DELETE FROM `dyn_session` WHERE `secretKey`=? && `characterID` IS NULL"); - setString(1, secKey); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_session` WHERE `secretKey`=? && `characterID` IS NULL")) { + + preparedStatement.setString(1, secKey); + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } public boolean DELETE_CSSESSION(String secKey) { - prepareCallable("DELETE FROM `dyn_session` WHERE `secretKey`=?"); - setString(1, secKey); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_session` WHERE `secretKey`=?")) { + + preparedStatement.setString(1, secKey); + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } public boolean UPDATE_CSSESSION(String secKey, int charID) { - prepareCallable("UPDATE `dyn_session` SET `characterID`=? WHERE `secretKey`=?"); - setInt(1, charID); - setString(2, secKey); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_session` SET `characterID`=? WHERE `secretKey`=?")) { + + preparedStatement.setInt(1, charID); + preparedStatement.setString(2, secKey); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } public CSSession GET_CSSESSION(String secKey) { + CSSession css = null; - prepareCallable("SELECT `accountID`, `characterID`, `machineID` FROM `dyn_session` WHERE `secretKey`=?"); - setString(1, secKey); - try { - ResultSet rs = executeQuery(); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `accountID`, `characterID`, `machineID` FROM `dyn_session` WHERE `secretKey`=?")) { - if (rs.next()) { + preparedStatement.setString(1, secKey); + ResultSet rs = preparedStatement.executeQuery(); + + if (rs.next()) css = new CSSession(secKey, DbManager.AccountQueries.GET_ACCOUNT(rs.getInt("accountID")), PlayerCharacter.getPlayerCharacter(rs .getInt("characterID")), getString("machineID")); - } - rs.close(); + } catch (SQLException e) { - Logger.error("Error with seckey: " + secKey); - } finally { - closeCallable(); + Logger.error(e); } + return css; } } From 4749186d86993250cef745a99242653d47a03d65 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sun, 21 May 2023 17:29:45 -0400 Subject: [PATCH 045/109] bugfix: missing break. --- src/engine/db/handlers/dbEffectsBaseHandler.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/engine/db/handlers/dbEffectsBaseHandler.java b/src/engine/db/handlers/dbEffectsBaseHandler.java index b2452eb9..5b030993 100644 --- a/src/engine/db/handlers/dbEffectsBaseHandler.java +++ b/src/engine/db/handlers/dbEffectsBaseHandler.java @@ -225,6 +225,7 @@ public class dbEffectsBaseHandler extends dbHandlerBase { break; case PassiveDefense: abstractEffectModifier = new PassiveDefenseEffectModifier(rs); + break; case PowerCost: abstractEffectModifier = new PowerCostEffectModifier(rs); break; From df1b0e3f0f56d907ffb626a175e445068ee6901d Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sun, 21 May 2023 17:34:31 -0400 Subject: [PATCH 046/109] Refactor to remove abstraction. --- .../dbEffectsResourceCostHandler.java | 27 +++++++++++++++---- src/engine/objects/Item.java | 1 - 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/src/engine/db/handlers/dbEffectsResourceCostHandler.java b/src/engine/db/handlers/dbEffectsResourceCostHandler.java index cd86d0b6..36e58b35 100644 --- a/src/engine/db/handlers/dbEffectsResourceCostHandler.java +++ b/src/engine/db/handlers/dbEffectsResourceCostHandler.java @@ -9,8 +9,14 @@ package engine.db.handlers; +import engine.gameManager.DbManager; import engine.objects.EffectsResourceCosts; +import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.ArrayList; public class dbEffectsResourceCostHandler extends dbHandlerBase { @@ -19,12 +25,23 @@ public class dbEffectsResourceCostHandler extends dbHandlerBase { this.localClass = EffectsResourceCosts.class; this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); } - - public ArrayList GET_ALL_EFFECT_RESOURCES(String idString) { - prepareCallable("SELECT * FROM `static_power_effectcost` WHERE `IDString` = ?"); - setString(1, idString); - return getObjectList(); + + ArrayList effectsResourceCosts = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_power_effectcost` WHERE `IDString` = ?")) { + + preparedStatement.setString(1, idString); + + ResultSet rs = preparedStatement.executeQuery(); + effectsResourceCosts = getObjectsFromRs(rs, 1000); + + } catch (SQLException e) { + Logger.error(e); + } + + return effectsResourceCosts; } } diff --git a/src/engine/objects/Item.java b/src/engine/objects/Item.java index ddabd85f..add14aa3 100644 --- a/src/engine/objects/Item.java +++ b/src/engine/objects/Item.java @@ -1062,7 +1062,6 @@ public float getBonusPercent(ModType modType, SourceType sourceType) { this.magicValue = this.getItemBase().getBaseValue() + calcMagicValue(); return; } - ConcurrentHashMap enchantList = DbManager.EnchantmentQueries.GET_ENCHANTMENTS_FOR_ITEM(this.getObjectUUID()); From db3f97eccfdac68f187780a0c32a631b2b50c6ee Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sun, 21 May 2023 17:50:44 -0400 Subject: [PATCH 047/109] Refactor to remove abstraction. --- .../db/handlers/dbEnchantmentHandler.java | 62 +++++++++++++------ 1 file changed, 43 insertions(+), 19 deletions(-) diff --git a/src/engine/db/handlers/dbEnchantmentHandler.java b/src/engine/db/handlers/dbEnchantmentHandler.java index 383f3d8c..a80a771c 100644 --- a/src/engine/db/handlers/dbEnchantmentHandler.java +++ b/src/engine/db/handlers/dbEnchantmentHandler.java @@ -9,9 +9,12 @@ package engine.db.handlers; +import engine.gameManager.DbManager; import engine.server.MBServerStatics; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.concurrent.ConcurrentHashMap; @@ -19,33 +22,54 @@ import java.util.concurrent.ConcurrentHashMap; public class dbEnchantmentHandler extends dbHandlerBase { public ConcurrentHashMap GET_ENCHANTMENTS_FOR_ITEM(final int id) { + ConcurrentHashMap enchants = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW); - prepareCallable("SELECT * FROM `dyn_item_enchantment` WHERE `ItemID`=?;"); - setLong(1, (long)id); - try { - ResultSet resultSet = executeQuery(); - while (resultSet.next()) - enchants.put(resultSet.getString("powerAction"), resultSet.getInt("rank")); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_item_enchantment` WHERE `ItemID`=?;")) { + + preparedStatement.setLong(1, (long) id); + + ResultSet rs = preparedStatement.executeQuery(); + + while (rs.next()) + enchants.put(rs.getString("powerAction"), rs.getInt("rank")); + } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } finally { - closeCallable(); + Logger.error(e); } + return enchants; } public boolean CREATE_ENCHANTMENT_FOR_ITEM(long itemID, String powerAction, int rank) { - prepareCallable("INSERT INTO `dyn_item_enchantment` (`itemID`, `powerAction`, `rank`) VALUES (?, ?, ?);"); - setLong(1, itemID); - setString(2, powerAction); - setInt(3, rank); - return (executeUpdate() != 0); - } - public boolean CLEAR_ENCHANTMENTS(long itemID) { - prepareCallable("DELETE FROM `dyn_item_enchantment` WHERE `itemID`=?;"); - setLong(1, itemID); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_item_enchantment` (`itemID`, `powerAction`, `rank`) VALUES (?, ?, ?);")) { + + preparedStatement.setLong(1, itemID); + preparedStatement.setString(2, powerAction); + preparedStatement.setInt(3, rank); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } + public boolean CLEAR_ENCHANTMENTS(long itemID) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_item_enchantment` WHERE `itemID`=?;")) { + + preparedStatement.setLong(1, itemID); + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } } From 6ce964ef18754ee2cae9ac441cdd3c4051b278b2 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sun, 21 May 2023 17:53:21 -0400 Subject: [PATCH 048/109] Unnecessary cast --- src/engine/db/handlers/dbEnchantmentHandler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/engine/db/handlers/dbEnchantmentHandler.java b/src/engine/db/handlers/dbEnchantmentHandler.java index a80a771c..61ab7a3d 100644 --- a/src/engine/db/handlers/dbEnchantmentHandler.java +++ b/src/engine/db/handlers/dbEnchantmentHandler.java @@ -28,7 +28,7 @@ public class dbEnchantmentHandler extends dbHandlerBase { try (Connection connection = DbManager.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_item_enchantment` WHERE `ItemID`=?;")) { - preparedStatement.setLong(1, (long) id); + preparedStatement.setLong(1, id); ResultSet rs = preparedStatement.executeQuery(); From 8cb0e66bff55f70471efa00bd76478332d7c36ca Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sun, 21 May 2023 20:13:00 -0400 Subject: [PATCH 049/109] Refactor to remove abstraction --- src/engine/db/handlers/dbGuildHandler.java | 203 ++++++++++++++------- src/engine/devcmd/cmds/GuildListCmd.java | 105 ----------- src/engine/gameManager/DevCmdManager.java | 1 - 3 files changed, 134 insertions(+), 175 deletions(-) delete mode 100644 src/engine/devcmd/cmds/GuildListCmd.java diff --git a/src/engine/db/handlers/dbGuildHandler.java b/src/engine/db/handlers/dbGuildHandler.java index 49dc05f5..bed92b74 100644 --- a/src/engine/db/handlers/dbGuildHandler.java +++ b/src/engine/db/handlers/dbGuildHandler.java @@ -17,8 +17,7 @@ import engine.server.MBServerStatics; import org.joda.time.DateTime; import org.pmw.tinylog.Logger; -import java.sql.ResultSet; -import java.sql.SQLException; +import java.sql.*; import java.util.ArrayList; public class dbGuildHandler extends dbHandlerBase { @@ -29,96 +28,129 @@ public class dbGuildHandler extends dbHandlerBase { } public int BANISH_FROM_GUILD_OFFLINE(final int target, boolean sourceIsGuildLeader) { - if (!sourceIsGuildLeader) //one IC cannot banish another IC - prepareCallable("UPDATE `obj_character` SET `guildUID`=NULL, `guild_isInnerCouncil`=0, `guild_isTaxCollector`=0," - + " `guild_isRecruiter`=0, `guild_isFullMember`=0, `guild_title`=0 WHERE `UID`=? && `guild_isInnerCouncil`=0"); + + String queryString; + int rowCount; + + // Only a Guild Leader can remove inner council + + if (sourceIsGuildLeader) + queryString = "UPDATE `obj_character` SET `guildUID`=NULL, `guild_isInnerCouncil`=0, `guild_isTaxCollector`=0," + + " `guild_isRecruiter`=0, `guild_isFullMember`=0, `guild_title`=0 WHERE `UID`=?"; else - prepareCallable("UPDATE `obj_character` SET `guildUID`=NULL, `guild_isInnerCouncil`=0, `guild_isTaxCollector`=0," - + " `guild_isRecruiter`=0, `guild_isFullMember`=0, `guild_title`=0 WHERE `UID`=?"); - setLong(1, (long) target); - return executeUpdate(); - } + queryString = "UPDATE `obj_character` SET `guildUID`=NULL, `guild_isInnerCouncil`=0, `guild_isTaxCollector`=0," + + " `guild_isRecruiter`=0, `guild_isFullMember`=0, `guild_title`=0 WHERE `UID`=? && `guild_isInnerCouncil`=0"; + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement(queryString)) { + + preparedStatement.setLong(1, target); + rowCount = preparedStatement.executeUpdate(); + + } catch (SQLException e) { + Logger.error(e); + return 0; + } + + return rowCount; + } public boolean ADD_TO_BANISHED_FROM_GUILDLIST(int target, long characterID) { - prepareCallable("INSERT INTO `dyn_guild_banishlist` (`GuildID`, `CharacterID`) VALUES (?,?)"); - setLong(1, (long) target); - setLong(2, characterID); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_guild_banishlist` (`GuildID`, `CharacterID`) VALUES (?,?)")) { + + preparedStatement.setLong(1, (long) target); + preparedStatement.setLong(2, characterID); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } public boolean REMOVE_FROM_BANISH_LIST(int target, long characterID) { - prepareCallable("DELETE FROM `dyn_guild_banishlist` (`GuildID`, `CharacterID`) VALUES (?,?)"); - setLong(1, (long) target); - setLong(2, characterID); - return (executeUpdate() > 0); - } - public boolean ADD_TO_GUILDHISTORY(int target, PlayerCharacter pc, DateTime historyDate, GuildHistoryType historyType) { - prepareCallable("INSERT INTO `dyn_character_guildhistory` (`GuildID`, `CharacterID`, `historyDate`, `historyType`) VALUES (?,?,?,?)"); - setLong(1, (long) target); - setLong(2, pc.getObjectUUID()); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_guild_banishlist` (`GuildID`, `CharacterID`) VALUES (?,?)")) { - if (historyDate == null) - setNULL(3, java.sql.Types.DATE); - else - setTimeStamp(3, historyDate.getMillis()); - setString(4,historyType.name()); - return (executeUpdate() > 0); - } + preparedStatement.setLong(1, (long) target); + preparedStatement.setLong(2, characterID); - //TODO Need to get this working. - public ArrayList GET_GUILD_HISTORY_OF_PLAYER(final int id) { - prepareCallable("SELECT g.* FROM `obj_guild` g, `dyn_character_guildhistory` l WHERE g.`UID` = l.`GuildID` && l.`CharacterID` = ?"); - setLong(1, (long) id); - return getObjectList(); + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } - public String GET_GUILD_LIST(int guildType) { + public boolean ADD_TO_GUILDHISTORY(int target, PlayerCharacter playerCharacter, DateTime historyDate, GuildHistoryType historyType) { - String newLine = System.getProperty("line.separator"); - String outputStr = null; - ResultSet resultSet; + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_guildhistory` (`GuildID`, `CharacterID`, `historyDate`, `historyType`) VALUES (?,?,?,?)")) { - // Setup and execute stored procedure + preparedStatement.setLong(1, target); + preparedStatement.setLong(2, playerCharacter.getObjectUUID()); - prepareCallable("CALL `guild_GETLIST`(?)"); - setInt(1, guildType); - resultSet = executeQuery(); + if (historyDate == null) + preparedStatement.setNull(3, java.sql.Types.DATE); + else + preparedStatement.setTimestamp(3, new Timestamp(historyDate.getMillis())); - // Build formatted string with data from query + preparedStatement.setString(4, historyType.name()); - outputStr += newLine; - outputStr += String.format("%-10s %-30s %-10s %-10s", "UUID", "Name", "GL UUID", "TOL_UUID"); - outputStr += newLine; + return (preparedStatement.executeUpdate() > 0); - try { + } catch (SQLException e) { + Logger.error(e); + return false; + } - while (resultSet.next()) { + } - outputStr += String.format("%-10d %-30s %-10d %-10d", resultSet.getInt(1), - resultSet.getString(2), resultSet.getInt(3), resultSet.getInt(4)); - outputStr += newLine; + //TODO Need to get this working. + public ArrayList GET_GUILD_HISTORY_OF_PLAYER(final int id) { - } + ArrayList guildList = null; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT g.* FROM `obj_guild` g, `dyn_character_guildhistory` l WHERE g.`UID` = l.`GuildID` && l.`CharacterID` = ?")) { + + preparedStatement.setLong(1, id); - // Exception handling + ResultSet rs = preparedStatement.executeQuery(); + guildList = getObjectsFromRs(rs, 20); } catch (SQLException e) { - Logger.error( e.getMessage()); - } finally { - closeCallable(); + Logger.error(e); } - return outputStr; + return guildList; } public ArrayList GET_GUILD_ALLIES(final int id) { - prepareCallable("SELECT g.* FROM `obj_guild` g, `dyn_guild_allianceenemylist` l " - + "WHERE l.isAlliance = 1 && l.OtherGuildID = g.UID && l.GuildID=?"); - setLong(1, (long) id); - return getObjectList(); + + ArrayList guildList = null; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT g.* FROM `obj_guild` g, `dyn_guild_allianceenemylist` l " + + "WHERE l.isAlliance = 1 && l.OtherGuildID = g.UID && l.GuildID=?")) { + + preparedStatement.setLong(1, id); + + ResultSet rs = preparedStatement.executeQuery(); + guildList = getObjectsFromRs(rs, 20); + + } catch (SQLException e) { + Logger.error(e); + } + + return guildList; } @@ -136,16 +168,49 @@ public class dbGuildHandler extends dbHandlerBase { } public ArrayList GET_GUILD_ENEMIES(final int id) { - prepareCallable("SELECT g.* FROM `obj_guild` g, `dyn_guild_allianceenemylist` l " - + "WHERE l.isAlliance = 0 && l.OtherGuildID = g.UID && l.GuildID=?"); - setLong(1, (long) id); - return getObjectList(); + + ArrayList guildList = null; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT g.* FROM `obj_guild` g, `dyn_guild_allianceenemylist` l " + + "WHERE l.isAlliance = 0 && l.OtherGuildID = g.UID && l.GuildID=?")) { + + preparedStatement.setLong(1, id); + + ResultSet rs = preparedStatement.executeQuery(); + guildList = getObjectsFromRs(rs, 20); + + } catch (SQLException e) { + Logger.error(e); + } + + return guildList; + } public ArrayList GET_GUILD_KOS_CHARACTER(final int id) { - prepareCallable("SELECT c.* FROM `obj_character` c, `dyn_guild_characterkoslist` l WHERE c.`char_isActive` = 1 && l.`KOSCharacterID` = c.`UID` && l.`GuildID`=?"); - setLong(1, (long) id); - return getObjectList(); + + ArrayList kosList = null; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT c.* FROM `obj_character` c, `dyn_guild_characterkoslist` l WHERE c.`char_isActive` = 1 && l.`KOSCharacterID` = c.`UID` && l.`GuildID`=?")) { + + preparedStatement.setLong(1, id); + ResultSet rs = preparedStatement.executeQuery(); + + while (rs.next()) { + int playerUUID = rs.getInt(1); + PlayerCharacter kosPlayer = PlayerCharacter.getPlayerCharacter(playerUUID); + + if (kosPlayer != null) + kosList.add(kosPlayer); + } + + } catch (SQLException e) { + Logger.error(e); + } + + return kosList; } public ArrayList GET_GUILD_KOS_GUILD(final int id) { diff --git a/src/engine/devcmd/cmds/GuildListCmd.java b/src/engine/devcmd/cmds/GuildListCmd.java deleted file mode 100644 index 71437576..00000000 --- a/src/engine/devcmd/cmds/GuildListCmd.java +++ /dev/null @@ -1,105 +0,0 @@ -// • ▌ ▄ ·. ▄▄▄· ▄▄ • ▪ ▄▄· ▄▄▄▄· ▄▄▄· ▐▄▄▄ ▄▄▄ . -// ·██ ▐███▪▐█ ▀█ ▐█ ▀ ▪██ ▐█ ▌▪▐█ ▀█▪▐█ ▀█ •█▌ ▐█▐▌· -// ▐█ ▌▐▌▐█·▄█▀▀█ ▄█ ▀█▄▐█·██ ▄▄▐█▀▀█▄▄█▀▀█ ▐█▐ ▐▌▐▀▀▀ -// ██ ██▌▐█▌▐█ ▪▐▌▐█▄▪▐█▐█▌▐███▌██▄▪▐█▐█ ▪▐▌██▐ █▌▐█▄▄▌ -// ▀▀ █▪▀▀▀ ▀ ▀ ·▀▀▀▀ ▀▀▀·▀▀▀ ·▀▀▀▀ ▀ ▀ ▀▀ █▪ ▀▀▀ -// Magicbane Emulator Project © 2013 - 2022 -// www.magicbane.com - - -package engine.devcmd.cmds; - -import engine.devcmd.AbstractDevCmd; -import engine.gameManager.DbManager; -import engine.objects.AbstractGameObject; -import engine.objects.PlayerCharacter; - - -/** - * @author - * Summary: Lists UID, Name and GL UID of either - * Player or NPC sovereign guilds - */ - -public class GuildListCmd extends AbstractDevCmd { - - // Instance variables - - private int _guildType; // 0 = Player : 1 = NPC sovereign guilds - private String outputStr = null; - - public GuildListCmd() { - super("guildlist"); - } - - - // AbstractDevCmd Overridden methods - - @Override - protected void _doCmd(PlayerCharacter pc, String[] args, - AbstractGameObject target) { - - if(validateUserInput(args) == false) { - this.sendUsage(pc); - return; - } - - parseUserInput(args); - - // Execute stored procedure - - outputStr = DbManager.GuildQueries.GET_GUILD_LIST(_guildType); - - // Send results to user - - throwbackInfo(pc, outputStr); - - } - - @Override - protected String _getHelpString() { - return "Lists guild info for sovereign guilds"; - } - - @Override - protected String _getUsageString() { - return "/guildlist npc|player"; - } - - // Class methods - - private static boolean validateUserInput(String[] userInput) { - - int stringIndex; - String commandSet = "npcplayer"; - - // incorrect number of arguments test - - if (userInput.length != 1) - return false; - - // Test of game object type argument - - stringIndex = commandSet.indexOf(userInput[0].toLowerCase()); - - return stringIndex != -1; - } - - private void parseUserInput(String[] userInput) { - - // Build mask from user input - - switch (userInput[0].toLowerCase()) { - case "npc": - _guildType = 1; - break; - case "player": - _guildType = 0; - break; - default: - break; - } - - } - -} diff --git a/src/engine/gameManager/DevCmdManager.java b/src/engine/gameManager/DevCmdManager.java index 74a326d2..8e2ecf82 100644 --- a/src/engine/gameManager/DevCmdManager.java +++ b/src/engine/gameManager/DevCmdManager.java @@ -112,7 +112,6 @@ public enum DevCmdManager { DevCmdManager.registerDevCmd(new DecachePlayerCmd()); DevCmdManager.registerDevCmd(new AuditMobsCmd()); DevCmdManager.registerDevCmd(new ChangeNameCmd()); - DevCmdManager.registerDevCmd(new GuildListCmd()); DevCmdManager.registerDevCmd(new SetGuildCmd()); DevCmdManager.registerDevCmd(new SetOwnerCmd()); DevCmdManager.registerDevCmd(new NetDebugCmd()); From 1cd4617c69e559f461d06d233acb1eb2ed1a929b Mon Sep 17 00:00:00 2001 From: MagicBot Date: Sun, 21 May 2023 20:26:53 -0400 Subject: [PATCH 050/109] Refactor to remove abstraction --- src/engine/db/handlers/dbGuildHandler.java | 98 ++++++++++++++-------- 1 file changed, 65 insertions(+), 33 deletions(-) diff --git a/src/engine/db/handlers/dbGuildHandler.java b/src/engine/db/handlers/dbGuildHandler.java index bed92b74..4af738b8 100644 --- a/src/engine/db/handlers/dbGuildHandler.java +++ b/src/engine/db/handlers/dbGuildHandler.java @@ -214,39 +214,89 @@ public class dbGuildHandler extends dbHandlerBase { } public ArrayList GET_GUILD_KOS_GUILD(final int id) { - prepareCallable("SELECT g.* FROM `obj_guild` g, `dyn_guild_guildkoslist` l " - + "WHERE l.KOSGuildID = g.UID && l.GuildID = ?"); - setLong(1, (long) id); - return getObjectList(); + + ArrayList guildList = null; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT g.* FROM `obj_guild` g, `dyn_guild_guildkoslist` l " + + "WHERE l.KOSGuildID = g.UID && l.GuildID = ?")) { + + preparedStatement.setLong(1, id); + + ResultSet rs = preparedStatement.executeQuery(); + guildList = getObjectsFromRs(rs, 20); + + } catch (SQLException e) { + Logger.error(e); + } + + return guildList; } public ArrayList GET_SUB_GUILDS(final int guildID) { - prepareCallable("SELECT `obj_guild`.*, `object`.`parent` FROM `object` INNER JOIN `obj_guild` ON `obj_guild`.`UID` = `object`.`UID` WHERE `object`.`parent` = ?;"); - setInt(1, guildID); - return getObjectList(); - } + ArrayList guildList = null; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_guild`.*, `object`.`parent` FROM `object` INNER JOIN `obj_guild` ON `obj_guild`.`UID` = `object`.`UID` WHERE `object`.`parent` = ?;")) { + + preparedStatement.setInt(1, guildID); + + ResultSet rs = preparedStatement.executeQuery(); + guildList = getObjectsFromRs(rs, 20); + + } catch (SQLException e) { + Logger.error(e); + } + + return guildList; + } public Guild GET_GUILD(int id) { + Guild guild = (Guild) DbManager.getFromCache(Enum.GameObjectType.Guild, id); + if (guild != null) return guild; + if (id == 0) return Guild.getErrantGuild(); - prepareCallable("SELECT `obj_guild`.*, `object`.`parent` FROM `obj_guild` INNER JOIN `object` ON `object`.`UID` = `obj_guild`.`UID` WHERE `object`.`UID`=?"); - setLong(1, (long) id); - return (Guild) getObjectSingle(id); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_guild`.*, `object`.`parent` FROM `obj_guild` INNER JOIN `object` ON `object`.`UID` = `obj_guild`.`UID` WHERE `object`.`UID`=?")) { + + preparedStatement.setLong(1, id); + + ResultSet rs = preparedStatement.executeQuery(); + guild = (Guild) getObjectFromRs(rs); + + } catch (SQLException e) { + Logger.error(e); + } + return guild; + } public ArrayList GET_ALL_GUILDS() { - - prepareCallable("SELECT `obj_guild`.*, `object`.`parent` FROM `obj_guild` INNER JOIN `object` ON `object`.`UID` = `obj_guild`.`UID`"); - - return getObjectList(); + + ArrayList guildList = null; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_guild`.*, `object`.`parent` FROM `obj_guild` INNER JOIN `object` ON `object`.`UID` = `obj_guild`.`UID`")) { + + ResultSet rs = preparedStatement.executeQuery(); + guildList = getObjectsFromRs(rs, 20); + + } catch (SQLException e) { + Logger.error(e); + } + return guildList; } public boolean IS_CREST_UNIQUE(final GuildTag gt) { + boolean valid = false; + if (gt.backgroundColor01 == gt.backgroundColor02) { //both background colors the same, ignore backgroundDesign prepareCallable("SELECT `name` FROM `obj_guild` WHERE `backgroundColor01`=? && `backgroundColor02`=? && `symbolColor`=? && `symbol`=?;"); @@ -274,23 +324,6 @@ public class dbGuildHandler extends dbHandlerBase { return valid; } - public String SET_PROPERTY(final Guild g, String name, Object new_value) { - prepareCallable("CALL guild_SETPROP(?,?,?)"); - setLong(1, (long) g.getObjectUUID()); - setString(2, name); - setString(3, String.valueOf(new_value)); - return getResult(); - } - - public String SET_PROPERTY(final Guild g, String name, Object new_value, Object old_value) { - prepareCallable("CALL guild_GETSETPROP(?,?,?,?)"); - setLong(1, (long) g.getObjectUUID()); - setString(2, name); - setString(3, String.valueOf(new_value)); - setString(4, String.valueOf(old_value)); - return getResult(); - } - public boolean SET_GUILD_OWNED_CITY(int guildID, int cityID) { prepareCallable("UPDATE `obj_guild` SET `ownedCity`=? WHERE `UID`=?"); setLong(1, (long) cityID); @@ -305,7 +338,6 @@ public class dbGuildHandler extends dbHandlerBase { return (executeUpdate() > 0); } - public boolean IS_NAME_UNIQUE(final String name) { boolean valid = false; prepareCallable("SELECT `name` FROM `obj_guild` WHERE `name`=?;"); From 135f66e46f0b37dc7752dacb9173e6cc0907a49a Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 05:11:55 -0400 Subject: [PATCH 051/109] Refactor to remove abstraction --- src/engine/db/handlers/dbBuildingHandler.java | 6 +- src/engine/db/handlers/dbGuildHandler.java | 272 ++++++++++++------ 2 files changed, 188 insertions(+), 90 deletions(-) diff --git a/src/engine/db/handlers/dbBuildingHandler.java b/src/engine/db/handlers/dbBuildingHandler.java index e247109f..c175e11a 100644 --- a/src/engine/db/handlers/dbBuildingHandler.java +++ b/src/engine/db/handlers/dbBuildingHandler.java @@ -40,7 +40,7 @@ public class dbBuildingHandler extends dbHandlerBase { ProtectionState protectionState, int currentGold, int rank, DateTime upgradeDate, int blueprintUUID, float w, float rotY) { - Building toCreate = null; + Building building = null; try (Connection connection = DbManager.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement("CALL `building_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,? ,? ,?, ?);")) { @@ -72,13 +72,13 @@ public class dbBuildingHandler extends dbHandlerBase { int objectUUID = (int) rs.getLong("UID"); if (objectUUID > 0) - toCreate = GET_BUILDINGBYUUID(objectUUID); + building = GET_BUILDINGBYUUID(objectUUID); } catch (SQLException e) { throw new RuntimeException(e); } - return toCreate; + return building; } public boolean DELETE_FROM_DATABASE(final Building b) { diff --git a/src/engine/db/handlers/dbGuildHandler.java b/src/engine/db/handlers/dbGuildHandler.java index 4af738b8..6efa854a 100644 --- a/src/engine/db/handlers/dbGuildHandler.java +++ b/src/engine/db/handlers/dbGuildHandler.java @@ -296,127 +296,218 @@ public class dbGuildHandler extends dbHandlerBase { public boolean IS_CREST_UNIQUE(final GuildTag gt) { boolean valid = false; + String queryString; + + // Ignore bg symbol if bg color is the same as fg color. + + if (gt.backgroundColor01 == gt.backgroundColor02) + queryString = "SELECT `name` FROM `obj_guild` WHERE `backgroundColor01`=? && `backgroundColor02`=? && `symbolColor`=? && `symbol`=?;"; + else + queryString = "SELECT `name` FROM `obj_guild` WHERE `backgroundColor01`=? && `backgroundColor02`=? && `symbolColor`=? && `backgroundDesign`=? && `symbol`=?;"; + + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement(queryString)) { + + if (gt.backgroundColor01 == gt.backgroundColor02) { + preparedStatement.setInt(1, gt.backgroundColor01); + preparedStatement.setInt(2, gt.backgroundColor02); + preparedStatement.setInt(3, gt.symbolColor); + preparedStatement.setInt(4, gt.symbol); + } else { + preparedStatement.setInt(1, gt.backgroundColor01); + preparedStatement.setInt(2, gt.backgroundColor02); + preparedStatement.setInt(3, gt.symbolColor); + preparedStatement.setInt(4, gt.backgroundDesign); + preparedStatement.setInt(5, gt.symbol); + } + + ResultSet rs = preparedStatement.executeQuery(); - if (gt.backgroundColor01 == gt.backgroundColor02) { - //both background colors the same, ignore backgroundDesign - prepareCallable("SELECT `name` FROM `obj_guild` WHERE `backgroundColor01`=? && `backgroundColor02`=? && `symbolColor`=? && `symbol`=?;"); - setInt(1, gt.backgroundColor01); - setInt(2, gt.backgroundColor02); - setInt(3, gt.symbolColor); - setInt(4, gt.symbol); - - } else { - prepareCallable("SELECT `name` FROM `obj_guild` WHERE `backgroundColor01`=? && `backgroundColor02`=? && `symbolColor`=? && `backgroundDesign`=? && `symbol`=?;"); - setInt(1, gt.backgroundColor01); - setInt(2, gt.backgroundColor02); - setInt(3, gt.symbolColor); - setInt(4, gt.backgroundDesign); - setInt(5, gt.symbol); - } - try { - ResultSet rs = executeQuery(); if (!rs.next()) valid = true; - rs.close(); + } catch (SQLException e) { - Logger.error(e.getMessage()); + Logger.error(e); } + return valid; } public boolean SET_GUILD_OWNED_CITY(int guildID, int cityID) { - prepareCallable("UPDATE `obj_guild` SET `ownedCity`=? WHERE `UID`=?"); - setLong(1, (long) cityID); - setLong(2, (long) guildID); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_guild` SET `ownedCity`=? WHERE `UID`=?")) { + + preparedStatement.setLong(1, cityID); + preparedStatement.setLong(2, guildID); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean SET_GUILD_LEADER(int objectUUID,int guildID) { - prepareCallable("UPDATE `obj_guild` SET `leaderUID`=? WHERE `UID`=?"); - setLong(1, (long) objectUUID); - setLong(2, (long) guildID); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_guild` SET `leaderUID`=? WHERE `UID`=?")) { + + preparedStatement.setLong(1, objectUUID); + preparedStatement.setLong(2, guildID); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } public boolean IS_NAME_UNIQUE(final String name) { + boolean valid = false; - prepareCallable("SELECT `name` FROM `obj_guild` WHERE `name`=?;"); - setString(1, name); - try { - ResultSet rs = executeQuery(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `name` FROM `obj_guild` WHERE `name`=?;")) { + + preparedStatement.setString(1, name); + ResultSet rs = preparedStatement.executeQuery(); + if (!rs.next()) valid = true; - rs.close(); + } catch (SQLException e) { - Logger.warn(e.getMessage()); + Logger.error(e); + return false; } return valid; - } public Guild SAVE_TO_DATABASE(Guild g) { - prepareCallable("CALL `guild_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); - - GuildTag gt = g.getGuildTag(); - if ( gt == null) + + Guild guild = null; + GuildTag guildTag = g.getGuildTag(); + + if (guildTag == null) return null; - setLong(1, MBServerStatics.worldUUID); - setLong(2, g.getGuildLeaderUUID()); - setString(3, g.getName()); - setInt(4, gt.backgroundColor01); - setInt(5, gt.backgroundColor02); - setInt(6, gt.symbolColor); - setInt(7, gt.backgroundDesign); - setInt(8 , gt.symbol); - setInt(9, g.getCharter()); - setString(10, g.getLeadershipType()); - setString(11, g.getMotto()); - - int objectUUID = (int) getUUID(); - if (objectUUID > 0) - return GET_GUILD(objectUUID); - return null; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL `guild_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) { + + preparedStatement.setLong(1, MBServerStatics.worldUUID); + preparedStatement.setLong(2, g.getGuildLeaderUUID()); + preparedStatement.setString(3, g.getName()); + preparedStatement.setInt(4, guildTag.backgroundColor01); + preparedStatement.setInt(5, guildTag.backgroundColor02); + preparedStatement.setInt(6, guildTag.symbolColor); + preparedStatement.setInt(7, guildTag.backgroundDesign); + preparedStatement.setInt(8, guildTag.symbol); + preparedStatement.setInt(9, g.getCharter()); + preparedStatement.setString(10, g.getLeadershipType()); + preparedStatement.setString(11, g.getMotto()); + + ResultSet rs = preparedStatement.executeQuery(); + + int objectUUID = (int) rs.getLong("UID"); + + if (objectUUID > 0) + guild = GET_GUILD(objectUUID); + + } catch (SQLException e) { + Logger.error(e); + } + return guild; } public boolean UPDATE_GUILD_RANK_OFFLINE(int target, int newRank, int guildId) { - prepareCallable("UPDATE `obj_character` SET `guild_title`=? WHERE `UID`=? && `guildUID`=?"); - setInt(1, newRank); - setInt(2, target); - setInt(3, guildId); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_title`=? WHERE `UID`=? && `guildUID`=?")) { + + preparedStatement.setInt(1, newRank); + preparedStatement.setInt(2, target); + preparedStatement.setInt(3, guildId); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean UPDATE_PARENT(int guildUID, int parentUID) { - prepareCallable("UPDATE `object` SET `parent`=? WHERE `UID`=?"); - setInt(1, parentUID); - setInt(2, guildUID); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `object` SET `parent`=? WHERE `UID`=?")) { + + preparedStatement.setInt(1, parentUID); + preparedStatement.setInt(2, guildUID); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } public int DELETE_GUILD(final Guild guild) { - prepareCallable("DELETE FROM `object` WHERE `UID` = ?"); - setLong(1, (long) guild.getObjectUUID()); - return executeUpdate(); + + int row_count = 0; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `object` WHERE `UID` = ?")) { + + preparedStatement.setLong(1, guild.getObjectUUID()); + row_count = preparedStatement.executeUpdate(); + + } catch (SQLException e) { + Logger.error(e); + } + return row_count; } public boolean UPDATE_MINETIME(int guildUID, int mineTime) { - prepareCallable("UPDATE `obj_guild` SET `mineTime`=? WHERE `UID`=?"); - setInt(1, mineTime); - setInt(2, guildUID); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_guild` SET `mineTime`=? WHERE `UID`=?")) { + + preparedStatement.setInt(1, mineTime); + preparedStatement.setInt(2, guildUID); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } public int UPDATE_GUILD_STATUS_OFFLINE(int target, boolean isInnerCouncil, boolean isRecruiter, boolean isTaxCollector, int guildId) { + int updateMask = 0; - prepareCallable("SELECT `guild_isInnerCouncil`, `guild_isTaxCollector`, `guild_isRecruiter` FROM `obj_character` WHERE `UID`=? && `guildUID`=?"); - setLong(1, (long) target); - setLong(2, (long) guildId); - try { - ResultSet rs = executeQuery(); + int row_count = 0; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `guild_isInnerCouncil`, `guild_isTaxCollector`, `guild_isRecruiter` FROM `obj_character` WHERE `UID`=? && `guildUID`=?")) { + + preparedStatement.setLong(1, target); + preparedStatement.setLong(2, guildId); + + ResultSet rs = preparedStatement.executeQuery(); //If the first query had no results, neither will the second + + //Determine what is different + if (rs.first()) { - //Determine what is different if (rs.getBoolean("guild_isInnerCouncil") != isInnerCouncil) updateMask |= 4; if (rs.getBoolean("guild_isRecruiter") != isRecruiter) @@ -424,19 +515,26 @@ public class dbGuildHandler extends dbHandlerBase { if (rs.getBoolean("guild_isTaxCollector") != isTaxCollector) updateMask |= 1; } - rs.close(); } catch (SQLException e) { - Logger.error( e.toString()); + Logger.error(e); } - prepareCallable("UPDATE `obj_character` SET `guild_isInnerCouncil`=?, `guild_isTaxCollector`=?, `guild_isRecruiter`=?, `guild_isFullMember`=? WHERE `UID`=? && `guildUID`=?"); - setBoolean(1, isInnerCouncil); - setBoolean(2, isRecruiter); - setBoolean(3, isTaxCollector); - setBoolean(4, ((updateMask > 0))); //If you are becoming an officer, or where an officer, your a full member... - setLong(5, (long) target); - setLong(6, (long) guildId); - return executeUpdate(); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_isInnerCouncil`=?, `guild_isTaxCollector`=?, `guild_isRecruiter`=?, `guild_isFullMember`=? WHERE `UID`=? && `guildUID`=?")) { + + preparedStatement.setBoolean(1, isInnerCouncil); + preparedStatement.setBoolean(2, isRecruiter); + preparedStatement.setBoolean(3, isTaxCollector); + preparedStatement.setBoolean(4, ((updateMask > 0))); //If you are becoming an officer, or where an officer, your a full member... + preparedStatement.setLong(5, target); + preparedStatement.setLong(6, guildId); + + row_count = preparedStatement.executeUpdate(); + + } catch (SQLException e) { + Logger.error(e); + } + return row_count; } From 3c9b624ca0e41a0865f3c321eab8831380db294f Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 05:55:33 -0400 Subject: [PATCH 052/109] Refactor to remove abstraction --- src/engine/db/handlers/dbGuildHandler.java | 178 +++++++++++++-------- 1 file changed, 111 insertions(+), 67 deletions(-) diff --git a/src/engine/db/handlers/dbGuildHandler.java b/src/engine/db/handlers/dbGuildHandler.java index 6efa854a..58a87441 100644 --- a/src/engine/db/handlers/dbGuildHandler.java +++ b/src/engine/db/handlers/dbGuildHandler.java @@ -542,62 +542,115 @@ public class dbGuildHandler extends dbHandlerBase { // It's not like this shit ever changes. public boolean updateDatabase(final Guild g) { - prepareCallable("UPDATE `obj_guild` SET `name`=?, `backgroundColor01`=?, `backgroundColor02`=?, `symbolColor`=?, `backgroundDesign`=?, `symbol`=?, `charter`=?, `motd`=?, `icMotd`=?, `nationMotd`=?, `leaderUID`=? WHERE `UID`=?"); - setString(1, g.getName()); - setInt(2, g.getGuildTag().backgroundColor01); - setInt(3, g.getGuildTag().backgroundColor02); - setInt(4, g.getGuildTag().symbolColor); - setInt(5, g.getGuildTag().backgroundDesign); - setInt(6, g.getGuildTag().symbol); - setInt(7, g.getCharter()); - setString(8, g.getMOTD()); - setString(9, g.getICMOTD()); - setString(10, ""); - setInt(11, g.getGuildLeaderUUID()); - setLong(12, (long) g.getObjectUUID()); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_guild` SET `name`=?, `backgroundColor01`=?, `backgroundColor02`=?, `symbolColor`=?, `backgroundDesign`=?, `symbol`=?, `charter`=?, `motd`=?, `icMotd`=?, `nationMotd`=?, `leaderUID`=? WHERE `UID`=?")) { + + preparedStatement.setString(1, g.getName()); + preparedStatement.setInt(2, g.getGuildTag().backgroundColor01); + preparedStatement.setInt(3, g.getGuildTag().backgroundColor02); + preparedStatement.setInt(4, g.getGuildTag().symbolColor); + preparedStatement.setInt(5, g.getGuildTag().backgroundDesign); + preparedStatement.setInt(6, g.getGuildTag().symbol); + preparedStatement.setInt(7, g.getCharter()); + preparedStatement.setString(8, g.getMOTD()); + preparedStatement.setString(9, g.getICMOTD()); + preparedStatement.setString(10, ""); + preparedStatement.setInt(11, g.getGuildLeaderUUID()); + preparedStatement.setLong(12, (long) g.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } + public boolean ADD_TO_ALLIANCE_LIST(final long sourceGuildID, final long targetGuildID, boolean isRecommended, boolean isAlly, String recommender) { - prepareCallable("INSERT INTO `dyn_guild_allianceenemylist` (`GuildID`, `OtherGuildID`,`isRecommended`, `isAlliance`, `recommender`) VALUES (?,?,?,?,?)"); - setLong(1, sourceGuildID); - setLong(2, targetGuildID); - setBoolean(3, isRecommended); - setBoolean(4, isAlly); - setString(5, recommender); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_guild_allianceenemylist` (`GuildID`, `OtherGuildID`,`isRecommended`, `isAlliance`, `recommender`) VALUES (?,?,?,?,?)")) { + + preparedStatement.setLong(1, sourceGuildID); + preparedStatement.setLong(2, targetGuildID); + preparedStatement.setBoolean(3, isRecommended); + preparedStatement.setBoolean(4, isAlly); + preparedStatement.setString(5, recommender); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean REMOVE_FROM_ALLIANCE_LIST(final long sourceGuildID, long targetGuildID) { - prepareCallable("DELETE FROM `dyn_guild_allianceenemylist` WHERE `GuildID`=? AND `OtherGuildID`=?"); - setLong(1, sourceGuildID); - setLong(2, targetGuildID); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_guild_allianceenemylist` WHERE `GuildID`=? AND `OtherGuildID`=?")) { + + preparedStatement.setLong(1, sourceGuildID); + preparedStatement.setLong(2, targetGuildID); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean UPDATE_RECOMMENDED(final long sourceGuildID, long targetGuildID) { - prepareCallable("UPDATE `dyn_guild_allianceenemylist` SET `isRecommended` = ? WHERE `GuildID`=? AND `OtherGuildID`=?"); - setByte(1,(byte)0); - setLong(2, sourceGuildID); - setLong(3, targetGuildID); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_guild_allianceenemylist` SET `isRecommended` = ? WHERE `GuildID`=? AND `OtherGuildID`=?")) { + + preparedStatement.setLong(1, sourceGuildID); + preparedStatement.setLong(2, targetGuildID); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean UPDATE_ALLIANCE(final long sourceGuildID, long targetGuildID, boolean isAlly) { - prepareCallable("UPDATE `dyn_guild_allianceenemylist` SET `isAlliance` = ? WHERE `GuildID`=? AND `OtherGuildID`=?"); - setBoolean(1,isAlly); - setLong(2, sourceGuildID); - setLong(3, targetGuildID); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_guild_allianceenemylist` SET `isAlliance` = ? WHERE `GuildID`=? AND `OtherGuildID`=?")) { + + preparedStatement.setLong(1, sourceGuildID); + preparedStatement.setLong(2, targetGuildID); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean UPDATE_ALLIANCE_AND_RECOMMENDED(final long sourceGuildID, long targetGuildID, boolean isAlly) { - prepareCallable("UPDATE `dyn_guild_allianceenemylist` SET `isRecommended` = ?, `isAlliance` = ? WHERE `GuildID`=? AND `OtherGuildID`=?"); - setByte(1,(byte)0); - setBoolean(2,isAlly); - setLong(3, sourceGuildID); - setLong(4, targetGuildID); - return (executeUpdate() > 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_guild_allianceenemylist` SET `isRecommended` = ?, `isAlliance` = ? WHERE `GuildID`=? AND `OtherGuildID`=?")) { + + preparedStatement.setByte(1, (byte) 0); + preparedStatement.setBoolean(2, isAlly); + preparedStatement.setLong(3, sourceGuildID); + preparedStatement.setLong(4, targetGuildID); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } public void LOAD_ALL_ALLIANCES_FOR_GUILD(Guild guild) { @@ -605,54 +658,45 @@ public class dbGuildHandler extends dbHandlerBase { if (guild == null) return; - prepareCallable("SELECT * FROM `dyn_guild_allianceenemylist` WHERE `GuildID` = ?"); - setInt(1,guild.getObjectUUID()); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_guild_allianceenemylist` WHERE `GuildID` = ?")) { - try { - ResultSet rs = executeQuery(); + preparedStatement.setInt(1, guild.getObjectUUID()); + ResultSet rs = preparedStatement.executeQuery(); - //shrines cached in rs for easy cache on creation. while (rs.next()) { GuildAlliances guildAlliance = new GuildAlliances(rs); guild.guildAlliances.put(guildAlliance.getAllianceGuild(), guildAlliance); } - } catch (SQLException e) { - Logger.error( e.getMessage()); - } finally { - closeCallable(); + Logger.error(e); } - } - public void LOAD_GUILD_HISTORY_FOR_PLAYER(PlayerCharacter pc) { + public static void LOAD_GUILD_HISTORY_FOR_PLAYER(PlayerCharacter playerCharacter) { - if (pc == null) + if (playerCharacter == null) return; - prepareCallable("SELECT * FROM `dyn_character_guildhistory` WHERE `CharacterID` = ?"); - setInt(1,pc.getObjectUUID()); + ArrayList guildList = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_guild_allianceenemylist` WHERE `GuildID` = ?")) { - try { - ArrayList tempList = new ArrayList<>(); - ResultSet rs = executeQuery(); + preparedStatement.setInt(1, playerCharacter.getObjectUUID()); + ResultSet rs = preparedStatement.executeQuery(); - //shrines cached in rs for easy cache on creation. while (rs.next()) { - GuildHistory guildHistory = new GuildHistory(rs); - tempList.add(guildHistory); + GuildHistory guildEntry = new GuildHistory(rs); + guildList.add(guildEntry); } - pc.setGuildHistory(tempList); - - } catch (SQLException e) { - Logger.error(e.getMessage()); - } finally { - closeCallable(); + Logger.error(e); } + playerCharacter.setGuildHistory(guildList); } //TODO uncomment this when finished with guild history warehouse integration From 609ee4621e7dfc770e4fbd38de9ea3641366d24b Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 05:58:30 -0400 Subject: [PATCH 053/109] Refactor to remove abstraction --- src/engine/db/handlers/dbKitHandler.java | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/engine/db/handlers/dbKitHandler.java b/src/engine/db/handlers/dbKitHandler.java index c0fa92ac..c1c0be74 100644 --- a/src/engine/db/handlers/dbKitHandler.java +++ b/src/engine/db/handlers/dbKitHandler.java @@ -9,8 +9,14 @@ package engine.db.handlers; +import engine.gameManager.DbManager; import engine.objects.Kit; +import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.ArrayList; public class dbKitHandler extends dbHandlerBase { @@ -21,8 +27,19 @@ public class dbKitHandler extends dbHandlerBase { } public ArrayList GET_ALL_KITS() { - prepareCallable("SELECT * FROM `static_rune_validkit`"); - return getObjectList(); + ArrayList kitList = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_validkit`")) { + + ResultSet rs = preparedStatement.executeQuery(); + kitList = getObjectsFromRs(rs, 20); + + } catch (SQLException e) { + Logger.error(e); + } + + return kitList; } } From ba76de72267d5b9a840f69710c884bdd80febcb0 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 06:15:19 -0400 Subject: [PATCH 054/109] Refactor to remove abstraction --- .../db/handlers/dbLootTableHandler.java | 203 ++++++++---------- 1 file changed, 95 insertions(+), 108 deletions(-) diff --git a/src/engine/db/handlers/dbLootTableHandler.java b/src/engine/db/handlers/dbLootTableHandler.java index 7e2d9f02..02854cb9 100644 --- a/src/engine/db/handlers/dbLootTableHandler.java +++ b/src/engine/db/handlers/dbLootTableHandler.java @@ -9,11 +9,14 @@ package engine.db.handlers; +import engine.gameManager.DbManager; import engine.loot.LootManager; import engine.objects.Item; import engine.objects.LootTable; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -23,206 +26,190 @@ public class dbLootTableHandler extends dbHandlerBase { } - public void populateLootGroups() { + int recordsRead = 0; - prepareCallable("SELECT `groupID`, `minRoll`, `maxRoll`, `lootTableID`, `pModTableID`, `sModTableID` FROM `static_lootgroups`"); - - try { - ResultSet rs = executeQuery(); - if (rs != null) - while (rs.next()) { - recordsRead++; - LootTable lootTable = LootTable.getLootGroup(rs.getInt("groupID")); - lootTable.addRow(rs.getFloat("minRoll"), rs.getFloat("maxRoll"), rs.getInt("lootTableID"), rs.getInt("pModTableID"), rs.getInt("sModTableID"), ""); - } - - Logger.info("read: " + recordsRead + " cached: " + LootTable.getLootGroups().size()); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `groupID`, `minRoll`, `maxRoll`, `lootTableID`, `pModTableID`, `sModTableID` FROM `static_lootgroups`")) { + + ResultSet rs = preparedStatement.executeQuery(); + + while (rs.next()) { + recordsRead++; + LootTable lootTable = LootTable.getLootGroup(rs.getInt("groupID")); + lootTable.addRow(rs.getFloat("minRoll"), rs.getFloat("maxRoll"), rs.getInt("lootTableID"), rs.getInt("pModTableID"), rs.getInt("sModTableID"), ""); + } + } catch (SQLException e) { - } finally { - closeCallable(); + Logger.error(e); } + + Logger.info("read: " + recordsRead + " cached: " + LootTable.getLootGroups().size()); } public void populateLootTables() { + int recordsRead = 0; - prepareCallable("SELECT `lootTable`, `minRoll`, `maxRoll`, `itemBaseUUID`, `minSpawn`, `maxSpawn` FROM `static_loottables`"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `lootTable`, `minRoll`, `maxRoll`, `itemBaseUUID`, `minSpawn`, `maxSpawn` FROM `static_loottables`")) { - try { - ResultSet rs = executeQuery(); - if (rs != null) - while (rs.next()) { - recordsRead++; - LootTable lootTable = LootTable.getLootTable(rs.getInt("lootTable")); - lootTable.addRow(rs.getFloat("minRoll"), rs.getFloat("maxRoll"), rs.getInt("itemBaseUUID"), rs.getInt("minSpawn"), rs.getInt("maxSpawn"), ""); - } + ResultSet rs = preparedStatement.executeQuery(); + + while (rs.next()) { + recordsRead++; + LootTable lootTable = LootTable.getLootTable(rs.getInt("lootTable")); + lootTable.addRow(rs.getFloat("minRoll"), rs.getFloat("maxRoll"), rs.getInt("itemBaseUUID"), rs.getInt("minSpawn"), rs.getInt("maxSpawn"), ""); + } - Logger.info("read: " + recordsRead + " cached: " + LootTable.getLootTables().size()); } catch (SQLException e) { - } finally { - closeCallable(); + Logger.error(e); } + + Logger.info("read: " + recordsRead + " cached: " + LootTable.getLootTables().size()); } public void populateModTables() { int recordsRead = 0; - prepareCallable("SELECT `modTable`,`minRoll`,`maxRoll`,`value`,`action` FROM `static_modtables`"); - - try { - ResultSet rs = executeQuery(); - if (rs != null) - while (rs.next()) { - recordsRead++; - LootTable lootTable = LootTable.getModTable(rs.getInt("modTable")); - lootTable.addRow(rs.getFloat("minRoll"), rs.getFloat("maxRoll"), rs.getInt("value"), 0, 0, rs.getString("action")); - } - Logger.info("read: " + recordsRead + " cached: " + LootTable.getModTables().size()); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `modTable`,`minRoll`,`maxRoll`,`value`,`action` FROM `static_modtables`")) { + + ResultSet rs = preparedStatement.executeQuery(); + + while (rs.next()) { + recordsRead++; + LootTable lootTable = LootTable.getModTable(rs.getInt("modTable")); + lootTable.addRow(rs.getFloat("minRoll"), rs.getFloat("maxRoll"), rs.getInt("value"), 0, 0, rs.getString("action")); + } + } catch (SQLException e) { - } finally { - closeCallable(); + Logger.error(e); } + + Logger.info("read: " + recordsRead + " cached: " + LootTable.getModTables().size()); } public void populateModGroups() { int recordsRead = 0; - prepareCallable("SELECT `modGroup`,`minRoll`,`maxRoll`,`subTableID` FROM `static_modgroups`"); - - try { - ResultSet rs = executeQuery(); - if (rs != null) - while (rs.next()) { - recordsRead++; - LootTable lootTable = LootTable.getModGroup(rs.getInt("modGroup")); - lootTable.addRow(rs.getFloat("minRoll"), rs.getFloat("maxRoll"), rs.getInt("subTableID"), 0, 0, ""); - } - Logger.info("read: " + recordsRead + " cached: " + LootTable.getModGroups().size()); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `modGroup`,`minRoll`,`maxRoll`,`subTableID` FROM `static_modgroups`")) { + + ResultSet rs = preparedStatement.executeQuery(); + + while (rs.next()) { + recordsRead++; + LootTable lootTable = LootTable.getModGroup(rs.getInt("modGroup")); + lootTable.addRow(rs.getFloat("minRoll"), rs.getFloat("maxRoll"), rs.getInt("subTableID"), 0, 0, ""); + } + } catch (SQLException e) { - } finally { - closeCallable(); + Logger.error(e); } + + Logger.info("read: " + recordsRead + " cached: " + LootTable.getModGroups().size()); } public void LOAD_ENCHANT_VALUES() { - prepareCallable("SELECT `IDString`, `minMod` FROM `static_power_effectmod` WHERE `modType` = ?"); - setString(1,"Value"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `IDString`, `minMod` FROM `static_power_effectmod` WHERE `modType` = ?")) { - try { - ResultSet rs = executeQuery(); - while (rs.next()) { + preparedStatement.setString(1, "Value"); + ResultSet rs = preparedStatement.executeQuery(); + + while (rs.next()) Item.addEnchantValue(rs.getString("IDString"), rs.getInt("minMod")); - } + } catch (SQLException e) { - Logger.error( e); - } finally { - closeCallable(); + Logger.error(e); } } public void LOAD_ALL_LOOTGROUPS() { + int recordsRead = 0; - prepareCallable("SELECT * FROM static_lootgroups"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_lootgroups")) { - try { - ResultSet rs = executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { LootManager.GenTableRow row = new LootManager.GenTableRow(rs); LootManager.AddGenTableRow(rs.getInt("groupID"), row); } - Logger.info( "read: " + recordsRead); - } catch (SQLException e) { - Logger.error( e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); + Logger.error(e); } + + Logger.info("read: " + recordsRead); } public void LOAD_ALL_LOOTTABLES() { int recordsRead = 0; - prepareCallable("SELECT * FROM static_loottables"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_loottables")) { - try { - ResultSet rs = executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { - recordsRead++; LootManager.ItemTableRow row = new LootManager.ItemTableRow(rs); - LootManager.AddItemTableRow(rs.getInt("lootTable"),row); + LootManager.AddItemTableRow(rs.getInt("lootTable"), row); } - Logger.info("read: " + recordsRead); - } catch (SQLException e) { - Logger.error( e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); + Logger.error(e); } + + Logger.info("read: " + recordsRead); } public void LOAD_ALL_MODGROUPS() { int recordsRead = 0; - prepareCallable("SELECT * FROM static_modgroups"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_modgroups")) { - try { - ResultSet rs = executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { - recordsRead++; - - LootManager.ModTypeTableRow mttr = new LootManager.ModTypeTableRow(rs); - LootManager.AddModTypeTableRow(rs.getInt("modGroup"), mttr); - + LootManager.ModTypeTableRow mttr = new LootManager.ModTypeTableRow(rs); + LootManager.AddModTypeTableRow(rs.getInt("modGroup"), mttr); } - Logger.info( "read: " + recordsRead); - } catch (SQLException e) { - Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); + Logger.error(e); } + Logger.info("read: " + recordsRead); } public void LOAD_ALL_MODTABLES() { int recordsRead = 0; - prepareCallable("SELECT * FROM static_modtables"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_modtables")) { - try { - ResultSet rs = executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { - recordsRead++; - try { LootManager.ModTableRow mtr = new LootManager.ModTableRow(rs); - LootManager.AddModTableRow(rs.getInt("modTable"),mtr); - } - catch(Exception ex){ - Logger.info("MOD TABLE ERROR: " + rs.getInt("modTable")); - } + LootManager.AddModTableRow(rs.getInt("modTable"), mtr); } - Logger.info( "read: " + recordsRead); - } catch (SQLException e) { - Logger.error( e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); + Logger.error(e); } + Logger.info("read: " + recordsRead); } } From 6ae6c91a71e8845affd7b16abfd718df37e38ede Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 06:17:40 -0400 Subject: [PATCH 055/109] Refactor to remove abstraction --- src/engine/db/handlers/dbMenuHandler.java | 25 ++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/src/engine/db/handlers/dbMenuHandler.java b/src/engine/db/handlers/dbMenuHandler.java index 426f4c4a..fcf7bfd4 100644 --- a/src/engine/db/handlers/dbMenuHandler.java +++ b/src/engine/db/handlers/dbMenuHandler.java @@ -9,8 +9,14 @@ package engine.db.handlers; +import engine.gameManager.DbManager; import engine.objects.MenuOption; +import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.ArrayList; public class dbMenuHandler extends dbHandlerBase { @@ -21,8 +27,21 @@ public class dbMenuHandler extends dbHandlerBase { } public ArrayList GET_MENU_OPTIONS(final int id) { - prepareCallable("SELECT * FROM `static_npc_menuoption` WHERE menuID = ?"); - setInt(1, id); - return getObjectList(); + + ArrayList menuOptions = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_menuoption` WHERE menuID = ?")) { + + preparedStatement.setInt(1, id); + + ResultSet rs = preparedStatement.executeQuery(); + menuOptions = getObjectsFromRs(rs, 1000); + + } catch (SQLException e) { + Logger.error(e); + } + + return menuOptions; } } From dc9a6fc82583749e8ca6c3602dd9f33e19fee288 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 06:25:51 -0400 Subject: [PATCH 056/109] Refactor to remove abstraction --- src/engine/db/handlers/dbMineHandler.java | 120 ++++++++++++++-------- 1 file changed, 80 insertions(+), 40 deletions(-) diff --git a/src/engine/db/handlers/dbMineHandler.java b/src/engine/db/handlers/dbMineHandler.java index eeca535b..c8e35d57 100644 --- a/src/engine/db/handlers/dbMineHandler.java +++ b/src/engine/db/handlers/dbMineHandler.java @@ -13,7 +13,12 @@ import engine.gameManager.DbManager; import engine.objects.Mine; import engine.objects.MineProduction; import engine.objects.Resource; +import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.ArrayList; public class dbMineHandler extends dbHandlerBase { @@ -29,68 +34,103 @@ public class dbMineHandler extends dbHandlerBase { return null; Mine mine = (Mine) DbManager.getFromCache(Enum.GameObjectType.Mine, id); + if (mine != null) return mine; - prepareCallable("SELECT `obj_building`.*, `object`.`parent` FROM `object` INNER JOIN `obj_building` ON `obj_building`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?;"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_building`.*, `object`.`parent` FROM `object` INNER JOIN `obj_building` ON `obj_building`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?;")) { + + preparedStatement.setLong(1, id); - setLong(1, (long) id); - return (Mine) getObjectSingle(id); + ResultSet rs = preparedStatement.executeQuery(); + mine = (Mine) getObjectFromRs(rs); + } catch (SQLException e) { + Logger.error(e); + } + return mine; } public ArrayList GET_ALL_MINES_FOR_SERVER() { - prepareCallable("SELECT `obj_mine`.*, `object`.`parent` FROM `object` INNER JOIN `obj_mine` ON `obj_mine`.`UID` = `object`.`UID`"); - return getObjectList(); + + ArrayList mines = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_mine`.*, `object`.`parent` FROM `object` INNER JOIN `obj_mine` ON `obj_mine`.`UID` = `object`.`UID`")) { + + ResultSet rs = preparedStatement.executeQuery(); + mines = getObjectsFromRs(rs, 1000); + + } catch (SQLException e) { + Logger.error(e); + } + return mines; } public boolean CHANGE_OWNER(Mine mine, int playerUID) { - prepareCallable("UPDATE `obj_mine` SET `mine_ownerUID`=? WHERE `UID`=?"); - setInt(1, playerUID); - setLong(2, (long) mine.getObjectUUID()); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_mine` SET `mine_ownerUID`=? WHERE `UID`=?")) { + + preparedStatement.setInt(1, playerUID); + preparedStatement.setLong(2, mine.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean CHANGE_RESOURCE(Mine mine, Resource resource) { - prepareCallable("UPDATE `obj_mine` SET `mine_resource`=? WHERE `UID`=?"); - setString(1, resource.name()); - setLong(2, (long) mine.getObjectUUID()); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_mine` SET `mine_resource`=? WHERE `UID`=?")) { + + preparedStatement.setString(1, resource.name()); + preparedStatement.setLong(2, mine.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean CHANGE_TYPE(Mine mine, MineProduction productionType) { - prepareCallable("UPDATE `obj_mine` SET `mine_type`=? WHERE `UID`=?"); - setString(1, productionType.name()); - setLong(2, (long) mine.getObjectUUID()); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_mine` SET `mine_type`=? WHERE `UID`=?")) { + + preparedStatement.setString(1, productionType.name()); + preparedStatement.setLong(2, mine.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } public boolean SET_FLAGS(Mine mine, int newFlags) { - prepareCallable("UPDATE `obj_mine` SET `flags`=? WHERE `UID`=?"); - setInt(1, newFlags); - setLong(2, (long) mine.getObjectUUID()); - return (executeUpdate() > 0); - } - public String SET_PROPERTY(final Mine m, String name, Object new_value) { - prepareCallable("CALL mine_SETPROP(?,?,?)"); - setLong(1, (long) m.getObjectUUID()); - setString(2, name); - setString(3, String.valueOf(new_value)); - return getResult(); - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_mine` SET `flags`=? WHERE `UID`=?")) { + + preparedStatement.setInt(1, newFlags); + preparedStatement.setLong(2, mine.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); - // Advance all the mine windows respective to the current day - // at boot time. This ensures that mines always go live - // no matter what date in the database - - public String SET_PROPERTY(final Mine m, String name, Object new_value, Object old_value) { - prepareCallable("CALL mine_GETSETPROP(?,?,?,?)"); - setLong(1, (long) m.getObjectUUID()); - setString(2, name); - setString(3, String.valueOf(new_value)); - setString(4, String.valueOf(old_value)); - return getResult(); + } catch (SQLException e) { + Logger.error(e); + return false; + } } } From 2cdb2fce422eaf465be1a343012f8be58fbf7c20 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 06:35:24 -0400 Subject: [PATCH 057/109] Refactor to remove abstraction --- src/engine/db/handlers/dbMobBaseHandler.java | 29 ++++-- src/engine/devcmd/cmds/RenameMobCmd.java | 101 ------------------- src/engine/gameManager/DevCmdManager.java | 1 - src/engine/objects/MobBase.java | 14 +-- 4 files changed, 23 insertions(+), 122 deletions(-) delete mode 100644 src/engine/devcmd/cmds/RenameMobCmd.java diff --git a/src/engine/db/handlers/dbMobBaseHandler.java b/src/engine/db/handlers/dbMobBaseHandler.java index d772f262..d5abeaec 100644 --- a/src/engine/db/handlers/dbMobBaseHandler.java +++ b/src/engine/db/handlers/dbMobBaseHandler.java @@ -11,10 +11,15 @@ package engine.db.handlers; import engine.Enum.GameObjectType; import engine.gameManager.DbManager; -import engine.objects.*; +import engine.objects.MobBase; +import engine.objects.MobBaseEffects; +import engine.objects.MobBaseStats; +import engine.objects.MobLootBase; import engine.server.MBServerStatics; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; @@ -27,22 +32,32 @@ public class dbMobBaseHandler extends dbHandlerBase { this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); } - public MobBase GET_MOBBASE(int id, boolean forceDB) { - + public MobBase GET_MOBBASE(int id) { if (id == 0) return null; MobBase mobBase = (MobBase) DbManager.getFromCache(GameObjectType.MobBase, id); - if ( mobBase != null) + if (mobBase != null) return mobBase; - prepareCallable("SELECT * FROM `static_npc_mobbase` WHERE `ID`=?"); - setInt(1, id); - return (MobBase) getObjectSingle(id, forceDB, true); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_mobbase` WHERE `ID`=?")) { + + preparedStatement.setInt(1, id); + + ResultSet rs = preparedStatement.executeQuery(); + mobBase = (MobBase) getObjectFromRs(rs); + + } catch (SQLException e) { + Logger.error(e); + } + + return mobBase; } + public ArrayList GET_ALL_MOBBASES() { prepareCallable("SELECT * FROM `static_npc_mobbase`;"); return getObjectList(); diff --git a/src/engine/devcmd/cmds/RenameMobCmd.java b/src/engine/devcmd/cmds/RenameMobCmd.java deleted file mode 100644 index 0e0dee1f..00000000 --- a/src/engine/devcmd/cmds/RenameMobCmd.java +++ /dev/null @@ -1,101 +0,0 @@ -// • ▌ ▄ ·. ▄▄▄· ▄▄ • ▪ ▄▄· ▄▄▄▄· ▄▄▄· ▐▄▄▄ ▄▄▄ . -// ·██ ▐███▪▐█ ▀█ ▐█ ▀ ▪██ ▐█ ▌▪▐█ ▀█▪▐█ ▀█ •█▌ ▐█▐▌· -// ▐█ ▌▐▌▐█·▄█▀▀█ ▄█ ▀█▄▐█·██ ▄▄▐█▀▀█▄▄█▀▀█ ▐█▐ ▐▌▐▀▀▀ -// ██ ██▌▐█▌▐█ ▪▐▌▐█▄▪▐█▐█▌▐███▌██▄▪▐█▐█ ▪▐▌██▐ █▌▐█▄▄▌ -// ▀▀ █▪▀▀▀ ▀ ▀ ·▀▀▀▀ ▀▀▀·▀▀▀ ·▀▀▀▀ ▀ ▀ ▀▀ █▪ ▀▀▀ -// Magicbane Emulator Project © 2013 - 2022 -// www.magicbane.com - - -package engine.devcmd.cmds; - -import engine.devcmd.AbstractDevCmd; -import engine.gameManager.ChatManager; -import engine.objects.AbstractGameObject; -import engine.objects.MobBase; -import engine.objects.NPC; -import engine.objects.PlayerCharacter; - -/** - * - * @author Eighty - * - */ -public class RenameMobCmd extends AbstractDevCmd { - - public RenameMobCmd() { - super("renamemob"); - } - - @Override - protected void _doCmd(PlayerCharacter pcSender, String[] args, - AbstractGameObject target) { - if (args.length < 1) { - this.sendUsage(pcSender); - return; - } - int loadID = 0; - String name = ""; - NPC npc; - if (target != null && target instanceof NPC) - npc = (NPC) target; - else - npc = getTargetAsNPC(pcSender); - if (npc != null) { - for (int i = 0; i < args.length; i++) { - name += args[i]; - if (i + 1 < args.length) - name += " "; - } - npc.setName(name); - npc.updateDatabase(); - ChatManager.chatSayInfo( - pcSender, - "NPC with ID " + npc.getObjectUUID() + " renamed to " - + npc.getFirstName()); - } else { - try { - loadID = Integer.parseInt(args[0]); - if (args.length > 1) { - for (int i = 1; i < args.length; i++) { - name += args[i]; - if (i + 1 < args.length) - name += " "; - } - } - } catch (Exception e) { - throwbackError(pcSender, - "Invalid renameMob Command. Need mob ID specified."); - return; // NaN - } - MobBase mob = MobBase.getMobBase(loadID); - if (mob == null) { - throwbackError(pcSender, - "Invalid renameMob Command. Mob ID specified is not valid."); - return; - } - if (!MobBase.renameMobBase(mob.getObjectUUID(), name)) { - throwbackError(pcSender, - "renameMob SQL Error. Failed to rename mob."); - return; - } - mob = MobBase.getMobBase(mob.getObjectUUID(), true); // force refresh - // from db - ChatManager.chatSayInfo( - pcSender, - "MobBase with ID " + mob.getObjectUUID() + " renamed to " - + mob.getFirstName()); - } - } - - @Override - protected String _getUsageString() { - return "' /renamemob [ID] newName'"; - } - - @Override - protected String _getHelpString() { - return "Changes a mobs old name to a new name"; - } - -} diff --git a/src/engine/gameManager/DevCmdManager.java b/src/engine/gameManager/DevCmdManager.java index 8e2ecf82..7c68d2f7 100644 --- a/src/engine/gameManager/DevCmdManager.java +++ b/src/engine/gameManager/DevCmdManager.java @@ -93,7 +93,6 @@ public enum DevCmdManager { DevCmdManager.registerDevCmd(new GetBankCmd()); DevCmdManager.registerDevCmd(new GetVaultCmd()); DevCmdManager.registerDevCmd(new CombatMessageCmd()); - DevCmdManager.registerDevCmd(new RenameMobCmd()); DevCmdManager.registerDevCmd(new RenameCmd()); DevCmdManager.registerDevCmd(new CreateItemCmd()); DevCmdManager.registerDevCmd(new GetMemoryCmd()); diff --git a/src/engine/objects/MobBase.java b/src/engine/objects/MobBase.java index 0f32a1d5..67df8821 100644 --- a/src/engine/objects/MobBase.java +++ b/src/engine/objects/MobBase.java @@ -206,20 +206,8 @@ public class MobBase extends AbstractGameObject { return this.spawnTime; } - /* - * Database - */ public static MobBase getMobBase(int id) { - return MobBase.getMobBase(id, false); - } - - public static MobBase getMobBase(int id, boolean forceDB) { - return DbManager.MobBaseQueries.GET_MOBBASE(id, forceDB); - } - - - public static boolean renameMobBase(int ID, String newName) { - return DbManager.MobBaseQueries.RENAME_MOBBASE(ID, newName); + return DbManager.MobBaseQueries.GET_MOBBASE(id); } @Override From 9f7da9a57acc266a177f95c8e8452a20c13a4e7d Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 06:46:30 -0400 Subject: [PATCH 058/109] Refactor to remove abstraction --- src/engine/db/handlers/dbMobBaseHandler.java | 140 ++++++++++--------- 1 file changed, 71 insertions(+), 69 deletions(-) diff --git a/src/engine/db/handlers/dbMobBaseHandler.java b/src/engine/db/handlers/dbMobBaseHandler.java index d5abeaec..531c1415 100644 --- a/src/engine/db/handlers/dbMobBaseHandler.java +++ b/src/engine/db/handlers/dbMobBaseHandler.java @@ -14,7 +14,6 @@ import engine.gameManager.DbManager; import engine.objects.MobBase; import engine.objects.MobBaseEffects; import engine.objects.MobBaseStats; -import engine.objects.MobLootBase; import engine.server.MBServerStatics; import org.pmw.tinylog.Logger; @@ -59,14 +58,28 @@ public class dbMobBaseHandler extends dbHandlerBase { public ArrayList GET_ALL_MOBBASES() { - prepareCallable("SELECT * FROM `static_npc_mobbase`;"); - return getObjectList(); + + ArrayList mobbaseList = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_mobbase`;")) { + + ResultSet rs = preparedStatement.executeQuery(); + mobbaseList = getObjectsFromRs(rs, 1000); + + } catch (SQLException e) { + Logger.error(e); + } + return mobbaseList; } public void SET_AI_DEFAULTS() { - prepareCallable("SELECT * FROM `static_ai_defaults`"); - try { - ResultSet rs = executeQuery(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_ai_defaults`")) { + + ResultSet rs = preparedStatement.executeQuery(); + while (rs.next()) { MBServerStatics.AI_BASE_AGGRO_RANGE = rs.getInt("aggro_range"); MBServerStatics.AI_PATROL_DIVISOR = rs.getInt("patrol_chance"); @@ -75,109 +88,101 @@ public class dbMobBaseHandler extends dbHandlerBase { MBServerStatics.AI_RECALL_RANGE = rs.getInt("recall_range"); MBServerStatics.AI_PET_HEEL_DISTANCE = rs.getInt("pet_heel_distance"); } - rs.close(); } catch (SQLException e) { - Logger.error( e.getMessage()); - } finally { - closeCallable(); + Logger.error(e); } - } public boolean UPDATE_AI_DEFAULTS() { - prepareCallable("UPDATE `static_ai_defaults` SET `aggro_range` = ?,`patrol_chance`= ?,`drop_aggro_range`= ?,`cast_chance`= ?,`recall_range`= ? WHERE `ID` = 1"); - setInt(1, MBServerStatics.AI_BASE_AGGRO_RANGE); - setInt(2, MBServerStatics.AI_PATROL_DIVISOR); - setInt(3, MBServerStatics.AI_DROP_AGGRO_RANGE); - setInt(4, MBServerStatics.AI_POWER_DIVISOR); - setInt(5, MBServerStatics.AI_RECALL_RANGE); - return (executeUpdate() > 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `static_ai_defaults` SET `aggro_range` = ?,`patrol_chance`= ?,`drop_aggro_range`= ?,`cast_chance`= ?,`recall_range`= ? WHERE `ID` = 1")) { + + preparedStatement.setInt(1, MBServerStatics.AI_BASE_AGGRO_RANGE); + preparedStatement.setInt(2, MBServerStatics.AI_PATROL_DIVISOR); + preparedStatement.setInt(3, MBServerStatics.AI_DROP_AGGRO_RANGE); + preparedStatement.setInt(4, MBServerStatics.AI_POWER_DIVISOR); + preparedStatement.setInt(5, MBServerStatics.AI_RECALL_RANGE); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public HashMap LOAD_STATIC_POWERS(int mobBaseUUID) { + HashMap powersList = new HashMap<>(); - prepareCallable("SELECT * FROM `static_npc_mobbase_powers` WHERE `mobbaseUUID`=?"); - setInt(1, mobBaseUUID); - try { - ResultSet rs = executeQuery(); - while (rs.next()) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_mobbase_powers` WHERE `mobbaseUUID`=?")) { + + preparedStatement.setInt(1, mobBaseUUID); + ResultSet rs = preparedStatement.executeQuery(); + + while (rs.next()) powersList.put(rs.getInt("token"), rs.getInt("rank")); - } - rs.close(); + } catch (SQLException e) { - Logger.error( e.getMessage()); - } finally { - closeCallable(); + Logger.error(e); } return powersList; - } public ArrayList GET_RUNEBASE_EFFECTS(int runeID) { + ArrayList effectsList = new ArrayList<>(); - prepareCallable("SELECT * FROM `static_npc_mobbase_effects` WHERE `mobbaseUUID` = ?"); - setInt(1, runeID); - try { - ResultSet rs = executeQuery(); - while (rs.next()) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_mobbase_effects` WHERE `mobbaseUUID` = ?")) { + preparedStatement.setInt(1, runeID); + ResultSet rs = preparedStatement.executeQuery(); + + while (rs.next()) { MobBaseEffects mbs = new MobBaseEffects(rs); effectsList.add(mbs); } - rs.close(); + } catch (SQLException e) { - Logger.error (e.getMessage()); - } finally { - closeCallable(); + Logger.error(e); } return effectsList; - } public MobBaseStats LOAD_STATS(int mobBaseUUID) { - MobBaseStats mbs = MobBaseStats.GetGenericStats(); - prepareCallable("SELECT * FROM `static_npc_mobbase_stats` WHERE `mobbaseUUID` = ?"); - setInt(1, mobBaseUUID); - try { - ResultSet rs = executeQuery(); - while (rs.next()) { + MobBaseStats mobBaseStats = MobBaseStats.GetGenericStats(); - mbs = new MobBaseStats(rs); - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_mobbase_stats` WHERE `mobbaseUUID` = ?")) { - } catch (SQLException e) { - Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); - } - return mbs; + preparedStatement.setInt(1, mobBaseUUID); + ResultSet rs = preparedStatement.executeQuery(); - } + while (rs.next()) + mobBaseStats = new MobBaseStats(rs); - public boolean RENAME_MOBBASE(int ID, String newName) { - prepareCallable("UPDATE `static_npc_mobbase` SET `name`=? WHERE `ID`=?;"); - setString(1, newName); - setInt(2, ID); - return (executeUpdate() > 0); + } catch (SQLException e) { + Logger.error(e); + } + return mobBaseStats; } public void LOAD_ALL_MOBBASE_SPEEDS(MobBase mobBase) { if (mobBase.getLoadID() == 0) return; - ArrayList mobLootList = new ArrayList<>(); - prepareCallable("SELECT * FROM `static_npc_mobbase_race` WHERE `mobbaseID` = ?"); - setInt(1, mobBase.getLoadID()); - try { - ResultSet rs = executeQuery(); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_mobbase_race` WHERE `mobbaseID` = ?")) { + + preparedStatement.setInt(1, mobBase.getLoadID()); + ResultSet rs = preparedStatement.executeQuery(); - //shrines cached in rs for easy cache on creation. while (rs.next()) { float walk = rs.getFloat("walkStandard"); float walkCombat = rs.getFloat("walkCombat"); @@ -186,11 +191,8 @@ public class dbMobBaseHandler extends dbHandlerBase { mobBase.updateSpeeds(walk, walkCombat, run, runCombat); } - } catch (SQLException e) { - Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); + Logger.error(e); } } } From 41451247620ace7fcc31420d1b88c5cd98a08a8b Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 07:18:26 -0400 Subject: [PATCH 059/109] Refactor to remove abstraction --- src/engine/db/handlers/dbMobHandler.java | 128 +++++++++++++---------- 1 file changed, 75 insertions(+), 53 deletions(-) diff --git a/src/engine/db/handlers/dbMobHandler.java b/src/engine/db/handlers/dbMobHandler.java index aea15d00..b594793f 100644 --- a/src/engine/db/handlers/dbMobHandler.java +++ b/src/engine/db/handlers/dbMobHandler.java @@ -9,12 +9,15 @@ package engine.db.handlers; +import engine.gameManager.DbManager; import engine.objects.Mob; import engine.objects.Zone; import engine.server.MBServerStatics; import org.joda.time.DateTime; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; @@ -26,87 +29,106 @@ public class dbMobHandler extends dbHandlerBase { this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); } - public Mob ADD_MOB(Mob toAdd) - { - prepareCallable("CALL `mob_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"); - setLong(1, toAdd.getParentZoneID()); - setInt(2, toAdd.getMobBaseID()); - setInt(3, toAdd.getGuildUUID()); - setFloat(4, toAdd.getSpawnX()); - setFloat(5, toAdd.getSpawnY()); - setFloat(6, toAdd.getSpawnZ()); - setInt(7, 0); - setFloat(8, toAdd.getSpawnRadius()); - setInt(9, toAdd.getTrueSpawnTime()); - if (toAdd.getContract() != null) - setInt(10, toAdd.getContract().getContractID()); - else - setInt(10, 0); - setInt(11, toAdd.getBuildingID()); - setInt(12, toAdd.getLevel()); - setString(13, toAdd.getFirstName()); - int objectUUID = (int) getUUID(); - if (objectUUID > 0) - return GET_MOB(objectUUID); - return null; + public Mob ADD_MOB(Mob toAdd) { + + Mob mobile = null; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL `mob_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);")) { + + preparedStatement.setLong(1, toAdd.getParentZoneID()); + preparedStatement.setInt(2, toAdd.getMobBaseID()); + preparedStatement.setInt(3, toAdd.getGuildUUID()); + preparedStatement.setFloat(4, toAdd.getSpawnX()); + preparedStatement.setFloat(5, toAdd.getSpawnY()); + preparedStatement.setFloat(6, toAdd.getSpawnZ()); + preparedStatement.setInt(7, 0); + preparedStatement.setFloat(8, toAdd.getSpawnRadius()); + preparedStatement.setInt(9, toAdd.getTrueSpawnTime()); + + if (toAdd.getContract() != null) + preparedStatement.setInt(10, toAdd.getContract().getContractID()); + else + preparedStatement.setInt(10, 0); + + preparedStatement.setInt(11, toAdd.getBuildingID()); + preparedStatement.setInt(12, toAdd.getLevel()); + preparedStatement.setString(13, toAdd.getFirstName()); + + ResultSet rs = preparedStatement.executeQuery(); + + int objectUUID = (int) rs.getLong("UID"); + + if (objectUUID > 0) + mobile = GET_MOB(objectUUID); + + } catch (SQLException e) { + throw new RuntimeException(e); + } + return mobile; } public boolean updateUpgradeTime(Mob mob, DateTime upgradeDateTime) { - try { - - prepareCallable("UPDATE obj_mob SET upgradeDate=? " - + "WHERE UID = ?"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE obj_mob SET upgradeDate=? " + + "WHERE UID = ?")) { if (upgradeDateTime == null) - setNULL(1, java.sql.Types.DATE); + preparedStatement.setNull(1, java.sql.Types.DATE); else - setTimeStamp(1, upgradeDateTime.getMillis()); + preparedStatement.setTimestamp(1, new java.sql.Timestamp(upgradeDateTime.getMillis())); - setInt(2, mob.getObjectUUID()); - executeUpdate(); - } catch (Exception e) { - Logger.error("Mob.updateUpgradeTime", "UUID: " + mob.getObjectUUID()); - return false; + preparedStatement.setInt(2, mob.getObjectUUID()); + + preparedStatement.execute(); + return true; + } catch (SQLException e) { + Logger.error(e); } - return true; + return false; } public int DELETE_MOB(final Mob mob) { - prepareCallable("DELETE FROM `object` WHERE `UID` = ?"); - setLong(1, mob.getDBID()); - return executeUpdate(); + + int row_count = 0; + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `object` WHERE `UID` = ?")) { + + preparedStatement.setLong(1, mob.getDBID()); + row_count = preparedStatement.executeUpdate(); + + } catch (SQLException e) { + Logger.error(e); + + } + return row_count; } public void LOAD_PATROL_POINTS(Mob captain) { - prepareCallable("SELECT * FROM `dyn_guards` WHERE `captainUID` = ?"); - setInt(1,captain.getObjectUUID()); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_guards` WHERE `captainUID` = ?")) { - try { - ResultSet rs = executeQuery(); + preparedStatement.setInt(1, captain.getObjectUUID()); + ResultSet rs = preparedStatement.executeQuery(); - //shrines cached in rs for easy cache on creation. - - while (rs.next()) { - int mobBaseID = rs.getInt("mobBaseID"); + while (rs.next()) { String name = rs.getString("name"); - Mob toCreate = Mob.createGuardMob(captain, captain.getGuild(), captain.getParentZone(), captain.building.getLoc(), captain.getLevel(),name); + Mob toCreate = Mob.createGuardMob(captain, captain.getGuild(), captain.getParentZone(), captain.building.getLoc(), captain.getLevel(), name); + if (toCreate == null) return; if (toCreate != null) { toCreate.setTimeToSpawnSiege(System.currentTimeMillis() + MBServerStatics.FIFTEEN_MINUTES); toCreate.setDeathTime(System.currentTimeMillis()); - } + } } } catch (SQLException e) { - Logger.error( e.toString()); - } finally { - closeCallable(); + Logger.error(e); } - } public boolean ADD_TO_GUARDS(final long captainUID, final int mobBaseID, final String name, final int slot) { @@ -122,7 +144,7 @@ public class dbMobHandler extends dbHandlerBase { prepareCallable("DELETE FROM `dyn_guards` WHERE `captainUID`=? AND `mobBaseID`=? AND `slot` =?"); setLong(1, captainUID); setInt(2, mobBaseID); - setInt(3,slot); + setInt(3, slot); return (executeUpdate() > 0); } From 608a28642857e024c6792ec95d84985b822dec9d Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 07:29:22 -0400 Subject: [PATCH 060/109] Refactor to remove abstraction --- src/engine/db/handlers/dbMobHandler.java | 131 ++++++++++++++++------- 1 file changed, 94 insertions(+), 37 deletions(-) diff --git a/src/engine/db/handlers/dbMobHandler.java b/src/engine/db/handlers/dbMobHandler.java index b594793f..c94d57a4 100644 --- a/src/engine/db/handlers/dbMobHandler.java +++ b/src/engine/db/handlers/dbMobHandler.java @@ -132,60 +132,117 @@ public class dbMobHandler extends dbHandlerBase { } public boolean ADD_TO_GUARDS(final long captainUID, final int mobBaseID, final String name, final int slot) { - prepareCallable("INSERT INTO `dyn_guards` (`captainUID`, `mobBaseID`,`name`, `slot`) VALUES (?,?,?,?)"); - setLong(1, captainUID); - setInt(2, mobBaseID); - setString(3, name); - setInt(4, slot); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_guards` (`captainUID`, `mobBaseID`,`name`, `slot`) VALUES (?,?,?,?)")) { + + preparedStatement.setLong(1, captainUID); + preparedStatement.setInt(2, mobBaseID); + preparedStatement.setString(3, name); + preparedStatement.setInt(4, slot); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean REMOVE_FROM_GUARDS(final long captainUID, final int mobBaseID, final int slot) { - prepareCallable("DELETE FROM `dyn_guards` WHERE `captainUID`=? AND `mobBaseID`=? AND `slot` =?"); - setLong(1, captainUID); - setInt(2, mobBaseID); - setInt(3, slot); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_guards` WHERE `captainUID`=? AND `mobBaseID`=? AND `slot` =?")) { + + preparedStatement.setLong(1, captainUID); + preparedStatement.setInt(2, mobBaseID); + preparedStatement.setInt(3, slot); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public ArrayList GET_ALL_MOBS_FOR_ZONE(Zone zone) { - prepareCallable("SELECT `obj_mob`.*, `object`.`parent` FROM `object` INNER JOIN `obj_mob` ON `obj_mob`.`UID` = `object`.`UID` WHERE `object`.`parent` = ?;"); - setLong(1, zone.getObjectUUID()); - return getLargeObjectList(); + + ArrayList mobileList = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_mob`.*, `object`.`parent` FROM `object` INNER JOIN `obj_mob` ON `obj_mob`.`UID` = `object`.`UID` WHERE `object`.`parent` = ?;")) { + + preparedStatement.setLong(1, zone.getObjectUUID()); + + ResultSet rs = preparedStatement.executeQuery(); + mobileList = getObjectsFromRs(rs, 1000); + + } catch (SQLException e) { + Logger.error(e); + } + + return mobileList; } public Mob GET_MOB(final int objectUUID) { - prepareCallable("SELECT `obj_mob`.*, `object`.`parent` FROM `object` INNER JOIN `obj_mob` ON `obj_mob`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?;"); - setLong(1, objectUUID); - return (Mob) getObjectSingle(objectUUID); + + Mob mobile = null; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_mob`.*, `object`.`parent` FROM `object` INNER JOIN `obj_mob` ON `obj_mob`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?;")) { + + preparedStatement.setLong(1, objectUUID); + ResultSet rs = preparedStatement.executeQuery(); + mobile = (Mob) getObjectFromRs(rs); + + } catch (SQLException e) { + Logger.error(e); + } + return mobile; } public int MOVE_MOB(long mobID, long parentID, float locX, float locY, float locZ) { - prepareCallable("UPDATE `object` INNER JOIN `obj_mob` On `object`.`UID` = `obj_mob`.`UID` SET `object`.`parent`=?, `obj_mob`.`mob_spawnX`=?, `obj_mob`.`mob_spawnY`=?, `obj_mob`.`mob_spawnZ`=? WHERE `obj_mob`.`UID`=?;"); - setLong(1, parentID); - setFloat(2, locX); - setFloat(3, locY); - setFloat(4, locZ); - setLong(5, mobID); - return executeUpdate(); + + int row_count = 0; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `object` INNER JOIN `obj_mob` On `object`.`UID` = `obj_mob`.`UID` SET `object`.`parent`=?, `obj_mob`.`mob_spawnX`=?, `obj_mob`.`mob_spawnY`=?, `obj_mob`.`mob_spawnZ`=? WHERE `obj_mob`.`UID`=?;")) { + + preparedStatement.setLong(1, parentID); + preparedStatement.setFloat(2, locX); + preparedStatement.setFloat(3, locY); + preparedStatement.setFloat(4, locZ); + preparedStatement.setLong(5, mobID); + + ResultSet rs = preparedStatement.executeQuery(); + row_count = preparedStatement.executeUpdate(); + + } catch (SQLException e) { + Logger.error(e); + } + return row_count; } public String SET_PROPERTY(final Mob m, String name, Object new_value) { - prepareCallable("CALL mob_SETPROP(?,?,?)"); - setLong(1, m.getObjectUUID()); - setString(2, name); - setString(3, String.valueOf(new_value)); - return getResult(); - } - public String SET_PROPERTY(final Mob m, String name, Object new_value, Object old_value) { - prepareCallable("CALL mob_GETSETPROP(?,?,?,?)"); - setLong(1, m.getObjectUUID()); - setString(2, name); - setString(3, String.valueOf(new_value)); - setString(4, String.valueOf(old_value)); - return getResult(); + String result = ""; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL mob_SETPROP(?,?,?)")) { + + preparedStatement.setLong(1, m.getObjectUUID()); + preparedStatement.setString(2, name); + preparedStatement.setString(3, String.valueOf(new_value)); + + ResultSet rs = preparedStatement.executeQuery(); + result = rs.getString("result"); + + } catch (SQLException e) { + Logger.error(e); + } + return result; } } From 1bf9fde684061fc8e0317fb011835ba6151d98e7 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 07:44:34 -0400 Subject: [PATCH 061/109] Bonus code removed. --- src/engine/db/handlers/dbNPCHandler.java | 610 ++++++++++++----------- 1 file changed, 313 insertions(+), 297 deletions(-) diff --git a/src/engine/db/handlers/dbNPCHandler.java b/src/engine/db/handlers/dbNPCHandler.java index 49b4b082..d34b7475 100644 --- a/src/engine/db/handlers/dbNPCHandler.java +++ b/src/engine/db/handlers/dbNPCHandler.java @@ -10,10 +10,13 @@ package engine.db.handlers; import engine.Enum.ProfitType; +import engine.gameManager.DbManager; import engine.objects.*; import org.joda.time.DateTime; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; @@ -21,301 +24,314 @@ import java.util.HashMap; public class dbNPCHandler extends dbHandlerBase { - public dbNPCHandler() { - this.localClass = NPC.class; - this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); - } - - public NPC ADD_NPC(NPC toAdd, boolean isMob) { - prepareCallable("CALL `npc_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"); - setLong(1, toAdd.getParentZoneID()); - setString(2, toAdd.getName()); - setInt(3, toAdd.getContractID()); - setInt(4, toAdd.getGuildUUID()); - setFloat(5, toAdd.getSpawnX()); - setFloat(6, toAdd.getSpawnY()); - setFloat(7, toAdd.getSpawnZ()); - setInt(8, toAdd.getLevel()); - setFloat(9, toAdd.getBuyPercent()); - setFloat(10, toAdd.getSellPercent()); - if (toAdd.getBuilding() != null) { - setInt(11, toAdd.getBuilding().getObjectUUID()); - } else { - setInt(11, 0); - } - - int objectUUID = (int) getUUID(); - if (objectUUID > 0) { - return GET_NPC(objectUUID); - } - return null; - } - - public int DELETE_NPC(final NPC npc) { - if (npc.isStatic()) { - return DELETE_STATIC_NPC(npc); - } - - npc.removeFromZone(); - prepareCallable("DELETE FROM `object` WHERE `UID` = ?"); - setLong(1, (long) npc.getDBID()); - return executeUpdate(); - } - - private int DELETE_STATIC_NPC(final NPC npc) { - npc.removeFromZone(); - prepareCallable("DELETE FROM `_init_npc` WHERE `ID` = ?"); - setInt(1, npc.getDBID()); - return executeUpdate(); - } - - public ArrayList GET_ALL_NPCS_FOR_ZONE(Zone zone) { - prepareCallable("SELECT `obj_npc`.*, `object`.`parent` FROM `object` INNER JOIN `obj_npc` ON `obj_npc`.`UID` = `object`.`UID` WHERE `object`.`parent` = ?;"); - setLong(1, (long) zone.getObjectUUID()); - return getLargeObjectList(); - } - - public NPC GET_NPC(final int objectUUID) { - prepareCallable("SELECT `obj_npc`.*, `object`.`parent` FROM `object` INNER JOIN `obj_npc` ON `obj_npc`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?;"); - setLong(1, (long) objectUUID); - return (NPC) getObjectSingle(objectUUID); - } - - public int MOVE_NPC(long npcID, long parentID, float locX, float locY, float locZ) { - prepareCallable("UPDATE `object` INNER JOIN `obj_npc` On `object`.`UID` = `obj_npc`.`UID` SET `object`.`parent`=?, `obj_npc`.`npc_spawnX`=?, `obj_npc`.`npc_spawnY`=?, `obj_npc`.`npc_spawnZ`=? WHERE `obj_npc`.`UID`=?;"); - setLong(1, parentID); - setFloat(2, locX); - setFloat(3, locY); - setFloat(4, locZ); - setLong(5, npcID); - return executeUpdate(); - } - - - public String SET_PROPERTY(final NPC n, String name, Object new_value) { - prepareCallable("CALL npc_SETPROP(?,?,?)"); - setLong(1, (long) n.getDBID()); - setString(2, name); - setString(3, String.valueOf(new_value)); - return getResult(); - } - - public String SET_PROPERTY(final NPC n, String name, Object new_value, Object old_value) { - prepareCallable("CALL npc_GETSETPROP(?,?,?,?)"); - setLong(1, (long) n.getDBID()); - setString(2, name); - setString(3, String.valueOf(new_value)); - setString(4, String.valueOf(old_value)); - return getResult(); - } - - public void updateDatabase(final NPC npc) { - prepareCallable("UPDATE obj_npc SET npc_name=?, npc_contractID=?, npc_typeID=?, npc_guildID=?," - + " npc_spawnX=?, npc_spawnY=?, npc_spawnZ=?, npc_level=? ," - + " npc_buyPercent=?, npc_sellPercent=?, npc_buildingID=? WHERE UID = ?"); - setString(1, npc.getName()); - setInt(2, (npc.getContract() != null) ? npc.getContract().getObjectUUID() : 0); - setInt(3, 0); - setInt(4, (npc.getGuild() != null) ? npc.getGuild().getObjectUUID() : 0); - setFloat(5, npc.getBindLoc().x); - setFloat(6, npc.getBindLoc().y); - setFloat(7, npc.getBindLoc().z); - setShort(8, npc.getLevel()); - setFloat(9, npc.getBuyPercent()); - setFloat(10, npc.getSellPercent()); - setInt(11, (npc.getBuilding() != null) ? npc.getBuilding().getObjectUUID() : 0); - setInt(12, npc.getDBID()); - executeUpdate(); - } - - public boolean updateUpgradeTime(NPC npc, DateTime upgradeDateTime) { - - try { - - prepareCallable("UPDATE obj_npc SET upgradeDate=? " - + "WHERE UID = ?"); - - if (upgradeDateTime == null) - setNULL(1, java.sql.Types.DATE); - else - setTimeStamp(1, upgradeDateTime.getMillis()); - - setInt(2, npc.getObjectUUID()); - executeUpdate(); - } catch (Exception e) { - Logger.error("UUID: " + npc.getObjectUUID()); - return false; - } - return true; - } - - public boolean UPDATE_MOBBASE(NPC npc, int mobBaseID) { - prepareCallable("UPDATE `obj_npc` SET `npc_raceID`=? WHERE `UID`=?"); - setLong(1, mobBaseID); - setLong(2, npc.getObjectUUID()); - return (executeUpdate() > 0); - } - - public boolean UPDATE_EQUIPSET(NPC npc, int equipSetID) { - prepareCallable("UPDATE `obj_npc` SET `equipsetID`=? WHERE `UID`=?"); - setInt(1, equipSetID); - setLong(2, npc.getObjectUUID()); - return (executeUpdate() > 0); - } - - public boolean UPDATE_NAME(NPC npc,String name) { - prepareCallable("UPDATE `obj_npc` SET `npc_name`=? WHERE `UID`=?"); - setString(1, name); - setLong(2, npc.getObjectUUID()); - return (executeUpdate() > 0); - } - - public void LOAD_PIRATE_NAMES() { - - String pirateName; - int mobBase; - int recordsRead = 0; - - prepareCallable("SELECT * FROM static_piratenames"); - - try { - ResultSet rs = executeQuery(); - - while (rs.next()) { - - recordsRead++; - mobBase = rs.getInt("mobbase"); - pirateName = rs.getString("first_name"); - - // Handle new mobbbase entries - - if (NPC._pirateNames.get(mobBase) == null) { - NPC._pirateNames.putIfAbsent(mobBase, new ArrayList<>()); - } - - // Insert name into proper arraylist - - NPC._pirateNames.get(mobBase).add(pirateName); - - } - - Logger.info("names read: " + recordsRead + " for " - + NPC._pirateNames.size() + " mobBases"); - - } catch (SQLException e) { - Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); - } - } - - - public boolean ADD_TO_PRODUCTION_LIST(final long ID,final long npcUID, final long itemBaseID, DateTime dateTime, String prefix, String suffix, String name, boolean isRandom, int playerID) { - prepareCallable("INSERT INTO `dyn_npc_production` (`ID`,`npcUID`, `itemBaseID`,`dateToUpgrade`, `isRandom`, `prefix`, `suffix`, `name`,`playerID`) VALUES (?,?,?,?,?,?,?,?,?)"); - setLong(1,ID); - setLong(2, npcUID); - setLong(3, itemBaseID); - setTimeStamp(4, dateTime.getMillis()); - setBoolean(5, isRandom); - setString(6, prefix); - setString(7, suffix); - setString(8, name); - setInt(9,playerID); - return (executeUpdate() > 0); - } - - public boolean REMOVE_FROM_PRODUCTION_LIST(final long ID,final long npcUID) { - prepareCallable("DELETE FROM `dyn_npc_production` WHERE `ID`=? AND `npcUID`=?;"); - setLong(1,ID); - setLong(2, npcUID); - return (executeUpdate() > 0); - } - - public boolean UPDATE_ITEM_TO_INVENTORY(final long ID,final long npcUID) { - prepareCallable("UPDATE `dyn_npc_production` SET `inForge`=? WHERE `ID`=? AND `npcUID`=?;"); - setByte(1, (byte)0); - setLong(2, ID); - setLong(3, npcUID); - return (executeUpdate() > 0); - } - - public boolean UPDATE_ITEM_PRICE(final long ID,final long npcUID, int value) { - prepareCallable("UPDATE `dyn_npc_production` SET `value`=? WHERE `ID`=? AND `npcUID`=?;"); - setInt(1, value); - setLong(2, ID); - setLong(3, npcUID); - - return (executeUpdate() > 0); - } - - public boolean UPDATE_ITEM_ID(final long ID,final long npcUID,final long value) { - prepareCallable("UPDATE `dyn_npc_production` SET `ID`=? WHERE `ID`=? AND `npcUID`=? LIMIT 1;"); - setLong(1, value); - setLong(2, ID); - setLong(3, npcUID); - - return (executeUpdate() > 0); - } - - public void LOAD_ALL_ITEMS_TO_PRODUCE(NPC npc) { - - if (npc == null) - return; - - prepareCallable("SELECT * FROM `dyn_npc_production` WHERE `npcUID` = ?"); - setInt(1,npc.getObjectUUID()); - - try { - ResultSet rs = executeQuery(); - - //shrines cached in rs for easy cache on creation. - while (rs.next()) { - ProducedItem producedItem = new ProducedItem(rs); - npc.forgedItems.add(producedItem); - } - - } catch (SQLException e) { - Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); - } - } - - public boolean UPDATE_PROFITS(NPC npc,ProfitType profitType, float value){ - prepareCallable("UPDATE `dyn_npc_profits` SET `" + profitType.dbField + "` = ? WHERE `npcUID`=?"); - setFloat(1, value); - setInt(2, npc.getObjectUUID()); - return (executeUpdate() > 0); - } - - public void LOAD_NPC_PROFITS() { - - HashMap> regions; - NPCProfits npcProfit; - - - prepareCallable("SELECT * FROM dyn_npc_profits"); - - try { - ResultSet rs = executeQuery(); - - while (rs.next()) { - - - npcProfit = new NPCProfits(rs); - NPCProfits.ProfitCache.put(npcProfit.npcUID, npcProfit); - } - - } catch (SQLException e) { - Logger.error(": " + e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); - } - } - - public boolean CREATE_PROFITS(NPC npc){ - prepareCallable("INSERT INTO `dyn_npc_profits` (`npcUID`) VALUES (?)"); - setLong(1,npc.getObjectUUID()); - return (executeUpdate() > 0); - } + public dbNPCHandler() { + this.localClass = NPC.class; + this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); + } + + public NPC ADD_NPC(NPC toAdd, boolean isMob) { + + NPC npc = null; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL `npc_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);")) { + + preparedStatement.setLong(1, toAdd.getParentZoneID()); + preparedStatement.setString(2, toAdd.getName()); + preparedStatement.setInt(3, toAdd.getContractID()); + preparedStatement.setInt(4, toAdd.getGuildUUID()); + preparedStatement.setFloat(5, toAdd.getSpawnX()); + preparedStatement.setFloat(6, toAdd.getSpawnY()); + preparedStatement.setFloat(7, toAdd.getSpawnZ()); + preparedStatement.setInt(8, toAdd.getLevel()); + preparedStatement.setFloat(9, toAdd.getBuyPercent()); + preparedStatement.setFloat(10, toAdd.getSellPercent()); + + if (toAdd.getBuilding() != null) + preparedStatement.setInt(11, toAdd.getBuilding().getObjectUUID()); + else + preparedStatement.setInt(11, 0); + + ResultSet rs = preparedStatement.executeQuery(); + + int objectUUID = (int) rs.getLong("UID"); + + if (objectUUID > 0) + npc = GET_NPC(objectUUID); + + } catch (SQLException e) { + throw new RuntimeException(e); + } + + return npc; + } + + public int DELETE_NPC(final NPC npc) { + + int row_count = 0; + + npc.removeFromZone(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `object` WHERE `UID` = ?")) { + + preparedStatement.setLong(1, npc.getDBID()); + row_count = preparedStatement.executeUpdate(); + + } catch (SQLException e) { + Logger.error(e); + + } + return row_count; + } + + public ArrayList GET_ALL_NPCS_FOR_ZONE(Zone zone) { + prepareCallable("SELECT `obj_npc`.*, `object`.`parent` FROM `object` INNER JOIN `obj_npc` ON `obj_npc`.`UID` = `object`.`UID` WHERE `object`.`parent` = ?;"); + setLong(1, zone.getObjectUUID()); + return getLargeObjectList(); + } + + public NPC GET_NPC(final int objectUUID) { + prepareCallable("SELECT `obj_npc`.*, `object`.`parent` FROM `object` INNER JOIN `obj_npc` ON `obj_npc`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?;"); + setLong(1, objectUUID); + return (NPC) getObjectSingle(objectUUID); + } + + public int MOVE_NPC(long npcID, long parentID, float locX, float locY, float locZ) { + prepareCallable("UPDATE `object` INNER JOIN `obj_npc` On `object`.`UID` = `obj_npc`.`UID` SET `object`.`parent`=?, `obj_npc`.`npc_spawnX`=?, `obj_npc`.`npc_spawnY`=?, `obj_npc`.`npc_spawnZ`=? WHERE `obj_npc`.`UID`=?;"); + setLong(1, parentID); + setFloat(2, locX); + setFloat(3, locY); + setFloat(4, locZ); + setLong(5, npcID); + return executeUpdate(); + } + + + public String SET_PROPERTY(final NPC n, String name, Object new_value) { + prepareCallable("CALL npc_SETPROP(?,?,?)"); + setLong(1, n.getDBID()); + setString(2, name); + setString(3, String.valueOf(new_value)); + return getResult(); + } + + public String SET_PROPERTY(final NPC n, String name, Object new_value, Object old_value) { + prepareCallable("CALL npc_GETSETPROP(?,?,?,?)"); + setLong(1, n.getDBID()); + setString(2, name); + setString(3, String.valueOf(new_value)); + setString(4, String.valueOf(old_value)); + return getResult(); + } + + public void updateDatabase(final NPC npc) { + prepareCallable("UPDATE obj_npc SET npc_name=?, npc_contractID=?, npc_typeID=?, npc_guildID=?," + + " npc_spawnX=?, npc_spawnY=?, npc_spawnZ=?, npc_level=? ," + + " npc_buyPercent=?, npc_sellPercent=?, npc_buildingID=? WHERE UID = ?"); + setString(1, npc.getName()); + setInt(2, (npc.getContract() != null) ? npc.getContract().getObjectUUID() : 0); + setInt(3, 0); + setInt(4, (npc.getGuild() != null) ? npc.getGuild().getObjectUUID() : 0); + setFloat(5, npc.getBindLoc().x); + setFloat(6, npc.getBindLoc().y); + setFloat(7, npc.getBindLoc().z); + setShort(8, npc.getLevel()); + setFloat(9, npc.getBuyPercent()); + setFloat(10, npc.getSellPercent()); + setInt(11, (npc.getBuilding() != null) ? npc.getBuilding().getObjectUUID() : 0); + setInt(12, npc.getDBID()); + executeUpdate(); + } + + public boolean updateUpgradeTime(NPC npc, DateTime upgradeDateTime) { + + try { + + prepareCallable("UPDATE obj_npc SET upgradeDate=? " + + "WHERE UID = ?"); + + if (upgradeDateTime == null) + setNULL(1, java.sql.Types.DATE); + else + setTimeStamp(1, upgradeDateTime.getMillis()); + + setInt(2, npc.getObjectUUID()); + executeUpdate(); + } catch (Exception e) { + Logger.error("UUID: " + npc.getObjectUUID()); + return false; + } + return true; + } + + public boolean UPDATE_MOBBASE(NPC npc, int mobBaseID) { + prepareCallable("UPDATE `obj_npc` SET `npc_raceID`=? WHERE `UID`=?"); + setLong(1, mobBaseID); + setLong(2, npc.getObjectUUID()); + return (executeUpdate() > 0); + } + + public boolean UPDATE_EQUIPSET(NPC npc, int equipSetID) { + prepareCallable("UPDATE `obj_npc` SET `equipsetID`=? WHERE `UID`=?"); + setInt(1, equipSetID); + setLong(2, npc.getObjectUUID()); + return (executeUpdate() > 0); + } + + public boolean UPDATE_NAME(NPC npc, String name) { + prepareCallable("UPDATE `obj_npc` SET `npc_name`=? WHERE `UID`=?"); + setString(1, name); + setLong(2, npc.getObjectUUID()); + return (executeUpdate() > 0); + } + + public void LOAD_PIRATE_NAMES() { + + String pirateName; + int mobBase; + int recordsRead = 0; + + prepareCallable("SELECT * FROM static_piratenames"); + + try { + ResultSet rs = executeQuery(); + + while (rs.next()) { + + recordsRead++; + mobBase = rs.getInt("mobbase"); + pirateName = rs.getString("first_name"); + + // Handle new mobbbase entries + + if (NPC._pirateNames.get(mobBase) == null) { + NPC._pirateNames.putIfAbsent(mobBase, new ArrayList<>()); + } + + // Insert name into proper arraylist + + NPC._pirateNames.get(mobBase).add(pirateName); + + } + + Logger.info("names read: " + recordsRead + " for " + + NPC._pirateNames.size() + " mobBases"); + + } catch (SQLException e) { + Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); + } finally { + closeCallable(); + } + } + + + public boolean ADD_TO_PRODUCTION_LIST(final long ID, final long npcUID, final long itemBaseID, DateTime dateTime, String prefix, String suffix, String name, boolean isRandom, int playerID) { + prepareCallable("INSERT INTO `dyn_npc_production` (`ID`,`npcUID`, `itemBaseID`,`dateToUpgrade`, `isRandom`, `prefix`, `suffix`, `name`,`playerID`) VALUES (?,?,?,?,?,?,?,?,?)"); + setLong(1, ID); + setLong(2, npcUID); + setLong(3, itemBaseID); + setTimeStamp(4, dateTime.getMillis()); + setBoolean(5, isRandom); + setString(6, prefix); + setString(7, suffix); + setString(8, name); + setInt(9, playerID); + return (executeUpdate() > 0); + } + + public boolean REMOVE_FROM_PRODUCTION_LIST(final long ID, final long npcUID) { + prepareCallable("DELETE FROM `dyn_npc_production` WHERE `ID`=? AND `npcUID`=?;"); + setLong(1, ID); + setLong(2, npcUID); + return (executeUpdate() > 0); + } + + public boolean UPDATE_ITEM_TO_INVENTORY(final long ID, final long npcUID) { + prepareCallable("UPDATE `dyn_npc_production` SET `inForge`=? WHERE `ID`=? AND `npcUID`=?;"); + setByte(1, (byte) 0); + setLong(2, ID); + setLong(3, npcUID); + return (executeUpdate() > 0); + } + + public boolean UPDATE_ITEM_PRICE(final long ID, final long npcUID, int value) { + prepareCallable("UPDATE `dyn_npc_production` SET `value`=? WHERE `ID`=? AND `npcUID`=?;"); + setInt(1, value); + setLong(2, ID); + setLong(3, npcUID); + + return (executeUpdate() > 0); + } + + public boolean UPDATE_ITEM_ID(final long ID, final long npcUID, final long value) { + prepareCallable("UPDATE `dyn_npc_production` SET `ID`=? WHERE `ID`=? AND `npcUID`=? LIMIT 1;"); + setLong(1, value); + setLong(2, ID); + setLong(3, npcUID); + + return (executeUpdate() > 0); + } + + public void LOAD_ALL_ITEMS_TO_PRODUCE(NPC npc) { + + if (npc == null) + return; + + prepareCallable("SELECT * FROM `dyn_npc_production` WHERE `npcUID` = ?"); + setInt(1, npc.getObjectUUID()); + + try { + ResultSet rs = executeQuery(); + + //shrines cached in rs for easy cache on creation. + while (rs.next()) { + ProducedItem producedItem = new ProducedItem(rs); + npc.forgedItems.add(producedItem); + } + + } catch (SQLException e) { + Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); + } finally { + closeCallable(); + } + } + + public boolean UPDATE_PROFITS(NPC npc, ProfitType profitType, float value) { + prepareCallable("UPDATE `dyn_npc_profits` SET `" + profitType.dbField + "` = ? WHERE `npcUID`=?"); + setFloat(1, value); + setInt(2, npc.getObjectUUID()); + return (executeUpdate() > 0); + } + + public void LOAD_NPC_PROFITS() { + + HashMap> regions; + NPCProfits npcProfit; + + + prepareCallable("SELECT * FROM dyn_npc_profits"); + + try { + ResultSet rs = executeQuery(); + + while (rs.next()) { + + + npcProfit = new NPCProfits(rs); + NPCProfits.ProfitCache.put(npcProfit.npcUID, npcProfit); + } + + } catch (SQLException e) { + Logger.error(": " + e.getErrorCode() + ' ' + e.getMessage(), e); + } finally { + closeCallable(); + } + } + + public boolean CREATE_PROFITS(NPC npc) { + prepareCallable("INSERT INTO `dyn_npc_profits` (`npcUID`) VALUES (?)"); + setLong(1, npc.getObjectUUID()); + return (executeUpdate() > 0); + } } From b7dd4a845a3dd24e043a8ae55ebe3bf6c990171d Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 07:57:08 -0400 Subject: [PATCH 062/109] Refactor to remove abstraction. --- src/engine/db/handlers/dbNPCHandler.java | 157 +++++++++++++++-------- 1 file changed, 103 insertions(+), 54 deletions(-) diff --git a/src/engine/db/handlers/dbNPCHandler.java b/src/engine/db/handlers/dbNPCHandler.java index d34b7475..88a297e0 100644 --- a/src/engine/db/handlers/dbNPCHandler.java +++ b/src/engine/db/handlers/dbNPCHandler.java @@ -86,83 +86,132 @@ public class dbNPCHandler extends dbHandlerBase { } public ArrayList GET_ALL_NPCS_FOR_ZONE(Zone zone) { - prepareCallable("SELECT `obj_npc`.*, `object`.`parent` FROM `object` INNER JOIN `obj_npc` ON `obj_npc`.`UID` = `object`.`UID` WHERE `object`.`parent` = ?;"); - setLong(1, zone.getObjectUUID()); - return getLargeObjectList(); + + ArrayList npcList = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_npc`.*, `object`.`parent` FROM `object` INNER JOIN `obj_npc` ON `obj_npc`.`UID` = `object`.`UID` WHERE `object`.`parent` = ?;")) { + + preparedStatement.setLong(1, zone.getObjectUUID()); + + ResultSet rs = preparedStatement.executeQuery(); + npcList = getObjectsFromRs(rs, 1000); + + } catch (SQLException e) { + Logger.error(e); + } + + return npcList; } public NPC GET_NPC(final int objectUUID) { - prepareCallable("SELECT `obj_npc`.*, `object`.`parent` FROM `object` INNER JOIN `obj_npc` ON `obj_npc`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?;"); - setLong(1, objectUUID); - return (NPC) getObjectSingle(objectUUID); + + NPC npc = null; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_npc`.*, `object`.`parent` FROM `object` INNER JOIN `obj_npc` ON `obj_npc`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?;")) { + + preparedStatement.setLong(1, objectUUID); + + ResultSet rs = preparedStatement.executeQuery(); + npc = (NPC) getObjectFromRs(rs); + + } catch (SQLException e) { + Logger.error(e); + } + return npc; } public int MOVE_NPC(long npcID, long parentID, float locX, float locY, float locZ) { - prepareCallable("UPDATE `object` INNER JOIN `obj_npc` On `object`.`UID` = `obj_npc`.`UID` SET `object`.`parent`=?, `obj_npc`.`npc_spawnX`=?, `obj_npc`.`npc_spawnY`=?, `obj_npc`.`npc_spawnZ`=? WHERE `obj_npc`.`UID`=?;"); - setLong(1, parentID); - setFloat(2, locX); - setFloat(3, locY); - setFloat(4, locZ); - setLong(5, npcID); - return executeUpdate(); + + int rowCount; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `object` INNER JOIN `obj_npc` On `object`.`UID` = `obj_npc`.`UID` SET `object`.`parent`=?, `obj_npc`.`npc_spawnX`=?, `obj_npc`.`npc_spawnY`=?, `obj_npc`.`npc_spawnZ`=? WHERE `obj_npc`.`UID`=?;")) { + + preparedStatement.setLong(1, parentID); + preparedStatement.setFloat(2, locX); + preparedStatement.setFloat(3, locY); + preparedStatement.setFloat(4, locZ); + preparedStatement.setLong(5, npcID); + + rowCount = preparedStatement.executeUpdate(); + + } catch (SQLException e) { + Logger.error(e); + return 0; + } + return rowCount; } public String SET_PROPERTY(final NPC n, String name, Object new_value) { - prepareCallable("CALL npc_SETPROP(?,?,?)"); - setLong(1, n.getDBID()); - setString(2, name); - setString(3, String.valueOf(new_value)); - return getResult(); - } - public String SET_PROPERTY(final NPC n, String name, Object new_value, Object old_value) { - prepareCallable("CALL npc_GETSETPROP(?,?,?,?)"); - setLong(1, n.getDBID()); - setString(2, name); - setString(3, String.valueOf(new_value)); - setString(4, String.valueOf(old_value)); - return getResult(); + String result = ""; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL npc_SETPROP(?,?,?)")) { + + preparedStatement.setLong(1, n.getDBID()); + preparedStatement.setString(2, name); + preparedStatement.setString(3, String.valueOf(new_value)); + + ResultSet rs = preparedStatement.executeQuery(); + result = rs.getString("result"); + + } catch (SQLException e) { + Logger.error(e); + } + return result; } public void updateDatabase(final NPC npc) { - prepareCallable("UPDATE obj_npc SET npc_name=?, npc_contractID=?, npc_typeID=?, npc_guildID=?," - + " npc_spawnX=?, npc_spawnY=?, npc_spawnZ=?, npc_level=? ," - + " npc_buyPercent=?, npc_sellPercent=?, npc_buildingID=? WHERE UID = ?"); - setString(1, npc.getName()); - setInt(2, (npc.getContract() != null) ? npc.getContract().getObjectUUID() : 0); - setInt(3, 0); - setInt(4, (npc.getGuild() != null) ? npc.getGuild().getObjectUUID() : 0); - setFloat(5, npc.getBindLoc().x); - setFloat(6, npc.getBindLoc().y); - setFloat(7, npc.getBindLoc().z); - setShort(8, npc.getLevel()); - setFloat(9, npc.getBuyPercent()); - setFloat(10, npc.getSellPercent()); - setInt(11, (npc.getBuilding() != null) ? npc.getBuilding().getObjectUUID() : 0); - setInt(12, npc.getDBID()); - executeUpdate(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE obj_npc SET npc_name=?, npc_contractID=?, npc_typeID=?, npc_guildID=?," + + " npc_spawnX=?, npc_spawnY=?, npc_spawnZ=?, npc_level=? ," + + " npc_buyPercent=?, npc_sellPercent=?, npc_buildingID=? WHERE UID = ?")) { + + preparedStatement.setString(1, npc.getName()); + preparedStatement.setInt(2, (npc.getContract() != null) ? npc.getContract().getObjectUUID() : 0); + preparedStatement.setInt(3, 0); + preparedStatement.setInt(4, (npc.getGuild() != null) ? npc.getGuild().getObjectUUID() : 0); + preparedStatement.setFloat(5, npc.getBindLoc().x); + preparedStatement.setFloat(6, npc.getBindLoc().y); + preparedStatement.setFloat(7, npc.getBindLoc().z); + preparedStatement.setShort(8, npc.getLevel()); + preparedStatement.setFloat(9, npc.getBuyPercent()); + preparedStatement.setFloat(10, npc.getSellPercent()); + preparedStatement.setInt(11, (npc.getBuilding() != null) ? npc.getBuilding().getObjectUUID() : 0); + preparedStatement.setInt(12, npc.getDBID()); + + preparedStatement.executeUpdate(); + + } catch (SQLException e) { + Logger.error(e); + } } public boolean updateUpgradeTime(NPC npc, DateTime upgradeDateTime) { - try { - - prepareCallable("UPDATE obj_npc SET upgradeDate=? " - + "WHERE UID = ?"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE obj_npc SET upgradeDate=? " + + "WHERE UID = ?")) { if (upgradeDateTime == null) - setNULL(1, java.sql.Types.DATE); + preparedStatement.setNull(1, java.sql.Types.DATE); else - setTimeStamp(1, upgradeDateTime.getMillis()); + preparedStatement.setTimestamp(1, new java.sql.Timestamp(upgradeDateTime.getMillis())); + + preparedStatement.setInt(2, npc.getObjectUUID()); - setInt(2, npc.getObjectUUID()); - executeUpdate(); - } catch (Exception e) { - Logger.error("UUID: " + npc.getObjectUUID()); - return false; + preparedStatement.execute(); + return true; + + } catch (SQLException e) { + Logger.error(e); } - return true; + return false; } public boolean UPDATE_MOBBASE(NPC npc, int mobBaseID) { From 860f7b7b4926cdf7e7ccfcda32f04f708e6a5311 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 08:28:58 -0400 Subject: [PATCH 063/109] Refactor to remove abstraction. --- src/engine/db/handlers/dbNPCHandler.java | 71 ++++++++++++++++-------- 1 file changed, 47 insertions(+), 24 deletions(-) diff --git a/src/engine/db/handlers/dbNPCHandler.java b/src/engine/db/handlers/dbNPCHandler.java index 88a297e0..66f0425e 100644 --- a/src/engine/db/handlers/dbNPCHandler.java +++ b/src/engine/db/handlers/dbNPCHandler.java @@ -215,24 +215,51 @@ public class dbNPCHandler extends dbHandlerBase { } public boolean UPDATE_MOBBASE(NPC npc, int mobBaseID) { - prepareCallable("UPDATE `obj_npc` SET `npc_raceID`=? WHERE `UID`=?"); - setLong(1, mobBaseID); - setLong(2, npc.getObjectUUID()); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_npc` SET `npc_raceID`=? WHERE `UID`=?")) { + + preparedStatement.setLong(1, mobBaseID); + preparedStatement.setLong(2, npc.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean UPDATE_EQUIPSET(NPC npc, int equipSetID) { - prepareCallable("UPDATE `obj_npc` SET `equipsetID`=? WHERE `UID`=?"); - setInt(1, equipSetID); - setLong(2, npc.getObjectUUID()); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_npc` SET `equipsetID`=? WHERE `UID`=?")) { + + preparedStatement.setInt(1, equipSetID); + preparedStatement.setLong(2, npc.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean UPDATE_NAME(NPC npc, String name) { - prepareCallable("UPDATE `obj_npc` SET `npc_name`=? WHERE `UID`=?"); - setString(1, name); - setLong(2, npc.getObjectUUID()); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_npc` SET `npc_name`=? WHERE `UID`=?")) { + + preparedStatement.setString(1, name); + preparedStatement.setLong(2, npc.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public void LOAD_PIRATE_NAMES() { @@ -241,10 +268,10 @@ public class dbNPCHandler extends dbHandlerBase { int mobBase; int recordsRead = 0; - prepareCallable("SELECT * FROM static_piratenames"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_piratenames")) { - try { - ResultSet rs = executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { @@ -254,24 +281,20 @@ public class dbNPCHandler extends dbHandlerBase { // Handle new mobbbase entries - if (NPC._pirateNames.get(mobBase) == null) { + if (NPC._pirateNames.get(mobBase) == null) NPC._pirateNames.putIfAbsent(mobBase, new ArrayList<>()); - } // Insert name into proper arraylist NPC._pirateNames.get(mobBase).add(pirateName); - } - Logger.info("names read: " + recordsRead + " for " - + NPC._pirateNames.size() + " mobBases"); - } catch (SQLException e) { - Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); + Logger.error(e); } + + Logger.info("names read: " + recordsRead + " for " + + NPC._pirateNames.size() + " mobBases"); } From b8c9d4faf27d065859597541332796502490ccfa Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 08:41:25 -0400 Subject: [PATCH 064/109] Refactor to remove abstraction. --- src/engine/db/handlers/dbNPCHandler.java | 168 +++++++++++++++-------- 1 file changed, 110 insertions(+), 58 deletions(-) diff --git a/src/engine/db/handlers/dbNPCHandler.java b/src/engine/db/handlers/dbNPCHandler.java index 66f0425e..2199d9a7 100644 --- a/src/engine/db/handlers/dbNPCHandler.java +++ b/src/engine/db/handlers/dbNPCHandler.java @@ -11,7 +11,10 @@ package engine.db.handlers; import engine.Enum.ProfitType; import engine.gameManager.DbManager; -import engine.objects.*; +import engine.objects.NPC; +import engine.objects.NPCProfits; +import engine.objects.ProducedItem; +import engine.objects.Zone; import org.joda.time.DateTime; import org.pmw.tinylog.Logger; @@ -20,7 +23,6 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; -import java.util.HashMap; public class dbNPCHandler extends dbHandlerBase { @@ -297,52 +299,94 @@ public class dbNPCHandler extends dbHandlerBase { + NPC._pirateNames.size() + " mobBases"); } - public boolean ADD_TO_PRODUCTION_LIST(final long ID, final long npcUID, final long itemBaseID, DateTime dateTime, String prefix, String suffix, String name, boolean isRandom, int playerID) { - prepareCallable("INSERT INTO `dyn_npc_production` (`ID`,`npcUID`, `itemBaseID`,`dateToUpgrade`, `isRandom`, `prefix`, `suffix`, `name`,`playerID`) VALUES (?,?,?,?,?,?,?,?,?)"); - setLong(1, ID); - setLong(2, npcUID); - setLong(3, itemBaseID); - setTimeStamp(4, dateTime.getMillis()); - setBoolean(5, isRandom); - setString(6, prefix); - setString(7, suffix); - setString(8, name); - setInt(9, playerID); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_npc_production` (`ID`,`npcUID`, `itemBaseID`,`dateToUpgrade`, `isRandom`, `prefix`, `suffix`, `name`,`playerID`) VALUES (?,?,?,?,?,?,?,?,?)")) { + + preparedStatement.setLong(1, ID); + preparedStatement.setLong(2, npcUID); + preparedStatement.setLong(3, itemBaseID); + preparedStatement.setTimestamp(4, new java.sql.Timestamp(dateTime.getMillis())); + preparedStatement.setBoolean(5, isRandom); + preparedStatement.setString(6, prefix); + preparedStatement.setString(7, suffix); + preparedStatement.setString(8, name); + preparedStatement.setInt(9, playerID); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean REMOVE_FROM_PRODUCTION_LIST(final long ID, final long npcUID) { - prepareCallable("DELETE FROM `dyn_npc_production` WHERE `ID`=? AND `npcUID`=?;"); - setLong(1, ID); - setLong(2, npcUID); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_npc_production` WHERE `ID`=? AND `npcUID`=?;")) { + + preparedStatement.setLong(1, ID); + preparedStatement.setLong(2, npcUID); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean UPDATE_ITEM_TO_INVENTORY(final long ID, final long npcUID) { - prepareCallable("UPDATE `dyn_npc_production` SET `inForge`=? WHERE `ID`=? AND `npcUID`=?;"); - setByte(1, (byte) 0); - setLong(2, ID); - setLong(3, npcUID); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_npc_production` SET `inForge`=? WHERE `ID`=? AND `npcUID`=?;")) { + + preparedStatement.setByte(1, (byte) 0); + preparedStatement.setLong(2, ID); + preparedStatement.setLong(3, npcUID); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean UPDATE_ITEM_PRICE(final long ID, final long npcUID, int value) { - prepareCallable("UPDATE `dyn_npc_production` SET `value`=? WHERE `ID`=? AND `npcUID`=?;"); - setInt(1, value); - setLong(2, ID); - setLong(3, npcUID); - return (executeUpdate() > 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_npc_production` SET `value`=? WHERE `ID`=? AND `npcUID`=?;")) { + + preparedStatement.setInt(1, value); + preparedStatement.setLong(2, ID); + preparedStatement.setLong(3, npcUID); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean UPDATE_ITEM_ID(final long ID, final long npcUID, final long value) { - prepareCallable("UPDATE `dyn_npc_production` SET `ID`=? WHERE `ID`=? AND `npcUID`=? LIMIT 1;"); - setLong(1, value); - setLong(2, ID); - setLong(3, npcUID); - return (executeUpdate() > 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_npc_production` SET `ID`=? WHERE `ID`=? AND `npcUID`=? LIMIT 1;")) { + + preparedStatement.setLong(1, value); + preparedStatement.setLong(2, ID); + preparedStatement.setLong(3, npcUID); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public void LOAD_ALL_ITEMS_TO_PRODUCE(NPC npc) { @@ -350,60 +394,68 @@ public class dbNPCHandler extends dbHandlerBase { if (npc == null) return; - prepareCallable("SELECT * FROM `dyn_npc_production` WHERE `npcUID` = ?"); - setInt(1, npc.getObjectUUID()); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_npc_production` WHERE `npcUID` = ?")) { - try { - ResultSet rs = executeQuery(); + preparedStatement.setInt(1, npc.getObjectUUID()); + ResultSet rs = preparedStatement.executeQuery(); - //shrines cached in rs for easy cache on creation. while (rs.next()) { ProducedItem producedItem = new ProducedItem(rs); npc.forgedItems.add(producedItem); } } catch (SQLException e) { - Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); + Logger.error(e); } } public boolean UPDATE_PROFITS(NPC npc, ProfitType profitType, float value) { - prepareCallable("UPDATE `dyn_npc_profits` SET `" + profitType.dbField + "` = ? WHERE `npcUID`=?"); - setFloat(1, value); - setInt(2, npc.getObjectUUID()); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_npc_profits` SET `" + profitType.dbField + "` = ? WHERE `npcUID`=?")) { + + preparedStatement.setFloat(1, value); + preparedStatement.setInt(2, npc.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public void LOAD_NPC_PROFITS() { - HashMap> regions; NPCProfits npcProfit; + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM dyn_npc_profits")) { - prepareCallable("SELECT * FROM dyn_npc_profits"); - - try { - ResultSet rs = executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { - - npcProfit = new NPCProfits(rs); NPCProfits.ProfitCache.put(npcProfit.npcUID, npcProfit); } } catch (SQLException e) { - Logger.error(": " + e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); + Logger.error(e); } } public boolean CREATE_PROFITS(NPC npc) { - prepareCallable("INSERT INTO `dyn_npc_profits` (`npcUID`) VALUES (?)"); - setLong(1, npc.getObjectUUID()); - return (executeUpdate() > 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_npc_profits` (`npcUID`) VALUES (?)")) { + + preparedStatement.setLong(1, npc.getObjectUUID()); + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } } From 3a2f08738189f951105facac0a7bdbe40351f364 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 08:54:59 -0400 Subject: [PATCH 065/109] Refactor to remove abstraction. --- .../db/handlers/dbPlayerCharacterHandler.java | 164 ++++++++++++------ 1 file changed, 108 insertions(+), 56 deletions(-) diff --git a/src/engine/db/handlers/dbPlayerCharacterHandler.java b/src/engine/db/handlers/dbPlayerCharacterHandler.java index 3dfeb6ae..eeadfc94 100644 --- a/src/engine/db/handlers/dbPlayerCharacterHandler.java +++ b/src/engine/db/handlers/dbPlayerCharacterHandler.java @@ -18,6 +18,8 @@ import engine.objects.PlayerFriends; import engine.server.MBServerStatics; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; @@ -31,60 +33,106 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { } public PlayerCharacter ADD_PLAYER_CHARACTER(final PlayerCharacter toAdd) { - if (toAdd.getAccount() == null) { + + PlayerCharacter playerCharacter = null; + + if (toAdd.getAccount() == null) return null; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL `character_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);")) { + + preparedStatement.setLong(1, toAdd.getAccount().getObjectUUID()); + preparedStatement.setString(2, toAdd.getFirstName()); + preparedStatement.setString(3, toAdd.getLastName()); + preparedStatement.setInt(4, toAdd.getRace().getRaceRuneID()); + preparedStatement.setInt(5, toAdd.getBaseClass().getObjectUUID()); + preparedStatement.setInt(6, toAdd.getStrMod()); + preparedStatement.setInt(7, toAdd.getDexMod()); + preparedStatement.setInt(8, toAdd.getConMod()); + preparedStatement.setInt(9, toAdd.getIntMod()); + preparedStatement.setInt(10, toAdd.getSpiMod()); + preparedStatement.setInt(11, toAdd.getExp()); + preparedStatement.setInt(12, toAdd.getSkinColor()); + preparedStatement.setInt(13, toAdd.getHairColor()); + preparedStatement.setByte(14, toAdd.getHairStyle()); + preparedStatement.setInt(15, toAdd.getBeardColor()); + preparedStatement.setByte(16, toAdd.getBeardStyle()); + + ResultSet rs = preparedStatement.executeQuery(); + + int objectUUID = (int) rs.getLong("UID"); + + if (objectUUID > 0) + playerCharacter = GET_PLAYER_CHARACTER(objectUUID); + + } catch (SQLException e) { + Logger.error(e); } - prepareCallable("CALL `character_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"); - setLong(1, toAdd.getAccount().getObjectUUID()); - setString(2, toAdd.getFirstName()); - setString(3, toAdd.getLastName()); - setInt(4, toAdd.getRace().getRaceRuneID()); - setInt(5, toAdd.getBaseClass().getObjectUUID()); - setInt(6, toAdd.getStrMod()); - setInt(7, toAdd.getDexMod()); - setInt(8, toAdd.getConMod()); - setInt(9, toAdd.getIntMod()); - setInt(10, toAdd.getSpiMod()); - setInt(11, toAdd.getExp()); - setInt(12, toAdd.getSkinColor()); - setInt(13, toAdd.getHairColor()); - setByte(14, toAdd.getHairStyle()); - setInt(15, toAdd.getBeardColor()); - setByte(16, toAdd.getBeardStyle()); - - int objectUUID = (int) getUUID(); - if (objectUUID > 0) { - return GET_PLAYER_CHARACTER(objectUUID); - } - return null; + + return playerCharacter; } public boolean SET_IGNORE_LIST(int sourceID, int targetID, boolean toIgnore, String charName) { - if (toIgnore) { - //Add to ignore list - prepareCallable("INSERT INTO `dyn_character_ignore` (`accountUID`, `ignoringUID`, `characterName`) VALUES (?, ?, ?)"); - setLong(1, (long) sourceID); - setLong(2, (long) targetID); - setString(3, charName); - return (executeUpdate() > 0); - } else { - //delete from ignore list - prepareCallable("DELETE FROM `dyn_character_ignore` WHERE `accountUID` = ? && `ignoringUID` = ?"); - setLong(1, (long) sourceID); - setLong(2, (long) targetID); - return (executeUpdate() > 0); + + String queryString = ""; + + if (toIgnore) + queryString = "INSERT INTO `dyn_character_ignore` (`accountUID`, `ignoringUID`, `characterName`) VALUES (?, ?, ?)"; + else + queryString = "DELETE FROM `dyn_character_ignore` WHERE `accountUID` = ? && `ignoringUID` = ?"; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement(queryString)) { + + preparedStatement.setLong(1, sourceID); + preparedStatement.setLong(2, targetID); + + if (toIgnore) + preparedStatement.setString(3, charName); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; } + } public ArrayList GET_CHARACTERS_FOR_ACCOUNT(final int id) { - prepareCallable("SELECT `obj_character`.*, `object`.`parent` FROM `object` INNER JOIN `obj_character` ON `obj_character`.`UID` = `object`.`UID` WHERE `object`.`parent`=? && `obj_character`.`char_isActive`='1';"); - setLong(1, (long) id); - return getObjectList(); + + ArrayList characterList = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_character`.*, `object`.`parent` FROM `object` INNER JOIN `obj_character` ON `obj_character`.`UID` = `object`.`UID` WHERE `object`.`parent`=? && `obj_character`.`char_isActive`='1';")) { + + preparedStatement.setLong(1, (long) id); + ResultSet rs = preparedStatement.executeQuery(); + characterList = getObjectsFromRs(rs, 10); + + } catch (SQLException e) { + Logger.error(e); + } + + return characterList; } public ArrayList GET_ALL_CHARACTERS() { - prepareCallable("SELECT `obj_character`.*, `object`.`parent` FROM `object` INNER JOIN `obj_character` ON `obj_character`.`UID` = `object`.`UID` WHERE `obj_character`.`char_isActive`='1';"); - return getObjectList(); + + ArrayList characterList = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_character`.*, `object`.`parent` FROM `object` INNER JOIN `obj_character` ON `obj_character`.`UID` = `object`.`UID` WHERE `obj_character`.`char_isActive`='1';")) { + + ResultSet rs = preparedStatement.executeQuery(); + characterList = getObjectsFromRs(rs, 2000); + + } catch (SQLException e) { + Logger.error(e); + } + + return characterList; } /** @@ -97,27 +145,31 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { */ public ConcurrentHashMap GET_IGNORE_LIST(final int objectUUID, final boolean skipActiveCheck) { - ConcurrentHashMap out = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW); - prepareCallable("SELECT * FROM `dyn_character_ignore` WHERE `accountUID` = ?;"); - setLong(1, (long) objectUUID); - try { - ResultSet rs = executeQuery(); + + ConcurrentHashMap ignoreList = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_character_ignore` WHERE `accountUID` = ?;")) { + + preparedStatement.setLong(1, objectUUID); + + ResultSet rs = preparedStatement.executeQuery(); + while (rs.next()) { int ignoreCharacterID = rs.getInt("ignoringUID"); - if (ignoreCharacterID == 0) { + + if (ignoreCharacterID == 0) continue; - } + String name = rs.getString("characterName"); - out.put(ignoreCharacterID, name); + ignoreList.put(ignoreCharacterID, name); } - rs.close(); + } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - return out; // null to explicitly indicate a problem and prevent data loss - } finally { - closeCallable(); + Logger.error(e); } - return out; + + return ignoreList; } public PlayerCharacter GET_PLAYER_CHARACTER(final int objectUUID) { From 20bbf85082835b24747fb29a64414d987f229262 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 09:34:59 -0400 Subject: [PATCH 066/109] Refactor to remove abstraction. --- .../db/handlers/dbPlayerCharacterHandler.java | 447 ++++++++++++------ 1 file changed, 310 insertions(+), 137 deletions(-) diff --git a/src/engine/db/handlers/dbPlayerCharacterHandler.java b/src/engine/db/handlers/dbPlayerCharacterHandler.java index eeadfc94..94c17d52 100644 --- a/src/engine/db/handlers/dbPlayerCharacterHandler.java +++ b/src/engine/db/handlers/dbPlayerCharacterHandler.java @@ -177,224 +177,397 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { if (objectUUID == 0) return null; - PlayerCharacter pc = (PlayerCharacter) DbManager.getFromCache(Enum.GameObjectType.PlayerCharacter, objectUUID); - if (pc != null) - return pc; - prepareCallable("SELECT `obj_character`.*, `object`.`parent` FROM `object` INNER JOIN `obj_character` ON `obj_character`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?"); - setLong(1, (long) objectUUID); - return (PlayerCharacter) getObjectSingle(objectUUID); + PlayerCharacter playerCharacter = (PlayerCharacter) DbManager.getFromCache(Enum.GameObjectType.PlayerCharacter, objectUUID); + + if (playerCharacter != null) + return playerCharacter; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_character`.*, `object`.`parent` FROM `object` INNER JOIN `obj_character` ON `obj_character`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?")) { + + preparedStatement.setLong(1, objectUUID); + + ResultSet rs = preparedStatement.executeQuery(); + playerCharacter = (PlayerCharacter) getObjectFromRs(rs); + + } catch (SQLException e) { + Logger.error(e); + } + ; + return playerCharacter; } public boolean IS_CHARACTER_NAME_UNIQUE(final String firstName) { + boolean unique = true; - prepareCallable("SELECT `char_firstname` FROM `obj_character` WHERE `char_isActive`=1 && `char_firstname`=?"); - setString(1, firstName); - try { - ResultSet rs = executeQuery(); - if (rs.next()) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `char_firstname` FROM `obj_character` WHERE `char_isActive`=1 && `char_firstname`=?")) { + + preparedStatement.setString(1, firstName); + + ResultSet rs = preparedStatement.executeQuery(); + + if (rs.next()) unique = false; - } - rs.close(); + } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getMessage()); - unique = false; - } finally { - closeCallable(); + Logger.error(e); } + return unique; } public boolean UPDATE_NAME(String oldFirstName, String newFirstName, String newLastName) { - prepareCallable("UPDATE `obj_character` SET `char_firstname`=?, `char_lastname`=? WHERE `char_firstname`=? AND `char_isActive`='1'"); - setString(1, newFirstName); - setString(2, newLastName); - setString(3, oldFirstName); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_firstname`=?, `char_lastname`=? WHERE `char_firstname`=? AND `char_isActive`='1'")) { + + preparedStatement.setString(1, newFirstName); + preparedStatement.setString(2, newLastName); + preparedStatement.setString(3, oldFirstName); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } public boolean SET_DELETED(final PlayerCharacter pc) { - prepareCallable("UPDATE `obj_character` SET `char_isActive`=? WHERE `UID` = ?"); - setBoolean(1, !pc.isDeleted()); - setLong(2, (long) pc.getObjectUUID()); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_isActive`=? WHERE `UID` = ?")) { + + preparedStatement.setBoolean(1, !pc.isDeleted()); + preparedStatement.setLong(2, pc.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } + public boolean SET_ACTIVE(final PlayerCharacter pc, boolean status) { - prepareCallable("UPDATE `obj_character` SET `char_isActive`=? WHERE `UID` = ?"); - setBoolean(1, status); - setLong(2, (long) pc.getObjectUUID()); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_isActive`=? WHERE `UID` = ?")) { + + preparedStatement.setBoolean(1, status); + preparedStatement.setLong(2, (long) pc.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } + public boolean SET_BIND_BUILDING(final PlayerCharacter pc, int bindBuildingID) { - prepareCallable("UPDATE `obj_character` SET `char_bindBuilding`=? WHERE `UID` = ?"); - setInt(1, bindBuildingID); - setLong(2, (long) pc.getObjectUUID()); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_bindBuilding`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, bindBuildingID); + preparedStatement.setLong(2, (long) pc.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean SET_ANNIVERSERY(final PlayerCharacter pc, boolean flag) { - prepareCallable("UPDATE `obj_character` SET `anniversery`=? WHERE `UID` = ?"); - setBoolean(1, flag); - setLong(2, (long) pc.getObjectUUID()); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `anniversery`=? WHERE `UID` = ?")) { + + preparedStatement.setBoolean(1, flag); + preparedStatement.setLong(2, (long) pc.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean UPDATE_CHARACTER_EXPERIENCE(final PlayerCharacter pc) { - prepareCallable("UPDATE `obj_character` SET `char_experience`=? WHERE `UID` = ?"); - setInt(1, pc.getExp()); - setLong(2, (long) pc.getObjectUUID()); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_experience`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, pc.getExp()); + preparedStatement.setLong(2, (long) pc.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean UPDATE_GUILD(final PlayerCharacter pc, int guildUUID) { - prepareCallable("UPDATE `obj_character` SET `guildUID`=? WHERE `UID` = ?"); - setInt(1, guildUUID); - setLong(2, (long) pc.getObjectUUID()); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guildUID`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, guildUUID); + preparedStatement.setLong(2, (long) pc.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean UPDATE_CHARACTER_STATS(final PlayerCharacter pc) { - prepareCallable("UPDATE `obj_character` SET `char_strMod`=?, `char_dexMod`=?, `char_conMod`=?, `char_intMod`=?, `char_spiMod`=? WHERE `UID`=?"); - setInt(1, pc.getStrMod()); - setInt(2, pc.getDexMod()); - setInt(3, pc.getConMod()); - setInt(4, pc.getIntMod()); - setInt(5, pc.getSpiMod()); - setLong(6, (long) pc.getObjectUUID()); - return (executeUpdate() != 0); - } - public String SET_PROPERTY(final PlayerCharacter c, String name, Object new_value) { - prepareCallable("CALL character_SETPROP(?,?,?)"); - setLong(1, (long) c.getObjectUUID()); - setString(2, name); - setString(3, String.valueOf(new_value)); - return getResult(); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_strMod`=?, `char_dexMod`=?, `char_conMod`=?, `char_intMod`=?, `char_spiMod`=? WHERE `UID`=?")) { + + preparedStatement.setInt(1, pc.getStrMod()); + preparedStatement.setInt(2, pc.getDexMod()); + preparedStatement.setInt(3, pc.getConMod()); + preparedStatement.setInt(4, pc.getIntMod()); + preparedStatement.setInt(5, pc.getSpiMod()); + preparedStatement.setLong(6, (long) pc.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } - public String SET_PROPERTY(final PlayerCharacter c, String name, Object new_value, Object old_value) { - prepareCallable("CALL character_GETSETPROP(?,?,?,?)"); - setLong(1, (long) c.getObjectUUID()); - setString(2, name); - setString(3, String.valueOf(new_value)); - setString(4, String.valueOf(old_value)); - return getResult(); + public String SET_PROPERTY(final PlayerCharacter playerCharacter, String name, Object new_value) { + + String result = ""; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL character_SETPROP(?,?,?)")) { + + preparedStatement.setLong(1, playerCharacter.getObjectUUID()); + preparedStatement.setString(2, name); + ; + preparedStatement.setString(3, String.valueOf(new_value)); + + ResultSet rs = preparedStatement.executeQuery(); + result = rs.getString("result"); + + } catch (SQLException e) { + Logger.error(e); + } + return result; } - + public boolean SET_PROMOTION_CLASS(PlayerCharacter player, int promotionClassID) { - prepareCallable("UPDATE `obj_character` SET `char_promotionClassID`=? WHERE `UID`=?;"); - setInt(1,promotionClassID); - setInt(2, player.getObjectUUID()); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_promotionClassID`=? WHERE `UID`=?;")) { + + preparedStatement.setInt(1, promotionClassID); + preparedStatement.setInt(2, player.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean SET_INNERCOUNCIL(PlayerCharacter player, boolean isInnerCouncil) { - prepareCallable("UPDATE `obj_character` SET `guild_isInnerCouncil`=? WHERE `UID`=?;"); - setBoolean(1,isInnerCouncil); - setInt(2, player.getObjectUUID()); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_isInnerCouncil`=? WHERE `UID`=?;")) { + + preparedStatement.setBoolean(1, isInnerCouncil); + preparedStatement.setInt(2, player.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean SET_FULL_MEMBER(PlayerCharacter player, boolean isFullMember) { - prepareCallable("UPDATE `obj_character` SET `guild_isFullMember`=? WHERE `UID`=?;"); - setBoolean(1,isFullMember); - setInt(2, player.getObjectUUID()); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_isFullMember`=? WHERE `UID`=?;")) { + + preparedStatement.setBoolean(1, isFullMember); + preparedStatement.setInt(2, player.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean SET_TAX_COLLECTOR(PlayerCharacter player, boolean isTaxCollector) { - prepareCallable("UPDATE `obj_character` SET `guild_isTaxCollector`=? WHERE `UID`=?;"); - setBoolean(1,isTaxCollector); - setInt(2, player.getObjectUUID()); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_isTaxCollector`=? WHERE `UID`=?;")) { + + preparedStatement.setBoolean(1, isTaxCollector); + preparedStatement.setInt(2, player.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean SET_RECRUITER(PlayerCharacter player, boolean isRecruiter) { - prepareCallable("UPDATE `obj_character` SET `guild_isRecruiter`=? WHERE `UID`=?;"); - setBoolean(1,isRecruiter); - setInt(2, player.getObjectUUID()); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_isRecruiter`=? WHERE `UID`=?;")) { + + preparedStatement.setBoolean(1, isRecruiter); + preparedStatement.setInt(2, player.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public boolean SET_GUILD_TITLE(PlayerCharacter player, int title) { - prepareCallable("UPDATE `obj_character` SET `guild_title`=? WHERE `UID`=?;"); - setInt(1,title); - setInt(2, player.getObjectUUID()); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_title`=? WHERE `UID`=?;")) { + + preparedStatement.setInt(1, title); + preparedStatement.setInt(2, player.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } - - - - public boolean ADD_FRIEND(int source, long friend){ - prepareCallable("INSERT INTO `dyn_character_friends` (`playerUID`, `friendUID`) VALUES (?, ?)"); - setLong(1, (long) source); - setLong(2, (long)friend); - return (executeUpdate() != 0); + + public boolean ADD_FRIEND(int source, long friend) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_friends` (`playerUID`, `friendUID`) VALUES (?, ?)")) { + + preparedStatement.setLong(1, source); + preparedStatement.setLong(2, friend); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } - public boolean REMOVE_FRIEND(int source, int friend){ - prepareCallable("DELETE FROM `dyn_character_friends` WHERE (`playerUID`=?) AND (`friendUID`=?)"); - setLong(1, (long) source); - setLong(2, (long)friend); - return (executeUpdate() != 0); + public boolean REMOVE_FRIEND(int source, int friend) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_character_friends` WHERE (`playerUID`=?) AND (`friendUID`=?)")) { + + preparedStatement.setLong(1, source); + preparedStatement.setLong(2, friend); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public void LOAD_PLAYER_FRIENDS() { PlayerFriends playerFriend; + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM dyn_character_friends")) { - prepareCallable("SELECT * FROM dyn_character_friends"); - - try { - ResultSet rs = executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); - while (rs.next()) { + while (rs.next()) playerFriend = new PlayerFriends(rs); - } - } catch (SQLException e) { - Logger.error("LoadMeshBounds: " + e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); + Logger.error(e); } + + prepareCallable("SELECT * FROM dyn_character_friends"); } - public boolean ADD_HERALDY(int source, AbstractWorldObject character){ - prepareCallable("INSERT INTO `dyn_character_heraldy` (`playerUID`, `characterUID`,`characterType`) VALUES (?, ?,?)"); - setLong(1, (long) source); - setLong(2, (long)character.getObjectUUID()); - setInt(3, character.getObjectType().ordinal()); - return (executeUpdate() != 0); + public boolean ADD_HERALDY(int source, AbstractWorldObject character) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_heraldy` (`playerUID`, `characterUID`,`characterType`) VALUES (?, ?,?)")) { + + preparedStatement.setLong(1, source); + preparedStatement.setLong(2, character.getObjectUUID()); + preparedStatement.setInt(3, character.getObjectType().ordinal()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } - public boolean REMOVE_HERALDY(int source, int characterUID){ - prepareCallable("DELETE FROM `dyn_character_heraldy` WHERE (`playerUID`=?) AND (`characterUID`=?)"); - setLong(1, (long) source); - setLong(2, (long)characterUID); - return (executeUpdate() != 0); + public boolean REMOVE_HERALDY(int source, int characterUID) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_character_heraldy` WHERE (`playerUID`=?) AND (`characterUID`=?)")) { + + preparedStatement.setLong(1, source); + preparedStatement.setLong(2, characterUID); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } } public void LOAD_HERALDY() { Heraldry heraldy; + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM dyn_character_heraldy")) { - prepareCallable("SELECT * FROM dyn_character_heraldy"); - - try { - ResultSet rs = executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); - while (rs.next()) { + while (rs.next()) heraldy = new Heraldry(rs); - } - } catch (SQLException e) { - Logger.error("LoadHeraldy: " + e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); + Logger.error(e); } } From 5721638cd62612bfe32c55907ec6f5c4cf3b3be5 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 09:42:30 -0400 Subject: [PATCH 067/109] Refactor to remove abstraction. --- .../db/handlers/dbPromotionClassHandler.java | 69 ++++++++++++++----- 1 file changed, 50 insertions(+), 19 deletions(-) diff --git a/src/engine/db/handlers/dbPromotionClassHandler.java b/src/engine/db/handlers/dbPromotionClassHandler.java index 230d3f15..fed00a7a 100644 --- a/src/engine/db/handlers/dbPromotionClassHandler.java +++ b/src/engine/db/handlers/dbPromotionClassHandler.java @@ -9,9 +9,12 @@ package engine.db.handlers; +import engine.gameManager.DbManager; import engine.objects.PromotionClass; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; @@ -24,31 +27,59 @@ public class dbPromotionClassHandler extends dbHandlerBase { } public ArrayList GET_ALLOWED_RUNES(final PromotionClass pc) { - ArrayList runes = new ArrayList<>(); - prepareCallable("SELECT * FROM `static_rune_promotionrunereq` WHERE `promoID`=?"); - setInt(1, pc.getObjectUUID()); - try { - ResultSet rs = executeQuery(); - while (rs.next()) { - runes.add(rs.getInt("runereqID")); - } + + ArrayList runeList = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_promotionrunereq` WHERE `promoID`=?")) { + + preparedStatement.setInt(1, pc.getObjectUUID()); + + ResultSet rs = preparedStatement.executeQuery(); + + while (rs.next()) + runeList.add(rs.getInt("runereqID")); + } catch (SQLException e) { - Logger.error("Failed to retrieve Allowed Runes for PromotionClass " + pc.getObjectUUID() + ". Error number: " + e.getErrorCode(), e); - return null; - } finally { - closeCallable(); + Logger.error(e); + } - return runes; + return runeList; } public PromotionClass GET_PROMOTION_CLASS(final int objectUUID) { - prepareCallable("SELECT * FROM `static_rune_promotion` WHERE `ID` = ?"); - setInt(1, objectUUID); - return (PromotionClass) getObjectSingle(objectUUID); + + PromotionClass promotionClass = null; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_promotion` WHERE `ID` = ?")) { + + preparedStatement.setInt(1, objectUUID); + + ResultSet rs = preparedStatement.executeQuery(); + promotionClass = (PromotionClass) getObjectFromRs(rs); + + } catch (SQLException e) { + Logger.error(e); + } + + return promotionClass; } public ArrayList GET_ALL_PROMOTIONS() { - prepareCallable("SELECT * FROM `static_rune_promotion`"); - return getObjectList(); - } + + ArrayList promotionList = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_promotion`")) { + + ResultSet rs = preparedStatement.executeQuery(); + promotionList = getObjectsFromRs(rs, 30); + + } catch (SQLException e) { + Logger.error(e); + } + + return promotionList; + } } From c7bd2123e868af23b6242d61a715f018606cb589 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 10:11:46 -0400 Subject: [PATCH 068/109] Pool size auto configured. --- src/engine/gameManager/DbManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/engine/gameManager/DbManager.java b/src/engine/gameManager/DbManager.java index 661cee8f..17d01365 100644 --- a/src/engine/gameManager/DbManager.java +++ b/src/engine/gameManager/DbManager.java @@ -298,7 +298,7 @@ public enum DbManager { HikariConfig config = new HikariConfig(); - config.setMaximumPoolSize(10); + config.setMaximumPoolSize(Runtime.getRuntime().availableProcessors() * 2); config.setJdbcUrl("jdbc:mysql://" + ConfigManager.MB_DATABASE_ADDRESS.getValue() + ":" + ConfigManager.MB_DATABASE_PORT.getValue() + "/" + From 271fc8a35fd89bb5a12fef0c7b49fe19b0916bde Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 10:21:55 -0400 Subject: [PATCH 069/109] Pool size auto configured. --- src/engine/db/archive/DataWarehouse.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/engine/db/archive/DataWarehouse.java b/src/engine/db/archive/DataWarehouse.java index 9236a38c..8ba3b744 100644 --- a/src/engine/db/archive/DataWarehouse.java +++ b/src/engine/db/archive/DataWarehouse.java @@ -32,10 +32,6 @@ public class DataWarehouse implements Runnable { public DataWarehouse() { - Logger.info("Configuring local Database Connection Pool..."); - - DbManager.configureConnectionPool(); - // If WarehousePush is disabled // then early exit @@ -46,7 +42,6 @@ public class DataWarehouse implements Runnable { Logger.info( "Configuring remote Database Connection Pool..."); configureRemoteConnectionPool(); - } public static void bootStrap() { From 07b337f3f158709cd858660cd90688f0318a889b Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 10:32:15 -0400 Subject: [PATCH 070/109] Pool size fixed --- src/engine/gameManager/DbManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/engine/gameManager/DbManager.java b/src/engine/gameManager/DbManager.java index 17d01365..c5271801 100644 --- a/src/engine/gameManager/DbManager.java +++ b/src/engine/gameManager/DbManager.java @@ -298,7 +298,7 @@ public enum DbManager { HikariConfig config = new HikariConfig(); - config.setMaximumPoolSize(Runtime.getRuntime().availableProcessors() * 2); + config.setMaximumPoolSize(50); config.setJdbcUrl("jdbc:mysql://" + ConfigManager.MB_DATABASE_ADDRESS.getValue() + ":" + ConfigManager.MB_DATABASE_PORT.getValue() + "/" + From 75dfc638e1a9373698584fac7e241cfe803245fc Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 10:34:57 -0400 Subject: [PATCH 071/109] Pool size auto-configure --- src/engine/gameManager/DbManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/engine/gameManager/DbManager.java b/src/engine/gameManager/DbManager.java index c5271801..17d01365 100644 --- a/src/engine/gameManager/DbManager.java +++ b/src/engine/gameManager/DbManager.java @@ -298,7 +298,7 @@ public enum DbManager { HikariConfig config = new HikariConfig(); - config.setMaximumPoolSize(50); + config.setMaximumPoolSize(Runtime.getRuntime().availableProcessors() * 2); config.setJdbcUrl("jdbc:mysql://" + ConfigManager.MB_DATABASE_ADDRESS.getValue() + ":" + ConfigManager.MB_DATABASE_PORT.getValue() + "/" + From d67026edba838b5e6de7fb17ecc17f95b66d49f8 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 12:35:15 -0400 Subject: [PATCH 072/109] Refactor to remove abstraction. --- src/engine/db/handlers/dbRaceHandler.java | 124 ++++++++++++++++++---- 1 file changed, 101 insertions(+), 23 deletions(-) diff --git a/src/engine/db/handlers/dbRaceHandler.java b/src/engine/db/handlers/dbRaceHandler.java index df83d381..a8c2727c 100644 --- a/src/engine/db/handlers/dbRaceHandler.java +++ b/src/engine/db/handlers/dbRaceHandler.java @@ -9,9 +9,12 @@ package engine.db.handlers; +import engine.gameManager.DbManager; import engine.objects.Race; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashSet; @@ -23,33 +26,110 @@ public class dbRaceHandler extends dbHandlerBase { } public HashSet BEARD_COLORS_FOR_RACE(final int id) { - prepareCallable("SELECT `color` FROM `static_rune_racebeardcolor` WHERE `RaceID` = ?"); - setInt(1, id); - return getIntegerList(1); + + HashSet integerSet = new HashSet<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `color` FROM `static_rune_racebeardcolor` WHERE `RaceID` = ?")) { + + preparedStatement.setInt(1, id); + + ResultSet rs = preparedStatement.executeQuery(); + + while (rs.next()) + integerSet.add(rs.getInt(1)); + + } catch (SQLException e) { + Logger.error(e); + } + + return integerSet; } public HashSet BEARD_STYLES_FOR_RACE(final int id) { - prepareCallable("SELECT `beardStyle` FROM `static_rune_racebeardstyle` WHERE `RaceID` = ?"); - setInt(1, id); - return getIntegerList(1); + + HashSet integerSet = new HashSet<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `beardStyle` FROM `static_rune_racebeardstyle` WHERE `RaceID` = ?")) { + + preparedStatement.setInt(1, id); + + ResultSet rs = preparedStatement.executeQuery(); + + while (rs.next()) + integerSet.add(rs.getInt(1)); + + } catch (SQLException e) { + Logger.error(e); + } + + return integerSet; } public HashSet HAIR_COLORS_FOR_RACE(final int id) { - prepareCallable("SELECT `color` FROM `static_rune_racehaircolor` WHERE `RaceID` = ?"); - setInt(1, id); - return getIntegerList(1); + + HashSet integerSet = new HashSet<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `color` FROM `static_rune_racehaircolor` WHERE `RaceID` = ?")) { + + preparedStatement.setInt(1, id); + + ResultSet rs = preparedStatement.executeQuery(); + + while (rs.next()) + integerSet.add(rs.getInt(1)); + + } catch (SQLException e) { + Logger.error(e); + } + + return integerSet; + } public HashSet HAIR_STYLES_FOR_RACE(final int id) { - prepareCallable("SELECT `hairStyle` FROM `static_rune_racehairstyle` WHERE `RaceID` = ?"); - setInt(1, id); - return getIntegerList(1); + + HashSet integerSet = new HashSet<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `hairStyle` FROM `static_rune_racehairstyle` WHERE `RaceID` = ?")) { + + preparedStatement.setInt(1, id); + + ResultSet rs = preparedStatement.executeQuery(); + + while (rs.next()) + integerSet.add(rs.getInt(1)); + + } catch (SQLException e) { + Logger.error(e); + } + + return integerSet; + } public HashSet SKIN_COLOR_FOR_RACE(final int id) { - prepareCallable("SELECT `color` FROM `static_rune_raceskincolor` WHERE `RaceID` = ?"); - setInt(1, id); - return getIntegerList(1); + + HashSet integerSet = new HashSet<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `color` FROM `static_rune_raceskincolor` WHERE `RaceID` = ?")) { + + preparedStatement.setInt(1, id); + + ResultSet rs = preparedStatement.executeQuery(); + + while (rs.next()) + integerSet.add(rs.getInt(1)); + + } catch (SQLException e) { + Logger.error(e); + } + + return integerSet; } public ConcurrentHashMap LOAD_ALL_RACES() { @@ -60,10 +140,10 @@ public class dbRaceHandler extends dbHandlerBase { races = new ConcurrentHashMap<>(); int recordsRead = 0; - prepareCallable("SELECT * FROM static_rune_race"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_rune_race")) { - try { - ResultSet rs = executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { @@ -73,13 +153,11 @@ public class dbRaceHandler extends dbHandlerBase { races.put(thisRace.getRaceRuneID(), thisRace); } - Logger.info("read: " + recordsRead + " cached: " + races.size()); - } catch (SQLException e) { - Logger.error( e.toString()); - } finally { - closeCallable(); + Logger.error(e); } + + Logger.info("read: " + recordsRead + " cached: " + races.size()); return races; } } From f6aa71e9fb03a1166e402a22237220de492e94f3 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 12:42:34 -0400 Subject: [PATCH 073/109] Refactor to remove abstraction. --- src/engine/db/handlers/dbRealmHandler.java | 47 ++++++++++----------- src/engine/db/handlers/dbResistHandler.java | 30 ++++++++----- src/engine/objects/Realm.java | 3 +- 3 files changed, 44 insertions(+), 36 deletions(-) diff --git a/src/engine/db/handlers/dbRealmHandler.java b/src/engine/db/handlers/dbRealmHandler.java index c11147c6..fd076505 100644 --- a/src/engine/db/handlers/dbRealmHandler.java +++ b/src/engine/db/handlers/dbRealmHandler.java @@ -9,14 +9,12 @@ package engine.db.handlers; +import engine.gameManager.DbManager; import engine.objects.Realm; import org.pmw.tinylog.Logger; -import java.net.UnknownHostException; -import java.sql.ResultSet; -import java.sql.SQLException; +import java.sql.*; import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Level; public class dbRealmHandler extends dbHandlerBase { @@ -32,42 +30,43 @@ public class dbRealmHandler extends dbHandlerBase { realmList = new ConcurrentHashMap<>(); int recordsRead = 0; - prepareCallable("SELECT * FROM obj_realm"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM obj_realm")) { - try { - ResultSet rs = executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { - recordsRead++; thisRealm = new Realm(rs); realmList.put(thisRealm.getRealmID(), thisRealm); } - Logger.info("read: " + recordsRead + " cached: " + realmList.size()); - } catch (SQLException e) { - Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); - } catch (UnknownHostException ex) { - java.util.logging.Logger.getLogger(dbRealmHandler.class.getName()).log(Level.SEVERE, null, ex); - } finally { - closeCallable(); + Logger.error(e); } + + Logger.info("read: " + recordsRead + " cached: " + realmList.size()); return realmList; } public void REALM_UPDATE(Realm realm) { - prepareCallable("CALL realm_UPDATE(?,?,?,?)"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL realm_UPDATE(?,?,?,?)")) { + + preparedStatement.setInt(1, realm.getRealmID()); + preparedStatement.setInt(2, (realm.getRulingCity() == null) ? 0 : realm.getRulingCity().getObjectUUID()); + preparedStatement.setInt(3, realm.getCharterType()); - setInt(1, realm.getRealmID()); - setInt(2, (realm.getRulingCity() == null) ? 0 : realm.getRulingCity().getObjectUUID()); - setInt(3, realm.getCharterType()); - if (realm.ruledSince != null) - setLocalDateTime(4, realm.ruledSince); - else - setNULL(4, java.sql.Types.DATE); + if (realm.ruledSince != null) + preparedStatement.setTimestamp(4, Timestamp.valueOf(realm.ruledSince)); + else + preparedStatement.setNull(4, java.sql.Types.DATE); - executeUpdate(); + preparedStatement.execute(); + + } catch (SQLException e) { + Logger.error(e); + } } } diff --git a/src/engine/db/handlers/dbResistHandler.java b/src/engine/db/handlers/dbResistHandler.java index 0eccf2e2..7557ba37 100644 --- a/src/engine/db/handlers/dbResistHandler.java +++ b/src/engine/db/handlers/dbResistHandler.java @@ -9,8 +9,12 @@ package engine.db.handlers; +import engine.gameManager.DbManager; import engine.objects.Resists; +import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -21,17 +25,23 @@ public class dbResistHandler extends dbHandlerBase { } public Resists GET_RESISTS_FOR_MOB(int resistID) { - prepareCallable("SELECT * FROM `static_npc_mob_resists` WHERE `ID` = ?;"); - setInt(1, resistID); - try { - ResultSet rs = executeQuery(); - if (rs.next()) { - return new Resists(rs); - } + + Resists resists = null; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_mob_resists` WHERE `ID` = ?;")) { + + preparedStatement.setInt(1, resistID); + + ResultSet rs = preparedStatement.executeQuery(); + + if (rs.next()) + resists = new Resists(rs); + } catch (SQLException e) { - } finally { - closeCallable(); + Logger.error(e); } - return null; + + return resists; } } diff --git a/src/engine/objects/Realm.java b/src/engine/objects/Realm.java index 26b5a2d0..7f00fcd9 100644 --- a/src/engine/objects/Realm.java +++ b/src/engine/objects/Realm.java @@ -22,7 +22,6 @@ import engine.server.MBServerStatics; import org.pmw.tinylog.Logger; import java.awt.*; -import java.net.UnknownHostException; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDateTime; @@ -72,7 +71,7 @@ public class Realm { /** * ResultSet Constructor */ - public Realm(ResultSet rs) throws SQLException, UnknownHostException { + public Realm(ResultSet rs) throws SQLException { this.mapColor = new Color(Integer.parseInt(rs.getString("realmColor"), 16)); this.mapR = (float) (mapColor.getRed() * 0.00392156863); From 3a95cc9b58524ad5afacca9861d4e38f8cf49e80 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 12:45:55 -0400 Subject: [PATCH 074/109] Refactor to remove abstraction. --- .../handlers/dbRuneBaseAttributeHandler.java | 28 +++++++++++++------ 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/src/engine/db/handlers/dbRuneBaseAttributeHandler.java b/src/engine/db/handlers/dbRuneBaseAttributeHandler.java index ce880b6a..923385b1 100644 --- a/src/engine/db/handlers/dbRuneBaseAttributeHandler.java +++ b/src/engine/db/handlers/dbRuneBaseAttributeHandler.java @@ -9,8 +9,14 @@ package engine.db.handlers; +import engine.gameManager.DbManager; import engine.objects.RuneBaseAttribute; +import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.ArrayList; public class dbRuneBaseAttributeHandler extends dbHandlerBase { @@ -20,15 +26,21 @@ public class dbRuneBaseAttributeHandler extends dbHandlerBase { this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); } - public ArrayList GET_ATTRIBUTES_FOR_RUNEBASE(int id) { - prepareCallable("SELECT * FROM `static_rune_runebaseattribute` WHERE `RuneBaseID`=?"); - setInt(1, id); - return getObjectList(); - } - public ArrayList GET_ATTRIBUTES_FOR_RUNEBASE() { - prepareCallable("SELECT * FROM `static_rune_runebaseattribute`"); - return getObjectList(); + + ArrayList runeBaseAttributesList = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_runebaseattribute`")) { + + ResultSet rs = preparedStatement.executeQuery(); + runeBaseAttributesList = getObjectsFromRs(rs, 10); + + } catch (SQLException e) { + Logger.error(e); + } + + return runeBaseAttributesList; } From 4b0a3627d495f8f8b870db09e8044b96a2c43aa7 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 12:50:04 -0400 Subject: [PATCH 075/109] Refactor to remove abstraction. --- .../db/handlers/dbRuneBaseEffectHandler.java | 54 +++++++++++++------ 1 file changed, 37 insertions(+), 17 deletions(-) diff --git a/src/engine/db/handlers/dbRuneBaseEffectHandler.java b/src/engine/db/handlers/dbRuneBaseEffectHandler.java index 0e84c8d0..14c51683 100644 --- a/src/engine/db/handlers/dbRuneBaseEffectHandler.java +++ b/src/engine/db/handlers/dbRuneBaseEffectHandler.java @@ -13,7 +13,12 @@ import engine.Enum.GameObjectType; import engine.gameManager.DbManager; import engine.objects.AbstractGameObject; import engine.objects.RuneBaseEffect; +import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; @@ -25,34 +30,49 @@ public class dbRuneBaseEffectHandler extends dbHandlerBase { } public ArrayList GET_EFFECTS_FOR_RUNEBASE(int id) { - prepareCallable("SELECT * FROM `static_rune_baseeffect` WHERE `runeID`=?"); - setInt(1, id); - return getObjectList(); - } - public RuneBaseEffect GET_RUNEBASE_EFFECT(int id) { + ArrayList runeBaseEffectsList = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_baseeffect` WHERE `runeID`=?")) { + + preparedStatement.setInt(1, id); + + ResultSet rs = preparedStatement.executeQuery(); + runeBaseEffectsList = getObjectsFromRs(rs, 250); - if (id == 0) - return null; - RuneBaseEffect runeBaseEffect = (RuneBaseEffect) DbManager.getFromCache(GameObjectType.RuneBaseEffect, id); - if (runeBaseEffect != null) - return runeBaseEffect; - prepareCallable("SELECT * FROM `static_rune_baseeffect` WHERE `ID` = ?"); - setInt(1, id); - return (RuneBaseEffect) getObjectSingle(id); + } catch (SQLException e) { + Logger.error(e); + } + + return runeBaseEffectsList; } - public ArrayList GET_ALL_RUNEBASE_EFFECTS(){ - prepareCallable("SELECT * FROM `static_rune_baseeffect`;"); - return getObjectList(); + public ArrayList GET_ALL_RUNEBASE_EFFECTS() { + + ArrayList runeBaseEffectsList = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_baseeffect`;")) { + + + ResultSet rs = preparedStatement.executeQuery(); + runeBaseEffectsList = getObjectsFromRs(rs, 250); + + } catch (SQLException e) { + Logger.error(e); + } + + return runeBaseEffectsList; } //This calls from cache only. Call this AFTER caching all runebase effects; + public HashMap> LOAD_BASEEFFECTS_FOR_RUNEBASE() { + HashMap> runeBaseEffectSet; runeBaseEffectSet = new HashMap<>(); - for (AbstractGameObject runeBaseEffect:DbManager.getList(GameObjectType.RuneBaseEffect)){ int runeBaseID = ((RuneBaseEffect)runeBaseEffect).getRuneBaseID(); From 3e604b53faa93372db1bdf021fae9785deb6f14a Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 12:58:16 -0400 Subject: [PATCH 076/109] Refactor to remove abstraction. --- .../db/handlers/dbRuneBaseEffectHandler.java | 1 - src/engine/db/handlers/dbRuneBaseHandler.java | 152 +++++++++--------- 2 files changed, 79 insertions(+), 74 deletions(-) diff --git a/src/engine/db/handlers/dbRuneBaseEffectHandler.java b/src/engine/db/handlers/dbRuneBaseEffectHandler.java index 14c51683..c8b790a1 100644 --- a/src/engine/db/handlers/dbRuneBaseEffectHandler.java +++ b/src/engine/db/handlers/dbRuneBaseEffectHandler.java @@ -55,7 +55,6 @@ public class dbRuneBaseEffectHandler extends dbHandlerBase { try (Connection connection = DbManager.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_baseeffect`;")) { - ResultSet rs = preparedStatement.executeQuery(); runeBaseEffectsList = getObjectsFromRs(rs, 250); diff --git a/src/engine/db/handlers/dbRuneBaseHandler.java b/src/engine/db/handlers/dbRuneBaseHandler.java index 44e58179..235f96a9 100644 --- a/src/engine/db/handlers/dbRuneBaseHandler.java +++ b/src/engine/db/handlers/dbRuneBaseHandler.java @@ -9,14 +9,16 @@ package engine.db.handlers; +import engine.gameManager.DbManager; import engine.objects.RuneBase; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; -import java.util.HashSet; public class dbRuneBaseHandler extends dbHandlerBase { @@ -26,66 +28,90 @@ public class dbRuneBaseHandler extends dbHandlerBase { } public void GET_RUNE_REQS(final RuneBase rb) { - prepareCallable("SELECT * FROM `static_rune_runereq` WHERE `runeID` = ?"); - setInt(1, rb.getObjectUUID()); - try { - ResultSet rs = executeQuery(); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_runereq` WHERE `runeID` = ?")) { + + preparedStatement.setInt(1, rb.getObjectUUID()); + + ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { int type = rs.getInt("type"); switch (type) { - case 1: - rb.getRace().put(rs.getInt("requiredRuneID"), rs.getBoolean("isAllowed")); - break; - case 2: - rb.getBaseClass().put(rs.getInt("requiredRuneID"), rs.getBoolean("isAllowed")); - break; - case 3: - rb.getPromotionClass().put(rs.getInt("requiredRuneID"), rs.getBoolean("isAllowed")); - break; - case 4: - rb.getDiscipline().put(rs.getInt("requiredRuneID"), rs.getBoolean("isAllowed")); - break; - case 5: - rb.getOverwrite().add(rs.getInt("requiredRuneID")); - break; - case 6: - rb.setLevelRequired(rs.getInt("requiredRuneID")); - break; + case 1: + rb.getRace().put(rs.getInt("requiredRuneID"), rs.getBoolean("isAllowed")); + break; + case 2: + rb.getBaseClass().put(rs.getInt("requiredRuneID"), rs.getBoolean("isAllowed")); + break; + case 3: + rb.getPromotionClass().put(rs.getInt("requiredRuneID"), rs.getBoolean("isAllowed")); + break; + case 4: + rb.getDiscipline().put(rs.getInt("requiredRuneID"), rs.getBoolean("isAllowed")); + break; + case 5: + rb.getOverwrite().add(rs.getInt("requiredRuneID")); + break; + case 6: + rb.setLevelRequired(rs.getInt("requiredRuneID")); + break; } } - rs.close(); + } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } finally { - closeCallable(); + Logger.error(e); } + } public RuneBase GET_RUNEBASE(final int id) { - prepareCallable("SELECT * FROM `static_rune_runebase` WHERE `ID` = ?"); - setInt(1, id); - return (RuneBase) getObjectSingle(id); + + RuneBase runeBase = null; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_runebase` WHERE `ID` = ?")) { + + preparedStatement.setInt(1, id); + + ResultSet rs = preparedStatement.executeQuery(); + runeBase = (RuneBase) getObjectFromRs(rs); + + } catch (SQLException e) { + Logger.error(e); + } + return runeBase; } public ArrayList LOAD_ALL_RUNEBASES() { - prepareCallable("SELECT * FROM `static_rune_runebase`;"); - return getObjectList(); + + ArrayList runeBasesList = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_runebase`;")) { + + ResultSet rs = preparedStatement.executeQuery(); + runeBasesList = getObjectsFromRs(rs, 1000); + + } catch (SQLException e) { + Logger.error(e); + } + + return runeBasesList; } public HashMap> LOAD_ALLOWED_STARTING_RUNES_FOR_BASECLASS() { - HashMap> runeSets; + HashMap> runeSets = new HashMap<>(); - runeSets = new HashMap<>(); int recordsRead = 0; - prepareCallable("SELECT * FROM static_rune_baseclassrune"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_rune_baseclassrune")) { - try { - ResultSet rs = executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { @@ -94,25 +120,23 @@ public class dbRuneBaseHandler extends dbHandlerBase { int baseClassID = rs.getInt("BaseClassesID"); int runeBaseID = rs.getInt("RuneBaseID"); - if (runeSets.get(baseClassID) == null){ + if (runeSets.get(baseClassID) == null) { ArrayList runeList = new ArrayList<>(); runeList.add(runeBaseID); runeSets.put(baseClassID, runeList); - } - else{ - ArrayListruneList = runeSets.get(baseClassID); + } else { + ArrayList runeList = runeSets.get(baseClassID); runeList.add(runeBaseID); runeSets.put(baseClassID, runeList); } } - Logger.info("read: " + recordsRead + " cached: " + runeSets.size()); - } catch (SQLException e) { - Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); + Logger.error(e); } + + Logger.info("read: " + recordsRead + " cached: " + runeSets.size()); + return runeSets; } @@ -123,10 +147,10 @@ public class dbRuneBaseHandler extends dbHandlerBase { runeSets = new HashMap<>(); int recordsRead = 0; - prepareCallable("SELECT * FROM static_rune_racerune"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_rune_racerune")) { - try { - ResultSet rs = executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { @@ -135,39 +159,21 @@ public class dbRuneBaseHandler extends dbHandlerBase { int raceID = rs.getInt("RaceID"); int runeBaseID = rs.getInt("RuneBaseID"); - if (runeSets.get(raceID) == null){ + if (runeSets.get(raceID) == null) { ArrayList runeList = new ArrayList<>(); runeList.add(runeBaseID); runeSets.put(raceID, runeList); - } - else{ - ArrayListruneList = runeSets.get(raceID); + } else { + ArrayList runeList = runeSets.get(raceID); runeList.add(runeBaseID); runeSets.put(raceID, runeList); } } - - Logger.info( "read: " + recordsRead + " cached: " + runeSets.size()); - } catch (SQLException e) { - Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); + Logger.error(e); } - return runeSets; - } - - public ArrayList GET_RUNEBASE_FOR_BASECLASS(final int id) { - prepareCallable("SELECT rb.* FROM static_rune_baseclassrune bcr, static_rune_runebase rb WHERE bcr.RuneBaseID = rb.ID " - + "&& ( bcr.BaseClassesID = 111111 || bcr.BaseClassesID = ? )"); - setInt(1, id); - return getObjectList(); - } - public HashSet GET_RUNEBASE_FOR_RACE(final int id) { - prepareCallable("SELECT rb.* FROM static_rune_racerune rr, static_rune_runebase rb" - + " WHERE rr.RuneBaseID = rb.ID && ( rr.RaceID = 111111 || rr.RaceID = ?)"); - setInt(1, id); - return new HashSet<>(getObjectList()); + Logger.info("read: " + recordsRead + " cached: " + runeSets.size()); + return runeSets; } } From 9bdbeeaf70c5911e264058f9d341d8ef068c406c Mon Sep 17 00:00:00 2001 From: MagicBot Date: Mon, 22 May 2023 13:00:47 -0400 Subject: [PATCH 077/109] Refactor to remove abstraction. --- src/engine/db/handlers/dbRunegateHandler.java | 30 ++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/src/engine/db/handlers/dbRunegateHandler.java b/src/engine/db/handlers/dbRunegateHandler.java index c0cc5b01..50b928b0 100644 --- a/src/engine/db/handlers/dbRunegateHandler.java +++ b/src/engine/db/handlers/dbRunegateHandler.java @@ -15,6 +15,8 @@ import engine.objects.Building; import engine.objects.Portal; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; @@ -29,17 +31,18 @@ public class dbRunegateHandler extends dbHandlerBase { ArrayList gateList = new ArrayList<>(); - prepareCallable("SELECT DISTINCT `sourceBuilding` FROM `static_runegate_portals`;"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT DISTINCT `sourceBuilding` FROM `static_runegate_portals`;")) { - try { - ResultSet rs = executeQuery(); - while (rs.next()) { + ResultSet rs = preparedStatement.executeQuery(); + + while (rs.next()) gateList.add(rs.getInt("sourceBuilding")); - } + } catch (SQLException e) { - } finally { - closeCallable(); + Logger.error(e); } + return gateList; } @@ -48,11 +51,12 @@ public class dbRunegateHandler extends dbHandlerBase { ArrayList portalList = new ArrayList<>(); Building sourceBuilding = (Building) DbManager.getObject(Enum.GameObjectType.Building, gateUID); - prepareCallable("SELECT * FROM `static_runegate_portals` WHERE `sourceBuilding` = ?;"); - setInt(1, gateUID); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_runegate_portals` WHERE `sourceBuilding` = ?;")) { + + preparedStatement.setInt(1, gateUID); - try { - ResultSet rs = executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { int targetBuildingID = rs.getInt("targetBuilding"); @@ -63,9 +67,7 @@ public class dbRunegateHandler extends dbHandlerBase { } } catch (SQLException e) { - Logger.error("Exception while loading runegate portals: " + e); - } finally { - closeCallable(); + Logger.error(e); } return portalList; } From 478e472dc418873002cdf273c48889144ff5cfd2 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 08:20:20 -0400 Subject: [PATCH 078/109] Refactor to remove abstraction. --- src/engine/db/handlers/dbShrineHandler.java | 140 ++++++++++---------- 1 file changed, 68 insertions(+), 72 deletions(-) diff --git a/src/engine/db/handlers/dbShrineHandler.java b/src/engine/db/handlers/dbShrineHandler.java index fbf23eff..2dc1289e 100644 --- a/src/engine/db/handlers/dbShrineHandler.java +++ b/src/engine/db/handlers/dbShrineHandler.java @@ -18,7 +18,8 @@ import engine.objects.Shrine; import org.joda.time.DateTime; import org.pmw.tinylog.Logger; -import java.net.UnknownHostException; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; @@ -35,78 +36,77 @@ public class dbShrineHandler extends dbHandlerBase { ProtectionState protectionState, int currentGold, int rank, DateTime upgradeDate, int blueprintUUID, float w, float rotY, String shrineType) { - prepareCallable("CALL `shrine_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,? ,? ,?, ?,?);"); - - - setInt(1, parentZoneID); - setInt(2, OwnerUUID); - setString(3, name); - setInt(4, meshUUID); - setFloat(5, location.x); - setFloat(6, location.y); - setFloat(7, location.z); - setFloat(8, meshScale); - setInt(9, currentHP); - setString(10, protectionState.name()); - setInt(11, currentGold); - setInt(12, rank); - - if (upgradeDate != null) { - setTimeStamp(13, upgradeDate.getMillis()); - } else { - setNULL(13, java.sql.Types.DATE); - } + ArrayList shrineList = new ArrayList<>(); - setInt(14, blueprintUUID); - setFloat(15, w); - setFloat(16, rotY); - setString(17, shrineType); - - ArrayList list = new ArrayList<>(); - //System.out.println(this.cs.get().toString()); - try { - boolean work = execute(); - if (work) { - ResultSet rs = this.callableStatement.get().getResultSet(); - while (rs.next()) { - addObject(list, rs); - } - rs.close(); - } else { - Logger.info("Shrine Creation Failed: " + this.callableStatement.get().toString()); - return list; //city creation failure - } - while (this.callableStatement.get().getMoreResults()) { - ResultSet rs = this.callableStatement.get().getResultSet(); - while (rs.next()) { - addObject(list, rs); - } - rs.close(); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL `shrine_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,? ,? ,?, ?,?);")) { + + preparedStatement.setInt(1, parentZoneID); + preparedStatement.setInt(2, OwnerUUID); + preparedStatement.setString(3, name); + preparedStatement.setInt(4, meshUUID); + preparedStatement.setFloat(5, location.x); + preparedStatement.setFloat(6, location.y); + preparedStatement.setFloat(7, location.z); + preparedStatement.setFloat(8, meshScale); + preparedStatement.setInt(9, currentHP); + preparedStatement.setString(10, protectionState.name()); + preparedStatement.setInt(11, currentGold); + preparedStatement.setInt(12, rank); + + if (upgradeDate != null) + preparedStatement.setTimestamp(13, new java.sql.Timestamp(upgradeDate.getMillis())); + else + preparedStatement.setNull(13, java.sql.Types.DATE); + + preparedStatement.setInt(14, blueprintUUID); + preparedStatement.setFloat(15, w); + preparedStatement.setFloat(16, rotY); + preparedStatement.setString(17, shrineType); + + preparedStatement.execute(); + + ResultSet rs = preparedStatement.getResultSet(); + + while (rs.next()) + addObject(shrineList, rs); + + while (preparedStatement.getMoreResults()) { + rs = preparedStatement.getResultSet(); + + while (rs.next()) + addObject(shrineList, rs); } + } catch (SQLException e) { - Logger.info("Shrine Creation Failed, SQLException: " + this.callableStatement.get().toString() + e.toString()); - return list; //city creation failure - } catch (UnknownHostException e) { - Logger.info("Shrine Creation Failed, UnknownHostException: " + this.callableStatement.get().toString()); - return list; //city creation failure - } finally { - closeCallable(); + Logger.error(e); } - return list; + return shrineList; } public boolean updateFavors(Shrine shrine, int amount, int oldAmount) { - prepareCallable("UPDATE `obj_shrine` SET `shrine_favors`=? WHERE `UID` = ? AND `shrine_favors` = ?"); - setInt(1, amount); - setLong(2, (long) shrine.getObjectUUID()); - setInt(3, oldAmount); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_shrine` SET `shrine_favors`=? WHERE `UID` = ? AND `shrine_favors` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setLong(2, shrine.getObjectUUID()); + preparedStatement.setInt(3, oldAmount); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + return false; + } + } - public static void addObject(ArrayList list, ResultSet rs) throws SQLException, UnknownHostException { + public static void addObject(ArrayList list, ResultSet rs) throws SQLException { + String type = rs.getString("type"); + switch (type) { case "building": Building building = new Building(rs); @@ -123,25 +123,21 @@ public class dbShrineHandler extends dbHandlerBase { public void LOAD_ALL_SHRINES() { - Shrine thisShrine; + Shrine shrine; - prepareCallable("SELECT `obj_shrine`.*, `object`.`parent`, `object`.`type` FROM `object` LEFT JOIN `obj_shrine` ON `object`.`UID` = `obj_shrine`.`UID` WHERE `object`.`type` = 'shrine';"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_shrine`.*, `object`.`parent`, `object`.`type` FROM `object` LEFT JOIN `obj_shrine` ON `object`.`UID` = `obj_shrine`.`UID` WHERE `object`.`type` = 'shrine';")) { - try { - ResultSet rs = executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); - //shrines cached in rs for easy cache on creation. while (rs.next()) { - thisShrine = new Shrine(rs); - thisShrine.getShrineType().addShrineToServerList(thisShrine); + shrine = new Shrine(rs); + shrine.getShrineType().addShrineToServerList(shrine); } } catch (SQLException e) { - Logger.error( e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); + Logger.error(e); } - } } From fce67a6bae50a8da37468e27a43e551973a266c8 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 08:22:46 -0400 Subject: [PATCH 079/109] Refactor to remove abstraction. --- .../db/handlers/dbSkillBaseHandler.java | 21 +++++++------------ 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/src/engine/db/handlers/dbSkillBaseHandler.java b/src/engine/db/handlers/dbSkillBaseHandler.java index f35b7be4..0811c3a2 100644 --- a/src/engine/db/handlers/dbSkillBaseHandler.java +++ b/src/engine/db/handlers/dbSkillBaseHandler.java @@ -17,6 +17,8 @@ import engine.objects.MaxSkills; import engine.objects.SkillsBase; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; @@ -110,34 +112,27 @@ public class dbSkillBaseHandler extends dbHandlerBase { public void LOAD_ALL_RUNE_SKILLS() { - prepareCallable("SELECT * FROM `static_skill_skillsgranted`"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_skill_skillsgranted`")) { - try { - ResultSet rs = executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); - //shrines cached in rs for easy cache on creation. while (rs.next()) { int runeID = rs.getInt("runeID"); int token = rs.getInt("token"); int amount = rs.getInt("amount"); - + if (SkillsBase.runeSkillsCache.get(runeID) == null) SkillsBase.runeSkillsCache.put(runeID, new HashMap<>()); - + SkillsBase.runeSkillsCache.get(runeID).put(token, amount); } - - } catch (SQLException e) { - Logger.error( e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); + Logger.error(e); } - } - } From e9cb8112ded30f57b3f696e532c7a7616aded4e3 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 08:31:10 -0400 Subject: [PATCH 080/109] Refactor to remove abstraction. --- src/engine/db/handlers/dbSkillReqHandler.java | 81 +++++++++++-------- 1 file changed, 47 insertions(+), 34 deletions(-) diff --git a/src/engine/db/handlers/dbSkillReqHandler.java b/src/engine/db/handlers/dbSkillReqHandler.java index 6025b7c6..c2e0830c 100644 --- a/src/engine/db/handlers/dbSkillReqHandler.java +++ b/src/engine/db/handlers/dbSkillReqHandler.java @@ -9,12 +9,15 @@ package engine.db.handlers; -import engine.objects.PreparedStatementShared; +import engine.gameManager.DbManager; import engine.objects.SkillReq; import engine.powers.PowersBase; import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; +import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; @@ -26,36 +29,39 @@ public class dbSkillReqHandler extends dbHandlerBase { } public static ArrayList getAllPowersBase() { - PreparedStatementShared ps = null; - ArrayList out = new ArrayList<>(); - try { - ps = new PreparedStatementShared("SELECT * FROM static_power_powerbase"); - ResultSet rs = ps.executeQuery(); + + ArrayList powerBaseList = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_power_powerbase")) { + + ResultSet rs = preparedStatement.executeQuery(); + while (rs.next()) { PowersBase toAdd = new PowersBase(rs); - out.add(toAdd); + powerBaseList.add(toAdd); } - rs.close(); - } catch (Exception e) { - Logger.error(e.toString()); - } finally { - ps.release(); + + } catch (SQLException e) { + Logger.error(e); } - return out; + + return powerBaseList; } public static void getFailConditions(HashMap powers) { - PreparedStatementShared ps = null; - try { - ps = new PreparedStatementShared("SELECT IDString, type FROM static_power_failcondition where powerOrEffect = 'Power'"); - ResultSet rs = ps.executeQuery(); - String type, IDString; - PowersBase pb; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT IDString, type FROM static_power_failcondition where powerOrEffect = 'Power'")) { + + ResultSet rs = preparedStatement.executeQuery(); + while (rs.next()) { - type = rs.getString("type"); - IDString = rs.getString("IDString"); - pb = powers.get(IDString); - if (pb != null) { + String type = rs.getString("type"); + String IDString = rs.getString("IDString"); + PowersBase pb = powers.get(IDString); + + if (pb != null) switch (type) { case "CastSpell": pb.cancelOnCastSpell = true; @@ -64,22 +70,29 @@ public class dbSkillReqHandler extends dbHandlerBase { pb.cancelOnTakeDamage = true; break; } - } else { - Logger.error("null power for Grief " + IDString); - } } - rs.close(); - } catch (Exception e) { - Logger.error(e.toString()); - } finally { - ps.release(); + } catch (SQLException e) { + Logger.error(e); } } public ArrayList GET_REQS_FOR_RUNE(final int objectUUID) { - prepareCallable("SELECT * FROM `static_skill_skillreq` WHERE `runeID`=?"); - setInt(1, objectUUID); - return getObjectList(); + + ArrayList skillReqsList = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_skill_skillreq` WHERE `runeID`=?")) { + + preparedStatement.setInt(1, objectUUID); + + ResultSet rs = preparedStatement.executeQuery(); + skillReqsList = getObjectsFromRs(rs, 5); + + } catch (SQLException e) { + Logger.error(e); + } + + return skillReqsList; } } From 98237cd53ee398a185350dd343833b72677bd5fa Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 08:33:14 -0400 Subject: [PATCH 081/109] Refactor to remove abstraction. --- .../db/handlers/dbVendorDialogHandler.java | 31 +++++++++++++++---- 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/src/engine/db/handlers/dbVendorDialogHandler.java b/src/engine/db/handlers/dbVendorDialogHandler.java index def139f2..eb6a1c92 100644 --- a/src/engine/db/handlers/dbVendorDialogHandler.java +++ b/src/engine/db/handlers/dbVendorDialogHandler.java @@ -12,6 +12,12 @@ package engine.db.handlers; import engine.Enum; import engine.gameManager.DbManager; import engine.objects.VendorDialog; +import org.pmw.tinylog.Logger; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; public class dbVendorDialogHandler extends dbHandlerBase { @@ -21,11 +27,24 @@ public class dbVendorDialogHandler extends dbHandlerBase { } public VendorDialog GET_VENDORDIALOG(final int objectUUID) { - VendorDialog vd = (VendorDialog) DbManager.getFromCache(Enum.GameObjectType.VendorDialog, objectUUID); - if (vd != null) - return vd; - prepareCallable("SELECT * FROM `static_npc_vendordialog` WHERE `ID`=?"); - setInt(1, objectUUID); - return (VendorDialog) getObjectSingle(objectUUID); + + VendorDialog vendorDialog = (VendorDialog) DbManager.getFromCache(Enum.GameObjectType.VendorDialog, objectUUID); + + if (vendorDialog != null) + return vendorDialog; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_vendordialog` WHERE `ID`=?")) { + + preparedStatement.setInt(1, objectUUID); + + ResultSet rs = preparedStatement.executeQuery(); + vendorDialog = (VendorDialog) getObjectFromRs(rs); + + } catch (SQLException e) { + Logger.error(e); + } + + return vendorDialog; } } From 55756472c68a93b42b5fd6d680066e99a6070264 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 08:38:20 -0400 Subject: [PATCH 082/109] Bonus code removed. --- .../db/handlers/dbWarehouseHandler.java | 86 ------------------- 1 file changed, 86 deletions(-) diff --git a/src/engine/db/handlers/dbWarehouseHandler.java b/src/engine/db/handlers/dbWarehouseHandler.java index d16f451e..c59142dd 100644 --- a/src/engine/db/handlers/dbWarehouseHandler.java +++ b/src/engine/db/handlers/dbWarehouseHandler.java @@ -33,20 +33,6 @@ public class dbWarehouseHandler extends dbHandlerBase { this.localClass = Warehouse.class; this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); - if (columns.isEmpty()) { - createColumns(); - } - } - - public Warehouse CREATE_WAREHOUSE(Warehouse wh) { - try { - wh = this.addWarehouse(wh); - } catch (Exception e) { - Logger.error(e); - wh = null; - - } - return wh; } public ArrayList CREATE_WAREHOUSE( int parentZoneID, int OwnerUUID, String name, int meshUUID, @@ -113,50 +99,6 @@ public class dbWarehouseHandler extends dbHandlerBase { } - //Don't call yet, not ready in DB. - - public boolean WAREHOUSE_ADD(Item item, Warehouse warehouse, ItemBase ib, int amount) { - if (item == null || warehouse == null || ib == null || !(dbWarehouseHandler.columns.containsKey(ib.getUUID()))) { - return false; - } - if ((item.getNumOfItems() - amount) < 0) { - return false; - } - if (!warehouse.getResources().containsKey(ib)) { - return false; - } - - prepareCallable("CALL `warehouse_ADD`(?,?,?,?,?,?,?);"); - setLong(1, (long) warehouse.getObjectUUID()); - setInt(2, warehouse.getResources().get(ib)); - setLong(3, (long) item.getObjectUUID()); - setInt(4, item.getNumOfItems()); - setInt(5, amount); - setString(6, dbWarehouseHandler.columns.get(ib.getUUID())); - setInt(7, ib.getUUID()); - String result = getResult(); - - return (result != null && result.equals("success")); - } - - private Warehouse addWarehouse(Warehouse toAdd) { - prepareCallable("CALL `warehouse_CREATE`(?);"); - setInt(1, toAdd.getUID()); - int objectUUID = (int) getUUID(); - if (objectUUID > 0) { - return GET_WAREHOUSE(objectUUID); - } - return null; - } - - public Warehouse GET_WAREHOUSE(int objectUUID) { - Warehouse warehouse = (Warehouse) DbManager.getFromCache(GameObjectType.Warehouse, objectUUID); - if (warehouse != null) - return warehouse; - prepareCallable("SELECT * FROM `obj_warehouse` WHERE `UID` = ?"); - setInt(1, objectUUID); - return (Warehouse) getObjectSingle(objectUUID); - } - public boolean updateLocks(final Warehouse wh, long locks) { prepareCallable("UPDATE `obj_warehouse` SET `warehouse_locks`=? WHERE `UID` = ?"); setLong(1, locks); @@ -347,32 +289,6 @@ public class dbWarehouseHandler extends dbHandlerBase { return (executeUpdate() != 0); } - private static void createColumns() { - columns.put(1580000, "warehouse_stone"); - columns.put(1580001, "warehouse_truesteel"); - columns.put(1580002, "warehouse_iron"); - columns.put(1580003, "warehouse_adamant"); - columns.put(1580004, "warehouse_lumber"); - columns.put(1580005, "warehouse_oak"); - columns.put(1580006, "warehouse_bronzewood"); - columns.put(1580007, "warehouse_mandrake"); - columns.put(1580008, "warehouse_coal"); - columns.put(1580009, "warehouse_agate"); - columns.put(1580010, "warehouse_diamond"); - columns.put(1580011, "warehouse_onyx"); - columns.put(1580012, "warehouse_azoth"); - columns.put(1580013, "warehouse_orichalk"); - columns.put(1580014, "warehouse_antimony"); - columns.put(1580015, "warehouse_sulfur"); - columns.put(1580016, "warehouse_quicksilver"); - columns.put(1580017, "warehouse_galvor"); - columns.put(1580018, "warehouse_wormwood"); - columns.put(1580019, "warehouse_obsidian"); - columns.put(1580020, "warehouse_bloodstone"); - columns.put(1580021, "warehouse_mithril"); - columns.put(7, "warehouse_gold"); - } - public boolean CREATE_TRANSACTION(int warehouseBuildingID, GameObjectType targetType, int targetUUID, TransactionType transactionType,Resource resource, int amount,DateTime date){ Transaction transactions = null; prepareCallable("INSERT INTO `dyn_warehouse_transactions` (`warehouseUID`, `targetType`,`targetUID`, `type`,`resource`,`amount`,`date` ) VALUES (?,?,?,?,?,?,?)"); @@ -386,8 +302,6 @@ public class dbWarehouseHandler extends dbHandlerBase { return (executeUpdate() != 0); } - - public static void addObject(ArrayList list, ResultSet rs) throws SQLException, UnknownHostException { String type = rs.getString("type"); switch (type) { From 7c57dcc73dd34372cdf23e6d3736c3547863c9de Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 09:17:06 -0400 Subject: [PATCH 083/109] Update to bool return handling. --- src/engine/db/handlers/dbAccountHandler.java | 9 --- src/engine/db/handlers/dbBaneHandler.java | 2 +- .../db/handlers/dbBaseClassHandler.java | 1 - src/engine/db/handlers/dbBuildingHandler.java | 65 +++++++------------ .../db/handlers/dbCSSessionHandler.java | 12 ++-- .../db/handlers/dbCharacterRuneHandler.java | 3 +- .../db/handlers/dbCharacterSkillHandler.java | 2 +- src/engine/db/handlers/dbContractHandler.java | 5 +- .../db/handlers/dbEnchantmentHandler.java | 6 +- src/engine/db/handlers/dbGuildHandler.java | 29 ++++----- src/engine/db/handlers/dbItemHandler.java | 4 +- src/engine/db/handlers/dbMineHandler.java | 9 ++- src/engine/db/handlers/dbMobBaseHandler.java | 2 +- .../db/handlers/dbPlayerCharacterHandler.java | 40 ++++++------ .../db/handlers/dbWarehouseHandler.java | 19 ++++-- 15 files changed, 88 insertions(+), 120 deletions(-) diff --git a/src/engine/db/handlers/dbAccountHandler.java b/src/engine/db/handlers/dbAccountHandler.java index 850e4eac..ad790a3b 100644 --- a/src/engine/db/handlers/dbAccountHandler.java +++ b/src/engine/db/handlers/dbAccountHandler.java @@ -89,7 +89,6 @@ public class dbAccountHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); } - } public ArrayList GET_TRASH_LIST() { @@ -107,7 +106,6 @@ public class dbAccountHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); } - return machineList; } @@ -122,7 +120,6 @@ public class dbAccountHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); } - } public ArrayList GET_ALL_CHARS_FOR_MACHINE(String machineID) { @@ -155,7 +152,6 @@ public class dbAccountHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); } - return trashList; } @@ -169,7 +165,6 @@ public class dbAccountHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); } - } public void CREATE_SINGLE(String accountName, String password) { @@ -185,7 +180,6 @@ public class dbAccountHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); } - } public Account GET_ACCOUNT(String uname) { @@ -238,7 +232,6 @@ public class dbAccountHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); } - } public void updateDatabase(final Account acc) { @@ -260,7 +253,6 @@ public class dbAccountHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); } - } public void INVALIDATE_LOGIN_CACHE(long accountUID, String objectType) { @@ -276,7 +268,6 @@ public class dbAccountHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); } - } } diff --git a/src/engine/db/handlers/dbBaneHandler.java b/src/engine/db/handlers/dbBaneHandler.java index 08794bc5..904f0cdd 100644 --- a/src/engine/db/handlers/dbBaneHandler.java +++ b/src/engine/db/handlers/dbBaneHandler.java @@ -104,7 +104,7 @@ public class dbBaneHandler extends dbHandlerBase { Logger.error(e); return false; } - return true; + return true; } } diff --git a/src/engine/db/handlers/dbBaseClassHandler.java b/src/engine/db/handlers/dbBaseClassHandler.java index ce4e1d41..30f476e6 100644 --- a/src/engine/db/handlers/dbBaseClassHandler.java +++ b/src/engine/db/handlers/dbBaseClassHandler.java @@ -87,6 +87,5 @@ public class dbBaseClassHandler extends dbHandlerBase { } return baseClasses; - } } diff --git a/src/engine/db/handlers/dbBuildingHandler.java b/src/engine/db/handlers/dbBuildingHandler.java index c175e11a..3550214d 100644 --- a/src/engine/db/handlers/dbBuildingHandler.java +++ b/src/engine/db/handlers/dbBuildingHandler.java @@ -204,12 +204,12 @@ public class dbBuildingHandler extends dbHandlerBase { preparedStatement.setLong(1, b.getObjectUUID()); preparedStatement.execute(); + return true; } catch (SQLException e) { Logger.error(e); - return false; } - return true; + return false; } public boolean CHANGE_NAME(Building b, String newName) { @@ -224,9 +224,8 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public boolean SET_RESERVE(Building b, int reserveAmount) { @@ -241,9 +240,9 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } //CAS update to rank @@ -259,9 +258,8 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public boolean UPDATE_BUILDING_HEALTH(final long buildingID, int NewHealth) { @@ -276,9 +274,8 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public boolean UPDATE_BUILDING_ALTITUDE(final long buildingID, float newAltitude) { @@ -293,9 +290,8 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public boolean UPDATE_PROTECTIONSTATE(final long buildingUUID, ProtectionState protectionState) { @@ -310,9 +306,8 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public boolean UPDATE_DOOR_LOCK(final int buildingUUID, int doorFlags) { @@ -327,9 +322,8 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public boolean ADD_TO_FRIENDS_LIST(final long buildingID, final long friendID, final long guildID, final int friendType) { @@ -346,9 +340,8 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public boolean REMOVE_FROM_FRIENDS_LIST(final long buildingID, long friendID, long guildID, int friendType) { @@ -365,9 +358,8 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public boolean REMOVE_FROM_CONDEMNED_LIST(final long buildingID, long friendID, long guildID, int friendType) { @@ -384,9 +376,8 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public void CLEAR_FRIENDS_LIST(final long buildingID) { @@ -427,9 +418,8 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public void LOAD_ALL_FRIENDS_FOR_BUILDING(Building building) { @@ -536,9 +526,8 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public boolean ADD_TO_PATROL(final long parentUID, final Vector3fImmutable patrolPoint) { @@ -555,9 +544,8 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public HashMap> LOAD_BUILDING_REGIONS() { @@ -589,7 +577,6 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return null; } Logger.info("read: " + recordsRead + " cached: " + regionList.size()); @@ -702,8 +689,8 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean updateReverseKOS(final Building b, boolean reverse) { @@ -718,9 +705,8 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public boolean updateActiveCondemn(final Condemned condemn, boolean active) { @@ -739,9 +725,8 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public boolean updateBuildingOwner(final Building building, int ownerUUID) { @@ -757,9 +742,8 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public boolean updateBuildingUpgradeTime(LocalDateTime upgradeDateTime, Building toUpgrade, int costToUpgrade) { @@ -781,8 +765,8 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean updateMaintDate(Building building) { @@ -802,8 +786,8 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean addTaxes(Building building, TaxType taxType, int amount, boolean enforceKOS) { @@ -821,9 +805,8 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public boolean removeTaxes(Building building) { @@ -842,8 +825,8 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean acceptTaxes(Building building) { @@ -859,8 +842,8 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } } diff --git a/src/engine/db/handlers/dbCSSessionHandler.java b/src/engine/db/handlers/dbCSSessionHandler.java index f14def21..b56341cc 100644 --- a/src/engine/db/handlers/dbCSSessionHandler.java +++ b/src/engine/db/handlers/dbCSSessionHandler.java @@ -44,9 +44,8 @@ public class dbCSSessionHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public boolean DELETE_UNUSED_CSSESSION(String secKey) { @@ -59,9 +58,8 @@ public class dbCSSessionHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public boolean DELETE_CSSESSION(String secKey) { @@ -74,9 +72,8 @@ public class dbCSSessionHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public boolean UPDATE_CSSESSION(String secKey, int charID) { @@ -91,9 +88,8 @@ public class dbCSSessionHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public CSSession GET_CSSESSION(String secKey) { diff --git a/src/engine/db/handlers/dbCharacterRuneHandler.java b/src/engine/db/handlers/dbCharacterRuneHandler.java index d905f0e2..e708dcea 100644 --- a/src/engine/db/handlers/dbCharacterRuneHandler.java +++ b/src/engine/db/handlers/dbCharacterRuneHandler.java @@ -83,9 +83,8 @@ public class dbCharacterRuneHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public ArrayList GET_RUNES_FOR_CHARACTER(final int characterId) { diff --git a/src/engine/db/handlers/dbCharacterSkillHandler.java b/src/engine/db/handlers/dbCharacterSkillHandler.java index d2e4909e..c966b77e 100644 --- a/src/engine/db/handlers/dbCharacterSkillHandler.java +++ b/src/engine/db/handlers/dbCharacterSkillHandler.java @@ -69,8 +69,8 @@ public class dbCharacterSkillHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public CharacterSkill GET_SKILL(final int objectUUID) { diff --git a/src/engine/db/handlers/dbContractHandler.java b/src/engine/db/handlers/dbContractHandler.java index 893dbcf4..479695f5 100644 --- a/src/engine/db/handlers/dbContractHandler.java +++ b/src/engine/db/handlers/dbContractHandler.java @@ -139,8 +139,8 @@ public class dbContractHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean updateDatabase(final Contract con) { @@ -162,8 +162,7 @@ public class dbContractHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } } diff --git a/src/engine/db/handlers/dbEnchantmentHandler.java b/src/engine/db/handlers/dbEnchantmentHandler.java index 61ab7a3d..1ba8c316 100644 --- a/src/engine/db/handlers/dbEnchantmentHandler.java +++ b/src/engine/db/handlers/dbEnchantmentHandler.java @@ -55,10 +55,10 @@ public class dbEnchantmentHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } + public boolean CLEAR_ENCHANTMENTS(long itemID) { try (Connection connection = DbManager.getConnection(); @@ -69,7 +69,7 @@ public class dbEnchantmentHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } } diff --git a/src/engine/db/handlers/dbGuildHandler.java b/src/engine/db/handlers/dbGuildHandler.java index 58a87441..b5a6dc70 100644 --- a/src/engine/db/handlers/dbGuildHandler.java +++ b/src/engine/db/handlers/dbGuildHandler.java @@ -68,9 +68,8 @@ public class dbGuildHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public boolean REMOVE_FROM_BANISH_LIST(int target, long characterID) { @@ -85,8 +84,8 @@ public class dbGuildHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean ADD_TO_GUILDHISTORY(int target, PlayerCharacter playerCharacter, DateTime historyDate, GuildHistoryType historyType) { @@ -108,9 +107,8 @@ public class dbGuildHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } //TODO Need to get this working. @@ -346,8 +344,8 @@ public class dbGuildHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean SET_GUILD_LEADER(int objectUUID,int guildID) { @@ -362,9 +360,8 @@ public class dbGuildHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public boolean IS_NAME_UNIQUE(final String name) { @@ -382,8 +379,8 @@ public class dbGuildHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return valid; } @@ -436,8 +433,8 @@ public class dbGuildHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean UPDATE_PARENT(int guildUID, int parentUID) { @@ -452,9 +449,8 @@ public class dbGuildHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public int DELETE_GUILD(final Guild guild) { @@ -485,9 +481,8 @@ public class dbGuildHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public int UPDATE_GUILD_STATUS_OFFLINE(int target, boolean isInnerCouncil, boolean isRecruiter, boolean isTaxCollector, int guildId) { @@ -563,8 +558,8 @@ public class dbGuildHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean ADD_TO_ALLIANCE_LIST(final long sourceGuildID, final long targetGuildID, boolean isRecommended, boolean isAlly, String recommender) { @@ -582,8 +577,8 @@ public class dbGuildHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean REMOVE_FROM_ALLIANCE_LIST(final long sourceGuildID, long targetGuildID) { @@ -598,8 +593,8 @@ public class dbGuildHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean UPDATE_RECOMMENDED(final long sourceGuildID, long targetGuildID) { diff --git a/src/engine/db/handlers/dbItemHandler.java b/src/engine/db/handlers/dbItemHandler.java index bd61223b..49f7f828 100644 --- a/src/engine/db/handlers/dbItemHandler.java +++ b/src/engine/db/handlers/dbItemHandler.java @@ -137,7 +137,6 @@ public class dbItemHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } return worked; } @@ -277,9 +276,8 @@ public class dbItemHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public boolean ORPHAN_INVENTORY(final HashSet inventory) { diff --git a/src/engine/db/handlers/dbMineHandler.java b/src/engine/db/handlers/dbMineHandler.java index c8e35d57..2c527de9 100644 --- a/src/engine/db/handlers/dbMineHandler.java +++ b/src/engine/db/handlers/dbMineHandler.java @@ -80,8 +80,8 @@ public class dbMineHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean CHANGE_RESOURCE(Mine mine, Resource resource) { @@ -96,8 +96,8 @@ public class dbMineHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean CHANGE_TYPE(Mine mine, MineProduction productionType) { @@ -112,9 +112,8 @@ public class dbMineHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public boolean SET_FLAGS(Mine mine, int newFlags) { @@ -129,8 +128,8 @@ public class dbMineHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } } diff --git a/src/engine/db/handlers/dbMobBaseHandler.java b/src/engine/db/handlers/dbMobBaseHandler.java index 531c1415..2c278492 100644 --- a/src/engine/db/handlers/dbMobBaseHandler.java +++ b/src/engine/db/handlers/dbMobBaseHandler.java @@ -108,8 +108,8 @@ public class dbMobBaseHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public HashMap LOAD_STATIC_POWERS(int mobBaseUUID) { diff --git a/src/engine/db/handlers/dbPlayerCharacterHandler.java b/src/engine/db/handlers/dbPlayerCharacterHandler.java index 94c17d52..f74e3d49 100644 --- a/src/engine/db/handlers/dbPlayerCharacterHandler.java +++ b/src/engine/db/handlers/dbPlayerCharacterHandler.java @@ -95,9 +95,8 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public ArrayList GET_CHARACTERS_FOR_ACCOUNT(final int id) { @@ -231,9 +230,8 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } - + return false; } public boolean SET_DELETED(final PlayerCharacter pc) { @@ -248,8 +246,8 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean SET_ACTIVE(final PlayerCharacter pc, boolean status) { @@ -264,8 +262,8 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean SET_BIND_BUILDING(final PlayerCharacter pc, int bindBuildingID) { @@ -280,8 +278,8 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean SET_ANNIVERSERY(final PlayerCharacter pc, boolean flag) { @@ -296,8 +294,8 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } @@ -313,8 +311,8 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean UPDATE_GUILD(final PlayerCharacter pc, int guildUUID) { @@ -329,8 +327,8 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean UPDATE_CHARACTER_STATS(final PlayerCharacter pc) { @@ -349,8 +347,8 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public String SET_PROPERTY(final PlayerCharacter playerCharacter, String name, Object new_value) { @@ -386,8 +384,8 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean SET_INNERCOUNCIL(PlayerCharacter player, boolean isInnerCouncil) { @@ -402,8 +400,8 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean SET_FULL_MEMBER(PlayerCharacter player, boolean isFullMember) { @@ -418,8 +416,8 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean SET_TAX_COLLECTOR(PlayerCharacter player, boolean isTaxCollector) { @@ -434,8 +432,8 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean SET_RECRUITER(PlayerCharacter player, boolean isRecruiter) { @@ -450,8 +448,8 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean SET_GUILD_TITLE(PlayerCharacter player, int title) { @@ -466,8 +464,8 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean ADD_FRIEND(int source, long friend) { @@ -482,8 +480,8 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean REMOVE_FRIEND(int source, int friend) { @@ -498,8 +496,8 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public void LOAD_PLAYER_FRIENDS() { @@ -534,8 +532,8 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public boolean REMOVE_HERALDY(int source, int characterUID) { @@ -550,8 +548,8 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error(e); - return false; } + return false; } public void LOAD_HERALDY() { diff --git a/src/engine/db/handlers/dbWarehouseHandler.java b/src/engine/db/handlers/dbWarehouseHandler.java index c59142dd..9ecb6348 100644 --- a/src/engine/db/handlers/dbWarehouseHandler.java +++ b/src/engine/db/handlers/dbWarehouseHandler.java @@ -20,6 +20,8 @@ import org.joda.time.DateTime; import org.pmw.tinylog.Logger; import java.net.UnknownHostException; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; @@ -100,10 +102,19 @@ public class dbWarehouseHandler extends dbHandlerBase { } public boolean updateLocks(final Warehouse wh, long locks) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_locks`=? WHERE `UID` = ?"); - setLong(1, locks); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_locks`=? WHERE `UID` = ?")) { + + preparedStatement.setLong(1, locks); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean updateGold(final Warehouse wh, int amount ) { From a92ac8671be26459afa6e461ab6f008206269c0c Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 09:26:11 -0400 Subject: [PATCH 084/109] Refactor to remove abstraction --- .../db/handlers/dbWarehouseHandler.java | 142 ++++++++---------- 1 file changed, 64 insertions(+), 78 deletions(-) diff --git a/src/engine/db/handlers/dbWarehouseHandler.java b/src/engine/db/handlers/dbWarehouseHandler.java index 9ecb6348..f5817003 100644 --- a/src/engine/db/handlers/dbWarehouseHandler.java +++ b/src/engine/db/handlers/dbWarehouseHandler.java @@ -19,7 +19,6 @@ import engine.server.MBServerStatics; import org.joda.time.DateTime; import org.pmw.tinylog.Logger; -import java.net.UnknownHostException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -37,68 +36,71 @@ public class dbWarehouseHandler extends dbHandlerBase { } - public ArrayList CREATE_WAREHOUSE( int parentZoneID, int OwnerUUID, String name, int meshUUID, - Vector3fImmutable location, float meshScale, int currentHP, - ProtectionState protectionState, int currentGold, int rank, - DateTime upgradeDate, int blueprintUUID, float w, float rotY) { - - prepareCallable("CALL `WAREHOUSE_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,? ,? ,?, ?);"); - - setInt(1, parentZoneID); - setInt(2, OwnerUUID); - setString(3, name); - setInt(4, meshUUID); - setFloat(5, location.x); - setFloat(6, location.y); - setFloat(7, location.z); - setFloat(8, meshScale); - setInt(9, currentHP); - setString(10, protectionState.name()); - setInt(11, currentGold); - setInt(12, rank); - - if (upgradeDate != null) { - setTimeStamp(13, upgradeDate.getMillis()); - } else { - setNULL(13, java.sql.Types.DATE); + public static void addObject(ArrayList list, ResultSet rs) throws SQLException { + String type = rs.getString("type"); + switch (type) { + case "building": + Building building = new Building(rs); + DbManager.addToCache(building); + list.add(building); + break; + case "warehouse": + Warehouse warehouse = new Warehouse(rs); + DbManager.addToCache(warehouse); + list.add(warehouse); + break; } + } - setInt(14, blueprintUUID); - setFloat(15, w); - setFloat(16, rotY); + public ArrayList CREATE_WAREHOUSE(int parentZoneID, int OwnerUUID, String name, int meshUUID, + Vector3fImmutable location, float meshScale, int currentHP, + ProtectionState protectionState, int currentGold, int rank, + DateTime upgradeDate, int blueprintUUID, float w, float rotY) { - ArrayList list = new ArrayList<>(); - //System.out.println(this.cs.get().toString()); - try { - boolean work = execute(); - if (work) { - ResultSet rs = this.callableStatement.get().getResultSet(); - while (rs.next()) { - addObject(list, rs); - } - rs.close(); - } else { - Logger.info("Warehouse Creation Failed: " + this.callableStatement.get().toString()); - return list; //city creation failure - } - while (this.callableStatement.get().getMoreResults()) { - ResultSet rs = this.callableStatement.get().getResultSet(); - while (rs.next()) { - addObject(list, rs); - } - rs.close(); + ArrayList warehouseList = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL `WAREHOUSE_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,? ,? ,?, ?);")) { + + preparedStatement.setInt(1, parentZoneID); + preparedStatement.setInt(2, OwnerUUID); + preparedStatement.setString(3, name); + preparedStatement.setInt(4, meshUUID); + preparedStatement.setFloat(5, location.x); + preparedStatement.setFloat(6, location.y); + preparedStatement.setFloat(7, location.z); + preparedStatement.setFloat(8, meshScale); + preparedStatement.setInt(9, currentHP); + preparedStatement.setString(10, protectionState.name()); + preparedStatement.setInt(11, currentGold); + preparedStatement.setInt(12, rank); + + if (upgradeDate != null) + preparedStatement.setTimestamp(13, new java.sql.Timestamp(upgradeDate.getMillis())); + else + preparedStatement.setNull(13, java.sql.Types.DATE); + + preparedStatement.setInt(14, blueprintUUID); + preparedStatement.setFloat(15, w); + preparedStatement.setFloat(16, rotY); + + preparedStatement.execute(); + ResultSet rs = preparedStatement.getResultSet(); + + while (rs.next()) + addObject(warehouseList, rs); + + while (preparedStatement.getMoreResults()) { + rs = preparedStatement.getResultSet(); + + while (rs.next()) + addObject(warehouseList, rs); } } catch (SQLException e) { - Logger.info("Warehouse Creation Failed, SQLException: " + this.callableStatement.get().toString() + e.toString()); - return list; //city creation failure - } catch (UnknownHostException e) { - Logger.info("Warehouse Creation Failed, UnknownHostException: " + this.callableStatement.get().toString()); - return list; //city creation failure - } finally { - closeCallable(); + Logger.error(e); } - return list; + return warehouseList; } public boolean updateLocks(final Warehouse wh, long locks) { @@ -117,7 +119,7 @@ public class dbWarehouseHandler extends dbHandlerBase { return false; } - public boolean updateGold(final Warehouse wh, int amount ) { + public boolean updateGold(final Warehouse wh, int amount) { prepareCallable("UPDATE `obj_warehouse` SET `warehouse_gold`=? WHERE `UID` = ?"); setInt(1, amount); setInt(2, wh.getUID()); @@ -268,7 +270,7 @@ public class dbWarehouseHandler extends dbHandlerBase { return (executeUpdate() != 0); } - public boolean updateWormwood(final Warehouse wh, int amount ) { + public boolean updateWormwood(final Warehouse wh, int amount) { prepareCallable("UPDATE `obj_warehouse` SET `warehouse_wormwood`=? WHERE `UID` = ?"); setInt(1, amount); setInt(2, wh.getUID()); @@ -300,7 +302,7 @@ public class dbWarehouseHandler extends dbHandlerBase { return (executeUpdate() != 0); } - public boolean CREATE_TRANSACTION(int warehouseBuildingID, GameObjectType targetType, int targetUUID, TransactionType transactionType,Resource resource, int amount,DateTime date){ + public boolean CREATE_TRANSACTION(int warehouseBuildingID, GameObjectType targetType, int targetUUID, TransactionType transactionType, Resource resource, int amount, DateTime date) { Transaction transactions = null; prepareCallable("INSERT INTO `dyn_warehouse_transactions` (`warehouseUID`, `targetType`,`targetUID`, `type`,`resource`,`amount`,`date` ) VALUES (?,?,?,?,?,?,?)"); setLong(1, warehouseBuildingID); @@ -308,27 +310,11 @@ public class dbWarehouseHandler extends dbHandlerBase { setLong(3, targetUUID); setString(4, transactionType.name()); setString(5, resource.name()); - setInt(6,amount); - setTimeStamp(7,date.getMillis()); + setInt(6, amount); + setTimeStamp(7, date.getMillis()); return (executeUpdate() != 0); } - public static void addObject(ArrayList list, ResultSet rs) throws SQLException, UnknownHostException { - String type = rs.getString("type"); - switch (type) { - case "building": - Building building = new Building(rs); - DbManager.addToCache(building); - list.add(building); - break; - case "warehouse": - Warehouse warehouse = new Warehouse(rs); - DbManager.addToCache(warehouse); - list.add(warehouse); - break; - } - } - public ArrayList GET_TRANSACTIONS_FOR_WAREHOUSE(final int warehouseUUID) { ArrayList transactionsList = new ArrayList<>(); prepareCallable("SELECT * FROM dyn_warehouse_transactions WHERE `warehouseUID` = ?;"); @@ -343,7 +329,7 @@ public class dbWarehouseHandler extends dbHandlerBase { } } catch (SQLException e) { - Logger.error( e.getErrorCode() + ' ' + e.getMessage(), e); + Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); } finally { closeCallable(); } From 3dd27976fea75630b893709ae8d1fac3eabeb925 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 09:39:27 -0400 Subject: [PATCH 085/109] Refactor to remove abstraction --- .../db/handlers/dbWarehouseHandler.java | 438 +++++++++++++----- 1 file changed, 317 insertions(+), 121 deletions(-) diff --git a/src/engine/db/handlers/dbWarehouseHandler.java b/src/engine/db/handlers/dbWarehouseHandler.java index f5817003..216aea87 100644 --- a/src/engine/db/handlers/dbWarehouseHandler.java +++ b/src/engine/db/handlers/dbWarehouseHandler.java @@ -120,241 +120,437 @@ public class dbWarehouseHandler extends dbHandlerBase { } public boolean updateGold(final Warehouse wh, int amount) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_gold`=? WHERE `UID` = ?"); - setInt(1, amount); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_gold`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean updateStone(final Warehouse wh, int amount) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_stone`=? WHERE `UID` = ?"); - setInt(1, amount); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_stone`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean updateTruesteel(final Warehouse wh, int amount) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_truesteel`=? WHERE `UID` = ?"); - setInt(1, amount); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_truesteel`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean updateIron(final Warehouse wh, int amount) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_iron`=? WHERE `UID` = ?"); - setInt(1, amount); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_iron`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean updateAdamant(final Warehouse wh, int amount) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_adamant`=? WHERE `UID` = ?"); - setInt(1, amount); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_adamant`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean updateLumber(final Warehouse wh, int amount) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_lumber`=? WHERE `UID` = ?"); - setInt(1, amount); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_lumber`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean updateOak(final Warehouse wh, int amount) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_oak`=? WHERE `UID` = ?"); - setInt(1, amount); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_oak`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean updateBronzewood(final Warehouse wh, int amount) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_bronzewood`=? WHERE `UID` = ?"); - setInt(1, amount); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_bronzewood`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean updateMandrake(final Warehouse wh, int amount) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_mandrake`=? WHERE `UID` = ?"); - setInt(1, amount); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_mandrake`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean updateCoal(final Warehouse wh, int amount) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_coal`=? WHERE `UID` = ?"); - setInt(1, amount); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_coal`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean updateAgate(final Warehouse wh, int amount) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_agate`=? WHERE `UID` = ?"); - setInt(1, amount); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_agate`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean updateDiamond(final Warehouse wh, int amount) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_diamond`=? WHERE `UID` = ?"); - setInt(1, amount); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_diamond`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean updateOnyx(final Warehouse wh, int amount) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_onyx`=? WHERE `UID` = ?"); - setInt(1, amount); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_onyx`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean updateAzoth(final Warehouse wh, int amount) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_azoth`=? WHERE `UID` = ?"); - setInt(1, amount); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_azoth`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean updateOrichalk(final Warehouse wh, int amount) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_orichalk`=? WHERE `UID` = ?"); - setInt(1, amount); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_orichalk`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean updateAntimony(final Warehouse wh, int amount) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_antimony`=? WHERE `UID` = ?"); - setInt(1, amount); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_antimony`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean updateSulfur(final Warehouse wh, int amount) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_sulfur`=? WHERE `UID` = ?"); - setInt(1, amount); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_sulfur`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean updateQuicksilver(final Warehouse wh, int amount) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_quicksilver`=? WHERE `UID` = ?"); - setInt(1, amount); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_quicksilver`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean updateGalvor(final Warehouse wh, int amount) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_galvor`=? WHERE `UID` = ?"); - setInt(1, amount); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_galvor`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean updateWormwood(final Warehouse wh, int amount) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_wormwood`=? WHERE `UID` = ?"); - setInt(1, amount); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_wormwood`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean updateObsidian(final Warehouse wh, int amount) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_obsidian`=? WHERE `UID` = ?"); - setInt(1, amount); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_obsidian`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean updateBloodstone(final Warehouse wh, int amount) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_bloodstone`=? WHERE `UID` = ?"); - setInt(1, amount); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_bloodstone`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean updateMithril(final Warehouse wh, int amount) { - prepareCallable("UPDATE `obj_warehouse` SET `warehouse_mithril`=? WHERE `UID` = ?"); - setInt(1, amount); - setInt(2, wh.getUID()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_mithril`=? WHERE `UID` = ?")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setInt(2, wh.getUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public boolean CREATE_TRANSACTION(int warehouseBuildingID, GameObjectType targetType, int targetUUID, TransactionType transactionType, Resource resource, int amount, DateTime date) { - Transaction transactions = null; - prepareCallable("INSERT INTO `dyn_warehouse_transactions` (`warehouseUID`, `targetType`,`targetUID`, `type`,`resource`,`amount`,`date` ) VALUES (?,?,?,?,?,?,?)"); - setLong(1, warehouseBuildingID); - setString(2, targetType.name()); - setLong(3, targetUUID); - setString(4, transactionType.name()); - setString(5, resource.name()); - setInt(6, amount); - setTimeStamp(7, date.getMillis()); - return (executeUpdate() != 0); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_warehouse_transactions` (`warehouseUID`, `targetType`,`targetUID`, `type`,`resource`,`amount`,`date` ) VALUES (?,?,?,?,?,?,?)")) { + + preparedStatement.setInt(1, amount); + preparedStatement.setLong(1, warehouseBuildingID); + preparedStatement.setString(2, targetType.name()); + preparedStatement.setLong(3, targetUUID); + preparedStatement.setString(4, transactionType.name()); + preparedStatement.setString(5, resource.name()); + preparedStatement.setInt(6, amount); + preparedStatement.setTimestamp(7, new java.sql.Timestamp(date.getMillis())); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; } public ArrayList GET_TRANSACTIONS_FOR_WAREHOUSE(final int warehouseUUID) { + ArrayList transactionsList = new ArrayList<>(); - prepareCallable("SELECT * FROM dyn_warehouse_transactions WHERE `warehouseUID` = ?;"); - setInt(1, warehouseUUID); - try { - ResultSet rs = executeQuery(); - //shrines cached in rs for easy cache on creation. + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM dyn_warehouse_transactions WHERE `warehouseUID` = ?;")) { + + preparedStatement.setInt(1, warehouseUUID); + + ResultSet rs = preparedStatement.executeQuery(); + while (rs.next()) { Transaction transactions = new Transaction(rs); transactionsList.add(transactions); } } catch (SQLException e) { - Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); + Logger.error(e); } + return transactionsList; } public void LOAD_ALL_WAREHOUSES() { - Warehouse thisWarehouse; + Warehouse warehouse; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_warehouse`.*, `object`.`parent`, `object`.`type` FROM `object` LEFT JOIN `obj_warehouse` ON `object`.`UID` = `obj_warehouse`.`UID` WHERE `object`.`type` = 'warehouse';")) { - prepareCallable("SELECT `obj_warehouse`.*, `object`.`parent`, `object`.`type` FROM `object` LEFT JOIN `obj_warehouse` ON `object`.`UID` = `obj_warehouse`.`UID` WHERE `object`.`type` = 'warehouse';"); - try { - ResultSet rs = executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); + while (rs.next()) { - thisWarehouse = new Warehouse(rs); - thisWarehouse.runAfterLoad(); - thisWarehouse.loadAllTransactions(); + warehouse = new Warehouse(rs); + warehouse.runAfterLoad(); + warehouse.loadAllTransactions(); } } catch (SQLException e) { - Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); + Logger.error(e); } - } } From f7da137e0f63e3141c1d881c3ec5afbdd4c490f9 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 09:57:17 -0400 Subject: [PATCH 086/109] Refactor to remove abstraction --- src/engine/db/handlers/dbBuildingHandler.java | 2 +- src/engine/db/handlers/dbZoneHandler.java | 86 +++++++++++++------ 2 files changed, 59 insertions(+), 29 deletions(-) diff --git a/src/engine/db/handlers/dbBuildingHandler.java b/src/engine/db/handlers/dbBuildingHandler.java index 3550214d..8894e118 100644 --- a/src/engine/db/handlers/dbBuildingHandler.java +++ b/src/engine/db/handlers/dbBuildingHandler.java @@ -146,8 +146,8 @@ public class dbBuildingHandler extends dbHandlerBase { } catch (SQLException e) { Logger.error("Building", e); - return null; } + return building; } diff --git a/src/engine/db/handlers/dbZoneHandler.java b/src/engine/db/handlers/dbZoneHandler.java index 6a6990ae..9950f31f 100644 --- a/src/engine/db/handlers/dbZoneHandler.java +++ b/src/engine/db/handlers/dbZoneHandler.java @@ -12,8 +12,12 @@ package engine.db.handlers; import engine.Enum; import engine.gameManager.DbManager; import engine.objects.Zone; +import org.pmw.tinylog.Logger; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; +import java.sql.SQLException; import java.util.ArrayList; public class dbZoneHandler extends dbHandlerBase { @@ -46,48 +50,74 @@ public class dbZoneHandler extends dbHandlerBase { public Zone GET_BY_UID(long ID) { - Zone zone = (Zone) DbManager.getFromCache(Enum.GameObjectType.Zone, (int)ID); + Zone zone = (Zone) DbManager.getFromCache(Enum.GameObjectType.Zone, (int) ID); + if (zone != null) return zone; - prepareCallable("SELECT `obj_zone`.*, `object`.`parent` FROM `object` INNER JOIN `obj_zone` ON `obj_zone`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?;"); - setLong(1, ID); - return (Zone) getObjectSingle((int) ID); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_zone`.*, `object`.`parent` FROM `object` INNER JOIN `obj_zone` ON `obj_zone`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?;")) { + + preparedStatement.setLong(1, ID); + + ResultSet rs = preparedStatement.executeQuery(); + zone = (Zone) getObjectFromRs(rs); + + } catch (SQLException e) { + Logger.error(e); + } + + return zone; } public ArrayList GET_MAP_NODES(final int objectUUID) { - prepareCallable("SELECT `obj_zone`.*, `object`.`parent` FROM `object` INNER JOIN `obj_zone` ON `obj_zone`.`UID` = `object`.`UID` WHERE `object`.`parent` = ?;"); - setLong(1, (long) objectUUID); - return getObjectList(); + + ArrayList zoneList = new ArrayList<>(); + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_zone`.*, `object`.`parent` FROM `object` INNER JOIN `obj_zone` ON `obj_zone`.`UID` = `object`.`UID` WHERE `object`.`parent` = ?;")) { + + preparedStatement.setLong(1, (long) objectUUID); + + ResultSet rs = preparedStatement.executeQuery(); + zoneList = getObjectsFromRs(rs, 2000); + + } catch (SQLException e) { + Logger.error(e); + } + + return zoneList; } public ResultSet GET_ZONE_EXTENTS(final int loadNum) { - prepareCallable("SELECT * FROM `static_zone_size` WHERE `loadNum`=?;"); - setInt(1, loadNum); - return executeQuery(); - } - public String SET_PROPERTY(final Zone z, String name, Object new_value) { - prepareCallable("CALL zone_SETPROP(?,?,?)"); - setLong(1, (long) z.getObjectUUID()); - setString(2, name); - setString(3, String.valueOf(new_value)); - return getResult(); - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_zone_size` WHERE `loadNum`=?;")) { + + preparedStatement.setInt(1, loadNum); + + return preparedStatement.executeQuery(); - public String SET_PROPERTY(final Zone z, String name, Object new_value, Object old_value) { - prepareCallable("CALL zone_GETSETPROP(?,?,?,?)"); - setLong(1, (long) z.getObjectUUID()); - setString(2, name); - setString(3, String.valueOf(new_value)); - setString(4, String.valueOf(old_value)); - return getResult(); + } catch (SQLException e) { + Logger.error(e); + } + return null; } public boolean DELETE_ZONE(final Zone zone) { - prepareCallable("DELETE FROM `object` WHERE `UID` = ? AND `type` = 'zone'"); - setInt(1, zone.getObjectUUID()); - return (executeUpdate() != 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `object` WHERE `UID` = ? AND `type` = 'zone'")) { + + preparedStatement.setInt(1, zone.getObjectUUID()); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + + return false; } } From 1e3aab1623441eda3c930875ac473df63575523d Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 10:03:05 -0400 Subject: [PATCH 087/109] Query string updated. --- src/engine/db/handlers/dbContractHandler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/engine/db/handlers/dbContractHandler.java b/src/engine/db/handlers/dbContractHandler.java index 479695f5..7f543cd3 100644 --- a/src/engine/db/handlers/dbContractHandler.java +++ b/src/engine/db/handlers/dbContractHandler.java @@ -39,7 +39,7 @@ public class dbContractHandler extends dbHandlerBase { return null; try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_building`.*, `object`.`parent` FROM `object` INNER JOIN `obj_building` ON `obj_building`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?;")) { + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_contract` WHERE `ID` = ?")) { preparedStatement.setInt(1, objectUUID); From 4d4d83d15a24ee99f05c1e002c2553df63c8c384 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 10:07:39 -0400 Subject: [PATCH 088/109] Unused method removed. --- src/engine/objects/Zone.java | 54 ------------------------------------ 1 file changed, 54 deletions(-) diff --git a/src/engine/objects/Zone.java b/src/engine/objects/Zone.java index 92f64c94..0655d040 100644 --- a/src/engine/objects/Zone.java +++ b/src/engine/objects/Zone.java @@ -408,60 +408,6 @@ public class Zone extends AbstractGameObject { // TODO Auto-generated method stub } - public Zone findRuinedCityZone(float centerX, float centerY, float centerZ){ - Bounds cityBounds; - cityBounds = Bounds.borrow(); - Zone RuinedZone = null; - cityBounds.setBounds(new Vector2f(centerX, centerZ), new Vector2f(Enum.CityBoundsType.ZONE.extents, Enum.CityBoundsType.ZONE.extents), 0.0f); - Zone currentZone = ZoneManager.findSmallestZone(new Vector3fImmutable(centerX, centerY, centerZ)); - if (currentZone != null) - if (this.getObjectUUID() == currentZone.getObjectUUID()){ - - if (currentZone.getPlayerCityUUID() != 0){ - //null player city? skip.. - if (City.GetCityFromCache(currentZone.getPlayerCityUUID()) == null) - RuinedZone = null; - else //no tol? skip... - if (City.GetCityFromCache(currentZone.getPlayerCityUUID()).getTOL() == null) - RuinedZone = null; - else - if (City.GetCityFromCache(currentZone.getPlayerCityUUID()).getTOL().getRank() == -1) - RuinedZone = currentZone; - //Dead tree? skip. - cityBounds.release(); - return RuinedZone; - } - } - - for (Zone zone : this.getNodes()) { - - if (zone == this) - continue; - - if (zone.isContinent() && zone.getPlayerCityUUID() == 0) - continue; - - if (zone.getPlayerCityUUID() != 0){ - //null player city? skip.. - if (City.GetCityFromCache(zone.getPlayerCityUUID()) == null) - continue; - //no tol? skip... - if (City.GetCityFromCache(zone.getPlayerCityUUID()).getTOL() == null) - continue; - - //Dead tree? skip. - if (Bounds.collide(zone.bounds, cityBounds, 0.0f)){ - if (City.GetCityFromCache(zone.getPlayerCityUUID()).getTOL().getRank() == -1){ - RuinedZone = zone; - break; - } - } - } - } - cityBounds.release(); - return RuinedZone; - } - public boolean isContinent() { if (this.equals(ZoneManager.getSeaFloor())) From a2d62ec221bb2aa722ea8de15dec4a820af11570 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 10:08:07 -0400 Subject: [PATCH 089/109] Unused method removed. --- src/engine/objects/Zone.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/engine/objects/Zone.java b/src/engine/objects/Zone.java index 0655d040..5f04cc74 100644 --- a/src/engine/objects/Zone.java +++ b/src/engine/objects/Zone.java @@ -340,10 +340,6 @@ public class Zone extends AbstractGameObject { this.nodes.add(child); } - public void removeNode(Zone child) { - this.nodes.remove(child); - } - /* * Serializing */ From 6dd731578650ff81c5de70b82ddb5f686263d0ac Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 10:27:03 -0400 Subject: [PATCH 090/109] Garbage cleanup in SetZone(). Package reformat. --- src/engine/db/handlers/dbAccountHandler.java | 338 +++---- .../db/handlers/dbBaseClassHandler.java | 86 +- .../handlers/dbBuildingLocationHandler.java | 36 +- .../db/handlers/dbCharacterPowerHandler.java | 204 ++-- .../db/handlers/dbCharacterRuneHandler.java | 132 +-- .../db/handlers/dbCharacterSkillHandler.java | 4 +- .../db/handlers/dbEffectsBaseHandler.java | 2 +- .../dbEffectsResourceCostHandler.java | 32 +- .../db/handlers/dbEnchantmentHandler.java | 70 +- src/engine/db/handlers/dbGuildHandler.java | 935 +++++++++--------- src/engine/db/handlers/dbHandlerBase.java | 835 ++++++++-------- src/engine/db/handlers/dbItemBaseHandler.java | 2 +- src/engine/db/handlers/dbItemHandler.java | 724 +++++++------- src/engine/db/handlers/dbKitHandler.java | 30 +- src/engine/db/handlers/dbMenuHandler.java | 30 +- src/engine/db/handlers/dbMineHandler.java | 150 +-- src/engine/db/handlers/dbMobBaseHandler.java | 240 ++--- src/engine/db/handlers/dbMobHandler.java | 316 +++--- .../db/handlers/dbPlayerCharacterHandler.java | 768 +++++++------- .../db/handlers/dbPromotionClassHandler.java | 2 +- .../handlers/dbRuneBaseAttributeHandler.java | 30 +- .../db/handlers/dbRuneBaseEffectHandler.java | 91 +- src/engine/db/handlers/dbRuneBaseHandler.java | 224 ++--- src/engine/db/handlers/dbShrineHandler.java | 44 +- .../db/handlers/dbSkillBaseHandler.java | 215 ++-- .../db/handlers/dbVendorDialogHandler.java | 36 +- src/engine/db/handlers/dbZoneHandler.java | 19 +- src/engine/gameManager/ZoneManager.java | 26 +- src/engine/objects/Zone.java | 265 +++-- 29 files changed, 2925 insertions(+), 2961 deletions(-) diff --git a/src/engine/db/handlers/dbAccountHandler.java b/src/engine/db/handlers/dbAccountHandler.java index ad790a3b..f34ebe60 100644 --- a/src/engine/db/handlers/dbAccountHandler.java +++ b/src/engine/db/handlers/dbAccountHandler.java @@ -25,249 +25,249 @@ import java.util.ArrayList; public class dbAccountHandler extends dbHandlerBase { - public dbAccountHandler() { - this.localClass = Account.class; - this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); - } + public dbAccountHandler() { + this.localClass = Account.class; + this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); + } - public Account GET_ACCOUNT(int accountID) { + public Account GET_ACCOUNT(int accountID) { - Account account; + Account account; - if (accountID == 0) - return null; + if (accountID == 0) + return null; - account = (Account) DbManager.getFromCache(GameObjectType.Account, accountID); + account = (Account) DbManager.getFromCache(GameObjectType.Account, accountID); - if (account != null) - return account; + if (account != null) + return account; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `obj_account` WHERE `UID`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `obj_account` WHERE `UID`=?")) { - preparedStatement.setLong(1, accountID); + preparedStatement.setLong(1, accountID); - ResultSet rs = preparedStatement.executeQuery(); - account = (Account) getObjectFromRs(rs); + ResultSet rs = preparedStatement.executeQuery(); + account = (Account) getObjectFromRs(rs); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - if (account != null) - account.runAfterLoad(); + if (account != null) + account.runAfterLoad(); - return account; - } + return account; + } - public void WRITE_ADMIN_LOG(String adminName, String logEntry) { + public void WRITE_ADMIN_LOG(String adminName, String logEntry) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO dyn_admin_log(`dateTime`, `charName`, `eventString`)" - + " VALUES (?, ?, ?)")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO dyn_admin_log(`dateTime`, `charName`, `eventString`)" + + " VALUES (?, ?, ?)")) { - preparedStatement.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis())); - preparedStatement.setString(2, adminName); - preparedStatement.setString(3, logEntry); + preparedStatement.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis())); + preparedStatement.setString(2, adminName); + preparedStatement.setString(3, logEntry); - preparedStatement.execute(); + preparedStatement.execute(); - } catch (SQLException e) { - Logger.error(e); - } - } + } catch (SQLException e) { + Logger.error(e); + } + } - public void SET_TRASH(String machineID) { + public void SET_TRASH(String machineID) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO dyn_trash(`machineID`, `count`)" - + " VALUES (?, 1) ON DUPLICATE KEY UPDATE `count` = `count` + 1;")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO dyn_trash(`machineID`, `count`)" + + " VALUES (?, 1) ON DUPLICATE KEY UPDATE `count` = `count` + 1;")) { - preparedStatement.setString(1, machineID); - preparedStatement.execute(); + preparedStatement.setString(1, machineID); + preparedStatement.execute(); - } catch (SQLException e) { - Logger.error(e); - } - } + } catch (SQLException e) { + Logger.error(e); + } + } - public ArrayList GET_TRASH_LIST() { + public ArrayList GET_TRASH_LIST() { - ArrayList machineList = new ArrayList<>(); + ArrayList machineList = new ArrayList<>(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("select `machineID` from `dyn_trash`")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("select `machineID` from `dyn_trash`")) { - ResultSet rs = preparedStatement.executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); - while (rs.next()) - machineList.add(rs.getString(1)); + while (rs.next()) + machineList.add(rs.getString(1)); - } catch (SQLException e) { - Logger.error(e); - } - return machineList; - } + } catch (SQLException e) { + Logger.error(e); + } + return machineList; + } - public void DELETE_VAULT_FOR_ACCOUNT(final int accountID) { + public void DELETE_VAULT_FOR_ACCOUNT(final int accountID) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `object` WHERE `parent`=? && `type`='item'")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `object` WHERE `parent`=? && `type`='item'")) { - preparedStatement.setLong(1, accountID); - preparedStatement.execute(); + preparedStatement.setLong(1, accountID); + preparedStatement.execute(); - } catch (SQLException e) { - Logger.error(e); - } - } + } catch (SQLException e) { + Logger.error(e); + } + } - public ArrayList GET_ALL_CHARS_FOR_MACHINE(String machineID) { + public ArrayList GET_ALL_CHARS_FOR_MACHINE(String machineID) { - ArrayList trashList = new ArrayList<>(); + ArrayList trashList = new ArrayList<>(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("select DISTINCT UID from object \n" + - "where parent IN (select AccountID from dyn_login_history " + - " WHERE`machineID`=?)")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("select DISTINCT UID from object \n" + + "where parent IN (select AccountID from dyn_login_history " + + " WHERE`machineID`=?)")) { - preparedStatement.setString(1, machineID); - ResultSet rs = preparedStatement.executeQuery(); + preparedStatement.setString(1, machineID); + ResultSet rs = preparedStatement.executeQuery(); - while (rs.next()) { + while (rs.next()) { - PlayerCharacter trashPlayer; - int playerID; + PlayerCharacter trashPlayer; + int playerID; - playerID = rs.getInt(1); - trashPlayer = PlayerCharacter.getPlayerCharacter(playerID); + playerID = rs.getInt(1); + trashPlayer = PlayerCharacter.getPlayerCharacter(playerID); - if (trashPlayer == null) - continue; + if (trashPlayer == null) + continue; - if (trashPlayer.isDeleted() == false) - trashList.add(trashPlayer); - } + if (trashPlayer.isDeleted() == false) + trashList.add(trashPlayer); + } - } catch (SQLException e) { - Logger.error(e); - } - return trashList; - } + } catch (SQLException e) { + Logger.error(e); + } + return trashList; + } - public void CLEAR_TRASH_TABLE() { + public void CLEAR_TRASH_TABLE() { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM dyn_trash")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM dyn_trash")) { - preparedStatement.execute(); + preparedStatement.execute(); - } catch (SQLException e) { - Logger.error(e); - } - } + } catch (SQLException e) { + Logger.error(e); + } + } - public void CREATE_SINGLE(String accountName, String password) { + public void CREATE_SINGLE(String accountName, String password) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("CALL singleAccountCreate(?,?)")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL singleAccountCreate(?,?)")) { - preparedStatement.setString(1, accountName); - preparedStatement.setString(2, password); + preparedStatement.setString(1, accountName); + preparedStatement.setString(2, password); - preparedStatement.execute(); + preparedStatement.execute(); - } catch (SQLException e) { - Logger.error(e); - } - } + } catch (SQLException e) { + Logger.error(e); + } + } - public Account GET_ACCOUNT(String uname) { + public Account GET_ACCOUNT(String uname) { - Account account = null; + Account account = null; - if (Account.AccountsMap.get(uname) != null) - return this.GET_ACCOUNT(Account.AccountsMap.get(uname)); + if (Account.AccountsMap.get(uname) != null) + return this.GET_ACCOUNT(Account.AccountsMap.get(uname)); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `obj_account` WHERE `acct_uname`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `obj_account` WHERE `acct_uname`=?")) { - preparedStatement.setString(1, uname); + preparedStatement.setString(1, uname); - ResultSet rs = preparedStatement.executeQuery(); - account = (Account) getObjectFromRs(rs); + ResultSet rs = preparedStatement.executeQuery(); + account = (Account) getObjectFromRs(rs); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - if (account != null) { - account.runAfterLoad(); + if (account != null) { + account.runAfterLoad(); - if (ConfigManager.serverType.equals(Enum.ServerType.LOGINSERVER)) - Account.AccountsMap.put(uname, account.getObjectUUID()); + if (ConfigManager.serverType.equals(Enum.ServerType.LOGINSERVER)) + Account.AccountsMap.put(uname, account.getObjectUUID()); - } - return account; - } + } + return account; + } - public void SET_ACCOUNT_LOGIN(final Account acc, String playerName, final String ip, final String machineID) { + public void SET_ACCOUNT_LOGIN(final Account acc, String playerName, final String ip, final String machineID) { - if (acc.getObjectUUID() == 0 || ip == null || ip.length() == 0) - return; + if (acc.getObjectUUID() == 0 || ip == null || ip.length() == 0) + return; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO dyn_login_history(`AccountID`, `accountName`, `characterName`, `ip`, `machineID`, `timeStamp`)" - + " VALUES (?, ?, ?, ?, ?, ?)")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO dyn_login_history(`AccountID`, `accountName`, `characterName`, `ip`, `machineID`, `timeStamp`)" + + " VALUES (?, ?, ?, ?, ?, ?)")) { - preparedStatement.setInt(1, acc.getObjectUUID()); - preparedStatement.setString(2, acc.getUname()); - preparedStatement.setString(3, playerName); - preparedStatement.setString(4, ip); - preparedStatement.setString(5, machineID); - preparedStatement.setTimestamp(6, new java.sql.Timestamp(System.currentTimeMillis())); + preparedStatement.setInt(1, acc.getObjectUUID()); + preparedStatement.setString(2, acc.getUname()); + preparedStatement.setString(3, playerName); + preparedStatement.setString(4, ip); + preparedStatement.setString(5, machineID); + preparedStatement.setTimestamp(6, new java.sql.Timestamp(System.currentTimeMillis())); - preparedStatement.execute(); + preparedStatement.execute(); - } catch (SQLException e) { - Logger.error(e); - } - } + } catch (SQLException e) { + Logger.error(e); + } + } - public void updateDatabase(final Account acc) { + public void updateDatabase(final Account acc) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_account` SET `acct_passwd`=?, " - + " `acct_lastCharUID`=?, `acct_salt`=?, `discordAccount`=?, " + - " status = ? WHERE `UID`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_account` SET `acct_passwd`=?, " + + " `acct_lastCharUID`=?, `acct_salt`=?, `discordAccount`=?, " + + " status = ? WHERE `UID`=?")) { - preparedStatement.setString(1, acc.getPasswd()); - preparedStatement.setInt(2, acc.getLastCharIDUsed()); - preparedStatement.setString(3, acc.getSalt()); - preparedStatement.setString(4, acc.discordAccount); - preparedStatement.setString(5, acc.status.name()); - preparedStatement.setInt(6, acc.getObjectUUID()); + preparedStatement.setString(1, acc.getPasswd()); + preparedStatement.setInt(2, acc.getLastCharIDUsed()); + preparedStatement.setString(3, acc.getSalt()); + preparedStatement.setString(4, acc.discordAccount); + preparedStatement.setString(5, acc.status.name()); + preparedStatement.setInt(6, acc.getObjectUUID()); - preparedStatement.execute(); + preparedStatement.execute(); - } catch (SQLException e) { - Logger.error(e); - } - } + } catch (SQLException e) { + Logger.error(e); + } + } - public void INVALIDATE_LOGIN_CACHE(long accountUID, String objectType) { + public void INVALIDATE_LOGIN_CACHE(long accountUID, String objectType) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("INSERT IGNORE INTO login_cachelist (`UID`, `type`) VALUES(?,?);")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT IGNORE INTO login_cachelist (`UID`, `type`) VALUES(?,?);")) { - preparedStatement.setLong(1, accountUID); - preparedStatement.setString(2, objectType); + preparedStatement.setLong(1, accountUID); + preparedStatement.setString(2, objectType); - preparedStatement.execute(); + preparedStatement.execute(); - } catch (SQLException e) { - Logger.error(e); - } - } + } catch (SQLException e) { + Logger.error(e); + } + } } diff --git a/src/engine/db/handlers/dbBaseClassHandler.java b/src/engine/db/handlers/dbBaseClassHandler.java index 30f476e6..93f144b5 100644 --- a/src/engine/db/handlers/dbBaseClassHandler.java +++ b/src/engine/db/handlers/dbBaseClassHandler.java @@ -23,69 +23,69 @@ import java.util.ArrayList; public class dbBaseClassHandler extends dbHandlerBase { - public dbBaseClassHandler() { - this.localClass = BaseClass.class; - this.localObjectType = Enum.GameObjectType.BaseClass; - } + public dbBaseClassHandler() { + this.localClass = BaseClass.class; + this.localObjectType = Enum.GameObjectType.BaseClass; + } - public BaseClass GET_BASE_CLASS(final int id) { + public BaseClass GET_BASE_CLASS(final int id) { - if (id == 0) - return null; + if (id == 0) + return null; - BaseClass baseClass = (BaseClass) DbManager.getFromCache(GameObjectType.BaseClass, id); + BaseClass baseClass = (BaseClass) DbManager.getFromCache(GameObjectType.BaseClass, id); - if (baseClass != null) - return baseClass; + if (baseClass != null) + return baseClass; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `obj_account` WHERE `UID`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `obj_account` WHERE `UID`=?")) { - preparedStatement.setLong(1, id); + preparedStatement.setLong(1, id); - ResultSet rs = preparedStatement.executeQuery(); - baseClass = (BaseClass) getObjectFromRs(rs); + ResultSet rs = preparedStatement.executeQuery(); + baseClass = (BaseClass) getObjectFromRs(rs); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return baseClass; - } + return baseClass; + } - public ArrayList GET_BASECLASS_FOR_RACE(final int id) { + public ArrayList GET_BASECLASS_FOR_RACE(final int id) { - ArrayList baseClasses = new ArrayList<>(); + ArrayList baseClasses = new ArrayList<>(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT b.* FROM `static_rune_baseclass` b, `static_rune_racebaseclass` r WHERE b.`ID` = r.`BaseClassID` && r.`RaceID` = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT b.* FROM `static_rune_baseclass` b, `static_rune_racebaseclass` r WHERE b.`ID` = r.`BaseClassID` && r.`RaceID` = ?")) { - preparedStatement.setInt(1, id); + preparedStatement.setInt(1, id); - ResultSet rs = preparedStatement.executeQuery(); - baseClasses = getObjectsFromRs(rs, 20); + ResultSet rs = preparedStatement.executeQuery(); + baseClasses = getObjectsFromRs(rs, 20); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return baseClasses; - } + return baseClasses; + } - public ArrayList GET_ALL_BASE_CLASSES() { + public ArrayList GET_ALL_BASE_CLASSES() { - ArrayList baseClasses = new ArrayList<>(); + ArrayList baseClasses = new ArrayList<>(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_baseclass`;")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_baseclass`;")) { - ResultSet rs = preparedStatement.executeQuery(); - baseClasses = getObjectsFromRs(rs, 20); + ResultSet rs = preparedStatement.executeQuery(); + baseClasses = getObjectsFromRs(rs, 20); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return baseClasses; - } + return baseClasses; + } } diff --git a/src/engine/db/handlers/dbBuildingLocationHandler.java b/src/engine/db/handlers/dbBuildingLocationHandler.java index bd89fad0..b92f2002 100644 --- a/src/engine/db/handlers/dbBuildingLocationHandler.java +++ b/src/engine/db/handlers/dbBuildingLocationHandler.java @@ -21,29 +21,29 @@ import java.util.ArrayList; public class dbBuildingLocationHandler extends dbHandlerBase { - public dbBuildingLocationHandler() { - this.localClass = BuildingLocation.class; + public dbBuildingLocationHandler() { + this.localClass = BuildingLocation.class; this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); - } + } - public ArrayList LOAD_BUILDING_LOCATIONS() { + public ArrayList LOAD_BUILDING_LOCATIONS() { - ArrayList buildingLocations = new ArrayList<>(); + ArrayList buildingLocations = new ArrayList<>(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("select * from static_building_location " + - "where type = 6 or type = 8 " + - "GROUP BY buildingID, slot " + - "ORDER BY buildingID, slot ASC;")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("select * from static_building_location " + + "where type = 6 or type = 8 " + + "GROUP BY buildingID, slot " + + "ORDER BY buildingID, slot ASC;")) { - ResultSet rs = preparedStatement.executeQuery(); - buildingLocations = getObjectsFromRs(rs, 20); + ResultSet rs = preparedStatement.executeQuery(); + buildingLocations = getObjectsFromRs(rs, 20); - } catch (SQLException e) { - Logger.error(e); - return buildingLocations; - } + } catch (SQLException e) { + Logger.error(e); + return buildingLocations; + } - return buildingLocations; - } + return buildingLocations; + } } diff --git a/src/engine/db/handlers/dbCharacterPowerHandler.java b/src/engine/db/handlers/dbCharacterPowerHandler.java index cbed4c38..3a2bbcf8 100644 --- a/src/engine/db/handlers/dbCharacterPowerHandler.java +++ b/src/engine/db/handlers/dbCharacterPowerHandler.java @@ -24,149 +24,149 @@ import java.util.concurrent.ConcurrentHashMap; public class dbCharacterPowerHandler extends dbHandlerBase { - public dbCharacterPowerHandler() { - this.localClass = CharacterPower.class; - this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); - } + public dbCharacterPowerHandler() { + this.localClass = CharacterPower.class; + this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); + } - public CharacterPower ADD_CHARACTER_POWER(CharacterPower toAdd) { + public CharacterPower ADD_CHARACTER_POWER(CharacterPower toAdd) { - CharacterPower characterPower = null; + CharacterPower characterPower = null; - if (CharacterPower.getOwner(toAdd) == null || toAdd.getPower() == null) { - Logger.error("dbCharacterSkillHandler.ADD_Power", toAdd.getObjectUUID() + " missing owner or powersBase"); - return null; - } + if (CharacterPower.getOwner(toAdd) == null || toAdd.getPower() == null) { + Logger.error("dbCharacterSkillHandler.ADD_Power", toAdd.getObjectUUID() + " missing owner or powersBase"); + return null; + } - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_power` (`CharacterID`, `powersBaseToken`, `trains`) VALUES (?, ?, ?);")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_power` (`CharacterID`, `powersBaseToken`, `trains`) VALUES (?, ?, ?);")) { - preparedStatement.setLong(1, CharacterPower.getOwner(toAdd).getObjectUUID()); - preparedStatement.setInt(2, toAdd.getPower().getToken()); - preparedStatement.setInt(3, toAdd.getTrains()); + preparedStatement.setLong(1, CharacterPower.getOwner(toAdd).getObjectUUID()); + preparedStatement.setInt(2, toAdd.getPower().getToken()); + preparedStatement.setInt(3, toAdd.getTrains()); - preparedStatement.executeUpdate(); - ResultSet rs = preparedStatement.getGeneratedKeys(); + preparedStatement.executeUpdate(); + ResultSet rs = preparedStatement.getGeneratedKeys(); - if (rs.next()) - characterPower = GET_CHARACTER_POWER(rs.getInt(1)); + if (rs.next()) + characterPower = GET_CHARACTER_POWER(rs.getInt(1)); - } catch (SQLException e) { - Logger.error(e); - return null; - } - return characterPower; - } + } catch (SQLException e) { + Logger.error(e); + return null; + } + return characterPower; + } - public int DELETE_CHARACTER_POWER(final int objectUUID) { + public int DELETE_CHARACTER_POWER(final int objectUUID) { - int rowCount = 0; + int rowCount = 0; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_character_power` WHERE `UID` = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_character_power` WHERE `UID` = ?")) { - preparedStatement.setLong(1, objectUUID); - rowCount = preparedStatement.executeUpdate(); + preparedStatement.setLong(1, objectUUID); + rowCount = preparedStatement.executeUpdate(); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return rowCount; - } + return rowCount; + } - public CharacterPower GET_CHARACTER_POWER(int objectUUID) { + public CharacterPower GET_CHARACTER_POWER(int objectUUID) { - CharacterPower characterPower = (CharacterPower) DbManager.getFromCache(Enum.GameObjectType.CharacterPower, objectUUID); + CharacterPower characterPower = (CharacterPower) DbManager.getFromCache(Enum.GameObjectType.CharacterPower, objectUUID); - if (characterPower != null) - return characterPower; + if (characterPower != null) + return characterPower; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_character_power` WHERE `UID` = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_character_power` WHERE `UID` = ?")) { - preparedStatement.setLong(1, objectUUID); - ResultSet rs = preparedStatement.executeQuery(); - characterPower = (CharacterPower) getObjectFromRs(rs); + preparedStatement.setLong(1, objectUUID); + ResultSet rs = preparedStatement.executeQuery(); + characterPower = (CharacterPower) getObjectFromRs(rs); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return characterPower; - } + return characterPower; + } - public ConcurrentHashMap GET_POWERS_FOR_CHARACTER(PlayerCharacter pc) { + public ConcurrentHashMap GET_POWERS_FOR_CHARACTER(PlayerCharacter pc) { - ConcurrentHashMap powers = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW); - int objectUUID = pc.getObjectUUID(); + ConcurrentHashMap powers = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW); + int objectUUID = pc.getObjectUUID(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_character_power` WHERE CharacterID = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_character_power` WHERE CharacterID = ?")) { - preparedStatement.setLong(1, (long) objectUUID); - ResultSet rs = preparedStatement.executeQuery(); + preparedStatement.setLong(1, objectUUID); + ResultSet rs = preparedStatement.executeQuery(); - while (rs.next()) { - CharacterPower cp = new CharacterPower(rs, pc); - if (cp.getPower() != null) - powers.put(cp.getPower().getToken(), cp); - } + while (rs.next()) { + CharacterPower cp = new CharacterPower(rs, pc); + if (cp.getPower() != null) + powers.put(cp.getPower().getToken(), cp); + } - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return powers; - } + return powers; + } - public void UPDATE_TRAINS(final CharacterPower characterPower) { + public void UPDATE_TRAINS(final CharacterPower characterPower) { - //skip update if nothing changed + //skip update if nothing changed - if (!characterPower.isTrained()) - return; + if (!characterPower.isTrained()) + return; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_character_power` SET `trains`=? WHERE `UID`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_character_power` SET `trains`=? WHERE `UID`=?")) { - preparedStatement.setShort(1, (short) characterPower.getTrains()); - preparedStatement.setInt(2, characterPower.getObjectUUID()); + preparedStatement.setShort(1, (short) characterPower.getTrains()); + preparedStatement.setInt(2, characterPower.getObjectUUID()); - preparedStatement.execute(); + preparedStatement.execute(); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - characterPower.setTrained(false); - } + characterPower.setTrained(false); + } - public void updateDatabase(final CharacterPower pow) { + public void updateDatabase(final CharacterPower pow) { - if (pow.getPower() == null) { - Logger.error("Failed to find powersBase for Power " + pow.getObjectUUID()); - return; - } + if (pow.getPower() == null) { + Logger.error("Failed to find powersBase for Power " + pow.getObjectUUID()); + return; + } - if (CharacterPower.getOwner(pow) == null) { - Logger.error("Failed to find owner for Power " + pow.getObjectUUID()); - return; - } + if (CharacterPower.getOwner(pow) == null) { + Logger.error("Failed to find owner for Power " + pow.getObjectUUID()); + return; + } - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_character_power` SET `PowersBaseToken`=?, `CharacterID`=?, `trains`=? WHERE `UID`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_character_power` SET `PowersBaseToken`=?, `CharacterID`=?, `trains`=? WHERE `UID`=?")) { - preparedStatement.setInt(1, pow.getPower().getToken()); - preparedStatement.setInt(2, CharacterPower.getOwner(pow).getObjectUUID()); - preparedStatement.setShort(3, (short) pow.getTrains()); - preparedStatement.setInt(4, pow.getObjectUUID()); - preparedStatement.execute(); + preparedStatement.setInt(1, pow.getPower().getToken()); + preparedStatement.setInt(2, CharacterPower.getOwner(pow).getObjectUUID()); + preparedStatement.setShort(3, (short) pow.getTrains()); + preparedStatement.setInt(4, pow.getObjectUUID()); + preparedStatement.execute(); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - pow.setTrained(false); - } + pow.setTrained(false); + } } diff --git a/src/engine/db/handlers/dbCharacterRuneHandler.java b/src/engine/db/handlers/dbCharacterRuneHandler.java index e708dcea..d63bc6d8 100644 --- a/src/engine/db/handlers/dbCharacterRuneHandler.java +++ b/src/engine/db/handlers/dbCharacterRuneHandler.java @@ -22,103 +22,103 @@ import java.util.ArrayList; public class dbCharacterRuneHandler extends dbHandlerBase { - public dbCharacterRuneHandler() { - this.localClass = CharacterRune.class; - this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); - } + public dbCharacterRuneHandler() { + this.localClass = CharacterRune.class; + this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); + } - public CharacterRune ADD_CHARACTER_RUNE(final CharacterRune toAdd) { + public CharacterRune ADD_CHARACTER_RUNE(final CharacterRune toAdd) { - CharacterRune characterRune = null; + CharacterRune characterRune = null; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_rune` (`CharacterID`, `RuneBaseID`) VALUES (?, ?);")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_rune` (`CharacterID`, `RuneBaseID`) VALUES (?, ?);")) { - preparedStatement.setLong(1, toAdd.getPlayerID()); - preparedStatement.setInt(2, toAdd.getRuneBaseID()); + preparedStatement.setLong(1, toAdd.getPlayerID()); + preparedStatement.setInt(2, toAdd.getRuneBaseID()); - preparedStatement.executeUpdate(); - ResultSet rs = preparedStatement.getGeneratedKeys(); + preparedStatement.executeUpdate(); + ResultSet rs = preparedStatement.getGeneratedKeys(); - if (rs.next()) - characterRune = GET_CHARACTER_RUNE(rs.getInt(1)); + if (rs.next()) + characterRune = GET_CHARACTER_RUNE(rs.getInt(1)); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return characterRune; - } + return characterRune; + } - public CharacterRune GET_CHARACTER_RUNE(int runeID) { + public CharacterRune GET_CHARACTER_RUNE(int runeID) { - CharacterRune characterRune = (CharacterRune) DbManager.getFromCache(Enum.GameObjectType.CharacterRune, runeID); + CharacterRune characterRune = (CharacterRune) DbManager.getFromCache(Enum.GameObjectType.CharacterRune, runeID); - if (characterRune != null) - return characterRune; + if (characterRune != null) + return characterRune; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_character_rune` WHERE `UID`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_character_rune` WHERE `UID`=?")) { - preparedStatement.setInt(1, runeID); - ResultSet rs = preparedStatement.executeQuery(); + preparedStatement.setInt(1, runeID); + ResultSet rs = preparedStatement.executeQuery(); - characterRune = (CharacterRune) getObjectFromRs(rs); + characterRune = (CharacterRune) getObjectFromRs(rs); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return characterRune; - } + return characterRune; + } - public boolean DELETE_CHARACTER_RUNE(final CharacterRune characterRune) { + public boolean DELETE_CHARACTER_RUNE(final CharacterRune characterRune) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_character_rune` WHERE `UID`=?;")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_character_rune` WHERE `UID`=?;")) { - preparedStatement.setLong(1, characterRune.getObjectUUID()); + preparedStatement.setLong(1, characterRune.getObjectUUID()); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - public ArrayList GET_RUNES_FOR_CHARACTER(final int characterId) { + public ArrayList GET_RUNES_FOR_CHARACTER(final int characterId) { - ArrayList characterRunes = new ArrayList<>(); + ArrayList characterRunes = new ArrayList<>(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_character_rune` WHERE `CharacterID` = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_character_rune` WHERE `CharacterID` = ?")) { - preparedStatement.setInt(1, characterId); + preparedStatement.setInt(1, characterId); - ResultSet rs = preparedStatement.executeQuery(); - characterRunes = getObjectsFromRs(rs, 10); + ResultSet rs = preparedStatement.executeQuery(); + characterRunes = getObjectsFromRs(rs, 10); - } catch (SQLException e) { - Logger.error(e); - } - return characterRunes; - } + } catch (SQLException e) { + Logger.error(e); + } + return characterRunes; + } - public void updateDatabase(final CharacterRune characterRune) { + public void updateDatabase(final CharacterRune characterRune) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_character_rune` SET `CharacterID`=?, `RuneBaseID`=? WHERE `UID` = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_character_rune` SET `CharacterID`=?, `RuneBaseID`=? WHERE `UID` = ?")) { - preparedStatement.setInt(1, characterRune.getPlayerID()); - preparedStatement.setInt(2, characterRune.getRuneBaseID()); - preparedStatement.setLong(3, (long) characterRune.getObjectUUID()); + preparedStatement.setInt(1, characterRune.getPlayerID()); + preparedStatement.setInt(2, characterRune.getRuneBaseID()); + preparedStatement.setLong(3, characterRune.getObjectUUID()); - preparedStatement.execute(); + preparedStatement.execute(); - } catch (SQLException e) { - Logger.error(e); - } - } + } catch (SQLException e) { + Logger.error(e); + } + } } diff --git a/src/engine/db/handlers/dbCharacterSkillHandler.java b/src/engine/db/handlers/dbCharacterSkillHandler.java index c966b77e..fd46d5c5 100644 --- a/src/engine/db/handlers/dbCharacterSkillHandler.java +++ b/src/engine/db/handlers/dbCharacterSkillHandler.java @@ -134,7 +134,7 @@ public class dbCharacterSkillHandler extends dbHandlerBase { PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_character_skill` SET `trains`=? WHERE `UID` = ?")) { preparedStatement.setShort(1, (short) characterSkill.getNumTrains()); - preparedStatement.setLong(2, (long) characterSkill.getObjectUUID()); + preparedStatement.setLong(2, characterSkill.getObjectUUID()); if (preparedStatement.executeUpdate() != 0) characterSkill.syncTrains(); @@ -162,7 +162,7 @@ public class dbCharacterSkillHandler extends dbHandlerBase { preparedStatement.setInt(1, characterSkill.getSkillsBase().getObjectUUID()); preparedStatement.setInt(2, CharacterSkill.GetOwner(characterSkill).getObjectUUID()); preparedStatement.setShort(3, (short) characterSkill.getNumTrains()); - preparedStatement.setLong(4, (long) characterSkill.getObjectUUID()); + preparedStatement.setLong(4, characterSkill.getObjectUUID()); if (preparedStatement.executeUpdate() != 0) characterSkill.syncTrains(); diff --git a/src/engine/db/handlers/dbEffectsBaseHandler.java b/src/engine/db/handlers/dbEffectsBaseHandler.java index 5b030993..de60587c 100644 --- a/src/engine/db/handlers/dbEffectsBaseHandler.java +++ b/src/engine/db/handlers/dbEffectsBaseHandler.java @@ -25,7 +25,7 @@ import java.util.HashSet; public class dbEffectsBaseHandler extends dbHandlerBase { - public dbEffectsBaseHandler() { + public dbEffectsBaseHandler() { } diff --git a/src/engine/db/handlers/dbEffectsResourceCostHandler.java b/src/engine/db/handlers/dbEffectsResourceCostHandler.java index 36e58b35..deae93a9 100644 --- a/src/engine/db/handlers/dbEffectsResourceCostHandler.java +++ b/src/engine/db/handlers/dbEffectsResourceCostHandler.java @@ -21,27 +21,27 @@ import java.util.ArrayList; public class dbEffectsResourceCostHandler extends dbHandlerBase { - public dbEffectsResourceCostHandler() { - this.localClass = EffectsResourceCosts.class; + public dbEffectsResourceCostHandler() { + this.localClass = EffectsResourceCosts.class; this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); - } - - public ArrayList GET_ALL_EFFECT_RESOURCES(String idString) { + } - ArrayList effectsResourceCosts = new ArrayList<>(); + public ArrayList GET_ALL_EFFECT_RESOURCES(String idString) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_power_effectcost` WHERE `IDString` = ?")) { + ArrayList effectsResourceCosts = new ArrayList<>(); - preparedStatement.setString(1, idString); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_power_effectcost` WHERE `IDString` = ?")) { - ResultSet rs = preparedStatement.executeQuery(); - effectsResourceCosts = getObjectsFromRs(rs, 1000); + preparedStatement.setString(1, idString); - } catch (SQLException e) { - Logger.error(e); - } + ResultSet rs = preparedStatement.executeQuery(); + effectsResourceCosts = getObjectsFromRs(rs, 1000); - return effectsResourceCosts; - } + } catch (SQLException e) { + Logger.error(e); + } + + return effectsResourceCosts; + } } diff --git a/src/engine/db/handlers/dbEnchantmentHandler.java b/src/engine/db/handlers/dbEnchantmentHandler.java index 1ba8c316..87e211de 100644 --- a/src/engine/db/handlers/dbEnchantmentHandler.java +++ b/src/engine/db/handlers/dbEnchantmentHandler.java @@ -21,55 +21,55 @@ import java.util.concurrent.ConcurrentHashMap; public class dbEnchantmentHandler extends dbHandlerBase { - public ConcurrentHashMap GET_ENCHANTMENTS_FOR_ITEM(final int id) { + public ConcurrentHashMap GET_ENCHANTMENTS_FOR_ITEM(final int id) { - ConcurrentHashMap enchants = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW); + ConcurrentHashMap enchants = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_item_enchantment` WHERE `ItemID`=?;")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_item_enchantment` WHERE `ItemID`=?;")) { - preparedStatement.setLong(1, id); + preparedStatement.setLong(1, id); - ResultSet rs = preparedStatement.executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); - while (rs.next()) - enchants.put(rs.getString("powerAction"), rs.getInt("rank")); + while (rs.next()) + enchants.put(rs.getString("powerAction"), rs.getInt("rank")); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return enchants; - } + return enchants; + } - public boolean CREATE_ENCHANTMENT_FOR_ITEM(long itemID, String powerAction, int rank) { + public boolean CREATE_ENCHANTMENT_FOR_ITEM(long itemID, String powerAction, int rank) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_item_enchantment` (`itemID`, `powerAction`, `rank`) VALUES (?, ?, ?);")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_item_enchantment` (`itemID`, `powerAction`, `rank`) VALUES (?, ?, ?);")) { - preparedStatement.setLong(1, itemID); - preparedStatement.setString(2, powerAction); - preparedStatement.setInt(3, rank); + preparedStatement.setLong(1, itemID); + preparedStatement.setString(2, powerAction); + preparedStatement.setInt(3, rank); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - public boolean CLEAR_ENCHANTMENTS(long itemID) { + public boolean CLEAR_ENCHANTMENTS(long itemID) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_item_enchantment` WHERE `itemID`=?;")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_item_enchantment` WHERE `itemID`=?;")) { - preparedStatement.setLong(1, itemID); - return (preparedStatement.executeUpdate() > 0); + preparedStatement.setLong(1, itemID); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + } catch (SQLException e) { + Logger.error(e); + } + return false; + } } diff --git a/src/engine/db/handlers/dbGuildHandler.java b/src/engine/db/handlers/dbGuildHandler.java index b5a6dc70..d4917eef 100644 --- a/src/engine/db/handlers/dbGuildHandler.java +++ b/src/engine/db/handlers/dbGuildHandler.java @@ -22,679 +22,678 @@ import java.util.ArrayList; public class dbGuildHandler extends dbHandlerBase { - public dbGuildHandler() { - this.localClass = Guild.class; - this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); - } + public dbGuildHandler() { + this.localClass = Guild.class; + this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); + } - public int BANISH_FROM_GUILD_OFFLINE(final int target, boolean sourceIsGuildLeader) { + public static ArrayList GET_GUILD_BANISHED(final int id) { - String queryString; - int rowCount; + return new ArrayList<>(); - // Only a Guild Leader can remove inner council + // Bugfix + // prepareCallable("SELECT * FROM `obj_character`, `dyn_guild_banishlist` WHERE `obj_character.char_isActive` = 1 AND `dyn_guild_banishlist.CharacterID` = `obj_character.UID` AND `obj_character.GuildID`=?"); - if (sourceIsGuildLeader) - queryString = "UPDATE `obj_character` SET `guildUID`=NULL, `guild_isInnerCouncil`=0, `guild_isTaxCollector`=0," - + " `guild_isRecruiter`=0, `guild_isFullMember`=0, `guild_title`=0 WHERE `UID`=?"; - else - queryString = "UPDATE `obj_character` SET `guildUID`=NULL, `guild_isInnerCouncil`=0, `guild_isTaxCollector`=0," - + " `guild_isRecruiter`=0, `guild_isFullMember`=0, `guild_title`=0 WHERE `UID`=? && `guild_isInnerCouncil`=0"; + //prepareCallable("SELECT * FROM `obj_character` `,` `dyn_guild_banishlist` WHERE obj_character.char_isActive = 1 AND dyn_guild_banishlist.CharacterID = obj_character.UID AND dyn_guild_banishlist.GuildID = ?"); + //setLong(1, (long) id); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement(queryString)) { + //return getObjectList(); + } - preparedStatement.setLong(1, target); - rowCount = preparedStatement.executeUpdate(); + public static void LOAD_GUILD_HISTORY_FOR_PLAYER(PlayerCharacter playerCharacter) { - } catch (SQLException e) { - Logger.error(e); - return 0; - } + if (playerCharacter == null) + return; - return rowCount; - } + ArrayList guildList = new ArrayList<>(); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_guild_allianceenemylist` WHERE `GuildID` = ?")) { - public boolean ADD_TO_BANISHED_FROM_GUILDLIST(int target, long characterID) { + preparedStatement.setInt(1, playerCharacter.getObjectUUID()); + ResultSet rs = preparedStatement.executeQuery(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_guild_banishlist` (`GuildID`, `CharacterID`) VALUES (?,?)")) { + while (rs.next()) { + GuildHistory guildEntry = new GuildHistory(rs); + guildList.add(guildEntry); + } - preparedStatement.setLong(1, (long) target); - preparedStatement.setLong(2, characterID); + } catch (SQLException e) { + Logger.error(e); + } - return (preparedStatement.executeUpdate() > 0); + playerCharacter.setGuildHistory(guildList); + } - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + public int BANISH_FROM_GUILD_OFFLINE(final int target, boolean sourceIsGuildLeader) { - public boolean REMOVE_FROM_BANISH_LIST(int target, long characterID) { + String queryString; + int rowCount; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_guild_banishlist` (`GuildID`, `CharacterID`) VALUES (?,?)")) { + // Only a Guild Leader can remove inner council - preparedStatement.setLong(1, (long) target); - preparedStatement.setLong(2, characterID); + if (sourceIsGuildLeader) + queryString = "UPDATE `obj_character` SET `guildUID`=NULL, `guild_isInnerCouncil`=0, `guild_isTaxCollector`=0," + + " `guild_isRecruiter`=0, `guild_isFullMember`=0, `guild_title`=0 WHERE `UID`=?"; + else + queryString = "UPDATE `obj_character` SET `guildUID`=NULL, `guild_isInnerCouncil`=0, `guild_isTaxCollector`=0," + + " `guild_isRecruiter`=0, `guild_isFullMember`=0, `guild_title`=0 WHERE `UID`=? && `guild_isInnerCouncil`=0"; - return (preparedStatement.executeUpdate() > 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement(queryString)) { - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + preparedStatement.setLong(1, target); + rowCount = preparedStatement.executeUpdate(); - public boolean ADD_TO_GUILDHISTORY(int target, PlayerCharacter playerCharacter, DateTime historyDate, GuildHistoryType historyType) { + } catch (SQLException e) { + Logger.error(e); + return 0; + } - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_guildhistory` (`GuildID`, `CharacterID`, `historyDate`, `historyType`) VALUES (?,?,?,?)")) { + return rowCount; + } - preparedStatement.setLong(1, target); - preparedStatement.setLong(2, playerCharacter.getObjectUUID()); + public boolean ADD_TO_BANISHED_FROM_GUILDLIST(int target, long characterID) { - if (historyDate == null) - preparedStatement.setNull(3, java.sql.Types.DATE); - else - preparedStatement.setTimestamp(3, new Timestamp(historyDate.getMillis())); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_guild_banishlist` (`GuildID`, `CharacterID`) VALUES (?,?)")) { - preparedStatement.setString(4, historyType.name()); + preparedStatement.setLong(1, target); + preparedStatement.setLong(2, characterID); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - //TODO Need to get this working. - public ArrayList GET_GUILD_HISTORY_OF_PLAYER(final int id) { + public boolean REMOVE_FROM_BANISH_LIST(int target, long characterID) { - ArrayList guildList = null; + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_guild_banishlist` (`GuildID`, `CharacterID`) VALUES (?,?)")) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT g.* FROM `obj_guild` g, `dyn_character_guildhistory` l WHERE g.`UID` = l.`GuildID` && l.`CharacterID` = ?")) { + preparedStatement.setLong(1, target); + preparedStatement.setLong(2, characterID); - preparedStatement.setLong(1, id); + return (preparedStatement.executeUpdate() > 0); - ResultSet rs = preparedStatement.executeQuery(); - guildList = getObjectsFromRs(rs, 20); + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - } catch (SQLException e) { - Logger.error(e); - } + public boolean ADD_TO_GUILDHISTORY(int target, PlayerCharacter playerCharacter, DateTime historyDate, GuildHistoryType historyType) { - return guildList; - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_guildhistory` (`GuildID`, `CharacterID`, `historyDate`, `historyType`) VALUES (?,?,?,?)")) { - public ArrayList GET_GUILD_ALLIES(final int id) { + preparedStatement.setLong(1, target); + preparedStatement.setLong(2, playerCharacter.getObjectUUID()); - ArrayList guildList = null; + if (historyDate == null) + preparedStatement.setNull(3, java.sql.Types.DATE); + else + preparedStatement.setTimestamp(3, new Timestamp(historyDate.getMillis())); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT g.* FROM `obj_guild` g, `dyn_guild_allianceenemylist` l " - + "WHERE l.isAlliance = 1 && l.OtherGuildID = g.UID && l.GuildID=?")) { + preparedStatement.setString(4, historyType.name()); - preparedStatement.setLong(1, id); + return (preparedStatement.executeUpdate() > 0); - ResultSet rs = preparedStatement.executeQuery(); - guildList = getObjectsFromRs(rs, 20); + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - } catch (SQLException e) { - Logger.error(e); - } + //TODO Need to get this working. + public ArrayList GET_GUILD_HISTORY_OF_PLAYER(final int id) { - return guildList; + ArrayList guildList = null; - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT g.* FROM `obj_guild` g, `dyn_character_guildhistory` l WHERE g.`UID` = l.`GuildID` && l.`CharacterID` = ?")) { - public static ArrayList GET_GUILD_BANISHED(final int id) { + preparedStatement.setLong(1, id); - return new ArrayList<>(); + ResultSet rs = preparedStatement.executeQuery(); + guildList = getObjectsFromRs(rs, 20); - // Bugfix - // prepareCallable("SELECT * FROM `obj_character`, `dyn_guild_banishlist` WHERE `obj_character.char_isActive` = 1 AND `dyn_guild_banishlist.CharacterID` = `obj_character.UID` AND `obj_character.GuildID`=?"); + } catch (SQLException e) { + Logger.error(e); + } - //prepareCallable("SELECT * FROM `obj_character` `,` `dyn_guild_banishlist` WHERE obj_character.char_isActive = 1 AND dyn_guild_banishlist.CharacterID = obj_character.UID AND dyn_guild_banishlist.GuildID = ?"); - //setLong(1, (long) id); + return guildList; + } - //return getObjectList(); - } + public ArrayList GET_GUILD_ALLIES(final int id) { - public ArrayList GET_GUILD_ENEMIES(final int id) { + ArrayList guildList = null; - ArrayList guildList = null; + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT g.* FROM `obj_guild` g, `dyn_guild_allianceenemylist` l " + + "WHERE l.isAlliance = 1 && l.OtherGuildID = g.UID && l.GuildID=?")) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT g.* FROM `obj_guild` g, `dyn_guild_allianceenemylist` l " - + "WHERE l.isAlliance = 0 && l.OtherGuildID = g.UID && l.GuildID=?")) { + preparedStatement.setLong(1, id); - preparedStatement.setLong(1, id); + ResultSet rs = preparedStatement.executeQuery(); + guildList = getObjectsFromRs(rs, 20); - ResultSet rs = preparedStatement.executeQuery(); - guildList = getObjectsFromRs(rs, 20); + } catch (SQLException e) { + Logger.error(e); + } - } catch (SQLException e) { - Logger.error(e); - } + return guildList; - return guildList; + } - } + public ArrayList GET_GUILD_ENEMIES(final int id) { - public ArrayList GET_GUILD_KOS_CHARACTER(final int id) { + ArrayList guildList = null; - ArrayList kosList = null; + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT g.* FROM `obj_guild` g, `dyn_guild_allianceenemylist` l " + + "WHERE l.isAlliance = 0 && l.OtherGuildID = g.UID && l.GuildID=?")) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT c.* FROM `obj_character` c, `dyn_guild_characterkoslist` l WHERE c.`char_isActive` = 1 && l.`KOSCharacterID` = c.`UID` && l.`GuildID`=?")) { + preparedStatement.setLong(1, id); - preparedStatement.setLong(1, id); - ResultSet rs = preparedStatement.executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); + guildList = getObjectsFromRs(rs, 20); - while (rs.next()) { - int playerUUID = rs.getInt(1); - PlayerCharacter kosPlayer = PlayerCharacter.getPlayerCharacter(playerUUID); + } catch (SQLException e) { + Logger.error(e); + } - if (kosPlayer != null) - kosList.add(kosPlayer); - } + return guildList; - } catch (SQLException e) { - Logger.error(e); - } + } - return kosList; - } + public ArrayList GET_GUILD_KOS_CHARACTER(final int id) { - public ArrayList GET_GUILD_KOS_GUILD(final int id) { + ArrayList kosList = null; - ArrayList guildList = null; + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT c.* FROM `obj_character` c, `dyn_guild_characterkoslist` l WHERE c.`char_isActive` = 1 && l.`KOSCharacterID` = c.`UID` && l.`GuildID`=?")) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT g.* FROM `obj_guild` g, `dyn_guild_guildkoslist` l " - + "WHERE l.KOSGuildID = g.UID && l.GuildID = ?")) { + preparedStatement.setLong(1, id); + ResultSet rs = preparedStatement.executeQuery(); - preparedStatement.setLong(1, id); + while (rs.next()) { + int playerUUID = rs.getInt(1); + PlayerCharacter kosPlayer = PlayerCharacter.getPlayerCharacter(playerUUID); - ResultSet rs = preparedStatement.executeQuery(); - guildList = getObjectsFromRs(rs, 20); + if (kosPlayer != null) + kosList.add(kosPlayer); + } - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return guildList; - } + return kosList; + } - public ArrayList GET_SUB_GUILDS(final int guildID) { + public ArrayList GET_GUILD_KOS_GUILD(final int id) { - ArrayList guildList = null; + ArrayList guildList = null; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_guild`.*, `object`.`parent` FROM `object` INNER JOIN `obj_guild` ON `obj_guild`.`UID` = `object`.`UID` WHERE `object`.`parent` = ?;")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT g.* FROM `obj_guild` g, `dyn_guild_guildkoslist` l " + + "WHERE l.KOSGuildID = g.UID && l.GuildID = ?")) { - preparedStatement.setInt(1, guildID); + preparedStatement.setLong(1, id); - ResultSet rs = preparedStatement.executeQuery(); - guildList = getObjectsFromRs(rs, 20); + ResultSet rs = preparedStatement.executeQuery(); + guildList = getObjectsFromRs(rs, 20); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return guildList; - } + return guildList; + } - public Guild GET_GUILD(int id) { + public ArrayList GET_SUB_GUILDS(final int guildID) { - Guild guild = (Guild) DbManager.getFromCache(Enum.GameObjectType.Guild, id); + ArrayList guildList = null; - if (guild != null) - return guild; + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_guild`.*, `object`.`parent` FROM `object` INNER JOIN `obj_guild` ON `obj_guild`.`UID` = `object`.`UID` WHERE `object`.`parent` = ?;")) { - if (id == 0) - return Guild.getErrantGuild(); + preparedStatement.setInt(1, guildID); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_guild`.*, `object`.`parent` FROM `obj_guild` INNER JOIN `object` ON `object`.`UID` = `obj_guild`.`UID` WHERE `object`.`UID`=?")) { + ResultSet rs = preparedStatement.executeQuery(); + guildList = getObjectsFromRs(rs, 20); - preparedStatement.setLong(1, id); + } catch (SQLException e) { + Logger.error(e); + } - ResultSet rs = preparedStatement.executeQuery(); - guild = (Guild) getObjectFromRs(rs); + return guildList; + } - } catch (SQLException e) { - Logger.error(e); - } - return guild; + public Guild GET_GUILD(int id) { - } - - public ArrayList GET_ALL_GUILDS() { + Guild guild = (Guild) DbManager.getFromCache(Enum.GameObjectType.Guild, id); - ArrayList guildList = null; + if (guild != null) + return guild; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_guild`.*, `object`.`parent` FROM `obj_guild` INNER JOIN `object` ON `object`.`UID` = `obj_guild`.`UID`")) { + if (id == 0) + return Guild.getErrantGuild(); - ResultSet rs = preparedStatement.executeQuery(); - guildList = getObjectsFromRs(rs, 20); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_guild`.*, `object`.`parent` FROM `obj_guild` INNER JOIN `object` ON `object`.`UID` = `obj_guild`.`UID` WHERE `object`.`UID`=?")) { - } catch (SQLException e) { - Logger.error(e); - } - return guildList; - } + preparedStatement.setLong(1, id); - public boolean IS_CREST_UNIQUE(final GuildTag gt) { + ResultSet rs = preparedStatement.executeQuery(); + guild = (Guild) getObjectFromRs(rs); - boolean valid = false; - String queryString; + } catch (SQLException e) { + Logger.error(e); + } + return guild; - // Ignore bg symbol if bg color is the same as fg color. + } - if (gt.backgroundColor01 == gt.backgroundColor02) - queryString = "SELECT `name` FROM `obj_guild` WHERE `backgroundColor01`=? && `backgroundColor02`=? && `symbolColor`=? && `symbol`=?;"; - else - queryString = "SELECT `name` FROM `obj_guild` WHERE `backgroundColor01`=? && `backgroundColor02`=? && `symbolColor`=? && `backgroundDesign`=? && `symbol`=?;"; + public ArrayList GET_ALL_GUILDS() { + ArrayList guildList = null; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement(queryString)) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_guild`.*, `object`.`parent` FROM `obj_guild` INNER JOIN `object` ON `object`.`UID` = `obj_guild`.`UID`")) { - if (gt.backgroundColor01 == gt.backgroundColor02) { - preparedStatement.setInt(1, gt.backgroundColor01); - preparedStatement.setInt(2, gt.backgroundColor02); - preparedStatement.setInt(3, gt.symbolColor); - preparedStatement.setInt(4, gt.symbol); - } else { - preparedStatement.setInt(1, gt.backgroundColor01); - preparedStatement.setInt(2, gt.backgroundColor02); - preparedStatement.setInt(3, gt.symbolColor); - preparedStatement.setInt(4, gt.backgroundDesign); - preparedStatement.setInt(5, gt.symbol); - } + ResultSet rs = preparedStatement.executeQuery(); + guildList = getObjectsFromRs(rs, 20); - ResultSet rs = preparedStatement.executeQuery(); + } catch (SQLException e) { + Logger.error(e); + } + return guildList; + } - if (!rs.next()) - valid = true; + public boolean IS_CREST_UNIQUE(final GuildTag gt) { - } catch (SQLException e) { - Logger.error(e); - } + boolean valid = false; + String queryString; - return valid; - } + // Ignore bg symbol if bg color is the same as fg color. - public boolean SET_GUILD_OWNED_CITY(int guildID, int cityID) { + if (gt.backgroundColor01 == gt.backgroundColor02) + queryString = "SELECT `name` FROM `obj_guild` WHERE `backgroundColor01`=? && `backgroundColor02`=? && `symbolColor`=? && `symbol`=?;"; + else + queryString = "SELECT `name` FROM `obj_guild` WHERE `backgroundColor01`=? && `backgroundColor02`=? && `symbolColor`=? && `backgroundDesign`=? && `symbol`=?;"; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_guild` SET `ownedCity`=? WHERE `UID`=?")) { - preparedStatement.setLong(1, cityID); - preparedStatement.setLong(2, guildID); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement(queryString)) { - return (preparedStatement.executeUpdate() > 0); + if (gt.backgroundColor01 == gt.backgroundColor02) { + preparedStatement.setInt(1, gt.backgroundColor01); + preparedStatement.setInt(2, gt.backgroundColor02); + preparedStatement.setInt(3, gt.symbolColor); + preparedStatement.setInt(4, gt.symbol); + } else { + preparedStatement.setInt(1, gt.backgroundColor01); + preparedStatement.setInt(2, gt.backgroundColor02); + preparedStatement.setInt(3, gt.symbolColor); + preparedStatement.setInt(4, gt.backgroundDesign); + preparedStatement.setInt(5, gt.symbol); + } - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + ResultSet rs = preparedStatement.executeQuery(); - public boolean SET_GUILD_LEADER(int objectUUID,int guildID) { + if (!rs.next()) + valid = true; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_guild` SET `leaderUID`=? WHERE `UID`=?")) { + } catch (SQLException e) { + Logger.error(e); + } - preparedStatement.setLong(1, objectUUID); - preparedStatement.setLong(2, guildID); + return valid; + } - return (preparedStatement.executeUpdate() > 0); + public boolean SET_GUILD_OWNED_CITY(int guildID, int cityID) { - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_guild` SET `ownedCity`=? WHERE `UID`=?")) { - public boolean IS_NAME_UNIQUE(final String name) { + preparedStatement.setLong(1, cityID); + preparedStatement.setLong(2, guildID); - boolean valid = false; + return (preparedStatement.executeUpdate() > 0); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `name` FROM `obj_guild` WHERE `name`=?;")) { + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - preparedStatement.setString(1, name); - ResultSet rs = preparedStatement.executeQuery(); + public boolean SET_GUILD_LEADER(int objectUUID, int guildID) { - if (!rs.next()) - valid = true; + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_guild` SET `leaderUID`=? WHERE `UID`=?")) { - } catch (SQLException e) { - Logger.error(e); - } + preparedStatement.setLong(1, objectUUID); + preparedStatement.setLong(2, guildID); - return valid; - } + return (preparedStatement.executeUpdate() > 0); - public Guild SAVE_TO_DATABASE(Guild g) { + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - Guild guild = null; - GuildTag guildTag = g.getGuildTag(); + public boolean IS_NAME_UNIQUE(final String name) { - if (guildTag == null) - return null; + boolean valid = false; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("CALL `guild_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `name` FROM `obj_guild` WHERE `name`=?;")) { - preparedStatement.setLong(1, MBServerStatics.worldUUID); - preparedStatement.setLong(2, g.getGuildLeaderUUID()); - preparedStatement.setString(3, g.getName()); - preparedStatement.setInt(4, guildTag.backgroundColor01); - preparedStatement.setInt(5, guildTag.backgroundColor02); - preparedStatement.setInt(6, guildTag.symbolColor); - preparedStatement.setInt(7, guildTag.backgroundDesign); - preparedStatement.setInt(8, guildTag.symbol); - preparedStatement.setInt(9, g.getCharter()); - preparedStatement.setString(10, g.getLeadershipType()); - preparedStatement.setString(11, g.getMotto()); + preparedStatement.setString(1, name); + ResultSet rs = preparedStatement.executeQuery(); - ResultSet rs = preparedStatement.executeQuery(); + if (!rs.next()) + valid = true; - int objectUUID = (int) rs.getLong("UID"); + } catch (SQLException e) { + Logger.error(e); + } - if (objectUUID > 0) - guild = GET_GUILD(objectUUID); + return valid; + } - } catch (SQLException e) { - Logger.error(e); - } - return guild; - } + public Guild SAVE_TO_DATABASE(Guild g) { - public boolean UPDATE_GUILD_RANK_OFFLINE(int target, int newRank, int guildId) { + Guild guild = null; + GuildTag guildTag = g.getGuildTag(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_title`=? WHERE `UID`=? && `guildUID`=?")) { + if (guildTag == null) + return null; - preparedStatement.setInt(1, newRank); - preparedStatement.setInt(2, target); - preparedStatement.setInt(3, guildId); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL `guild_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) { - return (preparedStatement.executeUpdate() > 0); + preparedStatement.setLong(1, MBServerStatics.worldUUID); + preparedStatement.setLong(2, g.getGuildLeaderUUID()); + preparedStatement.setString(3, g.getName()); + preparedStatement.setInt(4, guildTag.backgroundColor01); + preparedStatement.setInt(5, guildTag.backgroundColor02); + preparedStatement.setInt(6, guildTag.symbolColor); + preparedStatement.setInt(7, guildTag.backgroundDesign); + preparedStatement.setInt(8, guildTag.symbol); + preparedStatement.setInt(9, g.getCharter()); + preparedStatement.setString(10, g.getLeadershipType()); + preparedStatement.setString(11, g.getMotto()); - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + ResultSet rs = preparedStatement.executeQuery(); - public boolean UPDATE_PARENT(int guildUID, int parentUID) { + int objectUUID = (int) rs.getLong("UID"); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `object` SET `parent`=? WHERE `UID`=?")) { + if (objectUUID > 0) + guild = GET_GUILD(objectUUID); - preparedStatement.setInt(1, parentUID); - preparedStatement.setInt(2, guildUID); + } catch (SQLException e) { + Logger.error(e); + } + return guild; + } - return (preparedStatement.executeUpdate() > 0); + public boolean UPDATE_GUILD_RANK_OFFLINE(int target, int newRank, int guildId) { - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_title`=? WHERE `UID`=? && `guildUID`=?")) { - public int DELETE_GUILD(final Guild guild) { + preparedStatement.setInt(1, newRank); + preparedStatement.setInt(2, target); + preparedStatement.setInt(3, guildId); - int row_count = 0; + return (preparedStatement.executeUpdate() > 0); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `object` WHERE `UID` = ?")) { + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - preparedStatement.setLong(1, guild.getObjectUUID()); - row_count = preparedStatement.executeUpdate(); + public boolean UPDATE_PARENT(int guildUID, int parentUID) { - } catch (SQLException e) { - Logger.error(e); - } - return row_count; - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `object` SET `parent`=? WHERE `UID`=?")) { - public boolean UPDATE_MINETIME(int guildUID, int mineTime) { + preparedStatement.setInt(1, parentUID); + preparedStatement.setInt(2, guildUID); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_guild` SET `mineTime`=? WHERE `UID`=?")) { + return (preparedStatement.executeUpdate() > 0); - preparedStatement.setInt(1, mineTime); - preparedStatement.setInt(2, guildUID); + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - return (preparedStatement.executeUpdate() > 0); + public int DELETE_GUILD(final Guild guild) { - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + int row_count = 0; - public int UPDATE_GUILD_STATUS_OFFLINE(int target, boolean isInnerCouncil, boolean isRecruiter, boolean isTaxCollector, int guildId) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `object` WHERE `UID` = ?")) { - int updateMask = 0; - int row_count = 0; + preparedStatement.setLong(1, guild.getObjectUUID()); + row_count = preparedStatement.executeUpdate(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `guild_isInnerCouncil`, `guild_isTaxCollector`, `guild_isRecruiter` FROM `obj_character` WHERE `UID`=? && `guildUID`=?")) { + } catch (SQLException e) { + Logger.error(e); + } + return row_count; + } - preparedStatement.setLong(1, target); - preparedStatement.setLong(2, guildId); + public boolean UPDATE_MINETIME(int guildUID, int mineTime) { - ResultSet rs = preparedStatement.executeQuery(); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_guild` SET `mineTime`=? WHERE `UID`=?")) { - //If the first query had no results, neither will the second + preparedStatement.setInt(1, mineTime); + preparedStatement.setInt(2, guildUID); - //Determine what is different + return (preparedStatement.executeUpdate() > 0); - if (rs.first()) { - if (rs.getBoolean("guild_isInnerCouncil") != isInnerCouncil) - updateMask |= 4; - if (rs.getBoolean("guild_isRecruiter") != isRecruiter) - updateMask |= 2; - if (rs.getBoolean("guild_isTaxCollector") != isTaxCollector) - updateMask |= 1; - } - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_isInnerCouncil`=?, `guild_isTaxCollector`=?, `guild_isRecruiter`=?, `guild_isFullMember`=? WHERE `UID`=? && `guildUID`=?")) { - preparedStatement.setBoolean(1, isInnerCouncil); - preparedStatement.setBoolean(2, isRecruiter); - preparedStatement.setBoolean(3, isTaxCollector); - preparedStatement.setBoolean(4, ((updateMask > 0))); //If you are becoming an officer, or where an officer, your a full member... - preparedStatement.setLong(5, target); - preparedStatement.setLong(6, guildId); + // *** Refactor: Why are we saving tags/charter in update? + // It's not like this shit ever changes. - row_count = preparedStatement.executeUpdate(); + public int UPDATE_GUILD_STATUS_OFFLINE(int target, boolean isInnerCouncil, boolean isRecruiter, boolean isTaxCollector, int guildId) { - } catch (SQLException e) { - Logger.error(e); - } - return row_count; - } + int updateMask = 0; + int row_count = 0; + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `guild_isInnerCouncil`, `guild_isTaxCollector`, `guild_isRecruiter` FROM `obj_character` WHERE `UID`=? && `guildUID`=?")) { - // *** Refactor: Why are we saving tags/charter in update? - // It's not like this shit ever changes. + preparedStatement.setLong(1, target); + preparedStatement.setLong(2, guildId); - public boolean updateDatabase(final Guild g) { + ResultSet rs = preparedStatement.executeQuery(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_guild` SET `name`=?, `backgroundColor01`=?, `backgroundColor02`=?, `symbolColor`=?, `backgroundDesign`=?, `symbol`=?, `charter`=?, `motd`=?, `icMotd`=?, `nationMotd`=?, `leaderUID`=? WHERE `UID`=?")) { + //If the first query had no results, neither will the second - preparedStatement.setString(1, g.getName()); - preparedStatement.setInt(2, g.getGuildTag().backgroundColor01); - preparedStatement.setInt(3, g.getGuildTag().backgroundColor02); - preparedStatement.setInt(4, g.getGuildTag().symbolColor); - preparedStatement.setInt(5, g.getGuildTag().backgroundDesign); - preparedStatement.setInt(6, g.getGuildTag().symbol); - preparedStatement.setInt(7, g.getCharter()); - preparedStatement.setString(8, g.getMOTD()); - preparedStatement.setString(9, g.getICMOTD()); - preparedStatement.setString(10, ""); - preparedStatement.setInt(11, g.getGuildLeaderUUID()); - preparedStatement.setLong(12, (long) g.getObjectUUID()); + //Determine what is different - return (preparedStatement.executeUpdate() > 0); + if (rs.first()) { + if (rs.getBoolean("guild_isInnerCouncil") != isInnerCouncil) + updateMask |= 4; + if (rs.getBoolean("guild_isRecruiter") != isRecruiter) + updateMask |= 2; + if (rs.getBoolean("guild_isTaxCollector") != isTaxCollector) + updateMask |= 1; + } + } catch (SQLException e) { + Logger.error(e); + } - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_isInnerCouncil`=?, `guild_isTaxCollector`=?, `guild_isRecruiter`=?, `guild_isFullMember`=? WHERE `UID`=? && `guildUID`=?")) { - public boolean ADD_TO_ALLIANCE_LIST(final long sourceGuildID, final long targetGuildID, boolean isRecommended, boolean isAlly, String recommender) { + preparedStatement.setBoolean(1, isInnerCouncil); + preparedStatement.setBoolean(2, isRecruiter); + preparedStatement.setBoolean(3, isTaxCollector); + preparedStatement.setBoolean(4, ((updateMask > 0))); //If you are becoming an officer, or where an officer, your a full member... + preparedStatement.setLong(5, target); + preparedStatement.setLong(6, guildId); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_guild_allianceenemylist` (`GuildID`, `OtherGuildID`,`isRecommended`, `isAlliance`, `recommender`) VALUES (?,?,?,?,?)")) { + row_count = preparedStatement.executeUpdate(); - preparedStatement.setLong(1, sourceGuildID); - preparedStatement.setLong(2, targetGuildID); - preparedStatement.setBoolean(3, isRecommended); - preparedStatement.setBoolean(4, isAlly); - preparedStatement.setString(5, recommender); + } catch (SQLException e) { + Logger.error(e); + } + return row_count; + } - return (preparedStatement.executeUpdate() > 0); + public boolean updateDatabase(final Guild g) { - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_guild` SET `name`=?, `backgroundColor01`=?, `backgroundColor02`=?, `symbolColor`=?, `backgroundDesign`=?, `symbol`=?, `charter`=?, `motd`=?, `icMotd`=?, `nationMotd`=?, `leaderUID`=? WHERE `UID`=?")) { - public boolean REMOVE_FROM_ALLIANCE_LIST(final long sourceGuildID, long targetGuildID) { + preparedStatement.setString(1, g.getName()); + preparedStatement.setInt(2, g.getGuildTag().backgroundColor01); + preparedStatement.setInt(3, g.getGuildTag().backgroundColor02); + preparedStatement.setInt(4, g.getGuildTag().symbolColor); + preparedStatement.setInt(5, g.getGuildTag().backgroundDesign); + preparedStatement.setInt(6, g.getGuildTag().symbol); + preparedStatement.setInt(7, g.getCharter()); + preparedStatement.setString(8, g.getMOTD()); + preparedStatement.setString(9, g.getICMOTD()); + preparedStatement.setString(10, ""); + preparedStatement.setInt(11, g.getGuildLeaderUUID()); + preparedStatement.setLong(12, g.getObjectUUID()); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_guild_allianceenemylist` WHERE `GuildID`=? AND `OtherGuildID`=?")) { + return (preparedStatement.executeUpdate() > 0); - preparedStatement.setLong(1, sourceGuildID); - preparedStatement.setLong(2, targetGuildID); + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - return (preparedStatement.executeUpdate() > 0); + public boolean ADD_TO_ALLIANCE_LIST(final long sourceGuildID, final long targetGuildID, boolean isRecommended, boolean isAlly, String recommender) { - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_guild_allianceenemylist` (`GuildID`, `OtherGuildID`,`isRecommended`, `isAlliance`, `recommender`) VALUES (?,?,?,?,?)")) { - public boolean UPDATE_RECOMMENDED(final long sourceGuildID, long targetGuildID) { + preparedStatement.setLong(1, sourceGuildID); + preparedStatement.setLong(2, targetGuildID); + preparedStatement.setBoolean(3, isRecommended); + preparedStatement.setBoolean(4, isAlly); + preparedStatement.setString(5, recommender); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_guild_allianceenemylist` SET `isRecommended` = ? WHERE `GuildID`=? AND `OtherGuildID`=?")) { + return (preparedStatement.executeUpdate() > 0); - preparedStatement.setLong(1, sourceGuildID); - preparedStatement.setLong(2, targetGuildID); + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - return (preparedStatement.executeUpdate() > 0); + public boolean REMOVE_FROM_ALLIANCE_LIST(final long sourceGuildID, long targetGuildID) { - } catch (SQLException e) { - Logger.error(e); - return false; - } - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_guild_allianceenemylist` WHERE `GuildID`=? AND `OtherGuildID`=?")) { - public boolean UPDATE_ALLIANCE(final long sourceGuildID, long targetGuildID, boolean isAlly) { + preparedStatement.setLong(1, sourceGuildID); + preparedStatement.setLong(2, targetGuildID); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_guild_allianceenemylist` SET `isAlliance` = ? WHERE `GuildID`=? AND `OtherGuildID`=?")) { + return (preparedStatement.executeUpdate() > 0); - preparedStatement.setLong(1, sourceGuildID); - preparedStatement.setLong(2, targetGuildID); + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - return (preparedStatement.executeUpdate() > 0); + public boolean UPDATE_RECOMMENDED(final long sourceGuildID, long targetGuildID) { - } catch (SQLException e) { - Logger.error(e); - return false; - } - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_guild_allianceenemylist` SET `isRecommended` = ? WHERE `GuildID`=? AND `OtherGuildID`=?")) { - public boolean UPDATE_ALLIANCE_AND_RECOMMENDED(final long sourceGuildID, long targetGuildID, boolean isAlly) { + preparedStatement.setLong(1, sourceGuildID); + preparedStatement.setLong(2, targetGuildID); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_guild_allianceenemylist` SET `isRecommended` = ?, `isAlliance` = ? WHERE `GuildID`=? AND `OtherGuildID`=?")) { + return (preparedStatement.executeUpdate() > 0); - preparedStatement.setByte(1, (byte) 0); - preparedStatement.setBoolean(2, isAlly); - preparedStatement.setLong(3, sourceGuildID); - preparedStatement.setLong(4, targetGuildID); + } catch (SQLException e) { + Logger.error(e); + return false; + } + } - return (preparedStatement.executeUpdate() > 0); + public boolean UPDATE_ALLIANCE(final long sourceGuildID, long targetGuildID, boolean isAlly) { - } catch (SQLException e) { - Logger.error(e); - return false; - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_guild_allianceenemylist` SET `isAlliance` = ? WHERE `GuildID`=? AND `OtherGuildID`=?")) { - } + preparedStatement.setLong(1, sourceGuildID); + preparedStatement.setLong(2, targetGuildID); - public void LOAD_ALL_ALLIANCES_FOR_GUILD(Guild guild) { + return (preparedStatement.executeUpdate() > 0); - if (guild == null) - return; + } catch (SQLException e) { + Logger.error(e); + return false; + } + } - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_guild_allianceenemylist` WHERE `GuildID` = ?")) { + public boolean UPDATE_ALLIANCE_AND_RECOMMENDED(final long sourceGuildID, long targetGuildID, boolean isAlly) { - preparedStatement.setInt(1, guild.getObjectUUID()); - ResultSet rs = preparedStatement.executeQuery(); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_guild_allianceenemylist` SET `isRecommended` = ?, `isAlliance` = ? WHERE `GuildID`=? AND `OtherGuildID`=?")) { - while (rs.next()) { - GuildAlliances guildAlliance = new GuildAlliances(rs); - guild.guildAlliances.put(guildAlliance.getAllianceGuild(), guildAlliance); - } + preparedStatement.setByte(1, (byte) 0); + preparedStatement.setBoolean(2, isAlly); + preparedStatement.setLong(3, sourceGuildID); + preparedStatement.setLong(4, targetGuildID); - } catch (SQLException e) { - Logger.error(e); - } - } + return (preparedStatement.executeUpdate() > 0); - public static void LOAD_GUILD_HISTORY_FOR_PLAYER(PlayerCharacter playerCharacter) { + } catch (SQLException e) { + Logger.error(e); + return false; + } - if (playerCharacter == null) - return; + } - ArrayList guildList = new ArrayList<>(); + public void LOAD_ALL_ALLIANCES_FOR_GUILD(Guild guild) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_guild_allianceenemylist` WHERE `GuildID` = ?")) { + if (guild == null) + return; - preparedStatement.setInt(1, playerCharacter.getObjectUUID()); - ResultSet rs = preparedStatement.executeQuery(); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_guild_allianceenemylist` WHERE `GuildID` = ?")) { - while (rs.next()) { - GuildHistory guildEntry = new GuildHistory(rs); - guildList.add(guildEntry); - } + preparedStatement.setInt(1, guild.getObjectUUID()); + ResultSet rs = preparedStatement.executeQuery(); - } catch (SQLException e) { - Logger.error(e); - } + while (rs.next()) { + GuildAlliances guildAlliance = new GuildAlliances(rs); + guild.guildAlliances.put(guildAlliance.getAllianceGuild(), guildAlliance); + } - playerCharacter.setGuildHistory(guildList); - } - - //TODO uncomment this when finished with guild history warehouse integration + } catch (SQLException e) { + Logger.error(e); + } + } + + //TODO uncomment this when finished with guild history warehouse integration // public HashMap GET_WAREHOUSE_GUILD_HISTORY(){ // // HashMap tempMap = new HashMap<>(); diff --git a/src/engine/db/handlers/dbHandlerBase.java b/src/engine/db/handlers/dbHandlerBase.java index 53eea3c2..8de040d2 100644 --- a/src/engine/db/handlers/dbHandlerBase.java +++ b/src/engine/db/handlers/dbHandlerBase.java @@ -25,455 +25,456 @@ import java.util.HashSet; public abstract class dbHandlerBase { - /* - * CallableStatements handled below this line! - */ - protected Class localClass = null; - protected GameObjectType localObjectType; - protected final ThreadLocal callableStatement = new ThreadLocal<>(); - protected final ThreadLocal connection = new ThreadLocal<>(); - - protected final void prepareCallable(final String sql) { - try { - this.connection.set(DbManager.getConnection()); - this.callableStatement.set(this.connection.get().prepareCall(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)); - } catch (SQLException e) { - Logger.error("DbManager.getConn", e); - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - - protected final void setInt(int parameterIndex, int value) { - try { - this.callableStatement.get().setInt(parameterIndex, value); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - - protected final void setLong(int parameterIndex, long value) { - try { - this.callableStatement.get().setLong(parameterIndex, value); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - - protected final void setFloat(int parameterIndex, float value) { - try { - this.callableStatement.get().setFloat(parameterIndex, value); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - - protected final void setShort(int parameterIndex, short value) { - try { - this.callableStatement.get().setShort(parameterIndex, value); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - - protected final void setString(int parameterIndex, String value) { - try { - this.callableStatement.get().setString(parameterIndex, value); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - - protected final void setByte(int parameterIndex, byte value) { - try { - this.callableStatement.get().setByte(parameterIndex, value); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - - protected final void setBoolean(int parameterIndex, boolean value) { - try { - this.callableStatement.get().setBoolean(parameterIndex, value); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - - protected final void setNULL(int parameterIndex, int type) { - try { - this.callableStatement.get().setNull(parameterIndex, type); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - - protected final void setLocalDateTime(int parameterIndex, LocalDateTime localDateTime) { - - try { - this.callableStatement.get().setTimestamp(parameterIndex, Timestamp.valueOf(localDateTime)); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - - protected final void setTimeStamp(int parameterIndex, long time) { - try { - this.callableStatement.get().setTimestamp(parameterIndex, new java.sql.Timestamp(time)); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - - protected final boolean execute() { - try { - return this.callableStatement.get().execute(); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - logSQLCommand(); - } - return false; - } - - protected final ResultSet executeQuery() { - try { - return this.callableStatement.get().executeQuery(); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - logSQLCommand(); - } - return null; - } - - protected final int executeUpdate() { - return executeUpdate(true); - } - - protected final int executeUpdate(boolean close) { - try { - return this.callableStatement.get().executeUpdate(); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - logSQLCommand(); - } finally { - if (close) - closeCallable(); - } - return 0; - } - - protected final void logSQLCommand() { - try { - Logger.error("Failed SQL Command: " + this.callableStatement.get().toString()); - } catch (Exception e) { - - } - } - - // Common return values from the database when calling stored procedures, abstracted to this layer - protected final String getResult(){ - try { - ResultSet rs = this.executeQuery(); - if (rs.next() && !isError(rs)) - return rs.getString("result"); - } catch (SQLException e) { - Logger.error(e); - logSQLCommand(); - } finally { - closeCallable(); - } - return null; - } - - // Used for Stored procedures that return true when they succeed. - protected final boolean worked() { - try { - ResultSet rs = this.executeQuery(); - if (rs.next() && !isError(rs)) - return rs.getBoolean("result"); - } catch (SQLException e) { - Logger.error(e); - logSQLCommand(); - } finally { - closeCallable(); - } - return false; - } - - // Common return values from the database when calling stored procedures, abstracted to this layer - protected final long getUUID(){ - try { - ResultSet rs = this.executeQuery(); - if (rs.next() && !isError(rs)) - return rs.getLong("UID"); - } catch (SQLException e) { - Logger.error(e); - logSQLCommand(); - } finally { - closeCallable(); - } - return -1; - } - - protected final String getString(String field) { - try { - ResultSet rs = this.executeQuery(); - if (rs.next()) - return rs.getString(field); - } catch (SQLException e) { - Logger.error(e); - logSQLCommand(); - } finally { - closeCallable(); - } - return ""; - } - - protected final long getLong(String field) { - try { - ResultSet rs = this.executeQuery(); - if (rs.next()) - return rs.getLong(field); - } catch (SQLException e) { - Logger.error(e); - logSQLCommand(); - } finally { - closeCallable(); - } - return 0L; - } - - protected final int getInt(String field) { - try { - ResultSet rs = this.executeQuery(); - if (rs.next()) - return rs.getInt(field); - } catch (SQLException e) { - Logger.error(e); - logSQLCommand(); - } finally { - closeCallable(); - } - return 0; - } - - protected final int insertGetUUID() { - int key = 0; - try { - this.callableStatement.get().executeUpdate(); - ResultSet rs = this.callableStatement.get().getGeneratedKeys(); - if (rs.next()) - key = rs.getInt(1); - } catch (SQLException e) { - Logger.error(e); - logSQLCommand(); - } finally { - closeCallable(); - } - return key; - } - - protected final boolean isError(ResultSet rs) throws SQLException { - ResultSetMetaData rsmd = rs.getMetaData(); - if (rsmd.getColumnCount() > 0 && !rsmd.getColumnName(1).equals("errorno")) - return false; - printError(rs); - return true; - } - - protected final void printError(ResultSet rs) { - try { - int errorNum = rs.getInt("errorno"); - String errorMsg = rs.getString("errormsg"); - Logger.error("SQLError: errorNum: " + errorNum + ", errorMsg: " + errorMsg); - logSQLCommand(); - } catch (SQLException e) { - } - } - - protected AbstractGameObject getObjectFromRs(ResultSet rs) { - - AbstractGameObject abstractGameObject = null; - - try { - if (rs.next()) { - abstractGameObject = localClass.getConstructor(ResultSet.class).newInstance(rs); - - DbManager.addToCache(abstractGameObject); - } - } catch (Exception e) { - Logger.error(e); - } - - return abstractGameObject; - } - - protected ArrayList getObjectsFromRs(ResultSet rs, int listSize) { - - ArrayList objectList = new ArrayList<>(listSize); - - try { - while (rs.next()) { - - int id = rs.getInt(1); - - if (DbManager.inCache(localObjectType, id)) { - objectList.add((T) DbManager.getFromCache(localObjectType, id)); - } else { - AbstractGameObject toAdd = localClass.getConstructor(ResultSet.class).newInstance(rs); - DbManager.addToCache(toAdd); - objectList.add((T) toAdd); - - if (toAdd != null && toAdd instanceof AbstractWorldObject) - ((AbstractWorldObject) toAdd).runAfterLoad(); - } - } - } catch (Exception e) { - Logger.error(e); - } - return objectList; - - } - - protected AbstractGameObject getObjectSingle(int id) { - return getObjectSingle(id, false, true); - } - - protected AbstractGameObject getObjectSingle(int id, boolean forceFromDB, boolean storeInCache) { - - if (callableStatement.get() == null) { - return null; - } - - if (!forceFromDB) { - if (DbManager.inCache(localObjectType, id)) { - closeCallable(); - return DbManager.getFromCache(localObjectType, id); - } - } - - AbstractGameObject out = null; + protected final ThreadLocal callableStatement = new ThreadLocal<>(); + protected final ThreadLocal connection = new ThreadLocal<>(); + /* + * CallableStatements handled below this line! + */ + protected Class localClass = null; + protected GameObjectType localObjectType; + + protected final void prepareCallable(final String sql) { + try { + this.connection.set(DbManager.getConnection()); + this.callableStatement.set(this.connection.get().prepareCall(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)); + } catch (SQLException e) { + Logger.error("DbManager.getConn", e); + Logger.error("SQL Error number: " + e.getErrorCode()); + } + } + + protected final void setInt(int parameterIndex, int value) { + try { + this.callableStatement.get().setInt(parameterIndex, value); + } catch (SQLException e) { + Logger.error("SQL Error number: " + e.getErrorCode()); + } + } + + protected final void setLong(int parameterIndex, long value) { + try { + this.callableStatement.get().setLong(parameterIndex, value); + } catch (SQLException e) { + Logger.error("SQL Error number: " + e.getErrorCode()); + } + } + + protected final void setFloat(int parameterIndex, float value) { + try { + this.callableStatement.get().setFloat(parameterIndex, value); + } catch (SQLException e) { + Logger.error("SQL Error number: " + e.getErrorCode()); + } + } + + protected final void setShort(int parameterIndex, short value) { + try { + this.callableStatement.get().setShort(parameterIndex, value); + } catch (SQLException e) { + Logger.error("SQL Error number: " + e.getErrorCode()); + } + } + + protected final void setString(int parameterIndex, String value) { + try { + this.callableStatement.get().setString(parameterIndex, value); + } catch (SQLException e) { + Logger.error("SQL Error number: " + e.getErrorCode()); + } + } + + protected final void setByte(int parameterIndex, byte value) { + try { + this.callableStatement.get().setByte(parameterIndex, value); + } catch (SQLException e) { + Logger.error("SQL Error number: " + e.getErrorCode()); + } + } + + protected final void setBoolean(int parameterIndex, boolean value) { + try { + this.callableStatement.get().setBoolean(parameterIndex, value); + } catch (SQLException e) { + Logger.error("SQL Error number: " + e.getErrorCode()); + } + } + + protected final void setNULL(int parameterIndex, int type) { + try { + this.callableStatement.get().setNull(parameterIndex, type); + } catch (SQLException e) { + Logger.error("SQL Error number: " + e.getErrorCode()); + } + } + + protected final void setLocalDateTime(int parameterIndex, LocalDateTime localDateTime) { + + try { + this.callableStatement.get().setTimestamp(parameterIndex, Timestamp.valueOf(localDateTime)); + } catch (SQLException e) { + Logger.error("SQL Error number: " + e.getErrorCode()); + } + } + + protected final void setTimeStamp(int parameterIndex, long time) { + try { + this.callableStatement.get().setTimestamp(parameterIndex, new java.sql.Timestamp(time)); + } catch (SQLException e) { + Logger.error("SQL Error number: " + e.getErrorCode()); + } + } + + protected final boolean execute() { + try { + return this.callableStatement.get().execute(); + } catch (SQLException e) { + Logger.error("SQL Error number: " + e.getErrorCode()); + logSQLCommand(); + } + return false; + } + + protected final ResultSet executeQuery() { + try { + return this.callableStatement.get().executeQuery(); + } catch (SQLException e) { + Logger.error("SQL Error number: " + e.getErrorCode()); + logSQLCommand(); + } + return null; + } + + protected final int executeUpdate() { + return executeUpdate(true); + } + + protected final int executeUpdate(boolean close) { + try { + return this.callableStatement.get().executeUpdate(); + } catch (SQLException e) { + Logger.error("SQL Error number: " + e.getErrorCode()); + logSQLCommand(); + } finally { + if (close) + closeCallable(); + } + return 0; + } + + protected final void logSQLCommand() { + try { + Logger.error("Failed SQL Command: " + this.callableStatement.get().toString()); + } catch (Exception e) { + + } + } + + // Common return values from the database when calling stored procedures, abstracted to this layer + protected final String getResult() { + try { + ResultSet rs = this.executeQuery(); + if (rs.next() && !isError(rs)) + return rs.getString("result"); + } catch (SQLException e) { + Logger.error(e); + logSQLCommand(); + } finally { + closeCallable(); + } + return null; + } + + // Used for Stored procedures that return true when they succeed. + protected final boolean worked() { + try { + ResultSet rs = this.executeQuery(); + if (rs.next() && !isError(rs)) + return rs.getBoolean("result"); + } catch (SQLException e) { + Logger.error(e); + logSQLCommand(); + } finally { + closeCallable(); + } + return false; + } + + // Common return values from the database when calling stored procedures, abstracted to this layer + protected final long getUUID() { + try { + ResultSet rs = this.executeQuery(); + if (rs.next() && !isError(rs)) + return rs.getLong("UID"); + } catch (SQLException e) { + Logger.error(e); + logSQLCommand(); + } finally { + closeCallable(); + } + return -1; + } + + protected final String getString(String field) { + try { + ResultSet rs = this.executeQuery(); + if (rs.next()) + return rs.getString(field); + } catch (SQLException e) { + Logger.error(e); + logSQLCommand(); + } finally { + closeCallable(); + } + return ""; + } + + protected final long getLong(String field) { + try { + ResultSet rs = this.executeQuery(); + if (rs.next()) + return rs.getLong(field); + } catch (SQLException e) { + Logger.error(e); + logSQLCommand(); + } finally { + closeCallable(); + } + return 0L; + } + + protected final int getInt(String field) { + try { + ResultSet rs = this.executeQuery(); + if (rs.next()) + return rs.getInt(field); + } catch (SQLException e) { + Logger.error(e); + logSQLCommand(); + } finally { + closeCallable(); + } + return 0; + } + + protected final int insertGetUUID() { + int key = 0; + try { + this.callableStatement.get().executeUpdate(); + ResultSet rs = this.callableStatement.get().getGeneratedKeys(); + if (rs.next()) + key = rs.getInt(1); + } catch (SQLException e) { + Logger.error(e); + logSQLCommand(); + } finally { + closeCallable(); + } + return key; + } + + protected final boolean isError(ResultSet rs) throws SQLException { + ResultSetMetaData rsmd = rs.getMetaData(); + if (rsmd.getColumnCount() > 0 && !rsmd.getColumnName(1).equals("errorno")) + return false; + printError(rs); + return true; + } + + protected final void printError(ResultSet rs) { + try { + int errorNum = rs.getInt("errorno"); + String errorMsg = rs.getString("errormsg"); + Logger.error("SQLError: errorNum: " + errorNum + ", errorMsg: " + errorMsg); + logSQLCommand(); + } catch (SQLException e) { + } + } + + protected AbstractGameObject getObjectFromRs(ResultSet rs) { + + AbstractGameObject abstractGameObject = null; + + try { + if (rs.next()) { + abstractGameObject = localClass.getConstructor(ResultSet.class).newInstance(rs); + + DbManager.addToCache(abstractGameObject); + } + } catch (Exception e) { + Logger.error(e); + } + + return abstractGameObject; + } + + protected ArrayList getObjectsFromRs(ResultSet rs, int listSize) { + + ArrayList objectList = new ArrayList<>(listSize); + + try { + while (rs.next()) { + + int id = rs.getInt(1); + + if (DbManager.inCache(localObjectType, id)) { + objectList.add((T) DbManager.getFromCache(localObjectType, id)); + } else { + AbstractGameObject toAdd = localClass.getConstructor(ResultSet.class).newInstance(rs); + DbManager.addToCache(toAdd); + objectList.add((T) toAdd); + + if (toAdd != null && toAdd instanceof AbstractWorldObject) + ((AbstractWorldObject) toAdd).runAfterLoad(); + } + } + } catch (Exception e) { + Logger.error(e); + } + return objectList; + + } + + protected AbstractGameObject getObjectSingle(int id) { + return getObjectSingle(id, false, true); + } + + protected AbstractGameObject getObjectSingle(int id, boolean forceFromDB, boolean storeInCache) { + + if (callableStatement.get() == null) { + return null; + } + + if (!forceFromDB) { + if (DbManager.inCache(localObjectType, id)) { + closeCallable(); + return DbManager.getFromCache(localObjectType, id); + } + } + + AbstractGameObject out = null; + + try { + if (MBServerStatics.DB_ENABLE_QUERY_OUTPUT) + Logger.info("[GetObjectList] Executing query:" + callableStatement.get().toString()); - try { - if (MBServerStatics.DB_ENABLE_QUERY_OUTPUT) - Logger.info("[GetObjectList] Executing query:" + callableStatement.get().toString()); + ResultSet rs = callableStatement.get().executeQuery(); - ResultSet rs = callableStatement.get().executeQuery(); + if (rs.next()) { + out = localClass.getConstructor(ResultSet.class).newInstance(rs); - if (rs.next()) { - out = localClass.getConstructor(ResultSet.class).newInstance(rs); + if (storeInCache) + DbManager.addToCache(out); + } - if (storeInCache) - DbManager.addToCache(out); - } + rs.close(); - rs.close(); + } catch (Exception e) { + Logger.error("AbstractGameObject", e); + out = null; + } finally { + closeCallable(); + } - } catch (Exception e) { - Logger.error("AbstractGameObject", e); - out = null; - } finally { - closeCallable(); - } + // Only call runAfterLoad() for objects instanced on the world server - // Only call runAfterLoad() for objects instanced on the world server + if ((out != null && out instanceof AbstractWorldObject) && + (ConfigManager.serverType.equals(Enum.ServerType.WORLDSERVER) || + (out.getObjectType() == GameObjectType.Guild))) + ((AbstractWorldObject) out).runAfterLoad(); - if ((out != null && out instanceof AbstractWorldObject) && - (ConfigManager.serverType.equals(Enum.ServerType.WORLDSERVER) || - (out.getObjectType() == GameObjectType.Guild))) - ((AbstractWorldObject)out).runAfterLoad(); + return out; + } - return out; - } + protected void closeCallable() { + try { + if (this.callableStatement.get() != null) + this.callableStatement.get().close(); - protected void closeCallable() { - try { - if (this.callableStatement.get() != null) - this.callableStatement.get().close(); + this.connection.get().close(); - this.connection.get().close(); + } catch (SQLException e) { + } + } - } catch (SQLException e) {} - } + protected ArrayList getObjectList() { + return getObjectList(20, false); + } - protected ArrayList getObjectList() { - return getObjectList(20, false); - } + protected ArrayList getLargeObjectList() { + return getObjectList(2000, false); + } - protected ArrayList getLargeObjectList() { - return getObjectList(2000, false); - } + @SuppressWarnings("unchecked") + protected ArrayList getObjectList(int listSize, boolean forceFromDB) { - @SuppressWarnings("unchecked") - protected ArrayList getObjectList(int listSize, boolean forceFromDB) { + String query = "No Callable Statement accessable."; - String query = "No Callable Statement accessable."; + ArrayList out = new ArrayList<>(listSize); - ArrayList out = new ArrayList<>(listSize); + if (this.callableStatement.get() == null) + return out; - if (this.callableStatement.get() == null) - return out; + try { - try { + CallableStatement css = this.callableStatement.get(); - CallableStatement css = this.callableStatement.get(); + if (css != null) + query = this.callableStatement.get().toString(); - if (css != null) - query = this.callableStatement.get().toString(); + if (MBServerStatics.DB_ENABLE_QUERY_OUTPUT) + Logger.info("[GetObjectList] Executing query:" + query); - if (MBServerStatics.DB_ENABLE_QUERY_OUTPUT) - Logger.info( "[GetObjectList] Executing query:" + query); + ResultSet rs = this.callableStatement.get().executeQuery(); - ResultSet rs = this.callableStatement.get().executeQuery(); + while (rs.next()) { - while (rs.next()) { + int id = rs.getInt(1); - int id = rs.getInt(1); + if (!forceFromDB && DbManager.inCache(localObjectType, id)) { + out.add((T) DbManager.getFromCache(localObjectType, id)); + } else { + AbstractGameObject toAdd = localClass.getConstructor(ResultSet.class).newInstance(rs); + DbManager.addToCache(toAdd); + out.add((T) toAdd); - if (!forceFromDB && DbManager.inCache(localObjectType, id)) { - out.add((T) DbManager.getFromCache(localObjectType, id)); - } else { - AbstractGameObject toAdd = localClass.getConstructor(ResultSet.class).newInstance(rs); - DbManager.addToCache(toAdd); - out.add((T) toAdd); + if (toAdd != null && toAdd instanceof AbstractWorldObject) + ((AbstractWorldObject) toAdd).runAfterLoad(); - if (toAdd != null && toAdd instanceof AbstractWorldObject) - ((AbstractWorldObject)toAdd).runAfterLoad(); + } + } + rs.close(); + } catch (Exception e) { + Logger.error(localClass.getCanonicalName(), "List Failure: " + query, e); + e.printStackTrace(); + return new ArrayList<>(); // Do we want a null return on error? + } finally { + closeCallable(); + } - } - } - rs.close(); - } catch (Exception e) { - Logger.error(localClass.getCanonicalName(), "List Failure: " + query, e); - e.printStackTrace(); - return new ArrayList<>(); // Do we want a null return on error? - } finally { - closeCallable(); - } + return out; + } - return out; - } + /* Prepared Statements handled below this line */ - /* Prepared Statements handled below this line */ + protected HashSet getIntegerList(final int columnNumber) { - protected HashSet getIntegerList(final int columnNumber) { + if (MBServerStatics.DB_ENABLE_QUERY_OUTPUT) + Logger.info("[GetIntegerList] Executing query:" + this.callableStatement); - if (MBServerStatics.DB_ENABLE_QUERY_OUTPUT) - Logger.info("[GetIntegerList] Executing query:" + this.callableStatement.toString()); + HashSet out = new HashSet<>(); - HashSet out = new HashSet<>(); + try { + ResultSet rs = executeQuery(); - try { - ResultSet rs = executeQuery(); - - while (rs.next()) { - out.add(rs.getInt(columnNumber)); - } - rs.close(); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } finally { - closeCallable(); - } - return out; - } + while (rs.next()) { + out.add(rs.getInt(columnNumber)); + } + rs.close(); + } catch (SQLException e) { + Logger.error("SQL Error number: " + e.getErrorCode()); + } finally { + closeCallable(); + } + return out; + } } diff --git a/src/engine/db/handlers/dbItemBaseHandler.java b/src/engine/db/handlers/dbItemBaseHandler.java index ac824efc..61ebfdc5 100644 --- a/src/engine/db/handlers/dbItemBaseHandler.java +++ b/src/engine/db/handlers/dbItemBaseHandler.java @@ -23,7 +23,7 @@ import java.util.HashMap; public class dbItemBaseHandler extends dbHandlerBase { - public dbItemBaseHandler() { + public dbItemBaseHandler() { } diff --git a/src/engine/db/handlers/dbItemHandler.java b/src/engine/db/handlers/dbItemHandler.java index 49f7f828..5b21c257 100644 --- a/src/engine/db/handlers/dbItemHandler.java +++ b/src/engine/db/handlers/dbItemHandler.java @@ -27,491 +27,491 @@ import java.util.HashSet; public class dbItemHandler extends dbHandlerBase { - public dbItemHandler() { - this.localClass = Item.class; - this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); - } - - public Item ADD_ITEM(Item toAdd) { - - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("CALL `item_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?,?);")) { - - preparedStatement.setInt(1, toAdd.getOwnerID()); - preparedStatement.setInt(2, toAdd.getItemBaseID()); - preparedStatement.setInt(3, toAdd.getChargesRemaining()); - preparedStatement.setInt(4, toAdd.getDurabilityCurrent()); - preparedStatement.setInt(5, toAdd.getDurabilityMax()); - - if (toAdd.getNumOfItems() < 1) - preparedStatement.setInt(6, 1); - else - preparedStatement.setInt(6, toAdd.getNumOfItems()); - - switch (toAdd.containerType) { - case INVENTORY: - preparedStatement.setString(7, "inventory"); - break; - case EQUIPPED: - preparedStatement.setString(7, "equip"); - break; - case BANK: - preparedStatement.setString(7, "bank"); - break; - case VAULT: - preparedStatement.setString(7, "vault"); - break; - case FORGE: - preparedStatement.setString(7, "forge"); - break; - default: - preparedStatement.setString(7, "none"); //Shouldn't be here - break; - } + public dbItemHandler() { + this.localClass = Item.class; + this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); + } + + private static String formatTradeString(HashSet list) { + int size = list.size(); + + String ret = ""; + + if (size == 0) + return ret; + + boolean start = true; - preparedStatement.setByte(8, toAdd.getEquipSlot()); - preparedStatement.setInt(9, toAdd.getFlags()); - preparedStatement.setString(10, toAdd.getCustomName()); + for (int i : list) { + if (start) { + ret += i; + start = false; + } else + ret += "," + i; + } + return ret; + } + + public Item ADD_ITEM(Item toAdd) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL `item_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?,?);")) { + + preparedStatement.setInt(1, toAdd.getOwnerID()); + preparedStatement.setInt(2, toAdd.getItemBaseID()); + preparedStatement.setInt(3, toAdd.getChargesRemaining()); + preparedStatement.setInt(4, toAdd.getDurabilityCurrent()); + preparedStatement.setInt(5, toAdd.getDurabilityMax()); + + if (toAdd.getNumOfItems() < 1) + preparedStatement.setInt(6, 1); + else + preparedStatement.setInt(6, toAdd.getNumOfItems()); - ResultSet rs = preparedStatement.executeQuery(); + switch (toAdd.containerType) { + case INVENTORY: + preparedStatement.setString(7, "inventory"); + break; + case EQUIPPED: + preparedStatement.setString(7, "equip"); + break; + case BANK: + preparedStatement.setString(7, "bank"); + break; + case VAULT: + preparedStatement.setString(7, "vault"); + break; + case FORGE: + preparedStatement.setString(7, "forge"); + break; + default: + preparedStatement.setString(7, "none"); //Shouldn't be here + break; + } - int objectUUID = (int) rs.getLong("UID"); + preparedStatement.setByte(8, toAdd.getEquipSlot()); + preparedStatement.setInt(9, toAdd.getFlags()); + preparedStatement.setString(10, toAdd.getCustomName()); - if (objectUUID > 0) - return GET_ITEM(objectUUID); + ResultSet rs = preparedStatement.executeQuery(); - } catch (SQLException e) { - Logger.error(e); - } + int objectUUID = (int) rs.getLong("UID"); - return null; - } + if (objectUUID > 0) + return GET_ITEM(objectUUID); - public String GET_OWNER(int ownerID) { + } catch (SQLException e) { + Logger.error(e); + } - String ownerType; + return null; + } - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `type` FROM `object` WHERE `UID`=?")) { + public String GET_OWNER(int ownerID) { - preparedStatement.setInt(1, ownerID); - ResultSet rs = preparedStatement.executeQuery(); + String ownerType; - ownerType = rs.getString("type"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `type` FROM `object` WHERE `UID`=?")) { - } catch (SQLException e) { - Logger.error(e); - return ""; - } + preparedStatement.setInt(1, ownerID); + ResultSet rs = preparedStatement.executeQuery(); - return ownerType; - } + ownerType = rs.getString("type"); - public boolean DO_TRADE(HashSet from1, HashSet from2, - CharacterItemManager man1, CharacterItemManager man2, - Item inventoryGold1, Item inventoryGold2, int goldFrom1, int goldFrom2) { + } catch (SQLException e) { + Logger.error(e); + return ""; + } - AbstractCharacter ac1 = man1.getOwner(); - AbstractCharacter ac2 = man2.getOwner(); - boolean worked = false; + return ownerType; + } - if (ac1 == null || ac2 == null || inventoryGold1 == null || inventoryGold2 == null) - return false; + public boolean DO_TRADE(HashSet from1, HashSet from2, + CharacterItemManager man1, CharacterItemManager man2, + Item inventoryGold1, Item inventoryGold2, int goldFrom1, int goldFrom2) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("CALL `item_TRADE`(?, ?, ?, ?, ?, ?, ?, ?)")) { + AbstractCharacter ac1 = man1.getOwner(); + AbstractCharacter ac2 = man2.getOwner(); + boolean worked = false; - preparedStatement.setString(1, formatTradeString(from1)); - preparedStatement.setLong(2, (long) ac1.getObjectUUID()); - preparedStatement.setString(3, formatTradeString(from2)); - preparedStatement.setLong(4, (long) ac2.getObjectUUID()); - preparedStatement.setInt(5, goldFrom1); - preparedStatement.setLong(6, (long) inventoryGold1.getObjectUUID()); - preparedStatement.setInt(7, goldFrom2); - preparedStatement.setLong(8, (long) inventoryGold2.getObjectUUID()); + if (ac1 == null || ac2 == null || inventoryGold1 == null || inventoryGold2 == null) + return false; - ResultSet rs = preparedStatement.executeQuery(); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL `item_TRADE`(?, ?, ?, ?, ?, ?, ?, ?)")) { - if (rs.next()) - worked = rs.getBoolean("result"); + preparedStatement.setString(1, formatTradeString(from1)); + preparedStatement.setLong(2, ac1.getObjectUUID()); + preparedStatement.setString(3, formatTradeString(from2)); + preparedStatement.setLong(4, ac2.getObjectUUID()); + preparedStatement.setInt(5, goldFrom1); + preparedStatement.setLong(6, inventoryGold1.getObjectUUID()); + preparedStatement.setInt(7, goldFrom2); + preparedStatement.setLong(8, inventoryGold2.getObjectUUID()); - } catch (SQLException e) { - Logger.error(e); - } - return worked; - } + ResultSet rs = preparedStatement.executeQuery(); - private static String formatTradeString(HashSet list) { - int size = list.size(); + if (rs.next()) + worked = rs.getBoolean("result"); - String ret = ""; + } catch (SQLException e) { + Logger.error(e); + } + return worked; + } - if (size == 0) - return ret; + public ArrayList GET_EQUIPPED_ITEMS(final int targetId) { - boolean start = true; + ArrayList itemList; - for (int i : list) { - if (start) { - ret += i; - start = false; - } else - ret += "," + i; - } - return ret; - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_item`.*, `object`.`parent`, `object`.`type` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE `object`.`parent`=? && `obj_item`.`item_container`='equip';")) { - public ArrayList GET_EQUIPPED_ITEMS(final int targetId) { + preparedStatement.setLong(1, targetId); + ResultSet rs = preparedStatement.executeQuery(); - ArrayList itemList; + itemList = getObjectsFromRs(rs, 10); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_item`.*, `object`.`parent`, `object`.`type` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE `object`.`parent`=? && `obj_item`.`item_container`='equip';")) { + } catch (SQLException e) { + Logger.error(e); + return null; + } - preparedStatement.setLong(1, (long) targetId); - ResultSet rs = preparedStatement.executeQuery(); + return itemList; + } - itemList = getObjectsFromRs(rs, 10); + public Item GET_ITEM(final int itemUUID) { - } catch (SQLException e) { - Logger.error(e); - return null; - } + Item item; - return itemList; - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_item`.*, `object`.`parent`, `object`.`type` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE `object`.`UID`=?;")) { - public Item GET_ITEM(final int itemUUID) { + preparedStatement.setLong(1, itemUUID); + ResultSet rs = preparedStatement.executeQuery(); - Item item; + item = (Item) getObjectFromRs(rs); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_item`.*, `object`.`parent`, `object`.`type` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE `object`.`UID`=?;")) { + } catch (SQLException e) { + Logger.error(e); + return null; + } + return item; + } - preparedStatement.setLong(1, itemUUID); - ResultSet rs = preparedStatement.executeQuery(); + public ArrayList GET_ITEMS_FOR_ACCOUNT(final int accountId) { - item = (Item) getObjectFromRs(rs); + ArrayList itemList; - } catch (SQLException e) { - Logger.error(e); - return null; - } - return item; - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_item`.*, `object`.`parent`, `object`.`type` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE `object`.`parent`=?;")) { - public ArrayList GET_ITEMS_FOR_ACCOUNT(final int accountId) { + preparedStatement.setLong(1, accountId); + ResultSet rs = preparedStatement.executeQuery(); - ArrayList itemList; + itemList = getObjectsFromRs(rs, 100); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_item`.*, `object`.`parent`, `object`.`type` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE `object`.`parent`=?;")) { + } catch (SQLException e) { + Logger.error(e); + return null; + } + return itemList; + } - preparedStatement.setLong(1, (long) accountId); - ResultSet rs = preparedStatement.executeQuery(); + public ArrayList GET_ITEMS_FOR_NPC(final int npcId) { - itemList = getObjectsFromRs(rs, 100); + ArrayList itemList; - } catch (SQLException e) { - Logger.error(e); - return null; - } - return itemList; - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_item`.*, `object`.`parent`, `object`.`type` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE `object`.`parent`=?;")) { - public ArrayList GET_ITEMS_FOR_NPC(final int npcId) { + preparedStatement.setLong(1, npcId); + ResultSet rs = preparedStatement.executeQuery(); - ArrayList itemList; + itemList = getObjectsFromRs(rs, 20); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_item`.*, `object`.`parent`, `object`.`type` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE `object`.`parent`=?;")) { + } catch (SQLException e) { + Logger.error(e); + return null; + } + return itemList; + } - preparedStatement.setLong(1, npcId); - ResultSet rs = preparedStatement.executeQuery(); + public ArrayList GET_ITEMS_FOR_PC(final int id) { - itemList = getObjectsFromRs(rs, 20); + ArrayList itemList; - } catch (SQLException e) { - Logger.error(e); - return null; - } - return itemList; - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_item`.*, `object`.`parent`, `object`.`type` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE `object`.`parent`=?")) { - public ArrayList GET_ITEMS_FOR_PC(final int id) { + preparedStatement.setLong(1, id); + ResultSet rs = preparedStatement.executeQuery(); - ArrayList itemList; + itemList = getObjectsFromRs(rs, 100); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_item`.*, `object`.`parent`, `object`.`type` FROM `object` INNER JOIN `obj_item` ON `object`.`UID` = `obj_item`.`UID` WHERE `object`.`parent`=?")) { + } catch (SQLException e) { + Logger.error(e); + return null; + } + return itemList; + } - preparedStatement.setLong(1, (long) id); - ResultSet rs = preparedStatement.executeQuery(); + public boolean MOVE_GOLD(final Item from, final Item to, final int amt) { - itemList = getObjectsFromRs(rs, 100); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_numberOfItems` = CASE WHEN `UID`=? THEN ? WHEN `UID`=? THEN ? END WHERE `UID` IN (?, ?);")) { - } catch (SQLException e) { - Logger.error(e); - return null; - } - return itemList; - } + int newFromAmt = from.getNumOfItems() - amt; + int newToAmt = to.getNumOfItems() + amt; - public boolean MOVE_GOLD(final Item from, final Item to, final int amt) { + preparedStatement.setLong(1, from.getObjectUUID()); + preparedStatement.setInt(2, newFromAmt); + preparedStatement.setLong(3, to.getObjectUUID()); + preparedStatement.setInt(4, newToAmt); + preparedStatement.setLong(5, from.getObjectUUID()); + preparedStatement.setLong(6, to.getObjectUUID()); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_numberOfItems` = CASE WHEN `UID`=? THEN ? WHEN `UID`=? THEN ? END WHERE `UID` IN (?, ?);")) { + return (preparedStatement.executeUpdate() > 0); - int newFromAmt = from.getNumOfItems() - amt; - int newToAmt = to.getNumOfItems() + amt; + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - preparedStatement.setLong(1, (long) from.getObjectUUID()); - preparedStatement.setInt(2, newFromAmt); - preparedStatement.setLong(3, (long) to.getObjectUUID()); - preparedStatement.setInt(4, newToAmt); - preparedStatement.setLong(5, (long) from.getObjectUUID()); - preparedStatement.setLong(6, (long) to.getObjectUUID()); + public boolean ORPHAN_INVENTORY(final HashSet inventory) { - return (preparedStatement.executeUpdate() > 0); + boolean worked = true; - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + for (Item item : inventory) { - public boolean ORPHAN_INVENTORY(final HashSet inventory) { + if (item.getItemBase().getType().equals(ItemType.GOLD)) + continue; - boolean worked = true; + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` LEFT JOIN `object` ON `object`.`UID` = `obj_item`.`UID` SET `object`.`parent`=NULL, `obj_item`.`item_container`='none' WHERE `object`.`UID`=?;")) { - for (Item item : inventory) { + preparedStatement.setLong(1, item.getObjectUUID()); + worked = (preparedStatement.executeUpdate() > 0); - if (item.getItemBase().getType().equals(ItemType.GOLD)) - continue; + if (worked) + item.zeroItem(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` LEFT JOIN `object` ON `object`.`UID` = `obj_item`.`UID` SET `object`.`parent`=NULL, `obj_item`.`item_container`='none' WHERE `object`.`UID`=?;")) { + } catch (SQLException e) { + Logger.error(e); + return false; + } + } + return worked; + } - preparedStatement.setLong(1, (long) item.getObjectUUID()); - worked = (preparedStatement.executeUpdate() > 0); + public HashSet GET_ITEMS_FOR_VENDOR(final int vendorID) { - if (worked) - item.zeroItem(); + HashSet itemSet = new HashSet<>(); - } catch (SQLException e) { - Logger.error(e); - return false; - } - } - return worked; - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT ID FROM static_itembase WHERE vendorType = ?")) { - public HashSet GET_ITEMS_FOR_VENDOR(final int vendorID) { + preparedStatement.setInt(1, vendorID); - HashSet itemSet = new HashSet<>(); + ResultSet rs = preparedStatement.executeQuery(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT ID FROM static_itembase WHERE vendorType = ?")) { + while (rs.next()) + itemSet.add(rs.getInt(1)); - preparedStatement.setInt(1, vendorID); + } catch (SQLException e) { + Logger.error(e); + return itemSet; + } - ResultSet rs = preparedStatement.executeQuery(); + return itemSet; + } - while (rs.next()) - itemSet.add(rs.getInt(1)); + //Used to transfer a single item between owners or equip or vault or bank or inventory + public boolean UPDATE_OWNER(final Item item, int newOwnerID, boolean ownerNPC, boolean ownerPlayer, + boolean ownerAccount, ItemContainerType containerType, int slot) { - } catch (SQLException e) { - Logger.error(e); - return itemSet; - } + boolean worked = false; - return itemSet; - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL `item_TRANSFER_OWNER`(?, ?, ?, ? )")) { - //Used to transfer a single item between owners or equip or vault or bank or inventory - public boolean UPDATE_OWNER(final Item item, int newOwnerID, boolean ownerNPC, boolean ownerPlayer, - boolean ownerAccount, ItemContainerType containerType, int slot) { + preparedStatement.setLong(1, item.getObjectUUID()); - boolean worked = false; + if (newOwnerID != 0) + preparedStatement.setLong(2, newOwnerID); + else + preparedStatement.setNull(2, java.sql.Types.BIGINT); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("CALL `item_TRANSFER_OWNER`(?, ?, ?, ? )")) { + switch (containerType) { + case INVENTORY: + preparedStatement.setString(3, "inventory"); + break; + case EQUIPPED: + preparedStatement.setString(3, "equip"); + break; + case BANK: + preparedStatement.setString(3, "bank"); + break; + case VAULT: + preparedStatement.setString(3, "vault"); + break; + case FORGE: + preparedStatement.setString(3, "forge"); + break; + default: + preparedStatement.setString(3, "none"); //Shouldn't be here + break; + } + preparedStatement.setInt(4, slot); + ResultSet rs = preparedStatement.executeQuery(); - preparedStatement.setLong(1, item.getObjectUUID()); + if (rs.next()) + worked = rs.getBoolean("result"); - if (newOwnerID != 0) - preparedStatement.setLong(2, newOwnerID); - else - preparedStatement.setNull(2, java.sql.Types.BIGINT); + } catch (SQLException e) { + Logger.error(e); + return false; + } + return worked; + } - switch (containerType) { - case INVENTORY: - preparedStatement.setString(3, "inventory"); - break; - case EQUIPPED: - preparedStatement.setString(3, "equip"); - break; - case BANK: - preparedStatement.setString(3, "bank"); - break; - case VAULT: - preparedStatement.setString(3, "vault"); - break; - case FORGE: - preparedStatement.setString(3, "forge"); - break; - default: - preparedStatement.setString(3, "none"); //Shouldn't be here - break; - } - preparedStatement.setInt(4, slot); - ResultSet rs = preparedStatement.executeQuery(); + public boolean SET_DURABILITY(final Item item, int value) { - if (rs.next()) - worked = rs.getBoolean("result"); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_durabilityCurrent`=? WHERE `UID`=? AND `item_durabilityCurrent`=?")) { - } catch (SQLException e) { - Logger.error(e); - return false; - } - return worked; - } + preparedStatement.setInt(1, value); + preparedStatement.setLong(2, item.getObjectUUID()); + preparedStatement.setInt(3, item.getDurabilityCurrent()); - public boolean SET_DURABILITY(final Item item, int value) { + return (preparedStatement.executeUpdate() > 0); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_durabilityCurrent`=? WHERE `UID`=? AND `item_durabilityCurrent`=?")) { + } catch (SQLException e) { + Logger.error(e); + return false; + } + } - preparedStatement.setInt(1, value); - preparedStatement.setLong(2, (long) item.getObjectUUID()); - preparedStatement.setInt(3, (int) item.getDurabilityCurrent()); + public boolean UPDATE_FORGE_TO_INVENTORY(final Item item) { - return (preparedStatement.executeUpdate() > 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_container` = ? WHERE `UID` = ? AND `item_container` = 'forge';")) { - } catch (SQLException e) { - Logger.error(e); - return false; - } - } + preparedStatement.setString(1, "inventory"); + preparedStatement.setLong(2, item.getObjectUUID()); - public boolean UPDATE_FORGE_TO_INVENTORY(final Item item) { + return (preparedStatement.executeUpdate() > 0); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_container` = ? WHERE `UID` = ? AND `item_container` = 'forge';")) { + } catch (SQLException e) { + Logger.error(e); + return false; + } - preparedStatement.setString(1, "inventory"); - preparedStatement.setLong(2, (long) item.getObjectUUID()); + } - return (preparedStatement.executeUpdate() > 0); + /** + * Attempts to update the quantity of this gold item + * + * @param value New quantity of gold + * @return True on success + */ + public boolean UPDATE_GOLD(final Item item, int value) { + if (item == null) + return false; + return UPDATE_GOLD(item, value, item.getNumOfItems()); + } - } catch (SQLException e) { - Logger.error(e); - return false; - } + /** + * Attempts to update the quantity of this gold item using CAS + * + * @return True on success + */ + public boolean UPDATE_GOLD(final Item item, int newValue, int oldValue) { - } + if (!item.getItemBase().getType().equals(ItemType.GOLD)) + return false; - /** - * Attempts to update the quantity of this gold item - * - * @param value New quantity of gold - * @return True on success - */ - public boolean UPDATE_GOLD(final Item item, int value) { - if (item == null) - return false; - return UPDATE_GOLD(item, value, item.getNumOfItems()); - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_numberOfItems`=? WHERE `UID`=?")) { - /** - * Attempts to update the quantity of this gold item using CAS - * - * @return True on success - */ - public boolean UPDATE_GOLD(final Item item, int newValue, int oldValue) { + preparedStatement.setInt(1, newValue); + preparedStatement.setLong(2, item.getObjectUUID()); - if (!item.getItemBase().getType().equals(ItemType.GOLD)) - return false; + return (preparedStatement.executeUpdate() > 0); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_numberOfItems`=? WHERE `UID`=?")) { + } catch (SQLException e) { + Logger.error(e); + return false; + } - preparedStatement.setInt(1, newValue); - preparedStatement.setLong(2, (long) item.getObjectUUID()); + } - return (preparedStatement.executeUpdate() > 0); + public boolean UPDATE_REMAINING_CHARGES(final Item item) { - } catch (SQLException e) { - Logger.error(e); - return false; - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_chargesRemaining` = ? WHERE `UID` = ?")) { - } + preparedStatement.setInt(1, item.getChargesRemaining()); + preparedStatement.setLong(2, item.getObjectUUID()); - public boolean UPDATE_REMAINING_CHARGES(final Item item) { + return (preparedStatement.executeUpdate() > 0); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_chargesRemaining` = ? WHERE `UID` = ?")) { + } catch (SQLException e) { + Logger.error(e); + return false; + } - preparedStatement.setInt(1, item.getChargesRemaining()); - preparedStatement.setLong(2, (long) item.getObjectUUID()); + } - return (preparedStatement.executeUpdate() > 0); + // This is necessary because default number of items is 1. + // When we create gold, we want it to start at 0 quantity. - } catch (SQLException e) { - Logger.error(e); - return false; - } + public boolean ZERO_ITEM_STACK(Item item) { - } + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_numberOfItems`=0 WHERE `UID` = ?")) { - // This is necessary because default number of items is 1. - // When we create gold, we want it to start at 0 quantity. + preparedStatement.setLong(1, item.getObjectUUID()); - public boolean ZERO_ITEM_STACK(Item item) { + return (preparedStatement.executeUpdate() > 0); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_numberOfItems`=0 WHERE `UID` = ?")) { + } catch (SQLException e) { + Logger.error(e); + return false; + } + } - preparedStatement.setLong(1, (long) item.getObjectUUID()); + public boolean UPDATE_FLAGS(Item item) { - return (preparedStatement.executeUpdate() > 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_flags`=? WHERE `UID` = ?")) { - } catch (SQLException e) { - Logger.error(e); - return false; - } - } + preparedStatement.setInt(1, item.getFlags()); + preparedStatement.setLong(2, item.getObjectUUID()); - public boolean UPDATE_FLAGS(Item item) { + return (preparedStatement.executeUpdate() > 0); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_flags`=? WHERE `UID` = ?")) { + } catch (SQLException e) { + Logger.error(e); + return false; + } + } - preparedStatement.setInt(1, item.getFlags()); - preparedStatement.setLong(2, (long) item.getObjectUUID()); + public boolean UPDATE_VALUE(Item item, int value) { - return (preparedStatement.executeUpdate() > 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_value`=? WHERE `UID` = ?")) { - } catch (SQLException e) { - Logger.error(e); - return false; - } - } + preparedStatement.setInt(1, value); + preparedStatement.setLong(2, item.getObjectUUID()); - public boolean UPDATE_VALUE(Item item,int value) { + return (preparedStatement.executeUpdate() > 0); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_value`=? WHERE `UID` = ?")) { - - preparedStatement.setInt(1, value); - preparedStatement.setLong(2, (long) item.getObjectUUID()); - - return (preparedStatement.executeUpdate() > 0); - - } catch (SQLException e) { - Logger.error(e); - return false; - } - } + } catch (SQLException e) { + Logger.error(e); + return false; + } + } } diff --git a/src/engine/db/handlers/dbKitHandler.java b/src/engine/db/handlers/dbKitHandler.java index c1c0be74..b23e94a6 100644 --- a/src/engine/db/handlers/dbKitHandler.java +++ b/src/engine/db/handlers/dbKitHandler.java @@ -21,25 +21,25 @@ import java.util.ArrayList; public class dbKitHandler extends dbHandlerBase { - public dbKitHandler() { - this.localClass = Kit.class; - this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); - } + public dbKitHandler() { + this.localClass = Kit.class; + this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); + } - public ArrayList GET_ALL_KITS() { + public ArrayList GET_ALL_KITS() { - ArrayList kitList = new ArrayList<>(); + ArrayList kitList = new ArrayList<>(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_validkit`")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_validkit`")) { - ResultSet rs = preparedStatement.executeQuery(); - kitList = getObjectsFromRs(rs, 20); + ResultSet rs = preparedStatement.executeQuery(); + kitList = getObjectsFromRs(rs, 20); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return kitList; - } + return kitList; + } } diff --git a/src/engine/db/handlers/dbMenuHandler.java b/src/engine/db/handlers/dbMenuHandler.java index fcf7bfd4..959b0e23 100644 --- a/src/engine/db/handlers/dbMenuHandler.java +++ b/src/engine/db/handlers/dbMenuHandler.java @@ -21,27 +21,27 @@ import java.util.ArrayList; public class dbMenuHandler extends dbHandlerBase { - public dbMenuHandler() { - this.localClass = MenuOption.class; + public dbMenuHandler() { + this.localClass = MenuOption.class; this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); - } + } - public ArrayList GET_MENU_OPTIONS(final int id) { + public ArrayList GET_MENU_OPTIONS(final int id) { - ArrayList menuOptions = new ArrayList<>(); + ArrayList menuOptions = new ArrayList<>(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_menuoption` WHERE menuID = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_menuoption` WHERE menuID = ?")) { - preparedStatement.setInt(1, id); + preparedStatement.setInt(1, id); - ResultSet rs = preparedStatement.executeQuery(); - menuOptions = getObjectsFromRs(rs, 1000); + ResultSet rs = preparedStatement.executeQuery(); + menuOptions = getObjectsFromRs(rs, 1000); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return menuOptions; - } + return menuOptions; + } } diff --git a/src/engine/db/handlers/dbMineHandler.java b/src/engine/db/handlers/dbMineHandler.java index 2c527de9..da722779 100644 --- a/src/engine/db/handlers/dbMineHandler.java +++ b/src/engine/db/handlers/dbMineHandler.java @@ -23,113 +23,113 @@ import java.util.ArrayList; public class dbMineHandler extends dbHandlerBase { - public dbMineHandler() { - this.localClass = Mine.class; - this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); - } + public dbMineHandler() { + this.localClass = Mine.class; + this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); + } - public Mine GET_MINE(int id) { + public Mine GET_MINE(int id) { - if (id == 0) - return null; + if (id == 0) + return null; - Mine mine = (Mine) DbManager.getFromCache(Enum.GameObjectType.Mine, id); + Mine mine = (Mine) DbManager.getFromCache(Enum.GameObjectType.Mine, id); - if (mine != null) - return mine; + if (mine != null) + return mine; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_building`.*, `object`.`parent` FROM `object` INNER JOIN `obj_building` ON `obj_building`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?;")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_building`.*, `object`.`parent` FROM `object` INNER JOIN `obj_building` ON `obj_building`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?;")) { - preparedStatement.setLong(1, id); + preparedStatement.setLong(1, id); - ResultSet rs = preparedStatement.executeQuery(); - mine = (Mine) getObjectFromRs(rs); + ResultSet rs = preparedStatement.executeQuery(); + mine = (Mine) getObjectFromRs(rs); - } catch (SQLException e) { - Logger.error(e); - } - return mine; - } + } catch (SQLException e) { + Logger.error(e); + } + return mine; + } - public ArrayList GET_ALL_MINES_FOR_SERVER() { + public ArrayList GET_ALL_MINES_FOR_SERVER() { - ArrayList mines = new ArrayList<>(); + ArrayList mines = new ArrayList<>(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_mine`.*, `object`.`parent` FROM `object` INNER JOIN `obj_mine` ON `obj_mine`.`UID` = `object`.`UID`")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_mine`.*, `object`.`parent` FROM `object` INNER JOIN `obj_mine` ON `obj_mine`.`UID` = `object`.`UID`")) { - ResultSet rs = preparedStatement.executeQuery(); - mines = getObjectsFromRs(rs, 1000); + ResultSet rs = preparedStatement.executeQuery(); + mines = getObjectsFromRs(rs, 1000); - } catch (SQLException e) { - Logger.error(e); - } - return mines; - } + } catch (SQLException e) { + Logger.error(e); + } + return mines; + } - public boolean CHANGE_OWNER(Mine mine, int playerUID) { + public boolean CHANGE_OWNER(Mine mine, int playerUID) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_mine` SET `mine_ownerUID`=? WHERE `UID`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_mine` SET `mine_ownerUID`=? WHERE `UID`=?")) { - preparedStatement.setInt(1, playerUID); - preparedStatement.setLong(2, mine.getObjectUUID()); + preparedStatement.setInt(1, playerUID); + preparedStatement.setLong(2, mine.getObjectUUID()); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - public boolean CHANGE_RESOURCE(Mine mine, Resource resource) { + public boolean CHANGE_RESOURCE(Mine mine, Resource resource) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_mine` SET `mine_resource`=? WHERE `UID`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_mine` SET `mine_resource`=? WHERE `UID`=?")) { - preparedStatement.setString(1, resource.name()); - preparedStatement.setLong(2, mine.getObjectUUID()); + preparedStatement.setString(1, resource.name()); + preparedStatement.setLong(2, mine.getObjectUUID()); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - public boolean CHANGE_TYPE(Mine mine, MineProduction productionType) { + public boolean CHANGE_TYPE(Mine mine, MineProduction productionType) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_mine` SET `mine_type`=? WHERE `UID`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_mine` SET `mine_type`=? WHERE `UID`=?")) { - preparedStatement.setString(1, productionType.name()); - preparedStatement.setLong(2, mine.getObjectUUID()); + preparedStatement.setString(1, productionType.name()); + preparedStatement.setLong(2, mine.getObjectUUID()); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - public boolean SET_FLAGS(Mine mine, int newFlags) { + public boolean SET_FLAGS(Mine mine, int newFlags) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_mine` SET `flags`=? WHERE `UID`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_mine` SET `flags`=? WHERE `UID`=?")) { - preparedStatement.setInt(1, newFlags); - preparedStatement.setLong(2, mine.getObjectUUID()); + preparedStatement.setInt(1, newFlags); + preparedStatement.setLong(2, mine.getObjectUUID()); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + } catch (SQLException e) { + Logger.error(e); + } + return false; + } } diff --git a/src/engine/db/handlers/dbMobBaseHandler.java b/src/engine/db/handlers/dbMobBaseHandler.java index 2c278492..7ef95c6d 100644 --- a/src/engine/db/handlers/dbMobBaseHandler.java +++ b/src/engine/db/handlers/dbMobBaseHandler.java @@ -26,173 +26,173 @@ import java.util.HashMap; public class dbMobBaseHandler extends dbHandlerBase { - public dbMobBaseHandler() { - this.localClass = MobBase.class; - this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); - } + public dbMobBaseHandler() { + this.localClass = MobBase.class; + this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); + } - public MobBase GET_MOBBASE(int id) { + public MobBase GET_MOBBASE(int id) { - if (id == 0) - return null; + if (id == 0) + return null; - MobBase mobBase = (MobBase) DbManager.getFromCache(GameObjectType.MobBase, id); + MobBase mobBase = (MobBase) DbManager.getFromCache(GameObjectType.MobBase, id); - if (mobBase != null) - return mobBase; + if (mobBase != null) + return mobBase; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_mobbase` WHERE `ID`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_mobbase` WHERE `ID`=?")) { - preparedStatement.setInt(1, id); + preparedStatement.setInt(1, id); - ResultSet rs = preparedStatement.executeQuery(); - mobBase = (MobBase) getObjectFromRs(rs); + ResultSet rs = preparedStatement.executeQuery(); + mobBase = (MobBase) getObjectFromRs(rs); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return mobBase; - } + return mobBase; + } - public ArrayList GET_ALL_MOBBASES() { + public ArrayList GET_ALL_MOBBASES() { - ArrayList mobbaseList = new ArrayList<>(); + ArrayList mobbaseList = new ArrayList<>(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_mobbase`;")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_mobbase`;")) { - ResultSet rs = preparedStatement.executeQuery(); - mobbaseList = getObjectsFromRs(rs, 1000); + ResultSet rs = preparedStatement.executeQuery(); + mobbaseList = getObjectsFromRs(rs, 1000); - } catch (SQLException e) { - Logger.error(e); - } - return mobbaseList; - } + } catch (SQLException e) { + Logger.error(e); + } + return mobbaseList; + } - public void SET_AI_DEFAULTS() { + public void SET_AI_DEFAULTS() { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_ai_defaults`")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_ai_defaults`")) { - ResultSet rs = preparedStatement.executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); - while (rs.next()) { - MBServerStatics.AI_BASE_AGGRO_RANGE = rs.getInt("aggro_range"); - MBServerStatics.AI_PATROL_DIVISOR = rs.getInt("patrol_chance"); - MBServerStatics.AI_DROP_AGGRO_RANGE = rs.getInt("drop_aggro_range"); - MBServerStatics.AI_POWER_DIVISOR = rs.getInt("cast_chance"); - MBServerStatics.AI_RECALL_RANGE = rs.getInt("recall_range"); - MBServerStatics.AI_PET_HEEL_DISTANCE = rs.getInt("pet_heel_distance"); - } - } catch (SQLException e) { - Logger.error(e); - } - } + while (rs.next()) { + MBServerStatics.AI_BASE_AGGRO_RANGE = rs.getInt("aggro_range"); + MBServerStatics.AI_PATROL_DIVISOR = rs.getInt("patrol_chance"); + MBServerStatics.AI_DROP_AGGRO_RANGE = rs.getInt("drop_aggro_range"); + MBServerStatics.AI_POWER_DIVISOR = rs.getInt("cast_chance"); + MBServerStatics.AI_RECALL_RANGE = rs.getInt("recall_range"); + MBServerStatics.AI_PET_HEEL_DISTANCE = rs.getInt("pet_heel_distance"); + } + } catch (SQLException e) { + Logger.error(e); + } + } - public boolean UPDATE_AI_DEFAULTS() { + public boolean UPDATE_AI_DEFAULTS() { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `static_ai_defaults` SET `aggro_range` = ?,`patrol_chance`= ?,`drop_aggro_range`= ?,`cast_chance`= ?,`recall_range`= ? WHERE `ID` = 1")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `static_ai_defaults` SET `aggro_range` = ?,`patrol_chance`= ?,`drop_aggro_range`= ?,`cast_chance`= ?,`recall_range`= ? WHERE `ID` = 1")) { - preparedStatement.setInt(1, MBServerStatics.AI_BASE_AGGRO_RANGE); - preparedStatement.setInt(2, MBServerStatics.AI_PATROL_DIVISOR); - preparedStatement.setInt(3, MBServerStatics.AI_DROP_AGGRO_RANGE); - preparedStatement.setInt(4, MBServerStatics.AI_POWER_DIVISOR); - preparedStatement.setInt(5, MBServerStatics.AI_RECALL_RANGE); + preparedStatement.setInt(1, MBServerStatics.AI_BASE_AGGRO_RANGE); + preparedStatement.setInt(2, MBServerStatics.AI_PATROL_DIVISOR); + preparedStatement.setInt(3, MBServerStatics.AI_DROP_AGGRO_RANGE); + preparedStatement.setInt(4, MBServerStatics.AI_POWER_DIVISOR); + preparedStatement.setInt(5, MBServerStatics.AI_RECALL_RANGE); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - public HashMap LOAD_STATIC_POWERS(int mobBaseUUID) { + public HashMap LOAD_STATIC_POWERS(int mobBaseUUID) { - HashMap powersList = new HashMap<>(); + HashMap powersList = new HashMap<>(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_mobbase_powers` WHERE `mobbaseUUID`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_mobbase_powers` WHERE `mobbaseUUID`=?")) { - preparedStatement.setInt(1, mobBaseUUID); - ResultSet rs = preparedStatement.executeQuery(); + preparedStatement.setInt(1, mobBaseUUID); + ResultSet rs = preparedStatement.executeQuery(); - while (rs.next()) - powersList.put(rs.getInt("token"), rs.getInt("rank")); + while (rs.next()) + powersList.put(rs.getInt("token"), rs.getInt("rank")); - } catch (SQLException e) { - Logger.error(e); - } - return powersList; - } + } catch (SQLException e) { + Logger.error(e); + } + return powersList; + } - public ArrayList GET_RUNEBASE_EFFECTS(int runeID) { + public ArrayList GET_RUNEBASE_EFFECTS(int runeID) { - ArrayList effectsList = new ArrayList<>(); + ArrayList effectsList = new ArrayList<>(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_mobbase_effects` WHERE `mobbaseUUID` = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_mobbase_effects` WHERE `mobbaseUUID` = ?")) { - preparedStatement.setInt(1, runeID); - ResultSet rs = preparedStatement.executeQuery(); + preparedStatement.setInt(1, runeID); + ResultSet rs = preparedStatement.executeQuery(); - while (rs.next()) { - MobBaseEffects mbs = new MobBaseEffects(rs); - effectsList.add(mbs); - } + while (rs.next()) { + MobBaseEffects mbs = new MobBaseEffects(rs); + effectsList.add(mbs); + } - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return effectsList; - } + return effectsList; + } - public MobBaseStats LOAD_STATS(int mobBaseUUID) { + public MobBaseStats LOAD_STATS(int mobBaseUUID) { - MobBaseStats mobBaseStats = MobBaseStats.GetGenericStats(); + MobBaseStats mobBaseStats = MobBaseStats.GetGenericStats(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_mobbase_stats` WHERE `mobbaseUUID` = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_mobbase_stats` WHERE `mobbaseUUID` = ?")) { - preparedStatement.setInt(1, mobBaseUUID); - ResultSet rs = preparedStatement.executeQuery(); + preparedStatement.setInt(1, mobBaseUUID); + ResultSet rs = preparedStatement.executeQuery(); - while (rs.next()) - mobBaseStats = new MobBaseStats(rs); + while (rs.next()) + mobBaseStats = new MobBaseStats(rs); - } catch (SQLException e) { - Logger.error(e); - } - return mobBaseStats; - } + } catch (SQLException e) { + Logger.error(e); + } + return mobBaseStats; + } - public void LOAD_ALL_MOBBASE_SPEEDS(MobBase mobBase) { + public void LOAD_ALL_MOBBASE_SPEEDS(MobBase mobBase) { - if (mobBase.getLoadID() == 0) - return; + if (mobBase.getLoadID() == 0) + return; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_mobbase_race` WHERE `mobbaseID` = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_mobbase_race` WHERE `mobbaseID` = ?")) { - preparedStatement.setInt(1, mobBase.getLoadID()); - ResultSet rs = preparedStatement.executeQuery(); + preparedStatement.setInt(1, mobBase.getLoadID()); + ResultSet rs = preparedStatement.executeQuery(); - while (rs.next()) { - float walk = rs.getFloat("walkStandard"); - float walkCombat = rs.getFloat("walkCombat"); - float run = rs.getFloat("runStandard"); - float runCombat = rs.getFloat("runCombat"); - mobBase.updateSpeeds(walk, walkCombat, run, runCombat); - } + while (rs.next()) { + float walk = rs.getFloat("walkStandard"); + float walkCombat = rs.getFloat("walkCombat"); + float run = rs.getFloat("runStandard"); + float runCombat = rs.getFloat("runCombat"); + mobBase.updateSpeeds(walk, walkCombat, run, runCombat); + } - } catch (SQLException e) { - Logger.error(e); - } - } + } catch (SQLException e) { + Logger.error(e); + } + } } diff --git a/src/engine/db/handlers/dbMobHandler.java b/src/engine/db/handlers/dbMobHandler.java index c94d57a4..eeeb8439 100644 --- a/src/engine/db/handlers/dbMobHandler.java +++ b/src/engine/db/handlers/dbMobHandler.java @@ -24,225 +24,225 @@ import java.util.ArrayList; public class dbMobHandler extends dbHandlerBase { - public dbMobHandler() { - this.localClass = Mob.class; - this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); - } + public dbMobHandler() { + this.localClass = Mob.class; + this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); + } - public Mob ADD_MOB(Mob toAdd) { + public Mob ADD_MOB(Mob toAdd) { - Mob mobile = null; + Mob mobile = null; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("CALL `mob_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL `mob_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);")) { - preparedStatement.setLong(1, toAdd.getParentZoneID()); - preparedStatement.setInt(2, toAdd.getMobBaseID()); - preparedStatement.setInt(3, toAdd.getGuildUUID()); - preparedStatement.setFloat(4, toAdd.getSpawnX()); - preparedStatement.setFloat(5, toAdd.getSpawnY()); - preparedStatement.setFloat(6, toAdd.getSpawnZ()); - preparedStatement.setInt(7, 0); - preparedStatement.setFloat(8, toAdd.getSpawnRadius()); - preparedStatement.setInt(9, toAdd.getTrueSpawnTime()); + preparedStatement.setLong(1, toAdd.getParentZoneID()); + preparedStatement.setInt(2, toAdd.getMobBaseID()); + preparedStatement.setInt(3, toAdd.getGuildUUID()); + preparedStatement.setFloat(4, toAdd.getSpawnX()); + preparedStatement.setFloat(5, toAdd.getSpawnY()); + preparedStatement.setFloat(6, toAdd.getSpawnZ()); + preparedStatement.setInt(7, 0); + preparedStatement.setFloat(8, toAdd.getSpawnRadius()); + preparedStatement.setInt(9, toAdd.getTrueSpawnTime()); - if (toAdd.getContract() != null) - preparedStatement.setInt(10, toAdd.getContract().getContractID()); - else - preparedStatement.setInt(10, 0); + if (toAdd.getContract() != null) + preparedStatement.setInt(10, toAdd.getContract().getContractID()); + else + preparedStatement.setInt(10, 0); - preparedStatement.setInt(11, toAdd.getBuildingID()); - preparedStatement.setInt(12, toAdd.getLevel()); - preparedStatement.setString(13, toAdd.getFirstName()); + preparedStatement.setInt(11, toAdd.getBuildingID()); + preparedStatement.setInt(12, toAdd.getLevel()); + preparedStatement.setString(13, toAdd.getFirstName()); - ResultSet rs = preparedStatement.executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); - int objectUUID = (int) rs.getLong("UID"); + int objectUUID = (int) rs.getLong("UID"); - if (objectUUID > 0) - mobile = GET_MOB(objectUUID); + if (objectUUID > 0) + mobile = GET_MOB(objectUUID); - } catch (SQLException e) { - throw new RuntimeException(e); - } - return mobile; - } + } catch (SQLException e) { + throw new RuntimeException(e); + } + return mobile; + } - public boolean updateUpgradeTime(Mob mob, DateTime upgradeDateTime) { + public boolean updateUpgradeTime(Mob mob, DateTime upgradeDateTime) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE obj_mob SET upgradeDate=? " - + "WHERE UID = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE obj_mob SET upgradeDate=? " + + "WHERE UID = ?")) { - if (upgradeDateTime == null) - preparedStatement.setNull(1, java.sql.Types.DATE); - else - preparedStatement.setTimestamp(1, new java.sql.Timestamp(upgradeDateTime.getMillis())); + if (upgradeDateTime == null) + preparedStatement.setNull(1, java.sql.Types.DATE); + else + preparedStatement.setTimestamp(1, new java.sql.Timestamp(upgradeDateTime.getMillis())); - preparedStatement.setInt(2, mob.getObjectUUID()); + preparedStatement.setInt(2, mob.getObjectUUID()); - preparedStatement.execute(); - return true; - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + preparedStatement.execute(); + return true; + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - public int DELETE_MOB(final Mob mob) { + public int DELETE_MOB(final Mob mob) { - int row_count = 0; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `object` WHERE `UID` = ?")) { + int row_count = 0; + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `object` WHERE `UID` = ?")) { - preparedStatement.setLong(1, mob.getDBID()); - row_count = preparedStatement.executeUpdate(); + preparedStatement.setLong(1, mob.getDBID()); + row_count = preparedStatement.executeUpdate(); - } catch (SQLException e) { - Logger.error(e); + } catch (SQLException e) { + Logger.error(e); - } - return row_count; - } + } + return row_count; + } - public void LOAD_PATROL_POINTS(Mob captain) { + public void LOAD_PATROL_POINTS(Mob captain) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_guards` WHERE `captainUID` = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_guards` WHERE `captainUID` = ?")) { - preparedStatement.setInt(1, captain.getObjectUUID()); - ResultSet rs = preparedStatement.executeQuery(); + preparedStatement.setInt(1, captain.getObjectUUID()); + ResultSet rs = preparedStatement.executeQuery(); - while (rs.next()) { - String name = rs.getString("name"); - Mob toCreate = Mob.createGuardMob(captain, captain.getGuild(), captain.getParentZone(), captain.building.getLoc(), captain.getLevel(), name); + while (rs.next()) { + String name = rs.getString("name"); + Mob toCreate = Mob.createGuardMob(captain, captain.getGuild(), captain.getParentZone(), captain.building.getLoc(), captain.getLevel(), name); - if (toCreate == null) - return; + if (toCreate == null) + return; - if (toCreate != null) { - toCreate.setTimeToSpawnSiege(System.currentTimeMillis() + MBServerStatics.FIFTEEN_MINUTES); - toCreate.setDeathTime(System.currentTimeMillis()); - } - } + if (toCreate != null) { + toCreate.setTimeToSpawnSiege(System.currentTimeMillis() + MBServerStatics.FIFTEEN_MINUTES); + toCreate.setDeathTime(System.currentTimeMillis()); + } + } - } catch (SQLException e) { - Logger.error(e); - } - } + } catch (SQLException e) { + Logger.error(e); + } + } - public boolean ADD_TO_GUARDS(final long captainUID, final int mobBaseID, final String name, final int slot) { + public boolean ADD_TO_GUARDS(final long captainUID, final int mobBaseID, final String name, final int slot) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_guards` (`captainUID`, `mobBaseID`,`name`, `slot`) VALUES (?,?,?,?)")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_guards` (`captainUID`, `mobBaseID`,`name`, `slot`) VALUES (?,?,?,?)")) { - preparedStatement.setLong(1, captainUID); - preparedStatement.setInt(2, mobBaseID); - preparedStatement.setString(3, name); - preparedStatement.setInt(4, slot); + preparedStatement.setLong(1, captainUID); + preparedStatement.setInt(2, mobBaseID); + preparedStatement.setString(3, name); + preparedStatement.setInt(4, slot); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - return false; - } - } + } catch (SQLException e) { + Logger.error(e); + return false; + } + } - public boolean REMOVE_FROM_GUARDS(final long captainUID, final int mobBaseID, final int slot) { + public boolean REMOVE_FROM_GUARDS(final long captainUID, final int mobBaseID, final int slot) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_guards` WHERE `captainUID`=? AND `mobBaseID`=? AND `slot` =?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_guards` WHERE `captainUID`=? AND `mobBaseID`=? AND `slot` =?")) { - preparedStatement.setLong(1, captainUID); - preparedStatement.setInt(2, mobBaseID); - preparedStatement.setInt(3, slot); + preparedStatement.setLong(1, captainUID); + preparedStatement.setInt(2, mobBaseID); + preparedStatement.setInt(3, slot); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - return false; - } - } + } catch (SQLException e) { + Logger.error(e); + return false; + } + } - public ArrayList GET_ALL_MOBS_FOR_ZONE(Zone zone) { + public ArrayList GET_ALL_MOBS_FOR_ZONE(Zone zone) { - ArrayList mobileList = new ArrayList<>(); + ArrayList mobileList = new ArrayList<>(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_mob`.*, `object`.`parent` FROM `object` INNER JOIN `obj_mob` ON `obj_mob`.`UID` = `object`.`UID` WHERE `object`.`parent` = ?;")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_mob`.*, `object`.`parent` FROM `object` INNER JOIN `obj_mob` ON `obj_mob`.`UID` = `object`.`UID` WHERE `object`.`parent` = ?;")) { - preparedStatement.setLong(1, zone.getObjectUUID()); + preparedStatement.setLong(1, zone.getObjectUUID()); - ResultSet rs = preparedStatement.executeQuery(); - mobileList = getObjectsFromRs(rs, 1000); + ResultSet rs = preparedStatement.executeQuery(); + mobileList = getObjectsFromRs(rs, 1000); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return mobileList; - } + return mobileList; + } - public Mob GET_MOB(final int objectUUID) { + public Mob GET_MOB(final int objectUUID) { - Mob mobile = null; + Mob mobile = null; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_mob`.*, `object`.`parent` FROM `object` INNER JOIN `obj_mob` ON `obj_mob`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?;")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_mob`.*, `object`.`parent` FROM `object` INNER JOIN `obj_mob` ON `obj_mob`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?;")) { - preparedStatement.setLong(1, objectUUID); - ResultSet rs = preparedStatement.executeQuery(); - mobile = (Mob) getObjectFromRs(rs); + preparedStatement.setLong(1, objectUUID); + ResultSet rs = preparedStatement.executeQuery(); + mobile = (Mob) getObjectFromRs(rs); - } catch (SQLException e) { - Logger.error(e); - } - return mobile; - } + } catch (SQLException e) { + Logger.error(e); + } + return mobile; + } - public int MOVE_MOB(long mobID, long parentID, float locX, float locY, float locZ) { + public int MOVE_MOB(long mobID, long parentID, float locX, float locY, float locZ) { - int row_count = 0; + int row_count = 0; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `object` INNER JOIN `obj_mob` On `object`.`UID` = `obj_mob`.`UID` SET `object`.`parent`=?, `obj_mob`.`mob_spawnX`=?, `obj_mob`.`mob_spawnY`=?, `obj_mob`.`mob_spawnZ`=? WHERE `obj_mob`.`UID`=?;")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `object` INNER JOIN `obj_mob` On `object`.`UID` = `obj_mob`.`UID` SET `object`.`parent`=?, `obj_mob`.`mob_spawnX`=?, `obj_mob`.`mob_spawnY`=?, `obj_mob`.`mob_spawnZ`=? WHERE `obj_mob`.`UID`=?;")) { - preparedStatement.setLong(1, parentID); - preparedStatement.setFloat(2, locX); - preparedStatement.setFloat(3, locY); - preparedStatement.setFloat(4, locZ); - preparedStatement.setLong(5, mobID); + preparedStatement.setLong(1, parentID); + preparedStatement.setFloat(2, locX); + preparedStatement.setFloat(3, locY); + preparedStatement.setFloat(4, locZ); + preparedStatement.setLong(5, mobID); - ResultSet rs = preparedStatement.executeQuery(); - row_count = preparedStatement.executeUpdate(); + ResultSet rs = preparedStatement.executeQuery(); + row_count = preparedStatement.executeUpdate(); - } catch (SQLException e) { - Logger.error(e); - } - return row_count; - } + } catch (SQLException e) { + Logger.error(e); + } + return row_count; + } - public String SET_PROPERTY(final Mob m, String name, Object new_value) { + public String SET_PROPERTY(final Mob m, String name, Object new_value) { - String result = ""; + String result = ""; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("CALL mob_SETPROP(?,?,?)")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL mob_SETPROP(?,?,?)")) { - preparedStatement.setLong(1, m.getObjectUUID()); - preparedStatement.setString(2, name); - preparedStatement.setString(3, String.valueOf(new_value)); + preparedStatement.setLong(1, m.getObjectUUID()); + preparedStatement.setString(2, name); + preparedStatement.setString(3, String.valueOf(new_value)); - ResultSet rs = preparedStatement.executeQuery(); - result = rs.getString("result"); + ResultSet rs = preparedStatement.executeQuery(); + result = rs.getString("result"); - } catch (SQLException e) { - Logger.error(e); - } - return result; - } + } catch (SQLException e) { + Logger.error(e); + } + return result; + } } diff --git a/src/engine/db/handlers/dbPlayerCharacterHandler.java b/src/engine/db/handlers/dbPlayerCharacterHandler.java index f74e3d49..a716f05a 100644 --- a/src/engine/db/handlers/dbPlayerCharacterHandler.java +++ b/src/engine/db/handlers/dbPlayerCharacterHandler.java @@ -27,546 +27,542 @@ import java.util.concurrent.ConcurrentHashMap; public class dbPlayerCharacterHandler extends dbHandlerBase { - public dbPlayerCharacterHandler() { - this.localClass = PlayerCharacter.class; - this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); - } + public dbPlayerCharacterHandler() { + this.localClass = PlayerCharacter.class; + this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); + } - public PlayerCharacter ADD_PLAYER_CHARACTER(final PlayerCharacter toAdd) { + public PlayerCharacter ADD_PLAYER_CHARACTER(final PlayerCharacter toAdd) { - PlayerCharacter playerCharacter = null; + PlayerCharacter playerCharacter = null; - if (toAdd.getAccount() == null) - return null; + if (toAdd.getAccount() == null) + return null; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("CALL `character_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL `character_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);")) { - preparedStatement.setLong(1, toAdd.getAccount().getObjectUUID()); - preparedStatement.setString(2, toAdd.getFirstName()); - preparedStatement.setString(3, toAdd.getLastName()); - preparedStatement.setInt(4, toAdd.getRace().getRaceRuneID()); - preparedStatement.setInt(5, toAdd.getBaseClass().getObjectUUID()); - preparedStatement.setInt(6, toAdd.getStrMod()); - preparedStatement.setInt(7, toAdd.getDexMod()); - preparedStatement.setInt(8, toAdd.getConMod()); - preparedStatement.setInt(9, toAdd.getIntMod()); - preparedStatement.setInt(10, toAdd.getSpiMod()); - preparedStatement.setInt(11, toAdd.getExp()); - preparedStatement.setInt(12, toAdd.getSkinColor()); - preparedStatement.setInt(13, toAdd.getHairColor()); - preparedStatement.setByte(14, toAdd.getHairStyle()); - preparedStatement.setInt(15, toAdd.getBeardColor()); - preparedStatement.setByte(16, toAdd.getBeardStyle()); + preparedStatement.setLong(1, toAdd.getAccount().getObjectUUID()); + preparedStatement.setString(2, toAdd.getFirstName()); + preparedStatement.setString(3, toAdd.getLastName()); + preparedStatement.setInt(4, toAdd.getRace().getRaceRuneID()); + preparedStatement.setInt(5, toAdd.getBaseClass().getObjectUUID()); + preparedStatement.setInt(6, toAdd.getStrMod()); + preparedStatement.setInt(7, toAdd.getDexMod()); + preparedStatement.setInt(8, toAdd.getConMod()); + preparedStatement.setInt(9, toAdd.getIntMod()); + preparedStatement.setInt(10, toAdd.getSpiMod()); + preparedStatement.setInt(11, toAdd.getExp()); + preparedStatement.setInt(12, toAdd.getSkinColor()); + preparedStatement.setInt(13, toAdd.getHairColor()); + preparedStatement.setByte(14, toAdd.getHairStyle()); + preparedStatement.setInt(15, toAdd.getBeardColor()); + preparedStatement.setByte(16, toAdd.getBeardStyle()); - ResultSet rs = preparedStatement.executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); - int objectUUID = (int) rs.getLong("UID"); + int objectUUID = (int) rs.getLong("UID"); - if (objectUUID > 0) - playerCharacter = GET_PLAYER_CHARACTER(objectUUID); + if (objectUUID > 0) + playerCharacter = GET_PLAYER_CHARACTER(objectUUID); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return playerCharacter; - } + return playerCharacter; + } - public boolean SET_IGNORE_LIST(int sourceID, int targetID, boolean toIgnore, String charName) { + public boolean SET_IGNORE_LIST(int sourceID, int targetID, boolean toIgnore, String charName) { - String queryString = ""; + String queryString = ""; - if (toIgnore) - queryString = "INSERT INTO `dyn_character_ignore` (`accountUID`, `ignoringUID`, `characterName`) VALUES (?, ?, ?)"; - else - queryString = "DELETE FROM `dyn_character_ignore` WHERE `accountUID` = ? && `ignoringUID` = ?"; + if (toIgnore) + queryString = "INSERT INTO `dyn_character_ignore` (`accountUID`, `ignoringUID`, `characterName`) VALUES (?, ?, ?)"; + else + queryString = "DELETE FROM `dyn_character_ignore` WHERE `accountUID` = ? && `ignoringUID` = ?"; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement(queryString)) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement(queryString)) { - preparedStatement.setLong(1, sourceID); - preparedStatement.setLong(2, targetID); + preparedStatement.setLong(1, sourceID); + preparedStatement.setLong(2, targetID); - if (toIgnore) - preparedStatement.setString(3, charName); + if (toIgnore) + preparedStatement.setString(3, charName); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - public ArrayList GET_CHARACTERS_FOR_ACCOUNT(final int id) { + public ArrayList GET_CHARACTERS_FOR_ACCOUNT(final int id) { - ArrayList characterList = new ArrayList<>(); + ArrayList characterList = new ArrayList<>(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_character`.*, `object`.`parent` FROM `object` INNER JOIN `obj_character` ON `obj_character`.`UID` = `object`.`UID` WHERE `object`.`parent`=? && `obj_character`.`char_isActive`='1';")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_character`.*, `object`.`parent` FROM `object` INNER JOIN `obj_character` ON `obj_character`.`UID` = `object`.`UID` WHERE `object`.`parent`=? && `obj_character`.`char_isActive`='1';")) { - preparedStatement.setLong(1, (long) id); - ResultSet rs = preparedStatement.executeQuery(); - characterList = getObjectsFromRs(rs, 10); + preparedStatement.setLong(1, id); + ResultSet rs = preparedStatement.executeQuery(); + characterList = getObjectsFromRs(rs, 10); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return characterList; - } + return characterList; + } - public ArrayList GET_ALL_CHARACTERS() { + public ArrayList GET_ALL_CHARACTERS() { - ArrayList characterList = new ArrayList<>(); + ArrayList characterList = new ArrayList<>(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_character`.*, `object`.`parent` FROM `object` INNER JOIN `obj_character` ON `obj_character`.`UID` = `object`.`UID` WHERE `obj_character`.`char_isActive`='1';")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_character`.*, `object`.`parent` FROM `object` INNER JOIN `obj_character` ON `obj_character`.`UID` = `object`.`UID` WHERE `obj_character`.`char_isActive`='1';")) { - ResultSet rs = preparedStatement.executeQuery(); - characterList = getObjectsFromRs(rs, 2000); + ResultSet rs = preparedStatement.executeQuery(); + characterList = getObjectsFromRs(rs, 2000); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return characterList; - } + return characterList; + } - /** - * - * getFirstName looks up the first name of a PlayerCharacter by - * first checking the GOM cache and then querying the database. - * PlayerCharacter objects that are not already cached won't be instantiated - * and cached. - * - */ + /** + * getFirstName looks up the first name of a PlayerCharacter by + * first checking the GOM cache and then querying the database. + * PlayerCharacter objects that are not already cached won't be instantiated + * and cached. + */ - public ConcurrentHashMap GET_IGNORE_LIST(final int objectUUID, final boolean skipActiveCheck) { + public ConcurrentHashMap GET_IGNORE_LIST(final int objectUUID, final boolean skipActiveCheck) { - ConcurrentHashMap ignoreList = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW); + ConcurrentHashMap ignoreList = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_character_ignore` WHERE `accountUID` = ?;")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_character_ignore` WHERE `accountUID` = ?;")) { - preparedStatement.setLong(1, objectUUID); + preparedStatement.setLong(1, objectUUID); - ResultSet rs = preparedStatement.executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); - while (rs.next()) { - int ignoreCharacterID = rs.getInt("ignoringUID"); + while (rs.next()) { + int ignoreCharacterID = rs.getInt("ignoringUID"); - if (ignoreCharacterID == 0) - continue; + if (ignoreCharacterID == 0) + continue; - String name = rs.getString("characterName"); - ignoreList.put(ignoreCharacterID, name); - } + String name = rs.getString("characterName"); + ignoreList.put(ignoreCharacterID, name); + } - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return ignoreList; - } + return ignoreList; + } - public PlayerCharacter GET_PLAYER_CHARACTER(final int objectUUID) { + public PlayerCharacter GET_PLAYER_CHARACTER(final int objectUUID) { - if (objectUUID == 0) - return null; + if (objectUUID == 0) + return null; - PlayerCharacter playerCharacter = (PlayerCharacter) DbManager.getFromCache(Enum.GameObjectType.PlayerCharacter, objectUUID); + PlayerCharacter playerCharacter = (PlayerCharacter) DbManager.getFromCache(Enum.GameObjectType.PlayerCharacter, objectUUID); - if (playerCharacter != null) - return playerCharacter; + if (playerCharacter != null) + return playerCharacter; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_character`.*, `object`.`parent` FROM `object` INNER JOIN `obj_character` ON `obj_character`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_character`.*, `object`.`parent` FROM `object` INNER JOIN `obj_character` ON `obj_character`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?")) { - preparedStatement.setLong(1, objectUUID); + preparedStatement.setLong(1, objectUUID); - ResultSet rs = preparedStatement.executeQuery(); - playerCharacter = (PlayerCharacter) getObjectFromRs(rs); + ResultSet rs = preparedStatement.executeQuery(); + playerCharacter = (PlayerCharacter) getObjectFromRs(rs); - } catch (SQLException e) { - Logger.error(e); - } - ; - return playerCharacter; - } + } catch (SQLException e) { + Logger.error(e); + } + return playerCharacter; + } - public boolean IS_CHARACTER_NAME_UNIQUE(final String firstName) { + public boolean IS_CHARACTER_NAME_UNIQUE(final String firstName) { - boolean unique = true; + boolean unique = true; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `char_firstname` FROM `obj_character` WHERE `char_isActive`=1 && `char_firstname`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `char_firstname` FROM `obj_character` WHERE `char_isActive`=1 && `char_firstname`=?")) { - preparedStatement.setString(1, firstName); + preparedStatement.setString(1, firstName); - ResultSet rs = preparedStatement.executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); - if (rs.next()) - unique = false; + if (rs.next()) + unique = false; - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return unique; - } + return unique; + } - public boolean UPDATE_NAME(String oldFirstName, String newFirstName, String newLastName) { + public boolean UPDATE_NAME(String oldFirstName, String newFirstName, String newLastName) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_firstname`=?, `char_lastname`=? WHERE `char_firstname`=? AND `char_isActive`='1'")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_firstname`=?, `char_lastname`=? WHERE `char_firstname`=? AND `char_isActive`='1'")) { - preparedStatement.setString(1, newFirstName); - preparedStatement.setString(2, newLastName); - preparedStatement.setString(3, oldFirstName); + preparedStatement.setString(1, newFirstName); + preparedStatement.setString(2, newLastName); + preparedStatement.setString(3, oldFirstName); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - public boolean SET_DELETED(final PlayerCharacter pc) { + public boolean SET_DELETED(final PlayerCharacter pc) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_isActive`=? WHERE `UID` = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_isActive`=? WHERE `UID` = ?")) { - preparedStatement.setBoolean(1, !pc.isDeleted()); - preparedStatement.setLong(2, pc.getObjectUUID()); + preparedStatement.setBoolean(1, !pc.isDeleted()); + preparedStatement.setLong(2, pc.getObjectUUID()); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - public boolean SET_ACTIVE(final PlayerCharacter pc, boolean status) { + public boolean SET_ACTIVE(final PlayerCharacter pc, boolean status) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_isActive`=? WHERE `UID` = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_isActive`=? WHERE `UID` = ?")) { - preparedStatement.setBoolean(1, status); - preparedStatement.setLong(2, (long) pc.getObjectUUID()); + preparedStatement.setBoolean(1, status); + preparedStatement.setLong(2, pc.getObjectUUID()); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - public boolean SET_BIND_BUILDING(final PlayerCharacter pc, int bindBuildingID) { + public boolean SET_BIND_BUILDING(final PlayerCharacter pc, int bindBuildingID) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_bindBuilding`=? WHERE `UID` = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_bindBuilding`=? WHERE `UID` = ?")) { - preparedStatement.setInt(1, bindBuildingID); - preparedStatement.setLong(2, (long) pc.getObjectUUID()); + preparedStatement.setInt(1, bindBuildingID); + preparedStatement.setLong(2, pc.getObjectUUID()); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - public boolean SET_ANNIVERSERY(final PlayerCharacter pc, boolean flag) { + public boolean SET_ANNIVERSERY(final PlayerCharacter pc, boolean flag) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `anniversery`=? WHERE `UID` = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `anniversery`=? WHERE `UID` = ?")) { - preparedStatement.setBoolean(1, flag); - preparedStatement.setLong(2, (long) pc.getObjectUUID()); + preparedStatement.setBoolean(1, flag); + preparedStatement.setLong(2, pc.getObjectUUID()); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - public boolean UPDATE_CHARACTER_EXPERIENCE(final PlayerCharacter pc) { + public boolean UPDATE_CHARACTER_EXPERIENCE(final PlayerCharacter pc) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_experience`=? WHERE `UID` = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_experience`=? WHERE `UID` = ?")) { - preparedStatement.setInt(1, pc.getExp()); - preparedStatement.setLong(2, (long) pc.getObjectUUID()); + preparedStatement.setInt(1, pc.getExp()); + preparedStatement.setLong(2, pc.getObjectUUID()); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - } - return false; - } - - public boolean UPDATE_GUILD(final PlayerCharacter pc, int guildUUID) { + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guildUID`=? WHERE `UID` = ?")) { + public boolean UPDATE_GUILD(final PlayerCharacter pc, int guildUUID) { - preparedStatement.setInt(1, guildUUID); - preparedStatement.setLong(2, (long) pc.getObjectUUID()); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guildUID`=? WHERE `UID` = ?")) { - return (preparedStatement.executeUpdate() > 0); + preparedStatement.setInt(1, guildUUID); + preparedStatement.setLong(2, pc.getObjectUUID()); - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + return (preparedStatement.executeUpdate() > 0); - public boolean UPDATE_CHARACTER_STATS(final PlayerCharacter pc) { + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_strMod`=?, `char_dexMod`=?, `char_conMod`=?, `char_intMod`=?, `char_spiMod`=? WHERE `UID`=?")) { + public boolean UPDATE_CHARACTER_STATS(final PlayerCharacter pc) { - preparedStatement.setInt(1, pc.getStrMod()); - preparedStatement.setInt(2, pc.getDexMod()); - preparedStatement.setInt(3, pc.getConMod()); - preparedStatement.setInt(4, pc.getIntMod()); - preparedStatement.setInt(5, pc.getSpiMod()); - preparedStatement.setLong(6, (long) pc.getObjectUUID()); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_strMod`=?, `char_dexMod`=?, `char_conMod`=?, `char_intMod`=?, `char_spiMod`=? WHERE `UID`=?")) { - return (preparedStatement.executeUpdate() > 0); + preparedStatement.setInt(1, pc.getStrMod()); + preparedStatement.setInt(2, pc.getDexMod()); + preparedStatement.setInt(3, pc.getConMod()); + preparedStatement.setInt(4, pc.getIntMod()); + preparedStatement.setInt(5, pc.getSpiMod()); + preparedStatement.setLong(6, pc.getObjectUUID()); - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + return (preparedStatement.executeUpdate() > 0); - public String SET_PROPERTY(final PlayerCharacter playerCharacter, String name, Object new_value) { + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - String result = ""; + public String SET_PROPERTY(final PlayerCharacter playerCharacter, String name, Object new_value) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("CALL character_SETPROP(?,?,?)")) { + String result = ""; - preparedStatement.setLong(1, playerCharacter.getObjectUUID()); - preparedStatement.setString(2, name); - ; - preparedStatement.setString(3, String.valueOf(new_value)); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("CALL character_SETPROP(?,?,?)")) { - ResultSet rs = preparedStatement.executeQuery(); - result = rs.getString("result"); + preparedStatement.setLong(1, playerCharacter.getObjectUUID()); + preparedStatement.setString(2, name); + preparedStatement.setString(3, String.valueOf(new_value)); - } catch (SQLException e) { - Logger.error(e); - } - return result; - } + ResultSet rs = preparedStatement.executeQuery(); + result = rs.getString("result"); - public boolean SET_PROMOTION_CLASS(PlayerCharacter player, int promotionClassID) { + } catch (SQLException e) { + Logger.error(e); + } + return result; + } - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_promotionClassID`=? WHERE `UID`=?;")) { + public boolean SET_PROMOTION_CLASS(PlayerCharacter player, int promotionClassID) { - preparedStatement.setInt(1, promotionClassID); - preparedStatement.setInt(2, player.getObjectUUID()); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_promotionClassID`=? WHERE `UID`=?;")) { - return (preparedStatement.executeUpdate() > 0); + preparedStatement.setInt(1, promotionClassID); + preparedStatement.setInt(2, player.getObjectUUID()); - } catch (SQLException e) { - Logger.error(e); - } - return false; - } - - public boolean SET_INNERCOUNCIL(PlayerCharacter player, boolean isInnerCouncil) { + return (preparedStatement.executeUpdate() > 0); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_isInnerCouncil`=? WHERE `UID`=?;")) { + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - preparedStatement.setBoolean(1, isInnerCouncil); - preparedStatement.setInt(2, player.getObjectUUID()); + public boolean SET_INNERCOUNCIL(PlayerCharacter player, boolean isInnerCouncil) { - return (preparedStatement.executeUpdate() > 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_isInnerCouncil`=? WHERE `UID`=?;")) { - } catch (SQLException e) { - Logger.error(e); - } - return false; - } - - public boolean SET_FULL_MEMBER(PlayerCharacter player, boolean isFullMember) { + preparedStatement.setBoolean(1, isInnerCouncil); + preparedStatement.setInt(2, player.getObjectUUID()); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_isFullMember`=? WHERE `UID`=?;")) { + return (preparedStatement.executeUpdate() > 0); - preparedStatement.setBoolean(1, isFullMember); - preparedStatement.setInt(2, player.getObjectUUID()); + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - return (preparedStatement.executeUpdate() > 0); + public boolean SET_FULL_MEMBER(PlayerCharacter player, boolean isFullMember) { - } catch (SQLException e) { - Logger.error(e); - } - return false; - } - - public boolean SET_TAX_COLLECTOR(PlayerCharacter player, boolean isTaxCollector) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_isFullMember`=? WHERE `UID`=?;")) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_isTaxCollector`=? WHERE `UID`=?;")) { + preparedStatement.setBoolean(1, isFullMember); + preparedStatement.setInt(2, player.getObjectUUID()); - preparedStatement.setBoolean(1, isTaxCollector); - preparedStatement.setInt(2, player.getObjectUUID()); + return (preparedStatement.executeUpdate() > 0); - return (preparedStatement.executeUpdate() > 0); + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - } catch (SQLException e) { - Logger.error(e); - } - return false; - } - - public boolean SET_RECRUITER(PlayerCharacter player, boolean isRecruiter) { + public boolean SET_TAX_COLLECTOR(PlayerCharacter player, boolean isTaxCollector) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_isRecruiter`=? WHERE `UID`=?;")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_isTaxCollector`=? WHERE `UID`=?;")) { - preparedStatement.setBoolean(1, isRecruiter); - preparedStatement.setInt(2, player.getObjectUUID()); + preparedStatement.setBoolean(1, isTaxCollector); + preparedStatement.setInt(2, player.getObjectUUID()); - return (preparedStatement.executeUpdate() > 0); + return (preparedStatement.executeUpdate() > 0); - } catch (SQLException e) { - Logger.error(e); - } - return false; - } - - public boolean SET_GUILD_TITLE(PlayerCharacter player, int title) { + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_title`=? WHERE `UID`=?;")) { + public boolean SET_RECRUITER(PlayerCharacter player, boolean isRecruiter) { - preparedStatement.setInt(1, title); - preparedStatement.setInt(2, player.getObjectUUID()); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_isRecruiter`=? WHERE `UID`=?;")) { - return (preparedStatement.executeUpdate() > 0); + preparedStatement.setBoolean(1, isRecruiter); + preparedStatement.setInt(2, player.getObjectUUID()); - } catch (SQLException e) { - Logger.error(e); - } - return false; - } + return (preparedStatement.executeUpdate() > 0); - public boolean ADD_FRIEND(int source, long friend) { + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_friends` (`playerUID`, `friendUID`) VALUES (?, ?)")) { + public boolean SET_GUILD_TITLE(PlayerCharacter player, int title) { - preparedStatement.setLong(1, source); - preparedStatement.setLong(2, friend); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_title`=? WHERE `UID`=?;")) { - return (preparedStatement.executeUpdate() > 0); + preparedStatement.setInt(1, title); + preparedStatement.setInt(2, player.getObjectUUID()); - } catch (SQLException e) { - Logger.error(e); - } - return false; - } - - public boolean REMOVE_FRIEND(int source, int friend) { + return (preparedStatement.executeUpdate() > 0); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_character_friends` WHERE (`playerUID`=?) AND (`friendUID`=?)")) { + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - preparedStatement.setLong(1, source); - preparedStatement.setLong(2, friend); + public boolean ADD_FRIEND(int source, long friend) { - return (preparedStatement.executeUpdate() > 0); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_friends` (`playerUID`, `friendUID`) VALUES (?, ?)")) { - } catch (SQLException e) { - Logger.error(e); - } - return false; - } - - public void LOAD_PLAYER_FRIENDS() { + preparedStatement.setLong(1, source); + preparedStatement.setLong(2, friend); - PlayerFriends playerFriend; + return (preparedStatement.executeUpdate() > 0); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM dyn_character_friends")) { + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - ResultSet rs = preparedStatement.executeQuery(); + public boolean REMOVE_FRIEND(int source, int friend) { - while (rs.next()) - playerFriend = new PlayerFriends(rs); + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_character_friends` WHERE (`playerUID`=?) AND (`friendUID`=?)")) { - } catch (SQLException e) { - Logger.error(e); - } + preparedStatement.setLong(1, source); + preparedStatement.setLong(2, friend); - prepareCallable("SELECT * FROM dyn_character_friends"); - } - - public boolean ADD_HERALDY(int source, AbstractWorldObject character) { + return (preparedStatement.executeUpdate() > 0); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_heraldy` (`playerUID`, `characterUID`,`characterType`) VALUES (?, ?,?)")) { + } catch (SQLException e) { + Logger.error(e); + } + return false; + } - preparedStatement.setLong(1, source); - preparedStatement.setLong(2, character.getObjectUUID()); - preparedStatement.setInt(3, character.getObjectType().ordinal()); + public void LOAD_PLAYER_FRIENDS() { - return (preparedStatement.executeUpdate() > 0); + PlayerFriends playerFriend; - } catch (SQLException e) { - Logger.error(e); - } - return false; - } - - public boolean REMOVE_HERALDY(int source, int characterUID) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM dyn_character_friends")) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_character_heraldy` WHERE (`playerUID`=?) AND (`characterUID`=?)")) { + ResultSet rs = preparedStatement.executeQuery(); - preparedStatement.setLong(1, source); - preparedStatement.setLong(2, characterUID); + while (rs.next()) + playerFriend = new PlayerFriends(rs); - return (preparedStatement.executeUpdate() > 0); + } catch (SQLException e) { + Logger.error(e); + } - } catch (SQLException e) { - Logger.error(e); - } - return false; - } - - public void LOAD_HERALDY() { + prepareCallable("SELECT * FROM dyn_character_friends"); + } - Heraldry heraldy; + public boolean ADD_HERALDY(int source, AbstractWorldObject character) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM dyn_character_heraldy")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_heraldy` (`playerUID`, `characterUID`,`characterType`) VALUES (?, ?,?)")) { - ResultSet rs = preparedStatement.executeQuery(); + preparedStatement.setLong(1, source); + preparedStatement.setLong(2, character.getObjectUUID()); + preparedStatement.setInt(3, character.getObjectType().ordinal()); - while (rs.next()) - heraldy = new Heraldry(rs); + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; + } + + public boolean REMOVE_HERALDY(int source, int characterUID) { + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_character_heraldy` WHERE (`playerUID`=?) AND (`characterUID`=?)")) { + + preparedStatement.setLong(1, source); + preparedStatement.setLong(2, characterUID); + + return (preparedStatement.executeUpdate() > 0); + + } catch (SQLException e) { + Logger.error(e); + } + return false; + } + + public void LOAD_HERALDY() { + + Heraldry heraldy; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM dyn_character_heraldy")) { + + ResultSet rs = preparedStatement.executeQuery(); + + while (rs.next()) + heraldy = new Heraldry(rs); + + } catch (SQLException e) { + Logger.error(e); + } + } - } catch (SQLException e) { - Logger.error(e); - } - } - } diff --git a/src/engine/db/handlers/dbPromotionClassHandler.java b/src/engine/db/handlers/dbPromotionClassHandler.java index fed00a7a..aef9af8e 100644 --- a/src/engine/db/handlers/dbPromotionClassHandler.java +++ b/src/engine/db/handlers/dbPromotionClassHandler.java @@ -65,7 +65,7 @@ public class dbPromotionClassHandler extends dbHandlerBase { return promotionClass; } - + public ArrayList GET_ALL_PROMOTIONS() { ArrayList promotionList = new ArrayList<>(); diff --git a/src/engine/db/handlers/dbRuneBaseAttributeHandler.java b/src/engine/db/handlers/dbRuneBaseAttributeHandler.java index 923385b1..536addb5 100644 --- a/src/engine/db/handlers/dbRuneBaseAttributeHandler.java +++ b/src/engine/db/handlers/dbRuneBaseAttributeHandler.java @@ -21,27 +21,27 @@ import java.util.ArrayList; public class dbRuneBaseAttributeHandler extends dbHandlerBase { - public dbRuneBaseAttributeHandler() { - this.localClass = RuneBaseAttribute.class; - this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); - } + public dbRuneBaseAttributeHandler() { + this.localClass = RuneBaseAttribute.class; + this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); + } - public ArrayList GET_ATTRIBUTES_FOR_RUNEBASE() { + public ArrayList GET_ATTRIBUTES_FOR_RUNEBASE() { - ArrayList runeBaseAttributesList = new ArrayList<>(); + ArrayList runeBaseAttributesList = new ArrayList<>(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_runebaseattribute`")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_runebaseattribute`")) { - ResultSet rs = preparedStatement.executeQuery(); - runeBaseAttributesList = getObjectsFromRs(rs, 10); + ResultSet rs = preparedStatement.executeQuery(); + runeBaseAttributesList = getObjectsFromRs(rs, 10); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return runeBaseAttributesList; - } + return runeBaseAttributesList; + } } diff --git a/src/engine/db/handlers/dbRuneBaseEffectHandler.java b/src/engine/db/handlers/dbRuneBaseEffectHandler.java index c8b790a1..def0f204 100644 --- a/src/engine/db/handlers/dbRuneBaseEffectHandler.java +++ b/src/engine/db/handlers/dbRuneBaseEffectHandler.java @@ -24,69 +24,68 @@ import java.util.HashMap; public class dbRuneBaseEffectHandler extends dbHandlerBase { - public dbRuneBaseEffectHandler() { - this.localClass = RuneBaseEffect.class; - this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); - } + public dbRuneBaseEffectHandler() { + this.localClass = RuneBaseEffect.class; + this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); + } - public ArrayList GET_EFFECTS_FOR_RUNEBASE(int id) { + public ArrayList GET_EFFECTS_FOR_RUNEBASE(int id) { - ArrayList runeBaseEffectsList = new ArrayList<>(); + ArrayList runeBaseEffectsList = new ArrayList<>(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_baseeffect` WHERE `runeID`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_baseeffect` WHERE `runeID`=?")) { - preparedStatement.setInt(1, id); + preparedStatement.setInt(1, id); - ResultSet rs = preparedStatement.executeQuery(); - runeBaseEffectsList = getObjectsFromRs(rs, 250); + ResultSet rs = preparedStatement.executeQuery(); + runeBaseEffectsList = getObjectsFromRs(rs, 250); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return runeBaseEffectsList; - } + return runeBaseEffectsList; + } - public ArrayList GET_ALL_RUNEBASE_EFFECTS() { + public ArrayList GET_ALL_RUNEBASE_EFFECTS() { - ArrayList runeBaseEffectsList = new ArrayList<>(); + ArrayList runeBaseEffectsList = new ArrayList<>(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_baseeffect`;")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_baseeffect`;")) { - ResultSet rs = preparedStatement.executeQuery(); - runeBaseEffectsList = getObjectsFromRs(rs, 250); + ResultSet rs = preparedStatement.executeQuery(); + runeBaseEffectsList = getObjectsFromRs(rs, 250); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return runeBaseEffectsList; - } + return runeBaseEffectsList; + } - //This calls from cache only. Call this AFTER caching all runebase effects; + //This calls from cache only. Call this AFTER caching all runebase effects; - public HashMap> LOAD_BASEEFFECTS_FOR_RUNEBASE() { + public HashMap> LOAD_BASEEFFECTS_FOR_RUNEBASE() { - HashMap> runeBaseEffectSet; - runeBaseEffectSet = new HashMap<>(); + HashMap> runeBaseEffectSet; + runeBaseEffectSet = new HashMap<>(); - for (AbstractGameObject runeBaseEffect:DbManager.getList(GameObjectType.RuneBaseEffect)){ + for (AbstractGameObject runeBaseEffect : DbManager.getList(GameObjectType.RuneBaseEffect)) { - int runeBaseID = ((RuneBaseEffect)runeBaseEffect).getRuneBaseID(); - if (runeBaseEffectSet.get(runeBaseID) == null){ - ArrayList runeBaseEffectList = new ArrayList<>(); - runeBaseEffectList.add((RuneBaseEffect)runeBaseEffect); - runeBaseEffectSet.put(runeBaseID, runeBaseEffectList); - } - else{ - ArrayListruneBaseEffectList = runeBaseEffectSet.get(runeBaseID); - runeBaseEffectList.add((RuneBaseEffect)runeBaseEffect); - runeBaseEffectSet.put(runeBaseID, runeBaseEffectList); - } - } - return runeBaseEffectSet; - } + int runeBaseID = ((RuneBaseEffect) runeBaseEffect).getRuneBaseID(); + if (runeBaseEffectSet.get(runeBaseID) == null) { + ArrayList runeBaseEffectList = new ArrayList<>(); + runeBaseEffectList.add((RuneBaseEffect) runeBaseEffect); + runeBaseEffectSet.put(runeBaseID, runeBaseEffectList); + } else { + ArrayList runeBaseEffectList = runeBaseEffectSet.get(runeBaseID); + runeBaseEffectList.add((RuneBaseEffect) runeBaseEffect); + runeBaseEffectSet.put(runeBaseID, runeBaseEffectList); + } + } + return runeBaseEffectSet; + } } diff --git a/src/engine/db/handlers/dbRuneBaseHandler.java b/src/engine/db/handlers/dbRuneBaseHandler.java index 235f96a9..af66b036 100644 --- a/src/engine/db/handlers/dbRuneBaseHandler.java +++ b/src/engine/db/handlers/dbRuneBaseHandler.java @@ -22,158 +22,158 @@ import java.util.HashMap; public class dbRuneBaseHandler extends dbHandlerBase { - public dbRuneBaseHandler() { - this.localClass = RuneBase.class; - this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); - } + public dbRuneBaseHandler() { + this.localClass = RuneBase.class; + this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); + } - public void GET_RUNE_REQS(final RuneBase rb) { + public void GET_RUNE_REQS(final RuneBase rb) { - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_runereq` WHERE `runeID` = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_runereq` WHERE `runeID` = ?")) { - preparedStatement.setInt(1, rb.getObjectUUID()); + preparedStatement.setInt(1, rb.getObjectUUID()); - ResultSet rs = preparedStatement.executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); - while (rs.next()) { - int type = rs.getInt("type"); + while (rs.next()) { + int type = rs.getInt("type"); - switch (type) { - case 1: - rb.getRace().put(rs.getInt("requiredRuneID"), rs.getBoolean("isAllowed")); - break; - case 2: - rb.getBaseClass().put(rs.getInt("requiredRuneID"), rs.getBoolean("isAllowed")); - break; - case 3: - rb.getPromotionClass().put(rs.getInt("requiredRuneID"), rs.getBoolean("isAllowed")); - break; - case 4: - rb.getDiscipline().put(rs.getInt("requiredRuneID"), rs.getBoolean("isAllowed")); - break; - case 5: - rb.getOverwrite().add(rs.getInt("requiredRuneID")); - break; - case 6: - rb.setLevelRequired(rs.getInt("requiredRuneID")); - break; - } - } + switch (type) { + case 1: + rb.getRace().put(rs.getInt("requiredRuneID"), rs.getBoolean("isAllowed")); + break; + case 2: + rb.getBaseClass().put(rs.getInt("requiredRuneID"), rs.getBoolean("isAllowed")); + break; + case 3: + rb.getPromotionClass().put(rs.getInt("requiredRuneID"), rs.getBoolean("isAllowed")); + break; + case 4: + rb.getDiscipline().put(rs.getInt("requiredRuneID"), rs.getBoolean("isAllowed")); + break; + case 5: + rb.getOverwrite().add(rs.getInt("requiredRuneID")); + break; + case 6: + rb.setLevelRequired(rs.getInt("requiredRuneID")); + break; + } + } - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - } + } - public RuneBase GET_RUNEBASE(final int id) { + public RuneBase GET_RUNEBASE(final int id) { - RuneBase runeBase = null; + RuneBase runeBase = null; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_runebase` WHERE `ID` = ?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_runebase` WHERE `ID` = ?")) { - preparedStatement.setInt(1, id); + preparedStatement.setInt(1, id); - ResultSet rs = preparedStatement.executeQuery(); - runeBase = (RuneBase) getObjectFromRs(rs); + ResultSet rs = preparedStatement.executeQuery(); + runeBase = (RuneBase) getObjectFromRs(rs); - } catch (SQLException e) { - Logger.error(e); - } - return runeBase; - } + } catch (SQLException e) { + Logger.error(e); + } + return runeBase; + } - public ArrayList LOAD_ALL_RUNEBASES() { + public ArrayList LOAD_ALL_RUNEBASES() { - ArrayList runeBasesList = new ArrayList<>(); + ArrayList runeBasesList = new ArrayList<>(); - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_runebase`;")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_runebase`;")) { - ResultSet rs = preparedStatement.executeQuery(); - runeBasesList = getObjectsFromRs(rs, 1000); + ResultSet rs = preparedStatement.executeQuery(); + runeBasesList = getObjectsFromRs(rs, 1000); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return runeBasesList; - } + return runeBasesList; + } - public HashMap> LOAD_ALLOWED_STARTING_RUNES_FOR_BASECLASS() { + public HashMap> LOAD_ALLOWED_STARTING_RUNES_FOR_BASECLASS() { - HashMap> runeSets = new HashMap<>(); + HashMap> runeSets = new HashMap<>(); - int recordsRead = 0; + int recordsRead = 0; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_rune_baseclassrune")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_rune_baseclassrune")) { - ResultSet rs = preparedStatement.executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); - while (rs.next()) { + while (rs.next()) { - recordsRead++; + recordsRead++; - int baseClassID = rs.getInt("BaseClassesID"); - int runeBaseID = rs.getInt("RuneBaseID"); + int baseClassID = rs.getInt("BaseClassesID"); + int runeBaseID = rs.getInt("RuneBaseID"); - if (runeSets.get(baseClassID) == null) { - ArrayList runeList = new ArrayList<>(); - runeList.add(runeBaseID); - runeSets.put(baseClassID, runeList); - } else { - ArrayList runeList = runeSets.get(baseClassID); - runeList.add(runeBaseID); - runeSets.put(baseClassID, runeList); - } - } + if (runeSets.get(baseClassID) == null) { + ArrayList runeList = new ArrayList<>(); + runeList.add(runeBaseID); + runeSets.put(baseClassID, runeList); + } else { + ArrayList runeList = runeSets.get(baseClassID); + runeList.add(runeBaseID); + runeSets.put(baseClassID, runeList); + } + } - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - Logger.info("read: " + recordsRead + " cached: " + runeSets.size()); + Logger.info("read: " + recordsRead + " cached: " + runeSets.size()); - return runeSets; - } + return runeSets; + } - public HashMap> LOAD_ALLOWED_STARTING_RUNES_FOR_RACE() { + public HashMap> LOAD_ALLOWED_STARTING_RUNES_FOR_RACE() { - HashMap> runeSets; + HashMap> runeSets; - runeSets = new HashMap<>(); - int recordsRead = 0; + runeSets = new HashMap<>(); + int recordsRead = 0; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_rune_racerune")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_rune_racerune")) { - ResultSet rs = preparedStatement.executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); - while (rs.next()) { + while (rs.next()) { - recordsRead++; + recordsRead++; - int raceID = rs.getInt("RaceID"); - int runeBaseID = rs.getInt("RuneBaseID"); + int raceID = rs.getInt("RaceID"); + int runeBaseID = rs.getInt("RuneBaseID"); - if (runeSets.get(raceID) == null) { - ArrayList runeList = new ArrayList<>(); - runeList.add(runeBaseID); - runeSets.put(raceID, runeList); - } else { - ArrayList runeList = runeSets.get(raceID); - runeList.add(runeBaseID); - runeSets.put(raceID, runeList); - } - } - } catch (SQLException e) { - Logger.error(e); - } + if (runeSets.get(raceID) == null) { + ArrayList runeList = new ArrayList<>(); + runeList.add(runeBaseID); + runeSets.put(raceID, runeList); + } else { + ArrayList runeList = runeSets.get(raceID); + runeList.add(runeBaseID); + runeSets.put(raceID, runeList); + } + } + } catch (SQLException e) { + Logger.error(e); + } - Logger.info("read: " + recordsRead + " cached: " + runeSets.size()); - return runeSets; - } + Logger.info("read: " + recordsRead + " cached: " + runeSets.size()); + return runeSets; + } } diff --git a/src/engine/db/handlers/dbShrineHandler.java b/src/engine/db/handlers/dbShrineHandler.java index 2dc1289e..5857372a 100644 --- a/src/engine/db/handlers/dbShrineHandler.java +++ b/src/engine/db/handlers/dbShrineHandler.java @@ -31,10 +31,28 @@ public class dbShrineHandler extends dbHandlerBase { this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); } - public ArrayList CREATE_SHRINE( int parentZoneID, int OwnerUUID, String name, int meshUUID, - Vector3fImmutable location, float meshScale, int currentHP, - ProtectionState protectionState, int currentGold, int rank, - DateTime upgradeDate, int blueprintUUID, float w, float rotY, String shrineType) { + public static void addObject(ArrayList list, ResultSet rs) throws SQLException { + + String type = rs.getString("type"); + + switch (type) { + case "building": + Building building = new Building(rs); + DbManager.addToCache(building); + list.add(building); + break; + case "shrine": + Shrine shrine = new Shrine(rs); + DbManager.addToCache(shrine); + list.add(shrine); + break; + } + } + + public ArrayList CREATE_SHRINE(int parentZoneID, int OwnerUUID, String name, int meshUUID, + Vector3fImmutable location, float meshScale, int currentHP, + ProtectionState protectionState, int currentGold, int rank, + DateTime upgradeDate, int blueprintUUID, float w, float rotY, String shrineType) { ArrayList shrineList = new ArrayList<>(); @@ -103,24 +121,6 @@ public class dbShrineHandler extends dbHandlerBase { } - public static void addObject(ArrayList list, ResultSet rs) throws SQLException { - - String type = rs.getString("type"); - - switch (type) { - case "building": - Building building = new Building(rs); - DbManager.addToCache(building); - list.add(building); - break; - case "shrine": - Shrine shrine = new Shrine(rs); - DbManager.addToCache(shrine); - list.add(shrine); - break; - } - } - public void LOAD_ALL_SHRINES() { Shrine shrine; diff --git a/src/engine/db/handlers/dbSkillBaseHandler.java b/src/engine/db/handlers/dbSkillBaseHandler.java index 0811c3a2..77e55fdf 100644 --- a/src/engine/db/handlers/dbSkillBaseHandler.java +++ b/src/engine/db/handlers/dbSkillBaseHandler.java @@ -26,113 +26,112 @@ import java.util.HashMap; public class dbSkillBaseHandler extends dbHandlerBase { - public dbSkillBaseHandler() { - this.localClass = SkillsBase.class; - this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); - } - - public SkillsBase GET_BASE(final int objectUUID) { - - SkillsBase skillsBase = (SkillsBase) DbManager.getFromCache(GameObjectType.SkillsBase, objectUUID); - if (skillsBase != null) - return skillsBase; - prepareCallable("SELECT * FROM static_skill_skillsbase WHERE ID = ?"); - setInt(1, objectUUID); - SkillsBase sb; - sb = (SkillsBase) getObjectSingle(objectUUID); - SkillsBase.putInCache(sb); - return sb; - } - - public SkillsBase GET_BASE_BY_NAME(String name) { - SkillsBase sb = SkillsBase.getFromCache(name); - if (sb != null) { - return sb; - } - prepareCallable("SELECT * FROM static_skill_skillsbase WHERE name = ?"); - setString(1, name); - ArrayList result = getObjectList(); - if (result.size() > 0) { - sb = (SkillsBase) result.get(0); - SkillsBase.putInCache(sb); - return sb; - } else { - return null; - } - } - - public SkillsBase GET_BASE_BY_TOKEN(final int token) { - SkillsBase sb = SkillsBase.getFromCache(token); - if (sb != null) { - return sb; - } - - prepareCallable("SELECT * FROM static_skill_skillsbase WHERE token = ?"); - setInt(1, token); - ArrayList result = getObjectList(); - if (result.size() > 0) { - sb = (SkillsBase) result.get(0); - SkillsBase.putInCache(sb); - return sb; - } else { - return null; - } - } - - public void LOAD_ALL_MAX_SKILLS_FOR_CONTRACT() { - - prepareCallable("SELECT * FROM `static_rune_maxskills`"); - - - try { - ResultSet rs = executeQuery(); - - //shrines cached in rs for easy cache on creation. - while (rs.next()) { - - MaxSkills maxSKills = new MaxSkills(rs); - if (MaxSkills.MaxSkillsSet.get(maxSKills.getRuneID()) == null){ - ArrayList newMaxSkillsList = new ArrayList<>(); - newMaxSkillsList.add(maxSKills); - MaxSkills.MaxSkillsSet.put(maxSKills.getRuneID(), newMaxSkillsList); - }else - MaxSkills.MaxSkillsSet.get(maxSKills.getRuneID()).add(maxSKills); - - } - - - - } catch (SQLException e) { - Logger.error( e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); - } - - } - - public void LOAD_ALL_RUNE_SKILLS() { - - - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_skill_skillsgranted`")) { - - ResultSet rs = preparedStatement.executeQuery(); - - while (rs.next()) { - - int runeID = rs.getInt("runeID"); - int token = rs.getInt("token"); - int amount = rs.getInt("amount"); - - if (SkillsBase.runeSkillsCache.get(runeID) == null) - SkillsBase.runeSkillsCache.put(runeID, new HashMap<>()); - - SkillsBase.runeSkillsCache.get(runeID).put(token, amount); - } - - } catch (SQLException e) { - Logger.error(e); - } - } + public dbSkillBaseHandler() { + this.localClass = SkillsBase.class; + this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); + } + + public SkillsBase GET_BASE(final int objectUUID) { + + SkillsBase skillsBase = (SkillsBase) DbManager.getFromCache(GameObjectType.SkillsBase, objectUUID); + if (skillsBase != null) + return skillsBase; + prepareCallable("SELECT * FROM static_skill_skillsbase WHERE ID = ?"); + setInt(1, objectUUID); + SkillsBase sb; + sb = (SkillsBase) getObjectSingle(objectUUID); + SkillsBase.putInCache(sb); + return sb; + } + + public SkillsBase GET_BASE_BY_NAME(String name) { + SkillsBase sb = SkillsBase.getFromCache(name); + if (sb != null) { + return sb; + } + prepareCallable("SELECT * FROM static_skill_skillsbase WHERE name = ?"); + setString(1, name); + ArrayList result = getObjectList(); + if (result.size() > 0) { + sb = (SkillsBase) result.get(0); + SkillsBase.putInCache(sb); + return sb; + } else { + return null; + } + } + + public SkillsBase GET_BASE_BY_TOKEN(final int token) { + SkillsBase sb = SkillsBase.getFromCache(token); + if (sb != null) { + return sb; + } + + prepareCallable("SELECT * FROM static_skill_skillsbase WHERE token = ?"); + setInt(1, token); + ArrayList result = getObjectList(); + if (result.size() > 0) { + sb = (SkillsBase) result.get(0); + SkillsBase.putInCache(sb); + return sb; + } else { + return null; + } + } + + public void LOAD_ALL_MAX_SKILLS_FOR_CONTRACT() { + + prepareCallable("SELECT * FROM `static_rune_maxskills`"); + + + try { + ResultSet rs = executeQuery(); + + //shrines cached in rs for easy cache on creation. + while (rs.next()) { + + MaxSkills maxSKills = new MaxSkills(rs); + if (MaxSkills.MaxSkillsSet.get(maxSKills.getRuneID()) == null) { + ArrayList newMaxSkillsList = new ArrayList<>(); + newMaxSkillsList.add(maxSKills); + MaxSkills.MaxSkillsSet.put(maxSKills.getRuneID(), newMaxSkillsList); + } else + MaxSkills.MaxSkillsSet.get(maxSKills.getRuneID()).add(maxSKills); + + } + + + } catch (SQLException e) { + Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); + } finally { + closeCallable(); + } + + } + + public void LOAD_ALL_RUNE_SKILLS() { + + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_skill_skillsgranted`")) { + + ResultSet rs = preparedStatement.executeQuery(); + + while (rs.next()) { + + int runeID = rs.getInt("runeID"); + int token = rs.getInt("token"); + int amount = rs.getInt("amount"); + + if (SkillsBase.runeSkillsCache.get(runeID) == null) + SkillsBase.runeSkillsCache.put(runeID, new HashMap<>()); + + SkillsBase.runeSkillsCache.get(runeID).put(token, amount); + } + + } catch (SQLException e) { + Logger.error(e); + } + } } diff --git a/src/engine/db/handlers/dbVendorDialogHandler.java b/src/engine/db/handlers/dbVendorDialogHandler.java index eb6a1c92..8bcc40ee 100644 --- a/src/engine/db/handlers/dbVendorDialogHandler.java +++ b/src/engine/db/handlers/dbVendorDialogHandler.java @@ -21,30 +21,30 @@ import java.sql.SQLException; public class dbVendorDialogHandler extends dbHandlerBase { - public dbVendorDialogHandler() { - this.localClass = VendorDialog.class; - this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); - } + public dbVendorDialogHandler() { + this.localClass = VendorDialog.class; + this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); + } - public VendorDialog GET_VENDORDIALOG(final int objectUUID) { + public VendorDialog GET_VENDORDIALOG(final int objectUUID) { - VendorDialog vendorDialog = (VendorDialog) DbManager.getFromCache(Enum.GameObjectType.VendorDialog, objectUUID); + VendorDialog vendorDialog = (VendorDialog) DbManager.getFromCache(Enum.GameObjectType.VendorDialog, objectUUID); - if (vendorDialog != null) - return vendorDialog; + if (vendorDialog != null) + return vendorDialog; - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_vendordialog` WHERE `ID`=?")) { + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_vendordialog` WHERE `ID`=?")) { - preparedStatement.setInt(1, objectUUID); + preparedStatement.setInt(1, objectUUID); - ResultSet rs = preparedStatement.executeQuery(); - vendorDialog = (VendorDialog) getObjectFromRs(rs); + ResultSet rs = preparedStatement.executeQuery(); + vendorDialog = (VendorDialog) getObjectFromRs(rs); - } catch (SQLException e) { - Logger.error(e); - } + } catch (SQLException e) { + Logger.error(e); + } - return vendorDialog; - } + return vendorDialog; + } } diff --git a/src/engine/db/handlers/dbZoneHandler.java b/src/engine/db/handlers/dbZoneHandler.java index 9950f31f..8b6b603f 100644 --- a/src/engine/db/handlers/dbZoneHandler.java +++ b/src/engine/db/handlers/dbZoneHandler.java @@ -11,6 +11,8 @@ package engine.db.handlers; import engine.Enum; import engine.gameManager.DbManager; +import engine.gameManager.ZoneManager; +import engine.math.Vector2f; import engine.objects.Zone; import org.pmw.tinylog.Logger; @@ -77,7 +79,7 @@ public class dbZoneHandler extends dbHandlerBase { try (Connection connection = DbManager.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_zone`.*, `object`.`parent` FROM `object` INNER JOIN `obj_zone` ON `obj_zone`.`UID` = `object`.`UID` WHERE `object`.`parent` = ?;")) { - preparedStatement.setLong(1, (long) objectUUID); + preparedStatement.setLong(1, objectUUID); ResultSet rs = preparedStatement.executeQuery(); zoneList = getObjectsFromRs(rs, 2000); @@ -89,19 +91,24 @@ public class dbZoneHandler extends dbHandlerBase { return zoneList; } - public ResultSet GET_ZONE_EXTENTS(final int loadNum) { + public void LOAD_ZONE_EXTENTS() { try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_zone_size` WHERE `loadNum`=?;")) { + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_zone_size`;")) { - preparedStatement.setInt(1, loadNum); + ResultSet rs = preparedStatement.executeQuery(); - return preparedStatement.executeQuery(); + while (rs.next()) { + Vector2f zoneSize = new Vector2f(); + int loadNum = rs.getInt("loadNum"); + zoneSize.x = rs.getFloat("xRadius"); + zoneSize.y = rs.getFloat("zRadius"); + ZoneManager._zone_size_data.put(loadNum, zoneSize); + } } catch (SQLException e) { Logger.error(e); } - return null; } public boolean DELETE_ZONE(final Zone zone) { diff --git a/src/engine/gameManager/ZoneManager.java b/src/engine/gameManager/ZoneManager.java index f4e2f434..896c8fd1 100644 --- a/src/engine/gameManager/ZoneManager.java +++ b/src/engine/gameManager/ZoneManager.java @@ -24,10 +24,7 @@ import org.pmw.tinylog.Logger; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Set; +import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadLocalRandom; @@ -39,17 +36,18 @@ public enum ZoneManager { ZONEMANAGER; - public static Instant hotZoneLastUpdate; - /* Instance variables */ - private static Zone seaFloor = null; - public static Zone hotZone = null; - public static int hotZoneCycle = 0; // Used with HOTZONE_DURATION from config. + public static final Set macroZones = Collections.newSetFromMap(new ConcurrentHashMap<>()); private static final ConcurrentHashMap zonesByID = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD); private static final ConcurrentHashMap zonesByUUID = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD); private static final ConcurrentHashMap zonesByName = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD); - public static final Set macroZones = Collections.newSetFromMap(new ConcurrentHashMap<>()); private static final Set npcCityZones = Collections.newSetFromMap(new ConcurrentHashMap<>()); private static final Set playerCityZones = Collections.newSetFromMap(new ConcurrentHashMap<>()); + public static Instant hotZoneLastUpdate; + public static Zone hotZone = null; + public static int hotZoneCycle = 0; // Used with HOTZONE_DURATION from config. + public static HashMap _zone_size_data = new HashMap<>(); + /* Instance variables */ + private static Zone seaFloor = null; // Find all zones coordinates fit into, starting with Sea Floor @@ -170,14 +168,14 @@ public enum ZoneManager { return (Bounds.collide(loc, ZoneManager.hotZone.getBounds()) == true); } - public static void setSeaFloor(final Zone value) { - ZoneManager.seaFloor = value; - } - public static Zone getSeaFloor() { return ZoneManager.seaFloor; } + public static void setSeaFloor(final Zone value) { + ZoneManager.seaFloor = value; + } + public static final void populateWorldZones(final Zone zone) { int loadNum = zone.getLoadNum(); diff --git a/src/engine/objects/Zone.java b/src/engine/objects/Zone.java index 5f04cc74..8fddf5d5 100644 --- a/src/engine/objects/Zone.java +++ b/src/engine/objects/Zone.java @@ -30,19 +30,25 @@ import java.util.concurrent.ConcurrentHashMap; public class Zone extends AbstractGameObject { + public final Set zoneBuildingSet = Collections.newSetFromMap(new ConcurrentHashMap<>()); + public final Set zoneNPCSet = Collections.newSetFromMap(new ConcurrentHashMap<>()); + public final Set zoneMobSet = Collections.newSetFromMap(new ConcurrentHashMap<>()); private final int playerCityID; private final String zoneName; private final float xCoord; private final float zCoord; private final float yCoord; - public float absX = 0.0f; - public float absY = 0.0f; - public float absZ = 0.0f; private final int loadNum; private final byte safeZone; private final String Icon1; private final String Icon2; private final String Icon3; + public float absX = 0.0f; + public float absY = 0.0f; + public float absZ = 0.0f; + public int minLvl; + public int maxLvl; + public boolean hasBeenHotzone = false; private ArrayList nodes = null; private int parentZoneID; private Zone parent = null; @@ -50,16 +56,9 @@ public class Zone extends AbstractGameObject { private boolean isNPCCity = false; private boolean isPlayerCity = false; private String hash; - public int minLvl; - public int maxLvl; - private float worldAltitude = 0; - private float seaLevel = 0; - public final Set zoneBuildingSet = Collections.newSetFromMap(new ConcurrentHashMap<>()); - public final Set zoneNPCSet = Collections.newSetFromMap(new ConcurrentHashMap<>()); - public final Set zoneMobSet = Collections.newSetFromMap(new ConcurrentHashMap<>()); - public boolean hasBeenHotzone = false; + /** * ResultSet Constructor */ @@ -87,7 +86,7 @@ public class Zone extends AbstractGameObject { this.setParent(parentZone); - if (this.minLvl == 0 && parentZone != null){ + if (this.minLvl == 0 && parentZone != null) { this.minLvl = parentZone.minLvl; this.maxLvl = parentZone.maxLvl; } @@ -99,10 +98,63 @@ public class Zone extends AbstractGameObject { if (hash == null) setHash(); - + } + public static void serializeForClientMsg(Zone zone, ByteBufferWriter writer) { + + if (zone.loadNum == 0 && zone.playerCityID == 0) + Logger.warn("Warning! WorldServerMap with ID " + zone.getObjectUUID() + " has a loadnum of 0 (player city) and no city linked. This will probably crash the client!"); + + // Player City Terraform values serialized here. + + if (zone.playerCityID > 0) { + writer.put((byte) 1); // Player City - True + writer.putFloat(Enum.CityBoundsType.ZONE.extents); + writer.putFloat(Enum.CityBoundsType.ZONE.extents); + } else + writer.put((byte) 0); // Player City - False + + writer.putFloat(zone.xCoord); + writer.putFloat(zone.zCoord); + writer.putFloat(zone.yCoord); + + writer.putInt(0); + writer.putInt(0); + writer.putInt(zone.loadNum); + + if (zone.playerCityID > 0) { + City k = City.getCity(zone.playerCityID); + + if (k != null) { + writer.putInt(k.getObjectType().ordinal()); + writer.putInt(k.getObjectUUID()); + } else + writer.putLong(0x0); + } else { + writer.putInt(zone.getObjectType().ordinal()); + writer.putInt(zone.getObjectUUID()); + } + writer.putInt(zone.nodes.size()); + + City city = City.getCity(zone.playerCityID); + + if (city != null) + writer.putString(city.getCityName()); + else + writer.putString(zone.zoneName); + writer.put(zone.safeZone); + writer.putString(zone.Icon1); + writer.putString(zone.Icon2); + writer.putString(zone.Icon3); + writer.put((byte) 0); // Pad + + for (Zone child : zone.nodes) { + Zone.serializeForClientMsg(child, writer); + } + } + /* Method sets a default value for player cities * otherwise using values derived from the loadnum * field in the obj_zone database table. @@ -123,38 +175,18 @@ public class Zone extends AbstractGameObject { return; } - // All other zones have bounding boxes loaded from database - ResultSet rs = DbManager.ZoneQueries.GET_ZONE_EXTENTS(this.loadNum); - boolean loaded = false; - - if (rs != null) - try { - if (rs.next()) { - halfExtentX = rs.getFloat("xRadius"); - halfExtentY = rs.getFloat("zRadius"); - this.bounds.setBounds(new Vector2f(this.absX, this.absZ), new Vector2f(halfExtentX, halfExtentY), 0.0f); - loaded = true; - } + Vector2f zoneSize = ZoneManager._zone_size_data.get(this.loadNum); - } catch (SQLException e) { - Logger.error("SQLException: " + e.getMessage()); - } - - if (!loaded) { - - // Default to Citygrid size on error + // Default to player zone size on error? Maybe log this + if (zoneSize != null) + this.bounds.setBounds(new Vector2f(this.absX, this.absZ), zoneSize, 0.0f); + else bounds.setBounds(new Vector2f(this.absX, this.absZ), new Vector2f(Enum.CityBoundsType.ZONE.extents, Enum.CityBoundsType.ZONE.extents), 0.0f); - } } - /* - * Getters - */ public int getPlayerCityUUID() { - if (this.playerCityID == 0) - return 0; return this.playerCityID; } @@ -178,10 +210,6 @@ public class Zone extends AbstractGameObject { return loadNum; } - public int getLoadNumClient() { - return loadNum; - } - public byte getSafeZone() { return safeZone; } @@ -190,45 +218,9 @@ public class Zone extends AbstractGameObject { return Icon1; } - public String getIcon2() { - return Icon2; - } - - public String getIcon3() { - return Icon3; - } + public void generateWorldAltitude() { - public void setParent(final Zone value) { - - this.parent = value; - this.parentZoneID = (this.parent != null) ? this.parent.getObjectUUID() : 0; - - if (this.parent != null) { - this.absX = this.xCoord + parent.absX; - this.absY = this.yCoord + parent.absY; - this.absZ = this.zCoord + parent.absZ; - - if (this.minLvl == 0 || this.maxLvl == 0){ - this.minLvl = this.parent.minLvl; - this.maxLvl = this.parent.maxLvl; - } - } else { //only the Sea Floor zone does not have a parent - this.absX = this.xCoord; - this.absY = MBServerStatics.SEA_FLOOR_ALTITUDE; - this.absZ = this.zCoord; - } - - // Zone AABB is set here as it's coordinate space is world requiring a parent. - this.setBounds(); - - if (this.getHeightMap() != null && this.getHeightMap().getSeaLevel() != 0) - this.seaLevel = this.getHeightMap().getSeaLevel(); - - } - - public void generateWorldAltitude(){ - - if (ZoneManager.getSeaFloor().getObjectUUID() == this.getObjectUUID()){ + if (ZoneManager.getSeaFloor().getObjectUUID() == this.getObjectUUID()) { this.worldAltitude = MBServerStatics.SEA_FLOOR_ALTITUDE; return; } @@ -240,9 +232,9 @@ public class Zone extends AbstractGameObject { //seafloor only zone with null parent; - while(parentZone != ZoneManager.getSeaFloor()){ + while (parentZone != ZoneManager.getSeaFloor()) { - if(parentZone.getHeightMap() != null){ + if (parentZone.getHeightMap() != null) { Vector2f zoneLoc = ZoneManager.worldToZoneSpace(currentZone.getLoc(), parentZone); altitude += parentZone.getHeightMap().getInterpolatedTerrainHeight(zoneLoc); @@ -258,14 +250,14 @@ public class Zone extends AbstractGameObject { if (ZoneManager.getSeaFloor().equals(this)) this.seaLevel = 0; else if - (this.getHeightMap() != null && this.getHeightMap().getSeaLevel() == 0){ - this.seaLevel = this.parent.seaLevel; + (this.getHeightMap() != null && this.getHeightMap().getSeaLevel() == 0) { + this.seaLevel = this.parent.seaLevel; - }else if (this.getHeightMap() != null){ + } else if (this.getHeightMap() != null) { this.seaLevel = this.worldAltitude + this.getHeightMap().getSeaLevel(); - }else { - this.seaLevel = this.parent.seaLevel; - } + } else { + this.seaLevel = this.parent.seaLevel; + } } @@ -273,6 +265,34 @@ public class Zone extends AbstractGameObject { return this.parent; } + public void setParent(final Zone value) { + + this.parent = value; + this.parentZoneID = (this.parent != null) ? this.parent.getObjectUUID() : 0; + + if (this.parent != null) { + this.absX = this.xCoord + parent.absX; + this.absY = this.yCoord + parent.absY; + this.absZ = this.zCoord + parent.absZ; + + if (this.minLvl == 0 || this.maxLvl == 0) { + this.minLvl = this.parent.minLvl; + this.maxLvl = this.parent.maxLvl; + } + } else { //only the Sea Floor zone does not have a parent + this.absX = this.xCoord; + this.absY = MBServerStatics.SEA_FLOOR_ALTITUDE; + this.absZ = this.zCoord; + } + + // Zone AABB is set here as it's coordinate space is world requiring a parent. + this.setBounds(); + + if (this.getHeightMap() != null && this.getHeightMap().getSeaLevel() != 0) + this.seaLevel = this.getHeightMap().getSeaLevel(); + + } + public float getAbsX() { return this.absX; } @@ -302,14 +322,14 @@ public class Zone extends AbstractGameObject { return this.isNPCCity; } - public boolean isPlayerCity() { - return this.isPlayerCity; - } - public void setNPCCity(boolean value) { this.isNPCCity = value; } + public boolean isPlayerCity() { + return this.isPlayerCity; + } + public void setPlayerCity(boolean value) { this.isPlayerCity = value; } @@ -336,67 +356,12 @@ public class Zone extends AbstractGameObject { return nodes; } - public void addNode(Zone child) { - this.nodes.add(child); - } - /* * Serializing */ - - public static void serializeForClientMsg(Zone zone,ByteBufferWriter writer) { - - if (zone.loadNum == 0 && zone.playerCityID == 0) - Logger.warn( "Warning! WorldServerMap with ID " + zone.getObjectUUID() + " has a loadnum of 0 (player city) and no city linked. This will probably crash the client!"); - - // Player City Terraform values serialized here. - - if (zone.playerCityID > 0) { - writer.put((byte) 1); // Player City - True - writer.putFloat(Enum.CityBoundsType.ZONE.extents); - writer.putFloat(Enum.CityBoundsType.ZONE.extents); - } else - writer.put((byte) 0); // Player City - False - - writer.putFloat(zone.xCoord); - writer.putFloat(zone.zCoord); - writer.putFloat(zone.yCoord); - - writer.putInt(0); - writer.putInt(0); - writer.putInt(zone.loadNum); - - if (zone.playerCityID > 0) { - City k = City.getCity(zone.playerCityID); - - if (k != null) { - writer.putInt(k.getObjectType().ordinal()); - writer.putInt(k.getObjectUUID()); - } - else - writer.putLong(0x0); - } else { - writer.putInt(zone.getObjectType().ordinal()); - writer.putInt(zone.getObjectUUID()); - } - writer.putInt(zone.nodes.size()); - - City city = City.getCity(zone.playerCityID); - - if (city != null) - writer.putString(city.getCityName()); - else - writer.putString(zone.zoneName); - writer.put(zone.safeZone); - writer.putString(zone.Icon1); - writer.putString(zone.Icon2); - writer.putString(zone.Icon3); - writer.put((byte) 0); // Pad - - for (Zone child : zone.nodes) { - Zone.serializeForClientMsg(child,writer); - } + public void addNode(Zone child) { + this.nodes.add(child); } @Override @@ -442,7 +407,7 @@ public class Zone extends AbstractGameObject { // Return heightmap for this Zone. public HeightMap getHeightMap() { - + if (this.isPlayerCity) return HeightMap.PlayerCityHeightMap; From 3761384dfb98427b579b06b47d40452d7a7ad798 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 10:32:07 -0400 Subject: [PATCH 091/109] Bugfix; method is on rs. --- src/engine/db/handlers/dbBuildingHandler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/engine/db/handlers/dbBuildingHandler.java b/src/engine/db/handlers/dbBuildingHandler.java index 8894e118..3eaeb8c1 100644 --- a/src/engine/db/handlers/dbBuildingHandler.java +++ b/src/engine/db/handlers/dbBuildingHandler.java @@ -662,7 +662,7 @@ public class dbBuildingHandler extends dbHandlerBase { ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) - storedEnum = DbObjectType.valueOf(getString("type").toUpperCase()); + storedEnum = DbObjectType.valueOf(rs.getString("type").toUpperCase()); } catch (SQLException e) { Logger.error("Building", e); From c6b8d27d537c28849add2043dadedd26c7154df4 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 10:42:34 -0400 Subject: [PATCH 092/109] Refactor to remove abstraction. --- .../db/handlers/dbPlayerCharacterHandler.java | 1 - .../db/handlers/dbSkillBaseHandler.java | 103 ++++++++++-------- 2 files changed, 59 insertions(+), 45 deletions(-) diff --git a/src/engine/db/handlers/dbPlayerCharacterHandler.java b/src/engine/db/handlers/dbPlayerCharacterHandler.java index a716f05a..06a4d595 100644 --- a/src/engine/db/handlers/dbPlayerCharacterHandler.java +++ b/src/engine/db/handlers/dbPlayerCharacterHandler.java @@ -512,7 +512,6 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { Logger.error(e); } - prepareCallable("SELECT * FROM dyn_character_friends"); } public boolean ADD_HERALDY(int source, AbstractWorldObject character) { diff --git a/src/engine/db/handlers/dbSkillBaseHandler.java b/src/engine/db/handlers/dbSkillBaseHandler.java index 77e55fdf..3bfdefe6 100644 --- a/src/engine/db/handlers/dbSkillBaseHandler.java +++ b/src/engine/db/handlers/dbSkillBaseHandler.java @@ -12,7 +12,6 @@ package engine.db.handlers; import engine.Enum; import engine.Enum.GameObjectType; import engine.gameManager.DbManager; -import engine.objects.AbstractGameObject; import engine.objects.MaxSkills; import engine.objects.SkillsBase; import org.pmw.tinylog.Logger; @@ -34,63 +33,83 @@ public class dbSkillBaseHandler extends dbHandlerBase { public SkillsBase GET_BASE(final int objectUUID) { SkillsBase skillsBase = (SkillsBase) DbManager.getFromCache(GameObjectType.SkillsBase, objectUUID); + if (skillsBase != null) return skillsBase; - prepareCallable("SELECT * FROM static_skill_skillsbase WHERE ID = ?"); - setInt(1, objectUUID); - SkillsBase sb; - sb = (SkillsBase) getObjectSingle(objectUUID); - SkillsBase.putInCache(sb); - return sb; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_skill_skillsbase WHERE ID = ?")) { + + preparedStatement.setInt(1, objectUUID); + ResultSet rs = preparedStatement.executeQuery(); + + skillsBase = (SkillsBase) getObjectFromRs(rs); + + } catch (SQLException e) { + Logger.error(e); + } + + SkillsBase.putInCache(skillsBase); + return skillsBase; } public SkillsBase GET_BASE_BY_NAME(String name) { - SkillsBase sb = SkillsBase.getFromCache(name); - if (sb != null) { - return sb; - } - prepareCallable("SELECT * FROM static_skill_skillsbase WHERE name = ?"); - setString(1, name); - ArrayList result = getObjectList(); - if (result.size() > 0) { - sb = (SkillsBase) result.get(0); - SkillsBase.putInCache(sb); - return sb; - } else { - return null; + + SkillsBase skillsBase = SkillsBase.getFromCache(name); + + if (skillsBase != null) + return skillsBase; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_skill_skillsbase WHERE name = ?")) { + + preparedStatement.setString(1, name); + ResultSet rs = preparedStatement.executeQuery(); + + skillsBase = (SkillsBase) getObjectFromRs(rs); + + } catch (SQLException e) { + Logger.error(e); } + + SkillsBase.putInCache(skillsBase); + return skillsBase; } public SkillsBase GET_BASE_BY_TOKEN(final int token) { - SkillsBase sb = SkillsBase.getFromCache(token); - if (sb != null) { - return sb; - } - prepareCallable("SELECT * FROM static_skill_skillsbase WHERE token = ?"); - setInt(1, token); - ArrayList result = getObjectList(); - if (result.size() > 0) { - sb = (SkillsBase) result.get(0); - SkillsBase.putInCache(sb); - return sb; - } else { - return null; + SkillsBase skillsBase = SkillsBase.getFromCache(token); + + if (skillsBase != null) + return skillsBase; + + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_skill_skillsbase WHERE token = ?")) { + + preparedStatement.setInt(1, token); + ResultSet rs = preparedStatement.executeQuery(); + + skillsBase = (SkillsBase) getObjectFromRs(rs); + + } catch (SQLException e) { + Logger.error(e); } + + SkillsBase.putInCache(skillsBase); + return skillsBase; } public void LOAD_ALL_MAX_SKILLS_FOR_CONTRACT() { - prepareCallable("SELECT * FROM `static_rune_maxskills`"); - + try (Connection connection = DbManager.getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_maxskills`")) { - try { - ResultSet rs = executeQuery(); + ResultSet rs = preparedStatement.executeQuery(); - //shrines cached in rs for easy cache on creation. while (rs.next()) { MaxSkills maxSKills = new MaxSkills(rs); + if (MaxSkills.MaxSkillsSet.get(maxSKills.getRuneID()) == null) { ArrayList newMaxSkillsList = new ArrayList<>(); newMaxSkillsList.add(maxSKills); @@ -100,17 +119,13 @@ public class dbSkillBaseHandler extends dbHandlerBase { } - } catch (SQLException e) { - Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); - } finally { - closeCallable(); + Logger.error(e); } - } - public void LOAD_ALL_RUNE_SKILLS() { + public void LOAD_ALL_RUNE_SKILLS() { try (Connection connection = DbManager.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_skill_skillsgranted`")) { From 391e2d2a172f0661b7ab560361414266cb1c4030 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 10:50:00 -0400 Subject: [PATCH 093/109] Cleanup post db-refactor. --- src/engine/db/handlers/dbBuildingHandler.java | 8 +- .../db/handlers/dbCSSessionHandler.java | 3 +- src/engine/db/handlers/dbCityHandler.java | 7 +- src/engine/db/handlers/dbHandlerBase.java | 414 +----------------- 4 files changed, 10 insertions(+), 422 deletions(-) diff --git a/src/engine/db/handlers/dbBuildingHandler.java b/src/engine/db/handlers/dbBuildingHandler.java index 3eaeb8c1..3f574f49 100644 --- a/src/engine/db/handlers/dbBuildingHandler.java +++ b/src/engine/db/handlers/dbBuildingHandler.java @@ -61,11 +61,11 @@ public class dbBuildingHandler extends dbHandlerBase { if (upgradeDate != null) preparedStatement.setTimestamp(13, new java.sql.Timestamp(upgradeDate.getMillis())); else - setNULL(13, java.sql.Types.DATE); + preparedStatement.setNull(13, java.sql.Types.DATE); - setInt(14, blueprintUUID); - setFloat(15, w); - setFloat(16, rotY); + preparedStatement.setInt(14, blueprintUUID); + preparedStatement.setFloat(15, w); + preparedStatement.setFloat(16, rotY); ResultSet rs = preparedStatement.executeQuery(); diff --git a/src/engine/db/handlers/dbCSSessionHandler.java b/src/engine/db/handlers/dbCSSessionHandler.java index b56341cc..ae6cc04f 100644 --- a/src/engine/db/handlers/dbCSSessionHandler.java +++ b/src/engine/db/handlers/dbCSSessionHandler.java @@ -103,8 +103,7 @@ public class dbCSSessionHandler extends dbHandlerBase { ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) - css = new CSSession(secKey, DbManager.AccountQueries.GET_ACCOUNT(rs.getInt("accountID")), PlayerCharacter.getPlayerCharacter(rs - .getInt("characterID")), getString("machineID")); + css = new CSSession(secKey, DbManager.AccountQueries.GET_ACCOUNT(rs.getInt("accountID")), PlayerCharacter.getPlayerCharacter(rs.getInt("characterID")), rs.getString("machineID")); } catch (SQLException e) { Logger.error(e); diff --git a/src/engine/db/handlers/dbCityHandler.java b/src/engine/db/handlers/dbCityHandler.java index 9097e005..bf3d9d98 100644 --- a/src/engine/db/handlers/dbCityHandler.java +++ b/src/engine/db/handlers/dbCityHandler.java @@ -69,13 +69,14 @@ public class dbCityHandler extends dbHandlerBase { preparedStatement.setFloat(10, W); preparedStatement.setTimestamp(11, Timestamp.valueOf(upgradeTime)); - boolean work = execute(); + boolean work = preparedStatement.execute(); if (work) { + ResultSet rs = preparedStatement.getResultSet(); - while (rs.next()) { + + while (rs.next()) addObject(objectList, rs); - } rs.close(); } else { Logger.info("City Placement Failed: " + preparedStatement); diff --git a/src/engine/db/handlers/dbHandlerBase.java b/src/engine/db/handlers/dbHandlerBase.java index 8de040d2..e16b49ca 100644 --- a/src/engine/db/handlers/dbHandlerBase.java +++ b/src/engine/db/handlers/dbHandlerBase.java @@ -9,287 +9,20 @@ package engine.db.handlers; -import engine.Enum; import engine.Enum.GameObjectType; -import engine.gameManager.ConfigManager; import engine.gameManager.DbManager; import engine.objects.AbstractGameObject; import engine.objects.AbstractWorldObject; -import engine.server.MBServerStatics; import org.pmw.tinylog.Logger; -import java.sql.*; -import java.time.LocalDateTime; +import java.sql.ResultSet; import java.util.ArrayList; -import java.util.HashSet; public abstract class dbHandlerBase { - protected final ThreadLocal callableStatement = new ThreadLocal<>(); - protected final ThreadLocal connection = new ThreadLocal<>(); - /* - * CallableStatements handled below this line! - */ protected Class localClass = null; protected GameObjectType localObjectType; - protected final void prepareCallable(final String sql) { - try { - this.connection.set(DbManager.getConnection()); - this.callableStatement.set(this.connection.get().prepareCall(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)); - } catch (SQLException e) { - Logger.error("DbManager.getConn", e); - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - - protected final void setInt(int parameterIndex, int value) { - try { - this.callableStatement.get().setInt(parameterIndex, value); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - - protected final void setLong(int parameterIndex, long value) { - try { - this.callableStatement.get().setLong(parameterIndex, value); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - - protected final void setFloat(int parameterIndex, float value) { - try { - this.callableStatement.get().setFloat(parameterIndex, value); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - - protected final void setShort(int parameterIndex, short value) { - try { - this.callableStatement.get().setShort(parameterIndex, value); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - - protected final void setString(int parameterIndex, String value) { - try { - this.callableStatement.get().setString(parameterIndex, value); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - - protected final void setByte(int parameterIndex, byte value) { - try { - this.callableStatement.get().setByte(parameterIndex, value); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - - protected final void setBoolean(int parameterIndex, boolean value) { - try { - this.callableStatement.get().setBoolean(parameterIndex, value); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - - protected final void setNULL(int parameterIndex, int type) { - try { - this.callableStatement.get().setNull(parameterIndex, type); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - - protected final void setLocalDateTime(int parameterIndex, LocalDateTime localDateTime) { - - try { - this.callableStatement.get().setTimestamp(parameterIndex, Timestamp.valueOf(localDateTime)); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - - protected final void setTimeStamp(int parameterIndex, long time) { - try { - this.callableStatement.get().setTimestamp(parameterIndex, new java.sql.Timestamp(time)); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } - } - - protected final boolean execute() { - try { - return this.callableStatement.get().execute(); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - logSQLCommand(); - } - return false; - } - - protected final ResultSet executeQuery() { - try { - return this.callableStatement.get().executeQuery(); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - logSQLCommand(); - } - return null; - } - - protected final int executeUpdate() { - return executeUpdate(true); - } - - protected final int executeUpdate(boolean close) { - try { - return this.callableStatement.get().executeUpdate(); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - logSQLCommand(); - } finally { - if (close) - closeCallable(); - } - return 0; - } - - protected final void logSQLCommand() { - try { - Logger.error("Failed SQL Command: " + this.callableStatement.get().toString()); - } catch (Exception e) { - - } - } - - // Common return values from the database when calling stored procedures, abstracted to this layer - protected final String getResult() { - try { - ResultSet rs = this.executeQuery(); - if (rs.next() && !isError(rs)) - return rs.getString("result"); - } catch (SQLException e) { - Logger.error(e); - logSQLCommand(); - } finally { - closeCallable(); - } - return null; - } - - // Used for Stored procedures that return true when they succeed. - protected final boolean worked() { - try { - ResultSet rs = this.executeQuery(); - if (rs.next() && !isError(rs)) - return rs.getBoolean("result"); - } catch (SQLException e) { - Logger.error(e); - logSQLCommand(); - } finally { - closeCallable(); - } - return false; - } - - // Common return values from the database when calling stored procedures, abstracted to this layer - protected final long getUUID() { - try { - ResultSet rs = this.executeQuery(); - if (rs.next() && !isError(rs)) - return rs.getLong("UID"); - } catch (SQLException e) { - Logger.error(e); - logSQLCommand(); - } finally { - closeCallable(); - } - return -1; - } - - protected final String getString(String field) { - try { - ResultSet rs = this.executeQuery(); - if (rs.next()) - return rs.getString(field); - } catch (SQLException e) { - Logger.error(e); - logSQLCommand(); - } finally { - closeCallable(); - } - return ""; - } - - protected final long getLong(String field) { - try { - ResultSet rs = this.executeQuery(); - if (rs.next()) - return rs.getLong(field); - } catch (SQLException e) { - Logger.error(e); - logSQLCommand(); - } finally { - closeCallable(); - } - return 0L; - } - - protected final int getInt(String field) { - try { - ResultSet rs = this.executeQuery(); - if (rs.next()) - return rs.getInt(field); - } catch (SQLException e) { - Logger.error(e); - logSQLCommand(); - } finally { - closeCallable(); - } - return 0; - } - - protected final int insertGetUUID() { - int key = 0; - try { - this.callableStatement.get().executeUpdate(); - ResultSet rs = this.callableStatement.get().getGeneratedKeys(); - if (rs.next()) - key = rs.getInt(1); - } catch (SQLException e) { - Logger.error(e); - logSQLCommand(); - } finally { - closeCallable(); - } - return key; - } - - protected final boolean isError(ResultSet rs) throws SQLException { - ResultSetMetaData rsmd = rs.getMetaData(); - if (rsmd.getColumnCount() > 0 && !rsmd.getColumnName(1).equals("errorno")) - return false; - printError(rs); - return true; - } - - protected final void printError(ResultSet rs) { - try { - int errorNum = rs.getInt("errorno"); - String errorMsg = rs.getString("errormsg"); - Logger.error("SQLError: errorNum: " + errorNum + ", errorMsg: " + errorMsg); - logSQLCommand(); - } catch (SQLException e) { - } - } - protected AbstractGameObject getObjectFromRs(ResultSet rs) { AbstractGameObject abstractGameObject = null; @@ -331,150 +64,5 @@ public abstract class dbHandlerBase { Logger.error(e); } return objectList; - - } - - protected AbstractGameObject getObjectSingle(int id) { - return getObjectSingle(id, false, true); - } - - protected AbstractGameObject getObjectSingle(int id, boolean forceFromDB, boolean storeInCache) { - - if (callableStatement.get() == null) { - return null; - } - - if (!forceFromDB) { - if (DbManager.inCache(localObjectType, id)) { - closeCallable(); - return DbManager.getFromCache(localObjectType, id); - } - } - - AbstractGameObject out = null; - - try { - if (MBServerStatics.DB_ENABLE_QUERY_OUTPUT) - Logger.info("[GetObjectList] Executing query:" + callableStatement.get().toString()); - - ResultSet rs = callableStatement.get().executeQuery(); - - if (rs.next()) { - out = localClass.getConstructor(ResultSet.class).newInstance(rs); - - if (storeInCache) - DbManager.addToCache(out); - } - - rs.close(); - - } catch (Exception e) { - Logger.error("AbstractGameObject", e); - out = null; - } finally { - closeCallable(); - } - - // Only call runAfterLoad() for objects instanced on the world server - - if ((out != null && out instanceof AbstractWorldObject) && - (ConfigManager.serverType.equals(Enum.ServerType.WORLDSERVER) || - (out.getObjectType() == GameObjectType.Guild))) - ((AbstractWorldObject) out).runAfterLoad(); - - return out; - } - - protected void closeCallable() { - try { - if (this.callableStatement.get() != null) - this.callableStatement.get().close(); - - this.connection.get().close(); - - } catch (SQLException e) { - } - } - - protected ArrayList getObjectList() { - return getObjectList(20, false); - } - - protected ArrayList getLargeObjectList() { - return getObjectList(2000, false); - } - - @SuppressWarnings("unchecked") - protected ArrayList getObjectList(int listSize, boolean forceFromDB) { - - String query = "No Callable Statement accessable."; - - ArrayList out = new ArrayList<>(listSize); - - if (this.callableStatement.get() == null) - return out; - - try { - - CallableStatement css = this.callableStatement.get(); - - if (css != null) - query = this.callableStatement.get().toString(); - - if (MBServerStatics.DB_ENABLE_QUERY_OUTPUT) - Logger.info("[GetObjectList] Executing query:" + query); - - ResultSet rs = this.callableStatement.get().executeQuery(); - - while (rs.next()) { - - int id = rs.getInt(1); - - if (!forceFromDB && DbManager.inCache(localObjectType, id)) { - out.add((T) DbManager.getFromCache(localObjectType, id)); - } else { - AbstractGameObject toAdd = localClass.getConstructor(ResultSet.class).newInstance(rs); - DbManager.addToCache(toAdd); - out.add((T) toAdd); - - if (toAdd != null && toAdd instanceof AbstractWorldObject) - ((AbstractWorldObject) toAdd).runAfterLoad(); - - } - } - rs.close(); - } catch (Exception e) { - Logger.error(localClass.getCanonicalName(), "List Failure: " + query, e); - e.printStackTrace(); - return new ArrayList<>(); // Do we want a null return on error? - } finally { - closeCallable(); - } - - return out; - } - - /* Prepared Statements handled below this line */ - - protected HashSet getIntegerList(final int columnNumber) { - - if (MBServerStatics.DB_ENABLE_QUERY_OUTPUT) - Logger.info("[GetIntegerList] Executing query:" + this.callableStatement); - - HashSet out = new HashSet<>(); - - try { - ResultSet rs = executeQuery(); - - while (rs.next()) { - out.add(rs.getInt(columnNumber)); - } - rs.close(); - } catch (SQLException e) { - Logger.error("SQL Error number: " + e.getErrorCode()); - } finally { - closeCallable(); - } - return out; } } From 38ed65054edbb2a906f3b077e12fedd22cb4232d Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 10:56:27 -0400 Subject: [PATCH 094/109] Cleanup post db-refactor. --- src/engine/db/handlers/dbBuildingHandler.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/engine/db/handlers/dbBuildingHandler.java b/src/engine/db/handlers/dbBuildingHandler.java index 3f574f49..34387911 100644 --- a/src/engine/db/handlers/dbBuildingHandler.java +++ b/src/engine/db/handlers/dbBuildingHandler.java @@ -650,6 +650,7 @@ public class dbBuildingHandler extends dbHandlerBase { public final DbObjectType GET_UID_ENUM(long object_UID) { DbObjectType storedEnum = DbObjectType.INVALID; + String objectType = "INVALID"; if (object_UID == 0) return storedEnum; @@ -661,11 +662,13 @@ public class dbBuildingHandler extends dbHandlerBase { ResultSet rs = preparedStatement.executeQuery(); - if (rs.next()) - storedEnum = DbObjectType.valueOf(rs.getString("type").toUpperCase()); + if (rs.next()) { + objectType = rs.getString("type").toUpperCase(); + storedEnum = DbObjectType.valueOf(objectType); + } } catch (SQLException e) { - Logger.error("Building", e); + Logger.error("UID_ENUM Lookup failed for UID: " + object_UID + "type: " + objectType); return DbObjectType.INVALID; } From 89192c7ea01a2679750de029ae92904c39888a2d Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 11:07:20 -0400 Subject: [PATCH 095/109] Cleanup post db-refactor. --- src/engine/db/handlers/dbBuildingHandler.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/engine/db/handlers/dbBuildingHandler.java b/src/engine/db/handlers/dbBuildingHandler.java index 34387911..94b43be4 100644 --- a/src/engine/db/handlers/dbBuildingHandler.java +++ b/src/engine/db/handlers/dbBuildingHandler.java @@ -656,7 +656,7 @@ public class dbBuildingHandler extends dbHandlerBase { return storedEnum; try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `type` FROM `object` WHERE `object`.`UID` = n LIMIT 1;")) { + PreparedStatement preparedStatement = connection.prepareStatement("SELECT `type` FROM `object` WHERE `object`.`UID` = ? LIMIT 1;")) { preparedStatement.setLong(1, object_UID); @@ -668,7 +668,7 @@ public class dbBuildingHandler extends dbHandlerBase { } } catch (SQLException e) { - Logger.error("UID_ENUM Lookup failed for UID: " + object_UID + "type: " + objectType); + Logger.error(e); return DbObjectType.INVALID; } From 568b0291a255246427d9d823544bdd6e6f94ea12 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 11:18:21 -0400 Subject: [PATCH 096/109] Duplicate method removed. --- src/engine/db/handlers/dbBuildingHandler.java | 12 +++++------ src/engine/db/handlers/dbItemHandler.java | 20 ------------------- src/engine/objects/Item.java | 20 ++++++++++++------- 3 files changed, 19 insertions(+), 33 deletions(-) diff --git a/src/engine/db/handlers/dbBuildingHandler.java b/src/engine/db/handlers/dbBuildingHandler.java index 94b43be4..a7696dae 100644 --- a/src/engine/db/handlers/dbBuildingHandler.java +++ b/src/engine/db/handlers/dbBuildingHandler.java @@ -649,11 +649,11 @@ public class dbBuildingHandler extends dbHandlerBase { public final DbObjectType GET_UID_ENUM(long object_UID) { - DbObjectType storedEnum = DbObjectType.INVALID; - String objectType = "INVALID"; + DbObjectType objectType = DbObjectType.INVALID; + String typeString = "INVALID"; if (object_UID == 0) - return storedEnum; + return objectType; try (Connection connection = DbManager.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement("SELECT `type` FROM `object` WHERE `object`.`UID` = ? LIMIT 1;")) { @@ -663,8 +663,8 @@ public class dbBuildingHandler extends dbHandlerBase { ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { - objectType = rs.getString("type").toUpperCase(); - storedEnum = DbObjectType.valueOf(objectType); + typeString = rs.getString("type").toUpperCase(); + objectType = DbObjectType.valueOf(typeString); } } catch (SQLException e) { @@ -672,7 +672,7 @@ public class dbBuildingHandler extends dbHandlerBase { return DbObjectType.INVALID; } - return storedEnum; + return objectType; } public boolean updateBuildingRank(final Building b, int Rank) { diff --git a/src/engine/db/handlers/dbItemHandler.java b/src/engine/db/handlers/dbItemHandler.java index 5b21c257..9615bfe9 100644 --- a/src/engine/db/handlers/dbItemHandler.java +++ b/src/engine/db/handlers/dbItemHandler.java @@ -107,26 +107,6 @@ public class dbItemHandler extends dbHandlerBase { return null; } - public String GET_OWNER(int ownerID) { - - String ownerType; - - try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("SELECT `type` FROM `object` WHERE `UID`=?")) { - - preparedStatement.setInt(1, ownerID); - ResultSet rs = preparedStatement.executeQuery(); - - ownerType = rs.getString("type"); - - } catch (SQLException e) { - Logger.error(e); - return ""; - } - - return ownerType; - } - public boolean DO_TRADE(HashSet from1, HashSet from2, CharacterItemManager man1, CharacterItemManager man2, Item inventoryGold1, Item inventoryGold2, int goldFrom1, int goldFrom2) { diff --git a/src/engine/objects/Item.java b/src/engine/objects/Item.java index add14aa3..11bd94e5 100644 --- a/src/engine/objects/Item.java +++ b/src/engine/objects/Item.java @@ -210,14 +210,20 @@ public class Item extends AbstractWorldObject { this.durabilityCurrent = rs.getShort("item_durabilityCurrent"); this.durabilityMax = rs.getShort("item_durabilityMax"); - String ot = DbManager.ItemQueries.GET_OWNER(this.ownerID); + DbObjectType ownerType; + ownerType = DbManager.BuildingQueries.GET_UID_ENUM(this.ownerID); - if (ot.equals("character")) - this.ownerType = OwnerType.PlayerCharacter; - else if (ot.equals("npc")) - this.ownerType = OwnerType.Npc; - else if (ot.equals("account")) - this.ownerType = OwnerType.Account; + switch (ownerType) { + case CHARACTER: + this.ownerType = OwnerType.PlayerCharacter; + break; + case NPC: + this.ownerType = OwnerType.Npc; + break; + case ACCOUNT: + this.ownerType = OwnerType.Account; + break; + } this.canDestroy = true; From ad994156795acf7e268d9288d47b9b6d28e18da3 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 12:24:11 -0400 Subject: [PATCH 097/109] fix: bug class involving rs usage. --- src/engine/db/handlers/dbBuildingHandler.java | 8 +++++--- src/engine/db/handlers/dbGuildHandler.java | 9 +++++---- src/engine/db/handlers/dbItemHandler.java | 9 +++++---- src/engine/db/handlers/dbMobHandler.java | 9 +++++---- src/engine/db/handlers/dbNPCHandler.java | 9 +++++---- src/engine/db/handlers/dbPlayerCharacterHandler.java | 8 +++++--- 6 files changed, 30 insertions(+), 22 deletions(-) diff --git a/src/engine/db/handlers/dbBuildingHandler.java b/src/engine/db/handlers/dbBuildingHandler.java index a7696dae..2e4191ca 100644 --- a/src/engine/db/handlers/dbBuildingHandler.java +++ b/src/engine/db/handlers/dbBuildingHandler.java @@ -69,10 +69,12 @@ public class dbBuildingHandler extends dbHandlerBase { ResultSet rs = preparedStatement.executeQuery(); - int objectUUID = (int) rs.getLong("UID"); + if (rs.next()) { + int objectUUID = (int) rs.getLong("UID"); - if (objectUUID > 0) - building = GET_BUILDINGBYUUID(objectUUID); + if (objectUUID > 0) + building = GET_BUILDINGBYUUID(objectUUID); + } } catch (SQLException e) { throw new RuntimeException(e); diff --git a/src/engine/db/handlers/dbGuildHandler.java b/src/engine/db/handlers/dbGuildHandler.java index d4917eef..159c2bee 100644 --- a/src/engine/db/handlers/dbGuildHandler.java +++ b/src/engine/db/handlers/dbGuildHandler.java @@ -433,11 +433,12 @@ public class dbGuildHandler extends dbHandlerBase { ResultSet rs = preparedStatement.executeQuery(); - int objectUUID = (int) rs.getLong("UID"); - - if (objectUUID > 0) - guild = GET_GUILD(objectUUID); + if (rs.next()) { + int objectUUID = (int) rs.getLong("UID"); + if (objectUUID > 0) + guild = GET_GUILD(objectUUID); + } } catch (SQLException e) { Logger.error(e); } diff --git a/src/engine/db/handlers/dbItemHandler.java b/src/engine/db/handlers/dbItemHandler.java index 9615bfe9..38b43943 100644 --- a/src/engine/db/handlers/dbItemHandler.java +++ b/src/engine/db/handlers/dbItemHandler.java @@ -95,11 +95,12 @@ public class dbItemHandler extends dbHandlerBase { ResultSet rs = preparedStatement.executeQuery(); - int objectUUID = (int) rs.getLong("UID"); - - if (objectUUID > 0) - return GET_ITEM(objectUUID); + if (rs.next()) { + int objectUUID = (int) rs.getLong("UID"); + if (objectUUID > 0) + return GET_ITEM(objectUUID); + } } catch (SQLException e) { Logger.error(e); } diff --git a/src/engine/db/handlers/dbMobHandler.java b/src/engine/db/handlers/dbMobHandler.java index eeeb8439..0081f67e 100644 --- a/src/engine/db/handlers/dbMobHandler.java +++ b/src/engine/db/handlers/dbMobHandler.java @@ -57,11 +57,12 @@ public class dbMobHandler extends dbHandlerBase { ResultSet rs = preparedStatement.executeQuery(); - int objectUUID = (int) rs.getLong("UID"); - - if (objectUUID > 0) - mobile = GET_MOB(objectUUID); + if (rs.next()) { + int objectUUID = (int) rs.getLong("UID"); + if (objectUUID > 0) + mobile = GET_MOB(objectUUID); + } } catch (SQLException e) { throw new RuntimeException(e); } diff --git a/src/engine/db/handlers/dbNPCHandler.java b/src/engine/db/handlers/dbNPCHandler.java index 2199d9a7..b718ab25 100644 --- a/src/engine/db/handlers/dbNPCHandler.java +++ b/src/engine/db/handlers/dbNPCHandler.java @@ -56,11 +56,12 @@ public class dbNPCHandler extends dbHandlerBase { ResultSet rs = preparedStatement.executeQuery(); - int objectUUID = (int) rs.getLong("UID"); - - if (objectUUID > 0) - npc = GET_NPC(objectUUID); + if (rs.next()) { + int objectUUID = (int) rs.getLong("UID"); + if (objectUUID > 0) + npc = GET_NPC(objectUUID); + } } catch (SQLException e) { throw new RuntimeException(e); } diff --git a/src/engine/db/handlers/dbPlayerCharacterHandler.java b/src/engine/db/handlers/dbPlayerCharacterHandler.java index 06a4d595..99d771c4 100644 --- a/src/engine/db/handlers/dbPlayerCharacterHandler.java +++ b/src/engine/db/handlers/dbPlayerCharacterHandler.java @@ -61,11 +61,13 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { ResultSet rs = preparedStatement.executeQuery(); - int objectUUID = (int) rs.getLong("UID"); + if (rs.next()) { - if (objectUUID > 0) - playerCharacter = GET_PLAYER_CHARACTER(objectUUID); + int objectUUID = (int) rs.getLong("UID"); + if (objectUUID > 0) + playerCharacter = GET_PLAYER_CHARACTER(objectUUID); + } } catch (SQLException e) { Logger.error(e); } From 45d26a82f2b71dc3871ae13de75407d08ad14b3a Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 12:53:04 -0400 Subject: [PATCH 098/109] bugfix: runafterload for instanced agos --- src/engine/db/handlers/dbGuildHandler.java | 2 +- src/engine/db/handlers/dbHandlerBase.java | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/engine/db/handlers/dbGuildHandler.java b/src/engine/db/handlers/dbGuildHandler.java index 159c2bee..e625f939 100644 --- a/src/engine/db/handlers/dbGuildHandler.java +++ b/src/engine/db/handlers/dbGuildHandler.java @@ -307,7 +307,7 @@ public class dbGuildHandler extends dbHandlerBase { PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_guild`.*, `object`.`parent` FROM `obj_guild` INNER JOIN `object` ON `object`.`UID` = `obj_guild`.`UID`")) { ResultSet rs = preparedStatement.executeQuery(); - guildList = getObjectsFromRs(rs, 20); + guildList = getObjectsFromRs(rs, 100); } catch (SQLException e) { Logger.error(e); diff --git a/src/engine/db/handlers/dbHandlerBase.java b/src/engine/db/handlers/dbHandlerBase.java index e16b49ca..1e1ee851 100644 --- a/src/engine/db/handlers/dbHandlerBase.java +++ b/src/engine/db/handlers/dbHandlerBase.java @@ -9,7 +9,9 @@ package engine.db.handlers; +import engine.Enum; import engine.Enum.GameObjectType; +import engine.gameManager.ConfigManager; import engine.gameManager.DbManager; import engine.objects.AbstractGameObject; import engine.objects.AbstractWorldObject; @@ -37,6 +39,13 @@ public abstract class dbHandlerBase { Logger.error(e); } + // Only call runAfterLoad() for objects instanced on the world server + + if ((abstractGameObject != null && abstractGameObject instanceof AbstractWorldObject) && + (ConfigManager.serverType.equals(Enum.ServerType.WORLDSERVER) || + (abstractGameObject.getObjectType() == GameObjectType.Guild))) + ((AbstractWorldObject) abstractGameObject).runAfterLoad(); + return abstractGameObject; } From 4f7bb6de0b30b0a013fa93bcac24fb994fdf4599 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 13:25:50 -0400 Subject: [PATCH 099/109] Using server side statement cache (500). --- src/engine/gameManager/DbManager.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/engine/gameManager/DbManager.java b/src/engine/gameManager/DbManager.java index 17d01365..ebd7dc5f 100644 --- a/src/engine/gameManager/DbManager.java +++ b/src/engine/gameManager/DbManager.java @@ -307,9 +307,11 @@ public enum DbManager { config.setPassword(ConfigManager.MB_DATABASE_PASS.getValue()); config.addDataSourceProperty("characterEncoding", "utf8"); config.addDataSourceProperty("cachePrepStmts", "true"); - config.addDataSourceProperty("prepStmtCacheSize", "250"); + config.addDataSourceProperty("useServerPrepStmts", "true"); + config.addDataSourceProperty("prepStmtCacheSize", "500"); config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); config.addDataSourceProperty("leakDetectionThreshold", "5000"); + config.addDataSourceProperty("cacheServerConfiguration", "true"); connectionPool = new HikariDataSource(config); // setup the connection pool From f78c18abece45faca37e791cc709ba3719455166 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 13:51:10 -0400 Subject: [PATCH 100/109] Updated Hikari pool configuration. --- src/engine/gameManager/DbManager.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/engine/gameManager/DbManager.java b/src/engine/gameManager/DbManager.java index ebd7dc5f..0a90cb33 100644 --- a/src/engine/gameManager/DbManager.java +++ b/src/engine/gameManager/DbManager.java @@ -298,18 +298,24 @@ public enum DbManager { HikariConfig config = new HikariConfig(); - config.setMaximumPoolSize(Runtime.getRuntime().availableProcessors() * 2); + config.setMaximumPoolSize((Runtime.getRuntime().availableProcessors() * 2) + 1); config.setJdbcUrl("jdbc:mysql://" + ConfigManager.MB_DATABASE_ADDRESS.getValue() + ":" + ConfigManager.MB_DATABASE_PORT.getValue() + "/" + ConfigManager.MB_DATABASE_NAME.getValue()); config.setUsername(ConfigManager.MB_DATABASE_USER.getValue()); config.setPassword(ConfigManager.MB_DATABASE_PASS.getValue()); + + config.addDataSourceProperty("minimumIdle", "5"); + config.addDataSourceProperty("idleTimeout", "120000"); + config.addDataSourceProperty("characterEncoding", "utf8"); - config.addDataSourceProperty("cachePrepStmts", "true"); + config.addDataSourceProperty("useServerPrepStmts", "true"); + config.addDataSourceProperty("cachePrepStmts", "true"); config.addDataSourceProperty("prepStmtCacheSize", "500"); config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); + config.addDataSourceProperty("leakDetectionThreshold", "5000"); config.addDataSourceProperty("cacheServerConfiguration", "true"); From adcf7ca9279549d4737f42ba949797e410cf493f Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 14:06:15 -0400 Subject: [PATCH 101/109] Updated Hikari pool configuration. --- src/engine/gameManager/DbManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/engine/gameManager/DbManager.java b/src/engine/gameManager/DbManager.java index 0a90cb33..e8952fee 100644 --- a/src/engine/gameManager/DbManager.java +++ b/src/engine/gameManager/DbManager.java @@ -307,7 +307,7 @@ public enum DbManager { config.setPassword(ConfigManager.MB_DATABASE_PASS.getValue()); config.addDataSourceProperty("minimumIdle", "5"); - config.addDataSourceProperty("idleTimeout", "120000"); + config.addDataSourceProperty("maxLifetime", "3600000"); config.addDataSourceProperty("characterEncoding", "utf8"); From bcc1ac115d419ac239d0f4dc9f16c2d054a8b961 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 14:29:08 -0400 Subject: [PATCH 102/109] bug class fixed involving rs usage --- src/engine/db/handlers/dbBuildingHandler.java | 3 ++- src/engine/db/handlers/dbGuildHandler.java | 1 + src/engine/db/handlers/dbItemHandler.java | 1 + src/engine/db/handlers/dbMobHandler.java | 5 ++++- src/engine/db/handlers/dbNPCHandler.java | 5 ++++- src/engine/db/handlers/dbPlayerCharacterHandler.java | 6 ++++-- 6 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/engine/db/handlers/dbBuildingHandler.java b/src/engine/db/handlers/dbBuildingHandler.java index 2e4191ca..449def09 100644 --- a/src/engine/db/handlers/dbBuildingHandler.java +++ b/src/engine/db/handlers/dbBuildingHandler.java @@ -165,8 +165,9 @@ public class dbBuildingHandler extends dbHandlerBase { preparedStatement.setString(3, String.valueOf(new_value)); ResultSet rs = preparedStatement.executeQuery(); - result = rs.getString("result"); + if (rs.next()) + result = rs.getString("result"); } catch (SQLException e) { Logger.error(e); diff --git a/src/engine/db/handlers/dbGuildHandler.java b/src/engine/db/handlers/dbGuildHandler.java index e625f939..bcbe6b30 100644 --- a/src/engine/db/handlers/dbGuildHandler.java +++ b/src/engine/db/handlers/dbGuildHandler.java @@ -439,6 +439,7 @@ public class dbGuildHandler extends dbHandlerBase { if (objectUUID > 0) guild = GET_GUILD(objectUUID); } + } catch (SQLException e) { Logger.error(e); } diff --git a/src/engine/db/handlers/dbItemHandler.java b/src/engine/db/handlers/dbItemHandler.java index 38b43943..8e6ffd95 100644 --- a/src/engine/db/handlers/dbItemHandler.java +++ b/src/engine/db/handlers/dbItemHandler.java @@ -101,6 +101,7 @@ public class dbItemHandler extends dbHandlerBase { if (objectUUID > 0) return GET_ITEM(objectUUID); } + } catch (SQLException e) { Logger.error(e); } diff --git a/src/engine/db/handlers/dbMobHandler.java b/src/engine/db/handlers/dbMobHandler.java index 0081f67e..e3d64b0a 100644 --- a/src/engine/db/handlers/dbMobHandler.java +++ b/src/engine/db/handlers/dbMobHandler.java @@ -63,6 +63,7 @@ public class dbMobHandler extends dbHandlerBase { if (objectUUID > 0) mobile = GET_MOB(objectUUID); } + } catch (SQLException e) { throw new RuntimeException(e); } @@ -238,7 +239,9 @@ public class dbMobHandler extends dbHandlerBase { preparedStatement.setString(3, String.valueOf(new_value)); ResultSet rs = preparedStatement.executeQuery(); - result = rs.getString("result"); + + if (rs.next()) + result = rs.getString("result"); } catch (SQLException e) { Logger.error(e); diff --git a/src/engine/db/handlers/dbNPCHandler.java b/src/engine/db/handlers/dbNPCHandler.java index b718ab25..6bfc9da8 100644 --- a/src/engine/db/handlers/dbNPCHandler.java +++ b/src/engine/db/handlers/dbNPCHandler.java @@ -62,6 +62,7 @@ public class dbNPCHandler extends dbHandlerBase { if (objectUUID > 0) npc = GET_NPC(objectUUID); } + } catch (SQLException e) { throw new RuntimeException(e); } @@ -160,7 +161,9 @@ public class dbNPCHandler extends dbHandlerBase { preparedStatement.setString(3, String.valueOf(new_value)); ResultSet rs = preparedStatement.executeQuery(); - result = rs.getString("result"); + + if (rs.next()) + result = rs.getString("result"); } catch (SQLException e) { Logger.error(e); diff --git a/src/engine/db/handlers/dbPlayerCharacterHandler.java b/src/engine/db/handlers/dbPlayerCharacterHandler.java index 99d771c4..59b48a78 100644 --- a/src/engine/db/handlers/dbPlayerCharacterHandler.java +++ b/src/engine/db/handlers/dbPlayerCharacterHandler.java @@ -62,12 +62,12 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { - int objectUUID = (int) rs.getLong("UID"); if (objectUUID > 0) playerCharacter = GET_PLAYER_CHARACTER(objectUUID); } + } catch (SQLException e) { Logger.error(e); } @@ -362,7 +362,9 @@ public class dbPlayerCharacterHandler extends dbHandlerBase { preparedStatement.setString(3, String.valueOf(new_value)); ResultSet rs = preparedStatement.executeQuery(); - result = rs.getString("result"); + + if (rs.next()) + result = rs.getString("result"); } catch (SQLException e) { Logger.error(e); From d7d22dbb11082d0c4d3b3804824302d790d2c8e6 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 17:15:07 -0400 Subject: [PATCH 103/109] Populate zone extents cache. --- src/engine/server/world/WorldServer.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/engine/server/world/WorldServer.java b/src/engine/server/world/WorldServer.java index 276fd9ec..2632be6f 100644 --- a/src/engine/server/world/WorldServer.java +++ b/src/engine/server/world/WorldServer.java @@ -305,9 +305,12 @@ public class WorldServer { PowersManager.LoadAllMobPowers(); //load item enchantment values + Logger.info("Loading item enchants"); DbManager.LootQueries.LOAD_ENCHANT_VALUES(); - //initialize realms + Logger.info("Loading zone extent cache"); + DbManager.ZoneQueries.LOAD_ZONE_EXTENTS(); + Logger.info("Loading Realms"); Realm.loadAllRealms(); From c46615f1d280e9ba9491f22c081ccc50d706a112 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Tue, 23 May 2023 17:30:30 -0400 Subject: [PATCH 104/109] Logging info update on bootstrap. --- src/engine/gameManager/DbManager.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/engine/gameManager/DbManager.java b/src/engine/gameManager/DbManager.java index e8952fee..5c7f6402 100644 --- a/src/engine/gameManager/DbManager.java +++ b/src/engine/gameManager/DbManager.java @@ -298,7 +298,8 @@ public enum DbManager { HikariConfig config = new HikariConfig(); - config.setMaximumPoolSize((Runtime.getRuntime().availableProcessors() * 2) + 1); + int connectionCount = (Runtime.getRuntime().availableProcessors() * 2) + 1; + config.setMaximumPoolSize(connectionCount); config.setJdbcUrl("jdbc:mysql://" + ConfigManager.MB_DATABASE_ADDRESS.getValue() + ":" + ConfigManager.MB_DATABASE_PORT.getValue() + "/" + @@ -321,6 +322,6 @@ public enum DbManager { connectionPool = new HikariDataSource(config); // setup the connection pool - Logger.info("Database connection pool configured"); + Logger.info("Database pool has " + connectionCount + " max connections"); } } From 9edc32de13a504a0dd54badbcba80db4bb5d5140 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Wed, 24 May 2023 07:57:36 -0400 Subject: [PATCH 105/109] Pool - 10 minute idle; 60 min lifetime. --- src/engine/gameManager/DbManager.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/engine/gameManager/DbManager.java b/src/engine/gameManager/DbManager.java index 5c7f6402..9d6feaf0 100644 --- a/src/engine/gameManager/DbManager.java +++ b/src/engine/gameManager/DbManager.java @@ -308,6 +308,7 @@ public enum DbManager { config.setPassword(ConfigManager.MB_DATABASE_PASS.getValue()); config.addDataSourceProperty("minimumIdle", "5"); + config.addDataSourceProperty("idleTimeout", "600000"); config.addDataSourceProperty("maxLifetime", "3600000"); config.addDataSourceProperty("characterEncoding", "utf8"); From ee137c014631fa87d94e5d5fbb4970063575b648 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Wed, 24 May 2023 08:34:37 -0400 Subject: [PATCH 106/109] Fixed pool size auto-calculated. --- src/engine/gameManager/DbManager.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/engine/gameManager/DbManager.java b/src/engine/gameManager/DbManager.java index 9d6feaf0..3b538a8d 100644 --- a/src/engine/gameManager/DbManager.java +++ b/src/engine/gameManager/DbManager.java @@ -307,8 +307,6 @@ public enum DbManager { config.setUsername(ConfigManager.MB_DATABASE_USER.getValue()); config.setPassword(ConfigManager.MB_DATABASE_PASS.getValue()); - config.addDataSourceProperty("minimumIdle", "5"); - config.addDataSourceProperty("idleTimeout", "600000"); config.addDataSourceProperty("maxLifetime", "3600000"); config.addDataSourceProperty("characterEncoding", "utf8"); @@ -323,6 +321,6 @@ public enum DbManager { connectionPool = new HikariDataSource(config); // setup the connection pool - Logger.info("Database pool has " + connectionCount + " max connections"); + Logger.info("Database configured with " + connectionCount + " connections"); } } From cb0a89cb03a707bdc110d90477f0a5d5363e84a8 Mon Sep 17 00:00:00 2001 From: MagicBot Date: Wed, 24 May 2023 08:36:34 -0400 Subject: [PATCH 107/109] Fixed pool size auto-calculated. --- src/engine/gameManager/DbManager.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/engine/gameManager/DbManager.java b/src/engine/gameManager/DbManager.java index 3b538a8d..94282831 100644 --- a/src/engine/gameManager/DbManager.java +++ b/src/engine/gameManager/DbManager.java @@ -307,6 +307,8 @@ public enum DbManager { config.setUsername(ConfigManager.MB_DATABASE_USER.getValue()); config.setPassword(ConfigManager.MB_DATABASE_PASS.getValue()); + // Must be set lower than SQL server connection lifetime! + config.addDataSourceProperty("maxLifetime", "3600000"); config.addDataSourceProperty("characterEncoding", "utf8"); From d0287ba94e0e1daf8873762cd23f154d409170ac Mon Sep 17 00:00:00 2001 From: MagicBot Date: Thu, 25 May 2023 14:55:49 -0400 Subject: [PATCH 108/109] Login should fail fast. --- src/engine/server/login/LoginServer.java | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/engine/server/login/LoginServer.java b/src/engine/server/login/LoginServer.java index dfa35aa9..ea66b02f 100644 --- a/src/engine/server/login/LoginServer.java +++ b/src/engine/server/login/LoginServer.java @@ -116,16 +116,20 @@ public class LoginServer { // Invalidate cache for players driven by forum // and stored procedure forum_link_pass() - try { - // Run cache routine right away if requested. File cacheFile = new File("cacheInvalid"); if (cacheFile.exists() == true) { + nextCacheTime = LocalDateTime.now(); - Files.deleteIfExists(Paths.get("cacheInvalid")); + + try { + Files.deleteIfExists(Paths.get("cacheInvalid")); + } catch (IOException e) { + throw new RuntimeException(e); + } } if (LocalDateTime.now().isAfter(nextCacheTime)) { @@ -145,10 +149,7 @@ public class LoginServer { } ThreadUtils.sleep(100); - } catch (Exception e) { - Logger.error(e); - e.printStackTrace(); - } + } } From abb2521f585309e1a8fef6afaf91d70f3fc47d8d Mon Sep 17 00:00:00 2001 From: MagicBot Date: Fri, 26 May 2023 17:46:26 -0400 Subject: [PATCH 109/109] Bug class involving generated keys from statements. --- src/engine/db/handlers/dbCharacterPowerHandler.java | 7 ++----- src/engine/db/handlers/dbCharacterRuneHandler.java | 7 ++----- src/engine/db/handlers/dbCharacterSkillHandler.java | 7 ++----- 3 files changed, 6 insertions(+), 15 deletions(-) diff --git a/src/engine/db/handlers/dbCharacterPowerHandler.java b/src/engine/db/handlers/dbCharacterPowerHandler.java index 3a2bbcf8..f16f67fb 100644 --- a/src/engine/db/handlers/dbCharacterPowerHandler.java +++ b/src/engine/db/handlers/dbCharacterPowerHandler.java @@ -16,10 +16,7 @@ import engine.objects.PlayerCharacter; import engine.server.MBServerStatics; import org.pmw.tinylog.Logger; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; +import java.sql.*; import java.util.concurrent.ConcurrentHashMap; public class dbCharacterPowerHandler extends dbHandlerBase { @@ -39,7 +36,7 @@ public class dbCharacterPowerHandler extends dbHandlerBase { } try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_power` (`CharacterID`, `powersBaseToken`, `trains`) VALUES (?, ?, ?);")) { + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_power` (`CharacterID`, `powersBaseToken`, `trains`) VALUES (?, ?, ?);", Statement.RETURN_GENERATED_KEYS)) { preparedStatement.setLong(1, CharacterPower.getOwner(toAdd).getObjectUUID()); preparedStatement.setInt(2, toAdd.getPower().getToken()); diff --git a/src/engine/db/handlers/dbCharacterRuneHandler.java b/src/engine/db/handlers/dbCharacterRuneHandler.java index d63bc6d8..7cdbed5c 100644 --- a/src/engine/db/handlers/dbCharacterRuneHandler.java +++ b/src/engine/db/handlers/dbCharacterRuneHandler.java @@ -14,10 +14,7 @@ import engine.gameManager.DbManager; import engine.objects.CharacterRune; import org.pmw.tinylog.Logger; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; +import java.sql.*; import java.util.ArrayList; public class dbCharacterRuneHandler extends dbHandlerBase { @@ -32,7 +29,7 @@ public class dbCharacterRuneHandler extends dbHandlerBase { CharacterRune characterRune = null; try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_rune` (`CharacterID`, `RuneBaseID`) VALUES (?, ?);")) { + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_rune` (`CharacterID`, `RuneBaseID`) VALUES (?, ?);", Statement.RETURN_GENERATED_KEYS)) { preparedStatement.setLong(1, toAdd.getPlayerID()); preparedStatement.setInt(2, toAdd.getRuneBaseID()); diff --git a/src/engine/db/handlers/dbCharacterSkillHandler.java b/src/engine/db/handlers/dbCharacterSkillHandler.java index fd46d5c5..beb9b5bf 100644 --- a/src/engine/db/handlers/dbCharacterSkillHandler.java +++ b/src/engine/db/handlers/dbCharacterSkillHandler.java @@ -17,10 +17,7 @@ import engine.objects.PlayerCharacter; import engine.server.MBServerStatics; import org.pmw.tinylog.Logger; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; +import java.sql.*; import java.util.concurrent.ConcurrentHashMap; public class dbCharacterSkillHandler extends dbHandlerBase { @@ -40,7 +37,7 @@ public class dbCharacterSkillHandler extends dbHandlerBase { } try (Connection connection = DbManager.getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_skill` (`CharacterID`, `skillsBaseID`, `trains`) VALUES (?, ?, ?);")) { + PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_skill` (`CharacterID`, `skillsBaseID`, `trains`) VALUES (?, ?, ?);", Statement.RETURN_GENERATED_KEYS)) { preparedStatement.setLong(1, CharacterSkill.GetOwner(toAdd).getObjectUUID()); preparedStatement.setInt(2, toAdd.getSkillsBase().getObjectUUID());