refactor: use try-with-resources for character saving db operations

This commit is contained in:
P0nk
2021-04-04 21:24:12 +02:00
parent 2b0d918401
commit 8c41f713a6

View File

@@ -8347,13 +8347,12 @@ public class MapleCharacter extends AbstractMapleCharacterObject {
Server.getInstance().updateCharacterEntry(this);
Connection con = null;
try {
con = DatabaseConnection.getConnection();
con.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
try (Connection con = DatabaseConnection.getConnection()) {
con.setAutoCommit(false);
PreparedStatement ps;
ps = con.prepareStatement("UPDATE characters SET level = ?, fame = ?, str = ?, dex = ?, luk = ?, `int` = ?, exp = ?, gachaexp = ?, hp = ?, mp = ?, maxhp = ?, maxmp = ?, sp = ?, ap = ?, gm = ?, skincolor = ?, gender = ?, job = ?, hair = ?, face = ?, map = ?, meso = ?, hpMpUsed = ?, spawnpoint = ?, party = ?, buddyCapacity = ?, messengerid = ?, messengerposition = ?, mountlevel = ?, mountexp = ?, mounttiredness= ?, equipslots = ?, useslots = ?, setupslots = ?, etcslots = ?, monsterbookcover = ?, vanquisherStage = ?, dojoPoints = ?, lastDojoStage = ?, finishedDojoTutorial = ?, vanquisherKills = ?, matchcardwins = ?, matchcardlosses = ?, matchcardties = ?, omokwins = ?, omoklosses = ?, omokties = ?, dataString = ?, fquest = ?, jailexpire = ?, partnerId = ?, marriageItemId = ?, lastExpGainTime = ?, ariantPoints = ?, partySearch = ? WHERE id = ?", Statement.RETURN_GENERATED_KEYS);
con.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
try {
try (PreparedStatement ps = con.prepareStatement("UPDATE characters SET level = ?, fame = ?, str = ?, dex = ?, luk = ?, `int` = ?, exp = ?, gachaexp = ?, hp = ?, mp = ?, maxhp = ?, maxmp = ?, sp = ?, ap = ?, gm = ?, skincolor = ?, gender = ?, job = ?, hair = ?, face = ?, map = ?, meso = ?, hpMpUsed = ?, spawnpoint = ?, party = ?, buddyCapacity = ?, messengerid = ?, messengerposition = ?, mountlevel = ?, mountexp = ?, mounttiredness= ?, equipslots = ?, useslots = ?, setupslots = ?, etcslots = ?, monsterbookcover = ?, vanquisherStage = ?, dojoPoints = ?, lastDojoStage = ?, finishedDojoTutorial = ?, vanquisherKills = ?, matchcardwins = ?, matchcardlosses = ?, matchcardties = ?, omokwins = ?, omoklosses = ?, omokties = ?, dataString = ?, fquest = ?, jailexpire = ?, partnerId = ?, marriageItemId = ?, lastExpGainTime = ?, ariantPoints = ?, partySearch = ? WHERE id = ?", Statement.RETURN_GENERATED_KEYS)) {
ps.setInt(1, level); // thanks CanIGetaPR for noticing an unnecessary "level" limitation when persisting DB data
ps.setInt(2, fame);
@@ -8370,13 +8369,15 @@ public class MapleCharacter extends AbstractMapleCharacterObject {
ps.setInt(10, mp);
ps.setInt(11, maxhp);
ps.setInt(12, maxmp);
StringBuilder sps = new StringBuilder();
for (int i = 0; i < remainingSp.length; i++) {
sps.append(remainingSp[i]);
for (int j : remainingSp) {
sps.append(j);
sps.append(",");
}
String sp = sps.toString();
ps.setString(13, sp.substring(0, sp.length() - 1));
ps.setInt(14, remainingAp);
} finally {
statWlock.unlock();
@@ -8468,11 +8469,10 @@ public class MapleCharacter extends AbstractMapleCharacterObject {
ps.setInt(56, id);
int updateRows = ps.executeUpdate();
ps.close();
if (updateRows < 1) {
throw new RuntimeException("Character not in database (" + id + ")");
}
}
List<MaplePet> petList = new LinkedList<>();
petLock.lock();
@@ -8491,65 +8491,67 @@ public class MapleCharacter extends AbstractMapleCharacterObject {
}
for (Entry<Integer, Set<Integer>> es : getExcluded().entrySet()) { // this set is already protected
try (PreparedStatement ps2 = con.prepareStatement("DELETE FROM petignores WHERE petid=?")) {
ps2.setInt(1, es.getKey());
ps2.executeUpdate();
try (PreparedStatement psIgnore = con.prepareStatement("DELETE FROM petignores WHERE petid=?")) {
psIgnore.setInt(1, es.getKey());
psIgnore.executeUpdate();
}
try (PreparedStatement ps2 = con.prepareStatement("INSERT INTO petignores (petid, itemid) VALUES (?, ?)")) {
ps2.setInt(1, es.getKey());
try (PreparedStatement psIgnore = con.prepareStatement("INSERT INTO petignores (petid, itemid) VALUES (?, ?)")) {
psIgnore.setInt(1, es.getKey());
for (Integer x : es.getValue()) {
ps2.setInt(2, x);
ps2.addBatch();
psIgnore.setInt(2, x);
psIgnore.addBatch();
}
ps2.executeBatch();
psIgnore.executeBatch();
}
}
// Key config
deleteWhereCharacterId(con, "DELETE FROM keymap WHERE characterid = ?");
ps = con.prepareStatement("INSERT INTO keymap (characterid, `key`, `type`, `action`) VALUES (?, ?, ?, ?)");
ps.setInt(1, id);
try (PreparedStatement psKey = con.prepareStatement("INSERT INTO keymap (characterid, `key`, `type`, `action`) VALUES (?, ?, ?, ?)")) {
psKey.setInt(1, id);
Set<Entry<Integer, MapleKeyBinding>> keybindingItems = Collections.unmodifiableSet(keymap.entrySet());
for (Entry<Integer, MapleKeyBinding> keybinding : keybindingItems) {
ps.setInt(2, keybinding.getKey());
ps.setInt(3, keybinding.getValue().getType());
ps.setInt(4, keybinding.getValue().getAction());
ps.addBatch();
psKey.setInt(2, keybinding.getKey());
psKey.setInt(3, keybinding.getValue().getType());
psKey.setInt(4, keybinding.getValue().getAction());
psKey.addBatch();
}
psKey.executeBatch();
}
ps.executeBatch();
ps.close();
// No quickslots, or no change.
boolean bQuickslotEquals = this.m_pQuickslotKeyMapped == null || (this.m_aQuickslotLoaded != null && Arrays.equals(this.m_pQuickslotKeyMapped.GetKeybindings(), this.m_aQuickslotLoaded));
if (!bQuickslotEquals) {
long nQuickslotKeymapped = LongTool.BytesToLong(this.m_pQuickslotKeyMapped.GetKeybindings());
try (final PreparedStatement pInsertStatement = con.prepareStatement("INSERT INTO quickslotkeymapped (accountid, keymap) VALUES (?, ?) ON DUPLICATE KEY UPDATE keymap = ?;")) {
pInsertStatement.setInt(1, this.getAccountID());
pInsertStatement.setLong(2, nQuickslotKeymapped);
pInsertStatement.setLong(3, nQuickslotKeymapped);
pInsertStatement.executeUpdate();
try (final PreparedStatement psQuick = con.prepareStatement("INSERT INTO quickslotkeymapped (accountid, keymap) VALUES (?, ?) ON DUPLICATE KEY UPDATE keymap = ?;")) {
psQuick.setInt(1, this.getAccountID());
psQuick.setLong(2, nQuickslotKeymapped);
psQuick.setLong(3, nQuickslotKeymapped);
psQuick.executeUpdate();
}
}
// Skill macros
deleteWhereCharacterId(con, "DELETE FROM skillmacros WHERE characterid = ?");
ps = con.prepareStatement("INSERT INTO skillmacros (characterid, skill1, skill2, skill3, name, shout, position) VALUES (?, ?, ?, ?, ?, ?, ?)");
ps.setInt(1, getId());
try (PreparedStatement psMacro = con.prepareStatement("INSERT INTO skillmacros (characterid, skill1, skill2, skill3, name, shout, position) VALUES (?, ?, ?, ?, ?, ?, ?)")) {
psMacro.setInt(1, getId());
for (int i = 0; i < 5; i++) {
SkillMacro macro = skillMacros[i];
if (macro != null) {
ps.setInt(2, macro.getSkill1());
ps.setInt(3, macro.getSkill2());
ps.setInt(4, macro.getSkill3());
ps.setString(5, macro.getName());
ps.setInt(6, macro.getShout());
ps.setInt(7, i);
ps.addBatch();
psMacro.setInt(2, macro.getSkill1());
psMacro.setInt(3, macro.getSkill2());
psMacro.setInt(4, macro.getSkill3());
psMacro.setString(5, macro.getName());
psMacro.setInt(6, macro.getShout());
psMacro.setInt(7, i);
psMacro.addBatch();
}
}
ps.executeBatch();
ps.close();
psMacro.executeBatch();
}
List<Pair<Item, MapleInventoryType>> itemsWithType = new ArrayList<>();
for (MapleInventory iv : inventory) {
@@ -8558,142 +8560,159 @@ public class MapleCharacter extends AbstractMapleCharacterObject {
}
}
// Items
ItemFactory.INVENTORY.saveItems(itemsWithType, id, con);
ps = con.prepareStatement("REPLACE INTO skills (characterid, skillid, skilllevel, masterlevel, expiration) VALUES (?, ?, ?, ?, ?)");
ps.setInt(1, id);
// Skills
try (PreparedStatement psSkill = con.prepareStatement("REPLACE INTO skills (characterid, skillid, skilllevel, masterlevel, expiration) VALUES (?, ?, ?, ?, ?)")) {
psSkill.setInt(1, id);
for (Entry<Skill, SkillEntry> skill : skills.entrySet()) {
ps.setInt(2, skill.getKey().getId());
ps.setInt(3, skill.getValue().skillevel);
ps.setInt(4, skill.getValue().masterlevel);
ps.setLong(5, skill.getValue().expiration);
ps.addBatch();
psSkill.setInt(2, skill.getKey().getId());
psSkill.setInt(3, skill.getValue().skillevel);
psSkill.setInt(4, skill.getValue().masterlevel);
psSkill.setLong(5, skill.getValue().expiration);
psSkill.addBatch();
}
psSkill.executeBatch();
}
ps.executeBatch();
ps.close();
// Saved locations
deleteWhereCharacterId(con, "DELETE FROM savedlocations WHERE characterid = ?");
ps = con.prepareStatement("INSERT INTO savedlocations (characterid, `locationtype`, `map`, `portal`) VALUES (?, ?, ?, ?)");
ps.setInt(1, id);
try (PreparedStatement psLoc = con.prepareStatement("INSERT INTO savedlocations (characterid, `locationtype`, `map`, `portal`) VALUES (?, ?, ?, ?)")) {
psLoc.setInt(1, id);
for (SavedLocationType savedLocationType : SavedLocationType.values()) {
if (savedLocations[savedLocationType.ordinal()] != null) {
ps.setString(2, savedLocationType.name());
ps.setInt(3, savedLocations[savedLocationType.ordinal()].getMapId());
ps.setInt(4, savedLocations[savedLocationType.ordinal()].getPortal());
ps.addBatch();
psLoc.setString(2, savedLocationType.name());
psLoc.setInt(3, savedLocations[savedLocationType.ordinal()].getMapId());
psLoc.setInt(4, savedLocations[savedLocationType.ordinal()].getPortal());
psLoc.addBatch();
}
}
ps.executeBatch();
ps.close();
psLoc.executeBatch();
}
deleteWhereCharacterId(con, "DELETE FROM trocklocations WHERE characterid = ?");
ps = con.prepareStatement("INSERT INTO trocklocations(characterid, mapid, vip) VALUES (?, ?, 0)");
// Vip teleport rocks
try (PreparedStatement psVip = con.prepareStatement("INSERT INTO trocklocations(characterid, mapid, vip) VALUES (?, ?, 0)")) {
for (int i = 0; i < getTrockSize(); i++) {
if (trockmaps.get(i) != 999999999) {
ps.setInt(1, getId());
ps.setInt(2, trockmaps.get(i));
ps.addBatch();
psVip.setInt(1, getId());
psVip.setInt(2, trockmaps.get(i));
psVip.addBatch();
}
}
ps.executeBatch();
ps.close();
psVip.executeBatch();
}
ps = con.prepareStatement("INSERT INTO trocklocations(characterid, mapid, vip) VALUES (?, ?, 1)");
// Regular teleport rocks
try (PreparedStatement psReg = con.prepareStatement("INSERT INTO trocklocations(characterid, mapid, vip) VALUES (?, ?, 1)")) {
for (int i = 0; i < getVipTrockSize(); i++) {
if (viptrockmaps.get(i) != 999999999) {
ps.setInt(1, getId());
ps.setInt(2, viptrockmaps.get(i));
ps.addBatch();
psReg.setInt(1, getId());
psReg.setInt(2, viptrockmaps.get(i));
psReg.addBatch();
}
}
ps.executeBatch();
ps.close();
psReg.executeBatch();
}
// Buddy
deleteWhereCharacterId(con, "DELETE FROM buddies WHERE characterid = ? AND pending = 0");
ps = con.prepareStatement("INSERT INTO buddies (characterid, `buddyid`, `pending`, `group`) VALUES (?, ?, 0, ?)");
ps.setInt(1, id);
try (PreparedStatement psBuddy = con.prepareStatement("INSERT INTO buddies (characterid, `buddyid`, `pending`, `group`) VALUES (?, ?, 0, ?)")) {
psBuddy.setInt(1, id);
for (BuddylistEntry entry : buddylist.getBuddies()) {
if (entry.isVisible()) {
ps.setInt(2, entry.getCharacterId());
ps.setString(3, entry.getGroup());
ps.addBatch();
psBuddy.setInt(2, entry.getCharacterId());
psBuddy.setString(3, entry.getGroup());
psBuddy.addBatch();
}
}
ps.executeBatch();
ps.close();
psBuddy.executeBatch();
}
// Area info
deleteWhereCharacterId(con, "DELETE FROM area_info WHERE charid = ?");
ps = con.prepareStatement("INSERT INTO area_info (id, charid, area, info) VALUES (DEFAULT, ?, ?, ?)");
ps.setInt(1, id);
for (Entry<Short, String> area : area_info.entrySet()) {
ps.setInt(2, area.getKey());
ps.setString(3, area.getValue());
ps.addBatch();
}
ps.executeBatch();
ps.close();
try (PreparedStatement psArea = con.prepareStatement("INSERT INTO area_info (id, charid, area, info) VALUES (DEFAULT, ?, ?, ?)")) {
psArea.setInt(1, id);
for (Entry<Short, String> area : area_info.entrySet()) {
psArea.setInt(2, area.getKey());
psArea.setString(3, area.getValue());
psArea.addBatch();
}
psArea.executeBatch();
}
// Event stats
deleteWhereCharacterId(con, "DELETE FROM eventstats WHERE characterid = ?");
ps = con.prepareStatement("INSERT INTO eventstats (characterid, name, info) VALUES (?, ?, ?)");
ps.setInt(1, id);
try (PreparedStatement psEvent = con.prepareStatement("INSERT INTO eventstats (characterid, name, info) VALUES (?, ?, ?)")) {
psEvent.setInt(1, id);
for (Map.Entry<String, MapleEvents> entry : events.entrySet()) {
ps.setString(2, entry.getKey());
ps.setInt(3, entry.getValue().getInfo());
ps.addBatch();
psEvent.setString(2, entry.getKey());
psEvent.setInt(3, entry.getValue().getInfo());
psEvent.addBatch();
}
ps.executeBatch();
ps.close();
psEvent.executeBatch();
}
deleteQuestProgressWhereCharacterId(con, id);
ps = con.prepareStatement("INSERT INTO queststatus (`queststatusid`, `characterid`, `quest`, `status`, `time`, `expires`, `forfeited`, `completed`) VALUES (DEFAULT, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
PreparedStatement psf;
try (PreparedStatement pse = con.prepareStatement("INSERT INTO questprogress VALUES (DEFAULT, ?, ?, ?, ?)")) {
psf = con.prepareStatement("INSERT INTO medalmaps VALUES (DEFAULT, ?, ?, ?)");
ps.setInt(1, id);
// Quests and medals
try (PreparedStatement psStatus = con.prepareStatement("INSERT INTO queststatus (`queststatusid`, `characterid`, `quest`, `status`, `time`, `expires`, `forfeited`, `completed`) VALUES (DEFAULT, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
PreparedStatement psProgress = con.prepareStatement("INSERT INTO questprogress VALUES (DEFAULT, ?, ?, ?, ?)");
PreparedStatement psMedal = con.prepareStatement("INSERT INTO medalmaps VALUES (DEFAULT, ?, ?, ?)")) {
psStatus.setInt(1, id);
for (MapleQuestStatus qs : getQuests()) {
ps.setInt(2, qs.getQuest().getId());
ps.setInt(3, qs.getStatus().getId());
ps.setInt(4, (int) (qs.getCompletionTime() / 1000));
ps.setLong(5, qs.getExpirationTime());
ps.setInt(6, qs.getForfeited());
ps.setInt(7, qs.getCompleted());
ps.executeUpdate();
try (ResultSet rs = ps.getGeneratedKeys()) {
psStatus.setInt(2, qs.getQuest().getId());
psStatus.setInt(3, qs.getStatus().getId());
psStatus.setInt(4, (int) (qs.getCompletionTime() / 1000));
psStatus.setLong(5, qs.getExpirationTime());
psStatus.setInt(6, qs.getForfeited());
psStatus.setInt(7, qs.getCompleted());
psStatus.executeUpdate();
try (ResultSet rs = psStatus.getGeneratedKeys()) {
rs.next();
for (int mob : qs.getProgress().keySet()) {
pse.setInt(1, id);
pse.setInt(2, rs.getInt(1));
pse.setInt(3, mob);
pse.setString(4, qs.getProgress(mob));
pse.addBatch();
psProgress.setInt(1, id);
psProgress.setInt(2, rs.getInt(1));
psProgress.setInt(3, mob);
psProgress.setString(4, qs.getProgress(mob));
psProgress.addBatch();
}
psProgress.executeBatch();
for (int i = 0; i < qs.getMedalMaps().size(); i++) {
psf.setInt(1, id);
psf.setInt(2, rs.getInt(1));
psf.setInt(3, qs.getMedalMaps().get(i));
psf.addBatch();
psMedal.setInt(1, id);
psMedal.setInt(2, rs.getInt(1));
psMedal.setInt(3, qs.getMedalMaps().get(i));
psMedal.addBatch();
}
pse.executeBatch();
psf.executeBatch();
psMedal.executeBatch();
}
}
}
psf.close();
ps.close();
MapleFamilyEntry familyEntry = getFamilyEntry(); //save family rep
if (familyEntry != null) {
if(familyEntry.saveReputation(con)) familyEntry.savedSuccessfully();
if (familyEntry.saveReputation(con)) {
familyEntry.savedSuccessfully();
}
MapleFamilyEntry senior = familyEntry.getSenior();
if (senior != null && senior.getChr() == null) { //only save for offline family members
if(senior.saveReputation(con)) senior.savedSuccessfully();
if (senior.saveReputation(con)) {
senior.savedSuccessfully();
}
senior = senior.getSenior(); //save one level up as well
if (senior != null && senior.getChr() == null) {
if(senior.saveReputation(con)) senior.savedSuccessfully();
if (senior.saveReputation(con)) {
senior.savedSuccessfully();
}
}
}
@@ -8709,30 +8728,15 @@ public class MapleCharacter extends AbstractMapleCharacterObject {
}
con.commit();
con.setAutoCommit(true); // only commit after finishing all "con" usages, thanks Zygon
} catch (SQLException | RuntimeException t) {
FilePrinter.printError(FilePrinter.SAVE_CHAR, t, "Error saving " + name + " Level: " + level + " Job: " + job.getId());
try {
} catch (Exception e) {
con.rollback();
} catch (SQLException se) {
FilePrinter.printError(FilePrinter.SAVE_CHAR, se, "Error trying to rollback " + name);
throw e;
} finally {
con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
con.setAutoCommit(true);
}
} catch (Exception e) {
FilePrinter.printError(FilePrinter.SAVE_CHAR, e, "Error saving " + name + " Level: " + level + " Job: " + job.getId());
try {
con.rollback(); // thanks Zygon
} catch (SQLException se) {
FilePrinter.printError(FilePrinter.SAVE_CHAR, se, "Error trying to rollback " + name);
}
} finally {
try {
con.setAutoCommit(true);
con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}