Browse Source

Merge remote-tracking branch 'origin/magicbox1.5' into magicbox1.5

# Conflicts:
#	src/engine/ai/MobileFSM.java
master
FatBoy-DOTC 2 years ago
parent
commit
bee3a9b376
  1. 109
      src/discord/Database.java
  2. 2
      src/discord/handlers/StatusRequestHandler.java
  3. 16
      src/engine/ai/MobileFSMManager.java
  4. 323
      src/engine/ai/utilities/CombatUtilities.java
  5. 76
      src/engine/ai/utilities/MovementUtilities.java
  6. 1
      src/engine/ai/utilities/PowerUtilities.java
  7. 19
      src/engine/db/archive/BaneRecord.java
  8. 19
      src/engine/db/archive/CharacterRecord.java
  9. 3
      src/engine/db/archive/CityRecord.java
  10. 40
      src/engine/db/archive/DataWarehouse.java
  11. 3
      src/engine/db/archive/GuildRecord.java
  12. 3
      src/engine/db/archive/MineRecord.java
  13. 9
      src/engine/db/archive/PvpRecord.java
  14. 3
      src/engine/db/archive/RealmRecord.java
  15. 243
      src/engine/db/handlers/dbAccountHandler.java
  16. 101
      src/engine/db/handlers/dbBaneHandler.java
  17. 59
      src/engine/db/handlers/dbBaseClassHandler.java
  18. 31
      src/engine/db/handlers/dbBlueprintHandler.java
  19. 26
      src/engine/db/handlers/dbBoonHandler.java
  20. 954
      src/engine/db/handlers/dbBuildingHandler.java
  21. 27
      src/engine/db/handlers/dbBuildingLocationHandler.java
  22. 104
      src/engine/db/handlers/dbCSSessionHandler.java
  23. 136
      src/engine/db/handlers/dbCharacterPowerHandler.java
  24. 106
      src/engine/db/handlers/dbCharacterRuneHandler.java
  25. 161
      src/engine/db/handlers/dbCharacterSkillHandler.java
  26. 263
      src/engine/db/handlers/dbCityHandler.java
  27. 137
      src/engine/db/handlers/dbContractHandler.java
  28. 394
      src/engine/db/handlers/dbEffectsBaseHandler.java
  29. 25
      src/engine/db/handlers/dbEffectsResourceCostHandler.java
  30. 60
      src/engine/db/handlers/dbEnchantmentHandler.java
  31. 767
      src/engine/db/handlers/dbGuildHandler.java
  32. 429
      src/engine/db/handlers/dbHandlerBase.java
  33. 22
      src/engine/db/handlers/dbHeightMapHandler.java
  34. 96
      src/engine/db/handlers/dbItemBaseHandler.java
  35. 551
      src/engine/db/handlers/dbItemHandler.java
  36. 29
      src/engine/db/handlers/dbKitHandler.java
  37. 151
      src/engine/db/handlers/dbLootTableHandler.java
  38. 25
      src/engine/db/handlers/dbMenuHandler.java
  39. 119
      src/engine/db/handlers/dbMineHandler.java
  40. 167
      src/engine/db/handlers/dbMobBaseHandler.java
  41. 258
      src/engine/db/handlers/dbMobHandler.java
  42. 511
      src/engine/db/handlers/dbNPCHandler.java
  43. 639
      src/engine/db/handlers/dbPlayerCharacterHandler.java
  44. 67
      src/engine/db/handlers/dbPromotionClassHandler.java
  45. 124
      src/engine/db/handlers/dbRaceHandler.java
  46. 43
      src/engine/db/handlers/dbRealmHandler.java
  47. 30
      src/engine/db/handlers/dbResistHandler.java
  48. 26
      src/engine/db/handlers/dbRuneBaseAttributeHandler.java
  49. 66
      src/engine/db/handlers/dbRuneBaseEffectHandler.java
  50. 116
      src/engine/db/handlers/dbRuneBaseHandler.java
  51. 30
      src/engine/db/handlers/dbRunegateHandler.java
  52. 168
      src/engine/db/handlers/dbShrineHandler.java
  53. 125
      src/engine/db/handlers/dbSkillBaseHandler.java
  54. 79
      src/engine/db/handlers/dbSkillReqHandler.java
  55. 31
      src/engine/db/handlers/dbVendorDialogHandler.java
  56. 663
      src/engine/db/handlers/dbWarehouseHandler.java
  57. 91
      src/engine/db/handlers/dbZoneHandler.java
  58. 105
      src/engine/devcmd/cmds/GuildListCmd.java
  59. 101
      src/engine/devcmd/cmds/RenameMobCmd.java
  60. 67
      src/engine/gameManager/DbManager.java
  61. 2
      src/engine/gameManager/DevCmdManager.java
  62. 12
      src/engine/gameManager/PowersManager.java
  63. 25
      src/engine/gameManager/SimulationManager.java
  64. 55
      src/engine/gameManager/ZoneManager.java
  65. 19
      src/engine/net/client/handlers/MinionTrainingMsgHandler.java
  66. 38
      src/engine/net/client/msg/ManageNPCMsg.java
  67. 2
      src/engine/objects/Boon.java
  68. 34
      src/engine/objects/City.java
  69. 4
      src/engine/objects/Contract.java
  70. 15
      src/engine/objects/Item.java
  71. 12
      src/engine/objects/Mob.java
  72. 14
      src/engine/objects/MobBase.java
  73. 3
      src/engine/objects/Realm.java
  74. 313
      src/engine/objects/Zone.java
  75. 92
      src/engine/powers/EffectsBase.java
  76. 53
      src/engine/powers/PowersBase.java
  77. 263
      src/engine/powers/effectmodifiers/AbstractEffectModifier.java
  78. 2
      src/engine/powers/effectmodifiers/ItemNameEffectModifier.java
  79. 2
      src/engine/server/MBServerStatics.java
  80. 50
      src/engine/server/login/LoginServer.java
  81. 4
      src/engine/server/login/LoginServerMsgHandler.java
  82. 9
      src/engine/server/world/WorldServer.java
  83. 1
      src/engine/workthreads/HourlyJobThread.java
  84. 4
      src/engine/workthreads/PurgeOprhans.java
  85. 29
      src/engine/workthreads/WarehousePushThread.java

109
src/discord/Database.java

@ -54,15 +54,13 @@ public class Database {
public boolean updateAccountPassword(String discordAccountID, String newPassword) { public boolean updateAccountPassword(String discordAccountID, String newPassword) {
try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), 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("call discordUpdatePassword(?, ?)")) {
CallableStatement updatePassword = connection.prepareCall("call discordUpdatePassword(?, ?)");
updatePassword.setString(1, discordAccountID); updateStatement.setString(1, discordAccountID);
updatePassword.setString(2, newPassword); updateStatement.setString(2, newPassword);
updatePassword.executeUpdate(); updateStatement.executeUpdate();
updatePassword.close();
return true; return true;
} catch (SQLException e) { } catch (SQLException e) {
@ -75,15 +73,13 @@ public class Database {
public boolean updateAccountStatus(String discordAccountID, Enum.AccountStatus accountStatus) { public boolean updateAccountStatus(String discordAccountID, Enum.AccountStatus accountStatus) {
try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), 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()); updateStatement.executeUpdate();
updateAccountStatus.setString(2, discordAccountID);
updateAccountStatus.executeUpdate();
updateAccountStatus.close();
return true; return true;
} catch (SQLException e) { } catch (SQLException e) {
@ -98,14 +94,13 @@ public class Database {
try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(),
ConfigManager.MB_DATABASE_PASS.getValue())) { ConfigManager.MB_DATABASE_PASS.getValue())) {
CallableStatement registerAccount = connection.prepareCall("call discordAccountRegister(?, ?, ?)"); PreparedStatement registerStatement = connection.prepareStatement("call discordAccountRegister(?, ?, ?)");
registerAccount.setString(1, discordAccountID); registerStatement.setString(1, discordAccountID);
registerAccount.setString(2, discordUserName); registerStatement.setString(2, discordUserName);
registerAccount.setString(3, discordPassword); registerStatement.setString(3, discordPassword);
registerAccount.execute(); registerStatement.execute();
registerAccount.close();
return true; return true;
} catch (SQLException e) { } catch (SQLException e) {
@ -123,11 +118,11 @@ public class Database {
String queryString = "SELECT * FROM obj_account where discordAccount = ?"; String queryString = "SELECT * FROM obj_account where discordAccount = ?";
try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), 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 // Discord account name based lookup
PreparedStatement accountQuery = connection.prepareStatement(queryString);
accountQuery.setString(1, discordAccountID); accountQuery.setString(1, discordAccountID);
ResultSet rs = accountQuery.executeQuery(); ResultSet rs = accountQuery.executeQuery();
@ -169,11 +164,8 @@ public class Database {
String queryString = "SELECT * FROM dyn_trash_detail;"; String queryString = "SELECT * FROM dyn_trash_detail;";
try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(),
ConfigManager.MB_DATABASE_PASS.getValue())) { ConfigManager.MB_DATABASE_PASS.getValue());
PreparedStatement trashQuery = connection.prepareStatement(queryString)) {
// Discord account name based lookup
PreparedStatement trashQuery = connection.prepareStatement(queryString);
ResultSet rs = trashQuery.executeQuery(); ResultSet rs = trashQuery.executeQuery();
@ -195,15 +187,11 @@ public class Database {
public String getTrashList() { public String getTrashList() {
String outString = ""; String outString = "";
String queryString = "SELECT DISTINCT `characterName` FROM dyn_trash_detail;";
int counter = 0; int counter = 0;
try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(),
ConfigManager.MB_DATABASE_PASS.getValue())) { ConfigManager.MB_DATABASE_PASS.getValue());
PreparedStatement trashQuery = connection.prepareStatement("SELECT DISTINCT `characterName` FROM dyn_trash_detail;")) {
// Discord account name based lookup
PreparedStatement trashQuery = connection.prepareStatement(queryString);
ResultSet rs = trashQuery.executeQuery(); ResultSet rs = trashQuery.executeQuery();
@ -234,14 +222,9 @@ public class Database {
int trashCount = 0; int trashCount = 0;
String queryString = "SELECT count(distinct characterName) FROM dyn_trash_detail;";
try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(),
ConfigManager.MB_DATABASE_PASS.getValue())) { ConfigManager.MB_DATABASE_PASS.getValue());
PreparedStatement trashQuery = connection.prepareStatement("SELECT count(distinct characterName) FROM dyn_trash_detail;")) {
// Discord account name based lookup
PreparedStatement trashQuery = connection.prepareStatement(queryString);
ResultSet rs = trashQuery.executeQuery(); ResultSet rs = trashQuery.executeQuery();
@ -259,23 +242,17 @@ public class Database {
public void setAdminEventAsRead(int adminEvent) { 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(), try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(),
ConfigManager.MB_DATABASE_PASS.getValue())) { ConfigManager.MB_DATABASE_PASS.getValue());
PreparedStatement updateAdminEvent = connection.prepareStatement("UPDATE dyn_admin_log SET `SentFlag` = 1 WHERE `entry` = ? ")) {
PreparedStatement updateAdminEvent = connection.prepareCall(queryString);
updateAdminEvent.setInt(1, adminEvent); updateAdminEvent.setInt(1, adminEvent);
updateAdminEvent.executeUpdate(); updateAdminEvent.executeUpdate();
updateAdminEvent.close();
return;
} catch (SQLException e) { } catch (SQLException e) {
Logger.error(e.toString()); Logger.error(e.toString());
online = false; online = false;
return;
} }
} }
@ -283,14 +260,11 @@ public class Database {
public HashMap<Integer, String> getAdminEvents() { public HashMap<Integer, String> getAdminEvents() {
HashMap<Integer, String> outMap = new HashMap<>(); HashMap<Integer, String> outMap = new HashMap<>();
String queryString = "SELECT * from dyn_admin_log where `SentFlag` = 0";
try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(),
ConfigManager.MB_DATABASE_PASS.getValue())) { ConfigManager.MB_DATABASE_PASS.getValue());
PreparedStatement adminLogQuery = connection.prepareStatement("SELECT * from dyn_admin_log where `SentFlag` = 0")) {
// Discord Admin Log lookup of unreported events
PreparedStatement adminLogQuery = connection.prepareStatement(queryString);
ResultSet rs = adminLogQuery.executeQuery(); ResultSet rs = adminLogQuery.executeQuery();
String workString; String workString;
@ -311,14 +285,10 @@ public class Database {
public String getTrashFile() { public String getTrashFile() {
String outString = "machineID : count\n"; String outString = "machineID : count\n";
String queryString = "SELECT * FROM dyn_trash;";
try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(),
ConfigManager.MB_DATABASE_PASS.getValue())) { ConfigManager.MB_DATABASE_PASS.getValue());
PreparedStatement trashQuery = connection.prepareStatement("SELECT * FROM dyn_trash;")) {
// Discord account name based lookup
PreparedStatement trashQuery = connection.prepareStatement(queryString);
ResultSet rs = trashQuery.executeQuery(); ResultSet rs = trashQuery.executeQuery();
@ -346,14 +316,10 @@ public class Database {
else else
searchString = accountName + "%#%"; searchString = accountName + "%#%";
queryString = "SELECT * FROM obj_account where `acct_uname` LIKE ?";
try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(),
ConfigManager.MB_DATABASE_PASS.getValue())) { ConfigManager.MB_DATABASE_PASS.getValue());
PreparedStatement nameQuery = connection.prepareStatement("SELECT * FROM obj_account where `acct_uname` LIKE ?")) {
// Discord account name based lookup
PreparedStatement nameQuery = connection.prepareStatement(queryString);
nameQuery.setString(1, searchString); nameQuery.setString(1, searchString);
ResultSet rs = nameQuery.executeQuery(); ResultSet rs = nameQuery.executeQuery();
@ -389,15 +355,14 @@ public class Database {
return discordAccounts; return discordAccounts;
} }
public String getPopulationSTring() { public String getPopulationString() {
String popString = ""; String popString = "";
try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), 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(); ResultSet rs = getPopString.executeQuery();
if (rs.next()) if (rs.next())
@ -414,11 +379,9 @@ public class Database {
public void invalidateLoginCache(String discordAccountID) { public void invalidateLoginCache(String discordAccountID) {
try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(), try (Connection connection = DriverManager.getConnection(sqlURI, ConfigManager.MB_DATABASE_USER.getValue(),
ConfigManager.MB_DATABASE_PASS.getValue())) { ConfigManager.MB_DATABASE_PASS.getValue());
PreparedStatement invalidateAccounts = connection.prepareStatement("INSERT IGNORE INTO login_cachelist (`UID`) SELECT `UID` from `obj_account` WHERE `discordAccount` = ?")) {
String queryString = "INSERT IGNORE INTO login_cachelist (`UID`) SELECT `UID` from `obj_account` WHERE `discordAccount` = ?";
PreparedStatement invalidateAccounts = connection.prepareStatement(queryString);
invalidateAccounts.setString(1, discordAccountID); invalidateAccounts.setString(1, discordAccountID);
invalidateAccounts.executeUpdate(); invalidateAccounts.executeUpdate();

2
src/discord/handlers/StatusRequestHandler.java

@ -29,7 +29,7 @@ public class StatusRequestHandler {
outString += "OFFLINE\n"; outString += "OFFLINE\n";
if (Database.online == true) if (Database.online == true)
outString += MagicBot.database.getPopulationSTring(); outString += MagicBot.database.getPopulationString();
else else
outString += "Database offline: no population data."; outString += "Database offline: no population data.";

16
src/engine/ai/MobileFSMManager.java

@ -8,6 +8,8 @@
package engine.ai; package engine.ai;
import engine.gameManager.SessionManager;
import engine.gameManager.ZoneManager; import engine.gameManager.ZoneManager;
import engine.objects.Mob; import engine.objects.Mob;
import engine.objects.Zone; import engine.objects.Zone;
@ -22,12 +24,10 @@ import java.time.Instant;
public class MobileFSMManager { public class MobileFSMManager {
private static final MobileFSMManager INSTANCE = new MobileFSMManager(); private static final MobileFSMManager INSTANCE = new MobileFSMManager();
private volatile boolean alive;
private long timeOfKill = -1;
public static Duration executionTime = Duration.ofNanos(1); public static Duration executionTime = Duration.ofNanos(1);
public static Duration executionMax = Duration.ofNanos(1); public static Duration executionMax = Duration.ofNanos(1);
private volatile boolean alive;
private long timeOfKill = -1;
private MobileFSMManager() { private MobileFSMManager() {
@ -59,10 +59,6 @@ public class MobileFSMManager {
} }
public long getTimeOfKill() {
return this.timeOfKill;
}
public boolean isAlive() { public boolean isAlive() {
return this.alive; return this.alive;
} }
@ -88,7 +84,7 @@ public class MobileFSMManager {
for (Mob mob : zone.zoneMobSet) { for (Mob mob : zone.zoneMobSet) {
try { try {
if (mob != null) if (mob != null && SessionManager.getActivePlayerCharacterCount() > 0)
MobileFSM.DetermineAction(mob); MobileFSM.DetermineAction(mob);
} catch (Exception e) { } catch (Exception e) {
Logger.error("Mob: " + mob.getName() + " UUID: " + mob.getObjectUUID() + " ERROR: " + e); Logger.error("Mob: " + mob.getName() + " UUID: " + mob.getObjectUUID() + " ERROR: " + e);
@ -97,7 +93,7 @@ public class MobileFSMManager {
} }
} }
this.executionTime = Duration.between(startTime, Instant.now()); executionTime = Duration.between(startTime, Instant.now());
if (executionTime.compareTo(executionMax) > 0) if (executionTime.compareTo(executionMax) > 0)
executionMax = executionTime; executionMax = executionTime;

323
src/engine/ai/utilities/CombatUtilities.java

@ -7,7 +7,6 @@
// www.magicbane.com // www.magicbane.com
package engine.ai.utilities; package engine.ai.utilities;
import engine.Enum.*; import engine.Enum.*;
@ -27,99 +26,78 @@ import static java.lang.Math.pow;
public class CombatUtilities { public class CombatUtilities {
public static boolean inRangeToAttack(Mob agent,AbstractWorldObject target){ public static boolean inRangeToAttack(Mob agent, AbstractWorldObject target) {
if (Float.isNaN(agent.getLoc().x)) if (Float.isNaN(agent.getLoc().x))
return false; return false;
try{ try {
Vector3fImmutable sl = agent.getLoc(); Vector3fImmutable sl = agent.getLoc();
Vector3fImmutable tl = target.getLoc(); Vector3fImmutable tl = target.getLoc();
//add Hitbox's to range. //add Hitbox's to range.
float range = agent.getRange(); float range = agent.getRange();
range += CombatManager.calcHitBox(target) + CombatManager.calcHitBox(agent); range += CombatManager.calcHitBox(target) + CombatManager.calcHitBox(agent);
//if (target instanceof AbstractCharacter)
// if (((AbstractCharacter)target).isMoving())
// range+= 5;
return !(sl.distanceSquared(tl) > sqr(range)); return !(sl.distanceSquared(tl) > sqr(range));
}catch(Exception e){ } catch (Exception e) {
Logger.error( e.toString()); Logger.error(e.toString());
return false; return false;
} }
} }
public static boolean inRangeToAttack2D(Mob agent,AbstractWorldObject target){
if (Float.isNaN(agent.getLoc().x))
return false;
try{
Vector3fImmutable sl = agent.getLoc();
Vector3fImmutable tl = target.getLoc();
//add Hitbox's to range.
float range = agent.getRange();
range += CombatManager.calcHitBox(target) + CombatManager.calcHitBox(agent);
//if (target instanceof AbstractCharacter)
// if (((AbstractCharacter)target).isMoving())
// range+= 5;
return !(sl.distanceSquared2D(tl) > sqr(range)); public static boolean inRange2D(AbstractWorldObject entity1, AbstractWorldObject entity2, double range) {
}catch(Exception e){
Logger.error( e.toString());
return false;
}
}
public static boolean inRange2D(AbstractWorldObject entity1, AbstractWorldObject entity2, double range){
return entity1.getLoc().distance2D(entity2.getLoc()) < range; return entity1.getLoc().distance2D(entity2.getLoc()) < range;
} }
public static void swingIsBlock(Mob agent,AbstractWorldObject target, int animation) {
public static void swingIsBlock(Mob agent, AbstractWorldObject target, int animation) {
if (!target.isAlive()) if (!target.isAlive())
return; return;
TargetedActionMsg msg = new TargetedActionMsg(agent,animation, target, MBServerStatics.COMBAT_SEND_BLOCK); TargetedActionMsg msg = new TargetedActionMsg(agent, animation, target, MBServerStatics.COMBAT_SEND_BLOCK);
if (target.getObjectType() == GameObjectType.PlayerCharacter) if (target.getObjectType() == GameObjectType.PlayerCharacter)
DispatchMessage.dispatchMsgToInterestArea(target, msg, DispatchChannel.PRIMARY, MBServerStatics.CHARACTER_LOAD_RANGE, true,false); DispatchMessage.dispatchMsgToInterestArea(target, msg, DispatchChannel.PRIMARY, MBServerStatics.CHARACTER_LOAD_RANGE, true, false);
else else
DispatchMessage.sendToAllInRange(agent,msg); DispatchMessage.sendToAllInRange(agent, msg);
} }
public static void swingIsParry(Mob agent,AbstractWorldObject target, int animation) {
public static void swingIsParry(Mob agent, AbstractWorldObject target, int animation) {
if (!target.isAlive()) if (!target.isAlive())
return; return;
TargetedActionMsg msg = new TargetedActionMsg(agent,animation, target, MBServerStatics.COMBAT_SEND_PARRY); TargetedActionMsg msg = new TargetedActionMsg(agent, animation, target, MBServerStatics.COMBAT_SEND_PARRY);
if (target.getObjectType() == GameObjectType.PlayerCharacter) if (target.getObjectType() == GameObjectType.PlayerCharacter)
DispatchMessage.dispatchMsgToInterestArea(target, msg, DispatchChannel.PRIMARY, MBServerStatics.CHARACTER_LOAD_RANGE, true,false); DispatchMessage.dispatchMsgToInterestArea(target, msg, DispatchChannel.PRIMARY, MBServerStatics.CHARACTER_LOAD_RANGE, true, false);
else else
DispatchMessage.sendToAllInRange(agent,msg); DispatchMessage.sendToAllInRange(agent, msg);
} }
public static void swingIsDodge(Mob agent,AbstractWorldObject target, int animation) {
public static void swingIsDodge(Mob agent, AbstractWorldObject target, int animation) {
if (!target.isAlive()) if (!target.isAlive())
return; return;
TargetedActionMsg msg = new TargetedActionMsg(agent,animation, target, MBServerStatics.COMBAT_SEND_DODGE); TargetedActionMsg msg = new TargetedActionMsg(agent, animation, target, MBServerStatics.COMBAT_SEND_DODGE);
if (target.getObjectType() == GameObjectType.PlayerCharacter) if (target.getObjectType() == GameObjectType.PlayerCharacter)
DispatchMessage.dispatchMsgToInterestArea(target, msg, DispatchChannel.PRIMARY, MBServerStatics.CHARACTER_LOAD_RANGE, true,false); DispatchMessage.dispatchMsgToInterestArea(target, msg, DispatchChannel.PRIMARY, MBServerStatics.CHARACTER_LOAD_RANGE, true, false);
else else
DispatchMessage.sendToAllInRange(agent,msg); DispatchMessage.sendToAllInRange(agent, msg);
} }
public static void swingIsDamage(Mob agent, AbstractWorldObject target, float damage, int animation){
if(agent.isSiege() == true){ public static void swingIsDamage(Mob agent, AbstractWorldObject target, float damage, int animation) {
if (agent.isSiege() == true) {
damage = ThreadLocalRandom.current().nextInt(1000) + 1500; damage = ThreadLocalRandom.current().nextInt(1000) + 1500;
} }
float trueDamage = damage; float trueDamage = damage;
//target = agent.getCombatTarget();
if (!target.isAlive()) if (!target.isAlive())
return; return;
@ -133,30 +111,33 @@ public class CombatUtilities {
if (trueDamage == 0) if (trueDamage == 0)
return; return;
TargetedActionMsg msg = new TargetedActionMsg(agent,target, damage, animation); TargetedActionMsg msg = new TargetedActionMsg(agent, target, damage, animation);
if (target.getObjectType() == GameObjectType.PlayerCharacter) if (target.getObjectType() == GameObjectType.PlayerCharacter)
DispatchMessage.dispatchMsgToInterestArea(target, msg, DispatchChannel.PRIMARY, MBServerStatics.CHARACTER_LOAD_RANGE, true,false); DispatchMessage.dispatchMsgToInterestArea(target, msg, DispatchChannel.PRIMARY, MBServerStatics.CHARACTER_LOAD_RANGE, true, false);
else else
DispatchMessage.sendToAllInRange(agent,msg); DispatchMessage.sendToAllInRange(agent, msg);
//check damage shields //check damage shields
if(AbstractWorldObject.IsAbstractCharacter(target) && target.isAlive() && target.getObjectType() != GameObjectType.Mob) if (AbstractWorldObject.IsAbstractCharacter(target) && target.isAlive() && target.getObjectType() != GameObjectType.Mob)
CombatManager.handleDamageShields(agent,(AbstractCharacter)target, damage); CombatManager.handleDamageShields(agent, (AbstractCharacter) target, damage);
} }
public static boolean canSwing(Mob agent) { public static boolean canSwing(Mob agent) {
return (agent.isAlive() && !agent.getBonuses().getBool(ModType.Stunned, SourceType.None)); return (agent.isAlive() && !agent.getBonuses().getBool(ModType.Stunned, SourceType.None));
} }
public static void swingIsMiss(Mob agent,AbstractWorldObject target, int animation) {
TargetedActionMsg msg = new TargetedActionMsg(agent,target, 0f, animation); public static void swingIsMiss(Mob agent, AbstractWorldObject target, int animation) {
TargetedActionMsg msg = new TargetedActionMsg(agent, target, 0f, animation);
if (target.getObjectType() == GameObjectType.PlayerCharacter) if (target.getObjectType() == GameObjectType.PlayerCharacter)
DispatchMessage.dispatchMsgToInterestArea(target, msg, DispatchChannel.PRIMARY, MBServerStatics.CHARACTER_LOAD_RANGE, true,false); DispatchMessage.dispatchMsgToInterestArea(target, msg, DispatchChannel.PRIMARY, MBServerStatics.CHARACTER_LOAD_RANGE, true, false);
else else
DispatchMessage.sendToAllInRange(agent,msg); DispatchMessage.sendToAllInRange(agent, msg);
} }
public static boolean triggerDefense(Mob agent, AbstractWorldObject target) { public static boolean triggerDefense(Mob agent, AbstractWorldObject target) {
int defenseScore = 0; int defenseScore = 0;
int attackScore = agent.getAtrHandOne(); int attackScore = agent.getAtrHandOne();
@ -166,7 +147,7 @@ public class CombatUtilities {
break; break;
case Mob: case Mob:
Mob mob = (Mob)target; Mob mob = (Mob) target;
if (mob.isSiege()) if (mob.isSiege())
defenseScore = attackScore; defenseScore = attackScore;
break; break;
@ -174,8 +155,6 @@ public class CombatUtilities {
return false; return false;
} }
int hitChance; int hitChance;
if (attackScore > defenseScore || defenseScore == 0) if (attackScore > defenseScore || defenseScore == 0)
hitChance = 94; hitChance = 94;
@ -186,25 +165,29 @@ public class CombatUtilities {
if (dif <= 0.8f) if (dif <= 0.8f)
hitChance = 4; hitChance = 4;
else else
hitChance = ((int)(450 * (dif - 0.8f)) + 4); hitChance = ((int) (450 * (dif - 0.8f)) + 4);
if (target.getObjectType() == GameObjectType.Building) if (target.getObjectType() == GameObjectType.Building)
hitChance = 100; hitChance = 100;
} }
return ThreadLocalRandom.current().nextInt(100) > hitChance; return ThreadLocalRandom.current().nextInt(100) > hitChance;
} }
public static boolean triggerBlock(Mob agent,AbstractWorldObject ac) {
return triggerPassive(agent,ac, "Block"); public static boolean triggerBlock(Mob agent, AbstractWorldObject ac) {
return triggerPassive(agent, ac, "Block");
} }
public static boolean triggerParry(Mob agent,AbstractWorldObject ac) {
return triggerPassive(agent,ac, "Parry"); public static boolean triggerParry(Mob agent, AbstractWorldObject ac) {
return triggerPassive(agent, ac, "Parry");
} }
public static boolean triggerDodge(Mob agent,AbstractWorldObject ac) {
return triggerPassive(agent,ac, "Dodge"); public static boolean triggerDodge(Mob agent, AbstractWorldObject ac) {
return triggerPassive(agent, ac, "Dodge");
} }
public static boolean triggerPassive(Mob agent,AbstractWorldObject ac, String type) {
public static boolean triggerPassive(Mob agent, AbstractWorldObject ac, String type) {
float chance = 0; float chance = 0;
if (AbstractWorldObject.IsAbstractCharacter(ac)) if (AbstractWorldObject.IsAbstractCharacter(ac))
chance = ((AbstractCharacter)ac).getPassiveChance(type, agent.getLevel(), true); chance = ((AbstractCharacter) ac).getPassiveChance(type, agent.getLevel(), true);
if (chance > 75f) if (chance > 75f)
chance = 75f; chance = 75f;
@ -213,132 +196,140 @@ public class CombatUtilities {
return ThreadLocalRandom.current().nextInt(100) < chance; return ThreadLocalRandom.current().nextInt(100) < chance;
} }
public static void combatCycle(Mob agent,AbstractWorldObject target, boolean mainHand, ItemBase wb) {
if (!agent.isAlive() || !target.isAlive()) return; public static void combatCycle(Mob agent, AbstractWorldObject target, boolean mainHand, ItemBase wb) {
if (!agent.isAlive() || !target.isAlive())
return;
if (target.getObjectType() == GameObjectType.PlayerCharacter) if (target.getObjectType() == GameObjectType.PlayerCharacter)
if (!((PlayerCharacter)target).isActive()) if (!((PlayerCharacter) target).isActive())
return; return;
int anim = 75; int anim = 75;
float speed = 30f; float speed;
if (mainHand) if (mainHand)
speed = agent.getSpeedHandOne(); speed = agent.getSpeedHandOne();
else else
speed = agent.getSpeedHandTwo(); speed = agent.getSpeedHandTwo();
DamageType dt = DamageType.Crush; DamageType dt = DamageType.Crush;
if (agent.isSiege()) if (agent.isSiege())
dt = DamageType.Siege; dt = DamageType.Siege;
if (wb != null) { if (wb != null) {
anim = CombatManager.getSwingAnimation(wb, null,mainHand); anim = CombatManager.getSwingAnimation(wb, null, mainHand);
dt = wb.getDamageType(); dt = wb.getDamageType();
} else if (!mainHand) } else if (!mainHand)
return; return;
Resists res = null; Resists res = null;
PlayerBonuses bonus = null; PlayerBonuses bonus = null;
switch(target.getObjectType()){
switch (target.getObjectType()) {
case Building: case Building:
res = ((Building)target).getResists(); res = ((Building) target).getResists();
break; break;
case PlayerCharacter: case PlayerCharacter:
res = ((PlayerCharacter)target).getResists(); res = ((PlayerCharacter) target).getResists();
bonus = ((PlayerCharacter)target).getBonuses(); bonus = ((PlayerCharacter) target).getBonuses();
break; break;
case Mob: case Mob:
Mob mob = (Mob)target; Mob mob = (Mob) target;
res = mob.getResists(); res = mob.getResists();
bonus = ((Mob)target).getBonuses(); bonus = ((Mob) target).getBonuses();
break; break;
} }
//must not be immune to all or immune to attack //must not be immune to all or immune to attack
if (bonus != null && !bonus.getBool(ModType.NoMod, SourceType.ImmuneToAttack)) if (bonus != null && !bonus.getBool(ModType.NoMod, SourceType.ImmuneToAttack))
if (res != null &&(res.immuneToAll() || res.immuneToAttacks() || res.immuneTo(dt))) if (res != null && (res.immuneToAll() || res.immuneToAttacks() || res.immuneTo(dt)))
return; return;
int passiveAnim = CombatManager.getSwingAnimation(wb, null,mainHand); int passiveAnim = CombatManager.getSwingAnimation(wb, null, mainHand);
if(canSwing(agent)) { if (canSwing(agent)) {
if(triggerDefense(agent,target)) { if (triggerDefense(agent, target)) {
swingIsMiss(agent, target, passiveAnim); swingIsMiss(agent, target, passiveAnim);
return; return;
} } else if (triggerDodge(agent, target)) {
else if(triggerDodge(agent,target)) {
swingIsDodge(agent, target, passiveAnim); swingIsDodge(agent, target, passiveAnim);
return; return;
} } else if (triggerParry(agent, target)) {
else if (triggerParry(agent, target)){
swingIsParry(agent, target, passiveAnim); swingIsParry(agent, target, passiveAnim);
return; return;
} } else if (triggerBlock(agent, target)) {
else if(triggerBlock(agent,target)) {
swingIsBlock(agent, target, passiveAnim); swingIsBlock(agent, target, passiveAnim);
return; return;
} }
if(agent.getEquip().get(1) != null && agent.getEquip().get(2) != null && agent.getEquip().get(2).getItemBase().isShield() == false){ if (agent.getEquip().get(1) != null && agent.getEquip().get(2) != null && agent.getEquip().get(2).getItemBase().isShield() == false) {
//mob is duel wielding and should conduct an attack for each hand //mob is duel wielding and should conduct an attack for each hand
ItemBase weapon1 = agent.getEquip().get(1).getItemBase(); ItemBase weapon1 = agent.getEquip().get(1).getItemBase();
double range1 = getMaxDmg(weapon1.getMinDamage(),agent,weapon1) - getMinDmg(weapon1.getMinDamage(),agent,weapon1); double range1 = getMaxDmg(weapon1.getMinDamage(), agent, weapon1) - getMinDmg(weapon1.getMinDamage(), agent, weapon1);
double damage1 = getMinDmg(weapon1.getMinDamage(),agent,weapon1) + ((ThreadLocalRandom.current().nextFloat() * range1) + (ThreadLocalRandom.current().nextFloat() * range1)) / 2; double damage1 = getMinDmg(weapon1.getMinDamage(), agent, weapon1) + ((ThreadLocalRandom.current().nextFloat() * range1) + (ThreadLocalRandom.current().nextFloat() * range1)) / 2;
swingIsDamage(agent,target, (float) damage1, CombatManager.getSwingAnimation(weapon1, null,true)); swingIsDamage(agent, target, (float) damage1, CombatManager.getSwingAnimation(weapon1, null, true));
ItemBase weapon2 = agent.getEquip().get(2).getItemBase(); ItemBase weapon2 = agent.getEquip().get(2).getItemBase();
double range2 = getMaxDmg(weapon2.getMinDamage(),agent,weapon2) - getMinDmg(weapon2.getMinDamage(),agent,weapon2); double range2 = getMaxDmg(weapon2.getMinDamage(), agent, weapon2) - getMinDmg(weapon2.getMinDamage(), agent, weapon2);
double damage2 = getMinDmg(weapon2.getMinDamage(),agent,weapon2) + ((ThreadLocalRandom.current().nextFloat() * range2) + (ThreadLocalRandom.current().nextFloat() * range2)) / 2; double damage2 = getMinDmg(weapon2.getMinDamage(), agent, weapon2) + ((ThreadLocalRandom.current().nextFloat() * range2) + (ThreadLocalRandom.current().nextFloat() * range2)) / 2;
swingIsDamage(agent,target, (float) damage2, CombatManager.getSwingAnimation(weapon1, null,false)); swingIsDamage(agent, target, (float) damage2, CombatManager.getSwingAnimation(weapon1, null, false));
} else{ } else {
swingIsDamage(agent,target, determineDamage(agent), anim); swingIsDamage(agent, target, determineDamage(agent), anim);
} }
if (agent.getWeaponPower() != null) if (agent.getWeaponPower() != null)
agent.getWeaponPower().attack(target, MBServerStatics.ONE_MINUTE); agent.getWeaponPower().attack(target, MBServerStatics.ONE_MINUTE);
} }
if (target.getObjectType().equals(GameObjectType.PlayerCharacter)){ if (target.getObjectType().equals(GameObjectType.PlayerCharacter)) {
PlayerCharacter player = (PlayerCharacter)target; PlayerCharacter player = (PlayerCharacter) target;
if (player.getDebug(64)){
ChatManager.chatSayInfo(player, "Debug Combat: Mob UUID " + agent.getObjectUUID() + " || Building ID = " + agent.getBuildingID() + " || Floor = " + agent.getInFloorID() + " || Level = " + agent.getInBuilding() );//combat debug if (player.getDebug(64))
} ChatManager.chatSayInfo(player, "Debug Combat: Mob UUID " + agent.getObjectUUID() + " || Building ID = " + agent.getBuildingID() + " || Floor = " + agent.getInFloorID() + " || Level = " + agent.getInBuilding());//combat debug
} }
//SIEGE MONSTERS DO NOT ATTACK GUARDSs //SIEGE MONSTERS DO NOT ATTACK GUARDSs
if (target.getObjectType() == GameObjectType.Mob) if (target.getObjectType() == GameObjectType.Mob)
if (((Mob)target).isSiege()) if (((Mob) target).isSiege())
return; return;
//handle the retaliate //handle the retaliate
if (AbstractWorldObject.IsAbstractCharacter(target)) if (AbstractWorldObject.IsAbstractCharacter(target))
CombatManager.handleRetaliate((AbstractCharacter)target, agent); CombatManager.handleRetaliate((AbstractCharacter) target, agent);
if (target.getObjectType() == GameObjectType.Mob){ if (target.getObjectType() == GameObjectType.Mob) {
Mob targetMob = (Mob)target; Mob targetMob = (Mob) target;
if (targetMob.isSiege()) if (targetMob.isSiege())
return; return;
} }
} }
public static float determineDamage(Mob agent) { public static float determineDamage(Mob agent) {
if(agent == null){
//early exit for null //early exit for null
if (agent == null)
return 0; return 0;
}
AbstractWorldObject target = agent.getCombatTarget(); AbstractWorldObject target = agent.getCombatTarget();
if(target == null){
//early exit for null target if (target == null)
return 0; return 0;
}
float damage = 0; float damage = 0;
DamageType dt = getDamageType(agent); DamageType dt = getDamageType(agent);
if(agent.isSummonedPet() == true || agent.isPet() == true || agent.isNecroPet() == true) { if (agent.isSummonedPet() == true || agent.isPet() == true || agent.isNecroPet() == true) {
damage = calculatePetDamage(agent); damage = calculatePetDamage(agent);
}else if(agent.isPlayerGuard() == true){ } else if (agent.isPlayerGuard() == true) {
damage = calculateGuardDamage(agent); //damage = calculateGuardDamage(agent);
}else if (agent.getLevel() > 80) { damage = calculateMobDamage(agent);
} else if (agent.getLevel() > 80) {
damage = calculateEpicDamage(agent); damage = calculateEpicDamage(agent);
} else{ } else {
damage = calculateMobDamage(agent); damage = calculateMobDamage(agent);
} }
if (AbstractWorldObject.IsAbstractCharacter(target)) { if (AbstractWorldObject.IsAbstractCharacter(target)) {
@ -354,16 +345,18 @@ public class CombatUtilities {
} }
return damage; return damage;
} }
public static DamageType getDamageType(Mob agent){
public static DamageType getDamageType(Mob agent) {
DamageType dt = DamageType.Crush; DamageType dt = DamageType.Crush;
if(agent.getEquip().get(1) != null ){ if (agent.getEquip().get(1) != null) {
return agent.getEquip().get(1).getItemBase().getDamageType(); return agent.getEquip().get(1).getItemBase().getDamageType();
} }
if(agent.getEquip().get(2) != null && agent.getEquip().get(2).getItemBase().isShield() == false){ if (agent.getEquip().get(2) != null && agent.getEquip().get(2).getItemBase().isShield() == false) {
return agent.getEquip().get(2).getItemBase().getDamageType(); return agent.getEquip().get(2).getItemBase().getDamageType();
} }
return dt; return dt;
} }
public static int calculatePetDamage(Mob agent) { public static int calculatePetDamage(Mob agent) {
//damage calc for pet //damage calc for pet
float range; float range;
@ -372,90 +365,101 @@ public class CombatUtilities {
float max = 60; float max = 60;
AbstractWorldObject target = agent.getCombatTarget(); AbstractWorldObject target = agent.getCombatTarget();
float dmgMultiplier = 1 + agent.getBonuses().getFloatPercentAll(ModType.MeleeDamageModifier, SourceType.None); float dmgMultiplier = 1 + agent.getBonuses().getFloatPercentAll(ModType.MeleeDamageModifier, SourceType.None);
float str = agent.getStatStrCurrent(); double minDmg = getMinDmg(min, agent, null);
float dex = agent.getStatDexCurrent(); double maxDmg = getMaxDmg(max, agent, null);
double minDmg = getMinDmg(min,agent, null);
double maxDmg = getMaxDmg(max,agent, null);
dmgMultiplier += agent.getLevel() / 10; dmgMultiplier += agent.getLevel() / 10;
range = (float) (maxDmg - minDmg); range = (float) (maxDmg - minDmg);
damage = min + ((ThreadLocalRandom.current().nextFloat() * range) + (ThreadLocalRandom.current().nextFloat() * range)) / 2; damage = min + ((ThreadLocalRandom.current().nextFloat() * range) + (ThreadLocalRandom.current().nextFloat() * range)) / 2;
return (int) (damage * dmgMultiplier); return (int) (damage * dmgMultiplier);
} }
public static int calculateGuardDamage(Mob agent){
public static int calculateGuardDamage(Mob agent) {
//damage calc for guard //damage calc for guard
ItemBase weapon = agent.getEquip().get(1).getItemBase(); ItemBase weapon = agent.getEquip().get(1).getItemBase();
AbstractWorldObject target = agent.getCombatTarget(); AbstractWorldObject target = agent.getCombatTarget();
float dmgMultiplier = 1 + agent.getBonuses().getFloatPercentAll(ModType.MeleeDamageModifier, SourceType.None); float dmgMultiplier = 1 + agent.getBonuses().getFloatPercentAll(ModType.MeleeDamageModifier, SourceType.None);
double minDmg = weapon.getMinDamage(); double minDmg = weapon.getMinDamage();
double maxDmg = weapon.getMaxDamage(); double maxDmg = weapon.getMaxDamage();
float str = agent.getStatStrCurrent(); double min = getMinDmg(minDmg, agent, weapon);
float dex = agent.getStatDexCurrent(); double max = getMaxDmg(maxDmg, agent, weapon);
double min = getMinDmg(minDmg,agent, weapon);
double max = getMaxDmg(maxDmg,agent, weapon);
DamageType dt = weapon.getDamageType(); DamageType dt = weapon.getDamageType();
double range = max - min; double range = max - min;
double damage = min + ((ThreadLocalRandom.current().nextFloat() * range) + (ThreadLocalRandom.current().nextFloat() * range)) / 2; double damage = min + ((ThreadLocalRandom.current().nextFloat() * range) + (ThreadLocalRandom.current().nextFloat() * range)) / 2;
if (AbstractWorldObject.IsAbstractCharacter(target)) if (AbstractWorldObject.IsAbstractCharacter(target))
if (((AbstractCharacter) target).isSit()) if (((AbstractCharacter) target).isSit())
damage *= 2.5f; //increase damage if sitting damage *= 2.5f; //increase damage if sitting
if (AbstractWorldObject.IsAbstractCharacter(target)) if (AbstractWorldObject.IsAbstractCharacter(target))
return (int) (((AbstractCharacter) target).getResists().getResistedDamage((AbstractCharacter) agent, (AbstractCharacter) target, dt, (float) damage, 0) * dmgMultiplier); return (int) (((AbstractCharacter) target).getResists().getResistedDamage(agent, (AbstractCharacter) target, dt, (float) damage, 0) * dmgMultiplier);
return 0; return 0;
} }
public static int calculateEpicDamage(Mob agent){
public static int calculateEpicDamage(Mob agent) {
//handle r8 mob damage //handle r8 mob damage
DamageType dt = DamageType.Crush; DamageType dt = DamageType.Crush;
AbstractWorldObject target = agent.getCombatTarget(); AbstractWorldObject target = agent.getCombatTarget();
float dmgMultiplier = 1 + agent.getBonuses().getFloatPercentAll(ModType.MeleeDamageModifier, SourceType.None); float dmgMultiplier = 1 + agent.getBonuses().getFloatPercentAll(ModType.MeleeDamageModifier, SourceType.None);
if (agent.getEquip().get(1).getItemBase() != null) { if (agent.getEquip().get(1).getItemBase() != null) {
dt = agent.getEquip().get(1).getItemBase().getDamageType(); dt = agent.getEquip().get(1).getItemBase().getDamageType();
} else if(agent.getEquip().get(2).getItemBase() != null && agent.getEquip().get(2).getItemBase().isShield() == false){ } else if (agent.getEquip().get(2).getItemBase() != null && agent.getEquip().get(2).getItemBase().isShield() == false) {
dt = agent.getEquip().get(2).getItemBase().getDamageType(); dt = agent.getEquip().get(2).getItemBase().getDamageType();
} }
double min = agent.getMobBase().getMinDmg(); double min = agent.getMobBase().getMinDmg();
double max = agent.getMobBase().getMaxDmg(); double max = agent.getMobBase().getMaxDmg();
double range = max - min; double range = max - min;
double damage = min + ((ThreadLocalRandom.current().nextFloat() * range) + (ThreadLocalRandom.current().nextFloat() * range)) / 2; double damage = min + ((ThreadLocalRandom.current().nextFloat() * range) + (ThreadLocalRandom.current().nextFloat() * range)) / 2;
return (int) (((AbstractCharacter) target).getResists().getResistedDamage((AbstractCharacter) agent, (AbstractCharacter) target, dt, (float) damage, 0) * dmgMultiplier); return (int) (((AbstractCharacter) target).getResists().getResistedDamage(agent, (AbstractCharacter) target, dt, (float) damage, 0) * dmgMultiplier);
} }
public static int calculateMobDamage(Mob agent){
public static int calculateMobDamage(Mob agent) {
ItemBase weapon = null; ItemBase weapon = null;
double minDmg; double minDmg;
double maxDmg; double maxDmg;
DamageType dt; DamageType dt;
if(agent.getEquip().get(1) != null){
//mainhand damage //main hand or offhand damage
if (agent.getEquip().get(1) != null)
weapon = agent.getEquip().get(1).getItemBase(); weapon = agent.getEquip().get(1).getItemBase();
} else if(agent.getEquip().get(2) != null){ else if (agent.getEquip().get(2) != null)
//offhand damage
weapon = agent.getEquip().get(2).getItemBase(); weapon = agent.getEquip().get(2).getItemBase();
}
if(weapon != null){ if (weapon != null) {
minDmg = getMinDmg(weapon.getMinDamage(),agent,weapon); minDmg = getMinDmg(weapon.getMinDamage(), agent, weapon);
maxDmg = getMaxDmg(weapon.getMaxDamage(),agent, weapon); maxDmg = getMaxDmg(weapon.getMaxDamage(), agent, weapon);
dt = weapon.getDamageType(); dt = weapon.getDamageType();
}else{ } else {
minDmg = agent.getMobBase().getDamageMin(); minDmg = agent.getMobBase().getDamageMin();
maxDmg = agent.getMobBase().getDamageMax(); maxDmg = agent.getMobBase().getDamageMax();
dt = DamageType.Crush; dt = DamageType.Crush;
} }
AbstractWorldObject target = agent.getCombatTarget(); AbstractWorldObject target = agent.getCombatTarget();
float dmgMultiplier = 1 + agent.getBonuses().getFloatPercentAll(ModType.MeleeDamageModifier, SourceType.None); float dmgMultiplier = 1 + agent.getBonuses().getFloatPercentAll(ModType.MeleeDamageModifier, SourceType.None);
double range = maxDmg - minDmg; double range = maxDmg - minDmg;
double damage = minDmg + ((ThreadLocalRandom.current().nextFloat() * range) + (ThreadLocalRandom.current().nextFloat() * range)) / 2; double damage = minDmg + ((ThreadLocalRandom.current().nextFloat() * range) + (ThreadLocalRandom.current().nextFloat() * range)) / 2;
if (AbstractWorldObject.IsAbstractCharacter(target)) if (AbstractWorldObject.IsAbstractCharacter(target))
if (((AbstractCharacter) target).isSit()) if (((AbstractCharacter) target).isSit())
damage *= 2.5f; //increase damage if sitting damage *= 2.5f; //increase damage if sitting
if (AbstractWorldObject.IsAbstractCharacter(target)) if (AbstractWorldObject.IsAbstractCharacter(target))
return (int) (((AbstractCharacter) target).getResists().getResistedDamage((AbstractCharacter) agent, (AbstractCharacter) target, dt, (float) damage, 0) * dmgMultiplier); return (int) (((AbstractCharacter) target).getResists().getResistedDamage(agent, (AbstractCharacter) target, dt, (float) damage, 0) * dmgMultiplier);
return 0; return 0;
} }
public static double getMinDmg(double min, Mob agent, ItemBase weapon){
public static double getMinDmg(double min, Mob agent, ItemBase weapon) {
int primary = agent.getStatStrCurrent(); int primary = agent.getStatStrCurrent();
int secondary = agent.getStatDexCurrent(); int secondary = agent.getStatDexCurrent();
int focusLevel = 0; int focusLevel = 0;
int masteryLevel = 0; int masteryLevel = 0;
if(weapon != null) {
if (weapon != null) {
if (weapon.isStrBased() == true) { if (weapon.isStrBased() == true) {
primary = agent.getStatStrCurrent(); primary = agent.getStatStrCurrent();
secondary = agent.getStatDexCurrent(); secondary = agent.getStatDexCurrent();
@ -470,35 +474,34 @@ public class CombatUtilities {
} }
} }
} }
return min * (pow(0.0048*primary +.049*(primary-0.75),0.5) + pow(0.0066*secondary + 0.064*(secondary-0.75),0.5) + + 0.01*(focusLevel + masteryLevel)); return min * (pow(0.0048 * primary + .049 * (primary - 0.75), 0.5) + pow(0.0066 * secondary + 0.064 * (secondary - 0.75), 0.5) + +0.01 * (focusLevel + masteryLevel));
} }
public static double getMaxDmg(double max, Mob agent, ItemBase weapon){
public static double getMaxDmg(double max, Mob agent, ItemBase weapon) {
int primary = agent.getStatStrCurrent(); int primary = agent.getStatStrCurrent();
int secondary = agent.getStatDexCurrent(); int secondary = agent.getStatDexCurrent();
int focusLevel = 0; int focusLevel = 0;
int masteryLevel = 0; int masteryLevel = 0;
if (weapon != null) { if (weapon != null) {
if(weapon.isStrBased() == true){
if (weapon.isStrBased() == true) {
primary = agent.getStatStrCurrent(); primary = agent.getStatStrCurrent();
secondary = agent.getStatDexCurrent(); secondary = agent.getStatDexCurrent();
} } else {
else{
primary = agent.getStatDexCurrent(); primary = agent.getStatDexCurrent();
secondary = agent.getStatStrCurrent(); secondary = agent.getStatStrCurrent();
} }
if(agent.getSkills().containsKey(weapon.getSkillRequired())) { if (agent.getSkills().containsKey(weapon.getSkillRequired()))
focusLevel = (int) agent.getSkills().get(weapon.getSkillRequired()).getModifiedAmount(); focusLevel = (int) agent.getSkills().get(weapon.getSkillRequired()).getModifiedAmount();
}
if(agent.getSkills().containsKey(weapon.getSkillRequired())) { if (agent.getSkills().containsKey(weapon.getSkillRequired()))
masteryLevel = (int) agent.getSkills().get(weapon.getMastery()).getModifiedAmount(); masteryLevel = (int) agent.getSkills().get(weapon.getMastery()).getModifiedAmount();
} }
return max * (pow(0.0124 * primary + 0.118 * (primary - 0.75), 0.5) + pow(0.0022 * secondary + 0.028 * (secondary - 0.75), 0.5) + 0.0075 * (focusLevel + masteryLevel));
} }
return max * (pow(0.0124*primary + 0.118*(primary -0.75),0.5) + pow(0.0022*secondary + 0.028*(secondary-0.75),0.5) + 0.0075*(focusLevel + masteryLevel));
}
public static boolean RunAIRandom(){
int random = ThreadLocalRandom.current().nextInt(4);
return random == 0;
}
} }

76
src/engine/ai/utilities/MovementUtilities.java

@ -7,7 +7,6 @@
// www.magicbane.com // www.magicbane.com
package engine.ai.utilities; package engine.ai.utilities;
import engine.Enum; import engine.Enum;
@ -30,11 +29,10 @@ import static engine.math.FastMath.sqrt;
public class MovementUtilities { public class MovementUtilities {
public static boolean inRangeOfBindLocation(Mob agent){ public static boolean inRangeOfBindLocation(Mob agent) {
if (agent.isPlayerGuard()){ if (agent.isPlayerGuard()) {
Mob guardCaptain = null; Mob guardCaptain = null;
if (agent.getContract() != null) if (agent.getContract() != null)
@ -42,20 +40,18 @@ public class MovementUtilities {
else else
guardCaptain = (Mob) agent.npcOwner; guardCaptain = (Mob) agent.npcOwner;
if (guardCaptain != null){ if (guardCaptain != null) {
Building barracks = guardCaptain.building; Building barracks = guardCaptain.building;
if (barracks != null){ if (barracks != null) {
City city = barracks.getCity(); City city = barracks.getCity();
if (city != null){ if (city != null) {
Building tol = city.getTOL(); Building tol = city.getTOL();
//Guards recall distance = 814. //Guards recall distance = 814.
if (tol != null){ if (tol != null) {
if (agent.getLoc().distanceSquared2D(tol.getLoc()) > sqr(Enum.CityBoundsType.ZONE.extents)) { return !(agent.getLoc().distanceSquared2D(tol.getLoc()) > sqr(Enum.CityBoundsType.ZONE.extents));
return false;
}
} }
} }
@ -66,12 +62,12 @@ public class MovementUtilities {
} }
Vector3fImmutable sl = new Vector3fImmutable(agent.getLoc().getX(), 0, agent.getLoc().getZ()); Vector3fImmutable sl = new Vector3fImmutable(agent.getLoc().getX(), 0, agent.getLoc().getZ());
Vector3fImmutable tl = new Vector3fImmutable(agent.getTrueBindLoc().x,0,agent.getTrueBindLoc().z); Vector3fImmutable tl = new Vector3fImmutable(agent.getTrueBindLoc().x, 0, agent.getTrueBindLoc().z);
float distanceSquaredToTarget = sl.distanceSquared2D(tl); //distance to center of target float distanceSquaredToTarget = sl.distanceSquared2D(tl); //distance to center of target
float zoneRange = 250; float zoneRange = 250;
if (agent.getParentZone() != null){ if (agent.getParentZone() != null) {
if (agent.getParentZone().getBounds() != null) if (agent.getParentZone().getBounds() != null)
zoneRange = agent.getParentZone().getBounds().getHalfExtents().x * 2; zoneRange = agent.getParentZone().getBounds().getHalfExtents().x * 2;
} }
@ -87,10 +83,10 @@ public class MovementUtilities {
} }
public static boolean inRangeToAggro(Mob agent,PlayerCharacter target){ public static boolean inRangeToAggro(Mob agent, PlayerCharacter target) {
Vector3fImmutable sl = agent.getLoc(); Vector3fImmutable sl = agent.getLoc();
Vector3fImmutable tl =target.getLoc(); Vector3fImmutable tl = target.getLoc();
float distanceSquaredToTarget = sl.distanceSquared2D(tl) - sqr(agent.calcHitBox() + target.calcHitBox()); //distance to center of target float distanceSquaredToTarget = sl.distanceSquared2D(tl) - sqr(agent.calcHitBox() + target.calcHitBox()); //distance to center of target
float range = MBServerStatics.AI_BASE_AGGRO_RANGE; float range = MBServerStatics.AI_BASE_AGGRO_RANGE;
@ -102,7 +98,7 @@ public class MovementUtilities {
} }
public static boolean inRangeDropAggro(Mob agent,PlayerCharacter target){ public static boolean inRangeDropAggro(Mob agent, PlayerCharacter target) {
Vector3fImmutable sl = agent.getLoc(); Vector3fImmutable sl = agent.getLoc();
Vector3fImmutable tl = target.getLoc(); Vector3fImmutable tl = target.getLoc();
@ -119,7 +115,7 @@ public class MovementUtilities {
} }
public static Vector3fImmutable GetMoveLocation(Mob aiAgent, AbstractCharacter aggroTarget){ public static Vector3fImmutable GetMoveLocation(Mob aiAgent, AbstractCharacter aggroTarget) {
// Player isnt moving and neither is mob. Just return // Player isnt moving and neither is mob. Just return
// the mobile's current location. Ain't goin nowhere! // the mobile's current location. Ain't goin nowhere!
@ -129,15 +125,15 @@ public class MovementUtilities {
if ((aggroTarget.isMoving() == false)) if ((aggroTarget.isMoving() == false))
return aggroTarget.getLoc(); return aggroTarget.getLoc();
if (aggroTarget.getEndLoc().x != 0){ if (aggroTarget.getEndLoc().x != 0) {
float aggroTargetDistanceSquared = aggroTarget.getLoc().distanceSquared2D(aggroTarget.getEndLoc()); float aggroTargetDistanceSquared = aggroTarget.getLoc().distanceSquared2D(aggroTarget.getEndLoc());
float aiAgentDistanceSquared = aiAgent.getLoc().distanceSquared2D(aggroTarget.getEndLoc()); float aiAgentDistanceSquared = aiAgent.getLoc().distanceSquared2D(aggroTarget.getEndLoc());
if (aiAgentDistanceSquared >= aggroTargetDistanceSquared) if (aiAgentDistanceSquared >= aggroTargetDistanceSquared)
return aggroTarget.getEndLoc(); return aggroTarget.getEndLoc();
else{ else {
float distanceToMove = sqrt(aggroTargetDistanceSquared + aiAgentDistanceSquared) *.5f; float distanceToMove = sqrt(aggroTargetDistanceSquared + aiAgentDistanceSquared) * .5f;
return aggroTarget.getFaceDir().scaleAdd(distanceToMove, aggroTarget.getLoc()); return aggroTarget.getFaceDir().scaleAdd(distanceToMove, aggroTarget.getLoc());
@ -151,7 +147,7 @@ public class MovementUtilities {
return aiAgent.getLoc().ClosestPointOnLine(aggroTarget.getLoc(), aggroTarget.getEndLoc()); return aiAgent.getLoc().ClosestPointOnLine(aggroTarget.getLoc(), aggroTarget.getEndLoc());
} }
public static void moveToLocation(Mob agent,Vector3fImmutable newLocation, float offset){ public static void moveToLocation(Mob agent, Vector3fImmutable newLocation, float offset) {
try { try {
//don't move farther than 30 units from player. //don't move farther than 30 units from player.
@ -162,42 +158,42 @@ public class MovementUtilities {
agent.setFaceDir(newLoc.subtract2D(agent.getLoc()).normalize()); agent.setFaceDir(newLoc.subtract2D(agent.getLoc()).normalize());
aiMove(agent,newLoc,false); aiMove(agent, newLoc, false);
} catch (Exception e) { } catch (Exception e) {
Logger.error( e.toString()); Logger.error(e.toString());
} }
} }
public static boolean canMove(Mob agent) { public static boolean canMove(Mob agent) {
if (agent.getMobBase() != null && Enum.MobFlagType.SENTINEL.elementOf(agent.getMobBase().getFlags())) if (agent.getMobBase() != null && Enum.MobFlagType.SENTINEL.elementOf(agent.getMobBase().getFlags()))
return false; return false;
return (agent.isAlive() && !agent.getBonuses().getBool(ModType.Stunned,SourceType.None) && !agent.getBonuses().getBool(ModType.CannotMove, SourceType.None)); return (agent.isAlive() && !agent.getBonuses().getBool(ModType.Stunned, SourceType.None) && !agent.getBonuses().getBool(ModType.CannotMove, SourceType.None));
} }
public static Vector3fImmutable randomPatrolLocation(Mob agent,Vector3fImmutable center, float radius){ public static Vector3fImmutable randomPatrolLocation(Mob agent, Vector3fImmutable center, float radius) {
//Determing where I want to move. //Determing where I want to move.
return new Vector3fImmutable((center.x - radius) + ((ThreadLocalRandom.current().nextFloat()+.1f*2)*radius), return new Vector3fImmutable((center.x - radius) + ((ThreadLocalRandom.current().nextFloat() + .1f * 2) * radius),
center.y, center.y,
(center.z - radius) + ((ThreadLocalRandom.current().nextFloat()+.1f *2)*radius)); (center.z - radius) + ((ThreadLocalRandom.current().nextFloat() + .1f * 2) * radius));
} }
public static Long estimateMovementTime(Mob agent) { public static Long estimateMovementTime(Mob agent) {
if(agent.getEndLoc().x == 0 && agent.getEndLoc().y == 0) if (agent.getEndLoc().x == 0 && agent.getEndLoc().y == 0)
return 0L; return 0L;
return (long) ((agent.getLoc().distance2D(agent.getEndLoc())*1000)/agent.getSpeed()); return (long) ((agent.getLoc().distance2D(agent.getEndLoc()) * 1000) / agent.getSpeed());
} }
public static void aiMove(Mob agent,Vector3fImmutable vect, boolean isWalking) { public static void aiMove(Mob agent, Vector3fImmutable vect, boolean isWalking) {
//update our walk/run state. //update our walk/run state.
if (isWalking && !agent.isWalk()){ if (isWalking && !agent.isWalk()) {
agent.setWalkMode(true); agent.setWalkMode(true);
MovementManager.sendRWSSMsg(agent); MovementManager.sendRWSSMsg(agent);
}else if(!isWalking && agent.isWalk()){ } else if (!isWalking && agent.isWalk()) {
agent.setWalkMode(false); agent.setWalkMode(false);
MovementManager.sendRWSSMsg(agent); MovementManager.sendRWSSMsg(agent);
} }
@ -225,7 +221,6 @@ public class MovementUtilities {
// agent.setLastRegion(currentRegion); // agent.setLastRegion(currentRegion);
Vector3fImmutable startLoc = null; Vector3fImmutable startLoc = null;
Vector3fImmutable endLoc = null; Vector3fImmutable endLoc = null;
@ -263,7 +258,7 @@ public class MovementUtilities {
} }
} }
public static Vector3fImmutable GetDestinationToCharacter(Mob aiAgent, AbstractCharacter character){ public static Vector3fImmutable GetDestinationToCharacter(Mob aiAgent, AbstractCharacter character) {
if (!character.isMoving()) if (!character.isMoving())
return character.getLoc(); return character.getLoc();
@ -278,7 +273,7 @@ public class MovementUtilities {
return character.getLoc(); return character.getLoc();
} }
public static boolean updateMovementToCharacter(Mob aiAgent, AbstractCharacter aggroTarget){ public static boolean updateMovementToCharacter(Mob aiAgent, AbstractCharacter aggroTarget) {
if (aiAgent.destination.equals(Vector3fImmutable.ZERO)) if (aiAgent.destination.equals(Vector3fImmutable.ZERO))
return true; return true;
@ -287,12 +282,9 @@ public class MovementUtilities {
return true; return true;
if (aggroTarget.isMoving()) {
return !aiAgent.destination.equals(aggroTarget.getEndLoc()) && !aiAgent.destination.equals(aggroTarget.getLoc());
if (aggroTarget.isMoving()){ } else {
if (!aiAgent.destination.equals(aggroTarget.getEndLoc()) && !aiAgent.destination.equals(aggroTarget.getLoc()))
return true;
}else{
if (aiAgent.destination.equals(aggroTarget.getLoc())) if (aiAgent.destination.equals(aggroTarget.getLoc()))
return false; return false;
} }

1
src/engine/ai/utilities/PowerUtilities.java

@ -7,7 +7,6 @@
// www.magicbane.com // www.magicbane.com
package engine.ai.utilities; package engine.ai.utilities;
public class PowerUtilities { public class PowerUtilities {

19
src/engine/db/archive/BaneRecord.java

@ -10,6 +10,7 @@
package engine.db.archive; package engine.db.archive;
import engine.Enum; import engine.Enum;
import engine.gameManager.DbManager;
import engine.objects.Bane; import engine.objects.Bane;
import engine.objects.City; import engine.objects.City;
import engine.workthreads.WarehousePushThread; import engine.workthreads.WarehousePushThread;
@ -134,7 +135,7 @@ public class BaneRecord extends DataRecord {
DateTime outDateTime = null; DateTime outDateTime = null;
try (Connection connection = DataWarehouse.connectionPool.getConnection(); try (Connection connection = DbManager.getConnection();
PreparedStatement statement = buildDateTimeQueryStatement(connection, city); PreparedStatement statement = buildDateTimeQueryStatement(connection, city);
ResultSet rs = statement.executeQuery()) { ResultSet rs = statement.executeQuery()) {
@ -145,7 +146,7 @@ public class BaneRecord extends DataRecord {
} }
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.toString()); Logger.error(e.toString());
} }
return outDateTime; return outDateTime;
@ -166,13 +167,13 @@ public class BaneRecord extends DataRecord {
if (bane == null) if (bane == null)
return; return;
try (Connection connection = DataWarehouse.connectionPool.getConnection(); try (Connection connection = DbManager.getConnection();
PreparedStatement statement = buildUpdateLiveDateStatement(connection, bane, dateTime)) { PreparedStatement statement = buildUpdateLiveDateStatement(connection, bane, dateTime)) {
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.toString()); Logger.error(e.toString());
} }
} }
@ -203,7 +204,7 @@ public class BaneRecord extends DataRecord {
public static void updateResolution(Bane bane, RecordEventType eventType) { public static void updateResolution(Bane bane, RecordEventType eventType) {
try (Connection connection = DataWarehouse.connectionPool.getConnection(); try (Connection connection = DbManager.getConnection();
PreparedStatement statement = buildUpdateResolutionStatement(connection, bane, eventType)) { PreparedStatement statement = buildUpdateResolutionStatement(connection, bane, eventType)) {
statement.execute(); statement.execute();
@ -223,7 +224,7 @@ public class BaneRecord extends DataRecord {
dividerString = "--------------------------------" + newLine; dividerString = "--------------------------------" + newLine;
queryString = "CALL `baneHistory`()"; queryString = "CALL `baneHistory`()";
try (Connection connection = DataWarehouse.connectionPool.getConnection(); try (Connection connection = DbManager.getConnection();
PreparedStatement statement = connection.prepareCall(queryString); PreparedStatement statement = connection.prepareCall(queryString);
ResultSet rs = statement.executeQuery()) { ResultSet rs = statement.executeQuery()) {
@ -253,7 +254,7 @@ public class BaneRecord extends DataRecord {
WarehousePushThread.baneDelta = 0; WarehousePushThread.baneDelta = 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 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()) { ResultSet rs = statement.executeQuery()) {
@ -338,13 +339,13 @@ public class BaneRecord extends DataRecord {
public void write() { public void write() {
try (Connection connection = DataWarehouse.connectionPool.getConnection(); try (Connection connection = DbManager.getConnection();
PreparedStatement statement = buildBaneInsertStatement(connection)) { PreparedStatement statement = buildBaneInsertStatement(connection)) {
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.toString()); Logger.error(e.toString());
} }
} }

19
src/engine/db/archive/CharacterRecord.java

@ -10,6 +10,7 @@
package engine.db.archive; package engine.db.archive;
import engine.Enum; import engine.Enum;
import engine.gameManager.DbManager;
import engine.objects.Guild; import engine.objects.Guild;
import engine.objects.PlayerCharacter; import engine.objects.PlayerCharacter;
import engine.workthreads.WarehousePushThread; import engine.workthreads.WarehousePushThread;
@ -109,13 +110,13 @@ public class CharacterRecord extends DataRecord {
public static void advanceKillCounter(PlayerCharacter player) { public static void advanceKillCounter(PlayerCharacter player) {
try (Connection connection = DataWarehouse.connectionPool.getConnection(); try (Connection connection = DbManager.getConnection();
PreparedStatement statement = buildKillCounterStatement(connection, player)) { PreparedStatement statement = buildKillCounterStatement(connection, player)) {
statement.execute(); statement.execute();
} catch (SQLException e) { } 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) { public static void advanceDeathCounter(PlayerCharacter player) {
try (Connection connection = DataWarehouse.connectionPool.getConnection(); try (Connection connection = DbManager.getConnection();
PreparedStatement statement = buildDeathCounterStatement(connection, player)) { PreparedStatement statement = buildDeathCounterStatement(connection, player)) {
statement.execute(); statement.execute();
} catch (SQLException e) { } 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) { public static void updatePromotionClass(PlayerCharacter player) {
try (Connection connection = DataWarehouse.connectionPool.getConnection(); try (Connection connection = DbManager.getConnection();
PreparedStatement statement = buildUpdatePromotionStatement(connection, player)) { PreparedStatement statement = buildUpdatePromotionStatement(connection, player)) {
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.toString()); Logger.error(e.toString());
} }
} }
@ -197,7 +198,7 @@ public class CharacterRecord extends DataRecord {
WarehousePushThread.charDelta = 0; 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 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()) { ResultSet rs = statement.executeQuery()) {
@ -263,13 +264,13 @@ public class CharacterRecord extends DataRecord {
public void write() { public void write() {
try (Connection connection = DataWarehouse.connectionPool.getConnection(); try (Connection connection = DbManager.getConnection();
PreparedStatement statement = buildCharacterInsertStatement(connection, this.player)) { PreparedStatement statement = buildCharacterInsertStatement(connection, this.player)) {
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( "Error writing character record " + e.toString()); Logger.error("Error writing character record " + e.toString());
} }
} }

3
src/engine/db/archive/CityRecord.java

@ -10,6 +10,7 @@
package engine.db.archive; package engine.db.archive;
import engine.Enum; import engine.Enum;
import engine.gameManager.DbManager;
import engine.objects.City; import engine.objects.City;
import engine.workthreads.WarehousePushThread; import engine.workthreads.WarehousePushThread;
@ -126,7 +127,7 @@ public class CityRecord extends DataRecord {
public void write() { public void write() {
try (Connection connection = DataWarehouse.connectionPool.getConnection(); try (Connection connection = DbManager.getConnection();
PreparedStatement statement = this.buildCityInsertStatement(connection)) { PreparedStatement statement = this.buildCityInsertStatement(connection)) {
statement.execute(); statement.execute();

40
src/engine/db/archive/DataWarehouse.java

@ -12,6 +12,7 @@ package engine.db.archive;
import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.HikariDataSource;
import engine.gameManager.ConfigManager; import engine.gameManager.ConfigManager;
import engine.gameManager.DbManager;
import engine.util.Hasher; import engine.util.Hasher;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
@ -27,15 +28,10 @@ public class DataWarehouse implements Runnable {
public static final Hasher hasher = new Hasher("Cthulhu Owns Joo"); public static final Hasher hasher = new Hasher("Cthulhu Owns Joo");
private static final LinkedBlockingQueue<DataRecord> recordQueue = new LinkedBlockingQueue<>(); private static final LinkedBlockingQueue<DataRecord> recordQueue = new LinkedBlockingQueue<>();
public static HikariDataSource connectionPool = null;
public static HikariDataSource remoteConnectionPool = null; public static HikariDataSource remoteConnectionPool = null;
public DataWarehouse() { public DataWarehouse() {
Logger.info("Configuring local Database Connection Pool...");
configureConnectionPool();
// If WarehousePush is disabled // If WarehousePush is disabled
// then early exit // then early exit
@ -46,7 +42,6 @@ public class DataWarehouse implements Runnable {
Logger.info( "Configuring remote Database Connection Pool..."); Logger.info( "Configuring remote Database Connection Pool...");
configureRemoteConnectionPool(); configureRemoteConnectionPool();
} }
public static void bootStrap() { public static void bootStrap() {
@ -72,11 +67,7 @@ public class DataWarehouse implements Runnable {
String queryString; String queryString;
String hashString; String hashString;
try { connection = DbManager.getConnection();
connection = DataWarehouse.connectionPool.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
if (connection == null) { if (connection == null) {
Logger.error("Null connection when writing zone hash."); Logger.error("Null connection when writing zone hash.");
@ -140,11 +131,7 @@ public class DataWarehouse implements Runnable {
String queryString; String queryString;
ResultSet resultSet; ResultSet resultSet;
try { connection = DbManager.getConnection();
connection = DataWarehouse.connectionPool.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
if (connection == null) { if (connection == null) {
Logger.error("Null connection during char record lookup"); Logger.error("Null connection during char record lookup");
@ -282,27 +269,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() { private static void configureRemoteConnectionPool() {
HikariConfig config = new HikariConfig(); HikariConfig config = new HikariConfig();

3
src/engine/db/archive/GuildRecord.java

@ -11,6 +11,7 @@ package engine.db.archive;
import engine.Enum; import engine.Enum;
import engine.Enum.RecordEventType; import engine.Enum.RecordEventType;
import engine.gameManager.DbManager;
import engine.objects.Guild; import engine.objects.Guild;
import engine.workthreads.WarehousePushThread; import engine.workthreads.WarehousePushThread;
@ -164,7 +165,7 @@ public class GuildRecord extends DataRecord {
public void write() { public void write() {
try (Connection connection = DataWarehouse.connectionPool.getConnection(); try (Connection connection = DbManager.getConnection();
PreparedStatement statement = this.buildGuildInsertStatement(connection)) { PreparedStatement statement = this.buildGuildInsertStatement(connection)) {
statement.execute(); statement.execute();

3
src/engine/db/archive/MineRecord.java

@ -10,6 +10,7 @@
package engine.db.archive; package engine.db.archive;
import engine.Enum; import engine.Enum;
import engine.gameManager.DbManager;
import engine.objects.AbstractCharacter; import engine.objects.AbstractCharacter;
import engine.objects.Mine; import engine.objects.Mine;
import engine.objects.PlayerCharacter; import engine.objects.PlayerCharacter;
@ -131,7 +132,7 @@ public class MineRecord extends DataRecord {
public void write() { public void write() {
try (Connection connection = DataWarehouse.connectionPool.getConnection(); try (Connection connection = DbManager.getConnection();
PreparedStatement statement = this.buildMineInsertStatement(connection)) { PreparedStatement statement = this.buildMineInsertStatement(connection)) {
statement.execute(); statement.execute();

9
src/engine/db/archive/PvpRecord.java

@ -9,6 +9,7 @@
package engine.db.archive; package engine.db.archive;
import engine.gameManager.DbManager;
import engine.gameManager.ZoneManager; import engine.gameManager.ZoneManager;
import engine.math.Vector3fImmutable; import engine.math.Vector3fImmutable;
import engine.objects.Guild; import engine.objects.Guild;
@ -90,7 +91,7 @@ public class PvpRecord extends DataRecord {
LinkedList<Integer> outList = new LinkedList<>(); LinkedList<Integer> outList = new LinkedList<>();
try (Connection connection = DataWarehouse.connectionPool.getConnection(); try (Connection connection = DbManager.getConnection();
PreparedStatement statement = buildHistoryStatement(connection, charUUID, historyType); PreparedStatement statement = buildHistoryStatement(connection, charUUID, historyType);
ResultSet rs = statement.executeQuery()) { ResultSet rs = statement.executeQuery()) {
@ -132,7 +133,7 @@ public class PvpRecord extends DataRecord {
outString = "[LUA_PVP() DATA WAREHOUSE]" + newLine; outString = "[LUA_PVP() DATA WAREHOUSE]" + newLine;
dividerString = "--------------------------------" + newLine; dividerString = "--------------------------------" + newLine;
try (Connection connection = DataWarehouse.connectionPool.getConnection(); try (Connection connection = DbManager.getConnection();
PreparedStatement statement = buildLuaHistoryQueryStatement(connection, charUUID); PreparedStatement statement = buildLuaHistoryQueryStatement(connection, charUUID);
ResultSet rs = statement.executeQuery()) { ResultSet rs = statement.executeQuery()) {
@ -293,13 +294,13 @@ public class PvpRecord extends DataRecord {
public void write() { public void write() {
try (Connection connection = DataWarehouse.connectionPool.getConnection(); try (Connection connection = DbManager.getConnection();
PreparedStatement statement = buildPvPInsertStatement(connection)) { PreparedStatement statement = buildPvPInsertStatement(connection)) {
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.toString()); Logger.error(e.toString());
} }
// Warehouse record for this pvp event written if code path reaches here. // Warehouse record for this pvp event written if code path reaches here.

3
src/engine/db/archive/RealmRecord.java

@ -10,6 +10,7 @@
package engine.db.archive; package engine.db.archive;
import engine.Enum; import engine.Enum;
import engine.gameManager.DbManager;
import engine.objects.Realm; import engine.objects.Realm;
import engine.workthreads.WarehousePushThread; import engine.workthreads.WarehousePushThread;
@ -128,7 +129,7 @@ public class RealmRecord extends DataRecord {
public void write() { public void write() {
try (Connection connection = DataWarehouse.connectionPool.getConnection(); try (Connection connection = DbManager.getConnection();
PreparedStatement statement = this.buildRealmInsertStatement(connection)) { PreparedStatement statement = this.buildRealmInsertStatement(connection)) {
statement.execute(); statement.execute();

243
src/engine/db/handlers/dbAccountHandler.java

@ -17,6 +17,8 @@ import engine.objects.Account;
import engine.objects.PlayerCharacter; import engine.objects.PlayerCharacter;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
@ -28,84 +30,110 @@ public class dbAccountHandler extends dbHandlerBase {
this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName());
} }
public Account GET_ACCOUNT(int id) { public Account GET_ACCOUNT(int accountID) {
if (id == 0)
Account account;
if (accountID == 0)
return null; return null;
Account account = (Account) DbManager.getFromCache(GameObjectType.Account, id);
account = (Account) DbManager.getFromCache(GameObjectType.Account, accountID);
if (account != null) if (account != null)
return account; return account;
prepareCallable("SELECT * FROM `obj_account` WHERE `UID`=?"); try (Connection connection = DbManager.getConnection();
setLong(1, (long) id); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `obj_account` WHERE `UID`=?")) {
Account ac = null; preparedStatement.setLong(1, accountID);
ac = (Account) getObjectSingle(id);
ResultSet rs = preparedStatement.executeQuery();
account = (Account) getObjectFromRs(rs);
} catch (SQLException e) {
Logger.error(e);
}
if (ac != null) if (account != null)
ac.runAfterLoad(); account.runAfterLoad();
return ac; return account;
} }
public void WRITE_ADMIN_LOG(String adminName, String logEntry) { public void WRITE_ADMIN_LOG(String adminName, String logEntry) {
prepareCallable("INSERT INTO dyn_admin_log(`dateTime`, `charName`, `eventString`)" try (Connection connection = DbManager.getConnection();
+ " VALUES (?, ?, ?)"); PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO dyn_admin_log(`dateTime`, `charName`, `eventString`)"
setTimeStamp(1, System.currentTimeMillis()); + " VALUES (?, ?, ?)")) {
setString(2, adminName);
setString(3, logEntry); preparedStatement.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis()));
executeUpdate(); preparedStatement.setString(2, adminName);
preparedStatement.setString(3, logEntry);
preparedStatement.execute();
} catch (SQLException e) {
Logger.error(e);
}
} }
public void SET_TRASH(String machineID) { public void SET_TRASH(String machineID) {
prepareCallable("INSERT INTO dyn_trash(`machineID`, `count`)" try (Connection connection = DbManager.getConnection();
+ " VALUES (?, 1) ON DUPLICATE KEY UPDATE `count` = `count` + 1;"); PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO dyn_trash(`machineID`, `count`)"
+ " VALUES (?, 1) ON DUPLICATE KEY UPDATE `count` = `count` + 1;")) {
setTimeStamp(4, System.currentTimeMillis()); preparedStatement.setString(1, machineID);
setString(1, machineID); preparedStatement.execute();
executeUpdate();
} catch (SQLException e) {
Logger.error(e);
}
} }
public ArrayList<String> GET_TRASH_LIST() { public ArrayList<String> GET_TRASH_LIST() {
ArrayList<String> machineList = new ArrayList<>(); ArrayList<String> machineList = new ArrayList<>();
prepareCallable("select `machineID` from `dyn_trash`"); try (Connection connection = DbManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("select `machineID` from `dyn_trash`")) {
try { ResultSet rs = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
while (rs.next()) { while (rs.next())
machineList.add(rs.getString(1)); machineList.add(rs.getString(1));
}
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e); Logger.error(e);
} finally {
closeCallable();
} }
return machineList; return machineList;
} }
public boolean DELETE_VAULT_FOR_ACCOUNT(final int accountID) { public void DELETE_VAULT_FOR_ACCOUNT(final int accountID) {
prepareCallable("DELETE FROM `object` WHERE `parent`=? && `type`='item'");
setLong(1, (long) accountID); try (Connection connection = DbManager.getConnection();
return (executeUpdate() > 0); 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<PlayerCharacter> GET_ALL_CHARS_FOR_MACHINE(String machineID) { public ArrayList<PlayerCharacter> GET_ALL_CHARS_FOR_MACHINE(String machineID) {
ArrayList<PlayerCharacter> trashList = new ArrayList<>(); ArrayList<PlayerCharacter> trashList = new ArrayList<>();
prepareCallable("select DISTINCT UID from object \n" + 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 parent IN (select AccountID from dyn_login_history " +
" WHERE`machineID`=?)"); " WHERE`machineID`=?)")) {
setString(1, machineID);
preparedStatement.setString(1, machineID);
ResultSet rs = preparedStatement.executeQuery();
try {
ResultSet rs = executeQuery();
while (rs.next()) { while (rs.next()) {
PlayerCharacter trashPlayer; PlayerCharacter trashPlayer;
@ -115,52 +143,72 @@ public class dbAccountHandler extends dbHandlerBase {
trashPlayer = PlayerCharacter.getPlayerCharacter(playerID); trashPlayer = PlayerCharacter.getPlayerCharacter(playerID);
if (trashPlayer == null) if (trashPlayer == null)
continue;; continue;
if (trashPlayer.isDeleted() == false) if (trashPlayer.isDeleted() == false)
trashList.add(trashPlayer); trashList.add(trashPlayer);
} }
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e); Logger.error(e);
} finally {
closeCallable();
} }
return trashList; return trashList;
} }
public void CLEAR_TRASH_TABLE() { 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) { public void CREATE_SINGLE(String accountName, String password) {
prepareCallable("CALL singleAccountCreate(?,?)"); try (Connection connection = DbManager.getConnection();
setString(1, accountName); PreparedStatement preparedStatement = connection.prepareStatement("CALL singleAccountCreate(?,?)")) {
setString(2, password);
executeUpdate(); preparedStatement.setString(1, accountName);
preparedStatement.setString(2, password);
preparedStatement.execute();
} catch (SQLException e) {
Logger.error(e);
}
} }
public Account GET_ACCOUNT(String uname) { public Account GET_ACCOUNT(String uname) {
Account account = null;
if (Account.AccountsMap.get(uname) != null) if (Account.AccountsMap.get(uname) != null)
return this.GET_ACCOUNT(Account.AccountsMap.get(uname)); return this.GET_ACCOUNT(Account.AccountsMap.get(uname));
prepareCallable("SELECT * FROM `obj_account` WHERE `acct_uname`=?"); try (Connection connection = DbManager.getConnection();
setString(1, uname); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `obj_account` WHERE `acct_uname`=?")) {
ArrayList<Account> temp = getObjectList();
if (temp.isEmpty()) preparedStatement.setString(1, uname);
return null;
ResultSet rs = preparedStatement.executeQuery();
account = (Account) getObjectFromRs(rs);
if (temp.get(0) != null){ } catch (SQLException e) {
temp.get(0).runAfterLoad(); Logger.error(e);
}
if (account != null) {
account.runAfterLoad();
if (ConfigManager.serverType.equals(Enum.ServerType.LOGINSERVER)) 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) { public void SET_ACCOUNT_LOGIN(final Account acc, String playerName, final String ip, final String machineID) {
@ -168,55 +216,58 @@ public class dbAccountHandler extends dbHandlerBase {
if (acc.getObjectUUID() == 0 || ip == null || ip.length() == 0) if (acc.getObjectUUID() == 0 || ip == null || ip.length() == 0)
return; return;
prepareCallable("INSERT INTO dyn_login_history(`AccountID`, `accountName`, `characterName`, `ip`, `machineID`, `timeStamp`)" try (Connection connection = DbManager.getConnection();
+ " VALUES (?, ?, ?, ?, ?, ?)"); PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO dyn_login_history(`AccountID`, `accountName`, `characterName`, `ip`, `machineID`, `timeStamp`)"
+ " VALUES (?, ?, ?, ?, ?, ?)")) {
setInt(1, acc.getObjectUUID()); preparedStatement.setInt(1, acc.getObjectUUID());
setString(2, acc.getUname()); preparedStatement.setString(2, acc.getUname());
setString(3, playerName); preparedStatement.setString(3, playerName);
setString(4, ip); preparedStatement.setString(4, ip);
setString(5, machineID); preparedStatement.setString(5, machineID);
setTimeStamp(6, System.currentTimeMillis()); preparedStatement.setTimestamp(6, new java.sql.Timestamp(System.currentTimeMillis()));
executeUpdate();
}
public String SET_PROPERTY(final Account a, String name, Object new_value) { preparedStatement.execute();
prepareCallable("CALL account_SETPROP(?,?,?)");
setLong(1, (long) a.getObjectUUID());
setString(2, name);
setString(3, String.valueOf(new_value));
return getResult();
}
public String SET_PROPERTY(final Account a, String name, Object new_value, Object old_value) { } catch (SQLException e) {
prepareCallable("CALL account_GETSETPROP(?,?,?,?)"); Logger.error(e);
setLong(1, (long) a.getObjectUUID()); }
setString(2, name);
setString(3, String.valueOf(new_value));
setString(4, String.valueOf(old_value));
return getResult();
} }
public void updateDatabase(final Account acc) { public void updateDatabase(final Account acc) {
prepareCallable("UPDATE `obj_account` SET `acct_passwd`=?, "
try (Connection connection = DbManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_account` SET `acct_passwd`=?, "
+ " `acct_lastCharUID`=?, `acct_salt`=?, `discordAccount`=?, " + + " `acct_lastCharUID`=?, `acct_salt`=?, `discordAccount`=?, " +
" status = ? WHERE `UID`=?"); " 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());
setString(1, acc.getPasswd()); preparedStatement.execute();
setInt(2, acc.getLastCharIDUsed());
setString(3, acc.getSalt()); } catch (SQLException e) {
setString(4, acc.discordAccount); Logger.error(e);
setString(5, acc.status.name()); }
setInt(6, acc.getObjectUUID());
executeUpdate();
} }
public void INVALIDATE_LOGIN_CACHE(long accountUID, String objectType) { public void INVALIDATE_LOGIN_CACHE(long accountUID, String objectType) {
prepareCallable("INSERT IGNORE INTO login_cachelist (`UID`, `type`) VALUES(?,?);");
setLong(1, accountUID); try (Connection connection = DbManager.getConnection();
setString(2, objectType); PreparedStatement preparedStatement = connection.prepareStatement("INSERT IGNORE INTO login_cachelist (`UID`, `type`) VALUES(?,?);")) {
executeUpdate();
preparedStatement.setLong(1, accountUID);
preparedStatement.setString(2, objectType);
preparedStatement.execute();
} catch (SQLException e) {
Logger.error(e);
}
} }
} }

101
src/engine/db/handlers/dbBaneHandler.java

@ -9,6 +9,7 @@
package engine.db.handlers; package engine.db.handlers;
import engine.gameManager.DbManager;
import engine.objects.Bane; import engine.objects.Bane;
import engine.objects.Building; import engine.objects.Building;
import engine.objects.City; import engine.objects.City;
@ -16,10 +17,10 @@ import engine.objects.PlayerCharacter;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
public class dbBaneHandler extends dbHandlerBase { public class dbBaneHandler extends dbHandlerBase {
@ -29,78 +30,63 @@ public class dbBaneHandler extends dbHandlerBase {
public boolean CREATE_BANE(City city, PlayerCharacter owner, Building stone) { public boolean CREATE_BANE(City city, PlayerCharacter owner, Building stone) {
prepareCallable("INSERT INTO `dyn_banes` (`cityUUID`, `ownerUUID`, `stoneUUID`, `placementDate`) VALUES(?,?,?,?)"); try (Connection connection = DbManager.getConnection();
setLong(1, (long) city.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_banes` (`cityUUID`, `ownerUUID`, `stoneUUID`, `placementDate`) VALUES(?,?,?,?)")) {
setLong(2, (long) owner.getObjectUUID());
setLong(3, (long) stone.getObjectUUID());
setTimeStamp(4, System.currentTimeMillis());
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;
} }
public Bane LOAD_BANE(int cityUUID) { return true;
}
Bane newBane = null; public Bane LOAD_BANE(int cityUUID) {
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); preparedStatement.setLong(1, cityUUID);
ResultSet rs = executeQuery(); ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) { if (rs.next()) {
newBane = new Bane(rs); bane = new Bane(rs);
Bane.addBane(newBane); Bane.addBane(bane);
} }
} catch (SQLException ex) { } catch (SQLException e) {
java.util.logging.Logger.getLogger(dbBaneHandler.class.getName()).log(Level.SEVERE, null, ex); Logger.error(e);
} finally {
closeCallable();
} }
return newBane;
return bane;
} }
public ConcurrentHashMap<Integer, Bane> LOAD_ALL_BANES() {
ConcurrentHashMap<Integer, Bane> 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++; try (Connection connection = DbManager.getConnection();
thisBane = new Bane(rs); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_banes` SET `liveDate`=? WHERE `cityUUID`=?")) {
baneList.put(thisBane.getCityUUID(), thisBane);
} 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) { } catch (SQLException e) {
Logger.error( e.toString()); Logger.error(e);
} finally { return false;
closeCallable();
}
return baneList;
} }
public boolean SET_BANE_TIME(DateTime toSet, int cityUUID) { return true;
prepareCallable("UPDATE `dyn_banes` SET `liveDate`=? WHERE `cityUUID`=?");
setTimeStamp(1, toSet.getMillis());
setLong(2, cityUUID);
return (executeUpdate() > 0);
} }
public boolean REMOVE_BANE(Bane bane) { public boolean REMOVE_BANE(Bane bane) {
@ -108,8 +94,17 @@ public class dbBaneHandler extends dbHandlerBase {
if (bane == null) if (bane == null)
return false; return false;
prepareCallable("DELETE FROM `dyn_banes` WHERE `cityUUID` = ?"); try (Connection connection = DbManager.getConnection();
setLong(1, (long) bane.getCity().getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_banes` WHERE `cityUUID` = ?")) {
return (executeUpdate() > 0);
preparedStatement.setLong(1, bane.getCity().getObjectUUID());
preparedStatement.execute();
} catch (SQLException e) {
Logger.error(e);
return false;
}
return true;
} }
} }

59
src/engine/db/handlers/dbBaseClassHandler.java

@ -13,7 +13,12 @@ import engine.Enum;
import engine.Enum.GameObjectType; import engine.Enum.GameObjectType;
import engine.gameManager.DbManager; import engine.gameManager.DbManager;
import engine.objects.BaseClass; 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; import java.util.ArrayList;
public class dbBaseClassHandler extends dbHandlerBase { public class dbBaseClassHandler extends dbHandlerBase {
@ -27,24 +32,60 @@ public class dbBaseClassHandler extends dbHandlerBase {
if (id == 0) if (id == 0)
return null; return null;
BaseClass baseClass = (BaseClass) DbManager.getFromCache(GameObjectType.BaseClass, id); BaseClass baseClass = (BaseClass) DbManager.getFromCache(GameObjectType.BaseClass, id);
if (baseClass != null) if (baseClass != null)
return baseClass; 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` = ?;"); return baseClass;
setInt(1, id);
return (BaseClass) getObjectSingle(id);
} }
public ArrayList<BaseClass> GET_BASECLASS_FOR_RACE(final int id) { public ArrayList<BaseClass> 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); ArrayList<BaseClass> baseClasses = new ArrayList<>();
return getObjectList();
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<BaseClass> GET_ALL_BASE_CLASSES() {
ArrayList<BaseClass> 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);
} }
public ArrayList<BaseClass> GET_ALL_BASE_CLASSES(){ return baseClasses;
prepareCallable("SELECT * FROM `static_rune_baseclass`;");
return getObjectList();
} }
} }

31
src/engine/db/handlers/dbBlueprintHandler.java

@ -1,8 +1,11 @@
package engine.db.handlers; package engine.db.handlers;
import engine.gameManager.DbManager;
import engine.objects.Blueprint; import engine.objects.Blueprint;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
@ -22,10 +25,10 @@ public class dbBlueprintHandler extends dbHandlerBase {
int doorNum; int doorNum;
int recordsRead = 0; 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 = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
while (rs.next()) { while (rs.next()) {
@ -35,13 +38,11 @@ public class dbBlueprintHandler extends dbHandlerBase {
doorInfo.put(doorUUID, doorNum); doorInfo.put(doorUUID, doorNum);
} }
Logger.info( "read: " + recordsRead + " cached: " + doorInfo.size());
} catch (SQLException e) { } catch (SQLException e) {
Logger.error("LoadAllDoorNumbers: " + e.getErrorCode() + ' ' + e.getMessage(), e); Logger.error(e);
} finally {
closeCallable();
} }
Logger.info("read: " + recordsRead + " cached: " + doorInfo.size());
return doorInfo; return doorInfo;
} }
@ -53,10 +54,10 @@ public class dbBlueprintHandler extends dbHandlerBase {
blueprints = new HashMap<>(); blueprints = new HashMap<>();
int recordsRead = 0; int recordsRead = 0;
prepareCallable("SELECT * FROM static_building_blueprint"); try (Connection connection = DbManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_building_blueprint")) {
try { ResultSet rs = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
while (rs.next()) { while (rs.next()) {
@ -74,13 +75,11 @@ public class dbBlueprintHandler extends dbHandlerBase {
} }
Logger.info( "read: " + recordsRead + " cached: " + blueprints.size());
} catch (SQLException e) { } catch (SQLException e) {
Logger.error("LoadAllBlueprints: " + e.getErrorCode() + ' ' + e.getMessage(), e); Logger.error(e);
} finally {
closeCallable();
} }
Logger.info("read: " + recordsRead + " cached: " + blueprints.size());
return blueprints; return blueprints;
} }
} }

26
src/engine/db/handlers/dbBoonHandler.java

@ -9,9 +9,12 @@
package engine.db.handlers; package engine.db.handlers;
import engine.gameManager.DbManager;
import engine.objects.Boon; import engine.objects.Boon;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
@ -22,30 +25,27 @@ public class dbBoonHandler extends dbHandlerBase {
} }
public ArrayList<Boon> GET_BOON_AMOUNTS_FOR_ITEMBASEUUID(int itemBaseUUID){ public ArrayList<Boon> GET_BOON_AMOUNTS_FOR_ITEMBASE(int itemBaseUUID) {
ArrayList<Boon>boons = new ArrayList<>(); ArrayList<Boon> boons = new ArrayList<>();
Boon thisBoon; Boon thisBoon;
prepareCallable("SELECT * FROM `static_item_boons` WHERE `itemBaseID` = ?");
setInt(1, itemBaseUUID);
try { try (Connection connection = DbManager.getConnection();
ResultSet rs = executeQuery(); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_item_boons` WHERE `itemBaseID` = ?")) {
while (rs.next()) { preparedStatement.setInt(1, itemBaseUUID);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
thisBoon = new Boon(rs); thisBoon = new Boon(rs);
boons.add(thisBoon); boons.add(thisBoon);
} }
} catch (SQLException e) { } catch (SQLException e) {
Logger.error("GetBoonAmountsForItembaseUUID: " + e.getErrorCode() + ' ' + e.getMessage(), e); Logger.error(e);
} finally {
closeCallable();
} }
return boons; return boons;
} }
} }

954
src/engine/db/handlers/dbBuildingHandler.java

File diff suppressed because it is too large Load Diff

27
src/engine/db/handlers/dbBuildingLocationHandler.java

@ -9,8 +9,14 @@
package engine.db.handlers; package engine.db.handlers;
import engine.gameManager.DbManager;
import engine.objects.BuildingLocation; 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; import java.util.ArrayList;
public class dbBuildingLocationHandler extends dbHandlerBase { public class dbBuildingLocationHandler extends dbHandlerBase {
@ -21,16 +27,23 @@ public class dbBuildingLocationHandler extends dbHandlerBase {
} }
public ArrayList<BuildingLocation> LOAD_BUILDING_LOCATIONS() { public ArrayList<BuildingLocation> LOAD_BUILDING_LOCATIONS() {
prepareCallable("select * from static_building_location " +
ArrayList<BuildingLocation> buildingLocations = new ArrayList<>();
try (Connection connection = DbManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("select * from static_building_location " +
"where type = 6 or type = 8 " + "where type = 6 or type = 8 " +
"GROUP BY buildingID, slot " + "GROUP BY buildingID, slot " +
"ORDER BY buildingID, slot ASC;"); "ORDER BY buildingID, slot ASC;")) {
return getObjectList();
}
public ArrayList<BuildingLocation> LOAD_ALL_BUILDING_LOCATIONS() { ResultSet rs = preparedStatement.executeQuery();
prepareCallable("SELECT * FROM `static_building_location`;"); buildingLocations = getObjectsFromRs(rs, 20);
return getObjectList();
} catch (SQLException e) {
Logger.error(e);
return buildingLocations;
} }
return buildingLocations;
}
} }

104
src/engine/db/handlers/dbCSSessionHandler.java

@ -17,6 +17,8 @@ import engine.util.StringUtils;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.net.InetAddress; import java.net.InetAddress;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
@ -28,73 +30,85 @@ public class dbCSSessionHandler extends dbHandlerBase {
} }
public boolean ADD_CSSESSION(String secKey, Account acc, InetAddress inet, String machineID) { 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);
}
// This method returns population metrics from the database
public String GET_POPULATION_STRING() {
String outString = null; try (Connection connection = DbManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_session` (`secretKey`, `accountID`, `discordAccount`, `sessionIP`, machineID) VALUES (?,?,?,INET_ATON(?),?)")) {
// Set up call to stored procedure preparedStatement.setString(1, secKey);
prepareCallable("CALL GET_POPULATION_STRING()"); preparedStatement.setLong(2, acc.getObjectUUID());
preparedStatement.setString(3, acc.discordAccount);
preparedStatement.setString(4, StringUtils.InetAddressToClientString(inet));
preparedStatement.setString(5, machineID);
try { return (preparedStatement.executeUpdate() > 0);
// Evaluate database ordinal and return enum } catch (SQLException e) {
outString = getString("popstring"); Logger.error(e);
} catch (Exception e) {
Logger.error( "Failure in stored procedure:" + e.getMessage());
} finally {
closeCallable();
} }
return outString; return false;
} }
public boolean DELETE_UNUSED_CSSESSION(String secKey) { public boolean DELETE_UNUSED_CSSESSION(String secKey) {
prepareCallable("DELETE FROM `dyn_session` WHERE `secretKey`=? && `characterID` IS NULL");
setString(1, secKey); try (Connection connection = DbManager.getConnection();
return (executeUpdate() != 0); 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) { public boolean DELETE_CSSESSION(String secKey) {
prepareCallable("DELETE FROM `dyn_session` WHERE `secretKey`=?");
setString(1, secKey); try (Connection connection = DbManager.getConnection();
return (executeUpdate() != 0); 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) { public boolean UPDATE_CSSESSION(String secKey, int charID) {
prepareCallable("UPDATE `dyn_session` SET `characterID`=? WHERE `secretKey`=?");
setInt(1, charID); try (Connection connection = DbManager.getConnection();
setString(2, secKey); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_session` SET `characterID`=? WHERE `secretKey`=?")) {
return (executeUpdate() != 0);
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) { public CSSession GET_CSSESSION(String secKey) {
CSSession css = null; 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`=?")) {
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")), rs.getString("machineID"));
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) { } catch (SQLException e) {
Logger.error("Error with seckey: " + secKey); Logger.error(e);
} finally {
closeCallable();
} }
return css; return css;
} }
} }

136
src/engine/db/handlers/dbCharacterPowerHandler.java

@ -16,8 +16,7 @@ import engine.objects.PlayerCharacter;
import engine.server.MBServerStatics; import engine.server.MBServerStatics;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.ResultSet; import java.sql.*;
import java.sql.SQLException;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
public class dbCharacterPowerHandler extends dbHandlerBase { public class dbCharacterPowerHandler extends dbHandlerBase {
@ -28,86 +27,143 @@ public class dbCharacterPowerHandler extends dbHandlerBase {
} }
public CharacterPower ADD_CHARACTER_POWER(CharacterPower toAdd) { public CharacterPower ADD_CHARACTER_POWER(CharacterPower toAdd) {
CharacterPower characterPower = null;
if (CharacterPower.getOwner(toAdd) == null || toAdd.getPower() == null) { if (CharacterPower.getOwner(toAdd) == null || toAdd.getPower() == null) {
Logger.error("dbCharacterSkillHandler.ADD_Power", toAdd.getObjectUUID() + " missing owner or powersBase"); Logger.error("dbCharacterSkillHandler.ADD_Power", toAdd.getObjectUUID() + " missing owner or powersBase");
return null; return null;
} }
prepareCallable("INSERT INTO `dyn_character_power` (`CharacterID`, `powersBaseToken`, `trains`) VALUES (?, ?, ?);"); try (Connection connection = DbManager.getConnection();
setLong(1, (long)CharacterPower.getOwner(toAdd).getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_power` (`CharacterID`, `powersBaseToken`, `trains`) VALUES (?, ?, ?);", Statement.RETURN_GENERATED_KEYS)) {
setInt(2, toAdd.getPower().getToken());
setInt(3, toAdd.getTrains()); preparedStatement.setLong(1, CharacterPower.getOwner(toAdd).getObjectUUID());
int powerID = insertGetUUID(); preparedStatement.setInt(2, toAdd.getPower().getToken());
return GET_CHARACTER_POWER(powerID); 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) { public int DELETE_CHARACTER_POWER(final int objectUUID) {
prepareCallable("DELETE FROM `dyn_character_power` WHERE `UID` = ?");
setLong(1, (long)objectUUID); int rowCount = 0;
return executeUpdate();
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) { public CharacterPower GET_CHARACTER_POWER(int objectUUID) {
CharacterPower cp = (CharacterPower) DbManager.getFromCache(Enum.GameObjectType.CharacterPower, objectUUID); CharacterPower characterPower = (CharacterPower) DbManager.getFromCache(Enum.GameObjectType.CharacterPower, objectUUID);
if (cp != null)
return cp; if (characterPower != null)
prepareCallable("SELECT * FROM `dyn_character_power` WHERE `UID` = ?"); return characterPower;
setLong(1, (long)objectUUID);
return (CharacterPower) getObjectSingle(objectUUID); 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<Integer, CharacterPower> GET_POWERS_FOR_CHARACTER(PlayerCharacter pc) { public ConcurrentHashMap<Integer, CharacterPower> GET_POWERS_FOR_CHARACTER(PlayerCharacter pc) {
ConcurrentHashMap<Integer, CharacterPower> powers = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW); ConcurrentHashMap<Integer, CharacterPower> powers = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW);
int objectUUID = pc.getObjectUUID(); int objectUUID = pc.getObjectUUID();
prepareCallable("SELECT * FROM `dyn_character_power` WHERE CharacterID = ?");
setLong(1, (long)objectUUID); try (Connection connection = DbManager.getConnection();
ResultSet rs = executeQuery(); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_character_power` WHERE CharacterID = ?")) {
try {
preparedStatement.setLong(1, objectUUID);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) { while (rs.next()) {
CharacterPower cp = new CharacterPower(rs, pc); CharacterPower cp = new CharacterPower(rs, pc);
if (cp.getPower() != null) if (cp.getPower() != null)
powers.put(cp.getPower().getToken(), cp); powers.put(cp.getPower().getToken(), cp);
} }
rs.close();
} catch (SQLException e) { } catch (SQLException e) {
Logger.error("CharacterPower.getCharacterPowerForCharacter", "Exception:" + e.getMessage()); Logger.error(e);
} finally {
closeCallable();
} }
return powers; return powers;
} }
public void UPDATE_TRAINS(final CharacterPower pow) { public void UPDATE_TRAINS(final CharacterPower characterPower) {
//skip update if nothing changed //skip update if nothing changed
if (!pow.isTrained())
if (!characterPower.isTrained())
return; return;
prepareCallable("UPDATE `dyn_character_power` SET `trains`=? WHERE `UID`=?"); try (Connection connection = DbManager.getConnection();
setShort(1, (short)pow.getTrains()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_character_power` SET `trains`=? WHERE `UID`=?")) {
setInt(2, pow.getObjectUUID());
executeUpdate(); preparedStatement.setShort(1, (short) characterPower.getTrains());
pow.setTrained(false); preparedStatement.setInt(2, characterPower.getObjectUUID());
preparedStatement.execute();
} catch (SQLException e) {
Logger.error(e);
}
characterPower.setTrained(false);
} }
public void updateDatabase(final CharacterPower pow) { public void updateDatabase(final CharacterPower pow) {
if (pow.getPower() == null) { 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; return;
} }
if (CharacterPower.getOwner(pow) == null) { 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; 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); pow.setTrained(false);
} }
} }

106
src/engine/db/handlers/dbCharacterRuneHandler.java

@ -12,7 +12,9 @@ package engine.db.handlers;
import engine.Enum; import engine.Enum;
import engine.gameManager.DbManager; import engine.gameManager.DbManager;
import engine.objects.CharacterRune; import engine.objects.CharacterRune;
import org.pmw.tinylog.Logger;
import java.sql.*;
import java.util.ArrayList; import java.util.ArrayList;
public class dbCharacterRuneHandler extends dbHandlerBase { public class dbCharacterRuneHandler extends dbHandlerBase {
@ -23,41 +25,97 @@ public class dbCharacterRuneHandler extends dbHandlerBase {
} }
public CharacterRune ADD_CHARACTER_RUNE(final CharacterRune toAdd) { public CharacterRune ADD_CHARACTER_RUNE(final CharacterRune toAdd) {
prepareCallable("INSERT INTO `dyn_character_rune` (`CharacterID`, `RuneBaseID`) VALUES (?, ?);");
setLong(1, (long)toAdd.getPlayerID()); CharacterRune characterRune = null;
setInt(2, toAdd.getRuneBaseID());
int runeID = insertGetUUID(); try (Connection connection = DbManager.getConnection();
return GET_CHARACTER_RUNE(runeID); 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());
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) { public CharacterRune GET_CHARACTER_RUNE(int runeID) {
CharacterRune charRune = (CharacterRune) DbManager.getFromCache(Enum.GameObjectType.CharacterRune, runeID); CharacterRune characterRune = (CharacterRune) DbManager.getFromCache(Enum.GameObjectType.CharacterRune, runeID);
if (charRune != null)
return charRune; if (characterRune != null)
prepareCallable("SELECT * FROM `dyn_character_rune` WHERE `UID`=?"); return characterRune;
setInt(1, runeID);
return (CharacterRune) getObjectSingle(runeID); 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`=?;")) {
public boolean DELETE_CHARACTER_RUNE(final CharacterRune cr) { preparedStatement.setLong(1, characterRune.getObjectUUID());
prepareCallable("DELETE FROM `dyn_character_rune` WHERE `UID`=?;");
setLong(1, (long)cr.getObjectUUID()); return (preparedStatement.executeUpdate() > 0);
return (executeUpdate() != 0);
} catch (SQLException e) {
Logger.error(e);
}
return false;
} }
public ArrayList<CharacterRune> GET_RUNES_FOR_CHARACTER(final int characterId) { public ArrayList<CharacterRune> GET_RUNES_FOR_CHARACTER(final int characterId) {
prepareCallable("SELECT * FROM `dyn_character_rune` WHERE `CharacterID` = ?");
setInt(1, characterId); ArrayList<CharacterRune> characterRunes = new ArrayList<>();
return getObjectList();
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 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, characterRune.getObjectUUID());
public void updateDatabase(final CharacterRune cr) { preparedStatement.execute();
prepareCallable("UPDATE `dyn_character_rune` SET `CharacterID`=?, `RuneBaseID`=? WHERE `UID` = ?");
setInt(1, cr.getPlayerID()); } catch (SQLException e) {
setInt(2, cr.getRuneBaseID()); Logger.error(e);
setLong(3, (long) cr.getObjectUUID()); }
executeUpdate();
} }
} }

161
src/engine/db/handlers/dbCharacterSkillHandler.java

@ -17,8 +17,7 @@ import engine.objects.PlayerCharacter;
import engine.server.MBServerStatics; import engine.server.MBServerStatics;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.ResultSet; import java.sql.*;
import java.sql.SQLException;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
public class dbCharacterSkillHandler extends dbHandlerBase { public class dbCharacterSkillHandler extends dbHandlerBase {
@ -29,88 +28,146 @@ public class dbCharacterSkillHandler extends dbHandlerBase {
} }
public CharacterSkill ADD_SKILL(CharacterSkill toAdd) { public CharacterSkill ADD_SKILL(CharacterSkill toAdd) {
CharacterSkill characterSkill = null;
if (CharacterSkill.GetOwner(toAdd) == null || toAdd.getSkillsBase() == null) { if (CharacterSkill.GetOwner(toAdd) == null || toAdd.getSkillsBase() == null) {
Logger.error("dbCharacterSkillHandler.ADD_SKILL", toAdd.getObjectUUID() + " missing owner or skillsBase"); Logger.error("dbCharacterSkillHandler.ADD_SKILL", toAdd.getObjectUUID() + " missing owner or skillsBase");
return null; return null;
} }
prepareCallable("INSERT INTO `dyn_character_skill` (`CharacterID`, `skillsBaseID`, `trains`) VALUES (?, ?, ?);"); try (Connection connection = DbManager.getConnection();
setLong(1, (long)CharacterSkill.GetOwner(toAdd).getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_skill` (`CharacterID`, `skillsBaseID`, `trains`) VALUES (?, ?, ?);", Statement.RETURN_GENERATED_KEYS)) {
setInt(2, toAdd.getSkillsBase().getObjectUUID());
setInt(3, toAdd.getNumTrains()); preparedStatement.setLong(1, CharacterSkill.GetOwner(toAdd).getObjectUUID());
int skillID = insertGetUUID(); preparedStatement.setInt(2, toAdd.getSkillsBase().getObjectUUID());
return GET_SKILL(skillID); 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) { public boolean DELETE_SKILL(final int objectUUID) {
prepareCallable("DELETE FROM `dyn_character_skill` WHERE `UID` = ?");
setLong(1, (long)objectUUID); try (Connection connection = DbManager.getConnection();
return (executeUpdate() != 0); 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) { public CharacterSkill GET_SKILL(final int objectUUID) {
CharacterSkill skill = (CharacterSkill) DbManager.getFromCache(Enum.GameObjectType.CharacterSkill, objectUUID);
if (skill != null) CharacterSkill characterSkill = (CharacterSkill) DbManager.getFromCache(Enum.GameObjectType.CharacterSkill, objectUUID);
return skill;
prepareCallable("SELECT * FROM `dyn_character_skill` WHERE `UID` = ?"); if (characterSkill != null)
setInt(1, objectUUID); return characterSkill;
return (CharacterSkill) getObjectSingle(objectUUID);
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<String, CharacterSkill> GET_SKILLS_FOR_CHARACTER(final AbstractCharacter ac) { public ConcurrentHashMap<String, CharacterSkill> GET_SKILLS_FOR_CHARACTER(final AbstractCharacter ac) {
ConcurrentHashMap<String, CharacterSkill> skills = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW);
ConcurrentHashMap<String, CharacterSkill> characterSkills = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW);
if (ac == null || (!(ac.getObjectType().equals(Enum.GameObjectType.PlayerCharacter)))) if (ac == null || (!(ac.getObjectType().equals(Enum.GameObjectType.PlayerCharacter))))
return skills; return characterSkills;
PlayerCharacter pc = (PlayerCharacter) ac;
int objectUUID = pc.getObjectUUID(); PlayerCharacter playerCharacter = (PlayerCharacter) ac;
int characterId = playerCharacter.getObjectUUID();
prepareCallable("SELECT * FROM `dyn_character_skill` WHERE `CharacterID` = ?");
setInt(1, objectUUID); try (Connection connection = DbManager.getConnection();
try { PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_character_skill` WHERE `CharacterID` = ?")) {
ResultSet rs = executeQuery();
preparedStatement.setInt(1, characterId);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) { while (rs.next()) {
CharacterSkill cs = new CharacterSkill(rs, pc); CharacterSkill cs = new CharacterSkill(rs, playerCharacter);
if (cs.getSkillsBase() != null) if (cs.getSkillsBase() != null)
skills.put(cs.getSkillsBase().getName(), cs); characterSkills.put(cs.getSkillsBase().getName(), cs);
} }
rs.close();
} catch (SQLException e) { } catch (SQLException e) {
Logger.error("CharacterSkill.getCharacterSkillForCharacter", e); Logger.error(e);
} finally {
closeCallable();
} }
return skills;
return characterSkills;
} }
public void UPDATE_TRAINS(final CharacterSkill cs) { public void UPDATE_TRAINS(final CharacterSkill characterSkill) {
if (!cs.isTrained())
if (!characterSkill.isTrained())
return; return;
prepareCallable("UPDATE `dyn_character_skill` SET `trains`=? WHERE `UID` = ?"); try (Connection connection = DbManager.getConnection();
setShort(1, (short)cs.getNumTrains()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_character_skill` SET `trains`=? WHERE `UID` = ?")) {
setLong(2, (long)cs.getObjectUUID());
if (executeUpdate() != 0) preparedStatement.setShort(1, (short) characterSkill.getNumTrains());
cs.syncTrains(); preparedStatement.setLong(2, characterSkill.getObjectUUID());
if (preparedStatement.executeUpdate() != 0)
characterSkill.syncTrains();
} catch (SQLException e) {
Logger.error(e);
}
} }
public void updateDatabase(final CharacterSkill cs) { public void updateDatabase(final CharacterSkill characterSkill) {
if (cs.getSkillsBase() == null) {
Logger.error("Failed to find skillsBase for Skill " + cs.getObjectUUID()); if (characterSkill.getSkillsBase() == null) {
Logger.error("Failed to find skillsBase for Skill " + characterSkill.getObjectUUID());
return; 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; return;
} }
prepareCallable("UPDATE `dyn_character_skill` SET `skillsBaseID`=?, `CharacterID`=?, `trains`=? WHERE `UID`=?"); try (Connection connection = DbManager.getConnection();
setInt(1, cs.getSkillsBase().getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_character_skill` SET `skillsBaseID`=?, `CharacterID`=?, `trains`=? WHERE `UID`=?")) {
setInt(2, CharacterSkill.GetOwner(cs).getObjectUUID());
setShort(3, (short)cs.getNumTrains()); preparedStatement.setInt(1, characterSkill.getSkillsBase().getObjectUUID());
setLong(4, (long)cs.getObjectUUID()); preparedStatement.setInt(2, CharacterSkill.GetOwner(characterSkill).getObjectUUID());
if (executeUpdate() != 0) preparedStatement.setShort(3, (short) characterSkill.getNumTrains());
cs.syncTrains(); preparedStatement.setLong(4, characterSkill.getObjectUUID());
if (preparedStatement.executeUpdate() != 0)
characterSkill.syncTrains();
} catch (SQLException e) {
Logger.error(e);
}
} }
} }

263
src/engine/db/handlers/dbCityHandler.java

@ -17,9 +17,7 @@ import engine.objects.City;
import engine.objects.Zone; import engine.objects.Zone;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.net.UnknownHostException; import java.sql.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
@ -30,54 +28,7 @@ public class dbCityHandler extends dbHandlerBase {
this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); this.localObjectType = Enum.GameObjectType.valueOf(this.localClass.getSimpleName());
} }
public ArrayList<AbstractGameObject> CREATE_CITY(int ownerID, int parentZoneID, int realmID, float xCoord, float yCoord, float zCoord, float rotation, float W, String name, LocalDateTime established) { public static void addObject(ArrayList<AbstractGameObject> list, ResultSet rs) throws SQLException {
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<AbstractGameObject> list = new ArrayList<>();
try {
boolean work = execute();
if (work) {
ResultSet rs = this.cs.get().getResultSet();
while (rs.next()) {
addObject(list, rs);
}
rs.close();
} else {
Logger.info("City Placement Failed: " + this.cs.get().toString());
return list; //city creation failure
}
while (this.cs.get().getMoreResults()) {
ResultSet rs = this.cs.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());
return list; //city creation failure
} catch (UnknownHostException e) {
Logger.info("City Placement Failed, UnknownHostException: " + this.cs.get().toString());
return list; //city creation failure
} finally {
closeCallable();
}
return list;
}
public static void addObject(ArrayList<AbstractGameObject> list, ResultSet rs) throws SQLException, UnknownHostException {
String type = rs.getString("type"); String type = rs.getString("type");
switch (type) { switch (type) {
case "zone": case "zone":
@ -98,99 +49,197 @@ public class dbCityHandler extends dbHandlerBase {
} }
} }
public ArrayList<AbstractGameObject> 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<AbstractGameObject> 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 = preparedStatement.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<City> GET_CITIES_BY_ZONE(final int objectUUID) { public ArrayList<City> 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(); ArrayList<City> 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) { public City GET_CITY(final int cityId) {
City city = (City) DbManager.getFromCache(Enum.GameObjectType.City, cityId); City city = (City) DbManager.getFromCache(Enum.GameObjectType.City, cityId);
if (city != null) if (city != null)
return city; 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) { try (Connection connection = DbManager.getConnection();
prepareCallable("CALL city_SETPROP(?,?,?)"); PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_city`.*, `object`.`parent` FROM `obj_city` INNER JOIN `object` ON `object`.`UID` = `obj_city`.`UID` WHERE `object`.`UID`=?;")) {
setLong(1, (long) c.getObjectUUID());
setString(2, name); preparedStatement.setLong(1, cityId);
setString(3, String.valueOf(new_value));
return getResult(); ResultSet rs = preparedStatement.executeQuery();
city = (City) getObjectFromRs(rs);
} catch (SQLException e) {
Logger.error(e);
} }
public String SET_PROPERTY(final City c, String name, Object new_value, Object old_value) { return city;
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) { public boolean updateforceRename(City city, boolean value) {
prepareCallable("UPDATE `obj_city` SET `forceRename`=?" try (Connection connection = DbManager.getConnection();
+ " WHERE `UID` = ?"); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_city` SET `forceRename`=?"
setByte(1, (value == true) ? (byte) 1 : (byte) 0); + " WHERE `UID` = ?")) {
setInt(2, city.getObjectUUID());
return (executeUpdate() > 0); 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) { public boolean updateOpenCity(City city, boolean value) {
prepareCallable("UPDATE `obj_city` SET `open`=?" try (Connection connection = DbManager.getConnection();
+ " WHERE `UID` = ?"); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_city` SET `open`=?"
setByte(1, (value == true) ? (byte) 1 : (byte) 0); + " WHERE `UID` = ?")) {
setInt(2, city.getObjectUUID());
return (executeUpdate() > 0); 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) { public boolean updateTOL(City city, int tolID) {
prepareCallable("UPDATE `obj_city` SET `treeOfLifeUUID`=?" try (Connection connection = DbManager.getConnection();
+ " WHERE `UID` = ?"); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_city` SET `treeOfLifeUUID`=?"
setInt(1,tolID); + " WHERE `UID` = ?")) {
setInt(2, city.getObjectUUID());
return (executeUpdate() > 0); 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) { public boolean renameCity(City city, String name) {
prepareCallable("UPDATE `obj_city` SET `name`=?" try (Connection connection = DbManager.getConnection();
+ " WHERE `UID` = ?"); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_city` SET `name`=?"
setString(1, name); + " WHERE `UID` = ?")) {
setInt(2, city.getObjectUUID());
return (executeUpdate() > 0); 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) { public boolean updateSiegesWithstood(City city, int value) {
prepareCallable("UPDATE `obj_city` SET `siegesWithstood`=?" try (Connection connection = DbManager.getConnection();
+ " WHERE `UID` = ?"); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_city` SET `name`=?"
setInt(1, value); + " WHERE `UID` = ?")) {
setInt(2, city.getObjectUUID());
return (executeUpdate() > 0); 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) { public boolean updateRealmTaxDate(City city, LocalDateTime localDateTime) {
prepareCallable("UPDATE `obj_city` SET `realmTaxDate` =?" try (Connection connection = DbManager.getConnection();
+ " WHERE `UID` = ?"); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_city` SET `realmTaxDate` =?"
setLocalDateTime(1, localDateTime); + " WHERE `UID` = ?")) {
setInt(2,city.getObjectUUID());
return (executeUpdate() > 0); preparedStatement.setTimestamp(1, Timestamp.valueOf(localDateTime));
} preparedStatement.setInt(2, city.getObjectUUID());
public boolean DELETE_CITY(final City city) { return (preparedStatement.executeUpdate() > 0);
prepareCallable("DELETE FROM `object` WHERE `UID` = ? AND `type` = 'city'"); } catch (SQLException e) {
setInt(1, city.getObjectUUID()); Logger.error(e);
return (executeUpdate() != 0); return false;
}
} }
} }

137
src/engine/db/handlers/dbContractHandler.java

@ -16,9 +16,10 @@ import engine.objects.ItemBase;
import engine.objects.MobEquipment; import engine.objects.MobEquipment;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList;
public class dbContractHandler extends dbHandlerBase { public class dbContractHandler extends dbHandlerBase {
@ -28,48 +29,37 @@ public class dbContractHandler extends dbHandlerBase {
} }
public Contract GET_CONTRACT(final int objectUUID) { public Contract GET_CONTRACT(final int objectUUID) {
Contract contract = (Contract) DbManager.getFromCache(Enum.GameObjectType.Contract, objectUUID); Contract contract = (Contract) DbManager.getFromCache(Enum.GameObjectType.Contract, objectUUID);
if (contract != null) if (contract != null)
return contract; return contract;
if (objectUUID == 0) if (objectUUID == 0)
return null; return null;
prepareCallable("SELECT * FROM `static_npc_contract` WHERE `ID` = ?");
setInt(1, objectUUID);
return (Contract) getObjectSingle(objectUUID);
}
public ArrayList<Contract> GET_CONTRACT_BY_RACE(final int objectUUID) { try (Connection connection = DbManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_contract` WHERE `ID` = ?")) {
ArrayList<Contract> contracts = new ArrayList<>(); preparedStatement.setInt(1, objectUUID);
prepareCallable("SELECT * FROM static_npc_contract WHERE `mobbaseID` =?;"); ResultSet rs = preparedStatement.executeQuery();
setLong(1, objectUUID); contract = (Contract) getObjectFromRs(rs);
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);
}
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.getErrorCode() + ' ' + e.getMessage(), e); Logger.error(e);
} finally {
closeCallable();
} }
return contracts; return contract;
} }
public void GET_GENERIC_INVENTORY(final Contract contract) { public void LOAD_CONTRACT_INVENTORY(final Contract contract) {
prepareCallable("SELECT * FROM `static_npc_inventoryset` WHERE `inventorySet` = ?;"); try (Connection connection = DbManager.getConnection();
setInt(1, contract.inventorySet); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_inventoryset` WHERE `inventorySet` = ?;")) {
try { preparedStatement.setInt(1, contract.inventorySet);
ResultSet rs = executeQuery();
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) { while (rs.next()) {
@ -102,56 +92,77 @@ public class dbContractHandler extends dbHandlerBase {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Logger.error("SQL Error number: " + e.getErrorCode() + ' ' + e.getMessage()); Logger.error(e);
} finally {
closeCallable();
} }
} }
public void GET_SELL_LISTS(final Contract con) { public void LOAD_SELL_LIST_FOR_CONTRACT(final Contract contract) {
prepareCallable("SELECT * FROM `static_npc_contract_selltype` WHERE `contractID` = ?;");
setInt(1, con.getObjectUUID()); try (Connection connection = DbManager.getConnection();
try { PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_contract_selltype` WHERE `contractID` = ?;")) {
ResultSet rs = executeQuery();
ArrayList<Integer> item = con.getBuyItemType(); preparedStatement.setInt(1, contract.getObjectUUID());
ArrayList<Integer> skill = con.getBuySkillToken();
ArrayList<Integer> unknown = con.getBuyUnknownToken(); ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) { while (rs.next()) {
int type = rs.getInt("type"); int type = rs.getInt("type");
int value = rs.getInt("value"); int value = rs.getInt("value");
if (type == 1) {
item.add(value); switch (type) {
} else if (type == 2) { case 1:
skill.add(value); contract.getBuyItemType().add(value);
} else if (type == 3) { break;
unknown.add(value); case 2:
contract.getBuySkillToken().add(value);
break;
case 3:
contract.getBuyUnknownToken().add(value);
break;
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Logger.error("SQL Error number: " + e.getErrorCode() + ' ' + e.getMessage()); Logger.error(e);
} finally {
closeCallable();
} }
} }
public boolean updateAllowedBuildings(final Contract con, final long slotbitvalue) { public boolean updateAllowedBuildings(final Contract con, final long slotbitvalue) {
prepareCallable("UPDATE `static_npc_contract` SET `allowedBuildingTypeID`=? WHERE `contractID`=?");
setLong(1, slotbitvalue); try (Connection connection = DbManager.getConnection();
setInt(2, con.getContractID()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `static_npc_contract` SET `allowedBuildingTypeID`=? WHERE `contractID`=?")) {
return (executeUpdate() > 0);
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) { public boolean updateDatabase(final Contract con) {
prepareCallable("UPDATE `static_npc_contract` SET `contractID`=?, `name`=?, "
+ "`mobbaseID`=?, `classID`=?, vendorDialog=?, iconID=?, allowedBuildingTypeID=? WHERE `ID`=?"); try (Connection connection = DbManager.getConnection();
setInt(1, con.getContractID()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `static_npc_contract` SET `contractID`=?, `name`=?, "
setString(2, con.getName()); + "`mobbaseID`=?, `classID`=?, vendorDialog=?, iconID=?, allowedBuildingTypeID=? WHERE `ID`=?")) {
setInt(3, con.getMobbaseID());
setInt(4, con.getClassID()); preparedStatement.setInt(1, con.getContractID());
setInt(5, (con.getVendorDialog() != null) ? con.getVendorDialog().getObjectUUID() : 0); preparedStatement.setString(2, con.getName());
setInt(6, con.getIconID()); preparedStatement.setInt(3, con.getMobbaseID());
setInt(8, con.getObjectUUID()); preparedStatement.setInt(4, con.getClassID());
setLong(7, con.getAllowedBuildings().toLong()); preparedStatement.setInt(5, (con.getVendorDialog() != null) ? con.getVendorDialog().getObjectUUID() : 0);
return (executeUpdate() > 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;
} }
} }

394
src/engine/db/handlers/dbEffectsBaseHandler.java

@ -9,173 +9,295 @@
package engine.db.handlers; 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;
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 { public class dbEffectsBaseHandler extends dbHandlerBase {
public dbEffectsBaseHandler() { public dbEffectsBaseHandler() {
} }
public static ArrayList<EffectsBase> getAllEffectsBase() {
ArrayList<EffectsBase> effectList = new ArrayList<>();
public boolean CreateEffectBase(int token, String IDString,String name,int flags){ try (Connection connection = DbManager.getConnection();
prepareCallable("INSERT INTO `wpak_static_power_effectbase` (`token`,`IDString`,`name`,`flags`) VALUES (?,?,?,?)"); PreparedStatement prepareStatement = connection.prepareStatement("SELECT * FROM static_power_effectbase ORDER BY `IDString` DESC")) {
setInt(1,token);
setString(2,IDString);
setString(3,name);
setInt(4,flags);
return (executeUpdate() > 0);
}
public boolean CreateEffectBaseRAW(String IDString,String type,String detail){ ResultSet rs = prepareStatement.executeQuery();
prepareCallable("INSERT INTO `wpak_effect_effectbase_raw` (`token`,`IDString`,`name`,`flags`) VALUES (?,?,?,?)");
setString(1,IDString);
setString(2,type);
setString(3,detail);
return (executeUpdate() > 0); while (rs.next()) {
EffectsBase effectBase = new EffectsBase(rs);
effectList.add(effectBase);
} }
} catch (SQLException e) {
public boolean CreateEffectSource(String IDString,String source){ Logger.error(e.toString());
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){ return effectList;
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){ public static void cacheAllEffectModifiers() {
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){ String IDString;
prepareCallable("INSERT INTO `wpak_effect_condition_raw` (`effectID`,`type`, `text`) VALUES (?,?,?)"); AbstractEffectModifier abstractEffectModifier = null;
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){ try (Connection connection = DbManager.getConnection();
prepareCallable("INSERT INTO `wpak_static_power_effectmod` (`IDString`,`modType`,`minMod`,`maxMod`,`percentMod`,`ramp`,`useRampAdd`,`type`,`string1`,`string2`) VALUES (?,?,?,?,?,?,?,?,?,?)"); PreparedStatement prepareStatement = connection.prepareStatement("SELECT * FROM static_power_effectmod")) {
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){ ResultSet rs = prepareStatement.executeQuery();
prepareCallable("INSERT INTO `wpak_effect_mod_raw` (`effectID`,`type`, `text`) VALUES (?,?,?)");
setString(1,IDString);
setString(2,type);
setString(3,detail);
return (executeUpdate() > 0); while (rs.next()) {
}
IDString = rs.getString("IDString");
EffectsBase effectBase = PowersManager.getEffectByIDString(IDString);
Enum.ModType modifier = Enum.ModType.GetModType(rs.getString("modType"));
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){ //combine item prefix and suffix effect modifiers
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){ abstractEffectModifier = getCombinedModifiers(abstractEffectModifier, rs, effectBase, modifier);
prepareCallable("INSERT INTO `wpak_effect_poweraction_raw` (`effectID`,`type`, `text`) VALUES (?,?,?)");
setString(1,IDString); if (abstractEffectModifier != null) {
setString(2,type);
setString(3,detail);
return (executeUpdate() > 0); if (EffectsBase.modifiersMap.containsKey(effectBase.getIDString()) == false)
} EffectsBase.modifiersMap.put(effectBase.getIDString(), new HashSet<>());
public boolean ClearAllEffectBase(){
prepareCallable("DELETE from `wpak_static_power_effectbase`");
executeUpdate();
prepareCallable(" DELETE from `wpak_static_power_sourcetype` ");
executeUpdate();
prepareCallable(" DELETE from `wpak_static_power_failcondition` WHERE `powerOrEffect` = ?"); EffectsBase.modifiersMap.get(effectBase.getIDString()).add(abstractEffectModifier);
setString(1,"Effect");
executeUpdate();
prepareCallable(" DELETE from `wpak_static_power_effectmod` ");
executeUpdate();
return true;
} }
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"); } catch (Exception e) {
executeUpdate(); Logger.error(e);
}
}
return true; 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);
break;
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;
}
} }

25
src/engine/db/handlers/dbEffectsResourceCostHandler.java

@ -9,8 +9,14 @@
package engine.db.handlers; package engine.db.handlers;
import engine.gameManager.DbManager;
import engine.objects.EffectsResourceCosts; 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; import java.util.ArrayList;
public class dbEffectsResourceCostHandler extends dbHandlerBase { public class dbEffectsResourceCostHandler extends dbHandlerBase {
@ -20,11 +26,22 @@ public class dbEffectsResourceCostHandler extends dbHandlerBase {
this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName());
} }
public ArrayList<EffectsResourceCosts> GET_ALL_EFFECT_RESOURCES(String idString) {
ArrayList<EffectsResourceCosts> effectsResourceCosts = new ArrayList<>();
public ArrayList<EffectsResourceCosts> GET_ALL_EFFECT_RESOURCES(String idString) { try (Connection connection = DbManager.getConnection();
prepareCallable("SELECT * FROM `static_power_effectcost` WHERE `IDString` = ?"); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_power_effectcost` WHERE `IDString` = ?")) {
setString(1, idString);
return getObjectList(); preparedStatement.setString(1, idString);
ResultSet rs = preparedStatement.executeQuery();
effectsResourceCosts = getObjectsFromRs(rs, 1000);
} catch (SQLException e) {
Logger.error(e);
}
return effectsResourceCosts;
} }
} }

60
src/engine/db/handlers/dbEnchantmentHandler.java

@ -9,9 +9,12 @@
package engine.db.handlers; package engine.db.handlers;
import engine.gameManager.DbManager;
import engine.server.MBServerStatics; import engine.server.MBServerStatics;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@ -19,33 +22,54 @@ import java.util.concurrent.ConcurrentHashMap;
public class dbEnchantmentHandler extends dbHandlerBase { public class dbEnchantmentHandler extends dbHandlerBase {
public ConcurrentHashMap<String, Integer> GET_ENCHANTMENTS_FOR_ITEM(final int id) { public ConcurrentHashMap<String, Integer> GET_ENCHANTMENTS_FOR_ITEM(final int id) {
ConcurrentHashMap<String, Integer> enchants = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW); ConcurrentHashMap<String, Integer> 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 (Connection connection = DbManager.getConnection();
try { PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_item_enchantment` WHERE `ItemID`=?;")) {
ResultSet resultSet = executeQuery();
while (resultSet.next()) preparedStatement.setLong(1, id);
enchants.put(resultSet.getString("powerAction"), resultSet.getInt("rank"));
ResultSet rs = preparedStatement.executeQuery();
while (rs.next())
enchants.put(rs.getString("powerAction"), rs.getInt("rank"));
} catch (SQLException e) { } catch (SQLException e) {
Logger.error("SQL Error number: " + e.getErrorCode()); Logger.error(e);
} finally {
closeCallable();
} }
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) {
prepareCallable("INSERT INTO `dyn_item_enchantment` (`itemID`, `powerAction`, `rank`) VALUES (?, ?, ?);");
setLong(1, itemID); try (Connection connection = DbManager.getConnection();
setString(2, powerAction); PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_item_enchantment` (`itemID`, `powerAction`, `rank`) VALUES (?, ?, ?);")) {
setInt(3, rank);
return (executeUpdate() != 0); 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) { 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("DELETE FROM `dyn_item_enchantment` WHERE `itemID`=?;")) {
preparedStatement.setLong(1, itemID);
return (preparedStatement.executeUpdate() > 0);
} catch (SQLException e) {
Logger.error(e);
}
return false;
}
} }

767
src/engine/db/handlers/dbGuildHandler.java

@ -17,8 +17,7 @@ import engine.server.MBServerStatics;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.ResultSet; import java.sql.*;
import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
public class dbGuildHandler extends dbHandlerBase { public class dbGuildHandler extends dbHandlerBase {
@ -28,298 +27,512 @@ public class dbGuildHandler extends dbHandlerBase {
this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName());
} }
public static ArrayList<PlayerCharacter> GET_GUILD_BANISHED(final int id) {
return new ArrayList<>();
// 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`=?");
//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 getObjectList();
}
public static void LOAD_GUILD_HISTORY_FOR_PLAYER(PlayerCharacter playerCharacter) {
if (playerCharacter == null)
return;
ArrayList<GuildHistory> guildList = new ArrayList<>();
try (Connection connection = DbManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_guild_allianceenemylist` WHERE `GuildID` = ?")) {
preparedStatement.setInt(1, playerCharacter.getObjectUUID());
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
GuildHistory guildEntry = new GuildHistory(rs);
guildList.add(guildEntry);
}
} catch (SQLException e) {
Logger.error(e);
}
playerCharacter.setGuildHistory(guildList);
}
public int BANISH_FROM_GUILD_OFFLINE(final int target, boolean sourceIsGuildLeader) { 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," String queryString;
+ " `guild_isRecruiter`=0, `guild_isFullMember`=0, `guild_title`=0 WHERE `UID`=? && `guild_isInnerCouncil`=0"); 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 else
prepareCallable("UPDATE `obj_character` SET `guildUID`=NULL, `guild_isInnerCouncil`=0, `guild_isTaxCollector`=0," 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_isRecruiter`=0, `guild_isFullMember`=0, `guild_title`=0 WHERE `UID`=? && `guild_isInnerCouncil`=0";
setLong(1, (long) target);
return executeUpdate();
}
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) { public boolean ADD_TO_BANISHED_FROM_GUILDLIST(int target, long characterID) {
prepareCallable("INSERT INTO `dyn_guild_banishlist` (`GuildID`, `CharacterID`) VALUES (?,?)");
setLong(1, (long) target); try (Connection connection = DbManager.getConnection();
setLong(2, characterID); PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_guild_banishlist` (`GuildID`, `CharacterID`) VALUES (?,?)")) {
return (executeUpdate() > 0);
preparedStatement.setLong(1, 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) { public boolean REMOVE_FROM_BANISH_LIST(int target, long characterID) {
prepareCallable("DELETE FROM `dyn_guild_banishlist` (`GuildID`, `CharacterID`) VALUES (?,?)");
setLong(1, (long) target); try (Connection connection = DbManager.getConnection();
setLong(2, characterID); PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_guild_banishlist` (`GuildID`, `CharacterID`) VALUES (?,?)")) {
return (executeUpdate() > 0);
preparedStatement.setLong(1, target);
preparedStatement.setLong(2, characterID);
return (preparedStatement.executeUpdate() > 0);
} catch (SQLException e) {
Logger.error(e);
}
return false;
} }
public boolean ADD_TO_GUILDHISTORY(int target, PlayerCharacter pc, DateTime historyDate, GuildHistoryType historyType) { public boolean ADD_TO_GUILDHISTORY(int target, PlayerCharacter playerCharacter, DateTime historyDate, GuildHistoryType historyType) {
prepareCallable("INSERT INTO `dyn_character_guildhistory` (`GuildID`, `CharacterID`, `historyDate`, `historyType`) VALUES (?,?,?,?)");
setLong(1, (long) target); try (Connection connection = DbManager.getConnection();
setLong(2, pc.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_character_guildhistory` (`GuildID`, `CharacterID`, `historyDate`, `historyType`) VALUES (?,?,?,?)")) {
preparedStatement.setLong(1, target);
preparedStatement.setLong(2, playerCharacter.getObjectUUID());
if (historyDate == null) if (historyDate == null)
setNULL(3, java.sql.Types.DATE); preparedStatement.setNull(3, java.sql.Types.DATE);
else else
setTimeStamp(3, historyDate.getMillis()); preparedStatement.setTimestamp(3, new Timestamp(historyDate.getMillis()));
setString(4,historyType.name());
return (executeUpdate() > 0); preparedStatement.setString(4, historyType.name());
return (preparedStatement.executeUpdate() > 0);
} catch (SQLException e) {
Logger.error(e);
}
return false;
} }
//TODO Need to get this working. //TODO Need to get this working.
public ArrayList<Guild> GET_GUILD_HISTORY_OF_PLAYER(final int id) { public ArrayList<Guild> 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();
}
public String GET_GUILD_LIST(int guildType) { ArrayList<Guild> guildList = null;
String newLine = System.getProperty("line.separator"); try (Connection connection = DbManager.getConnection();
String outputStr = null; PreparedStatement preparedStatement = connection.prepareStatement("SELECT g.* FROM `obj_guild` g, `dyn_character_guildhistory` l WHERE g.`UID` = l.`GuildID` && l.`CharacterID` = ?")) {
ResultSet resultSet;
// Setup and execute stored procedure preparedStatement.setLong(1, id);
prepareCallable("CALL `guild_GETLIST`(?)"); ResultSet rs = preparedStatement.executeQuery();
setInt(1, guildType); guildList = getObjectsFromRs(rs, 20);
resultSet = executeQuery();
// Build formatted string with data from query } catch (SQLException e) {
Logger.error(e);
}
outputStr += newLine; return guildList;
outputStr += String.format("%-10s %-30s %-10s %-10s", "UUID", "Name", "GL UUID", "TOL_UUID"); }
outputStr += newLine;
try { public ArrayList<Guild> GET_GUILD_ALLIES(final int id) {
while (resultSet.next()) { ArrayList<Guild> guildList = null;
outputStr += String.format("%-10d %-30s %-10d %-10d", resultSet.getInt(1), try (Connection connection = DbManager.getConnection();
resultSet.getString(2), resultSet.getInt(3), resultSet.getInt(4)); PreparedStatement preparedStatement = connection.prepareStatement("SELECT g.* FROM `obj_guild` g, `dyn_guild_allianceenemylist` l "
outputStr += newLine; + "WHERE l.isAlliance = 1 && l.OtherGuildID = g.UID && l.GuildID=?")) {
} preparedStatement.setLong(1, id);
// Exception handling ResultSet rs = preparedStatement.executeQuery();
guildList = getObjectsFromRs(rs, 20);
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.getMessage()); Logger.error(e);
} finally {
closeCallable();
} }
return outputStr; return guildList;
} }
public ArrayList<Guild> GET_GUILD_ALLIES(final int id) { public ArrayList<Guild> GET_GUILD_ENEMIES(final int id) {
prepareCallable("SELECT g.* FROM `obj_guild` g, `dyn_guild_allianceenemylist` l "
+ "WHERE l.isAlliance = 1 && l.OtherGuildID = g.UID && l.GuildID=?"); ArrayList<Guild> guildList = null;
setLong(1, (long) id);
return getObjectList(); 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);
} }
public static ArrayList<PlayerCharacter> GET_GUILD_BANISHED(final int id) { return guildList;
return new ArrayList<>(); }
// Bugfix public ArrayList<PlayerCharacter> GET_GUILD_KOS_CHARACTER(final int id) {
// 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`=?");
//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 = ?"); ArrayList<PlayerCharacter> kosList = null;
//setLong(1, (long) id);
//return getObjectList(); 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);
} }
public ArrayList<Guild> GET_GUILD_ENEMIES(final int id) { } catch (SQLException e) {
prepareCallable("SELECT g.* FROM `obj_guild` g, `dyn_guild_allianceenemylist` l " Logger.error(e);
+ "WHERE l.isAlliance = 0 && l.OtherGuildID = g.UID && l.GuildID=?");
setLong(1, (long) id);
return getObjectList();
} }
public ArrayList<PlayerCharacter> GET_GUILD_KOS_CHARACTER(final int id) { return kosList;
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();
} }
public ArrayList<Guild> GET_GUILD_KOS_GUILD(final int id) { public ArrayList<Guild> 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 = ?"); ArrayList<Guild> guildList = null;
setLong(1, (long) id);
return getObjectList(); 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<Guild> GET_SUB_GUILDS(final int guildID) { public ArrayList<Guild> 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); ArrayList<Guild> guildList = null;
return getObjectList();
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) { public Guild GET_GUILD(int id) {
Guild guild = (Guild) DbManager.getFromCache(Enum.GameObjectType.Guild, id); Guild guild = (Guild) DbManager.getFromCache(Enum.GameObjectType.Guild, id);
if (guild != null) if (guild != null)
return guild; return guild;
if (id == 0) if (id == 0)
return Guild.getErrantGuild(); 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); try (Connection connection = DbManager.getConnection();
return (Guild) getObjectSingle(id); 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<Guild> GET_ALL_GUILDS() { public ArrayList<Guild> GET_ALL_GUILDS() {
prepareCallable("SELECT `obj_guild`.*, `object`.`parent` FROM `obj_guild` INNER JOIN `object` ON `object`.`UID` = `obj_guild`.`UID`"); ArrayList<Guild> guildList = null;
return getObjectList(); 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, 100);
} catch (SQLException e) {
Logger.error(e);
}
return guildList;
} }
public boolean IS_CREST_UNIQUE(final GuildTag gt) { public boolean IS_CREST_UNIQUE(final GuildTag gt) {
boolean valid = false; boolean valid = false;
if (gt.backgroundColor01 == gt.backgroundColor02) { String queryString;
//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);
// 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 { } else {
prepareCallable("SELECT `name` FROM `obj_guild` WHERE `backgroundColor01`=? && `backgroundColor02`=? && `symbolColor`=? && `backgroundDesign`=? && `symbol`=?;"); preparedStatement.setInt(1, gt.backgroundColor01);
setInt(1, gt.backgroundColor01); preparedStatement.setInt(2, gt.backgroundColor02);
setInt(2, gt.backgroundColor02); preparedStatement.setInt(3, gt.symbolColor);
setInt(3, gt.symbolColor); preparedStatement.setInt(4, gt.backgroundDesign);
setInt(4, gt.backgroundDesign); preparedStatement.setInt(5, gt.symbol);
setInt(5, gt.symbol); }
}
try { ResultSet rs = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
if (!rs.next()) if (!rs.next())
valid = true; valid = true;
rs.close();
} catch (SQLException e) { } catch (SQLException e) {
Logger.error(e.getMessage()); Logger.error(e);
} }
return valid; return valid;
} }
public String SET_PROPERTY(final Guild g, String name, Object new_value) { public boolean SET_GUILD_OWNED_CITY(int guildID, int cityID) {
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) { try (Connection connection = DbManager.getConnection();
prepareCallable("CALL guild_GETSETPROP(?,?,?,?)"); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_guild` SET `ownedCity`=? WHERE `UID`=?")) {
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) { preparedStatement.setLong(1, cityID);
prepareCallable("UPDATE `obj_guild` SET `ownedCity`=? WHERE `UID`=?"); preparedStatement.setLong(2, guildID);
setLong(1, (long) cityID);
setLong(2, (long) guildID); return (preparedStatement.executeUpdate() > 0);
return (executeUpdate() > 0);
}
public boolean SET_GUILD_LEADER(int objectUUID,int guildID) { } catch (SQLException e) {
prepareCallable("UPDATE `obj_guild` SET `leaderUID`=? WHERE `UID`=?"); Logger.error(e);
setLong(1, (long) objectUUID); }
setLong(2, (long) guildID); return false;
return (executeUpdate() > 0);
} }
public boolean SET_GUILD_LEADER(int objectUUID, int guildID) {
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) { public boolean IS_NAME_UNIQUE(final String name) {
boolean valid = false; boolean valid = false;
prepareCallable("SELECT `name` FROM `obj_guild` WHERE `name`=?;");
setString(1, name); try (Connection connection = DbManager.getConnection();
try { PreparedStatement preparedStatement = connection.prepareStatement("SELECT `name` FROM `obj_guild` WHERE `name`=?;")) {
ResultSet rs = executeQuery();
preparedStatement.setString(1, name);
ResultSet rs = preparedStatement.executeQuery();
if (!rs.next()) if (!rs.next())
valid = true; valid = true;
rs.close();
} catch (SQLException e) { } catch (SQLException e) {
Logger.warn(e.getMessage()); Logger.error(e);
} }
return valid;
return valid;
} }
public Guild SAVE_TO_DATABASE(Guild g) { public Guild SAVE_TO_DATABASE(Guild g) {
prepareCallable("CALL `guild_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
GuildTag gt = g.getGuildTag(); Guild guild = null;
if ( gt == null) GuildTag guildTag = g.getGuildTag();
if (guildTag == null)
return null; return null;
setLong(1, MBServerStatics.worldUUID);
setLong(2, g.getGuildLeaderUUID()); try (Connection connection = DbManager.getConnection();
setString(3, g.getName()); PreparedStatement preparedStatement = connection.prepareStatement("CALL `guild_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) {
setInt(4, gt.backgroundColor01);
setInt(5, gt.backgroundColor02); preparedStatement.setLong(1, MBServerStatics.worldUUID);
setInt(6, gt.symbolColor); preparedStatement.setLong(2, g.getGuildLeaderUUID());
setInt(7, gt.backgroundDesign); preparedStatement.setString(3, g.getName());
setInt(8 , gt.symbol); preparedStatement.setInt(4, guildTag.backgroundColor01);
setInt(9, g.getCharter()); preparedStatement.setInt(5, guildTag.backgroundColor02);
setString(10, g.getLeadershipType()); preparedStatement.setInt(6, guildTag.symbolColor);
setString(11, g.getMotto()); preparedStatement.setInt(7, guildTag.backgroundDesign);
preparedStatement.setInt(8, guildTag.symbol);
int objectUUID = (int) getUUID(); preparedStatement.setInt(9, g.getCharter());
preparedStatement.setString(10, g.getLeadershipType());
preparedStatement.setString(11, g.getMotto());
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
int objectUUID = (int) rs.getLong("UID");
if (objectUUID > 0) if (objectUUID > 0)
return GET_GUILD(objectUUID); guild = GET_GUILD(objectUUID);
return null; }
} catch (SQLException e) {
Logger.error(e);
}
return guild;
} }
public boolean UPDATE_GUILD_RANK_OFFLINE(int target, int newRank, int guildId) { 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); try (Connection connection = DbManager.getConnection();
setInt(2, target); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_title`=? WHERE `UID`=? && `guildUID`=?")) {
setInt(3, guildId);
return (executeUpdate() > 0); 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) { public boolean UPDATE_PARENT(int guildUID, int parentUID) {
prepareCallable("UPDATE `object` SET `parent`=? WHERE `UID`=?");
setInt(1, parentUID); try (Connection connection = DbManager.getConnection();
setInt(2, guildUID); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `object` SET `parent`=? WHERE `UID`=?")) {
return (executeUpdate() > 0);
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) { public int DELETE_GUILD(final Guild guild) {
prepareCallable("DELETE FROM `object` WHERE `UID` = ?");
setLong(1, (long) guild.getObjectUUID()); int row_count = 0;
return executeUpdate();
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) { public boolean UPDATE_MINETIME(int guildUID, int mineTime) {
prepareCallable("UPDATE `obj_guild` SET `mineTime`=? WHERE `UID`=?");
setInt(1, mineTime); try (Connection connection = DbManager.getConnection();
setInt(2, guildUID); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_guild` SET `mineTime`=? WHERE `UID`=?")) {
return (executeUpdate() > 0);
preparedStatement.setInt(1, mineTime);
preparedStatement.setInt(2, guildUID);
return (preparedStatement.executeUpdate() > 0);
} catch (SQLException e) {
Logger.error(e);
}
return false;
} }
// *** Refactor: Why are we saving tags/charter in update?
// It's not like this shit ever changes.
public int UPDATE_GUILD_STATUS_OFFLINE(int target, boolean isInnerCouncil, boolean isRecruiter, boolean isTaxCollector, int guildId) { public int UPDATE_GUILD_STATUS_OFFLINE(int target, boolean isInnerCouncil, boolean isRecruiter, boolean isTaxCollector, int guildId) {
int updateMask = 0; int updateMask = 0;
prepareCallable("SELECT `guild_isInnerCouncil`, `guild_isTaxCollector`, `guild_isRecruiter` FROM `obj_character` WHERE `UID`=? && `guildUID`=?"); int row_count = 0;
setLong(1, (long) target);
setLong(2, (long) guildId); try (Connection connection = DbManager.getConnection();
try { PreparedStatement preparedStatement = connection.prepareStatement("SELECT `guild_isInnerCouncil`, `guild_isTaxCollector`, `guild_isRecruiter` FROM `obj_character` WHERE `UID`=? && `guildUID`=?")) {
ResultSet rs = executeQuery();
preparedStatement.setLong(1, target);
preparedStatement.setLong(2, guildId);
ResultSet rs = preparedStatement.executeQuery();
//If the first query had no results, neither will the second //If the first query had no results, neither will the second
if (rs.first()) {
//Determine what is different //Determine what is different
if (rs.first()) {
if (rs.getBoolean("guild_isInnerCouncil") != isInnerCouncil) if (rs.getBoolean("guild_isInnerCouncil") != isInnerCouncil)
updateMask |= 4; updateMask |= 4;
if (rs.getBoolean("guild_isRecruiter") != isRecruiter) if (rs.getBoolean("guild_isRecruiter") != isRecruiter)
@ -327,137 +540,159 @@ public class dbGuildHandler extends dbHandlerBase {
if (rs.getBoolean("guild_isTaxCollector") != isTaxCollector) if (rs.getBoolean("guild_isTaxCollector") != isTaxCollector)
updateMask |= 1; updateMask |= 1;
} }
rs.close();
} catch (SQLException e) { } 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);
// *** Refactor: Why are we saving tags/charter in update? row_count = preparedStatement.executeUpdate();
// It's not like this shit ever changes.
} catch (SQLException e) {
Logger.error(e);
}
return row_count;
}
public boolean updateDatabase(final Guild g) { 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()); try (Connection connection = DbManager.getConnection();
setInt(2, g.getGuildTag().backgroundColor01); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_guild` SET `name`=?, `backgroundColor01`=?, `backgroundColor02`=?, `symbolColor`=?, `backgroundDesign`=?, `symbol`=?, `charter`=?, `motd`=?, `icMotd`=?, `nationMotd`=?, `leaderUID`=? WHERE `UID`=?")) {
setInt(3, g.getGuildTag().backgroundColor02);
setInt(4, g.getGuildTag().symbolColor); preparedStatement.setString(1, g.getName());
setInt(5, g.getGuildTag().backgroundDesign); preparedStatement.setInt(2, g.getGuildTag().backgroundColor01);
setInt(6, g.getGuildTag().symbol); preparedStatement.setInt(3, g.getGuildTag().backgroundColor02);
setInt(7, g.getCharter()); preparedStatement.setInt(4, g.getGuildTag().symbolColor);
setString(8, g.getMOTD()); preparedStatement.setInt(5, g.getGuildTag().backgroundDesign);
setString(9, g.getICMOTD()); preparedStatement.setInt(6, g.getGuildTag().symbol);
setString(10, ""); preparedStatement.setInt(7, g.getCharter());
setInt(11, g.getGuildLeaderUUID()); preparedStatement.setString(8, g.getMOTD());
setLong(12, (long) g.getObjectUUID()); preparedStatement.setString(9, g.getICMOTD());
return (executeUpdate() != 0); preparedStatement.setString(10, "");
preparedStatement.setInt(11, g.getGuildLeaderUUID());
preparedStatement.setLong(12, 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) { 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); try (Connection connection = DbManager.getConnection();
setLong(2, targetGuildID); PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_guild_allianceenemylist` (`GuildID`, `OtherGuildID`,`isRecommended`, `isAlliance`, `recommender`) VALUES (?,?,?,?,?)")) {
setBoolean(3, isRecommended);
setBoolean(4, isAlly); preparedStatement.setLong(1, sourceGuildID);
setString(5, recommender); preparedStatement.setLong(2, targetGuildID);
return (executeUpdate() > 0); 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) { public boolean REMOVE_FROM_ALLIANCE_LIST(final long sourceGuildID, long targetGuildID) {
prepareCallable("DELETE FROM `dyn_guild_allianceenemylist` WHERE `GuildID`=? AND `OtherGuildID`=?");
setLong(1, sourceGuildID); try (Connection connection = DbManager.getConnection();
setLong(2, targetGuildID); PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_guild_allianceenemylist` WHERE `GuildID`=? AND `OtherGuildID`=?")) {
return (executeUpdate() > 0);
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) { 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);
}
public boolean UPDATE_ALLIANCE(final long sourceGuildID, long targetGuildID, boolean isAlly) { try (Connection connection = DbManager.getConnection();
prepareCallable("UPDATE `dyn_guild_allianceenemylist` SET `isAlliance` = ? WHERE `GuildID`=? AND `OtherGuildID`=?"); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_guild_allianceenemylist` SET `isRecommended` = ? WHERE `GuildID`=? AND `OtherGuildID`=?")) {
setBoolean(1,isAlly);
setLong(2, sourceGuildID);
setLong(3, targetGuildID);
return (executeUpdate() > 0);
}
public boolean UPDATE_ALLIANCE_AND_RECOMMENDED(final long sourceGuildID, long targetGuildID, boolean isAlly) { preparedStatement.setLong(1, sourceGuildID);
prepareCallable("UPDATE `dyn_guild_allianceenemylist` SET `isRecommended` = ?, `isAlliance` = ? WHERE `GuildID`=? AND `OtherGuildID`=?"); preparedStatement.setLong(2, targetGuildID);
setByte(1,(byte)0);
setBoolean(2,isAlly);
setLong(3, sourceGuildID);
setLong(4, targetGuildID);
return (executeUpdate() > 0); return (preparedStatement.executeUpdate() > 0);
} catch (SQLException e) {
Logger.error(e);
return false;
}
} }
public void LOAD_ALL_ALLIANCES_FOR_GUILD(Guild guild) { public boolean UPDATE_ALLIANCE(final long sourceGuildID, long targetGuildID, boolean isAlly) {
if (guild == null) try (Connection connection = DbManager.getConnection();
return; PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_guild_allianceenemylist` SET `isAlliance` = ? WHERE `GuildID`=? AND `OtherGuildID`=?")) {
prepareCallable("SELECT * FROM `dyn_guild_allianceenemylist` WHERE `GuildID` = ?"); preparedStatement.setLong(1, sourceGuildID);
setInt(1,guild.getObjectUUID()); preparedStatement.setLong(2, targetGuildID);
try { return (preparedStatement.executeUpdate() > 0);
ResultSet rs = executeQuery();
//shrines cached in rs for easy cache on creation. } catch (SQLException e) {
while (rs.next()) { Logger.error(e);
GuildAlliances guildAlliance = new GuildAlliances(rs); return false;
guild.guildAlliances.put(guildAlliance.getAllianceGuild(), guildAlliance); }
} }
public boolean UPDATE_ALLIANCE_AND_RECOMMENDED(final long sourceGuildID, long targetGuildID, boolean isAlly) {
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) { } catch (SQLException e) {
Logger.error( e.getMessage()); Logger.error(e);
} finally { return false;
closeCallable();
} }
} }
public void LOAD_GUILD_HISTORY_FOR_PLAYER(PlayerCharacter pc) { public void LOAD_ALL_ALLIANCES_FOR_GUILD(Guild guild) {
if (pc == null) if (guild == null)
return; return;
prepareCallable("SELECT * FROM `dyn_character_guildhistory` WHERE `CharacterID` = ?"); try (Connection connection = DbManager.getConnection();
setInt(1,pc.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_guild_allianceenemylist` WHERE `GuildID` = ?")) {
try { preparedStatement.setInt(1, guild.getObjectUUID());
ArrayList<GuildHistory> tempList = new ArrayList<>(); ResultSet rs = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
//shrines cached in rs for easy cache on creation.
while (rs.next()) { while (rs.next()) {
GuildHistory guildHistory = new GuildHistory(rs); GuildAlliances guildAlliance = new GuildAlliances(rs);
tempList.add(guildHistory); guild.guildAlliances.put(guildAlliance.getAllianceGuild(), guildAlliance);
} }
pc.setGuildHistory(tempList);
} catch (SQLException e) { } catch (SQLException e) {
Logger.error(e.getMessage()); Logger.error(e);
} finally {
closeCallable();
} }
} }
//TODO uncomment this when finished with guild history warehouse integration //TODO uncomment this when finished with guild history warehouse integration

429
src/engine/db/handlers/dbHandlerBase.java

@ -15,456 +15,63 @@ import engine.gameManager.ConfigManager;
import engine.gameManager.DbManager; import engine.gameManager.DbManager;
import engine.objects.AbstractGameObject; import engine.objects.AbstractGameObject;
import engine.objects.AbstractWorldObject; import engine.objects.AbstractWorldObject;
import engine.server.MBServerStatics;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.*; import java.sql.ResultSet;
import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet;
public abstract class dbHandlerBase { public abstract class dbHandlerBase {
/*
* CallableStatements handled below this line!
*/
protected Class<? extends AbstractGameObject> localClass = null; protected Class<? extends AbstractGameObject> localClass = null;
protected GameObjectType localObjectType; protected GameObjectType localObjectType;
protected final ThreadLocal<CallableStatement> cs = new ThreadLocal<>();
protected final void prepareCallable(final String sql) { protected <T extends AbstractGameObject> AbstractGameObject getObjectFromRs(ResultSet rs) {
try {
this.cs.set((CallableStatement) DbManager.getConn().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);
} catch (SQLException e) {
Logger.error("SQL Error number: " + e.getErrorCode());
}
}
protected final void setLong(int parameterIndex, long value) { AbstractGameObject abstractGameObject = null;
try {
this.cs.get().setLong(parameterIndex, value);
} catch (SQLException e) {
Logger.error("SQL Error number: " + e.getErrorCode());
}
}
protected final void setFloat(int parameterIndex, float value) {
try {
this.cs.get().setFloat(parameterIndex, value);
} catch (SQLException e) {
Logger.error("SQL Error number: " + e.getErrorCode());
}
}
protected final void setShort(int parameterIndex, short value) {
try {
this.cs.get().setShort(parameterIndex, value);
} catch (SQLException e) {
Logger.error("SQL Error number: " + e.getErrorCode());
}
}
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);
} catch (SQLException e) {
Logger.error("SQL Error number: " + e.getErrorCode());
}
}
protected final void setByte(int parameterIndex, byte value) {
try {
this.cs.get().setByte(parameterIndex, value);
} catch (SQLException e) {
Logger.error("SQL Error number: " + e.getErrorCode());
}
}
protected final void setBoolean(int parameterIndex, boolean value) {
try {
this.cs.get().setBoolean(parameterIndex, value);
} catch (SQLException e) {
Logger.error("SQL Error number: " + e.getErrorCode());
}
}
protected final void setNULL(int parameterIndex, int type) {
try {
this.cs.get().setNull(parameterIndex, type);
} catch (SQLException e) {
Logger.error("SQL Error number: " + e.getErrorCode());
}
}
protected final void setLocalDateTime(int parameterIndex, LocalDateTime localDateTime) {
try {
this.cs.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.cs.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.cs.get().execute();
} catch (SQLException e) {
Logger.error("SQL Error number: " + e.getErrorCode());
logSQLCommand();
}
return false;
}
protected final ResultSet executeQuery() {
try {
return this.cs.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.cs.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.cs.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 { 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.cs.get().executeUpdate();
ResultSet rs = this.cs.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 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<numColumns+1; i++)
out += i + ": " + rsmd.getColumnName(i) + ", ";
Logger.info(out);
}
// Default actions to the objects table, generic to all objects
protected final long SET_PARENT(long objUID, long new_value, long old_value) {
prepareCallable("CALL object_GETSETPARENT(?,?,?)");
setLong(1, objUID);
setLong(2, new_value);
setLong(3, old_value);
return getUUID();
}
// NOTE: CALLING THIS FUNCTION CASCADE DELETES OBJECTS FROM THE DATABASE
protected final long REMOVE(long objUID) {
prepareCallable("CALL object_PURGECASCADE(?)");
setLong(1, objUID);
return getUUID();
}
protected <T extends AbstractGameObject> AbstractGameObject getObjectSingle(int id) {
return getObjectSingle(id, false, true);
}
protected <T extends AbstractGameObject> AbstractGameObject getObjectSingle(int id, boolean forceFromDB, boolean storeInCache) {
if (cs.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:" + cs.get().toString());
ResultSet rs = cs.get().executeQuery();
if (rs.next()) { if (rs.next()) {
out = localClass.getConstructor(ResultSet.class).newInstance(rs); abstractGameObject = localClass.getConstructor(ResultSet.class).newInstance(rs);
if (storeInCache) DbManager.addToCache(abstractGameObject);
DbManager.addToCache(out);
} }
rs.close();
} catch (Exception e) { } catch (Exception e) {
Logger.error("AbstractGameObject", e); Logger.error(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) && if ((abstractGameObject != null && abstractGameObject instanceof AbstractWorldObject) &&
(ConfigManager.serverType.equals(Enum.ServerType.WORLDSERVER) || (ConfigManager.serverType.equals(Enum.ServerType.WORLDSERVER) ||
(out.getObjectType() == GameObjectType.Guild))) (abstractGameObject.getObjectType() == GameObjectType.Guild)))
((AbstractWorldObject)out).runAfterLoad(); ((AbstractWorldObject) abstractGameObject).runAfterLoad();
return out;
}
protected void closeCallable() {
try {
if (this.cs.get() != null)
this.cs.get().close();
} catch (SQLException e) {}
}
protected <T extends AbstractGameObject> ArrayList<T> getObjectList() {
return getObjectList(20, false);
}
protected <T extends AbstractGameObject> ArrayList<T> getLargeObjectList() { return abstractGameObject;
return getObjectList(2000, false);
} }
@SuppressWarnings("unchecked") protected <T extends AbstractGameObject> ArrayList<T> getObjectsFromRs(ResultSet rs, int listSize) {
protected <T extends AbstractGameObject> ArrayList<T> getObjectList(int listSize, boolean forceFromDB) {
String query = "No Callable Statement accessable.";
ArrayList<T> out = new ArrayList<>(listSize);
if (this.cs.get() == null) ArrayList<T> objectList = new ArrayList<>(listSize);
return out;
try { try {
CallableStatement css = this.cs.get();
if (css != null)
query = this.cs.get().toString();
if (MBServerStatics.DB_ENABLE_QUERY_OUTPUT)
Logger.info( "[GetObjectList] Executing query:" + query);
ResultSet rs = this.cs.get().executeQuery();
while (rs.next()) { while (rs.next()) {
int id = rs.getInt(1); int id = rs.getInt(1);
if (!forceFromDB && DbManager.inCache(localObjectType, id)) { if (DbManager.inCache(localObjectType, id)) {
out.add((T) DbManager.getFromCache(localObjectType, id)); objectList.add((T) DbManager.getFromCache(localObjectType, id));
} else { } else {
AbstractGameObject toAdd = localClass.getConstructor(ResultSet.class).newInstance(rs); AbstractGameObject toAdd = localClass.getConstructor(ResultSet.class).newInstance(rs);
DbManager.addToCache(toAdd); DbManager.addToCache(toAdd);
out.add((T) toAdd); objectList.add((T) toAdd);
if (toAdd != null && toAdd instanceof AbstractWorldObject) if (toAdd != null && toAdd instanceof AbstractWorldObject)
((AbstractWorldObject)toAdd).runAfterLoad(); ((AbstractWorldObject) toAdd).runAfterLoad();
} }
} }
rs.close();
} catch (Exception e) { } catch (Exception e) {
Logger.error(localClass.getCanonicalName(), "List Failure: " + query, e); Logger.error(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<Integer> getIntegerList(final int columnNumber) {
if (MBServerStatics.DB_ENABLE_QUERY_OUTPUT)
Logger.info("[GetIntegerList] Executing query:" + this.cs.toString());
HashSet<Integer> 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; return objectList;
} }
} }

22
src/engine/db/handlers/dbHeightMapHandler.java

@ -1,8 +1,11 @@
package engine.db.handlers; package engine.db.handlers;
import engine.InterestManagement.HeightMap; import engine.InterestManagement.HeightMap;
import engine.gameManager.DbManager;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
@ -16,31 +19,24 @@ public class dbHeightMapHandler extends dbHandlerBase {
public void LOAD_ALL_HEIGHTMAPS() { public void LOAD_ALL_HEIGHTMAPS() {
HeightMap thisHeightmap; HeightMap thisHeightmap;
int recordsRead = 0;
int worthlessDupes = 0;
HeightMap.heightMapsCreated = 0; HeightMap.heightMapsCreated = 0;
prepareCallable("SELECT * FROM static_zone_heightmap INNER JOIN static_zone_size ON static_zone_size.loadNum = static_zone_heightmap.zoneLoadID"); 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")) {
try { ResultSet rs = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
while (rs.next()) { while (rs.next()) {
recordsRead++;
thisHeightmap = new HeightMap(rs); thisHeightmap = new HeightMap(rs);
if (thisHeightmap.getHeightmapImage() == null) { if (thisHeightmap.getHeightmapImage() == null) {
Logger.info( "Imagemap for " + thisHeightmap.getHeightMapID() + " was null"); Logger.info("Imagemap for " + thisHeightmap.getHeightMapID() + " was null");
continue; continue;
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Logger.error("LoadAllHeightMaps: " + e.getErrorCode() + ' ' + e.getMessage(), e); Logger.error(e);
} finally {
closeCallable();
} }
} }

96
src/engine/db/handlers/dbItemBaseHandler.java

@ -9,10 +9,13 @@
package engine.db.handlers; package engine.db.handlers;
import engine.gameManager.DbManager;
import engine.objects.BootySetEntry; import engine.objects.BootySetEntry;
import engine.objects.ItemBase; import engine.objects.ItemBase;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
@ -26,23 +29,20 @@ public class dbItemBaseHandler extends dbHandlerBase {
public void LOAD_BAKEDINSTATS(ItemBase itemBase) { public void LOAD_BAKEDINSTATS(ItemBase itemBase) {
try { try (Connection connection = DbManager.getConnection();
prepareCallable("SELECT * FROM `static_item_bakedinstat` WHERE `itemID` = ?"); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_item_bakedinstat` WHERE `itemID` = ?")) {
setInt(1, itemBase.getUUID());
ResultSet rs = executeQuery(); preparedStatement.setInt(1, itemBase.getUUID());
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) { while (rs.next()) {
if (rs.getBoolean("fromUse")) if (rs.getBoolean("fromUse"))
itemBase.getUsedStats().put(rs.getInt("token"), rs.getInt("numTrains")); itemBase.getUsedStats().put(rs.getInt("token"), rs.getInt("numTrains"));
else else
itemBase.getBakedInStats().put(rs.getInt("token"), rs.getInt("numTrains")); itemBase.getBakedInStats().put(rs.getInt("token"), rs.getInt("numTrains"));
} }
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.toString()); Logger.error(e);
} finally {
closeCallable();
} }
} }
@ -50,27 +50,24 @@ public class dbItemBaseHandler extends dbHandlerBase {
ArrayList<Integer> tempList = new ArrayList<>(); ArrayList<Integer> tempList = new ArrayList<>();
ArrayList<Integer> tempListOff = new ArrayList<>(); ArrayList<Integer> 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()) { while (rs.next()) {
int animation = rs.getInt("animation"); int animation = rs.getInt("animation");
boolean rightHand = rs.getBoolean("rightHand"); boolean rightHand = rs.getBoolean("rightHand");
if (rightHand) if (rightHand)
tempList.add(animation); tempList.add(animation);
else else
tempListOff.add(animation); tempListOff.add(animation);
} }
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.toString()); Logger.error(e);
} finally {
closeCallable();
} }
itemBase.setAnimations(tempList); itemBase.setAnimations(tempList);
@ -80,31 +77,24 @@ public class dbItemBaseHandler extends dbHandlerBase {
public void LOAD_ALL_ITEMBASES() { public void LOAD_ALL_ITEMBASES() {
ItemBase itemBase; ItemBase itemBase;
int recordsRead = 0; int recordsRead = 0;
prepareCallable("SELECT * FROM static_itembase"); try (Connection connection = DbManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_itembase")) {
try { ResultSet rs = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
while (rs.next()) { while (rs.next()) {
recordsRead++; recordsRead++;
itemBase = new ItemBase(rs); itemBase = new ItemBase(rs);
// Add ItemBase to internal cache
ItemBase.addToCache(itemBase); ItemBase.addToCache(itemBase);
} }
Logger.info( "read: " + recordsRead + "cached: " + ItemBase.getUUIDCache().size());
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.toString()); Logger.error(e);
} finally {
closeCallable();
} }
Logger.info("read: " + recordsRead + " cached: " + ItemBase.getUUIDCache().size());
} }
public HashMap<Integer, ArrayList<Integer>> LOAD_RUNES_FOR_NPC_AND_MOBS() { public HashMap<Integer, ArrayList<Integer>> LOAD_RUNES_FOR_NPC_AND_MOBS() {
@ -114,10 +104,10 @@ public class dbItemBaseHandler extends dbHandlerBase {
int runeBaseID; int runeBaseID;
int recordsRead = 0; 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 = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
while (rs.next()) { while (rs.next()) {
@ -126,25 +116,23 @@ public class dbItemBaseHandler extends dbHandlerBase {
runeSetID = rs.getInt("runeSet"); runeSetID = rs.getInt("runeSet");
runeBaseID = rs.getInt("runeBase"); runeBaseID = rs.getInt("runeBase");
if (runeSets.get(runeSetID) == null){ if (runeSets.get(runeSetID) == null) {
ArrayList<Integer> runeList = new ArrayList<>(); ArrayList<Integer> runeList = new ArrayList<>();
runeList.add(runeBaseID); runeList.add(runeBaseID);
runeSets.put(runeSetID, runeList); runeSets.put(runeSetID, runeList);
} } else {
else{ ArrayList<Integer> runeList = runeSets.get(runeSetID);
ArrayList<Integer>runeList = runeSets.get(runeSetID);
runeList.add(runeSetID); runeList.add(runeSetID);
runeSets.put(runeSetID, runeList); runeSets.put(runeSetID, runeList);
} }
} }
Logger.info("read: " + recordsRead + " cached: " + runeSets.size());
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.toString()); Logger.error(e);
} finally { return runeSets;
closeCallable();
} }
Logger.info("read: " + recordsRead + " cached: " + runeSets.size());
return runeSets; return runeSets;
} }
@ -153,13 +141,12 @@ public class dbItemBaseHandler extends dbHandlerBase {
HashMap<Integer, ArrayList<BootySetEntry>> bootySets = new HashMap<>(); HashMap<Integer, ArrayList<BootySetEntry>> bootySets = new HashMap<>();
BootySetEntry bootySetEntry; BootySetEntry bootySetEntry;
int bootySetID; int bootySetID;
int recordsRead = 0; 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 = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
while (rs.next()) { while (rs.next()) {
@ -168,25 +155,22 @@ public class dbItemBaseHandler extends dbHandlerBase {
bootySetID = rs.getInt("bootySet"); bootySetID = rs.getInt("bootySet");
bootySetEntry = new BootySetEntry(rs); bootySetEntry = new BootySetEntry(rs);
if (bootySets.get(bootySetID) == null){ if (bootySets.get(bootySetID) == null) {
ArrayList<BootySetEntry> bootyList = new ArrayList<>(); ArrayList<BootySetEntry> bootyList = new ArrayList<>();
bootyList.add(bootySetEntry); bootyList.add(bootySetEntry);
bootySets.put(bootySetID, bootyList); bootySets.put(bootySetID, bootyList);
} } else {
else{ ArrayList<BootySetEntry> bootyList = bootySets.get(bootySetID);
ArrayList<BootySetEntry>bootyList = bootySets.get(bootySetID);
bootyList.add(bootySetEntry); bootyList.add(bootySetEntry);
bootySets.put(bootySetID, bootyList); bootySets.put(bootySetID, bootyList);
} }
} }
Logger.info("read: " + recordsRead + " cached: " + bootySets.size());
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.toString()); Logger.error(e);
} finally { return bootySets;
closeCallable();
} }
Logger.info("read: " + recordsRead + " cached: " + bootySets.size());
return bootySets; return bootySets;
} }
} }

551
src/engine/db/handlers/dbItemHandler.java

@ -11,10 +11,16 @@ package engine.db.handlers;
import engine.Enum.ItemContainerType; import engine.Enum.ItemContainerType;
import engine.Enum.ItemType; import engine.Enum.ItemType;
import engine.Enum.OwnerType; import engine.gameManager.DbManager;
import engine.objects.*; import engine.objects.AbstractCharacter;
import engine.objects.CharacterItemManager;
import engine.objects.Item;
import org.pmw.tinylog.Logger; 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.ArrayList;
import java.util.HashSet; import java.util.HashSet;
@ -26,65 +32,81 @@ public class dbItemHandler extends dbHandlerBase {
this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName());
} }
private static String formatTradeString(HashSet<Integer> list) {
int size = list.size();
String ret = "";
if (size == 0)
return ret;
boolean start = true;
for (int i : list) {
if (start) {
ret += i;
start = false;
} else
ret += "," + i;
}
return ret;
}
public Item ADD_ITEM(Item toAdd) { public Item ADD_ITEM(Item toAdd) {
prepareCallable("CALL `item_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?,?);");
setInt(1, toAdd.getOwnerID()); try (Connection connection = DbManager.getConnection();
setInt(2, toAdd.getItemBaseID()); PreparedStatement preparedStatement = connection.prepareStatement("CALL `item_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?,?);")) {
setInt(3, toAdd.getChargesRemaining());
setInt(4, toAdd.getDurabilityCurrent()); preparedStatement.setInt(1, toAdd.getOwnerID());
setInt(5, toAdd.getDurabilityMax()); preparedStatement.setInt(2, toAdd.getItemBaseID());
preparedStatement.setInt(3, toAdd.getChargesRemaining());
preparedStatement.setInt(4, toAdd.getDurabilityCurrent());
preparedStatement.setInt(5, toAdd.getDurabilityMax());
if (toAdd.getNumOfItems() < 1) if (toAdd.getNumOfItems() < 1)
setInt(6, 1); preparedStatement.setInt(6, 1);
else else
setInt(6, toAdd.getNumOfItems()); preparedStatement.setInt(6, toAdd.getNumOfItems());
switch (toAdd.containerType) { switch (toAdd.containerType) {
case INVENTORY: case INVENTORY:
setString(7, "inventory"); preparedStatement.setString(7, "inventory");
break; break;
case EQUIPPED: case EQUIPPED:
setString(7, "equip"); preparedStatement.setString(7, "equip");
break; break;
case BANK: case BANK:
setString(7, "bank"); preparedStatement.setString(7, "bank");
break; break;
case VAULT: case VAULT:
setString(7, "vault"); preparedStatement.setString(7, "vault");
break; break;
case FORGE: case FORGE:
setString(7, "forge"); preparedStatement.setString(7, "forge");
break; break;
default: default:
setString(7, "none"); //Shouldn't be here preparedStatement.setString(7, "none"); //Shouldn't be here
break; break;
} }
setByte(8, toAdd.getEquipSlot()); preparedStatement.setByte(8, toAdd.getEquipSlot());
setInt(9, toAdd.getFlags()); preparedStatement.setInt(9, toAdd.getFlags());
setString(10, toAdd.getCustomName()); preparedStatement.setString(10, toAdd.getCustomName());
int objectUUID = (int) getUUID();
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
int objectUUID = (int) rs.getLong("UID");
if (objectUUID > 0) if (objectUUID > 0)
return GET_ITEM(objectUUID); return GET_ITEM(objectUUID);
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) { } catch (SQLException e) {
prepareCallable("DELETE FROM `object` WHERE `UID`=? && `type`='item' limit 1"); Logger.error(e);
setLong(1, (long) itemUUID);
return (executeUpdate() > 0);
} }
public String GET_OWNER(int ownerID) { return null;
prepareCallable("SELECT `type` FROM `object` WHERE `UID`=?");
setLong(1, (long) ownerID);
return getString("type");
} }
public boolean DO_TRADE(HashSet<Integer> from1, HashSet<Integer> from2, public boolean DO_TRADE(HashSet<Integer> from1, HashSet<Integer> from2,
@ -93,241 +115,282 @@ public class dbItemHandler extends dbHandlerBase {
AbstractCharacter ac1 = man1.getOwner(); AbstractCharacter ac1 = man1.getOwner();
AbstractCharacter ac2 = man2.getOwner(); AbstractCharacter ac2 = man2.getOwner();
boolean worked = false;
if (ac1 == null || ac2 == null || inventoryGold1 == null || inventoryGold2 == null) if (ac1 == null || ac2 == null || inventoryGold1 == null || inventoryGold2 == null)
return false; return false;
prepareCallable("CALL `item_TRADE`(?, ?, ?, ?, ?, ?, ?, ?)"); try (Connection connection = DbManager.getConnection();
setString(1, formatTradeString(from1)); PreparedStatement preparedStatement = connection.prepareStatement("CALL `item_TRADE`(?, ?, ?, ?, ?, ?, ?, ?)")) {
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();
}
private static String formatTradeString(HashSet<Integer> list) { preparedStatement.setString(1, formatTradeString(from1));
int size = list.size(); 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());
String ret = ""; ResultSet rs = preparedStatement.executeQuery();
if (size == 0)
return ret; if (rs.next())
boolean start = true; worked = rs.getBoolean("result");
for (int i : list) {
if (start){ } catch (SQLException e) {
ret += i; Logger.error(e);
start = false;
}
else
ret += "," + i;
} }
return ret; return worked;
} }
public ArrayList<Item> GET_EQUIPPED_ITEMS(final int targetId) { public ArrayList<Item> 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();
}
public Item GET_ITEM(final int id) { ArrayList<Item> 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, targetId);
ResultSet rs = preparedStatement.executeQuery();
itemList = getObjectsFromRs(rs, 10);
prepareCallable("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) {
setLong(1, (long) id); Logger.error(e);
return (Item) getObjectSingle(id); return null;
} }
public Item GET_GOLD_FOR_PLAYER(final int playerID, final int goldID, int worldID) { return itemList;
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); public Item GET_ITEM(final int itemUUID) {
int objectUUID = (int) getUUID();
return (Item) getObjectSingle(objectUUID); Item 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`.`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<Item> GET_ITEMS_FOR_ACCOUNT(final int accountId) { public ArrayList<Item> 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); ArrayList<Item> itemList;
return getObjectList();
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, accountId);
ResultSet rs = preparedStatement.executeQuery();
itemList = getObjectsFromRs(rs, 100);
} catch (SQLException e) {
Logger.error(e);
return null;
}
return itemList;
} }
public ArrayList<Item> GET_ITEMS_FOR_NPC(final int npcId) { public ArrayList<Item> 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); ArrayList<Item> itemList;
return getObjectList();
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<Item> GET_ITEMS_FOR_PC(final int id) { public ArrayList<Item> 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();
}
public ArrayList<Item> GET_ITEMS_FOR_PLAYER_AND_ACCOUNT(final int playerID, final int accountID) { ArrayList<Item> itemList;
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); try (Connection connection = DbManager.getConnection();
setLong(2, (long) accountID); 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`=?")) {
return getLargeObjectList();
preparedStatement.setLong(1, 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) { public boolean MOVE_GOLD(final Item from, final Item to, final int amt) {
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 newFromAmt = from.getNumOfItems() - amt;
int newToAmt = to.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()); preparedStatement.setLong(1, from.getObjectUUID());
setInt(2, newFromAmt); preparedStatement.setInt(2, newFromAmt);
setLong(3, (long) to.getObjectUUID()); preparedStatement.setLong(3, to.getObjectUUID());
setInt(4, newToAmt); preparedStatement.setInt(4, newToAmt);
setLong(5, (long) from.getObjectUUID()); preparedStatement.setLong(5, from.getObjectUUID());
setLong(6, (long) to.getObjectUUID()); preparedStatement.setLong(6, to.getObjectUUID());
return (executeUpdate() != 0);
return (preparedStatement.executeUpdate() > 0);
} catch (SQLException e) {
Logger.error(e);
}
return false;
} }
public boolean ORPHAN_INVENTORY(final HashSet<Item> inventory) { public boolean ORPHAN_INVENTORY(final HashSet<Item> inventory) {
boolean worked = true; boolean worked = true;
for (Item item : inventory) { for (Item item : inventory) {
if (item.getItemBase().getType().equals(ItemType.GOLD)) if (item.getItemBase().getType().equals(ItemType.GOLD))
continue; 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`=?;"); try (Connection connection = DbManager.getConnection();
setLong(1, (long) item.getObjectUUID()); 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`=?;")) {
if (executeUpdate() == 0)
worked = false; preparedStatement.setLong(1, item.getObjectUUID());
else worked = (preparedStatement.executeUpdate() > 0);
item.zeroItem();
}
return worked;
}
public Item PURCHASE_ITEM_FROM_VENDOR(final PlayerCharacter pc, final ItemBase ib) { if (worked)
Item item = null; item.zeroItem();
byte charges = 0;
charges = (byte) ib.getNumCharges();
short durability = (short) ib.getDurability();
Item temp = new Item(ib, pc.getObjectUUID(), } catch (SQLException e) {
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); Logger.error(e);
return false;
} }
return item; }
return worked;
} }
public HashSet<Integer> GET_ITEMS_FOR_VENDOR(final int vendorID) { public HashSet<Integer> GET_ITEMS_FOR_VENDOR(final int vendorID) {
prepareCallable("SELECT ID FROM static_itembase WHERE vendorType = ?");
setInt(1, vendorID);
return getIntegerList(1);
}
public ArrayList<Item> GET_ITEMS_FOR_VENDOR_FORGING(final int npcID) { HashSet<Integer> itemSet = new HashSet<>();
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); try (Connection connection = DbManager.getConnection();
setString(2, "forge"); PreparedStatement preparedStatement = connection.prepareStatement("SELECT ID FROM static_itembase WHERE vendorType = ?")) {
return getObjectList();
}
public String SET_PROPERTY(final Item i, String name, Object new_value) { preparedStatement.setInt(1, vendorID);
prepareCallable("CALL item_SETPROP(?,?,?)");
setLong(1, (long) i.getObjectUUID()); ResultSet rs = preparedStatement.executeQuery();
setString(2, name);
setString(3, String.valueOf(new_value)); while (rs.next())
return getResult(); itemSet.add(rs.getInt(1));
} catch (SQLException e) {
Logger.error(e);
return itemSet;
} }
public String SET_PROPERTY(final Item i, String name, Object new_value, Object old_value) { return itemSet;
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();
} }
//Used to transfer a single item between owners or equip or vault or bank or inventory //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, public boolean UPDATE_OWNER(final Item item, int newOwnerID, boolean ownerNPC, boolean ownerPlayer,
boolean ownerAccount, ItemContainerType containerType, int slot) { boolean ownerAccount, ItemContainerType containerType, int slot) {
prepareCallable("CALL `item_TRANSFER_OWNER`(?, ?, ?, ? )"); boolean worked = false;
setLong(1, (long) item.getObjectUUID());
try (Connection connection = DbManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("CALL `item_TRANSFER_OWNER`(?, ?, ?, ? )")) {
preparedStatement.setLong(1, item.getObjectUUID());
if (newOwnerID != 0) if (newOwnerID != 0)
setLong(2, (long) newOwnerID); preparedStatement.setLong(2, newOwnerID);
else else
setNULL(2, java.sql.Types.BIGINT); preparedStatement.setNull(2, java.sql.Types.BIGINT);
switch (containerType) { switch (containerType) {
case INVENTORY: case INVENTORY:
setString(3, "inventory"); preparedStatement.setString(3, "inventory");
break; break;
case EQUIPPED: case EQUIPPED:
setString(3, "equip"); preparedStatement.setString(3, "equip");
break; break;
case BANK: case BANK:
setString(3, "bank"); preparedStatement.setString(3, "bank");
break; break;
case VAULT: case VAULT:
setString(3, "vault"); preparedStatement.setString(3, "vault");
break; break;
case FORGE: case FORGE:
setString(3, "forge"); preparedStatement.setString(3, "forge");
break; break;
default: default:
setString(3, "none"); //Shouldn't be here preparedStatement.setString(3, "none"); //Shouldn't be here
break; break;
} }
setInt(4, slot); preparedStatement.setInt(4, slot);
return worked(); ResultSet rs = preparedStatement.executeQuery();
if (rs.next())
worked = rs.getBoolean("result");
} catch (SQLException e) {
Logger.error(e);
return false;
}
return worked;
} }
public boolean SET_DURABILITY(final Item item, int value) { 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`=?")) {
//Update an item except ownership preparedStatement.setInt(1, value);
public boolean UPDATE_DATABASE(final Item item) { preparedStatement.setLong(2, item.getObjectUUID());
prepareCallable("UPDATE `obj_item` SET `item_itembaseID`=?, `item_chargesRemaining`=?, `item_durabilityCurrent`=?, `item_durabilityMax`=?, `item_numberOfItems`=? WHERE `UID`=?"); preparedStatement.setInt(3, item.getDurabilityCurrent());
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) { return (preparedStatement.executeUpdate() > 0);
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) { } catch (SQLException e) {
prepareCallable("UPDATE `obj_item` SET `item_dateToUPGRADE` = ? WHERE `UID` = ?"); Logger.error(e);
setLong(1, date); return false;
setLong(2, (long) item.getObjectUUID()); }
return (executeUpdate() != 0);
} }
public boolean UPDATE_FORGE_TO_INVENTORY(final Item item) { 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"); try (Connection connection = DbManager.getConnection();
setLong(2, (long) item.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_container` = ? WHERE `UID` = ? AND `item_container` = 'forge';")) {
return (executeUpdate() != 0);
preparedStatement.setString(1, "inventory");
preparedStatement.setLong(2, item.getObjectUUID());
return (preparedStatement.executeUpdate() > 0);
} catch (SQLException e) {
Logger.error(e);
return false;
}
} }
/** /**
@ -349,82 +412,88 @@ public class dbItemHandler extends dbHandlerBase {
*/ */
public boolean UPDATE_GOLD(final Item item, int newValue, int oldValue) { 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; return false;
prepareCallable("UPDATE `obj_item` SET `item_numberOfItems`=? WHERE `UID`=?"); try (Connection connection = DbManager.getConnection();
setInt(1, newValue); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_numberOfItems`=? WHERE `UID`=?")) {
setLong(2, (long) item.getObjectUUID());
return (executeUpdate() != 0);
}
/** preparedStatement.setInt(1, newValue);
* Attempts to update the value of two Gold items simultaneously. preparedStatement.setLong(2, item.getObjectUUID());
*
* @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 (preparedStatement.executeUpdate() > 0);
return false;
if (otherGold.getItemBase().getType().equals(ItemType.GOLD) == false) } catch (SQLException e) {
Logger.error(e);
return 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) { public boolean UPDATE_REMAINING_CHARGES(final Item item) {
prepareCallable("UPDATE `obj_item` SET `item_chargesRemaining` = ? WHERE `UID` = ?");
setInt(1, item.getChargesRemaining()); try (Connection connection = DbManager.getConnection();
setLong(2, (long) item.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_chargesRemaining` = ? WHERE `UID` = ?")) {
return (executeUpdate() != 0);
preparedStatement.setInt(1, item.getChargesRemaining());
preparedStatement.setLong(2, item.getObjectUUID());
return (preparedStatement.executeUpdate() > 0);
} catch (SQLException e) {
Logger.error(e);
return false;
}
} }
// This is necessary because default number of items is 1. // This is necessary because default number of items is 1.
// When we create gold, we want it to start at 0 quantity. // When we create gold, we want it to start at 0 quantity.
public boolean ZERO_ITEM_STACK(Item item) { public boolean ZERO_ITEM_STACK(Item item) {
prepareCallable("UPDATE `obj_item` SET `item_numberOfItems`=0 WHERE `UID` = ?");
setLong(1, (long) item.getObjectUUID()); try (Connection connection = DbManager.getConnection();
return (executeUpdate() != 0); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_numberOfItems`=0 WHERE `UID` = ?")) {
preparedStatement.setLong(1, item.getObjectUUID());
return (preparedStatement.executeUpdate() > 0);
} catch (SQLException e) {
Logger.error(e);
return false;
}
} }
public boolean UPDATE_FLAGS(Item item) { 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);
}
public boolean UPDATE_VALUE(Item item,int value) { try (Connection connection = DbManager.getConnection();
prepareCallable("UPDATE `obj_item` SET `item_value`=? WHERE `UID` = ?"); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_flags`=? WHERE `UID` = ?")) {
setInt(1, value);
setLong(2, (long) item.getObjectUUID()); preparedStatement.setInt(1, item.getFlags());
return (executeUpdate() != 0); preparedStatement.setLong(2, item.getObjectUUID());
}
return (preparedStatement.executeUpdate() > 0);
public boolean UPDATE_FLAGS(Item item, int flags) { } catch (SQLException e) {
prepareCallable("UPDATE `obj_item` SET `item_flags`=? WHERE `UID` = ?"); Logger.error(e);
setInt(1, flags); return false;
setLong(2, (long) item.getObjectUUID()); }
return (executeUpdate() != 0);
} }
public boolean UPDATE_VALUE(Item item, int value) {
try (Connection connection = DbManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_item` SET `item_value`=? WHERE `UID` = ?")) {
preparedStatement.setInt(1, value);
preparedStatement.setLong(2, item.getObjectUUID());
return (preparedStatement.executeUpdate() > 0);
} catch (SQLException e) {
Logger.error(e);
return false;
}
}
} }

29
src/engine/db/handlers/dbKitHandler.java

@ -9,8 +9,14 @@
package engine.db.handlers; package engine.db.handlers;
import engine.gameManager.DbManager;
import engine.objects.Kit; 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; import java.util.ArrayList;
public class dbKitHandler extends dbHandlerBase { public class dbKitHandler extends dbHandlerBase {
@ -20,17 +26,20 @@ public class dbKitHandler extends dbHandlerBase {
this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName());
} }
public ArrayList<Kit> 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<Kit> GET_ALL_KITS() { public ArrayList<Kit> GET_ALL_KITS() {
prepareCallable("SELECT * FROM `static_rune_validkit`");
return getObjectList(); ArrayList<Kit> 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;
} }
} }

151
src/engine/db/handlers/dbLootTableHandler.java

@ -9,11 +9,14 @@
package engine.db.handlers; package engine.db.handlers;
import engine.gameManager.DbManager;
import engine.loot.LootManager; import engine.loot.LootManager;
import engine.objects.Item; import engine.objects.Item;
import engine.objects.LootTable; import engine.objects.LootTable;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
@ -23,206 +26,190 @@ public class dbLootTableHandler extends dbHandlerBase {
} }
public void populateLootGroups() { public void populateLootGroups() {
int recordsRead = 0; int recordsRead = 0;
prepareCallable("SELECT `groupID`, `minRoll`, `maxRoll`, `lootTableID`, `pModTableID`, `sModTableID` FROM `static_lootgroups`");
try { try (Connection connection = DbManager.getConnection();
ResultSet rs = executeQuery(); PreparedStatement preparedStatement = connection.prepareStatement("SELECT `groupID`, `minRoll`, `maxRoll`, `lootTableID`, `pModTableID`, `sModTableID` FROM `static_lootgroups`")) {
if (rs != null)
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) { while (rs.next()) {
recordsRead++; recordsRead++;
LootTable lootTable = LootTable.getLootGroup(rs.getInt("groupID")); LootTable lootTable = LootTable.getLootGroup(rs.getInt("groupID"));
lootTable.addRow(rs.getFloat("minRoll"), rs.getFloat("maxRoll"), rs.getInt("lootTableID"), rs.getInt("pModTableID"), rs.getInt("sModTableID"), ""); 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());
} catch (SQLException e) { } catch (SQLException e) {
} finally { Logger.error(e);
closeCallable();
} }
Logger.info("read: " + recordsRead + " cached: " + LootTable.getLootGroups().size());
} }
public void populateLootTables() { public void populateLootTables() {
int recordsRead = 0; 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`")) {
ResultSet rs = preparedStatement.executeQuery();
try {
ResultSet rs = executeQuery();
if (rs != null)
while (rs.next()) { while (rs.next()) {
recordsRead++; recordsRead++;
LootTable lootTable = LootTable.getLootTable(rs.getInt("lootTable")); LootTable lootTable = LootTable.getLootTable(rs.getInt("lootTable"));
lootTable.addRow(rs.getFloat("minRoll"), rs.getFloat("maxRoll"), rs.getInt("itemBaseUUID"), rs.getInt("minSpawn"), rs.getInt("maxSpawn"), ""); 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) { } catch (SQLException e) {
} finally { Logger.error(e);
closeCallable();
} }
Logger.info("read: " + recordsRead + " cached: " + LootTable.getLootTables().size());
} }
public void populateModTables() { public void populateModTables() {
int recordsRead = 0; int recordsRead = 0;
prepareCallable("SELECT `modTable`,`minRoll`,`maxRoll`,`value`,`action` FROM `static_modtables`"); try (Connection connection = DbManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT `modTable`,`minRoll`,`maxRoll`,`value`,`action` FROM `static_modtables`")) {
ResultSet rs = preparedStatement.executeQuery();
try {
ResultSet rs = executeQuery();
if (rs != null)
while (rs.next()) { while (rs.next()) {
recordsRead++; recordsRead++;
LootTable lootTable = LootTable.getModTable(rs.getInt("modTable")); LootTable lootTable = LootTable.getModTable(rs.getInt("modTable"));
lootTable.addRow(rs.getFloat("minRoll"), rs.getFloat("maxRoll"), rs.getInt("value"), 0, 0, rs.getString("action")); lootTable.addRow(rs.getFloat("minRoll"), rs.getFloat("maxRoll"), rs.getInt("value"), 0, 0, rs.getString("action"));
} }
Logger.info("read: " + recordsRead + " cached: " + LootTable.getModTables().size());
} catch (SQLException e) { } catch (SQLException e) {
} finally { Logger.error(e);
closeCallable();
} }
Logger.info("read: " + recordsRead + " cached: " + LootTable.getModTables().size());
} }
public void populateModGroups() { public void populateModGroups() {
int recordsRead = 0; int recordsRead = 0;
prepareCallable("SELECT `modGroup`,`minRoll`,`maxRoll`,`subTableID` FROM `static_modgroups`"); try (Connection connection = DbManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT `modGroup`,`minRoll`,`maxRoll`,`subTableID` FROM `static_modgroups`")) {
ResultSet rs = preparedStatement.executeQuery();
try {
ResultSet rs = executeQuery();
if (rs != null)
while (rs.next()) { while (rs.next()) {
recordsRead++; recordsRead++;
LootTable lootTable = LootTable.getModGroup(rs.getInt("modGroup")); LootTable lootTable = LootTable.getModGroup(rs.getInt("modGroup"));
lootTable.addRow(rs.getFloat("minRoll"), rs.getFloat("maxRoll"), rs.getInt("subTableID"), 0, 0, ""); lootTable.addRow(rs.getFloat("minRoll"), rs.getFloat("maxRoll"), rs.getInt("subTableID"), 0, 0, "");
} }
Logger.info("read: " + recordsRead + " cached: " + LootTable.getModGroups().size());
} catch (SQLException e) { } catch (SQLException e) {
} finally { Logger.error(e);
closeCallable();
} }
Logger.info("read: " + recordsRead + " cached: " + LootTable.getModGroups().size());
} }
public void LOAD_ENCHANT_VALUES() { public void LOAD_ENCHANT_VALUES() {
prepareCallable("SELECT `IDString`, `minMod` FROM `static_power_effectmod` WHERE `modType` = ?"); try (Connection connection = DbManager.getConnection();
setString(1,"Value"); PreparedStatement preparedStatement = connection.prepareStatement("SELECT `IDString`, `minMod` FROM `static_power_effectmod` WHERE `modType` = ?")) {
try { preparedStatement.setString(1, "Value");
ResultSet rs = executeQuery(); ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
while (rs.next())
Item.addEnchantValue(rs.getString("IDString"), rs.getInt("minMod")); Item.addEnchantValue(rs.getString("IDString"), rs.getInt("minMod"));
}
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e); Logger.error(e);
} finally {
closeCallable();
} }
} }
public void LOAD_ALL_LOOTGROUPS() { public void LOAD_ALL_LOOTGROUPS() {
int recordsRead = 0; int recordsRead = 0;
prepareCallable("SELECT * FROM static_lootgroups"); try (Connection connection = DbManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_lootgroups")) {
try { ResultSet rs = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
while (rs.next()) { while (rs.next()) {
LootManager.GenTableRow row = new LootManager.GenTableRow(rs); LootManager.GenTableRow row = new LootManager.GenTableRow(rs);
LootManager.AddGenTableRow(rs.getInt("groupID"), row); LootManager.AddGenTableRow(rs.getInt("groupID"), row);
} }
Logger.info( "read: " + recordsRead);
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.getErrorCode() + ' ' + e.getMessage(), e); Logger.error(e);
} finally {
closeCallable();
} }
Logger.info("read: " + recordsRead);
} }
public void LOAD_ALL_LOOTTABLES() { public void LOAD_ALL_LOOTTABLES() {
int recordsRead = 0; int recordsRead = 0;
prepareCallable("SELECT * FROM static_loottables"); try (Connection connection = DbManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_loottables")) {
try { ResultSet rs = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
while (rs.next()) { while (rs.next()) {
recordsRead++; recordsRead++;
LootManager.ItemTableRow row = new LootManager.ItemTableRow(rs); 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) { } catch (SQLException e) {
Logger.error( e.getErrorCode() + ' ' + e.getMessage(), e); Logger.error(e);
} finally {
closeCallable();
} }
Logger.info("read: " + recordsRead);
} }
public void LOAD_ALL_MODGROUPS() { public void LOAD_ALL_MODGROUPS() {
int recordsRead = 0; int recordsRead = 0;
prepareCallable("SELECT * FROM static_modgroups"); try (Connection connection = DbManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_modgroups")) {
try { ResultSet rs = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
while (rs.next()) { while (rs.next()) {
recordsRead++; recordsRead++;
LootManager.ModTypeTableRow mttr = new LootManager.ModTypeTableRow(rs); LootManager.ModTypeTableRow mttr = new LootManager.ModTypeTableRow(rs);
LootManager.AddModTypeTableRow(rs.getInt("modGroup"), mttr); LootManager.AddModTypeTableRow(rs.getInt("modGroup"), mttr);
} }
Logger.info( "read: " + recordsRead);
} catch (SQLException e) { } catch (SQLException e) {
Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); Logger.error(e);
} finally {
closeCallable();
} }
Logger.info("read: " + recordsRead);
} }
public void LOAD_ALL_MODTABLES() { public void LOAD_ALL_MODTABLES() {
int recordsRead = 0; int recordsRead = 0;
prepareCallable("SELECT * FROM static_modtables"); try (Connection connection = DbManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_modtables")) {
try { ResultSet rs = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
while (rs.next()) { while (rs.next()) {
recordsRead++; recordsRead++;
try {
LootManager.ModTableRow mtr = new LootManager.ModTableRow(rs); LootManager.ModTableRow mtr = new LootManager.ModTableRow(rs);
LootManager.AddModTableRow(rs.getInt("modTable"),mtr); LootManager.AddModTableRow(rs.getInt("modTable"), mtr);
}
catch(Exception ex){
Logger.info("MOD TABLE ERROR: " + rs.getInt("modTable"));
}
} }
Logger.info( "read: " + recordsRead);
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.getErrorCode() + ' ' + e.getMessage(), e); Logger.error(e);
} finally {
closeCallable();
} }
Logger.info("read: " + recordsRead);
} }
} }

25
src/engine/db/handlers/dbMenuHandler.java

@ -9,8 +9,14 @@
package engine.db.handlers; package engine.db.handlers;
import engine.gameManager.DbManager;
import engine.objects.MenuOption; 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; import java.util.ArrayList;
public class dbMenuHandler extends dbHandlerBase { public class dbMenuHandler extends dbHandlerBase {
@ -21,8 +27,21 @@ public class dbMenuHandler extends dbHandlerBase {
} }
public ArrayList<MenuOption> GET_MENU_OPTIONS(final int id) { public ArrayList<MenuOption> GET_MENU_OPTIONS(final int id) {
prepareCallable("SELECT * FROM `static_npc_menuoption` WHERE menuID = ?");
setInt(1, id); ArrayList<MenuOption> menuOptions = new ArrayList<>();
return getObjectList();
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;
} }
} }

119
src/engine/db/handlers/dbMineHandler.java

@ -13,7 +13,12 @@ import engine.gameManager.DbManager;
import engine.objects.Mine; import engine.objects.Mine;
import engine.objects.MineProduction; import engine.objects.MineProduction;
import engine.objects.Resource; 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; import java.util.ArrayList;
public class dbMineHandler extends dbHandlerBase { public class dbMineHandler extends dbHandlerBase {
@ -29,68 +34,102 @@ public class dbMineHandler extends dbHandlerBase {
return null; return null;
Mine mine = (Mine) DbManager.getFromCache(Enum.GameObjectType.Mine, id); Mine mine = (Mine) DbManager.getFromCache(Enum.GameObjectType.Mine, id);
if (mine != null) if (mine != null)
return mine; 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); ResultSet rs = preparedStatement.executeQuery();
return (Mine) getObjectSingle(id); mine = (Mine) getObjectFromRs(rs);
} catch (SQLException e) {
Logger.error(e);
}
return mine;
} }
public ArrayList<Mine> GET_ALL_MINES_FOR_SERVER() { public ArrayList<Mine> 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<Mine> 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) { public boolean CHANGE_OWNER(Mine mine, int playerUID) {
prepareCallable("UPDATE `obj_mine` SET `mine_ownerUID`=? WHERE `UID`=?");
setInt(1, playerUID); try (Connection connection = DbManager.getConnection();
setLong(2, (long) mine.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_mine` SET `mine_ownerUID`=? WHERE `UID`=?")) {
return (executeUpdate() > 0);
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) { public boolean CHANGE_RESOURCE(Mine mine, Resource resource) {
prepareCallable("UPDATE `obj_mine` SET `mine_resource`=? WHERE `UID`=?");
setString(1, resource.name()); try (Connection connection = DbManager.getConnection();
setLong(2, (long) mine.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_mine` SET `mine_resource`=? WHERE `UID`=?")) {
return (executeUpdate() > 0);
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) { public boolean CHANGE_TYPE(Mine mine, MineProduction productionType) {
prepareCallable("UPDATE `obj_mine` SET `mine_type`=? WHERE `UID`=?");
setString(1, productionType.name()); try (Connection connection = DbManager.getConnection();
setLong(2, (long) mine.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_mine` SET `mine_type`=? WHERE `UID`=?")) {
return (executeUpdate() > 0);
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) { 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) { try (Connection connection = DbManager.getConnection();
prepareCallable("CALL mine_SETPROP(?,?,?)"); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_mine` SET `flags`=? WHERE `UID`=?")) {
setLong(1, (long) m.getObjectUUID());
setString(2, name);
setString(3, String.valueOf(new_value));
return getResult();
}
// Advance all the mine windows respective to the current day preparedStatement.setInt(1, newFlags);
// at boot time. This ensures that mines always go live preparedStatement.setLong(2, mine.getObjectUUID());
// no matter what date in the database
return (preparedStatement.executeUpdate() > 0);
public String SET_PROPERTY(final Mine m, String name, Object new_value, Object old_value) {
prepareCallable("CALL mine_GETSETPROP(?,?,?,?)"); } catch (SQLException e) {
setLong(1, (long) m.getObjectUUID()); Logger.error(e);
setString(2, name); }
setString(3, String.valueOf(new_value)); return false;
setString(4, String.valueOf(old_value));
return getResult();
} }
} }

167
src/engine/db/handlers/dbMobBaseHandler.java

@ -11,10 +11,14 @@ package engine.db.handlers;
import engine.Enum.GameObjectType; import engine.Enum.GameObjectType;
import engine.gameManager.DbManager; import engine.gameManager.DbManager;
import engine.objects.*; import engine.objects.MobBase;
import engine.objects.MobBaseEffects;
import engine.objects.MobBaseStats;
import engine.server.MBServerStatics; import engine.server.MBServerStatics;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
@ -27,31 +31,55 @@ public class dbMobBaseHandler extends dbHandlerBase {
this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); 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) if (id == 0)
return null; return null;
MobBase mobBase = (MobBase) DbManager.getFromCache(GameObjectType.MobBase, id); MobBase mobBase = (MobBase) DbManager.getFromCache(GameObjectType.MobBase, id);
if ( mobBase != null) if (mobBase != null)
return mobBase; return mobBase;
prepareCallable("SELECT * FROM `static_npc_mobbase` WHERE `ID`=?"); try (Connection connection = DbManager.getConnection();
setInt(1, id); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_mobbase` WHERE `ID`=?")) {
return (MobBase) getObjectSingle(id, forceDB, true);
preparedStatement.setInt(1, id);
ResultSet rs = preparedStatement.executeQuery();
mobBase = (MobBase) getObjectFromRs(rs);
} catch (SQLException e) {
Logger.error(e);
}
return mobBase;
} }
public ArrayList<MobBase> GET_ALL_MOBBASES() { public ArrayList<MobBase> GET_ALL_MOBBASES() {
prepareCallable("SELECT * FROM `static_npc_mobbase`;");
return getObjectList(); ArrayList<MobBase> 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() { public void SET_AI_DEFAULTS() {
prepareCallable("SELECT * FROM `static_ai_defaults`");
try { try (Connection connection = DbManager.getConnection();
ResultSet rs = executeQuery(); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_ai_defaults`")) {
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) { while (rs.next()) {
MBServerStatics.AI_BASE_AGGRO_RANGE = rs.getInt("aggro_range"); MBServerStatics.AI_BASE_AGGRO_RANGE = rs.getInt("aggro_range");
MBServerStatics.AI_PATROL_DIVISOR = rs.getInt("patrol_chance"); MBServerStatics.AI_PATROL_DIVISOR = rs.getInt("patrol_chance");
@ -60,109 +88,101 @@ public class dbMobBaseHandler extends dbHandlerBase {
MBServerStatics.AI_RECALL_RANGE = rs.getInt("recall_range"); MBServerStatics.AI_RECALL_RANGE = rs.getInt("recall_range");
MBServerStatics.AI_PET_HEEL_DISTANCE = rs.getInt("pet_heel_distance"); MBServerStatics.AI_PET_HEEL_DISTANCE = rs.getInt("pet_heel_distance");
} }
rs.close();
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.getMessage()); Logger.error(e);
} finally {
closeCallable();
} }
} }
public boolean UPDATE_AI_DEFAULTS() { 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<Integer, Integer> LOAD_STATIC_POWERS(int mobBaseUUID) { public HashMap<Integer, Integer> LOAD_STATIC_POWERS(int mobBaseUUID) {
HashMap<Integer, Integer> powersList = new HashMap<>(); HashMap<Integer, Integer> 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")); powersList.put(rs.getInt("token"), rs.getInt("rank"));
}
rs.close();
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.getMessage()); Logger.error(e);
} finally {
closeCallable();
} }
return powersList; return powersList;
} }
public ArrayList<MobBaseEffects> GET_RUNEBASE_EFFECTS(int runeID) { public ArrayList<MobBaseEffects> GET_RUNEBASE_EFFECTS(int runeID) {
ArrayList<MobBaseEffects> effectsList = new ArrayList<>(); ArrayList<MobBaseEffects> effectsList = new ArrayList<>();
prepareCallable("SELECT * FROM `static_npc_mobbase_effects` WHERE `mobbaseUUID` = ?");
setInt(1, runeID);
try { try (Connection connection = DbManager.getConnection();
ResultSet rs = executeQuery(); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_mobbase_effects` WHERE `mobbaseUUID` = ?")) {
while (rs.next()) {
preparedStatement.setInt(1, runeID);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
MobBaseEffects mbs = new MobBaseEffects(rs); MobBaseEffects mbs = new MobBaseEffects(rs);
effectsList.add(mbs); effectsList.add(mbs);
} }
rs.close();
} catch (SQLException e) { } catch (SQLException e) {
Logger.error (e.getMessage()); Logger.error(e);
} finally {
closeCallable();
} }
return effectsList; return effectsList;
} }
public MobBaseStats LOAD_STATS(int mobBaseUUID) { public MobBaseStats LOAD_STATS(int mobBaseUUID) {
MobBaseStats mbs = MobBaseStats.GetGenericStats();
prepareCallable("SELECT * FROM `static_npc_mobbase_stats` WHERE `mobbaseUUID` = ?"); MobBaseStats mobBaseStats = MobBaseStats.GetGenericStats();
setInt(1, mobBaseUUID);
try {
ResultSet rs = executeQuery();
while (rs.next()) {
mbs = new MobBaseStats(rs); try (Connection connection = DbManager.getConnection();
} PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_mobbase_stats` WHERE `mobbaseUUID` = ?")) {
} catch (SQLException e) { preparedStatement.setInt(1, mobBaseUUID);
Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); ResultSet rs = preparedStatement.executeQuery();
} finally {
closeCallable();
}
return mbs;
} while (rs.next())
mobBaseStats = new MobBaseStats(rs);
public boolean RENAME_MOBBASE(int ID, String newName) { } catch (SQLException e) {
prepareCallable("UPDATE `static_npc_mobbase` SET `name`=? WHERE `ID`=?;"); Logger.error(e);
setString(1, newName); }
setInt(2, ID); return mobBaseStats;
return (executeUpdate() > 0);
} }
public void LOAD_ALL_MOBBASE_SPEEDS(MobBase mobBase) { public void LOAD_ALL_MOBBASE_SPEEDS(MobBase mobBase) {
if (mobBase.getLoadID() == 0) if (mobBase.getLoadID() == 0)
return; return;
ArrayList<MobLootBase> mobLootList = new ArrayList<>();
prepareCallable("SELECT * FROM `static_npc_mobbase_race` WHERE `mobbaseID` = ?");
setInt(1, mobBase.getLoadID());
try { try (Connection connection = DbManager.getConnection();
ResultSet rs = executeQuery(); 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()) { while (rs.next()) {
float walk = rs.getFloat("walkStandard"); float walk = rs.getFloat("walkStandard");
float walkCombat = rs.getFloat("walkCombat"); float walkCombat = rs.getFloat("walkCombat");
@ -171,11 +191,8 @@ public class dbMobBaseHandler extends dbHandlerBase {
mobBase.updateSpeeds(walk, walkCombat, run, runCombat); mobBase.updateSpeeds(walk, walkCombat, run, runCombat);
} }
} catch (SQLException e) { } catch (SQLException e) {
Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); Logger.error(e);
} finally {
closeCallable();
} }
} }
} }

258
src/engine/db/handlers/dbMobHandler.java

@ -9,12 +9,15 @@
package engine.db.handlers; package engine.db.handlers;
import engine.gameManager.DbManager;
import engine.objects.Mob; import engine.objects.Mob;
import engine.objects.Zone; import engine.objects.Zone;
import engine.server.MBServerStatics; import engine.server.MBServerStatics;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
@ -26,151 +29,224 @@ public class dbMobHandler extends dbHandlerBase {
this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName());
} }
public Mob ADD_MOB(Mob toAdd) public Mob ADD_MOB(Mob toAdd) {
{
prepareCallable("CALL `mob_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"); Mob mobile = null;
setLong(1, toAdd.getParentZoneID());
setInt(2, toAdd.getMobBaseID()); try (Connection connection = DbManager.getConnection();
setInt(3, toAdd.getGuildUUID()); PreparedStatement preparedStatement = connection.prepareStatement("CALL `mob_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);")) {
setFloat(4, toAdd.getSpawnX());
setFloat(5, toAdd.getSpawnY()); preparedStatement.setLong(1, toAdd.getParentZoneID());
setFloat(6, toAdd.getSpawnZ()); preparedStatement.setInt(2, toAdd.getMobBaseID());
setInt(7, 0); preparedStatement.setInt(3, toAdd.getGuildUUID());
setFloat(8, toAdd.getSpawnRadius()); preparedStatement.setFloat(4, toAdd.getSpawnX());
setInt(9, toAdd.getTrueSpawnTime()); 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) if (toAdd.getContract() != null)
setInt(10, toAdd.getContract().getContractID()); preparedStatement.setInt(10, toAdd.getContract().getContractID());
else else
setInt(10, 0); preparedStatement.setInt(10, 0);
setInt(11, toAdd.getBuildingID());
setInt(12, toAdd.getLevel()); preparedStatement.setInt(11, toAdd.getBuildingID());
setString(13, toAdd.getFirstName()); preparedStatement.setInt(12, toAdd.getLevel());
int objectUUID = (int) getUUID(); preparedStatement.setString(13, toAdd.getFirstName());
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
int objectUUID = (int) rs.getLong("UID");
if (objectUUID > 0) if (objectUUID > 0)
return GET_MOB(objectUUID); mobile = GET_MOB(objectUUID);
return null;
} }
public boolean updateUpgradeTime(Mob mob, DateTime upgradeDateTime) { } catch (SQLException e) {
throw new RuntimeException(e);
}
return mobile;
}
try { public boolean updateUpgradeTime(Mob mob, DateTime upgradeDateTime) {
prepareCallable("UPDATE obj_mob SET upgradeDate=? " try (Connection connection = DbManager.getConnection();
+ "WHERE UID = ?"); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE obj_mob SET upgradeDate=? "
+ "WHERE UID = ?")) {
if (upgradeDateTime == null) if (upgradeDateTime == null)
setNULL(1, java.sql.Types.DATE); preparedStatement.setNull(1, java.sql.Types.DATE);
else else
setTimeStamp(1, upgradeDateTime.getMillis()); preparedStatement.setTimestamp(1, new java.sql.Timestamp(upgradeDateTime.getMillis()));
setInt(2, mob.getObjectUUID()); preparedStatement.setInt(2, mob.getObjectUUID());
executeUpdate();
} catch (Exception e) { preparedStatement.execute();
Logger.error("Mob.updateUpgradeTime", "UUID: " + mob.getObjectUUID());
return false;
}
return true; return true;
} catch (SQLException e) {
Logger.error(e);
}
return false;
} }
public int DELETE_MOB(final Mob mob) { public int DELETE_MOB(final Mob mob) {
prepareCallable("DELETE FROM `object` WHERE `UID` = ?");
setLong(1, mob.getDBID());
return executeUpdate();
}
public void LOAD_PATROL_POINTS(Mob captain) { 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` = ?"); try (Connection connection = DbManager.getConnection();
setInt(1,captain.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_guards` WHERE `captainUID` = ?")) {
try { preparedStatement.setInt(1, captain.getObjectUUID());
ResultSet rs = executeQuery(); ResultSet rs = preparedStatement.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"); 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) if (toCreate == null)
return; return;
// toCreate.despawn();
if (toCreate != null) { if (toCreate != null) {
toCreate.setTimeToSpawnSiege(System.currentTimeMillis() + MBServerStatics.FIFTEEN_MINUTES); toCreate.setTimeToSpawnSiege(System.currentTimeMillis() + MBServerStatics.FIFTEEN_MINUTES);
toCreate.setDeathTime(System.currentTimeMillis()); toCreate.setDeathTime(System.currentTimeMillis());
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.toString()); Logger.error(e);
} finally { }
closeCallable();
} }
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 (?,?,?,?)")) {
} preparedStatement.setLong(1, captainUID);
preparedStatement.setInt(2, mobBaseID);
preparedStatement.setString(3, name);
preparedStatement.setInt(4, slot);
public boolean ADD_TO_GUARDS(final long captainUID, final int mobBaseID, final String name, final int slot) { return (preparedStatement.executeUpdate() > 0);
prepareCallable("INSERT INTO `dyn_guards` (`captainUID`, `mobBaseID`,`name`, `slot`) VALUES (?,?,?,?)");
setLong(1, captainUID); } catch (SQLException e) {
setInt(2, mobBaseID); Logger.error(e);
setString(3, name); return false;
setInt(4, slot); }
return (executeUpdate() > 0);
} }
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) {
prepareCallable("DELETE FROM `dyn_guards` WHERE `captainUID`=? AND `mobBaseID`=? AND `slot` =?");
setLong(1, captainUID); try (Connection connection = DbManager.getConnection();
setInt(2, mobBaseID); PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_guards` WHERE `captainUID`=? AND `mobBaseID`=? AND `slot` =?")) {
setInt(3,slot);
return (executeUpdate() > 0); 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<Mob> GET_ALL_MOBS_FOR_ZONE(Zone zone) { public ArrayList<Mob> 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()); ArrayList<Mob> mobileList = new ArrayList<>();
return getLargeObjectList();
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) { 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); Mob mobile = null;
return (Mob) getObjectSingle(objectUUID);
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) { 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); int row_count = 0;
setFloat(2, locX);
setFloat(3, locY); try (Connection connection = DbManager.getConnection();
setFloat(4, locZ); 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`=?;")) {
setLong(5, mobID);
return executeUpdate(); 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) { public String SET_PROPERTY(final Mob m, String name, Object new_value) {
prepareCallable("CALL mob_SETPROP(?,?,?)");
setLong(1, m.getObjectUUID()); String result = "";
setString(2, name);
setString(3, String.valueOf(new_value)); try (Connection connection = DbManager.getConnection();
return getResult(); PreparedStatement preparedStatement = connection.prepareStatement("CALL mob_SETPROP(?,?,?)")) {
}
preparedStatement.setLong(1, m.getObjectUUID());
public String SET_PROPERTY(final Mob m, String name, Object new_value, Object old_value) { preparedStatement.setString(2, name);
prepareCallable("CALL mob_GETSETPROP(?,?,?,?)"); preparedStatement.setString(3, String.valueOf(new_value));
setLong(1, m.getObjectUUID());
setString(2, name); ResultSet rs = preparedStatement.executeQuery();
setString(3, String.valueOf(new_value));
setString(4, String.valueOf(old_value)); if (rs.next())
return getResult(); result = rs.getString("result");
} catch (SQLException e) {
Logger.error(e);
}
return result;
} }
} }

511
src/engine/db/handlers/dbNPCHandler.java

@ -10,14 +10,19 @@
package engine.db.handlers; package engine.db.handlers;
import engine.Enum.ProfitType; import engine.Enum.ProfitType;
import engine.objects.*; import engine.gameManager.DbManager;
import engine.objects.NPC;
import engine.objects.NPCProfits;
import engine.objects.ProducedItem;
import engine.objects.Zone;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
public class dbNPCHandler extends dbHandlerBase { public class dbNPCHandler extends dbHandlerBase {
@ -27,182 +32,240 @@ public class dbNPCHandler extends dbHandlerBase {
} }
public NPC ADD_NPC(NPC toAdd, boolean isMob) { public NPC ADD_NPC(NPC toAdd, boolean isMob) {
prepareCallable("CALL `npc_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);");
setLong(1, toAdd.getParentZoneID()); NPC npc = null;
setString(2, toAdd.getName());
setInt(3, toAdd.getContractID()); try (Connection connection = DbManager.getConnection();
setInt(4, toAdd.getGuildUUID()); PreparedStatement preparedStatement = connection.prepareStatement("CALL `npc_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);")) {
setFloat(5, toAdd.getSpawnX());
setFloat(6, toAdd.getSpawnY()); preparedStatement.setLong(1, toAdd.getParentZoneID());
setFloat(7, toAdd.getSpawnZ()); preparedStatement.setString(2, toAdd.getName());
setInt(8, toAdd.getLevel()); preparedStatement.setInt(3, toAdd.getContractID());
setFloat(9, toAdd.getBuyPercent()); preparedStatement.setInt(4, toAdd.getGuildUUID());
setFloat(10, toAdd.getSellPercent()); preparedStatement.setFloat(5, toAdd.getSpawnX());
if (toAdd.getBuilding() != null) { preparedStatement.setFloat(6, toAdd.getSpawnY());
setInt(11, toAdd.getBuilding().getObjectUUID()); preparedStatement.setFloat(7, toAdd.getSpawnZ());
} else { preparedStatement.setInt(8, toAdd.getLevel());
setInt(11, 0); preparedStatement.setFloat(9, toAdd.getBuyPercent());
} preparedStatement.setFloat(10, toAdd.getSellPercent());
int objectUUID = (int) getUUID(); if (toAdd.getBuilding() != null)
if (objectUUID > 0) { preparedStatement.setInt(11, toAdd.getBuilding().getObjectUUID());
return GET_NPC(objectUUID); else
} preparedStatement.setInt(11, 0);
return null;
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
int objectUUID = (int) rs.getLong("UID");
if (objectUUID > 0)
npc = GET_NPC(objectUUID);
} }
public int DELETE_NPC(final NPC npc) { } catch (SQLException e) {
if (npc.isStatic()) { throw new RuntimeException(e);
return DELETE_STATIC_NPC(npc);
} }
npc.removeFromZone(); return npc;
prepareCallable("DELETE FROM `object` WHERE `UID` = ?");
setLong(1, (long) npc.getDBID());
return executeUpdate();
} }
private int DELETE_STATIC_NPC(final NPC npc) { public int DELETE_NPC(final NPC npc) {
int row_count = 0;
npc.removeFromZone(); npc.removeFromZone();
prepareCallable("DELETE FROM `_init_npc` WHERE `ID` = ?");
setInt(1, npc.getDBID()); try (Connection connection = DbManager.getConnection();
return executeUpdate(); 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<NPC> GET_ALL_NPCS_FOR_ZONE(Zone zone) { public ArrayList<NPC> 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 ArrayList<NPC> GET_ALL_NPCS() { ArrayList<NPC> npcList = new ArrayList<>();
prepareCallable("SELECT `obj_npc`.*, `object`.`parent` FROM `object` INNER JOIN `obj_npc` ON `obj_npc`.`UID` = `object`.`UID`;");
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` = ?;")) {
return getObjectList(); preparedStatement.setLong(1, zone.getObjectUUID());
ResultSet rs = preparedStatement.executeQuery();
npcList = getObjectsFromRs(rs, 1000);
} catch (SQLException e) {
Logger.error(e);
} }
public ArrayList<NPC> GET_NPCS_BY_BUILDING(final int buildingID) { return npcList;
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) { 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); NPC npc = null;
return (NPC) getObjectSingle(objectUUID);
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) { 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); int rowCount;
setFloat(2, locX);
setFloat(3, locY); try (Connection connection = DbManager.getConnection();
setFloat(4, locZ); 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`=?;")) {
setLong(5, npcID);
return executeUpdate(); 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) { 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) { String result = "";
prepareCallable("CALL npc_GETSETPROP(?,?,?,?)");
setLong(1, (long) n.getDBID()); try (Connection connection = DbManager.getConnection();
setString(2, name); PreparedStatement preparedStatement = connection.prepareStatement("CALL npc_SETPROP(?,?,?)")) {
setString(3, String.valueOf(new_value));
setString(4, String.valueOf(old_value)); preparedStatement.setLong(1, n.getDBID());
return getResult(); preparedStatement.setString(2, name);
preparedStatement.setString(3, String.valueOf(new_value));
ResultSet rs = preparedStatement.executeQuery();
if (rs.next())
result = rs.getString("result");
} catch (SQLException e) {
Logger.error(e);
}
return result;
} }
public void updateDatabase(final NPC npc) { public void updateDatabase(final NPC npc) {
prepareCallable("UPDATE obj_npc SET npc_name=?, npc_contractID=?, npc_typeID=?, npc_guildID=?,"
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_spawnX=?, npc_spawnY=?, npc_spawnZ=?, npc_level=? ,"
+ " npc_buyPercent=?, npc_sellPercent=?, npc_buildingID=? WHERE UID = ?"); + " npc_buyPercent=?, npc_sellPercent=?, npc_buildingID=? WHERE UID = ?")) {
setString(1, npc.getName());
setInt(2, (npc.getContract() != null) ? npc.getContract().getObjectUUID() : 0); preparedStatement.setString(1, npc.getName());
setInt(3, 0); preparedStatement.setInt(2, (npc.getContract() != null) ? npc.getContract().getObjectUUID() : 0);
setInt(4, (npc.getGuild() != null) ? npc.getGuild().getObjectUUID() : 0); preparedStatement.setInt(3, 0);
setFloat(5, npc.getBindLoc().x); preparedStatement.setInt(4, (npc.getGuild() != null) ? npc.getGuild().getObjectUUID() : 0);
setFloat(6, npc.getBindLoc().y); preparedStatement.setFloat(5, npc.getBindLoc().x);
setFloat(7, npc.getBindLoc().z); preparedStatement.setFloat(6, npc.getBindLoc().y);
setShort(8, npc.getLevel()); preparedStatement.setFloat(7, npc.getBindLoc().z);
setFloat(9, npc.getBuyPercent()); preparedStatement.setShort(8, npc.getLevel());
setFloat(10, npc.getSellPercent()); preparedStatement.setFloat(9, npc.getBuyPercent());
setInt(11, (npc.getBuilding() != null) ? npc.getBuilding().getObjectUUID() : 0); preparedStatement.setFloat(10, npc.getSellPercent());
setInt(12, npc.getDBID()); preparedStatement.setInt(11, (npc.getBuilding() != null) ? npc.getBuilding().getObjectUUID() : 0);
executeUpdate(); preparedStatement.setInt(12, npc.getDBID());
preparedStatement.executeUpdate();
} catch (SQLException e) {
Logger.error(e);
}
} }
public boolean updateUpgradeTime(NPC npc, DateTime upgradeDateTime) { public boolean updateUpgradeTime(NPC npc, DateTime upgradeDateTime) {
try (Connection connection = DbManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("UPDATE obj_npc SET upgradeDate=? "
try { + "WHERE UID = ?")) {
prepareCallable("UPDATE obj_npc SET upgradeDate=? "
+ "WHERE UID = ?");
if (upgradeDateTime == null) if (upgradeDateTime == null)
setNULL(1, java.sql.Types.DATE); preparedStatement.setNull(1, java.sql.Types.DATE);
else else
setTimeStamp(1, upgradeDateTime.getMillis()); preparedStatement.setTimestamp(1, new java.sql.Timestamp(upgradeDateTime.getMillis()));
setInt(2, npc.getObjectUUID()); preparedStatement.setInt(2, npc.getObjectUUID());
executeUpdate();
} catch (Exception e) {
Logger.error("UUID: " + npc.getObjectUUID());
return false;
}
return true;
}
public boolean UPDATE_BUY_PROFIT(NPC npc,float percent) { preparedStatement.execute();
prepareCallable("UPDATE `obj_npc` SET `npc_buyPercent`=? WHERE `UID`=?"); return true;
setFloat(1, percent);
setLong(2, npc.getObjectUUID());
return (executeUpdate() > 0);
}
public boolean UPDATE_SELL_PROFIT(NPC npc,float percent) { } catch (SQLException e) {
prepareCallable("UPDATE `obj_npc` SET `npc_sellPercent`=? WHERE `UID`=?"); Logger.error(e);
setFloat(1, percent);
setLong(2, npc.getObjectUUID());
return (executeUpdate() > 0);
} }
return false;
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) { public boolean UPDATE_MOBBASE(NPC npc, int mobBaseID) {
prepareCallable("UPDATE `obj_npc` SET `npc_raceID`=? WHERE `UID`=?");
setLong(1, mobBaseID); try (Connection connection = DbManager.getConnection();
setLong(2, npc.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_npc` SET `npc_raceID`=? WHERE `UID`=?")) {
return (executeUpdate() > 0);
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) { public boolean UPDATE_EQUIPSET(NPC npc, int equipSetID) {
prepareCallable("UPDATE `obj_npc` SET `equipsetID`=? WHERE `UID`=?");
setInt(1, equipSetID); try (Connection connection = DbManager.getConnection();
setLong(2, npc.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_npc` SET `equipsetID`=? WHERE `UID`=?")) {
return (executeUpdate() > 0);
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) {
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());
public boolean UPDATE_NAME(NPC npc,String name) { return (preparedStatement.executeUpdate() > 0);
prepareCallable("UPDATE `obj_npc` SET `npc_name`=? WHERE `UID`=?");
setString(1, name); } catch (SQLException e) {
setLong(2, npc.getObjectUUID()); Logger.error(e);
return (executeUpdate() > 0); return false;
}
} }
public void LOAD_PIRATE_NAMES() { public void LOAD_PIRATE_NAMES() {
@ -211,10 +274,10 @@ public class dbNPCHandler extends dbHandlerBase {
int mobBase; int mobBase;
int recordsRead = 0; int recordsRead = 0;
prepareCallable("SELECT * FROM static_piratenames"); try (Connection connection = DbManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_piratenames")) {
try { ResultSet rs = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
while (rs.next()) { while (rs.next()) {
@ -224,72 +287,110 @@ public class dbNPCHandler extends dbHandlerBase {
// Handle new mobbbase entries // Handle new mobbbase entries
if (NPC._pirateNames.get(mobBase) == null) { if (NPC._pirateNames.get(mobBase) == null)
NPC._pirateNames.putIfAbsent(mobBase, new ArrayList<>()); NPC._pirateNames.putIfAbsent(mobBase, new ArrayList<>());
}
// Insert name into proper arraylist // Insert name into proper arraylist
NPC._pirateNames.get(mobBase).add(pirateName); NPC._pirateNames.get(mobBase).add(pirateName);
}
} catch (SQLException e) {
Logger.error(e);
} }
Logger.info("names read: " + recordsRead + " for " Logger.info("names read: " + recordsRead + " for "
+ NPC._pirateNames.size() + " mobBases"); + 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) {
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) { } catch (SQLException e) {
Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); Logger.error(e);
} finally { return false;
closeCallable();
} }
} }
public boolean REMOVE_FROM_PRODUCTION_LIST(final long ID, final long npcUID) {
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) { try (Connection connection = DbManager.getConnection();
prepareCallable("INSERT INTO `dyn_npc_production` (`ID`,`npcUID`, `itemBaseID`,`dateToUpgrade`, `isRandom`, `prefix`, `suffix`, `name`,`playerID`) VALUES (?,?,?,?,?,?,?,?,?)"); PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_npc_production` WHERE `ID`=? AND `npcUID`=?;")) {
setLong(1,ID);
setLong(2, npcUID); preparedStatement.setLong(1, ID);
setLong(3, itemBaseID); preparedStatement.setLong(2, npcUID);
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) { return (preparedStatement.executeUpdate() > 0);
prepareCallable("DELETE FROM `dyn_npc_production` WHERE `ID`=? AND `npcUID`=?;");
setLong(1,ID); } catch (SQLException e) {
setLong(2, npcUID); Logger.error(e);
return (executeUpdate() > 0); return false;
}
} }
public boolean UPDATE_ITEM_TO_INVENTORY(final long ID,final long npcUID) { 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); try (Connection connection = DbManager.getConnection();
setLong(2, ID); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_npc_production` SET `inForge`=? WHERE `ID`=? AND `npcUID`=?;")) {
setLong(3, npcUID);
return (executeUpdate() > 0); 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) { 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) { 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); try (Connection connection = DbManager.getConnection();
setLong(2, ID); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_npc_production` SET `ID`=? WHERE `ID`=? AND `npcUID`=? LIMIT 1;")) {
setLong(3, npcUID);
preparedStatement.setLong(1, value);
preparedStatement.setLong(2, ID);
preparedStatement.setLong(3, npcUID);
return (executeUpdate() > 0); return (preparedStatement.executeUpdate() > 0);
} catch (SQLException e) {
Logger.error(e);
return false;
}
} }
public void LOAD_ALL_ITEMS_TO_PRODUCE(NPC npc) { public void LOAD_ALL_ITEMS_TO_PRODUCE(NPC npc) {
@ -297,60 +398,68 @@ public class dbNPCHandler extends dbHandlerBase {
if (npc == null) if (npc == null)
return; return;
prepareCallable("SELECT * FROM `dyn_npc_production` WHERE `npcUID` = ?"); try (Connection connection = DbManager.getConnection();
setInt(1,npc.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_npc_production` WHERE `npcUID` = ?")) {
try { preparedStatement.setInt(1, npc.getObjectUUID());
ResultSet rs = executeQuery(); ResultSet rs = preparedStatement.executeQuery();
//shrines cached in rs for easy cache on creation.
while (rs.next()) { while (rs.next()) {
ProducedItem producedItem = new ProducedItem(rs); ProducedItem producedItem = new ProducedItem(rs);
npc.forgedItems.add(producedItem); npc.forgedItems.add(producedItem);
} }
} catch (SQLException e) { } catch (SQLException e) {
Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); Logger.error(e);
} finally {
closeCallable();
} }
} }
public boolean UPDATE_PROFITS(NPC npc,ProfitType profitType, float value){ public boolean UPDATE_PROFITS(NPC npc, ProfitType profitType, float value) {
prepareCallable("UPDATE `dyn_npc_profits` SET `" + profitType.dbField + "` = ? WHERE `npcUID`=?");
setFloat(1, value); try (Connection connection = DbManager.getConnection();
setInt(2, npc.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `dyn_npc_profits` SET `" + profitType.dbField + "` = ? WHERE `npcUID`=?")) {
return (executeUpdate() > 0);
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() { public void LOAD_NPC_PROFITS() {
HashMap<Integer, ArrayList<BuildingRegions>> regions;
NPCProfits npcProfit; NPCProfits npcProfit;
try (Connection connection = DbManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM dyn_npc_profits")) {
prepareCallable("SELECT * FROM dyn_npc_profits"); ResultSet rs = preparedStatement.executeQuery();
try {
ResultSet rs = executeQuery();
while (rs.next()) { while (rs.next()) {
npcProfit = new NPCProfits(rs); npcProfit = new NPCProfits(rs);
NPCProfits.ProfitCache.put(npcProfit.npcUID, npcProfit); NPCProfits.ProfitCache.put(npcProfit.npcUID, npcProfit);
} }
} catch (SQLException e) { } catch (SQLException e) {
Logger.error(": " + e.getErrorCode() + ' ' + e.getMessage(), e); Logger.error(e);
} finally {
closeCallable();
} }
} }
public boolean CREATE_PROFITS(NPC npc){ public boolean CREATE_PROFITS(NPC npc) {
prepareCallable("INSERT INTO `dyn_npc_profits` (`npcUID`) VALUES (?)");
setLong(1,npc.getObjectUUID()); try (Connection connection = DbManager.getConnection();
return (executeUpdate() > 0); 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;
}
} }
} }

639
src/engine/db/handlers/dbPlayerCharacterHandler.java

@ -18,6 +18,8 @@ import engine.objects.PlayerFriends;
import engine.server.MBServerStatics; import engine.server.MBServerStatics;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
@ -31,125 +33,142 @@ public class dbPlayerCharacterHandler extends dbHandlerBase {
} }
public PlayerCharacter ADD_PLAYER_CHARACTER(final PlayerCharacter toAdd) { public PlayerCharacter ADD_PLAYER_CHARACTER(final PlayerCharacter toAdd) {
if (toAdd.getAccount() == null) {
PlayerCharacter playerCharacter = null;
if (toAdd.getAccount() == null)
return 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();
if (rs.next()) {
int objectUUID = (int) rs.getLong("UID");
if (objectUUID > 0)
playerCharacter = GET_PLAYER_CHARACTER(objectUUID);
} }
prepareCallable("CALL `character_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);");
setLong(1, toAdd.getAccount().getObjectUUID()); } catch (SQLException e) {
setString(2, toAdd.getFirstName()); Logger.error(e);
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) { 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);
}
}
public static boolean DELETE_CHARACTER_IGNORE(final PlayerCharacter pc, final ArrayList<Integer> toDelete) { 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; return false;
} }
public ArrayList<PlayerCharacter> GET_ALL_PLAYERCHARACTERS() { public ArrayList<PlayerCharacter> GET_CHARACTERS_FOR_ACCOUNT(final int id) {
prepareCallable("SELECT * FROM `obj_character`");
return getObjectList(); ArrayList<PlayerCharacter> 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';")) {
public ArrayList<PlayerCharacter> GET_CHARACTERS_FOR_ACCOUNT(final int id, boolean forceFromDB) { preparedStatement.setLong(1, 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';"); ResultSet rs = preparedStatement.executeQuery();
setLong(1, (long) id); characterList = getObjectsFromRs(rs, 10);
return getObjectList(10, forceFromDB);
} catch (SQLException e) {
Logger.error(e);
} }
public ArrayList<PlayerCharacter> GET_CHARACTERS_FOR_ACCOUNT(final int id) { return characterList;
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();
} }
public ArrayList<PlayerCharacter> GET_ALL_CHARACTERS() { public ArrayList<PlayerCharacter> 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<PlayerCharacter> 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;
} }
/** /**
*
* <code>getFirstName</code> looks up the first name of a PlayerCharacter by * <code>getFirstName</code> looks up the first name of a PlayerCharacter by
* first checking the GOM cache and then querying the database. * first checking the GOM cache and then querying the database.
* PlayerCharacter objects that are not already cached won't be instantiated * PlayerCharacter objects that are not already cached won't be instantiated
* and cached. * 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<Integer, String> GET_IGNORE_LIST(final int objectUUID, final boolean skipActiveCheck) { public ConcurrentHashMap<Integer, String> GET_IGNORE_LIST(final int objectUUID, final boolean skipActiveCheck) {
ConcurrentHashMap<Integer, String> out = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW);
prepareCallable("SELECT * FROM `dyn_character_ignore` WHERE `accountUID` = ?;"); ConcurrentHashMap<Integer, String> ignoreList = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW);
setLong(1, (long) objectUUID);
try { try (Connection connection = DbManager.getConnection();
ResultSet rs = executeQuery(); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_character_ignore` WHERE `accountUID` = ?;")) {
preparedStatement.setLong(1, objectUUID);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) { while (rs.next()) {
int ignoreCharacterID = rs.getInt("ignoringUID"); int ignoreCharacterID = rs.getInt("ignoringUID");
if (ignoreCharacterID == 0) {
if (ignoreCharacterID == 0)
continue; continue;
}
String name = rs.getString("characterName"); String name = rs.getString("characterName");
out.put(ignoreCharacterID, name); ignoreList.put(ignoreCharacterID, name);
} }
rs.close();
} catch (SQLException e) { } catch (SQLException e) {
Logger.error("SQL Error number: " + e.getErrorCode()); Logger.error(e);
return out; // null to explicitly indicate a problem and prevent data loss
} finally {
closeCallable();
} }
return out;
return ignoreList;
} }
public PlayerCharacter GET_PLAYER_CHARACTER(final int objectUUID) { public PlayerCharacter GET_PLAYER_CHARACTER(final int objectUUID) {
@ -157,245 +176,395 @@ public class dbPlayerCharacterHandler extends dbHandlerBase {
if (objectUUID == 0) if (objectUUID == 0)
return null; return null;
PlayerCharacter pc = (PlayerCharacter) DbManager.getFromCache(Enum.GameObjectType.PlayerCharacter, objectUUID); PlayerCharacter playerCharacter = (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);
}
public boolean INSERT_CHARACTER_IGNORE(final PlayerCharacter pc, final ArrayList<Integer> toAdd) { if (playerCharacter != null)
boolean allWorked = true; return playerCharacter;
prepareCallable("INSERT INTO `dyn_character_ignore` (`characterUID`, `ignoringUID`) VALUES (?, ?)");
setLong(1, (long) pc.getObjectUUID()); try (Connection connection = DbManager.getConnection();
for (int id : toAdd) { PreparedStatement preparedStatement = connection.prepareStatement("SELECT `obj_character`.*, `object`.`parent` FROM `object` INNER JOIN `obj_character` ON `obj_character`.`UID` = `object`.`UID` WHERE `object`.`UID` = ?")) {
setLong(2, (long) id);
if (executeUpdate(false) == 0) { preparedStatement.setLong(1, objectUUID);
allWorked = false;
} ResultSet rs = preparedStatement.executeQuery();
playerCharacter = (PlayerCharacter) getObjectFromRs(rs);
} catch (SQLException e) {
Logger.error(e);
} }
closeCallable(); return playerCharacter;
return allWorked;
} }
public boolean IS_CHARACTER_NAME_UNIQUE(final String firstName) { public boolean IS_CHARACTER_NAME_UNIQUE(final String firstName) {
boolean unique = true; boolean unique = true;
prepareCallable("SELECT `char_firstname` FROM `obj_character` WHERE `char_isActive`=1 && `char_firstname`=?");
setString(1, firstName); try (Connection connection = DbManager.getConnection();
try { PreparedStatement preparedStatement = connection.prepareStatement("SELECT `char_firstname` FROM `obj_character` WHERE `char_isActive`=1 && `char_firstname`=?")) {
ResultSet rs = executeQuery();
if (rs.next()) { preparedStatement.setString(1, firstName);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next())
unique = false; unique = false;
}
rs.close();
} catch (SQLException e) { } catch (SQLException e) {
Logger.error("SQL Error number: " + e.getMessage()); Logger.error(e);
unique = false;
} finally {
closeCallable();
} }
return unique; return unique;
} }
public boolean UPDATE_NAME(String oldFirstName, String newFirstName, String newLastName) { 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); try (Connection connection = DbManager.getConnection();
setString(2, newLastName); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_firstname`=?, `char_lastname`=? WHERE `char_firstname`=? AND `char_isActive`='1'")) {
setString(3, oldFirstName);
return (executeUpdate() != 0); 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) { public boolean SET_DELETED(final PlayerCharacter pc) {
prepareCallable("UPDATE `obj_character` SET `char_isActive`=? WHERE `UID` = ?");
setBoolean(1, !pc.isDeleted()); try (Connection connection = DbManager.getConnection();
setLong(2, (long) pc.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_isActive`=? WHERE `UID` = ?")) {
return (executeUpdate() != 0);
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) { public boolean SET_ACTIVE(final PlayerCharacter pc, boolean status) {
prepareCallable("UPDATE `obj_character` SET `char_isActive`=? WHERE `UID` = ?");
setBoolean(1, status); try (Connection connection = DbManager.getConnection();
setLong(2, (long) pc.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_isActive`=? WHERE `UID` = ?")) {
return (executeUpdate() != 0);
preparedStatement.setBoolean(1, status);
preparedStatement.setLong(2, pc.getObjectUUID());
return (preparedStatement.executeUpdate() > 0);
} 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) {
prepareCallable("UPDATE `obj_character` SET `char_bindBuilding`=? WHERE `UID` = ?");
setInt(1, bindBuildingID); try (Connection connection = DbManager.getConnection();
setLong(2, (long) pc.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_bindBuilding`=? WHERE `UID` = ?")) {
return (executeUpdate() != 0);
preparedStatement.setInt(1, bindBuildingID);
preparedStatement.setLong(2, pc.getObjectUUID());
return (preparedStatement.executeUpdate() > 0);
} 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) {
prepareCallable("UPDATE `obj_character` SET `anniversery`=? WHERE `UID` = ?");
setBoolean(1, flag); try (Connection connection = DbManager.getConnection();
setLong(2, (long) pc.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `anniversery`=? WHERE `UID` = ?")) {
return (executeUpdate() != 0);
preparedStatement.setBoolean(1, flag);
preparedStatement.setLong(2, pc.getObjectUUID());
return (preparedStatement.executeUpdate() > 0);
} catch (SQLException e) {
Logger.error(e);
}
return false;
} }
public boolean UPDATE_CHARACTER_EXPERIENCE(final PlayerCharacter pc) { public boolean UPDATE_CHARACTER_EXPERIENCE(final PlayerCharacter pc) {
prepareCallable("UPDATE `obj_character` SET `char_experience`=? WHERE `UID` = ?");
setInt(1, pc.getExp()); try (Connection connection = DbManager.getConnection();
setLong(2, (long) pc.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_experience`=? WHERE `UID` = ?")) {
return (executeUpdate() != 0);
preparedStatement.setInt(1, pc.getExp());
preparedStatement.setLong(2, pc.getObjectUUID());
return (preparedStatement.executeUpdate() > 0);
} catch (SQLException e) {
Logger.error(e);
}
return false;
} }
public boolean UPDATE_GUILD(final PlayerCharacter pc, int guildUUID) { 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);
}
public boolean UPDATE_CHARACTER_STAT(final PlayerCharacter pc, String stat, short amount) { try (Connection connection = DbManager.getConnection();
prepareCallable("UPDATE `obj_character` SET `" + stat + "`=? WHERE `UID`=?"); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guildUID`=? WHERE `UID` = ?")) {
setInt(1, pc.getExp());
setLong(2, (long) pc.getObjectUUID()); preparedStatement.setInt(1, guildUUID);
return (executeUpdate() != 0); preparedStatement.setLong(2, pc.getObjectUUID());
return (preparedStatement.executeUpdate() > 0);
} catch (SQLException e) {
Logger.error(e);
}
return false;
} }
public boolean UPDATE_CHARACTER_STATS(final PlayerCharacter pc) { 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) { try (Connection connection = DbManager.getConnection();
prepareCallable("CALL character_SETPROP(?,?,?)"); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_strMod`=?, `char_dexMod`=?, `char_conMod`=?, `char_intMod`=?, `char_spiMod`=? WHERE `UID`=?")) {
setLong(1, (long) c.getObjectUUID());
setString(2, name); preparedStatement.setInt(1, pc.getStrMod());
setString(3, String.valueOf(new_value)); preparedStatement.setInt(2, pc.getDexMod());
return getResult(); preparedStatement.setInt(3, pc.getConMod());
preparedStatement.setInt(4, pc.getIntMod());
preparedStatement.setInt(5, pc.getSpiMod());
preparedStatement.setLong(6, 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) { public String SET_PROPERTY(final PlayerCharacter playerCharacter, String name, Object new_value) {
prepareCallable("CALL character_GETSETPROP(?,?,?,?)");
setLong(1, (long) c.getObjectUUID()); String result = "";
setString(2, name);
setString(3, String.valueOf(new_value)); try (Connection connection = DbManager.getConnection();
setString(4, String.valueOf(old_value)); PreparedStatement preparedStatement = connection.prepareStatement("CALL character_SETPROP(?,?,?)")) {
return getResult();
preparedStatement.setLong(1, playerCharacter.getObjectUUID());
preparedStatement.setString(2, name);
preparedStatement.setString(3, String.valueOf(new_value));
ResultSet rs = preparedStatement.executeQuery();
if (rs.next())
result = rs.getString("result");
} catch (SQLException e) {
Logger.error(e);
}
return result;
} }
public boolean SET_PROMOTION_CLASS(PlayerCharacter player, int promotionClassID) { public boolean SET_PROMOTION_CLASS(PlayerCharacter player, int promotionClassID) {
prepareCallable("UPDATE `obj_character` SET `char_promotionClassID`=? WHERE `UID`=?;");
setInt(1,promotionClassID); try (Connection connection = DbManager.getConnection();
setInt(2, player.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `char_promotionClassID`=? WHERE `UID`=?;")) {
return (executeUpdate() != 0);
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) { public boolean SET_INNERCOUNCIL(PlayerCharacter player, boolean isInnerCouncil) {
prepareCallable("UPDATE `obj_character` SET `guild_isInnerCouncil`=? WHERE `UID`=?;");
setBoolean(1,isInnerCouncil); try (Connection connection = DbManager.getConnection();
setInt(2, player.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_isInnerCouncil`=? WHERE `UID`=?;")) {
return (executeUpdate() != 0);
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) { public boolean SET_FULL_MEMBER(PlayerCharacter player, boolean isFullMember) {
prepareCallable("UPDATE `obj_character` SET `guild_isFullMember`=? WHERE `UID`=?;");
setBoolean(1,isFullMember); try (Connection connection = DbManager.getConnection();
setInt(2, player.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_isFullMember`=? WHERE `UID`=?;")) {
return (executeUpdate() != 0);
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) { public boolean SET_TAX_COLLECTOR(PlayerCharacter player, boolean isTaxCollector) {
prepareCallable("UPDATE `obj_character` SET `guild_isTaxCollector`=? WHERE `UID`=?;");
setBoolean(1,isTaxCollector); try (Connection connection = DbManager.getConnection();
setInt(2, player.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_isTaxCollector`=? WHERE `UID`=?;")) {
return (executeUpdate() != 0);
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) { public boolean SET_RECRUITER(PlayerCharacter player, boolean isRecruiter) {
prepareCallable("UPDATE `obj_character` SET `guild_isRecruiter`=? WHERE `UID`=?;");
setBoolean(1,isRecruiter); try (Connection connection = DbManager.getConnection();
setInt(2, player.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_isRecruiter`=? WHERE `UID`=?;")) {
return (executeUpdate() != 0);
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) { public boolean SET_GUILD_TITLE(PlayerCharacter player, int title) {
prepareCallable("UPDATE `obj_character` SET `guild_title`=? WHERE `UID`=?;");
setInt(1,title); try (Connection connection = DbManager.getConnection();
setInt(2, player.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_character` SET `guild_title`=? WHERE `UID`=?;")) {
return (executeUpdate() != 0);
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) {
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);
public boolean ADD_FRIEND(int source, long friend){ } catch (SQLException e) {
prepareCallable("INSERT INTO `dyn_character_friends` (`playerUID`, `friendUID`) VALUES (?, ?)"); Logger.error(e);
setLong(1, (long) source); }
setLong(2, (long)friend); return false;
return (executeUpdate() != 0);
} }
public boolean REMOVE_FRIEND(int source, int friend){ public boolean REMOVE_FRIEND(int source, int friend) {
prepareCallable("DELETE FROM `dyn_character_friends` WHERE (`playerUID`=?) AND (`friendUID`=?)");
setLong(1, (long) source); try (Connection connection = DbManager.getConnection();
setLong(2, (long)friend); PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_character_friends` WHERE (`playerUID`=?) AND (`friendUID`=?)")) {
return (executeUpdate() != 0);
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() { public void LOAD_PLAYER_FRIENDS() {
PlayerFriends playerFriend; PlayerFriends playerFriend;
try (Connection connection = DbManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM dyn_character_friends")) {
prepareCallable("SELECT * FROM dyn_character_friends"); ResultSet rs = preparedStatement.executeQuery();
try { while (rs.next())
ResultSet rs = executeQuery();
while (rs.next()) {
playerFriend = new PlayerFriends(rs); playerFriend = new PlayerFriends(rs);
} catch (SQLException e) {
Logger.error(e);
}
} }
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) { } catch (SQLException e) {
Logger.error("LoadMeshBounds: " + e.getErrorCode() + ' ' + e.getMessage(), e); Logger.error(e);
} finally {
closeCallable();
} }
return false;
} }
public boolean ADD_HERALDY(int source, AbstractWorldObject character){ public boolean REMOVE_HERALDY(int source, int characterUID) {
prepareCallable("INSERT INTO `dyn_character_heraldy` (`playerUID`, `characterUID`,`characterType`) VALUES (?, ?,?)");
setLong(1, (long) source); try (Connection connection = DbManager.getConnection();
setLong(2, (long)character.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_character_heraldy` WHERE (`playerUID`=?) AND (`characterUID`=?)")) {
setInt(3, character.getObjectType().ordinal());
return (executeUpdate() != 0);
}
public boolean REMOVE_HERALDY(int source, int characterUID){ preparedStatement.setLong(1, source);
prepareCallable("DELETE FROM `dyn_character_heraldy` WHERE (`playerUID`=?) AND (`characterUID`=?)"); preparedStatement.setLong(2, characterUID);
setLong(1, (long) source);
setLong(2, (long)characterUID); return (preparedStatement.executeUpdate() > 0);
return (executeUpdate() != 0);
} catch (SQLException e) {
Logger.error(e);
}
return false;
} }
public void LOAD_HERALDY() { public void LOAD_HERALDY() {
Heraldry heraldy; Heraldry heraldy;
try (Connection connection = DbManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM dyn_character_heraldy")) {
prepareCallable("SELECT * FROM dyn_character_heraldy"); ResultSet rs = preparedStatement.executeQuery();
try {
ResultSet rs = executeQuery();
while (rs.next()) { while (rs.next())
heraldy = new Heraldry(rs); heraldy = new Heraldry(rs);
}
} catch (SQLException e) { } catch (SQLException e) {
Logger.error("LoadHeraldy: " + e.getErrorCode() + ' ' + e.getMessage(), e); Logger.error(e);
} finally {
closeCallable();
} }
} }

67
src/engine/db/handlers/dbPromotionClassHandler.java

@ -9,9 +9,12 @@
package engine.db.handlers; package engine.db.handlers;
import engine.gameManager.DbManager;
import engine.objects.PromotionClass; import engine.objects.PromotionClass;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
@ -24,31 +27,59 @@ public class dbPromotionClassHandler extends dbHandlerBase {
} }
public ArrayList<Integer> GET_ALLOWED_RUNES(final PromotionClass pc) { public ArrayList<Integer> GET_ALLOWED_RUNES(final PromotionClass pc) {
ArrayList<Integer> runes = new ArrayList<>();
prepareCallable("SELECT * FROM `static_rune_promotionrunereq` WHERE `promoID`=?"); ArrayList<Integer> runeList = new ArrayList<>();
setInt(1, pc.getObjectUUID());
try { try (Connection connection = DbManager.getConnection();
ResultSet rs = executeQuery(); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_promotionrunereq` WHERE `promoID`=?")) {
while (rs.next()) {
runes.add(rs.getInt("runereqID")); preparedStatement.setInt(1, pc.getObjectUUID());
}
ResultSet rs = preparedStatement.executeQuery();
while (rs.next())
runeList.add(rs.getInt("runereqID"));
} catch (SQLException e) { } catch (SQLException e) {
Logger.error("Failed to retrieve Allowed Runes for PromotionClass " + pc.getObjectUUID() + ". Error number: " + e.getErrorCode(), e); Logger.error(e);
return null;
} finally {
closeCallable();
} }
return runes; return runeList;
} }
public PromotionClass GET_PROMOTION_CLASS(final int objectUUID) { public PromotionClass GET_PROMOTION_CLASS(final int objectUUID) {
prepareCallable("SELECT * FROM `static_rune_promotion` WHERE `ID` = ?");
setInt(1, objectUUID); PromotionClass promotionClass = null;
return (PromotionClass) getObjectSingle(objectUUID);
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<PromotionClass> GET_ALL_PROMOTIONS() { public ArrayList<PromotionClass> GET_ALL_PROMOTIONS() {
prepareCallable("SELECT * FROM `static_rune_promotion`");
return getObjectList(); ArrayList<PromotionClass> 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;
} }
} }

124
src/engine/db/handlers/dbRaceHandler.java

@ -9,9 +9,12 @@
package engine.db.handlers; package engine.db.handlers;
import engine.gameManager.DbManager;
import engine.objects.Race; import engine.objects.Race;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.HashSet; import java.util.HashSet;
@ -23,33 +26,110 @@ public class dbRaceHandler extends dbHandlerBase {
} }
public HashSet<Integer> BEARD_COLORS_FOR_RACE(final int id) { public HashSet<Integer> BEARD_COLORS_FOR_RACE(final int id) {
prepareCallable("SELECT `color` FROM `static_rune_racebeardcolor` WHERE `RaceID` = ?");
setInt(1, id); HashSet<Integer> integerSet = new HashSet<>();
return getIntegerList(1);
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<Integer> BEARD_STYLES_FOR_RACE(final int id) { public HashSet<Integer> BEARD_STYLES_FOR_RACE(final int id) {
prepareCallable("SELECT `beardStyle` FROM `static_rune_racebeardstyle` WHERE `RaceID` = ?");
setInt(1, id); HashSet<Integer> integerSet = new HashSet<>();
return getIntegerList(1);
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<Integer> HAIR_COLORS_FOR_RACE(final int id) { public HashSet<Integer> HAIR_COLORS_FOR_RACE(final int id) {
prepareCallable("SELECT `color` FROM `static_rune_racehaircolor` WHERE `RaceID` = ?");
setInt(1, id); HashSet<Integer> integerSet = new HashSet<>();
return getIntegerList(1);
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<Integer> HAIR_STYLES_FOR_RACE(final int id) { public HashSet<Integer> HAIR_STYLES_FOR_RACE(final int id) {
prepareCallable("SELECT `hairStyle` FROM `static_rune_racehairstyle` WHERE `RaceID` = ?");
setInt(1, id); HashSet<Integer> integerSet = new HashSet<>();
return getIntegerList(1);
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<Integer> SKIN_COLOR_FOR_RACE(final int id) { public HashSet<Integer> SKIN_COLOR_FOR_RACE(final int id) {
prepareCallable("SELECT `color` FROM `static_rune_raceskincolor` WHERE `RaceID` = ?");
setInt(1, id); HashSet<Integer> integerSet = new HashSet<>();
return getIntegerList(1);
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<Integer, Race> LOAD_ALL_RACES() { public ConcurrentHashMap<Integer, Race> LOAD_ALL_RACES() {
@ -60,10 +140,10 @@ public class dbRaceHandler extends dbHandlerBase {
races = new ConcurrentHashMap<>(); races = new ConcurrentHashMap<>();
int recordsRead = 0; 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 = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
while (rs.next()) { while (rs.next()) {
@ -73,13 +153,11 @@ public class dbRaceHandler extends dbHandlerBase {
races.put(thisRace.getRaceRuneID(), thisRace); races.put(thisRace.getRaceRuneID(), thisRace);
} }
Logger.info("read: " + recordsRead + " cached: " + races.size());
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.toString()); Logger.error(e);
} finally {
closeCallable();
} }
Logger.info("read: " + recordsRead + " cached: " + races.size());
return races; return races;
} }
} }

43
src/engine/db/handlers/dbRealmHandler.java

@ -9,14 +9,12 @@
package engine.db.handlers; package engine.db.handlers;
import engine.gameManager.DbManager;
import engine.objects.Realm; import engine.objects.Realm;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.net.UnknownHostException; import java.sql.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
public class dbRealmHandler extends dbHandlerBase { public class dbRealmHandler extends dbHandlerBase {
@ -32,42 +30,43 @@ public class dbRealmHandler extends dbHandlerBase {
realmList = new ConcurrentHashMap<>(); realmList = new ConcurrentHashMap<>();
int recordsRead = 0; int recordsRead = 0;
prepareCallable("SELECT * FROM obj_realm"); try (Connection connection = DbManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM obj_realm")) {
try { ResultSet rs = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
while (rs.next()) { while (rs.next()) {
recordsRead++; recordsRead++;
thisRealm = new Realm(rs); thisRealm = new Realm(rs);
realmList.put(thisRealm.getRealmID(), thisRealm); realmList.put(thisRealm.getRealmID(), thisRealm);
} }
Logger.info( "read: " + recordsRead + " cached: " + realmList.size());
} catch (SQLException e) { } catch (SQLException e) {
Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); Logger.error(e);
} catch (UnknownHostException ex) {
java.util.logging.Logger.getLogger(dbRealmHandler.class.getName()).log(Level.SEVERE, null, ex);
} finally {
closeCallable();
} }
Logger.info("read: " + recordsRead + " cached: " + realmList.size());
return realmList; return realmList;
} }
public void REALM_UPDATE(Realm realm) { 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) if (realm.ruledSince != null)
setLocalDateTime(4, realm.ruledSince); preparedStatement.setTimestamp(4, Timestamp.valueOf(realm.ruledSince));
else else
setNULL(4, java.sql.Types.DATE); preparedStatement.setNull(4, java.sql.Types.DATE);
executeUpdate(); preparedStatement.execute();
} catch (SQLException e) {
Logger.error(e);
}
} }
} }

30
src/engine/db/handlers/dbResistHandler.java

@ -9,8 +9,12 @@
package engine.db.handlers; package engine.db.handlers;
import engine.gameManager.DbManager;
import engine.objects.Resists; import engine.objects.Resists;
import org.pmw.tinylog.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
@ -21,17 +25,23 @@ public class dbResistHandler extends dbHandlerBase {
} }
public Resists GET_RESISTS_FOR_MOB(int resistID) { public Resists GET_RESISTS_FOR_MOB(int resistID) {
prepareCallable("SELECT * FROM `static_npc_mob_resists` WHERE `ID` = ?;");
setInt(1, resistID); Resists resists = null;
try {
ResultSet rs = executeQuery(); try (Connection connection = DbManager.getConnection();
if (rs.next()) { PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_npc_mob_resists` WHERE `ID` = ?;")) {
return new Resists(rs);
} preparedStatement.setInt(1, resistID);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next())
resists = new Resists(rs);
} catch (SQLException e) { } catch (SQLException e) {
} finally { Logger.error(e);
closeCallable();
} }
return null;
return resists;
} }
} }

26
src/engine/db/handlers/dbRuneBaseAttributeHandler.java

@ -9,8 +9,14 @@
package engine.db.handlers; package engine.db.handlers;
import engine.gameManager.DbManager;
import engine.objects.RuneBaseAttribute; 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; import java.util.ArrayList;
public class dbRuneBaseAttributeHandler extends dbHandlerBase { public class dbRuneBaseAttributeHandler extends dbHandlerBase {
@ -20,15 +26,21 @@ public class dbRuneBaseAttributeHandler extends dbHandlerBase {
this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName());
} }
public ArrayList<RuneBaseAttribute> GET_ATTRIBUTES_FOR_RUNEBASE(int id) { public ArrayList<RuneBaseAttribute> GET_ATTRIBUTES_FOR_RUNEBASE() {
prepareCallable("SELECT * FROM `static_rune_runebaseattribute` WHERE `RuneBaseID`=?");
setInt(1, id); ArrayList<RuneBaseAttribute> runeBaseAttributesList = new ArrayList<>();
return getObjectList();
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);
} }
public ArrayList<RuneBaseAttribute> GET_ATTRIBUTES_FOR_RUNEBASE() { return runeBaseAttributesList;
prepareCallable("SELECT * FROM `static_rune_runebaseattribute`");
return getObjectList();
} }

66
src/engine/db/handlers/dbRuneBaseEffectHandler.java

@ -13,7 +13,12 @@ import engine.Enum.GameObjectType;
import engine.gameManager.DbManager; import engine.gameManager.DbManager;
import engine.objects.AbstractGameObject; import engine.objects.AbstractGameObject;
import engine.objects.RuneBaseEffect; 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.ArrayList;
import java.util.HashMap; import java.util.HashMap;
@ -25,45 +30,58 @@ public class dbRuneBaseEffectHandler extends dbHandlerBase {
} }
public ArrayList<RuneBaseEffect> GET_EFFECTS_FOR_RUNEBASE(int id) { public ArrayList<RuneBaseEffect> GET_EFFECTS_FOR_RUNEBASE(int id) {
prepareCallable("SELECT * FROM `static_rune_baseeffect` WHERE `runeID`=?");
setInt(1, id); ArrayList<RuneBaseEffect> runeBaseEffectsList = new ArrayList<>();
return getObjectList();
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);
} catch (SQLException e) {
Logger.error(e);
}
return runeBaseEffectsList;
} }
public RuneBaseEffect GET_RUNEBASE_EFFECT(int id) { public ArrayList<RuneBaseEffect> GET_ALL_RUNEBASE_EFFECTS() {
if (id == 0) ArrayList<RuneBaseEffect> runeBaseEffectsList = new ArrayList<>();
return null;
RuneBaseEffect runeBaseEffect = (RuneBaseEffect) DbManager.getFromCache(GameObjectType.RuneBaseEffect, id); try (Connection connection = DbManager.getConnection();
if (runeBaseEffect != null) PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_rune_baseeffect`;")) {
return runeBaseEffect;
prepareCallable("SELECT * FROM `static_rune_baseeffect` WHERE `ID` = ?"); ResultSet rs = preparedStatement.executeQuery();
setInt(1, id); runeBaseEffectsList = getObjectsFromRs(rs, 250);
return (RuneBaseEffect) getObjectSingle(id);
} catch (SQLException e) {
Logger.error(e);
} }
public ArrayList<RuneBaseEffect> GET_ALL_RUNEBASE_EFFECTS(){ return runeBaseEffectsList;
prepareCallable("SELECT * FROM `static_rune_baseeffect`;");
return getObjectList();
} }
//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<Integer, ArrayList<RuneBaseEffect>> LOAD_BASEEFFECTS_FOR_RUNEBASE() { public HashMap<Integer, ArrayList<RuneBaseEffect>> LOAD_BASEEFFECTS_FOR_RUNEBASE() {
HashMap<Integer, ArrayList<RuneBaseEffect>> runeBaseEffectSet; HashMap<Integer, ArrayList<RuneBaseEffect>> runeBaseEffectSet;
runeBaseEffectSet = new HashMap<>(); 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) {
int runeBaseID = ((RuneBaseEffect)runeBaseEffect).getRuneBaseID();
if (runeBaseEffectSet.get(runeBaseID) == null){
ArrayList<RuneBaseEffect> runeBaseEffectList = new ArrayList<>(); ArrayList<RuneBaseEffect> runeBaseEffectList = new ArrayList<>();
runeBaseEffectList.add((RuneBaseEffect)runeBaseEffect); runeBaseEffectList.add((RuneBaseEffect) runeBaseEffect);
runeBaseEffectSet.put(runeBaseID, runeBaseEffectList); runeBaseEffectSet.put(runeBaseID, runeBaseEffectList);
} } else {
else{ ArrayList<RuneBaseEffect> runeBaseEffectList = runeBaseEffectSet.get(runeBaseID);
ArrayList<RuneBaseEffect>runeBaseEffectList = runeBaseEffectSet.get(runeBaseID); runeBaseEffectList.add((RuneBaseEffect) runeBaseEffect);
runeBaseEffectList.add((RuneBaseEffect)runeBaseEffect);
runeBaseEffectSet.put(runeBaseID, runeBaseEffectList); runeBaseEffectSet.put(runeBaseID, runeBaseEffectList);
} }
} }

116
src/engine/db/handlers/dbRuneBaseHandler.java

@ -9,14 +9,16 @@
package engine.db.handlers; package engine.db.handlers;
import engine.gameManager.DbManager;
import engine.objects.RuneBase; import engine.objects.RuneBase;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
public class dbRuneBaseHandler extends dbHandlerBase { public class dbRuneBaseHandler extends dbHandlerBase {
@ -26,11 +28,13 @@ public class dbRuneBaseHandler extends dbHandlerBase {
} }
public void GET_RUNE_REQS(final RuneBase rb) { 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()) { while (rs.next()) {
int type = rs.getInt("type"); int type = rs.getInt("type");
@ -56,36 +60,58 @@ public class dbRuneBaseHandler extends dbHandlerBase {
break; break;
} }
} }
rs.close();
} catch (SQLException e) { } catch (SQLException e) {
Logger.error("SQL Error number: " + e.getErrorCode()); Logger.error(e);
} finally {
closeCallable();
} }
} }
public RuneBase GET_RUNEBASE(final int id) { public RuneBase GET_RUNEBASE(final int id) {
prepareCallable("SELECT * FROM `static_rune_runebase` WHERE `ID` = ?");
setInt(1, id); RuneBase runeBase = null;
return (RuneBase) getObjectSingle(id);
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<RuneBase> LOAD_ALL_RUNEBASES() { public ArrayList<RuneBase> LOAD_ALL_RUNEBASES() {
prepareCallable("SELECT * FROM `static_rune_runebase`;");
return getObjectList(); ArrayList<RuneBase> 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<Integer, ArrayList<Integer>> LOAD_ALLOWED_STARTING_RUNES_FOR_BASECLASS() { public HashMap<Integer, ArrayList<Integer>> LOAD_ALLOWED_STARTING_RUNES_FOR_BASECLASS() {
HashMap<Integer, ArrayList<Integer>> runeSets; HashMap<Integer, ArrayList<Integer>> runeSets = new HashMap<>();
runeSets = new HashMap<>();
int recordsRead = 0; 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 = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
while (rs.next()) { while (rs.next()) {
@ -94,25 +120,23 @@ public class dbRuneBaseHandler extends dbHandlerBase {
int baseClassID = rs.getInt("BaseClassesID"); int baseClassID = rs.getInt("BaseClassesID");
int runeBaseID = rs.getInt("RuneBaseID"); int runeBaseID = rs.getInt("RuneBaseID");
if (runeSets.get(baseClassID) == null){ if (runeSets.get(baseClassID) == null) {
ArrayList<Integer> runeList = new ArrayList<>(); ArrayList<Integer> runeList = new ArrayList<>();
runeList.add(runeBaseID); runeList.add(runeBaseID);
runeSets.put(baseClassID, runeList); runeSets.put(baseClassID, runeList);
} } else {
else{ ArrayList<Integer> runeList = runeSets.get(baseClassID);
ArrayList<Integer>runeList = runeSets.get(baseClassID);
runeList.add(runeBaseID); runeList.add(runeBaseID);
runeSets.put(baseClassID, runeList); runeSets.put(baseClassID, runeList);
} }
} }
Logger.info("read: " + recordsRead + " cached: " + runeSets.size());
} catch (SQLException e) { } catch (SQLException e) {
Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); Logger.error(e);
} finally {
closeCallable();
} }
Logger.info("read: " + recordsRead + " cached: " + runeSets.size());
return runeSets; return runeSets;
} }
@ -123,10 +147,10 @@ public class dbRuneBaseHandler extends dbHandlerBase {
runeSets = new HashMap<>(); runeSets = new HashMap<>();
int recordsRead = 0; 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 = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
while (rs.next()) { while (rs.next()) {
@ -135,39 +159,21 @@ public class dbRuneBaseHandler extends dbHandlerBase {
int raceID = rs.getInt("RaceID"); int raceID = rs.getInt("RaceID");
int runeBaseID = rs.getInt("RuneBaseID"); int runeBaseID = rs.getInt("RuneBaseID");
if (runeSets.get(raceID) == null){ if (runeSets.get(raceID) == null) {
ArrayList<Integer> runeList = new ArrayList<>(); ArrayList<Integer> runeList = new ArrayList<>();
runeList.add(runeBaseID); runeList.add(runeBaseID);
runeSets.put(raceID, runeList); runeSets.put(raceID, runeList);
} } else {
else{ ArrayList<Integer> runeList = runeSets.get(raceID);
ArrayList<Integer>runeList = runeSets.get(raceID);
runeList.add(runeBaseID); runeList.add(runeBaseID);
runeSets.put(raceID, runeList); runeSets.put(raceID, runeList);
} }
} }
Logger.info( "read: " + recordsRead + " cached: " + runeSets.size());
} catch (SQLException e) { } catch (SQLException e) {
Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); Logger.error(e);
} finally {
closeCallable();
}
return runeSets;
} }
public ArrayList<RuneBase> GET_RUNEBASE_FOR_BASECLASS(final int id) { Logger.info("read: " + recordsRead + " cached: " + runeSets.size());
prepareCallable("SELECT rb.* FROM static_rune_baseclassrune bcr, static_rune_runebase rb WHERE bcr.RuneBaseID = rb.ID " return runeSets;
+ "&& ( bcr.BaseClassesID = 111111 || bcr.BaseClassesID = ? )");
setInt(1, id);
return getObjectList();
}
public HashSet<RuneBase> 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());
} }
} }

30
src/engine/db/handlers/dbRunegateHandler.java

@ -13,7 +13,10 @@ import engine.Enum;
import engine.gameManager.DbManager; import engine.gameManager.DbManager;
import engine.objects.Building; import engine.objects.Building;
import engine.objects.Portal; import engine.objects.Portal;
import org.pmw.tinylog.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
@ -28,17 +31,18 @@ public class dbRunegateHandler extends dbHandlerBase {
ArrayList<Integer> gateList = new ArrayList<>(); ArrayList<Integer> 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 = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
while (rs.next()) { while (rs.next())
gateList.add(rs.getInt("sourceBuilding")); gateList.add(rs.getInt("sourceBuilding"));
}
} catch (SQLException e) { } catch (SQLException e) {
} finally { Logger.error(e);
closeCallable();
} }
return gateList; return gateList;
} }
@ -47,11 +51,12 @@ public class dbRunegateHandler extends dbHandlerBase {
ArrayList<Portal> portalList = new ArrayList<>(); ArrayList<Portal> portalList = new ArrayList<>();
Building sourceBuilding = (Building) DbManager.getObject(Enum.GameObjectType.Building, gateUID); Building sourceBuilding = (Building) DbManager.getObject(Enum.GameObjectType.Building, gateUID);
prepareCallable("SELECT * FROM `static_runegate_portals` WHERE `sourceBuilding` = ?;"); try (Connection connection = DbManager.getConnection();
setInt(1, gateUID); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_runegate_portals` WHERE `sourceBuilding` = ?;")) {
preparedStatement.setInt(1, gateUID);
try { ResultSet rs = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
while (rs.next()) { while (rs.next()) {
int targetBuildingID = rs.getInt("targetBuilding"); int targetBuildingID = rs.getInt("targetBuilding");
@ -62,8 +67,7 @@ public class dbRunegateHandler extends dbHandlerBase {
} }
} catch (SQLException e) { } catch (SQLException e) {
} finally { Logger.error(e);
closeCallable();
} }
return portalList; return portalList;
} }

168
src/engine/db/handlers/dbShrineHandler.java

@ -18,7 +18,8 @@ import engine.objects.Shrine;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.net.UnknownHostException; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
@ -30,118 +31,113 @@ public class dbShrineHandler extends dbHandlerBase {
this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName());
} }
public ArrayList<AbstractGameObject> CREATE_SHRINE( int parentZoneID, int OwnerUUID, String name, int meshUUID, public static void addObject(ArrayList<AbstractGameObject> 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<AbstractGameObject> CREATE_SHRINE(int parentZoneID, int OwnerUUID, String name, int meshUUID,
Vector3fImmutable location, float meshScale, int currentHP, Vector3fImmutable location, float meshScale, int currentHP,
ProtectionState protectionState, int currentGold, int rank, ProtectionState protectionState, int currentGold, int rank,
DateTime upgradeDate, int blueprintUUID, float w, float rotY, String shrineType) { DateTime upgradeDate, int blueprintUUID, float w, float rotY, String shrineType) {
prepareCallable("CALL `shrine_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,? ,? ,?, ?,?);"); ArrayList<AbstractGameObject> shrineList = new ArrayList<>();
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);
}
setInt(14, blueprintUUID); try (Connection connection = DbManager.getConnection();
setFloat(15, w); PreparedStatement preparedStatement = connection.prepareStatement("CALL `shrine_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,? ,? ,?, ?,?);")) {
setFloat(16, rotY);
setString(17, shrineType); preparedStatement.setInt(1, parentZoneID);
preparedStatement.setInt(2, OwnerUUID);
ArrayList<AbstractGameObject> list = new ArrayList<>(); preparedStatement.setString(3, name);
//System.out.println(this.cs.get().toString()); preparedStatement.setInt(4, meshUUID);
try { preparedStatement.setFloat(5, location.x);
boolean work = execute(); preparedStatement.setFloat(6, location.y);
if (work) { preparedStatement.setFloat(7, location.z);
ResultSet rs = this.cs.get().getResultSet(); preparedStatement.setFloat(8, meshScale);
while (rs.next()) { preparedStatement.setInt(9, currentHP);
addObject(list, rs); preparedStatement.setString(10, protectionState.name());
} preparedStatement.setInt(11, currentGold);
rs.close(); preparedStatement.setInt(12, rank);
} else {
Logger.info("Shrine Creation Failed: " + this.cs.get().toString()); if (upgradeDate != null)
return list; //city creation failure preparedStatement.setTimestamp(13, new java.sql.Timestamp(upgradeDate.getMillis()));
} else
while (this.cs.get().getMoreResults()) { preparedStatement.setNull(13, java.sql.Types.DATE);
ResultSet rs = this.cs.get().getResultSet();
while (rs.next()) { preparedStatement.setInt(14, blueprintUUID);
addObject(list, rs); preparedStatement.setFloat(15, w);
} preparedStatement.setFloat(16, rotY);
rs.close(); 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) { } catch (SQLException e) {
Logger.info("Shrine Creation Failed, SQLException: " + this.cs.get().toString() + e.toString()); Logger.error(e);
return list; //city creation failure
} catch (UnknownHostException e) {
Logger.info("Shrine Creation Failed, UnknownHostException: " + this.cs.get().toString());
return list; //city creation failure
} finally {
closeCallable();
} }
return list;
return shrineList;
} }
public boolean updateFavors(Shrine shrine, int amount, int oldAmount) { public boolean updateFavors(Shrine shrine, int amount, int oldAmount) {
prepareCallable("UPDATE `obj_shrine` SET `shrine_favors`=? WHERE `UID` = ? AND `shrine_favors` = ?"); try (Connection connection = DbManager.getConnection();
setInt(1, amount); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_shrine` SET `shrine_favors`=? WHERE `UID` = ? AND `shrine_favors` = ?")) {
setLong(2, (long) shrine.getObjectUUID());
setInt(3, oldAmount);
return (executeUpdate() != 0);
}
public static void addObject(ArrayList<AbstractGameObject> list, ResultSet rs) throws SQLException, UnknownHostException { preparedStatement.setInt(1, amount);
String type = rs.getString("type"); preparedStatement.setLong(2, shrine.getObjectUUID());
switch (type) { preparedStatement.setInt(3, oldAmount);
case "building":
Building building = new Building(rs); return (preparedStatement.executeUpdate() > 0);
DbManager.addToCache(building);
list.add(building); } catch (SQLException e) {
break; Logger.error(e);
case "shrine": return false;
Shrine shrine = new Shrine(rs);
DbManager.addToCache(shrine);
list.add(shrine);
break;
} }
} }
public void LOAD_ALL_SHRINES() { 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 = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
//shrines cached in rs for easy cache on creation.
while (rs.next()) { while (rs.next()) {
thisShrine = new Shrine(rs); shrine = new Shrine(rs);
thisShrine.getShrineType().addShrineToServerList(thisShrine); shrine.getShrineType().addShrineToServerList(shrine);
} }
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.getErrorCode() + ' ' + e.getMessage(), e); Logger.error(e);
} finally {
closeCallable();
} }
} }
} }

125
src/engine/db/handlers/dbSkillBaseHandler.java

@ -12,11 +12,12 @@ package engine.db.handlers;
import engine.Enum; import engine.Enum;
import engine.Enum.GameObjectType; import engine.Enum.GameObjectType;
import engine.gameManager.DbManager; import engine.gameManager.DbManager;
import engine.objects.AbstractGameObject;
import engine.objects.MaxSkills; import engine.objects.MaxSkills;
import engine.objects.SkillsBase; import engine.objects.SkillsBase;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
@ -32,91 +33,105 @@ public class dbSkillBaseHandler extends dbHandlerBase {
public SkillsBase GET_BASE(final int objectUUID) { public SkillsBase GET_BASE(final int objectUUID) {
SkillsBase skillsBase = (SkillsBase) DbManager.getFromCache(GameObjectType.SkillsBase, objectUUID); SkillsBase skillsBase = (SkillsBase) DbManager.getFromCache(GameObjectType.SkillsBase, objectUUID);
if (skillsBase != null) if (skillsBase != null)
return skillsBase; return skillsBase;
prepareCallable("SELECT * FROM static_skill_skillsbase WHERE ID = ?");
setInt(1, objectUUID); try (Connection connection = DbManager.getConnection();
SkillsBase sb; PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_skill_skillsbase WHERE ID = ?")) {
sb = (SkillsBase) getObjectSingle(objectUUID);
SkillsBase.putInCache(sb); preparedStatement.setInt(1, objectUUID);
return sb; ResultSet rs = preparedStatement.executeQuery();
skillsBase = (SkillsBase) getObjectFromRs(rs);
} catch (SQLException e) {
Logger.error(e);
} }
public SkillsBase GET_BASE_BY_NAME(String name) { SkillsBase.putInCache(skillsBase);
SkillsBase sb = SkillsBase.getFromCache(name); return skillsBase;
if (sb != null) {
return sb;
} }
prepareCallable("SELECT * FROM static_skill_skillsbase WHERE name = ?");
setString(1, name); public SkillsBase GET_BASE_BY_NAME(String name) {
ArrayList<AbstractGameObject> result = getObjectList();
if (result.size() > 0) { SkillsBase skillsBase = SkillsBase.getFromCache(name);
sb = (SkillsBase) result.get(0);
SkillsBase.putInCache(sb); if (skillsBase != null)
return sb; return skillsBase;
} else {
return null; 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) { 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 = ?"); SkillsBase skillsBase = SkillsBase.getFromCache(token);
setInt(1, token);
ArrayList<AbstractGameObject> result = getObjectList(); if (skillsBase != null)
if (result.size() > 0) { return skillsBase;
sb = (SkillsBase) result.get(0);
SkillsBase.putInCache(sb); try (Connection connection = DbManager.getConnection();
return sb; PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM static_skill_skillsbase WHERE token = ?")) {
} else {
return null; 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() { 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 = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
//shrines cached in rs for easy cache on creation.
while (rs.next()) { while (rs.next()) {
MaxSkills maxSKills = new MaxSkills(rs); MaxSkills maxSKills = new MaxSkills(rs);
if (MaxSkills.MaxSkillsSet.get(maxSKills.getRuneID()) == null){
if (MaxSkills.MaxSkillsSet.get(maxSKills.getRuneID()) == null) {
ArrayList<MaxSkills> newMaxSkillsList = new ArrayList<>(); ArrayList<MaxSkills> newMaxSkillsList = new ArrayList<>();
newMaxSkillsList.add(maxSKills); newMaxSkillsList.add(maxSKills);
MaxSkills.MaxSkillsSet.put(maxSKills.getRuneID(), newMaxSkillsList); MaxSkills.MaxSkillsSet.put(maxSKills.getRuneID(), newMaxSkillsList);
}else } else
MaxSkills.MaxSkillsSet.get(maxSKills.getRuneID()).add(maxSKills); MaxSkills.MaxSkillsSet.get(maxSKills.getRuneID()).add(maxSKills);
} }
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.getErrorCode() + ' ' + e.getMessage(), e); Logger.error(e);
} finally {
closeCallable();
} }
} }
public void LOAD_ALL_RUNE_SKILLS() {
prepareCallable("SELECT * FROM `static_skill_skillsgranted`"); public void LOAD_ALL_RUNE_SKILLS() {
try (Connection connection = DbManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_skill_skillsgranted`")) {
try { ResultSet rs = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
//shrines cached in rs for easy cache on creation.
while (rs.next()) { while (rs.next()) {
int runeID = rs.getInt("runeID"); int runeID = rs.getInt("runeID");
@ -129,15 +144,9 @@ public class dbSkillBaseHandler extends dbHandlerBase {
SkillsBase.runeSkillsCache.get(runeID).put(token, amount); SkillsBase.runeSkillsCache.get(runeID).put(token, amount);
} }
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.getErrorCode() + ' ' + e.getMessage(), e); Logger.error(e);
} finally {
closeCallable();
} }
} }
} }

79
src/engine/db/handlers/dbSkillReqHandler.java

@ -9,9 +9,17 @@
package engine.db.handlers; package engine.db.handlers;
import engine.gameManager.DbManager;
import engine.objects.SkillReq; 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.ArrayList;
import java.util.HashMap;
public class dbSkillReqHandler extends dbHandlerBase { public class dbSkillReqHandler extends dbHandlerBase {
@ -20,16 +28,71 @@ public class dbSkillReqHandler extends dbHandlerBase {
this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName());
} }
public static ArrayList<PowersBase> getAllPowersBase() {
ArrayList<PowersBase> 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);
powerBaseList.add(toAdd);
}
} catch (SQLException e) {
Logger.error(e);
}
return powerBaseList;
}
public static void getFailConditions(HashMap<String, PowersBase> powers) {
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()) {
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;
break;
case "TakeDamage":
pb.cancelOnTakeDamage = true;
break;
}
}
} catch (SQLException e) {
Logger.error(e);
}
}
public ArrayList<SkillReq> GET_REQS_FOR_RUNE(final int objectUUID) { public ArrayList<SkillReq> GET_REQS_FOR_RUNE(final int objectUUID) {
prepareCallable("SELECT * FROM `static_skill_skillreq` WHERE `runeID`=?");
setInt(1, objectUUID); ArrayList<SkillReq> skillReqsList = new ArrayList<>();
return getObjectList();
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);
} }
public SkillReq GET_REQS_BY_SKILLID(int skillID) { return skillReqsList;
prepareCallable("SELECT * FROM `static_skill_skillreq` WHERE `skillID` = ?");
setInt(1,skillID);
int objectUUID = (int) getUUID();
return (SkillReq) this.getObjectSingle(objectUUID);
} }
} }

31
src/engine/db/handlers/dbVendorDialogHandler.java

@ -12,6 +12,12 @@ package engine.db.handlers;
import engine.Enum; import engine.Enum;
import engine.gameManager.DbManager; import engine.gameManager.DbManager;
import engine.objects.VendorDialog; 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 { public class dbVendorDialogHandler extends dbHandlerBase {
@ -21,11 +27,24 @@ public class dbVendorDialogHandler extends dbHandlerBase {
} }
public VendorDialog GET_VENDORDIALOG(final int objectUUID) { public VendorDialog GET_VENDORDIALOG(final int objectUUID) {
VendorDialog vd = (VendorDialog) DbManager.getFromCache(Enum.GameObjectType.VendorDialog, objectUUID);
if (vd != null) VendorDialog vendorDialog = (VendorDialog) DbManager.getFromCache(Enum.GameObjectType.VendorDialog, objectUUID);
return vd;
prepareCallable("SELECT * FROM `static_npc_vendordialog` WHERE `ID`=?"); if (vendorDialog != null)
setInt(1, objectUUID); return vendorDialog;
return (VendorDialog) getObjectSingle(objectUUID);
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;
} }
} }

663
src/engine/db/handlers/dbWarehouseHandler.java

@ -19,7 +19,8 @@ import engine.server.MBServerStatics;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.net.UnknownHostException; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
@ -33,417 +34,523 @@ public class dbWarehouseHandler extends dbHandlerBase {
this.localClass = Warehouse.class; this.localClass = Warehouse.class;
this.localObjectType = engine.Enum.GameObjectType.valueOf(this.localClass.getSimpleName()); 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;
public static void addObject(ArrayList<AbstractGameObject> 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;
} }
return wh;
} }
public ArrayList<AbstractGameObject> CREATE_WAREHOUSE( int parentZoneID, int OwnerUUID, String name, int meshUUID, public ArrayList<AbstractGameObject> CREATE_WAREHOUSE(int parentZoneID, int OwnerUUID, String name, int meshUUID,
Vector3fImmutable location, float meshScale, int currentHP, Vector3fImmutable location, float meshScale, int currentHP,
ProtectionState protectionState, int currentGold, int rank, ProtectionState protectionState, int currentGold, int rank,
DateTime upgradeDate, int blueprintUUID, float w, float rotY) { DateTime upgradeDate, int blueprintUUID, float w, float rotY) {
prepareCallable("CALL `WAREHOUSE_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,? ,? ,?, ?);"); ArrayList<AbstractGameObject> warehouseList = new ArrayList<>();
setInt(1, parentZoneID); try (Connection connection = DbManager.getConnection();
setInt(2, OwnerUUID); PreparedStatement preparedStatement = connection.prepareStatement("CALL `WAREHOUSE_CREATE`(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,? ,? ,?, ?);")) {
setString(3, name);
setInt(4, meshUUID); preparedStatement.setInt(1, parentZoneID);
setFloat(5, location.x); preparedStatement.setInt(2, OwnerUUID);
setFloat(6, location.y); preparedStatement.setString(3, name);
setFloat(7, location.z); preparedStatement.setInt(4, meshUUID);
setFloat(8, meshScale); preparedStatement.setFloat(5, location.x);
setInt(9, currentHP); preparedStatement.setFloat(6, location.y);
setString(10, protectionState.name()); preparedStatement.setFloat(7, location.z);
setInt(11, currentGold); preparedStatement.setFloat(8, meshScale);
setInt(12, rank); preparedStatement.setInt(9, currentHP);
preparedStatement.setString(10, protectionState.name());
if (upgradeDate != null) { preparedStatement.setInt(11, currentGold);
setTimeStamp(13, upgradeDate.getMillis()); preparedStatement.setInt(12, rank);
} else {
setNULL(13, java.sql.Types.DATE); if (upgradeDate != null)
} preparedStatement.setTimestamp(13, new java.sql.Timestamp(upgradeDate.getMillis()));
else
setInt(14, blueprintUUID); preparedStatement.setNull(13, java.sql.Types.DATE);
setFloat(15, w);
setFloat(16, rotY); preparedStatement.setInt(14, blueprintUUID);
preparedStatement.setFloat(15, w);
ArrayList<AbstractGameObject> list = new ArrayList<>(); preparedStatement.setFloat(16, rotY);
//System.out.println(this.cs.get().toString());
try { preparedStatement.execute();
boolean work = execute(); ResultSet rs = preparedStatement.getResultSet();
if (work) {
ResultSet rs = this.cs.get().getResultSet(); while (rs.next())
while (rs.next()) { addObject(warehouseList, rs);
addObject(list, rs);
} while (preparedStatement.getMoreResults()) {
rs.close(); rs = preparedStatement.getResultSet();
} else {
Logger.info("Warehouse Creation Failed: " + this.cs.get().toString()); while (rs.next())
return list; //city creation failure addObject(warehouseList, rs);
}
while (this.cs.get().getMoreResults()) {
ResultSet rs = this.cs.get().getResultSet();
while (rs.next()) {
addObject(list, rs);
}
rs.close();
} }
} catch (SQLException e) { } catch (SQLException e) {
Logger.info("Warehouse Creation Failed, SQLException: " + this.cs.get().toString() + e.toString()); Logger.error(e);
return list; //city creation failure
} catch (UnknownHostException e) {
Logger.info("Warehouse Creation Failed, UnknownHostException: " + this.cs.get().toString());
return list; //city creation failure
} finally {
closeCallable();
} }
return list;
return warehouseList;
} }
//Don't call yet, not ready in DB. - public boolean updateLocks(final Warehouse wh, long locks) {
public boolean WAREHOUSE_ADD(Item item, Warehouse warehouse, ItemBase ib, int amount) {
if (item == null || warehouse == null || ib == null || !(dbWarehouseHandler.columns.containsKey(ib.getUUID()))) { try (Connection connection = DbManager.getConnection();
return false; PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_locks`=? WHERE `UID` = ?")) {
}
if ((item.getNumOfItems() - amount) < 0) { preparedStatement.setLong(1, locks);
return false; preparedStatement.setInt(2, wh.getUID());
return (preparedStatement.executeUpdate() > 0);
} catch (SQLException e) {
Logger.error(e);
} }
if (!warehouse.getResources().containsKey(ib)) {
return false; return false;
} }
prepareCallable("CALL `warehouse_ADD`(?,?,?,?,?,?,?);"); public boolean updateGold(final Warehouse wh, int amount) {
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")); try (Connection connection = DbManager.getConnection();
} PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_gold`=? WHERE `UID` = ?")) {
private Warehouse addWarehouse(Warehouse toAdd) { preparedStatement.setInt(1, amount);
prepareCallable("CALL `warehouse_CREATE`(?);"); preparedStatement.setInt(2, wh.getUID());
setInt(1, toAdd.getUID());
int objectUUID = (int) getUUID();
if (objectUUID > 0) {
return GET_WAREHOUSE(objectUUID);
}
return null;
}
public Warehouse GET_WAREHOUSE(int objectUUID) { return (preparedStatement.executeUpdate() > 0);
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) { } catch (SQLException e) {
prepareCallable("UPDATE `obj_warehouse` SET `warehouse_locks`=? WHERE `UID` = ?"); Logger.error(e);
setLong(1, locks);
setInt(2, wh.getUID());
return (executeUpdate() != 0);
} }
return false;
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);
} }
public boolean updateStone(final Warehouse wh, int amount) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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 ) { public boolean updateWormwood(final Warehouse wh, int amount) {
prepareCallable("UPDATE `obj_warehouse` SET `warehouse_wormwood`=? WHERE `UID` = ?");
setInt(1, amount); try (Connection connection = DbManager.getConnection();
setInt(2, wh.getUID()); 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);
return (executeUpdate() != 0); } catch (SQLException e) {
Logger.error(e);
}
return false;
} }
public boolean updateObsidian(final Warehouse wh, int amount) { 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) { 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) { public boolean updateMithril(final Warehouse wh, int amount) {
prepareCallable("UPDATE `obj_warehouse` SET `warehouse_mithril`=? WHERE `UID` = ?");
setInt(1, amount); try (Connection connection = DbManager.getConnection();
setInt(2, wh.getUID()); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE `obj_warehouse` SET `warehouse_mithril`=? WHERE `UID` = ?")) {
return (executeUpdate() != 0); preparedStatement.setInt(1, amount);
} preparedStatement.setInt(2, wh.getUID());
private static void createColumns() { return (preparedStatement.executeUpdate() > 0);
columns.put(1580000, "warehouse_stone");
columns.put(1580001, "warehouse_truesteel"); } catch (SQLException e) {
columns.put(1580002, "warehouse_iron"); Logger.error(e);
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 (?,?,?,?,?,?,?)");
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);
}
public static void addObject(ArrayList<AbstractGameObject> 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;
} }
return false;
}
public boolean CREATE_TRANSACTION(int warehouseBuildingID, GameObjectType targetType, int targetUUID, TransactionType transactionType, Resource resource, int amount, DateTime date) {
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<Transaction> GET_TRANSACTIONS_FOR_WAREHOUSE(final int warehouseUUID) { public ArrayList<Transaction> GET_TRANSACTIONS_FOR_WAREHOUSE(final int warehouseUUID) {
ArrayList<Transaction> transactionsList = new ArrayList<>(); ArrayList<Transaction> 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()) { while (rs.next()) {
Transaction transactions = new Transaction(rs); Transaction transactions = new Transaction(rs);
transactionsList.add(transactions); transactionsList.add(transactions);
} }
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.getErrorCode() + ' ' + e.getMessage(), e); Logger.error(e);
} finally {
closeCallable();
} }
return transactionsList; return transactionsList;
} }
public void LOAD_ALL_WAREHOUSES() { 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 = preparedStatement.executeQuery();
ResultSet rs = executeQuery();
while (rs.next()) { while (rs.next()) {
thisWarehouse = new Warehouse(rs); warehouse = new Warehouse(rs);
thisWarehouse.runAfterLoad(); warehouse.runAfterLoad();
thisWarehouse.loadAllTransactions(); warehouse.loadAllTransactions();
} }
} catch (SQLException e) { } catch (SQLException e) {
Logger.error(e.getErrorCode() + ' ' + e.getMessage(), e); Logger.error(e);
} finally {
closeCallable();
} }
} }
} }

91
src/engine/db/handlers/dbZoneHandler.java

@ -11,9 +11,15 @@ package engine.db.handlers;
import engine.Enum; import engine.Enum;
import engine.gameManager.DbManager; import engine.gameManager.DbManager;
import engine.gameManager.ZoneManager;
import engine.math.Vector2f;
import engine.objects.Zone; import engine.objects.Zone;
import org.pmw.tinylog.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
public class dbZoneHandler extends dbHandlerBase { public class dbZoneHandler extends dbHandlerBase {
@ -46,48 +52,79 @@ public class dbZoneHandler extends dbHandlerBase {
public Zone GET_BY_UID(long ID) { 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) if (zone != null)
return zone; 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); try (Connection connection = DbManager.getConnection();
return (Zone) getObjectSingle((int) ID); 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<Zone> GET_MAP_NODES(final int objectUUID) { public ArrayList<Zone> 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); ArrayList<Zone> zoneList = new ArrayList<>();
return getObjectList();
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, objectUUID);
ResultSet rs = preparedStatement.executeQuery();
zoneList = getObjectsFromRs(rs, 2000);
} catch (SQLException e) {
Logger.error(e);
} }
public ResultSet GET_ZONE_EXTENTS(final int loadNum) { return zoneList;
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) { public void LOAD_ZONE_EXTENTS() {
prepareCallable("CALL zone_SETPROP(?,?,?)");
setLong(1, (long) z.getObjectUUID()); try (Connection connection = DbManager.getConnection();
setString(2, name); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `static_zone_size`;")) {
setString(3, String.valueOf(new_value));
return getResult(); ResultSet rs = 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);
} }
public String SET_PROPERTY(final Zone z, String name, Object new_value, Object old_value) { } catch (SQLException e) {
prepareCallable("CALL zone_GETSETPROP(?,?,?,?)"); Logger.error(e);
setLong(1, (long) z.getObjectUUID()); }
setString(2, name);
setString(3, String.valueOf(new_value));
setString(4, String.valueOf(old_value));
return getResult();
} }
public boolean DELETE_ZONE(final Zone zone) { public boolean DELETE_ZONE(final Zone zone) {
prepareCallable("DELETE FROM `object` WHERE `UID` = ? AND `type` = 'zone'"); try (Connection connection = DbManager.getConnection();
setInt(1, zone.getObjectUUID()); PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `object` WHERE `UID` = ? AND `type` = 'zone'")) {
return (executeUpdate() != 0);
preparedStatement.setInt(1, zone.getObjectUUID());
return (preparedStatement.executeUpdate() > 0);
} catch (SQLException e) {
Logger.error(e);
}
return false;
} }
} }

105
src/engine/devcmd/cmds/GuildListCmd.java

@ -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;
}
}
}

101
src/engine/devcmd/cmds/RenameMobCmd.java

@ -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";
}
}

67
src/engine/gameManager/DbManager.java

@ -8,11 +8,12 @@
package engine.gameManager; package engine.gameManager;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import engine.Enum; import engine.Enum;
import engine.Enum.GameObjectType; import engine.Enum.GameObjectType;
import engine.db.handlers.*; import engine.db.handlers.*;
import engine.objects.*; import engine.objects.*;
import engine.pooling.ConnectionPool;
import engine.server.MBServerStatics; import engine.server.MBServerStatics;
import engine.util.Hasher; import engine.util.Hasher;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
@ -26,28 +27,14 @@ import java.util.concurrent.ConcurrentHashMap;
public enum DbManager { public enum DbManager {
DBMANAGER; DBMANAGER;
private static ConnectionPool connPool; private static HikariDataSource connectionPool = null;
public static Hasher hasher; public static Hasher hasher;
//Local Object Caching //Local Object Caching
private static final EnumMap<GameObjectType, ConcurrentHashMap<Integer, AbstractGameObject>> objectCache = new EnumMap<>(GameObjectType.class); private static final EnumMap<GameObjectType, ConcurrentHashMap<Integer, AbstractGameObject>> 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) { public static AbstractGameObject getObject(GameObjectType objectType, int objectUUID) {
AbstractGameObject outObject = null; AbstractGameObject outObject = null;
@ -87,9 +74,6 @@ public enum DbManager {
return outObject; return outObject;
} }
public static int getPoolSize(){
return connPool.getPoolSize();
}
public static boolean inCache(GameObjectType gameObjectType, int uuid) { public static boolean inCache(GameObjectType gameObjectType, int uuid) {
@ -227,7 +211,7 @@ public enum DbManager {
} }
public static PreparedStatement prepareStatement(String sql) throws SQLException { public static PreparedStatement prepareStatement(String sql) throws SQLException {
return getConn().prepareStatement(sql, 1); return getConnection().prepareStatement(sql, 1);
} }
// Omg refactor this out, somebody! // Omg refactor this out, somebody!
@ -259,15 +243,12 @@ public enum DbManager {
* @return the conn * @return the conn
*/ */
//XXX I think we have a severe resource leak here! No one is putting the connections back! //XXX I think we have a severe resource leak here! No one is putting the connections back!
public static Connection getConn() { public static Connection getConnection() {
Connection conn = DbManager.connPool.get();
try { try {
if (!conn.isClosed()) return DbManager.connectionPool.getConnection();
DbManager.connPool.put(conn);
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.toString()); throw new RuntimeException(e);
} }
return conn;
} }
public static final dbAccountHandler AccountQueries = new dbAccountHandler(); public static final dbAccountHandler AccountQueries = new dbAccountHandler();
@ -312,4 +293,36 @@ public enum DbManager {
public static final dbHeightMapHandler HeightMapQueries = new dbHeightMapHandler(); public static final dbHeightMapHandler HeightMapQueries = new dbHeightMapHandler();
public static final dbRunegateHandler RunegateQueries = new dbRunegateHandler(); public static final dbRunegateHandler RunegateQueries = new dbRunegateHandler();
public static void configureConnectionPool() {
HikariConfig config = new HikariConfig();
int connectionCount = (Runtime.getRuntime().availableProcessors() * 2) + 1;
config.setMaximumPoolSize(connectionCount);
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());
// Must be set lower than SQL server connection lifetime!
config.addDataSourceProperty("maxLifetime", "3600000");
config.addDataSourceProperty("characterEncoding", "utf8");
config.addDataSourceProperty("useServerPrepStmts", "true");
config.addDataSourceProperty("cachePrepStmts", "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
Logger.info("Database configured with " + connectionCount + " connections");
}
} }

2
src/engine/gameManager/DevCmdManager.java

@ -93,7 +93,6 @@ public enum DevCmdManager {
DevCmdManager.registerDevCmd(new GetBankCmd()); DevCmdManager.registerDevCmd(new GetBankCmd());
DevCmdManager.registerDevCmd(new GetVaultCmd()); DevCmdManager.registerDevCmd(new GetVaultCmd());
DevCmdManager.registerDevCmd(new CombatMessageCmd()); DevCmdManager.registerDevCmd(new CombatMessageCmd());
DevCmdManager.registerDevCmd(new RenameMobCmd());
DevCmdManager.registerDevCmd(new RenameCmd()); DevCmdManager.registerDevCmd(new RenameCmd());
DevCmdManager.registerDevCmd(new CreateItemCmd()); DevCmdManager.registerDevCmd(new CreateItemCmd());
DevCmdManager.registerDevCmd(new GetMemoryCmd()); DevCmdManager.registerDevCmd(new GetMemoryCmd());
@ -112,7 +111,6 @@ public enum DevCmdManager {
DevCmdManager.registerDevCmd(new DecachePlayerCmd()); DevCmdManager.registerDevCmd(new DecachePlayerCmd());
DevCmdManager.registerDevCmd(new AuditMobsCmd()); DevCmdManager.registerDevCmd(new AuditMobsCmd());
DevCmdManager.registerDevCmd(new ChangeNameCmd()); DevCmdManager.registerDevCmd(new ChangeNameCmd());
DevCmdManager.registerDevCmd(new GuildListCmd());
DevCmdManager.registerDevCmd(new SetGuildCmd()); DevCmdManager.registerDevCmd(new SetGuildCmd());
DevCmdManager.registerDevCmd(new SetOwnerCmd()); DevCmdManager.registerDevCmd(new SetOwnerCmd());
DevCmdManager.registerDevCmd(new NetDebugCmd()); DevCmdManager.registerDevCmd(new NetDebugCmd());

12
src/engine/gameManager/PowersManager.java

@ -11,6 +11,8 @@ package engine.gameManager;
import engine.Enum.*; import engine.Enum.*;
import engine.InterestManagement.HeightMap; import engine.InterestManagement.HeightMap;
import engine.InterestManagement.WorldGrid; import engine.InterestManagement.WorldGrid;
import engine.db.handlers.dbEffectsBaseHandler;
import engine.db.handlers.dbSkillReqHandler;
import engine.job.AbstractJob; import engine.job.AbstractJob;
import engine.job.AbstractScheduleJob; import engine.job.AbstractScheduleJob;
import engine.job.JobContainer; import engine.job.JobContainer;
@ -99,7 +101,7 @@ public enum PowersManager {
public static void InitializeLoginPowers() { public static void InitializeLoginPowers() {
// get all PowersBase // get all PowersBase
ArrayList<PowersBase> pbList = PowersBase.getAllPowersBase(); ArrayList<PowersBase> pbList = dbSkillReqHandler.getAllPowersBase();
for (PowersBase pb : pbList) { for (PowersBase pb : pbList) {
if (pb.getToken() != 0) if (pb.getToken() != 0)
@ -111,7 +113,7 @@ public enum PowersManager {
public static void InitializePowers() { public static void InitializePowers() {
// Add EffectsBase // Add EffectsBase
ArrayList<EffectsBase> ebList = EffectsBase.getAllEffectsBase(); ArrayList<EffectsBase> ebList = dbEffectsBaseHandler.getAllEffectsBase();
for (EffectsBase eb : ebList) { for (EffectsBase eb : ebList) {
PowersManager.effectsBaseByToken.put(eb.getToken(), eb); PowersManager.effectsBaseByToken.put(eb.getToken(), eb);
@ -123,7 +125,7 @@ public enum PowersManager {
EffectsBase.getFailConditions(PowersManager.effectsBaseByIDString); EffectsBase.getFailConditions(PowersManager.effectsBaseByIDString);
// Add Modifiers to Effects // Add Modifiers to Effects
AbstractEffectModifier.getAllEffectModifiers(); dbEffectsBaseHandler.cacheAllEffectModifiers();
// Add Source Types to Effects // Add Source Types to Effects
PowersManager.addAllSourceTypes(); PowersManager.addAllSourceTypes();
@ -136,7 +138,7 @@ public enum PowersManager {
// AbstractPowerAction.loadValidItemFlags(PowersManager.powerActionsByIDString); // AbstractPowerAction.loadValidItemFlags(PowersManager.powerActionsByIDString);
// get all PowersBase // get all PowersBase
ArrayList<PowersBase> pbList = PowersBase.getAllPowersBase(); ArrayList<PowersBase> pbList = dbSkillReqHandler.getAllPowersBase();
for (PowersBase pb : pbList) { for (PowersBase pb : pbList) {
if (pb.getToken() != 0) { if (pb.getToken() != 0) {
PowersManager.powersBaseByIDString.put(pb.getIDString(), pb); PowersManager.powersBaseByIDString.put(pb.getIDString(), pb);
@ -147,7 +149,7 @@ public enum PowersManager {
// Add Power Prereqs // Add Power Prereqs
PowerPrereq.getAllPowerPrereqs(PowersManager.powersBaseByIDString); PowerPrereq.getAllPowerPrereqs(PowersManager.powersBaseByIDString);
// Add Fail Conditions // Add Fail Conditions
PowersBase.getFailConditions(PowersManager.powersBaseByIDString); dbSkillReqHandler.getFailConditions(PowersManager.powersBaseByIDString);
// Add Actions Base // Add Actions Base
ActionsBase.getActionsBase(PowersManager.powersBaseByIDString, ActionsBase.getActionsBase(PowersManager.powersBaseByIDString,
PowersManager.powerActionsByIDString); PowersManager.powerActionsByIDString);

25
src/engine/gameManager/SimulationManager.java

@ -16,6 +16,10 @@ import engine.objects.PlayerCharacter;
import engine.objects.Runegate; import engine.objects.Runegate;
import org.pmw.tinylog.Logger; 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.Duration;
import java.time.Instant; import java.time.Instant;
import java.util.Collection; import java.util.Collection;
@ -50,11 +54,22 @@ public enum SimulationManager {
} }
public static String getPopulationString() { public static String getPopulationString() {
String outString;
String newLine = System.getProperty("line.separator"); String popString = "";
outString = "[LUA_POPULATION()]" + newLine;
outString += DbManager.CSSessionQueries.GET_POPULATION_STRING(); try (Connection connection = DbManager.getConnection();
return outString; 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;
} }
/* /*

55
src/engine/gameManager/ZoneManager.java

@ -9,6 +9,8 @@
package engine.gameManager; package engine.gameManager;
import engine.Enum; import engine.Enum;
import engine.db.archive.CityRecord;
import engine.db.archive.DataWarehouse;
import engine.math.Bounds; import engine.math.Bounds;
import engine.math.Vector2f; import engine.math.Vector2f;
import engine.math.Vector3f; import engine.math.Vector3f;
@ -22,10 +24,7 @@ import org.pmw.tinylog.Logger;
import java.time.Instant; import java.time.Instant;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.ZoneId; import java.time.ZoneId;
import java.util.ArrayList; import java.util.*;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
@ -37,17 +36,18 @@ public enum ZoneManager {
ZONEMANAGER; ZONEMANAGER;
public static Instant hotZoneLastUpdate; public static final Set<Zone> macroZones = Collections.newSetFromMap(new ConcurrentHashMap<>());
/* Instance variables */
private static Zone seaFloor = null;
public static Zone hotZone = null;
public static int hotZoneCycle = 0; // Used with HOTZONE_DURATION from config.
private static final ConcurrentHashMap<Integer, Zone> zonesByID = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD); private static final ConcurrentHashMap<Integer, Zone> zonesByID = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD);
private static final ConcurrentHashMap<Integer, Zone> zonesByUUID = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD); private static final ConcurrentHashMap<Integer, Zone> zonesByUUID = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD);
private static final ConcurrentHashMap<String, Zone> zonesByName = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD); private static final ConcurrentHashMap<String, Zone> zonesByName = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD);
public static final Set<Zone> macroZones = Collections.newSetFromMap(new ConcurrentHashMap<>());
private static final Set<Zone> npcCityZones = Collections.newSetFromMap(new ConcurrentHashMap<>()); private static final Set<Zone> npcCityZones = Collections.newSetFromMap(new ConcurrentHashMap<>());
private static final Set<Zone> playerCityZones = Collections.newSetFromMap(new ConcurrentHashMap<>()); private static final Set<Zone> 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<Integer, Vector2f> _zone_size_data = new HashMap<>();
/* Instance variables */
private static Zone seaFloor = null;
// Find all zones coordinates fit into, starting with Sea Floor // Find all zones coordinates fit into, starting with Sea Floor
@ -168,14 +168,14 @@ public enum ZoneManager {
return (Bounds.collide(loc, ZoneManager.hotZone.getBounds()) == true); return (Bounds.collide(loc, ZoneManager.hotZone.getBounds()) == true);
} }
public static void setSeaFloor(final Zone value) {
ZoneManager.seaFloor = value;
}
public static Zone getSeaFloor() { public static Zone getSeaFloor() {
return ZoneManager.seaFloor; return ZoneManager.seaFloor;
} }
public static void setSeaFloor(final Zone value) {
ZoneManager.seaFloor = value;
}
public static final void populateWorldZones(final Zone zone) { public static final void populateWorldZones(final Zone zone) {
int loadNum = zone.getLoadNum(); int loadNum = zone.getLoadNum();
@ -423,4 +423,31 @@ public enum ZoneManager {
treeBounds.release(); treeBounds.release();
return validLocation; return validLocation;
} }
public static void loadCities(Zone zone) {
ArrayList<City> 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);
}
}
}
}
} }

19
src/engine/net/client/handlers/MinionTrainingMsgHandler.java

@ -4,10 +4,8 @@ import engine.Enum;
import engine.Enum.DispatchChannel; import engine.Enum.DispatchChannel;
import engine.InterestManagement.WorldGrid; import engine.InterestManagement.WorldGrid;
import engine.exception.MsgSendException; import engine.exception.MsgSendException;
import engine.gameManager.BuildingManager; import engine.gameManager.*;
import engine.gameManager.DbManager; import engine.math.Vector3fImmutable;
import engine.gameManager.NPCManager;
import engine.gameManager.SessionManager;
import engine.net.Dispatch; import engine.net.Dispatch;
import engine.net.DispatchMessage; import engine.net.DispatchMessage;
import engine.net.client.ClientConnection; import engine.net.client.ClientConnection;
@ -156,8 +154,16 @@ public class MinionTrainingMsgHandler extends AbstractClientMsgHandler {
// toCreate.despawn(); // toCreate.despawn();
if (toCreate != null) { if (toCreate != null) {
toCreate.setSpawnTime(60 * 15); toCreate.setSpawnTime(60 * 15);
toCreate.setTimeToSpawnSiege(System.currentTimeMillis() + (60 * 15 * 1000)); Building building = BuildingManager.getBuilding(((MinionTrainingMessage) baseMsg).getBuildingID());
toCreate.setDeathTime(System.currentTimeMillis()); int slot = ((NPC)toCreate.npcOwner).getSiegeMinionMap().get(toCreate);
Vector3fImmutable slotLocation;
toCreate.building = building;
toCreate.parentZone = zone;
BuildingLocation buildingLocation = BuildingManager._slotLocations.get(building.meshUUID).get(slot);
slotLocation = building.getLoc().add(buildingLocation.getLocation());
toCreate.setBindLoc(slotLocation);
zone.zoneMobSet.add(toCreate);
MovementManager.translocate(toCreate,toCreate.getBindLoc(),toCreate.npcOwner.region);
} }
} }
@ -289,6 +295,7 @@ public class MinionTrainingMsgHandler extends AbstractClientMsgHandler {
if (toCreate != null) { if (toCreate != null) {
toCreate.setTimeToSpawnSiege(System.currentTimeMillis() + MBServerStatics.FIFTEEN_MINUTES); toCreate.setTimeToSpawnSiege(System.currentTimeMillis() + MBServerStatics.FIFTEEN_MINUTES);
toCreate.setDeathTime(System.currentTimeMillis()); toCreate.setDeathTime(System.currentTimeMillis());
toCreate.parentZone.zoneMobSet.add(toCreate);
} }
} }

38
src/engine/net/client/msg/ManageNPCMsg.java

@ -465,19 +465,43 @@ public class ManageNPCMsg extends ClientNetMsg {
writer.putInt(0); writer.putInt(0);
writer.putInt(1); writer.putInt(1);
writer.putInt(1); writer.putInt(1);
writer.put((byte) 0);
long curTime = System.currentTimeMillis() / 1000; long curTime = System.currentTimeMillis() / 1000;
long upgradeTime = mob.getTimeToSpawnSiege() / 1000; long upgradeTime = (mob.deathTime + (mob.spawnTime * 1000)) / 1000;
long timeLife = upgradeTime - curTime; long timeLife = upgradeTime - curTime;
if (upgradeTime * 1000 > System.currentTimeMillis()) {
writer.putInt(900); if(mob.npcOwner.isAlive()) {
writer.putInt(900); writer.put((byte) 0);//shows respawning timer
writer.putInt((int) timeLife); //time remaining? writer.putInt(mob.spawnTime);
writer.putInt(mob.spawnTime);
writer.putInt((int) timeLife); //time remaining for mob that is dead
writer.putInt(0); writer.putInt(0);
writer.put((byte) 0); writer.put((byte) 0);
writer.putString(mob.getName()); writer.putString(mob.getNameOverride().isEmpty() ? mob.getName() : mob.getNameOverride());
writer.put((byte) 0); writer.put((byte) 0);
} }
else{
writer.put((byte) 0);//shows respawning timer
writer.putInt(0);
writer.putInt(0);
writer.putInt(0); //time remaining for mob that is dead
writer.putInt(0);
writer.put((byte) 0);
writer.putString(mob.getNameOverride().isEmpty() ? mob.getName() : mob.getNameOverride());
writer.put((byte) 0);
}
} else {
//nothing required for countdown for a mob that is alive
writer.put((byte) 1);//shows "Standing By"
writer.putInt(0);
writer.putInt(0);
writer.putInt(0);
writer.putInt(0);
writer.put((byte) 0);
writer.putString(mob.getNameOverride().isEmpty() ? mob.getName() : mob.getNameOverride());
writer.put((byte) 0);
}
}
return; return;
} else { } else {

2
src/engine/objects/Boon.java

@ -55,7 +55,7 @@ public class Boon {
public static void HandleBoonListsForItemBase(int itemBaseID){ public static void HandleBoonListsForItemBase(int itemBaseID){
ArrayList<Boon> boons = null; ArrayList<Boon> boons = null;
boons = DbManager.BoonQueries.GET_BOON_AMOUNTS_FOR_ITEMBASEUUID(itemBaseID); boons = DbManager.BoonQueries.GET_BOON_AMOUNTS_FOR_ITEMBASE(itemBaseID);
if (boons != null) if (boons != null)
GetBoonsForItemBase.put(itemBaseID, boons); GetBoonsForItemBase.put(itemBaseID, boons);
} }

34
src/engine/objects/City.java

@ -34,7 +34,6 @@ import engine.workthreads.DestroyCityThread;
import engine.workthreads.TransferCityThread; import engine.workthreads.TransferCityThread;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.net.UnknownHostException;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.time.LocalDateTime; import java.time.LocalDateTime;
@ -87,7 +86,7 @@ public class City extends AbstractWorldObject {
// Players who have entered the city (used for adding and removing affects) // Players who have entered the city (used for adding and removing affects)
private final HashSet<Integer> _playerMemory = new HashSet<>(); public final HashSet<Integer> _playerMemory = new HashSet<>();
public volatile boolean protectionEnforced = true; public volatile boolean protectionEnforced = true;
private String hash; private String hash;
@ -98,9 +97,9 @@ public class City extends AbstractWorldObject {
* ResultSet Constructor * ResultSet Constructor
*/ */
public City(ResultSet rs) throws SQLException, UnknownHostException { public City(ResultSet rs) throws SQLException {
super(rs); super(rs);
try{ try {
this.cityName = rs.getString("name"); this.cityName = rs.getString("name");
this.motto = rs.getString("motto"); this.motto = rs.getString("motto");
this.isNpc = rs.getByte("isNpc"); this.isNpc = rs.getByte("isNpc");
@ -746,33 +745,6 @@ public class City extends AbstractWorldObject {
return open; return open;
} }
public static void loadCities(Zone zone) {
ArrayList<City> 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 @Override
public void updateDatabase() { public void updateDatabase() {

4
src/engine/objects/Contract.java

@ -138,8 +138,8 @@ public class Contract extends AbstractGameObject {
//Specify if trainer, merchant, banker, etc via classID //Specify if trainer, merchant, banker, etc via classID
private void setBools() { private void setBools() {
DbManager.ContractQueries.GET_GENERIC_INVENTORY(this); DbManager.ContractQueries.LOAD_CONTRACT_INVENTORY(this);
DbManager.ContractQueries.GET_SELL_LISTS(this); DbManager.ContractQueries.LOAD_SELL_LIST_FOR_CONTRACT(this);
this.isTrainer = this.classID > 2499 && this.classID < 3050 || this.classID == 2028; this.isTrainer = this.classID > 2499 && this.classID < 3050 || this.classID == 2028;

15
src/engine/objects/Item.java

@ -210,14 +210,20 @@ public class Item extends AbstractWorldObject {
this.durabilityCurrent = rs.getShort("item_durabilityCurrent"); this.durabilityCurrent = rs.getShort("item_durabilityCurrent");
this.durabilityMax = rs.getShort("item_durabilityMax"); 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")) switch (ownerType) {
case CHARACTER:
this.ownerType = OwnerType.PlayerCharacter; this.ownerType = OwnerType.PlayerCharacter;
else if (ot.equals("npc")) break;
case NPC:
this.ownerType = OwnerType.Npc; this.ownerType = OwnerType.Npc;
else if (ot.equals("account")) break;
case ACCOUNT:
this.ownerType = OwnerType.Account; this.ownerType = OwnerType.Account;
break;
}
this.canDestroy = true; this.canDestroy = true;
@ -1063,7 +1069,6 @@ public float getBonusPercent(ModType modType, SourceType sourceType) {
return; return;
} }
ConcurrentHashMap<String, Integer> enchantList = DbManager.EnchantmentQueries.GET_ENCHANTMENTS_FOR_ITEM(this.getObjectUUID()); ConcurrentHashMap<String, Integer> enchantList = DbManager.EnchantmentQueries.GET_ENCHANTMENTS_FOR_ITEM(this.getObjectUUID());
for (String enchant : enchantList.keySet()) { for (String enchant : enchantList.keySet()) {

12
src/engine/objects/Mob.java

@ -99,6 +99,7 @@ public class Mob extends AbstractIntelligenceAgent {
private DeferredPowerJob weaponPower; private DeferredPowerJob weaponPower;
private DateTime upgradeDateTime = null; private DateTime upgradeDateTime = null;
private boolean lootSync = false; private boolean lootSync = false;
public City guardedCity;
/** /**
* No Id Constructor * No Id Constructor
@ -806,6 +807,7 @@ public class Mob extends AbstractIntelligenceAgent {
mob.npcOwner = guardCaptain; mob.npcOwner = guardCaptain;
mob.spawnTime = (int)(-2.500 * guardCaptain.building.getRank() + 22.5) * 60; mob.spawnTime = (int)(-2.500 * guardCaptain.building.getRank() + 22.5) * 60;
mob.BehaviourType = Enum.MobBehaviourType.GuardMinion; mob.BehaviourType = Enum.MobBehaviourType.GuardMinion;
mob.guardedCity = guardCaptain.guardedCity;
mob.parentZone = parent; mob.parentZone = parent;
parent.zoneMobSet.add(mob); parent.zoneMobSet.add(mob);
return mob; return mob;
@ -825,7 +827,7 @@ public class Mob extends AbstractIntelligenceAgent {
return null; return null;
mob = new Mob(minionMobBase, guild, parent, level, new Vector3fImmutable(1, 1, 1), 0, false); mob = new Mob(minionMobBase, guild, parent, level, new Vector3fImmutable(1, 1, 1), 0, false);
mob.runAfterLoad(); //mob.runAfterLoad();
mob.despawned = true; mob.despawned = true;
DbManager.addToCache(mob); DbManager.addToCache(mob);
@ -843,7 +845,6 @@ public class Mob extends AbstractIntelligenceAgent {
owner.getSiegeMinionMap().put(mob, slot); owner.getSiegeMinionMap().put(mob, slot);
mob.setSpawnTime(10);
mob.setNpcOwner(owner); mob.setNpcOwner(owner);
mob.BehaviourType = MobBehaviourType.Pet1; mob.BehaviourType = MobBehaviourType.Pet1;
mob.BehaviourType.canRoam = false; mob.BehaviourType.canRoam = false;
@ -1376,7 +1377,7 @@ public class Mob extends AbstractIntelligenceAgent {
public void respawn() { public void respawn() {
//Commenting out Mob ID rotation. //Commenting out Mob ID rotation.
this.despawned = false; this.despawned = false;
this.playerAgroMap.clear(); //this.playerAgroMap.clear();
this.setCombatTarget(null); this.setCombatTarget(null);
this.setHealth(this.healthMax); this.setHealth(this.healthMax);
this.stamina.set(this.staminaMax); this.stamina.set(this.staminaMax);
@ -1392,7 +1393,11 @@ public class Mob extends AbstractIntelligenceAgent {
NPCManager.applyRuneSetEffects(this); NPCManager.applyRuneSetEffects(this);
this.recalculateStats(); this.recalculateStats();
this.setHealth(this.healthMax); this.setHealth(this.healthMax);
if(this.building == null && ((Mob)this.npcOwner).BehaviourType.ordinal() == MobBehaviourType.GuardCaptain.ordinal()){
this.building = ((Mob)this.npcOwner).building;
} else {
this.region = BuildingManager.GetRegion(this.building, bindLoc.x, bindLoc.y, bindLoc.z); this.region = BuildingManager.GetRegion(this.building, bindLoc.x, bindLoc.y, bindLoc.z);
}
MovementManager.translocate(this,this.bindLoc, this.region); MovementManager.translocate(this,this.bindLoc, this.region);
if (!this.isSiege && !this.isPlayerGuard && contract == null) if (!this.isSiege && !this.isPlayerGuard && contract == null)
loadInventory(); loadInventory();
@ -1987,6 +1992,7 @@ public class Mob extends AbstractIntelligenceAgent {
else { else {
this.BehaviourType = MobBehaviourType.GuardCaptain; this.BehaviourType = MobBehaviourType.GuardCaptain;
this.spawnTime = 900; this.spawnTime = 900;
this.guardedCity = ZoneManager.getCityAtLocation(this.bindLoc);
} }
this.deathTime = 0; this.deathTime = 0;

14
src/engine/objects/MobBase.java

@ -206,20 +206,8 @@ public class MobBase extends AbstractGameObject {
return this.spawnTime; return this.spawnTime;
} }
/*
* Database
*/
public static MobBase getMobBase(int id) { public static MobBase getMobBase(int id) {
return MobBase.getMobBase(id, false); return DbManager.MobBaseQueries.GET_MOBBASE(id);
}
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);
} }
@Override @Override

3
src/engine/objects/Realm.java

@ -22,7 +22,6 @@ import engine.server.MBServerStatics;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.awt.*; import java.awt.*;
import java.net.UnknownHostException;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.time.LocalDateTime; import java.time.LocalDateTime;
@ -72,7 +71,7 @@ public class Realm {
/** /**
* ResultSet Constructor * 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.mapColor = new Color(Integer.parseInt(rs.getString("realmColor"), 16));
this.mapR = (float) (mapColor.getRed() * 0.00392156863); this.mapR = (float) (mapColor.getRed() * 0.00392156863);

313
src/engine/objects/Zone.java

@ -30,19 +30,25 @@ import java.util.concurrent.ConcurrentHashMap;
public class Zone extends AbstractGameObject { public class Zone extends AbstractGameObject {
public final Set<Building> zoneBuildingSet = Collections.newSetFromMap(new ConcurrentHashMap<>());
public final Set<NPC> zoneNPCSet = Collections.newSetFromMap(new ConcurrentHashMap<>());
public final Set<Mob> zoneMobSet = Collections.newSetFromMap(new ConcurrentHashMap<>());
private final int playerCityID; private final int playerCityID;
private final String zoneName; private final String zoneName;
private final float xCoord; private final float xCoord;
private final float zCoord; private final float zCoord;
private final float yCoord; 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 int loadNum;
private final byte safeZone; private final byte safeZone;
private final String Icon1; private final String Icon1;
private final String Icon2; private final String Icon2;
private final String Icon3; 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<Zone> nodes = null; private ArrayList<Zone> nodes = null;
private int parentZoneID; private int parentZoneID;
private Zone parent = null; private Zone parent = null;
@ -50,16 +56,9 @@ public class Zone extends AbstractGameObject {
private boolean isNPCCity = false; private boolean isNPCCity = false;
private boolean isPlayerCity = false; private boolean isPlayerCity = false;
private String hash; private String hash;
public int minLvl;
public int maxLvl;
private float worldAltitude = 0; private float worldAltitude = 0;
private float seaLevel = 0; private float seaLevel = 0;
public final Set<Building> zoneBuildingSet = Collections.newSetFromMap(new ConcurrentHashMap<>());
public final Set<NPC> zoneNPCSet = Collections.newSetFromMap(new ConcurrentHashMap<>());
public final Set<Mob> zoneMobSet = Collections.newSetFromMap(new ConcurrentHashMap<>());
public boolean hasBeenHotzone = false;
/** /**
* ResultSet Constructor * ResultSet Constructor
*/ */
@ -87,7 +86,7 @@ public class Zone extends AbstractGameObject {
this.setParent(parentZone); this.setParent(parentZone);
if (this.minLvl == 0 && parentZone != null){ if (this.minLvl == 0 && parentZone != null) {
this.minLvl = parentZone.minLvl; this.minLvl = parentZone.minLvl;
this.maxLvl = parentZone.maxLvl; this.maxLvl = parentZone.maxLvl;
} }
@ -103,6 +102,59 @@ public class Zone extends AbstractGameObject {
} }
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 /* Method sets a default value for player cities
* otherwise using values derived from the loadnum * otherwise using values derived from the loadnum
* field in the obj_zone database table. * field in the obj_zone database table.
@ -123,38 +175,18 @@ public class Zone extends AbstractGameObject {
return; return;
} }
// All other zones have bounding boxes loaded from database Vector2f zoneSize = ZoneManager._zone_size_data.get(this.loadNum);
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;
}
} catch (SQLException e) { // Default to player zone size on error? Maybe log this
Logger.error("SQLException: " + e.getMessage());
}
if (!loaded) {
// Default to Citygrid size on error
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); bounds.setBounds(new Vector2f(this.absX, this.absZ), new Vector2f(Enum.CityBoundsType.ZONE.extents, Enum.CityBoundsType.ZONE.extents), 0.0f);
}
} }
/*
* Getters
*/
public int getPlayerCityUUID() { public int getPlayerCityUUID() {
if (this.playerCityID == 0)
return 0;
return this.playerCityID; return this.playerCityID;
} }
@ -178,10 +210,6 @@ public class Zone extends AbstractGameObject {
return loadNum; return loadNum;
} }
public int getLoadNumClient() {
return loadNum;
}
public byte getSafeZone() { public byte getSafeZone() {
return safeZone; return safeZone;
} }
@ -190,45 +218,9 @@ public class Zone extends AbstractGameObject {
return Icon1; return Icon1;
} }
public String getIcon2() { public void generateWorldAltitude() {
return Icon2;
}
public String getIcon3() {
return Icon3;
}
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; this.worldAltitude = MBServerStatics.SEA_FLOOR_ALTITUDE;
return; return;
} }
@ -240,9 +232,9 @@ public class Zone extends AbstractGameObject {
//seafloor only zone with null parent; //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); Vector2f zoneLoc = ZoneManager.worldToZoneSpace(currentZone.getLoc(), parentZone);
altitude += parentZone.getHeightMap().getInterpolatedTerrainHeight(zoneLoc); altitude += parentZone.getHeightMap().getInterpolatedTerrainHeight(zoneLoc);
@ -258,12 +250,12 @@ public class Zone extends AbstractGameObject {
if (ZoneManager.getSeaFloor().equals(this)) if (ZoneManager.getSeaFloor().equals(this))
this.seaLevel = 0; this.seaLevel = 0;
else if else if
(this.getHeightMap() != null && this.getHeightMap().getSeaLevel() == 0){ (this.getHeightMap() != null && this.getHeightMap().getSeaLevel() == 0) {
this.seaLevel = this.parent.seaLevel; this.seaLevel = this.parent.seaLevel;
}else if (this.getHeightMap() != null){ } else if (this.getHeightMap() != null) {
this.seaLevel = this.worldAltitude + this.getHeightMap().getSeaLevel(); this.seaLevel = this.worldAltitude + this.getHeightMap().getSeaLevel();
}else { } else {
this.seaLevel = this.parent.seaLevel; this.seaLevel = this.parent.seaLevel;
} }
@ -273,6 +265,34 @@ public class Zone extends AbstractGameObject {
return this.parent; 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() { public float getAbsX() {
return this.absX; return this.absX;
} }
@ -302,14 +322,14 @@ public class Zone extends AbstractGameObject {
return this.isNPCCity; return this.isNPCCity;
} }
public boolean isPlayerCity() {
return this.isPlayerCity;
}
public void setNPCCity(boolean value) { public void setNPCCity(boolean value) {
this.isNPCCity = value; this.isNPCCity = value;
} }
public boolean isPlayerCity() {
return this.isPlayerCity;
}
public void setPlayerCity(boolean value) { public void setPlayerCity(boolean value) {
this.isPlayerCity = value; this.isPlayerCity = value;
} }
@ -336,71 +356,12 @@ public class Zone extends AbstractGameObject {
return nodes; return nodes;
} }
public void addNode(Zone child) {
this.nodes.add(child);
}
public void removeNode(Zone child) {
this.nodes.remove(child);
}
/* /*
* Serializing * Serializing
*/ */
public void addNode(Zone child) {
public static void serializeForClientMsg(Zone zone,ByteBufferWriter writer) { this.nodes.add(child);
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);
}
} }
@Override @Override
@ -408,60 +369,6 @@ public class Zone extends AbstractGameObject {
// TODO Auto-generated method stub // 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() { public boolean isContinent() {
if (this.equals(ZoneManager.getSeaFloor())) if (this.equals(ZoneManager.getSeaFloor()))

92
src/engine/powers/EffectsBase.java

@ -183,98 +183,6 @@ public class EffectsBase {
// getFailConditions(); // 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<EffectsBase> getAllEffectsBase() {
PreparedStatementShared ps = null;
ArrayList<EffectsBase> 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<EffectsBase> getAllLiveEffectsBase() {
PreparedStatementShared ps = null;
ArrayList<EffectsBase> 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<EffectsBase> 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<String, EffectsBase> effects) { public static void getFailConditions(HashMap<String, EffectsBase> effects) {
PreparedStatementShared ps = null; PreparedStatementShared ps = null;
try { try {

53
src/engine/powers/PowersBase.java

@ -11,13 +11,11 @@ package engine.powers;
import engine.Enum.PowerCategoryType; import engine.Enum.PowerCategoryType;
import engine.Enum.PowerTargetType; import engine.Enum.PowerTargetType;
import engine.objects.PreparedStatementShared;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
public class PowersBase { public class PowersBase {
@ -340,57 +338,6 @@ public class PowersBase {
this.monsterTypeRestrictions.add(ct); this.monsterTypeRestrictions.add(ct);
} }
public static ArrayList<PowersBase> getAllPowersBase() {
PreparedStatementShared ps = null;
ArrayList<PowersBase> 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<String, PowersBase> 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() { public String getName() {
return this.name; return this.name;

263
src/engine/powers/effectmodifiers/AbstractEffectModifier.java

@ -11,17 +11,15 @@ package engine.powers.effectmodifiers;
import engine.Enum.ModType; import engine.Enum.ModType;
import engine.Enum.SourceType; import engine.Enum.SourceType;
import engine.gameManager.DbManager;
import engine.gameManager.PowersManager;
import engine.jobs.AbstractEffectJob; 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 engine.powers.EffectsBase;
import org.pmw.tinylog.Logger;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
public abstract class AbstractEffectModifier { public abstract class AbstractEffectModifier {
@ -30,7 +28,7 @@ public abstract class AbstractEffectModifier {
protected int UUID; protected int UUID;
protected String IDString; protected String IDString;
protected String effectType; protected String effectType;
protected float minMod; public float minMod;
protected float maxMod; protected float maxMod;
protected float percentMod; protected float percentMod;
protected float ramp; protected float ramp;
@ -60,257 +58,6 @@ public abstract class AbstractEffectModifier {
this.string2 = rs.getString("string2"); this.string2 = rs.getString("string2");
} }
public static ArrayList<AbstractEffectModifier> getAllEffectModifiers() {
PreparedStatementShared ps = null;
ArrayList<AbstractEffectModifier> 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() { public int getUUID() {
return this.UUID; return this.UUID;

2
src/engine/powers/effectmodifiers/ItemNameEffectModifier.java

@ -21,7 +21,7 @@ import java.sql.SQLException;
public class ItemNameEffectModifier extends AbstractEffectModifier { public class ItemNameEffectModifier extends AbstractEffectModifier {
String name = ""; public String name = "";
public ItemNameEffectModifier(ResultSet rs) throws SQLException { public ItemNameEffectModifier(ResultSet rs) throws SQLException {
super(rs); super(rs);

2
src/engine/server/MBServerStatics.java

@ -651,7 +651,7 @@ public class MBServerStatics {
public static int AI_RECALL_RANGE = 400; public static int AI_RECALL_RANGE = 400;
public static int AI_PULSE_MOB_THRESHOLD = 200; public static int AI_PULSE_MOB_THRESHOLD = 200;
public static int AI_THREAD_SLEEP = 1000; public static int AI_THREAD_SLEEP = 1000;
public static int AI_PATROL_DIVISOR = 10; public static int AI_PATROL_DIVISOR = 15;
public static int AI_POWER_DIVISOR = 20; public static int AI_POWER_DIVISOR = 20;
public static int AI_PET_HEEL_DISTANCE = 10; public static int AI_PET_HEEL_DISTANCE = 10;
public static int AI_PATROL_RADIUS = 60; public static int AI_PATROL_RADIUS = 60;

50
src/engine/server/login/LoginServer.java

@ -9,8 +9,6 @@
package engine.server.login; package engine.server.login;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import engine.Enum; import engine.Enum;
import engine.gameManager.*; import engine.gameManager.*;
import engine.job.JobScheduler; import engine.job.JobScheduler;
@ -52,7 +50,6 @@ public class LoginServer {
// Instance variables // Instance variables
private VersionInfoMsg versionInfoMessage; private VersionInfoMsg versionInfoMessage;
public static HikariDataSource connectionPool = null;
public static int population = 0; public static int population = 0;
public static boolean worldServerRunning = false; public static boolean worldServerRunning = false;
public static boolean loginServerRunning = false; public static boolean loginServerRunning = false;
@ -119,16 +116,20 @@ public class LoginServer {
// Invalidate cache for players driven by forum // Invalidate cache for players driven by forum
// and stored procedure forum_link_pass() // and stored procedure forum_link_pass()
try {
// Run cache routine right away if requested. // Run cache routine right away if requested.
File cacheFile = new File("cacheInvalid"); File cacheFile = new File("cacheInvalid");
if (cacheFile.exists() == true) { if (cacheFile.exists() == true) {
nextCacheTime = LocalDateTime.now(); nextCacheTime = LocalDateTime.now();
try {
Files.deleteIfExists(Paths.get("cacheInvalid")); Files.deleteIfExists(Paths.get("cacheInvalid"));
} catch (IOException e) {
throw new RuntimeException(e);
}
} }
if (LocalDateTime.now().isAfter(nextCacheTime)) { if (LocalDateTime.now().isAfter(nextCacheTime)) {
@ -148,10 +149,7 @@ public class LoginServer {
} }
ThreadUtils.sleep(100); ThreadUtils.sleep(100);
} catch (Exception e) {
Logger.error(e);
e.printStackTrace();
}
} }
} }
@ -172,9 +170,6 @@ public class LoginServer {
this.versionInfoMessage = new VersionInfoMsg(ConfigManager.MB_MAJOR_VER.getValue(), this.versionInfoMessage = new VersionInfoMsg(ConfigManager.MB_MAJOR_VER.getValue(),
ConfigManager.MB_MINOR_VER.getValue()); ConfigManager.MB_MINOR_VER.getValue());
Logger.info("Initializing Database Pool");
initDatabasePool();
Logger.info("Initializing Database layer"); Logger.info("Initializing Database layer");
initDatabaseLayer(); initDatabaseLayer();
@ -229,12 +224,12 @@ public class LoginServer {
// Try starting a GOM <-> DB connection. // Try starting a GOM <-> DB connection.
try { try {
Logger.info("Configuring GameObjectManager to use Database: '" Logger.info("Configuring Magicbane to use Database: '"
+ ConfigManager.MB_DATABASE_NAME.getValue() + "' on " + ConfigManager.MB_DATABASE_NAME.getValue() + "' on "
+ ConfigManager.MB_DATABASE_ADDRESS.getValue() + ':' + ConfigManager.MB_DATABASE_ADDRESS.getValue() + ':'
+ ConfigManager.MB_DATABASE_PORT.getValue()); + ConfigManager.MB_DATABASE_PORT.getValue());
DbManager.configureDatabaseLayer(); DbManager.configureConnectionPool();
} catch (Exception e) { } catch (Exception e) {
Logger.error(e.getMessage()); Logger.error(e.getMessage());
@ -365,33 +360,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() { public void invalidateCacheList() {
int objectUUID; int objectUUID;
String objectType; String objectType;
try (Connection connection = connectionPool.getConnection(); try (Connection connection = DbManager.getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT * FROM `login_cachelist`"); PreparedStatement statement = connection.prepareStatement("SELECT * FROM `login_cachelist`");
ResultSet rs = statement.executeQuery()) { ResultSet rs = statement.executeQuery()) {
@ -424,7 +398,7 @@ public class LoginServer {
// clear the db table // clear the db table
try (Connection connection = connectionPool.getConnection(); try (Connection connection = DbManager.getConnection();
PreparedStatement statement = connection.prepareStatement("DELETE FROM `login_cachelist`")) { PreparedStatement statement = connection.prepareStatement("DELETE FROM `login_cachelist`")) {
statement.execute(); statement.execute();
@ -447,7 +421,7 @@ public class LoginServer {
// query data warehouse for unresolved bane with this character // query data warehouse for unresolved bane with this character
try (Connection connection = connectionPool.getConnection(); try (Connection connection = DbManager.getConnection();
PreparedStatement statement = buildQueryActiveBaneStatement(connection, playerCharacter); PreparedStatement statement = buildQueryActiveBaneStatement(connection, playerCharacter);
ResultSet rs = statement.executeQuery()) { ResultSet rs = statement.executeQuery()) {

4
src/engine/server/login/LoginServerMsgHandler.java

@ -449,9 +449,9 @@ public class LoginServerMsgHandler implements NetMsgHandler {
Account account = session.getAccount(); Account account = session.getAccount();
account.setLastCharIDUsed(gameServerIPRequestMessage.getCharacterUUID()); 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"); Logger.error("Failed to send message");
this.KickToLogin(MBServerStatics.LOGINERROR_UNABLE_TO_LOGIN, "Unable to send GameServerIPResponseMsg to client.", conn); this.KickToLogin(MBServerStatics.LOGINERROR_UNABLE_TO_LOGIN, "Unable to send GameServerIPResponseMsg to client.", conn);
} }

9
src/engine/server/world/WorldServer.java

@ -305,9 +305,12 @@ public class WorldServer {
PowersManager.LoadAllMobPowers(); PowersManager.LoadAllMobPowers();
//load item enchantment values //load item enchantment values
Logger.info("Loading item enchants");
DbManager.LootQueries.LOAD_ENCHANT_VALUES(); DbManager.LootQueries.LOAD_ENCHANT_VALUES();
//initialize realms Logger.info("Loading zone extent cache");
DbManager.ZoneQueries.LOAD_ZONE_EXTENTS();
Logger.info("Loading Realms"); Logger.info("Loading Realms");
Realm.loadAllRealms(); Realm.loadAllRealms();
@ -471,7 +474,7 @@ public class WorldServer {
+ ConfigManager.MB_DATABASE_ADDRESS.getValue() + ':' + ConfigManager.MB_DATABASE_ADDRESS.getValue() + ':'
+ ConfigManager.MB_DATABASE_PORT.getValue()); + ConfigManager.MB_DATABASE_PORT.getValue());
DbManager.configureDatabaseLayer(); DbManager.configureConnectionPool();
} catch (Exception e) { } catch (Exception e) {
Logger.error(e.getMessage()); Logger.error(e.getMessage());
@ -572,7 +575,7 @@ public class WorldServer {
//Handle cities //Handle cities
City.loadCities(zone); ZoneManager.loadCities(zone);
ZoneManager.populateWorldZones(zone); ZoneManager.populateWorldZones(zone);
} catch (Exception e) { } catch (Exception e) {

1
src/engine/workthreads/HourlyJobThread.java

@ -284,7 +284,6 @@ public class HourlyJobThread implements Runnable {
Logger.info(WorldServer.getUptimeString()); Logger.info(WorldServer.getUptimeString());
Logger.info(SimulationManager.getPopulationString()); Logger.info(SimulationManager.getPopulationString());
Logger.info(MessageDispatcher.getNetstatString()); Logger.info(MessageDispatcher.getNetstatString());
Logger.info("Connection Pool Size: " + DbManager.getPoolSize());
Logger.info(PurgeOprhans.recordsDeleted.toString() + "orphaned items deleted"); Logger.info(PurgeOprhans.recordsDeleted.toString() + "orphaned items deleted");
} }
} }

4
src/engine/workthreads/PurgeOprhans.java

@ -8,7 +8,7 @@
package engine.workthreads; package engine.workthreads;
import engine.db.archive.DataWarehouse; import engine.gameManager.DbManager;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.Connection; import java.sql.Connection;
@ -46,7 +46,7 @@ public class PurgeOprhans implements Runnable {
// Member variable declaration // Member variable declaration
try ( 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); 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()) { ResultSet rs = statement.executeQuery()) {

29
src/engine/workthreads/WarehousePushThread.java

@ -18,6 +18,7 @@ package engine.workthreads;
import engine.Enum; import engine.Enum;
import engine.db.archive.*; import engine.db.archive.*;
import engine.gameManager.ConfigManager; import engine.gameManager.ConfigManager;
import engine.gameManager.DbManager;
import org.pmw.tinylog.Logger; import org.pmw.tinylog.Logger;
import java.sql.*; import java.sql.*;
@ -153,7 +154,7 @@ public class WarehousePushThread implements Runnable {
public static boolean pushMineRecords() { public static boolean pushMineRecords() {
try (Connection localConnection = DataWarehouse.connectionPool.getConnection(); try (Connection localConnection = DbManager.getConnection();
PreparedStatement statement = MineRecord.buildMineQueryStatement(localConnection); PreparedStatement statement = MineRecord.buildMineQueryStatement(localConnection);
ResultSet rs = statement.executeQuery()) { ResultSet rs = statement.executeQuery()) {
@ -164,7 +165,7 @@ public class WarehousePushThread implements Runnable {
return true; return true;
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( "Error with local DB connection: " + e.toString()); Logger.error("Error with local DB connection: " + e.toString());
e.printStackTrace(); e.printStackTrace();
return false; return false;
} }
@ -172,7 +173,7 @@ public class WarehousePushThread implements Runnable {
public static boolean pushCharacterRecords() { public static boolean pushCharacterRecords() {
try (Connection localConnection = DataWarehouse.connectionPool.getConnection(); try (Connection localConnection = DbManager.getConnection();
PreparedStatement statement = CharacterRecord.buildCharacterQueryStatement(localConnection); PreparedStatement statement = CharacterRecord.buildCharacterQueryStatement(localConnection);
ResultSet rs = statement.executeQuery()) { ResultSet rs = statement.executeQuery()) {
@ -183,7 +184,7 @@ public class WarehousePushThread implements Runnable {
return true; return true;
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( "Error with local DB connection: " + e.toString()); Logger.error("Error with local DB connection: " + e.toString());
e.printStackTrace(); e.printStackTrace();
return false; return false;
} }
@ -191,7 +192,7 @@ public class WarehousePushThread implements Runnable {
private static boolean pushGuildRecords() { private static boolean pushGuildRecords() {
try (Connection localConnection = DataWarehouse.connectionPool.getConnection(); try (Connection localConnection = DbManager.getConnection();
PreparedStatement statement = GuildRecord.buildGuildQueryStatement(localConnection); PreparedStatement statement = GuildRecord.buildGuildQueryStatement(localConnection);
ResultSet rs = statement.executeQuery()) { ResultSet rs = statement.executeQuery()) {
@ -238,7 +239,7 @@ public class WarehousePushThread implements Runnable {
private static boolean pushBaneRecords() { private static boolean pushBaneRecords() {
try (Connection localConnection = DataWarehouse.connectionPool.getConnection(); try (Connection localConnection = DbManager.getConnection();
PreparedStatement statement = BaneRecord.buildBaneQueryStatement(localConnection); PreparedStatement statement = BaneRecord.buildBaneQueryStatement(localConnection);
ResultSet rs = statement.executeQuery()) { ResultSet rs = statement.executeQuery()) {
@ -271,7 +272,7 @@ public class WarehousePushThread implements Runnable {
private static boolean pushCityRecords() { private static boolean pushCityRecords() {
try (Connection localConnection = DataWarehouse.connectionPool.getConnection(); try (Connection localConnection = DbManager.getConnection();
PreparedStatement statement = CityRecord.buildCityQueryStatement(localConnection); PreparedStatement statement = CityRecord.buildCityQueryStatement(localConnection);
ResultSet rs = statement.executeQuery()) { ResultSet rs = statement.executeQuery()) {
@ -282,7 +283,7 @@ public class WarehousePushThread implements Runnable {
return true; return true;
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( "Error with local DB connection: " + e.toString()); Logger.error("Error with local DB connection: " + e.toString());
e.printStackTrace(); e.printStackTrace();
return false; return false;
} }
@ -290,7 +291,7 @@ public class WarehousePushThread implements Runnable {
private static boolean pushPvpRecords() { private static boolean pushPvpRecords() {
try (Connection localConnection = DataWarehouse.connectionPool.getConnection(); try (Connection localConnection = DbManager.getConnection();
PreparedStatement statement = PvpRecord.buildPvpQueryStatement(localConnection); PreparedStatement statement = PvpRecord.buildPvpQueryStatement(localConnection);
ResultSet rs = statement.executeQuery()) { ResultSet rs = statement.executeQuery()) {
@ -323,7 +324,7 @@ public class WarehousePushThread implements Runnable {
private static boolean pushRealmRecords() { private static boolean pushRealmRecords() {
try (Connection localConnection = DataWarehouse.connectionPool.getConnection(); try (Connection localConnection = DbManager.getConnection();
PreparedStatement statement = RealmRecord.buildRealmQueryStatement(localConnection); PreparedStatement statement = RealmRecord.buildRealmQueryStatement(localConnection);
ResultSet rs = statement.executeQuery()) { ResultSet rs = statement.executeQuery()) {
@ -335,7 +336,7 @@ public class WarehousePushThread implements Runnable {
return true; return true;
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( "Error with local DB connection: " + e.toString()); Logger.error("Error with local DB connection: " + e.toString());
e.printStackTrace(); e.printStackTrace();
return false; return false;
} }
@ -392,7 +393,7 @@ public class WarehousePushThread implements Runnable {
queryString = "SELECT * FROM `warehouse_index`"; queryString = "SELECT * FROM `warehouse_index`";
try (Connection localConnection = DataWarehouse.connectionPool.getConnection(); try (Connection localConnection = DbManager.getConnection();
CallableStatement statement = localConnection.prepareCall(queryString); CallableStatement statement = localConnection.prepareCall(queryString);
ResultSet rs = statement.executeQuery()) { ResultSet rs = statement.executeQuery()) {
@ -417,14 +418,14 @@ public class WarehousePushThread implements Runnable {
private static boolean updateWarehouseIndex() { private static boolean updateWarehouseIndex() {
try (Connection connection = DataWarehouse.connectionPool.getConnection(); try (Connection connection = DbManager.getConnection();
PreparedStatement statement = WarehousePushThread.buildIndexUpdateStatement(connection)) { PreparedStatement statement = WarehousePushThread.buildIndexUpdateStatement(connection)) {
statement.execute(); statement.execute();
return true; return true;
} catch (SQLException e) { } catch (SQLException e) {
Logger.error( e.toString()); Logger.error(e.toString());
return false; return false;
} }
} }

Loading…
Cancel
Save