diff --git a/src/main/java/client/BuddyList.java b/src/main/java/client/BuddyList.java index b3ecf2a2c4..823b617c93 100644 --- a/src/main/java/client/BuddyList.java +++ b/src/main/java/client/BuddyList.java @@ -141,26 +141,24 @@ public class BuddyList { } public void loadFromDb(int characterId) { - try { - Connection con = DatabaseConnection.getConnection(); - - PreparedStatement ps = con.prepareStatement("SELECT b.buddyid, b.pending, b.group, c.name as buddyname FROM buddies as b, characters as c WHERE c.id = b.buddyid AND b.characterid = ?"); - ps.setInt(1, characterId); - ResultSet rs = ps.executeQuery(); - while (rs.next()) { - if (rs.getInt("pending") == 1) { - pendingRequests.push(new CharacterNameAndId(rs.getInt("buddyid"), rs.getString("buddyname"))); - } else { - put(new BuddylistEntry(rs.getString("buddyname"), rs.getString("group"), rs.getInt("buddyid"), (byte) -1, true)); + try (Connection con = DatabaseConnection.getConnection()) { + try (PreparedStatement ps = con.prepareStatement("SELECT b.buddyid, b.pending, b.group, c.name as buddyname FROM buddies as b, characters as c WHERE c.id = b.buddyid AND b.characterid = ?")) { + ps.setInt(1, characterId); + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + if (rs.getInt("pending") == 1) { + pendingRequests.push(new CharacterNameAndId(rs.getInt("buddyid"), rs.getString("buddyname"))); + } else { + put(new BuddylistEntry(rs.getString("buddyname"), rs.getString("group"), rs.getInt("buddyid"), (byte) -1, true)); + } + } } } - rs.close(); - ps.close(); - ps = con.prepareStatement("DELETE FROM buddies WHERE pending = 1 AND characterid = ?"); - ps.setInt(1, characterId); - ps.executeUpdate(); - ps.close(); - con.close(); + + try (PreparedStatement ps = con.prepareStatement("DELETE FROM buddies WHERE pending = 1 AND characterid = ?")) { + ps.setInt(1, characterId); + ps.executeUpdate(); + } } catch (SQLException ex) { ex.printStackTrace(); } diff --git a/src/main/java/client/MapleCharacter.java b/src/main/java/client/MapleCharacter.java index 081640b84b..f3fc390ed5 100644 --- a/src/main/java/client/MapleCharacter.java +++ b/src/main/java/client/MapleCharacter.java @@ -22,38 +22,22 @@ */ package client; -import java.awt.Point; -import java.lang.ref.WeakReference; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.Stack; -import java.util.Comparator; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.regex.Pattern; - +import client.autoban.AutobanManager; +import client.creator.CharacterFactoryRecipe; +import client.inventory.*; +import client.inventory.Equip.StatUpgrade; +import client.inventory.manipulator.MapleCashidGenerator; +import client.inventory.manipulator.MapleInventoryManipulator; +import client.keybind.MapleKeyBinding; +import client.keybind.MapleQuickslotBinding; +import client.newyear.NewYearCardRecord; +import client.processor.action.PetAutopotProcessor; +import client.processor.npc.FredrickProcessor; import config.YamlConfig; +import constants.game.ExpTable; +import constants.game.GameConstants; +import constants.inventory.ItemConstants; +import constants.skills.*; import net.server.PlayerBuffValueHolder; import net.server.PlayerCoolDownValueHolder; import net.server.Server; @@ -63,25 +47,17 @@ import net.server.coordinator.world.MapleInviteCoordinator; import net.server.guild.MapleAlliance; import net.server.guild.MapleGuild; import net.server.guild.MapleGuildCharacter; -import net.server.world.MapleMessenger; -import net.server.world.MapleMessengerCharacter; -import net.server.world.MapleParty; -import net.server.world.MaplePartyCharacter; -import net.server.world.PartyOperation; -import net.server.world.World; +import net.server.services.task.channel.FaceExpressionService; +import net.server.services.task.world.CharacterSaveService; +import net.server.services.type.ChannelServices; +import net.server.services.type.WorldServices; +import net.server.world.*; +import org.apache.mina.util.ConcurrentHashSet; import scripting.AbstractPlayerInteraction; import scripting.event.EventInstanceManager; import scripting.item.ItemScriptManager; -import server.CashShop; -import server.MapleItemInformationProvider; +import server.*; import server.MapleItemInformationProvider.ScriptedItem; -import server.MapleMarriage; -import server.MapleShop; -import server.MapleStatEffect; -import server.MapleStorage; -import server.MapleTrade; -import server.TimerManager; -import server.ThreadManager; import server.events.MapleEvents; import server.events.RescueGaga; import server.events.gm.MapleFitness; @@ -90,96 +66,30 @@ import server.life.MapleMonster; import server.life.MaplePlayerNPC; import server.life.MobSkill; import server.life.MobSkillFactory; -import server.maps.FieldLimit; -import server.maps.MapleHiredMerchant; -import server.maps.MapleDoor; -import server.maps.MapleDoorObject; -import server.maps.MapleDragon; -import server.maps.MapleMap; -import server.maps.MapleMapEffect; -import server.maps.MapleMapManager; -import server.maps.MapleMapItem; -import server.maps.MapleMapObject; -import server.maps.MapleMapObjectType; -import server.maps.MapleMiniGame; +import server.maps.*; import server.maps.MapleMiniGame.MiniGameResult; -import server.maps.MaplePlayerShop; -import server.maps.MaplePlayerShopItem; -import server.maps.MaplePortal; -import server.maps.MapleSummon; -import server.maps.SavedLocation; -import server.maps.SavedLocationType; import server.minigame.MapleRockPaperScissor; import server.partyquest.AriantColiseum; import server.partyquest.MonsterCarnival; import server.partyquest.MonsterCarnivalParty; import server.partyquest.PartyQuest; import server.quest.MapleQuest; -import tools.DatabaseConnection; -import tools.FilePrinter; -import tools.MaplePacketCreator; -import tools.Pair; -import tools.Randomizer; +import tools.*; import tools.exceptions.NotEnabledException; import tools.packets.Wedding; -import client.autoban.AutobanManager; -import client.creator.CharacterFactoryRecipe; -import client.keybind.MapleKeyBinding; -import client.keybind.MapleQuickslotBinding; -import client.inventory.Equip; -import client.inventory.Equip.StatUpgrade; -import client.inventory.Item; -import client.inventory.ItemFactory; -import client.inventory.MapleInventory; -import client.inventory.MapleInventoryProof; -import client.inventory.MapleInventoryType; -import client.inventory.MaplePet; -import client.inventory.MapleWeaponType; -import client.inventory.ModifyInventory; -import client.inventory.PetDataFactory; -import client.inventory.manipulator.MapleCashidGenerator; -import client.inventory.manipulator.MapleInventoryManipulator; -import client.newyear.NewYearCardRecord; -import client.processor.npc.FredrickProcessor; -import client.processor.action.PetAutopotProcessor; -import constants.game.ExpTable; -import constants.game.GameConstants; -import constants.inventory.ItemConstants; -import constants.skills.Aran; -import constants.skills.Beginner; -import constants.skills.Bishop; -import constants.skills.BlazeWizard; -import constants.skills.Bowmaster; -import constants.skills.Brawler; -import constants.skills.Buccaneer; -import constants.skills.Corsair; -import constants.skills.Crusader; -import constants.skills.DarkKnight; -import constants.skills.DawnWarrior; -import constants.skills.Evan; -import constants.skills.FPArchMage; -import constants.skills.Hermit; -import constants.skills.Hero; -import constants.skills.ILArchMage; -import constants.skills.Legend; -import constants.skills.Magician; -import constants.skills.Marauder; -import constants.skills.Marksman; -import constants.skills.NightLord; -import constants.skills.Noblesse; -import constants.skills.Paladin; -import constants.skills.Priest; -import constants.skills.Ranger; -import constants.skills.Shadower; -import constants.skills.Sniper; -import constants.skills.Warrior; -import constants.skills.ThunderBreaker; -import net.server.services.type.ChannelServices; -import net.server.services.task.channel.FaceExpressionService; -import net.server.services.task.world.CharacterSaveService; -import net.server.services.type.WorldServices; -import org.apache.mina.util.ConcurrentHashSet; -import tools.LongTool; + +import java.awt.*; +import java.lang.ref.WeakReference; +import java.sql.*; +import java.time.LocalDateTime; +import java.util.List; +import java.util.*; +import java.util.Map.Entry; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.Lock; +import java.util.regex.Pattern; public class MapleCharacter extends AbstractMapleCharacterObject { private static final MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance(); @@ -731,76 +641,51 @@ public class MapleCharacter extends AbstractMapleCharacterObject { public void ban(String reason) { this.isbanned = true; - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("UPDATE accounts SET banned = 1, banreason = ? WHERE id = ?")) { - ps.setString(1, reason); - ps.setInt(2, accountid); - ps.executeUpdate(); - } - con.close(); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE accounts SET banned = 1, banreason = ? WHERE id = ?")) { + ps.setString(1, reason); + ps.setInt(2, accountid); + ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } - } public static boolean ban(String id, String reason, boolean accountId) { - PreparedStatement ps = null; - ResultSet rs = null; - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - + try (Connection con = DatabaseConnection.getConnection()) { if (id.matches("/[0-9]{1,3}\\..*")) { - ps = con.prepareStatement("INSERT INTO ipbans VALUES (DEFAULT, ?)"); - ps.setString(1, id); - ps.executeUpdate(); - ps.close(); - return true; + try (PreparedStatement ps = con.prepareStatement("INSERT INTO ipbans VALUES (DEFAULT, ?)")) { + ps.setString(1, id); + ps.executeUpdate(); + return true; + } } + + final String query; if (accountId) { - ps = con.prepareStatement("SELECT id FROM accounts WHERE name = ?"); + query = "SELECT id FROM accounts WHERE name = ?"; } else { - ps = con.prepareStatement("SELECT accountid FROM characters WHERE name = ?"); + query ="SELECT accountid FROM characters WHERE name = ?"; } boolean ret = false; - ps.setString(1, id); - rs = ps.executeQuery(); - if (rs.next()) { - Connection con2 = DatabaseConnection.getConnection(); + try (PreparedStatement ps = con.prepareStatement(query)) { + ps.setString(1, id); - try (PreparedStatement psb = con2.prepareStatement("UPDATE accounts SET banned = 1, banreason = ? WHERE id = ?")) { - psb.setString(1, reason); - psb.setInt(2, rs.getInt(1)); - psb.executeUpdate(); - } finally { - con2.close(); + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + try (PreparedStatement ps2 = con.prepareStatement("UPDATE accounts SET banned = 1, banreason = ? WHERE id = ?")) { + ps2.setString(1, reason); + ps2.setInt(2, rs.getInt(1)); + ps2.executeUpdate(); + } + ret = true; } - ret = true; + } } - - rs.close(); - ps.close(); - con.close(); return ret; } catch (SQLException ex) { ex.printStackTrace(); - } finally { - try { - if (ps != null && !ps.isClosed()) { - ps.close(); - } - if (rs != null && !rs.isClosed()) { - rs.close(); - } - if (con != null && !con.isClosed()) { - con.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } } return false; } @@ -1335,18 +1220,18 @@ public class MapleCharacter extends AbstractMapleCharacterObject { public void broadcastStance() { map.broadcastMessage(this, MaplePacketCreator.movePlayer(id, this.getIdleMovement(), getIdleMovementDataLength()), false); } - + public MapleMap getWarpMap(int map) { - MapleMap warpMap; + MapleMap warpMap; EventInstanceManager eim = getEventInstance(); - if (eim != null) { + if (eim != null) { warpMap = eim.getMapInstance(map); } else if (this.getMonsterCarnival() != null && this.getMonsterCarnival().getEventMap().getId() == map) { warpMap = this.getMonsterCarnival().getEventMap(); - } else { + } else { warpMap = client.getChannelServer().getMapFactory().getMap(map); - } - return warpMap; + } + return warpMap; } // for use ONLY inside OnUserEnter map scripts that requires a player to change map while still moving between maps. @@ -1877,15 +1762,11 @@ public class MapleCharacter extends AbstractMapleCharacterObject { } else { skills.remove(skill); this.client.announce(MaplePacketCreator.updateSkill(skill.getId(), newLevel, newMasterlevel, -1)); //Shouldn't use expiration anymore :) - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("DELETE FROM skills WHERE skillid = ? AND characterid = ?")) { - ps.setInt(1, skill.getId()); - ps.setInt(2, id); - ps.execute(); - } finally { - con.close(); - } + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("DELETE FROM skills WHERE skillid = ? AND characterid = ?")) { + ps.setInt(1, skill.getId()); + ps.setInt(2, id); + ps.executeUpdate(); } catch (SQLException ex) { ex.printStackTrace(); } @@ -2216,19 +2097,14 @@ public class MapleCharacter extends AbstractMapleCharacterObject { } public void deleteGuild(int guildId) { - try { - Connection con = DatabaseConnection.getConnection(); - try { - try (PreparedStatement ps = con.prepareStatement("UPDATE characters SET guildid = 0, guildrank = 5 WHERE guildid = ?")) { - ps.setInt(1, guildId); - ps.execute(); - } - try (PreparedStatement ps = con.prepareStatement("DELETE FROM guilds WHERE guildid = ?")) { - ps.setInt(1, id); - ps.execute(); - } - } finally { - con.close(); + try (Connection con = DatabaseConnection.getConnection()) { + try (PreparedStatement ps = con.prepareStatement("UPDATE characters SET guildid = 0, guildrank = 5 WHERE guildid = ?")) { + ps.setInt(1, guildId); + ps.executeUpdate(); + } + try (PreparedStatement ps = con.prepareStatement("DELETE FROM guilds WHERE guildid = ?")) { + ps.setInt(1, id); + ps.executeUpdate(); } } catch (SQLException ex) { ex.printStackTrace(); @@ -2261,188 +2137,192 @@ public class MapleCharacter extends AbstractMapleCharacterObject { } public static boolean deleteCharFromDB(MapleCharacter player, int senderAccId) { - int cid = player.getId(); - if(!Server.getInstance().haveCharacterEntry(senderAccId, cid)) { // thanks zera (EpiphanyMS) for pointing a critical exploit with non-authed character deletion request - return false; + int cid = player.getId(); + if (!Server.getInstance().haveCharacterEntry(senderAccId, cid)) { // thanks zera (EpiphanyMS) for pointing a critical exploit with non-authed character deletion request + return false; + } + + final int accId = senderAccId; + int world = 0; + try (Connection con = DatabaseConnection.getConnection()) { + try (PreparedStatement ps = con.prepareStatement("SELECT world FROM characters WHERE id = ?")) { + ps.setInt(1, cid); + + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + world = rs.getInt("world"); + } + } } - - int accId = senderAccId, world = 0; - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - - try (PreparedStatement ps = con.prepareStatement("SELECT world FROM characters WHERE id = ?")) { - ps.setInt(1, cid); - try (ResultSet rs = ps.executeQuery()) { - if(rs.next()) { - world = rs.getInt("world"); - } - } - } - - try (PreparedStatement ps = con.prepareStatement("SELECT buddyid FROM buddies WHERE characterid = ?")) { - ps.setInt(1, cid); + try (PreparedStatement ps = con.prepareStatement("SELECT buddyid FROM buddies WHERE characterid = ?")) { + ps.setInt(1, cid); - try (ResultSet rs = ps.executeQuery()) { - while(rs.next()) { - int buddyid = rs.getInt("buddyid"); - MapleCharacter buddy = Server.getInstance().getWorld(world).getPlayerStorage().getCharacterById(buddyid); - - if(buddy != null) { - buddy.deleteBuddy(cid); - } - } - } - } - try (PreparedStatement ps = con.prepareStatement("DELETE FROM buddies WHERE characterid = ?")) { - ps.setInt(1, cid); - ps.executeUpdate(); - } - - try (PreparedStatement ps = con.prepareStatement("SELECT threadid FROM bbs_threads WHERE postercid = ?")) { - ps.setInt(1, cid); - - try (ResultSet rs = ps.executeQuery()) { - while (rs.next()) { - int tid = rs.getInt("threadid"); - - try (PreparedStatement ps2 = con.prepareStatement("DELETE FROM bbs_replies WHERE threadid = ?")) { - ps2.setInt(1, tid); - ps2.executeUpdate(); - } - } - } - } - try (PreparedStatement ps = con.prepareStatement("DELETE FROM bbs_threads WHERE postercid = ?")) { - ps.setInt(1, cid); - ps.executeUpdate(); - } - - try (PreparedStatement ps = con.prepareStatement("SELECT id, guildid, guildrank, name, allianceRank FROM characters WHERE id = ? AND accountid = ?")) { - ps.setInt(1, cid); - ps.setInt(2, accId); - try (ResultSet rs = ps.executeQuery()) { - if (rs.next() && rs.getInt("guildid") > 0) { - Server.getInstance().deleteGuildCharacter(new MapleGuildCharacter(player, cid, 0, rs.getString("name"), (byte) -1, (byte) -1, 0, rs.getInt("guildrank"), rs.getInt("guildid"), false, rs.getInt("allianceRank"))); - } - } - } - - if (con.isClosed()) { //wtf tho - con = DatabaseConnection.getConnection(); - } + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + int buddyid = rs.getInt("buddyid"); + MapleCharacter buddy = Server.getInstance().getWorld(world).getPlayerStorage().getCharacterById(buddyid); - try (PreparedStatement ps = con.prepareStatement("DELETE FROM wishlists WHERE charid = ?")) { - ps.setInt(1, cid); - ps.executeUpdate(); + if (buddy != null) { + buddy.deleteBuddy(cid); + } } - try (PreparedStatement ps = con.prepareStatement("DELETE FROM cooldowns WHERE charid = ?")) { - ps.setInt(1, cid); - ps.executeUpdate(); - } - try (PreparedStatement ps = con.prepareStatement("DELETE FROM playerdiseases WHERE charid = ?")) { - ps.setInt(1, cid); - ps.executeUpdate(); - } - try (PreparedStatement ps = con.prepareStatement("DELETE FROM area_info WHERE charid = ?")) { - ps.setInt(1, cid); - ps.executeUpdate(); - } - try (PreparedStatement ps = con.prepareStatement("DELETE FROM monsterbook WHERE charid = ?")) { - ps.setInt(1, cid); - ps.executeUpdate(); - } - try (PreparedStatement ps = con.prepareStatement("DELETE FROM characters WHERE id = ?")) { - ps.setInt(1, cid); - ps.executeUpdate(); - } - try (PreparedStatement ps = con.prepareStatement("DELETE FROM family_character WHERE cid = ?")) { - ps.setInt(1, cid); - ps.executeUpdate(); - } - try (PreparedStatement ps = con.prepareStatement("DELETE FROM famelog WHERE characterid_to = ?")) { - ps.setInt(1, cid); - ps.executeUpdate(); - } - - try (PreparedStatement ps = con.prepareStatement("SELECT inventoryitemid, petid FROM inventoryitems WHERE characterid = ?")) { - ps.setInt(1, cid); - - try (ResultSet rs = ps.executeQuery()) { - while (rs.next()) { - int inventoryitemid = rs.getInt("inventoryitemid"); - - try (PreparedStatement ps2 = con.prepareStatement("SELECT ringid FROM inventoryequipment WHERE inventoryitemid = ?")) { - ps2.setInt(1, inventoryitemid); - - try (ResultSet rs2 = ps2.executeQuery()) { - while (rs2.next()) { - int ringid = rs2.getInt("ringid"); - - if(ringid > -1) { - try (PreparedStatement ps3 = con.prepareStatement("DELETE FROM rings WHERE id = ?")) { - ps3.setInt(1, ringid); - ps3.executeUpdate(); - } - - MapleCashidGenerator.freeCashId(ringid); - } - } - } - } - - try (PreparedStatement ps2 = con.prepareStatement("DELETE FROM inventoryequipment WHERE inventoryitemid = ?")) { - ps2.setInt(1, inventoryitemid); - ps2.executeUpdate(); - } - - int petid = rs.getInt("petid"); - if(!rs.wasNull()) { - try (PreparedStatement ps2 = con.prepareStatement("DELETE FROM pets WHERE petid = ?")) { - ps2.setInt(1, petid); - ps2.executeUpdate(); - } - MapleCashidGenerator.freeCashId(petid); - } - } - } - } - - deleteQuestProgressWhereCharacterId(con, cid); - FredrickProcessor.removeFredrickLog(cid); // thanks maple006 for pointing out the player's Fredrick items are not being deleted at character deletion - - try (PreparedStatement ps = con.prepareStatement("SELECT id FROM mts_cart WHERE cid = ?")) { - ps.setInt(1, cid); - - try (ResultSet rs = ps.executeQuery()) { - while (rs.next()) { - int mtsid = rs.getInt("id"); - - try (PreparedStatement ps2 = con.prepareStatement("DELETE FROM mts_items WHERE id = ?")) { - ps2.setInt(1, mtsid); - ps2.executeUpdate(); - } - } - } - } - try (PreparedStatement ps = con.prepareStatement("DELETE FROM mts_cart WHERE cid = ?")) { - ps.setInt(1, cid); - ps.executeUpdate(); - } - - String[] toDel = {"famelog", "inventoryitems", "keymap", "queststatus", "savedlocations", "trocklocations", "skillmacros", "skills", "eventstats", "server_queue"}; - for (String s : toDel) { - MapleCharacter.deleteWhereCharacterId(con, "DELETE FROM `" + s + "` WHERE characterid = ?", cid); - } - - con.close(); - Server.getInstance().deleteCharacterEntry(accId, cid); - return true; - } catch (SQLException e) { - e.printStackTrace(); - return false; + } } + + try (PreparedStatement ps = con.prepareStatement("DELETE FROM buddies WHERE characterid = ?")) { + ps.setInt(1, cid); + ps.executeUpdate(); + } + + try (PreparedStatement ps = con.prepareStatement("SELECT threadid FROM bbs_threads WHERE postercid = ?")) { + ps.setInt(1, cid); + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + int threadId = rs.getInt("threadid"); + + try (PreparedStatement ps2 = con.prepareStatement("DELETE FROM bbs_replies WHERE threadid = ?")) { + ps2.setInt(1, threadId); + ps2.executeUpdate(); + } + } + } + } + + try (PreparedStatement ps = con.prepareStatement("DELETE FROM bbs_threads WHERE postercid = ?")) { + ps.setInt(1, cid); + ps.executeUpdate(); + } + + try (PreparedStatement ps = con.prepareStatement("SELECT id, guildid, guildrank, name, allianceRank FROM characters WHERE id = ? AND accountid = ?")) { + ps.setInt(1, cid); + ps.setInt(2, accId); + + try (ResultSet rs = ps.executeQuery()) { + if (rs.next() && rs.getInt("guildid") > 0) { + Server.getInstance().deleteGuildCharacter(new MapleGuildCharacter(player, cid, 0, rs.getString("name"), (byte) -1, (byte) -1, 0, rs.getInt("guildrank"), rs.getInt("guildid"), false, rs.getInt("allianceRank"))); + } + } + } + + try (PreparedStatement ps = con.prepareStatement("DELETE FROM wishlists WHERE charid = ?")) { + ps.setInt(1, cid); + ps.executeUpdate(); + } + + try (PreparedStatement ps = con.prepareStatement("DELETE FROM cooldowns WHERE charid = ?")) { + ps.setInt(1, cid); + ps.executeUpdate(); + } + + try (PreparedStatement ps = con.prepareStatement("DELETE FROM playerdiseases WHERE charid = ?")) { + ps.setInt(1, cid); + ps.executeUpdate(); + } + + try (PreparedStatement ps = con.prepareStatement("DELETE FROM area_info WHERE charid = ?")) { + ps.setInt(1, cid); + ps.executeUpdate(); + } + + try (PreparedStatement ps = con.prepareStatement("DELETE FROM monsterbook WHERE charid = ?")) { + ps.setInt(1, cid); + ps.executeUpdate(); + } + + try (PreparedStatement ps = con.prepareStatement("DELETE FROM characters WHERE id = ?")) { + ps.setInt(1, cid); + ps.executeUpdate(); + } + + try (PreparedStatement ps = con.prepareStatement("DELETE FROM family_character WHERE cid = ?")) { + ps.setInt(1, cid); + ps.executeUpdate(); + } + + try (PreparedStatement ps = con.prepareStatement("DELETE FROM famelog WHERE characterid_to = ?")) { + ps.setInt(1, cid); + ps.executeUpdate(); + } + + try (PreparedStatement ps = con.prepareStatement("SELECT inventoryitemid, petid FROM inventoryitems WHERE characterid = ?")) { + ps.setInt(1, cid); + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + int inventoryitemid = rs.getInt("inventoryitemid"); + + try (PreparedStatement ps2 = con.prepareStatement("SELECT ringid FROM inventoryequipment WHERE inventoryitemid = ?")) { + ps2.setInt(1, inventoryitemid); + + try (ResultSet rs2 = ps2.executeQuery()) { + while (rs2.next()) { + final int ringid = rs2.getInt("ringid"); + + if (ringid > -1) { + try (PreparedStatement ps3 = con.prepareStatement("DELETE FROM rings WHERE id = ?")) { + ps3.setInt(1, ringid); + ps3.executeUpdate(); + } + + MapleCashidGenerator.freeCashId(ringid); + } + } + } + } + + try (PreparedStatement ps2 = con.prepareStatement("DELETE FROM inventoryequipment WHERE inventoryitemid = ?")) { + ps2.setInt(1, inventoryitemid); + ps2.executeUpdate(); + } + + final int petid = rs.getInt("petid"); + if (!rs.wasNull()) { + try (PreparedStatement ps2 = con.prepareStatement("DELETE FROM pets WHERE petid = ?")) { + ps2.setInt(1, petid); + ps2.executeUpdate(); + } + MapleCashidGenerator.freeCashId(petid); + } + } + } + } + + deleteQuestProgressWhereCharacterId(con, cid); + FredrickProcessor.removeFredrickLog(cid); // thanks maple006 for pointing out the player's Fredrick items are not being deleted at character deletion + + try (PreparedStatement ps = con.prepareStatement("SELECT id FROM mts_cart WHERE cid = ?")) { + ps.setInt(1, cid); + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + final int mtsid = rs.getInt("id"); + + try (PreparedStatement ps2 = con.prepareStatement("DELETE FROM mts_items WHERE id = ?")) { + ps2.setInt(1, mtsid); + ps2.executeUpdate(); + } + } + } + } + + try (PreparedStatement ps = con.prepareStatement("DELETE FROM mts_cart WHERE cid = ?")) { + ps.setInt(1, cid); + ps.executeUpdate(); + } + + String[] toDel = {"famelog", "inventoryitems", "keymap", "queststatus", "savedlocations", "trocklocations", "skillmacros", "skills", "eventstats", "server_queue"}; + for (String s : toDel) { + MapleCharacter.deleteWhereCharacterId(con, "DELETE FROM `" + s + "` WHERE characterid = ?", cid); + } + + Server.getInstance().deleteCharacterEntry(accId, cid); + return true; + } catch (SQLException e) { + e.printStackTrace(); + return false; + } } private static void deleteQuestProgressWhereCharacterId(Connection con, int cid) throws SQLException { @@ -3390,24 +3270,18 @@ public class MapleCharacter extends AbstractMapleCharacterObject { public static Map getCharacterFromDatabase(String name) { Map character = new LinkedHashMap<>(); - try { - Connection con = DatabaseConnection.getConnection(); - - try (PreparedStatement ps = con.prepareStatement("SELECT `id`, `accountid`, `name` FROM `characters` WHERE `name` = ?")) { - ps.setString(1, name); - try (ResultSet rs = ps.executeQuery()) { - if (!rs.next()) { - rs.close(); - ps.close(); - return null; - } + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT `id`, `accountid`, `name` FROM `characters` WHERE `name` = ?")) { + ps.setString(1, name); - for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { - character.put(rs.getMetaData().getColumnLabel(i), rs.getString(i)); - } + try (ResultSet rs = ps.executeQuery()) { + if (!rs.next()) { + return null; + } + + for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { + character.put(rs.getMetaData().getColumnLabel(i), rs.getString(i)); } - } finally { - con.close(); } } catch (SQLException sqle) { sqle.printStackTrace(); @@ -5162,22 +5036,15 @@ public class MapleCharacter extends AbstractMapleCharacterObject { } public static int getAccountIdByName(String name) { - try { - int id; - Connection con = DatabaseConnection.getConnection(); - - try (PreparedStatement ps = con.prepareStatement("SELECT accountid FROM characters WHERE name = ?")) { - ps.setString(1, name); - try (ResultSet rs = ps.executeQuery()) { - if (!rs.next()) { - rs.close(); - ps.close(); - return -1; - } - id = rs.getInt("accountid"); + final int id; + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT accountid FROM characters WHERE name = ?")) { + ps.setString(1, name); + try (ResultSet rs = ps.executeQuery()) { + if (!rs.next()) { + return -1; } - } finally { - con.close(); + id = rs.getInt("accountid"); } return id; } catch (Exception e) { @@ -5187,21 +5054,15 @@ public class MapleCharacter extends AbstractMapleCharacterObject { } public static int getIdByName(String name) { - try { - int id; - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("SELECT id FROM characters WHERE name = ?")) { - ps.setString(1, name); - try (ResultSet rs = ps.executeQuery()) { - if (!rs.next()) { - rs.close(); - ps.close(); - return -1; - } - id = rs.getInt("id"); + final int id; + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT id FROM characters WHERE name = ?")) { + ps.setString(1, name); + try (ResultSet rs = ps.executeQuery()) { + if (!rs.next()) { + return -1; } - } finally { - con.close(); + id = rs.getInt("id"); } return id; } catch (Exception e) { @@ -5211,21 +5072,15 @@ public class MapleCharacter extends AbstractMapleCharacterObject { } public static String getNameById(int id) { - try { - String name; - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("SELECT name FROM characters WHERE id = ?")) { - ps.setInt(1, id); - try (ResultSet rs = ps.executeQuery()) { - if (!rs.next()) { - rs.close(); - ps.close(); - return null; - } - name = rs.getString("name"); + final String name; + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT name FROM characters WHERE id = ?")) { + ps.setInt(1, id); + try (ResultSet rs = ps.executeQuery()) { + if (!rs.next()) { + return null; } - } finally { - con.close(); + name = rs.getString("name"); } return name; } catch (Exception e) { @@ -5398,26 +5253,24 @@ public class MapleCharacter extends AbstractMapleCharacterObject { public int getMerchantNetMeso() { int elapsedDays = 0; - - try { - Connection con = DatabaseConnection.getConnection(); - - try (PreparedStatement ps = con.prepareStatement("SELECT `timestamp` FROM `fredstorage` WHERE `cid` = ?")) { - ps.setInt(1, id); - try (ResultSet rs = ps.executeQuery()) { - if (rs.next()) { - elapsedDays = FredrickProcessor.timestampElapsedDays(rs.getTimestamp(1), System.currentTimeMillis()); - } + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT `timestamp` FROM `fredstorage` WHERE `cid` = ?")) { + ps.setInt(1, id); + + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + elapsedDays = FredrickProcessor.timestampElapsedDays(rs.getTimestamp(1), System.currentTimeMillis()); } } - - con.close(); } catch (SQLException e) { e.printStackTrace(); } - - if (elapsedDays > 100) elapsedDays = 100; - + + if (elapsedDays > 100) { + elapsedDays = 100; + } + long netMeso = (long) merchantmeso; // negative mesos issues found thanks to Flash, Vcoc netMeso = (netMeso * (100 - elapsedDays)) / 100; return (int) netMeso; @@ -6147,15 +6000,11 @@ public class MapleCharacter extends AbstractMapleCharacterObject { public void hasGivenFame(MapleCharacter to) { lastfametime = System.currentTimeMillis(); lastmonthfameids.add(Integer.valueOf(to.getId())); - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("INSERT INTO famelog (characterid, characterid_to) VALUES (?, ?)")) { - ps.setInt(1, getId()); - ps.setInt(2, to.getId()); - ps.executeUpdate(); - } finally { - con.close(); - } + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("INSERT INTO famelog (characterid, characterid_to) VALUES (?, ?)")) { + ps.setInt(1, getId()); + ps.setInt(2, to.getId()); + ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } @@ -7092,423 +6941,478 @@ public class MapleCharacter extends AbstractMapleCharacterObject { updateRemainingSp(remainingSp, GameConstants.getSkillBook(job.getId())); } - public static MapleCharacter loadCharFromDB(int charid, MapleClient client, boolean channelserver) throws SQLException { - try { - MapleCharacter ret = new MapleCharacter(); - ret.client = client; - ret.id = charid; - - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT * FROM characters WHERE id = ?"); - ps.setInt(1, charid); - ResultSet rs = ps.executeQuery(); - if (!rs.next()) { - rs.close(); - ps.close(); - throw new RuntimeException("Loading char failed (not found)"); - } - ret.name = rs.getString("name"); - ret.level = rs.getInt("level"); - ret.fame = rs.getInt("fame"); - ret.quest_fame = rs.getInt("fquest"); - ret.str = rs.getInt("str"); - ret.dex = rs.getInt("dex"); - ret.int_ = rs.getInt("int"); - ret.luk = rs.getInt("luk"); - ret.exp.set(rs.getInt("exp")); - ret.gachaexp.set(rs.getInt("gachaexp")); - ret.hp = rs.getInt("hp"); - ret.setMaxHp(rs.getInt("maxhp")); - ret.mp = rs.getInt("mp"); - ret.setMaxMp(rs.getInt("maxmp")); - ret.hpMpApUsed = rs.getInt("hpMpUsed"); - ret.hasMerchant = rs.getInt("HasMerchant") == 1; - ret.remainingAp = rs.getInt("ap"); - ret.loadCharSkillPoints(rs.getString("sp").split(",")); - ret.meso.set(rs.getInt("meso")); - ret.merchantmeso = rs.getInt("MerchantMesos"); - ret.setGMLevel(rs.getInt("gm")); - ret.skinColor = MapleSkinColor.getById(rs.getInt("skincolor")); - ret.gender = rs.getInt("gender"); - ret.job = MapleJob.getById(rs.getInt("job")); - ret.finishedDojoTutorial = rs.getInt("finishedDojoTutorial") == 1; - ret.vanquisherKills = rs.getInt("vanquisherKills"); - ret.omokwins = rs.getInt("omokwins"); - ret.omoklosses = rs.getInt("omoklosses"); - ret.omokties = rs.getInt("omokties"); - ret.matchcardwins = rs.getInt("matchcardwins"); - ret.matchcardlosses = rs.getInt("matchcardlosses"); - ret.matchcardties = rs.getInt("matchcardties"); - ret.hair = rs.getInt("hair"); - ret.face = rs.getInt("face"); - ret.accountid = rs.getInt("accountid"); - ret.mapid = rs.getInt("map"); - ret.jailExpiration = rs.getLong("jailexpire"); - ret.initialSpawnPoint = rs.getInt("spawnpoint"); - ret.world = rs.getByte("world"); - ret.rank = rs.getInt("rank"); - ret.rankMove = rs.getInt("rankMove"); - ret.jobRank = rs.getInt("jobRank"); - ret.jobRankMove = rs.getInt("jobRankMove"); - int mountexp = rs.getInt("mountexp"); - int mountlevel = rs.getInt("mountlevel"); - int mounttiredness = rs.getInt("mounttiredness"); - ret.guildid = rs.getInt("guildid"); - ret.guildRank = rs.getInt("guildrank"); - ret.allianceRank = rs.getInt("allianceRank"); - ret.familyId = rs.getInt("familyId"); - ret.bookCover = rs.getInt("monsterbookcover"); - ret.monsterbook = new MonsterBook(); - ret.monsterbook.loadCards(charid); - ret.vanquisherStage = rs.getInt("vanquisherStage"); - ret.ariantPoints = rs.getInt("ariantPoints"); - ret.dojoPoints = rs.getInt("dojoPoints"); - ret.dojoStage = rs.getInt("lastDojoStage"); - ret.dataString = rs.getString("dataString"); - ret.mgc = new MapleGuildCharacter(ret); - int buddyCapacity = rs.getInt("buddyCapacity"); - ret.buddylist = new BuddyList(buddyCapacity); - ret.lastExpGainTime = rs.getTimestamp("lastExpGainTime").getTime(); - ret.canRecvPartySearchInvite = rs.getBoolean("partySearch"); - - ret.getInventory(MapleInventoryType.EQUIP).setSlotLimit(rs.getByte("equipslots")); - ret.getInventory(MapleInventoryType.USE).setSlotLimit(rs.getByte("useslots")); - ret.getInventory(MapleInventoryType.SETUP).setSlotLimit(rs.getByte("setupslots")); - ret.getInventory(MapleInventoryType.ETC).setSlotLimit(rs.getByte("etcslots")); - - short sandboxCheck = 0x0; - for (Pair item : ItemFactory.INVENTORY.loadItems(ret.id, !channelserver)) { - sandboxCheck |= item.getLeft().getFlag(); - - ret.getInventory(item.getRight()).addItemFromDB(item.getLeft()); - Item itemz = item.getLeft(); - if (itemz.getPetId() > -1) { - MaplePet pet = itemz.getPet(); - if (pet != null && pet.isSummoned()) { - ret.addPet(pet); + public static MapleCharacter loadCharFromDB(final int charid, MapleClient client, boolean channelserver) throws SQLException { + MapleCharacter ret = new MapleCharacter(); + ret.client = client; + ret.id = charid; + + try (Connection con = DatabaseConnection.getConnection()) { + final int mountexp; + final int mountlevel; + final int mounttiredness; + final World wserv; + + // Character info + try (PreparedStatement ps = con.prepareStatement("SELECT * FROM characters WHERE id = ?")) { + ps.setInt(1, charid); + + try (ResultSet rs = ps.executeQuery()) { + if (!rs.next()) { + throw new RuntimeException("Loading char failed (not found)"); } - continue; - } - - MapleInventoryType mit = item.getRight(); - if (mit.equals(MapleInventoryType.EQUIP) || mit.equals(MapleInventoryType.EQUIPPED)) { - Equip equip = (Equip) item.getLeft(); - if (equip.getRingId() > -1) { - MapleRing ring = MapleRing.loadFromDb(equip.getRingId()); - if (item.getRight().equals(MapleInventoryType.EQUIPPED)) { - ring.equip(); + + ret.name = rs.getString("name"); + ret.level = rs.getInt("level"); + ret.fame = rs.getInt("fame"); + ret.quest_fame = rs.getInt("fquest"); + ret.str = rs.getInt("str"); + ret.dex = rs.getInt("dex"); + ret.int_ = rs.getInt("int"); + ret.luk = rs.getInt("luk"); + ret.exp.set(rs.getInt("exp")); + ret.gachaexp.set(rs.getInt("gachaexp")); + ret.hp = rs.getInt("hp"); + ret.setMaxHp(rs.getInt("maxhp")); + ret.mp = rs.getInt("mp"); + ret.setMaxMp(rs.getInt("maxmp")); + ret.hpMpApUsed = rs.getInt("hpMpUsed"); + ret.hasMerchant = rs.getInt("HasMerchant") == 1; + ret.remainingAp = rs.getInt("ap"); + ret.loadCharSkillPoints(rs.getString("sp").split(",")); + ret.meso.set(rs.getInt("meso")); + ret.merchantmeso = rs.getInt("MerchantMesos"); + ret.setGMLevel(rs.getInt("gm")); + ret.skinColor = MapleSkinColor.getById(rs.getInt("skincolor")); + ret.gender = rs.getInt("gender"); + ret.job = MapleJob.getById(rs.getInt("job")); + ret.finishedDojoTutorial = rs.getInt("finishedDojoTutorial") == 1; + ret.vanquisherKills = rs.getInt("vanquisherKills"); + ret.omokwins = rs.getInt("omokwins"); + ret.omoklosses = rs.getInt("omoklosses"); + ret.omokties = rs.getInt("omokties"); + ret.matchcardwins = rs.getInt("matchcardwins"); + ret.matchcardlosses = rs.getInt("matchcardlosses"); + ret.matchcardties = rs.getInt("matchcardties"); + ret.hair = rs.getInt("hair"); + ret.face = rs.getInt("face"); + ret.accountid = rs.getInt("accountid"); + ret.mapid = rs.getInt("map"); + ret.jailExpiration = rs.getLong("jailexpire"); + ret.initialSpawnPoint = rs.getInt("spawnpoint"); + ret.world = rs.getByte("world"); + ret.rank = rs.getInt("rank"); + ret.rankMove = rs.getInt("rankMove"); + ret.jobRank = rs.getInt("jobRank"); + ret.jobRankMove = rs.getInt("jobRankMove"); + mountexp = rs.getInt("mountexp"); + mountlevel = rs.getInt("mountlevel"); + mounttiredness = rs.getInt("mounttiredness"); + ret.guildid = rs.getInt("guildid"); + ret.guildRank = rs.getInt("guildrank"); + ret.allianceRank = rs.getInt("allianceRank"); + ret.familyId = rs.getInt("familyId"); + ret.bookCover = rs.getInt("monsterbookcover"); + ret.monsterbook = new MonsterBook(); + ret.monsterbook.loadCards(charid); + ret.vanquisherStage = rs.getInt("vanquisherStage"); + ret.ariantPoints = rs.getInt("ariantPoints"); + ret.dojoPoints = rs.getInt("dojoPoints"); + ret.dojoStage = rs.getInt("lastDojoStage"); + ret.dataString = rs.getString("dataString"); + ret.mgc = new MapleGuildCharacter(ret); + int buddyCapacity = rs.getInt("buddyCapacity"); + ret.buddylist = new BuddyList(buddyCapacity); + ret.lastExpGainTime = rs.getTimestamp("lastExpGainTime").getTime(); + ret.canRecvPartySearchInvite = rs.getBoolean("partySearch"); + + wserv = Server.getInstance().getWorld(ret.world); + + ret.getInventory(MapleInventoryType.EQUIP).setSlotLimit(rs.getByte("equipslots")); + ret.getInventory(MapleInventoryType.USE).setSlotLimit(rs.getByte("useslots")); + ret.getInventory(MapleInventoryType.SETUP).setSlotLimit(rs.getByte("setupslots")); + ret.getInventory(MapleInventoryType.ETC).setSlotLimit(rs.getByte("etcslots")); + + short sandboxCheck = 0x0; + for (Pair item : ItemFactory.INVENTORY.loadItems(ret.id, !channelserver)) { + sandboxCheck |= item.getLeft().getFlag(); + + ret.getInventory(item.getRight()).addItemFromDB(item.getLeft()); + Item itemz = item.getLeft(); + if (itemz.getPetId() > -1) { + MaplePet pet = itemz.getPet(); + if (pet != null && pet.isSummoned()) { + ret.addPet(pet); + } + continue; } - - ret.addPlayerRing(ring); + + MapleInventoryType mit = item.getRight(); + if (mit.equals(MapleInventoryType.EQUIP) || mit.equals(MapleInventoryType.EQUIPPED)) { + Equip equip = (Equip) item.getLeft(); + if (equip.getRingId() > -1) { + MapleRing ring = MapleRing.loadFromDb(equip.getRingId()); + if (item.getRight().equals(MapleInventoryType.EQUIPPED)) { + ring.equip(); + } + + ret.addPlayerRing(ring); + } + } + } + + if ((sandboxCheck & ItemConstants.SANDBOX) == ItemConstants.SANDBOX) { + ret.setHasSandboxItem(); + } + + ret.partnerId = rs.getInt("partnerId"); + ret.marriageItemid = rs.getInt("marriageItemId"); + if (ret.marriageItemid > 0 && ret.partnerId <= 0) { + ret.marriageItemid = -1; + } else if (ret.partnerId > 0 && wserv.getRelationshipId(ret.id) <= 0) { + ret.marriageItemid = -1; + ret.partnerId = -1; + } + + NewYearCardRecord.loadPlayerNewYearCards(ret); + + //PreparedStatement ps2, ps3; + //ResultSet rs2, rs3; + + // Items excluded from pet loot + try (PreparedStatement psPet = con.prepareStatement("SELECT petid FROM inventoryitems WHERE characterid = ? AND petid > -1")) { + psPet.setInt(1, charid); + + try (ResultSet rsPet = psPet.executeQuery()) { + while (rsPet.next()) { + final int petId = rsPet.getInt("petid"); + + try (PreparedStatement psItem = con.prepareStatement("SELECT itemid FROM petignores WHERE petid = ?")) { + psItem.setInt(1, petId); + + ret.resetExcluded(petId); + + try (ResultSet rsItem = psItem.executeQuery()) { + while (rsItem.next()) { + ret.addExcluded(petId, rsItem.getInt("itemid")); + } + } + } + } + } + } + ret.commitExcludedItems(); + + + if (channelserver) { + MapleMapManager mapManager = client.getChannelServer().getMapFactory(); + ret.map = mapManager.getMap(ret.mapid); + + if (ret.map == null) { + ret.map = mapManager.getMap(100000000); + } + MaplePortal portal = ret.map.getPortal(ret.initialSpawnPoint); + if (portal == null) { + portal = ret.map.getPortal(0); + ret.initialSpawnPoint = 0; + } + ret.setPosition(portal.getPosition()); + int partyid = rs.getInt("party"); + MapleParty party = wserv.getParty(partyid); + if (party != null) { + ret.mpc = party.getMemberById(ret.id); + if (ret.mpc != null) { + ret.mpc = new MaplePartyCharacter(ret); + ret.party = party; + } + } + int messengerid = rs.getInt("messengerid"); + int position = rs.getInt("messengerposition"); + if (messengerid > 0 && position < 4 && position > -1) { + MapleMessenger messenger = wserv.getMessenger(messengerid); + if (messenger != null) { + ret.messenger = messenger; + ret.messengerposition = position; + } + } + ret.loggedIn = true; } } } - if ((sandboxCheck & ItemConstants.SANDBOX) == ItemConstants.SANDBOX) { - ret.setHasSandboxItem(); - } - - World wserv = Server.getInstance().getWorld(ret.world); - - ret.partnerId = rs.getInt("partnerId"); - ret.marriageItemid = rs.getInt("marriageItemId"); - if(ret.marriageItemid > 0 && ret.partnerId <= 0) { - ret.marriageItemid = -1; - } else if(ret.partnerId > 0 && wserv.getRelationshipId(ret.id) <= 0) { - ret.marriageItemid = -1; - ret.partnerId = -1; - } - - NewYearCardRecord.loadPlayerNewYearCards(ret); - - PreparedStatement ps2, ps3; - ResultSet rs2, rs3; - - ps3 = con.prepareStatement("SELECT petid FROM inventoryitems WHERE characterid = ? AND petid > -1"); - ps3.setInt(1, charid); - rs3 = ps3.executeQuery(); - while (rs3.next()) { - final int petId = rs3.getInt("petid"); - ps2 = con.prepareStatement("SELECT itemid FROM petignores WHERE petid = ?"); - ps2.setInt(1, petId); + // Teleport rocks + try (PreparedStatement ps = con.prepareStatement("SELECT mapid,vip FROM trocklocations WHERE characterid = ? LIMIT 15")) { + ps.setInt(1, charid); - ret.resetExcluded(petId); - - rs2 = ps2.executeQuery(); - while(rs2.next()) { - ret.addExcluded(petId, rs2.getInt("itemid")); - } - - ps2.close(); - rs2.close(); - } - ps3.close(); - rs3.close(); - - ret.commitExcludedItems(); - - if (channelserver) { - MapleMapManager mapManager = client.getChannelServer().getMapFactory(); - ret.map = mapManager.getMap(ret.mapid); - - if (ret.map == null) { - ret.map = mapManager.getMap(100000000); - } - MaplePortal portal = ret.map.getPortal(ret.initialSpawnPoint); - if (portal == null) { - portal = ret.map.getPortal(0); - ret.initialSpawnPoint = 0; - } - ret.setPosition(portal.getPosition()); - int partyid = rs.getInt("party"); - MapleParty party = wserv.getParty(partyid); - if (party != null) { - ret.mpc = party.getMemberById(ret.id); - if (ret.mpc != null) { - ret.mpc = new MaplePartyCharacter(ret); - ret.party = party; + try (ResultSet rs = ps.executeQuery()) { + byte vip = 0; + byte reg = 0; + while (rs.next()) { + if (rs.getInt("vip") == 1) { + ret.viptrockmaps.add(rs.getInt("mapid")); + vip++; + } else { + ret.trockmaps.add(rs.getInt("mapid")); + reg++; + } + } + while (vip < 10) { + ret.viptrockmaps.add(999999999); + vip++; + } + while (reg < 5) { + ret.trockmaps.add(999999999); + reg++; } } - int messengerid = rs.getInt("messengerid"); - int position = rs.getInt("messengerposition"); - if (messengerid > 0 && position < 4 && position > -1) { - MapleMessenger messenger = wserv.getMessenger(messengerid); - if (messenger != null) { - ret.messenger = messenger; - ret.messengerposition = position; + } + + // Account info + try (PreparedStatement ps = con.prepareStatement("SELECT name, characterslots, language FROM accounts WHERE id = ?", Statement.RETURN_GENERATED_KEYS)) { + ps.setInt(1, ret.accountid); + + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + MapleClient retClient = ret.getClient(); + + retClient.setAccountName(rs.getString("name")); + retClient.setCharacterSlots(rs.getByte("characterslots")); + retClient.setLanguage(rs.getInt("language")); // thanks Zein for noticing user language not overriding default once player is in-game } } - ret.loggedIn = true; } - rs.close(); - ps.close(); - ps = con.prepareStatement("SELECT mapid,vip FROM trocklocations WHERE characterid = ? LIMIT 15"); - ps.setInt(1, charid); - rs = ps.executeQuery(); - byte v = 0; - byte r = 0; - while (rs.next()) { - if (rs.getInt("vip") == 1) { - ret.viptrockmaps.add(rs.getInt("mapid")); - v++; - } else { - ret.trockmaps.add(rs.getInt("mapid")); - r++; + + // Area info + try (PreparedStatement ps = con.prepareStatement("SELECT `area`,`info` FROM area_info WHERE charid = ?")) { + ps.setInt(1, ret.id); + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + ret.area_info.put(rs.getShort("area"), rs.getString("info")); + } } } - while (v < 10) { - ret.viptrockmaps.add(999999999); - v++; - } - while (r < 5) { - ret.trockmaps.add(999999999); - r++; - } - rs.close(); - ps.close(); - ps = con.prepareStatement("SELECT name, characterslots, language FROM accounts WHERE id = ?", Statement.RETURN_GENERATED_KEYS); - ps.setInt(1, ret.accountid); - rs = ps.executeQuery(); - if (rs.next()) { - MapleClient retClient = ret.getClient(); - - retClient.setAccountName(rs.getString("name")); - retClient.setCharacterSlots(rs.getByte("characterslots")); - retClient.setLanguage(rs.getInt("language")); // thanks Zein for noticing user language not overriding default once player is in-game - } - rs.close(); - ps.close(); - ps = con.prepareStatement("SELECT `area`,`info` FROM area_info WHERE charid = ?"); - ps.setInt(1, ret.id); - rs = ps.executeQuery(); - while (rs.next()) { - ret.area_info.put(rs.getShort("area"), rs.getString("info")); - } - rs.close(); - ps.close(); - ps = con.prepareStatement("SELECT `name`,`info` FROM eventstats WHERE characterid = ?"); - ps.setInt(1, ret.id); - rs = ps.executeQuery(); - while (rs.next()) { - String name = rs.getString("name"); - if (rs.getString("name").contentEquals("rescueGaga")) { - ret.events.put(name, new RescueGaga(rs.getInt("info"))); + + // Event stats + try (PreparedStatement ps = con.prepareStatement("SELECT `name`,`info` FROM eventstats WHERE characterid = ?")) { + ps.setInt(1, ret.id); + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + String name = rs.getString("name"); + if (rs.getString("name").contentEquals("rescueGaga")) { + ret.events.put(name, new RescueGaga(rs.getInt("info"))); + } + } } } - rs.close(); - ps.close(); + ret.cashshop = new CashShop(ret.accountid, ret.id, ret.getJobType()); ret.autoban = new AutobanManager(ret); - ps = con.prepareStatement("SELECT name, level FROM characters WHERE accountid = ? AND id != ? ORDER BY level DESC limit 1"); - ps.setInt(1, ret.accountid); - ps.setInt(2, charid); - rs = ps.executeQuery(); - if (rs.next()) { - ret.linkedName = rs.getString("name"); - ret.linkedLevel = rs.getInt("level"); - } - rs.close(); - ps.close(); - if (channelserver) { - ps = con.prepareStatement("SELECT * FROM queststatus WHERE characterid = ?"); - ps.setInt(1, charid); - rs = ps.executeQuery(); - - Map loadedQuestStatus = new LinkedHashMap<>(); - while (rs.next()) { - MapleQuest q = MapleQuest.getInstance(rs.getShort("quest")); - MapleQuestStatus status = new MapleQuestStatus(q, MapleQuestStatus.Status.getById(rs.getInt("status"))); - long cTime = rs.getLong("time"); - if (cTime > -1) { - status.setCompletionTime(cTime * 1000); - } - long eTime = rs.getLong("expires"); - if (eTime > 0) { - status.setExpirationTime(eTime); - } + // Blessing of the Fairy + try (PreparedStatement ps = con.prepareStatement("SELECT name, level FROM characters WHERE accountid = ? AND id != ? ORDER BY level DESC limit 1")) { + ps.setInt(1, ret.accountid); + ps.setInt(2, charid); - status.setForfeited(rs.getInt("forfeited")); - status.setCompleted(rs.getInt("completed")); - ret.quests.put(q.getId(), status); - loadedQuestStatus.put(rs.getInt("queststatusid"), status); + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + ret.linkedName = rs.getString("name"); + ret.linkedLevel = rs.getInt("level"); + } } - rs.close(); - ps.close(); - + } + + if (channelserver) { + final Map loadedQuestStatus = new LinkedHashMap<>(); + + // Quest status + try (PreparedStatement ps = con.prepareStatement("SELECT * FROM queststatus WHERE characterid = ?")) { + ps.setInt(1, charid); + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + MapleQuest q = MapleQuest.getInstance(rs.getShort("quest")); + MapleQuestStatus status = new MapleQuestStatus(q, MapleQuestStatus.Status.getById(rs.getInt("status"))); + long cTime = rs.getLong("time"); + if (cTime > -1) { + status.setCompletionTime(cTime * 1000); + } + + long eTime = rs.getLong("expires"); + if (eTime > 0) { + status.setExpirationTime(eTime); + } + + status.setForfeited(rs.getInt("forfeited")); + status.setCompleted(rs.getInt("completed")); + ret.quests.put(q.getId(), status); + loadedQuestStatus.put(rs.getInt("queststatusid"), status); + } + } + } + + // Quest progress // opportunity for improvement on questprogress/medalmaps calls to DB - try (PreparedStatement pse = con.prepareStatement("SELECT * FROM questprogress WHERE characterid = ?")) { - pse.setInt(1, charid); - try (ResultSet rsProgress = pse.executeQuery()) { - while(rsProgress.next()) { + try (PreparedStatement ps = con.prepareStatement("SELECT * FROM questprogress WHERE characterid = ?")) { + ps.setInt(1, charid); + try (ResultSet rsProgress = ps.executeQuery()) { + while (rsProgress.next()) { MapleQuestStatus status = loadedQuestStatus.get(rsProgress.getInt("queststatusid")); - if(status != null) { + if (status != null) { status.setProgress(rsProgress.getInt("progressid"), rsProgress.getString("progress")); } } } } - - try (PreparedStatement pse = con.prepareStatement("SELECT * FROM medalmaps WHERE characterid = ?")) { - pse.setInt(1, charid); - try (ResultSet rsMedalMaps = pse.executeQuery()) { - while(rsMedalMaps.next()) { + + // Medal map visit progress + try (PreparedStatement ps = con.prepareStatement("SELECT * FROM medalmaps WHERE characterid = ?")) { + ps.setInt(1, charid); + try (ResultSet rsMedalMaps = ps.executeQuery()) { + while (rsMedalMaps.next()) { MapleQuestStatus status = loadedQuestStatus.get(rsMedalMaps.getInt("queststatusid")); - if(status != null) { + if (status != null) { status.addMedalMap(rsMedalMaps.getInt("mapid")); } } } } - + loadedQuestStatus.clear(); - - ps = con.prepareStatement("SELECT skillid,skilllevel,masterlevel,expiration FROM skills WHERE characterid = ?"); - ps.setInt(1, charid); - rs = ps.executeQuery(); - while (rs.next()) { - Skill pSkill = SkillFactory.getSkill(rs.getInt("skillid")); - if(pSkill != null) // edit reported by Shavit (=^● ⋏ ●^=), thanks Zein for noticing an NPE here - { - ret.skills.put(pSkill, new SkillEntry(rs.getByte("skilllevel"), rs.getInt("masterlevel"), rs.getLong("expiration"))); + + // Skills + try (PreparedStatement ps = con.prepareStatement("SELECT skillid,skilllevel,masterlevel,expiration FROM skills WHERE characterid = ?")) { + ps.setInt(1, charid); + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + Skill pSkill = SkillFactory.getSkill(rs.getInt("skillid")); + if (pSkill != null) { // edit reported by Shavit (=^● ⋏ ●^=), thanks Zein for noticing an NPE here + ret.skills.put(pSkill, new SkillEntry(rs.getByte("skilllevel"), rs.getInt("masterlevel"), rs.getLong("expiration"))); + } + } } } - rs.close(); - ps.close(); - ps = con.prepareStatement("SELECT SkillID,StartTime,length FROM cooldowns WHERE charid = ?"); - ps.setInt(1, ret.getId()); - rs = ps.executeQuery(); - long curTime = Server.getInstance().getCurrentTime(); - while (rs.next()) { - final int skillid = rs.getInt("SkillID"); - final long length = rs.getLong("length"), startTime = rs.getLong("StartTime"); - if (skillid != 5221999 && (length + startTime < curTime)) { - continue; + + // Cooldowns (load) + try (PreparedStatement ps = con.prepareStatement("SELECT SkillID,StartTime,length FROM cooldowns WHERE charid = ?")) { + ps.setInt(1, ret.getId()); + + try (ResultSet rs = ps.executeQuery()) { + long curTime = Server.getInstance().getCurrentTime(); + while (rs.next()) { + final int skillid = rs.getInt("SkillID"); + final long length = rs.getLong("length"), startTime = rs.getLong("StartTime"); + if (skillid != 5221999 && (length + startTime < curTime)) { + continue; + } + ret.giveCoolDowns(skillid, startTime, length); + } } - ret.giveCoolDowns(skillid, startTime, length); } - rs.close(); - ps.close(); - ps = con.prepareStatement("DELETE FROM cooldowns WHERE charid = ?"); - ps.setInt(1, ret.getId()); - ps.executeUpdate(); - ps.close(); + + // Cooldowns (delete) + try (PreparedStatement ps = con.prepareStatement("DELETE FROM cooldowns WHERE charid = ?")) { + ps.setInt(1, ret.getId()); + ps.executeUpdate(); + } + + // Debuffs (load) Map> loadedDiseases = new LinkedHashMap<>(); - ps = con.prepareStatement("SELECT * FROM playerdiseases WHERE charid = ?"); - ps.setInt(1, ret.getId()); - rs = ps.executeQuery(); - while (rs.next()) { - final MapleDisease disease = MapleDisease.ordinal(rs.getInt("disease")); - if (disease == MapleDisease.NULL) { - continue; - } - - final int skillid = rs.getInt("mobskillid"), skilllv = rs.getInt("mobskilllv"); - final long length = rs.getInt("length"); - - MobSkill ms = MobSkillFactory.getMobSkill(skillid, skilllv); - if(ms != null) { - loadedDiseases.put(disease, new Pair<>(length, ms)); + try (PreparedStatement ps = con.prepareStatement("SELECT * FROM playerdiseases WHERE charid = ?")) { + ps.setInt(1, ret.getId()); + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + final MapleDisease disease = MapleDisease.ordinal(rs.getInt("disease")); + if (disease == MapleDisease.NULL) { + continue; + } + + final int skillid = rs.getInt("mobskillid"); + final int skilllv = rs.getInt("mobskilllv"); + final long length = rs.getInt("length"); + + MobSkill ms = MobSkillFactory.getMobSkill(skillid, skilllv); + if (ms != null) { + loadedDiseases.put(disease, new Pair<>(length, ms)); + } + } } } - rs.close(); - ps.close(); - ps = con.prepareStatement("DELETE FROM playerdiseases WHERE charid = ?"); - ps.setInt(1, ret.getId()); - ps.executeUpdate(); - ps.close(); + + // Debuffs (delete) + try (PreparedStatement ps = con.prepareStatement("DELETE FROM playerdiseases WHERE charid = ?")) { + ps.setInt(1, ret.getId()); + ps.executeUpdate(); + } + if (!loadedDiseases.isEmpty()) { Server.getInstance().getPlayerBuffStorage().addDiseasesToStorage(ret.id, loadedDiseases); } - ps = con.prepareStatement("SELECT * FROM skillmacros WHERE characterid = ?"); - ps.setInt(1, charid); - rs = ps.executeQuery(); - while (rs.next()) { - int position = rs.getInt("position"); - SkillMacro macro = new SkillMacro(rs.getInt("skill1"), rs.getInt("skill2"), rs.getInt("skill3"), rs.getString("name"), rs.getInt("shout"), position); - ret.skillMacros[position] = macro; + + // Skill macros + try (PreparedStatement ps = con.prepareStatement("SELECT * FROM skillmacros WHERE characterid = ?")) { + ps.setInt(1, charid); + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + int position = rs.getInt("position"); + SkillMacro macro = new SkillMacro(rs.getInt("skill1"), rs.getInt("skill2"), rs.getInt("skill3"), rs.getString("name"), rs.getInt("shout"), position); + ret.skillMacros[position] = macro; + } + } } - rs.close(); - ps.close(); - ps = con.prepareStatement("SELECT `key`,`type`,`action` FROM keymap WHERE characterid = ?"); - ps.setInt(1, charid); - rs = ps.executeQuery(); - while (rs.next()) { - int key = rs.getInt("key"); - int type = rs.getInt("type"); - int action = rs.getInt("action"); - ret.keymap.put(Integer.valueOf(key), new MapleKeyBinding(type, action)); + + // Key config + try (PreparedStatement ps = con.prepareStatement("SELECT `key`,`type`,`action` FROM keymap WHERE characterid = ?")) { + ps.setInt(1, charid); + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + int key = rs.getInt("key"); + int type = rs.getInt("type"); + int action = rs.getInt("action"); + ret.keymap.put(key, new MapleKeyBinding(type, action)); + } + } } - rs.close(); - ps.close(); - ps = con.prepareStatement("SELECT `locationtype`,`map`,`portal` FROM savedlocations WHERE characterid = ?"); - ps.setInt(1, charid); - rs = ps.executeQuery(); - while (rs.next()) { - ret.savedLocations[SavedLocationType.valueOf(rs.getString("locationtype")).ordinal()] = new SavedLocation(rs.getInt("map"), rs.getInt("portal")); + + // Saved locations + try (PreparedStatement ps = con.prepareStatement("SELECT `locationtype`,`map`,`portal` FROM savedlocations WHERE characterid = ?")) { + ps.setInt(1, charid); + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + ret.savedLocations[SavedLocationType.valueOf(rs.getString("locationtype")).ordinal()] = new SavedLocation(rs.getInt("map"), rs.getInt("portal")); + } + } } - rs.close(); - ps.close(); - ps = con.prepareStatement("SELECT `characterid_to`,`when` FROM famelog WHERE characterid = ? AND DATEDIFF(NOW(),`when`) < 30"); - ps.setInt(1, charid); - rs = ps.executeQuery(); - ret.lastfametime = 0; - ret.lastmonthfameids = new ArrayList<>(31); - while (rs.next()) { - ret.lastfametime = Math.max(ret.lastfametime, rs.getTimestamp("when").getTime()); - ret.lastmonthfameids.add(Integer.valueOf(rs.getInt("characterid_to"))); + + // Fame history + try (PreparedStatement ps = con.prepareStatement("SELECT `characterid_to`,`when` FROM famelog WHERE characterid = ? AND DATEDIFF(NOW(),`when`) < 30")) { + ps.setInt(1, charid); + + try (ResultSet rs = ps.executeQuery()) { + ret.lastfametime = 0; + ret.lastmonthfameids = new ArrayList<>(31); + while (rs.next()) { + ret.lastfametime = Math.max(ret.lastfametime, rs.getTimestamp("when").getTime()); + ret.lastmonthfameids.add(rs.getInt("characterid_to")); + } + } } - rs.close(); - ps.close(); + ret.buddylist.loadFromDb(charid); ret.storage = wserv.getAccountStorage(ret.accountid); - + int startHp = ret.hp, startMp = ret.mp; ret.reapplyLocalStats(); ret.changeHpMp(startHp, startMp, true); //ret.resetBattleshipHp(); } - int mountid = ret.getJobType() * 10000000 + 1004; + + final int mountid = ret.getJobType() * 10000000 + 1004; if (ret.getInventory(MapleInventoryType.EQUIPPED).getItem((short) -18) != null) { ret.maplemount = new MapleMount(ret, ret.getInventory(MapleInventoryType.EQUIPPED).getItem((short) -18).getItemId(), mountid); } else { @@ -7518,7 +7422,8 @@ public class MapleCharacter extends AbstractMapleCharacterObject { ret.maplemount.setLevel(mountlevel); ret.maplemount.setTiredness(mounttiredness); ret.maplemount.setActive(false); - + + // Quickslot key config try (final PreparedStatement pSelectQuickslotKeyMapped = con.prepareStatement("SELECT keymap FROM quickslotkeymapped WHERE accountid = ?;")) { pSelectQuickslotKeyMapped.setInt(1, ret.getAccountID()); @@ -7529,8 +7434,7 @@ public class MapleCharacter extends AbstractMapleCharacterObject { } } } - - con.close(); + return ret; } catch (SQLException | RuntimeException e) { e.printStackTrace(); @@ -8177,8 +8081,7 @@ public class MapleCharacter extends AbstractMapleCharacterObject { List listcd = getAllCooldowns(); if (!listcd.isEmpty()) { - try { - Connection con = DatabaseConnection.getConnection(); + try (Connection con = DatabaseConnection.getConnection()) { deleteWhereCharacterId(con, "DELETE FROM cooldowns WHERE charid = ?"); try (PreparedStatement ps = con.prepareStatement("INSERT INTO cooldowns (charid, SkillID, StartTime, length) VALUES (?, ?, ?, ?)")) { ps.setInt(1, getId()); @@ -8190,8 +8093,6 @@ public class MapleCharacter extends AbstractMapleCharacterObject { } ps.executeBatch(); } - - con.close(); } catch (SQLException se) { se.printStackTrace(); } @@ -8199,8 +8100,7 @@ public class MapleCharacter extends AbstractMapleCharacterObject { Map> listds = getAllDiseases(); if (!listds.isEmpty()) { - try { - Connection con = DatabaseConnection.getConnection(); + try (Connection con = DatabaseConnection.getConnection()) { deleteWhereCharacterId(con, "DELETE FROM playerdiseases WHERE charid = ?"); try (PreparedStatement ps = con.prepareStatement("INSERT INTO playerdiseases (charid, disease, mobskillid, mobskilllv, length) VALUES (?, ?, ?, ?, ?)")) { ps.setInt(1, getId()); @@ -8217,8 +8117,6 @@ public class MapleCharacter extends AbstractMapleCharacterObject { ps.executeBatch(); } - - con.close(); } catch (SQLException se) { se.printStackTrace(); } @@ -8226,17 +8124,13 @@ public class MapleCharacter extends AbstractMapleCharacterObject { } public void saveGuildStatus() { - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("UPDATE characters SET guildid = ?, guildrank = ?, allianceRank = ? WHERE id = ?")) { - ps.setInt(1, guildid); - ps.setInt(2, guildRank); - ps.setInt(3, allianceRank); - ps.setInt(4, id); - ps.executeUpdate(); - } - - con.close(); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE characters SET guildid = ?, guildrank = ?, allianceRank = ? WHERE id = ?")) { + ps.setInt(1, guildid); + ps.setInt(2, guildRank); + ps.setInt(3, allianceRank); + ps.setInt(4, id); + ps.executeUpdate(); } catch (SQLException se) { se.printStackTrace(); } @@ -8274,159 +8168,151 @@ public class MapleCharacter extends AbstractMapleCharacterObject { meso.set(recipe.getMeso()); List> startingSkills = recipe.getStartingSkillLevel(); - for(Pair skEntry : startingSkills) { + for (Pair skEntry : startingSkills) { Skill skill = skEntry.getLeft(); this.changeSkillLevel(skill, skEntry.getRight().byteValue(), skill.getMaxLevel(), -1); } List> itemsWithType = recipe.getStartingItems(); - for(Pair itEntry : itemsWithType) { + for (Pair itEntry : itemsWithType) { this.getInventory(itEntry.getRight()).addItem(itEntry.getLeft()); } - + this.events.put("rescueGaga", new RescueGaga(0)); - - Connection con = null; - PreparedStatement ps = null; - try { - con = DatabaseConnection.getConnection(); - - con.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); + + try (Connection con = DatabaseConnection.getConnection()) { con.setAutoCommit(false); - ps = con.prepareStatement("INSERT INTO characters (str, dex, luk, `int`, gm, skincolor, gender, job, hair, face, map, meso, spawnpoint, accountid, name, world, hp, mp, maxhp, maxmp, level, ap, sp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); - ps.setInt(1, str); - ps.setInt(2, dex); - ps.setInt(3, luk); - ps.setInt(4, int_); - ps.setInt(5, gmLevel); - ps.setInt(6, skinColor.getId()); - ps.setInt(7, gender); - ps.setInt(8, getJob().getId()); - ps.setInt(9, hair); - ps.setInt(10, face); - ps.setInt(11, mapid); - ps.setInt(12, Math.abs(meso.get())); - ps.setInt(13, 0); - ps.setInt(14, accountid); - ps.setString(15, name); - ps.setInt(16, world); - ps.setInt(17, hp); - ps.setInt(18, mp); - ps.setInt(19, maxhp); - ps.setInt(20, maxmp); - ps.setInt(21, level); - ps.setInt(22, remainingAp); - - StringBuilder sps = new StringBuilder(); - for (int i = 0; i < remainingSp.length; i++) { - sps.append(remainingSp[i]); - sps.append(","); - } - String sp = sps.toString(); - ps.setString(23, sp.substring(0, sp.length() - 1)); + con.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); - int updateRows = ps.executeUpdate(); - if (updateRows < 1) { - ps.close(); - FilePrinter.printError(FilePrinter.INSERT_CHAR, "Error trying to insert " + name); - return false; - } - ResultSet rs = ps.getGeneratedKeys(); - if (rs.next()) { - this.id = rs.getInt(1); - rs.close(); - ps.close(); - } else { - rs.close(); - ps.close(); - FilePrinter.printError(FilePrinter.INSERT_CHAR, "Inserting char failed " + name); - return false; - } + try { + // Character info + try (PreparedStatement ps = con.prepareStatement("INSERT INTO characters (str, dex, luk, `int`, gm, skincolor, gender, job, hair, face, map, meso, spawnpoint, accountid, name, world, hp, mp, maxhp, maxmp, level, ap, sp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) { + ps.setInt(1, str); + ps.setInt(2, dex); + ps.setInt(3, luk); + ps.setInt(4, int_); + ps.setInt(5, gmLevel); + ps.setInt(6, skinColor.getId()); + ps.setInt(7, gender); + ps.setInt(8, getJob().getId()); + ps.setInt(9, hair); + ps.setInt(10, face); + ps.setInt(11, mapid); + ps.setInt(12, Math.abs(meso.get())); + ps.setInt(13, 0); + ps.setInt(14, accountid); + ps.setString(15, name); + ps.setInt(16, world); + ps.setInt(17, hp); + ps.setInt(18, mp); + ps.setInt(19, maxhp); + ps.setInt(20, maxmp); + ps.setInt(21, level); + ps.setInt(22, remainingAp); - // Select a keybinding method - int[] selectedKey; - int[] selectedType; - int[] selectedAction; + StringBuilder sps = new StringBuilder(); + for (int j : remainingSp) { + sps.append(j); + sps.append(","); + } + String sp = sps.toString(); + ps.setString(23, sp.substring(0, sp.length() - 1)); - if(YamlConfig.config.server.USE_CUSTOM_KEYSET) { - selectedKey = GameConstants.getCustomKey(true); - selectedType = GameConstants.getCustomType(true); - selectedAction = GameConstants.getCustomAction(true); - } else { - selectedKey = GameConstants.getCustomKey(false); - selectedType = GameConstants.getCustomType(false); - selectedAction = GameConstants.getCustomAction(false); - } - - ps = con.prepareStatement("INSERT INTO keymap (characterid, `key`, `type`, `action`) VALUES (?, ?, ?, ?)"); - ps.setInt(1, id); - for (int i = 0; i < selectedKey.length; i++) { - ps.setInt(2, selectedKey[i]); - ps.setInt(3, selectedType[i]); - ps.setInt(4, selectedAction[i]); - ps.execute(); - } - 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(); + int updateRows = ps.executeUpdate(); + if (updateRows < 1) { + FilePrinter.printError(FilePrinter.INSERT_CHAR, "Error trying to insert " + name); + return false; + } + + try (ResultSet rs = ps.getGeneratedKeys()) { + if (rs.next()) { + this.id = rs.getInt(1); + } else { + FilePrinter.printError(FilePrinter.INSERT_CHAR, "Inserting char failed " + name); + return false; + } + } } - } - itemsWithType = new ArrayList<>(); - for (MapleInventory iv : inventory) { - for (Item item : iv.list()) { - itemsWithType.add(new Pair<>(item, iv.getType())); - } - } + // Select a keybinding method + int[] selectedKey; + int[] selectedType; + int[] selectedAction; - ItemFactory.INVENTORY.saveItems(itemsWithType, id, con); - - if(!skills.isEmpty()) { - ps = con.prepareStatement("INSERT INTO skills (characterid, skillid, skilllevel, masterlevel, expiration) VALUES (?, ?, ?, ?, ?)"); - ps.setInt(1, id); - for (Entry 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(); + if (YamlConfig.config.server.USE_CUSTOM_KEYSET) { + selectedKey = GameConstants.getCustomKey(true); + selectedType = GameConstants.getCustomType(true); + selectedAction = GameConstants.getCustomAction(true); + } else { + selectedKey = GameConstants.getCustomKey(false); + selectedType = GameConstants.getCustomType(false); + selectedAction = GameConstants.getCustomAction(false); } - ps.executeBatch(); - ps.close(); + + // Key config + try (PreparedStatement ps = con.prepareStatement("INSERT INTO keymap (characterid, `key`, `type`, `action`) VALUES (?, ?, ?, ?)")) { + ps.setInt(1, id); + for (int i = 0; i < selectedKey.length; i++) { + ps.setInt(2, selectedKey[i]); + ps.setInt(3, selectedType[i]); + ps.setInt(4, selectedAction[i]); + ps.executeUpdate(); + } + } + + // 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()); + + // Quickslot key config + try (PreparedStatement ps = con.prepareStatement("INSERT INTO quickslotkeymapped (accountid, keymap) VALUES (?, ?) ON DUPLICATE KEY UPDATE keymap = ?;")) { + ps.setInt(1, this.getAccountID()); + ps.setLong(2, nQuickslotKeymapped); + ps.setLong(3, nQuickslotKeymapped); + ps.executeUpdate(); + } + } + + itemsWithType = new ArrayList<>(); + for (MapleInventory iv : inventory) { + for (Item item : iv.list()) { + itemsWithType.add(new Pair<>(item, iv.getType())); + } + } + + ItemFactory.INVENTORY.saveItems(itemsWithType, id, con); + + if (!skills.isEmpty()) { + // Skills + try (PreparedStatement ps = con.prepareStatement("INSERT INTO skills (characterid, skillid, skilllevel, masterlevel, expiration) VALUES (?, ?, ?, ?, ?)")) { + ps.setInt(1, id); + for (Entry 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(); + } + ps.executeBatch(); + } + } + + con.commit(); + return true; + } catch (Exception e) { + con.rollback(); + throw e; + } finally { + con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); + con.setAutoCommit(true); } - - con.commit(); - return true; } catch (Throwable t) { FilePrinter.printError(FilePrinter.INSERT_CHAR, t, "Error creating " + name + " Level: " + level + " Job: " + job.getId()); - try { - con.rollback(); - } catch (SQLException se) { - FilePrinter.printError(FilePrinter.INSERT_CHAR, se, "Error trying to rollback " + name); - } - return false; - } finally { - try { - if (ps != null && !ps.isClosed()) { - ps.close(); - } - con.setAutoCommit(true); - con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); - con.close(); - } catch (SQLException e) { - e.printStackTrace(); - } } + + return false; } public void saveCharToDB() { @@ -8450,403 +8336,407 @@ public class MapleCharacter extends AbstractMapleCharacterObject { if (!loggedIn) { return; } - + Calendar c = Calendar.getInstance(); - - if(notAutosave) { + + if (notAutosave) { FilePrinter.print(FilePrinter.SAVING_CHARACTER, "Attempting to save " + name + " at " + c.getTime().toString()); } else { FilePrinter.print(FilePrinter.AUTOSAVING_CHARACTER, "Attempting to autosave " + name + " at " + c.getTime().toString()); } - - Server.getInstance().updateCharacterEntry(this); - - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - con.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); - 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); - ps.setInt(1, level); // thanks CanIGetaPR for noticing an unnecessary "level" limitation when persisting DB data - ps.setInt(2, fame); - - effLock.lock(); - statWlock.lock(); - try { - ps.setInt(3, str); - ps.setInt(4, dex); - ps.setInt(5, luk); - ps.setInt(6, int_); - ps.setInt(7, Math.abs(exp.get())); - ps.setInt(8, Math.abs(gachaexp.get())); - ps.setInt(9, hp); - 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]); - sps.append(","); - } - String sp = sps.toString(); - ps.setString(13, sp.substring(0, sp.length() - 1)); - ps.setInt(14, remainingAp); - } finally { - statWlock.unlock(); - effLock.unlock(); - } - - ps.setInt(15, gmLevel); - ps.setInt(16, skinColor.getId()); - ps.setInt(17, gender); - ps.setInt(18, job.getId()); - ps.setInt(19, hair); - ps.setInt(20, face); - if (map == null || (cashshop != null && cashshop.isOpened())) { - ps.setInt(21, mapid); - } else { - if (map.getForcedReturnId() != 999999999) { - ps.setInt(21, map.getForcedReturnId()); - } else { - ps.setInt(21, getHp() < 1 ? map.getReturnMapId() : map.getId()); - } - } - ps.setInt(22, meso.get()); - ps.setInt(23, hpMpApUsed); - if (map == null || map.getId() == 610020000 || map.getId() == 610020001) { // reset to first spawnpoint on those maps - ps.setInt(24, 0); - } else { - MaplePortal closest = map.findClosestPlayerSpawnpoint(getPosition()); - if (closest != null) { - ps.setInt(24, closest.getId()); - } else { - ps.setInt(24, 0); - } - } - - prtLock.lock(); - try { - if (party != null) { - ps.setInt(25, party.getId()); - } else { - ps.setInt(25, -1); - } - } finally { - prtLock.unlock(); - } - - ps.setInt(26, buddylist.getCapacity()); - if (messenger != null) { - ps.setInt(27, messenger.getId()); - ps.setInt(28, messengerposition); - } else { - ps.setInt(27, 0); - ps.setInt(28, 4); - } - if (maplemount != null) { - ps.setInt(29, maplemount.getLevel()); - ps.setInt(30, maplemount.getExp()); - ps.setInt(31, maplemount.getTiredness()); - } else { - ps.setInt(29, 1); - ps.setInt(30, 0); - ps.setInt(31, 0); - } - for (int i = 1; i < 5; i++) { - ps.setInt(i + 31, getSlots(i)); - } - - monsterbook.saveCards(getId()); - - ps.setInt(36, bookCover); - ps.setInt(37, vanquisherStage); - ps.setInt(38, dojoPoints); - ps.setInt(39, dojoStage); - ps.setInt(40, finishedDojoTutorial ? 1 : 0); - ps.setInt(41, vanquisherKills); - ps.setInt(42, matchcardwins); - ps.setInt(43, matchcardlosses); - ps.setInt(44, matchcardties); - ps.setInt(45, omokwins); - ps.setInt(46, omoklosses); - ps.setInt(47, omokties); - ps.setString(48, dataString); - ps.setInt(49, quest_fame); - ps.setLong(50, jailExpiration); - ps.setInt(51, partnerId); - ps.setInt(52, marriageItemid); - ps.setTimestamp(53, new Timestamp(lastExpGainTime)); - ps.setInt(54, ariantPoints); - ps.setBoolean(55, canRecvPartySearchInvite); - ps.setInt(56, id); - int updateRows = ps.executeUpdate(); - ps.close(); - - if (updateRows < 1) { - throw new RuntimeException("Character not in database (" + id + ")"); - } - - List petList = new LinkedList<>(); - petLock.lock(); + Server.getInstance().updateCharacterEntry(this); + + try (Connection con = DatabaseConnection.getConnection()) { + con.setAutoCommit(false); + con.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); + try { - for (int i = 0; i < 3; i++) { - if (pets[i] != null) { - petList.add(pets[i]); - } - } - } finally { - petLock.unlock(); - } - - for (MaplePet pet : petList) { - pet.saveToDb(); - } - - for(Entry> 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 ps2 = con.prepareStatement("INSERT INTO petignores (petid, itemid) VALUES (?, ?)")) { - ps2.setInt(1, es.getKey()); - for(Integer x: es.getValue()) { - ps2.setInt(2, x); - ps2.addBatch(); - } - ps2.executeBatch(); - } - } - - deleteWhereCharacterId(con, "DELETE FROM keymap WHERE characterid = ?"); - ps = con.prepareStatement("INSERT INTO keymap (characterid, `key`, `type`, `action`) VALUES (?, ?, ?, ?)"); - ps.setInt(1, id); - - Set> keybindingItems = Collections.unmodifiableSet(keymap.entrySet()); - for (Entry keybinding : keybindingItems) { - ps.setInt(2, keybinding.getKey()); - ps.setInt(3, keybinding.getValue().getType()); - ps.setInt(4, keybinding.getValue().getAction()); - ps.addBatch(); - } - 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(); - } - } - - 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()); - 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(); - } - } - ps.executeBatch(); - ps.close(); - - List> itemsWithType = new ArrayList<>(); - for (MapleInventory iv : inventory) { - for (Item item : iv.list()) { - itemsWithType.add(new Pair<>(item, iv.getType())); - } - } - - ItemFactory.INVENTORY.saveItems(itemsWithType, id, con); - - ps = con.prepareStatement("REPLACE INTO skills (characterid, skillid, skilllevel, masterlevel, expiration) VALUES (?, ?, ?, ?, ?)"); - ps.setInt(1, id); - for (Entry 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(); - } - ps.executeBatch(); - ps.close(); - - deleteWhereCharacterId(con, "DELETE FROM savedlocations WHERE characterid = ?"); - ps = con.prepareStatement("INSERT INTO savedlocations (characterid, `locationtype`, `map`, `portal`) VALUES (?, ?, ?, ?)"); - ps.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(); - } - } - ps.executeBatch(); - ps.close(); - - deleteWhereCharacterId(con, "DELETE FROM trocklocations WHERE characterid = ?"); - ps = 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(); - } - } - ps.executeBatch(); - ps.close(); - - ps = 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(); - } - } - ps.executeBatch(); - ps.close(); - - 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); - for (BuddylistEntry entry : buddylist.getBuddies()) { - if (entry.isVisible()) { - ps.setInt(2, entry.getCharacterId()); - ps.setString(3, entry.getGroup()); - ps.addBatch(); - } - } - ps.executeBatch(); - ps.close(); - - 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 area : area_info.entrySet()) { - ps.setInt(2, area.getKey()); - ps.setString(3, area.getValue()); - ps.addBatch(); - } - ps.executeBatch(); - ps.close(); - - deleteWhereCharacterId(con, "DELETE FROM eventstats WHERE characterid = ?"); - ps = con.prepareStatement("INSERT INTO eventstats (characterid, name, info) VALUES (?, ?, ?)"); - ps.setInt(1, id); - - for (Map.Entry entry : events.entrySet()) { - ps.setString(2, entry.getKey()); - ps.setInt(3, entry.getValue().getInfo()); - ps.addBatch(); - } - - ps.executeBatch(); - ps.close(); - - 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); - - 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()) { - 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(); + 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); + + effLock.lock(); + statWlock.lock(); + try { + ps.setInt(3, str); + ps.setInt(4, dex); + ps.setInt(5, luk); + ps.setInt(6, int_); + ps.setInt(7, Math.abs(exp.get())); + ps.setInt(8, Math.abs(gachaexp.get())); + ps.setInt(9, hp); + ps.setInt(10, mp); + ps.setInt(11, maxhp); + ps.setInt(12, maxmp); + + StringBuilder sps = new StringBuilder(); + for (int j : remainingSp) { + sps.append(j); + sps.append(","); } - 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(); + String sp = sps.toString(); + ps.setString(13, sp.substring(0, sp.length() - 1)); + + ps.setInt(14, remainingAp); + } finally { + statWlock.unlock(); + effLock.unlock(); + } + + ps.setInt(15, gmLevel); + ps.setInt(16, skinColor.getId()); + ps.setInt(17, gender); + ps.setInt(18, job.getId()); + ps.setInt(19, hair); + ps.setInt(20, face); + if (map == null || (cashshop != null && cashshop.isOpened())) { + ps.setInt(21, mapid); + } else { + if (map.getForcedReturnId() != 999999999) { + ps.setInt(21, map.getForcedReturnId()); + } else { + ps.setInt(21, getHp() < 1 ? map.getReturnMapId() : map.getId()); } - pse.executeBatch(); - psf.executeBatch(); + } + ps.setInt(22, meso.get()); + ps.setInt(23, hpMpApUsed); + if (map == null || map.getId() == 610020000 || map.getId() == 610020001) { // reset to first spawnpoint on those maps + ps.setInt(24, 0); + } else { + MaplePortal closest = map.findClosestPlayerSpawnpoint(getPosition()); + if (closest != null) { + ps.setInt(24, closest.getId()); + } else { + ps.setInt(24, 0); + } + } + + prtLock.lock(); + try { + if (party != null) { + ps.setInt(25, party.getId()); + } else { + ps.setInt(25, -1); + } + } finally { + prtLock.unlock(); + } + + ps.setInt(26, buddylist.getCapacity()); + if (messenger != null) { + ps.setInt(27, messenger.getId()); + ps.setInt(28, messengerposition); + } else { + ps.setInt(27, 0); + ps.setInt(28, 4); + } + if (maplemount != null) { + ps.setInt(29, maplemount.getLevel()); + ps.setInt(30, maplemount.getExp()); + ps.setInt(31, maplemount.getTiredness()); + } else { + ps.setInt(29, 1); + ps.setInt(30, 0); + ps.setInt(31, 0); + } + for (int i = 1; i < 5; i++) { + ps.setInt(i + 31, getSlots(i)); + } + + monsterbook.saveCards(getId()); + + ps.setInt(36, bookCover); + ps.setInt(37, vanquisherStage); + ps.setInt(38, dojoPoints); + ps.setInt(39, dojoStage); + ps.setInt(40, finishedDojoTutorial ? 1 : 0); + ps.setInt(41, vanquisherKills); + ps.setInt(42, matchcardwins); + ps.setInt(43, matchcardlosses); + ps.setInt(44, matchcardties); + ps.setInt(45, omokwins); + ps.setInt(46, omoklosses); + ps.setInt(47, omokties); + ps.setString(48, dataString); + ps.setInt(49, quest_fame); + ps.setLong(50, jailExpiration); + ps.setInt(51, partnerId); + ps.setInt(52, marriageItemid); + ps.setTimestamp(53, new Timestamp(lastExpGainTime)); + ps.setInt(54, ariantPoints); + ps.setBoolean(55, canRecvPartySearchInvite); + ps.setInt(56, id); + + int updateRows = ps.executeUpdate(); + if (updateRows < 1) { + throw new RuntimeException("Character not in database (" + id + ")"); } } - } - psf.close(); - ps.close(); - - MapleFamilyEntry familyEntry = getFamilyEntry(); //save family rep - if(familyEntry != null) { - 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(); - senior = senior.getSenior(); //save one level up as well - if(senior != null && senior.getChr() == null) { - if(senior.saveReputation(con)) senior.savedSuccessfully(); + + List petList = new LinkedList<>(); + petLock.lock(); + try { + for (int i = 0; i < 3; i++) { + if (pets[i] != null) { + petList.add(pets[i]); + } + } + } finally { + petLock.unlock(); + } + + for (MaplePet pet : petList) { + pet.saveToDb(); + } + + for (Entry> es : getExcluded().entrySet()) { // this set is already protected + try (PreparedStatement psIgnore = con.prepareStatement("DELETE FROM petignores WHERE petid=?")) { + psIgnore.setInt(1, es.getKey()); + psIgnore.executeUpdate(); + } + + try (PreparedStatement psIgnore = con.prepareStatement("INSERT INTO petignores (petid, itemid) VALUES (?, ?)")) { + psIgnore.setInt(1, es.getKey()); + for (Integer x : es.getValue()) { + psIgnore.setInt(2, x); + psIgnore.addBatch(); + } + psIgnore.executeBatch(); } } - - } - - if (cashshop != null) { - cashshop.save(con); - } - - if (storage != null && usedStorage) { - storage.saveToDB(con); - usedStorage = false; - } - - 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 { + + // Key config + deleteWhereCharacterId(con, "DELETE FROM keymap WHERE characterid = ?"); + try (PreparedStatement psKey = con.prepareStatement("INSERT INTO keymap (characterid, `key`, `type`, `action`) VALUES (?, ?, ?, ?)")) { + psKey.setInt(1, id); + + Set> keybindingItems = Collections.unmodifiableSet(keymap.entrySet()); + for (Entry keybinding : keybindingItems) { + psKey.setInt(2, keybinding.getKey()); + psKey.setInt(3, keybinding.getValue().getType()); + psKey.setInt(4, keybinding.getValue().getAction()); + psKey.addBatch(); + } + psKey.executeBatch(); + } + + // 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 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 = ?"); + 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) { + 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(); + } + } + psMacro.executeBatch(); + } + + List> itemsWithType = new ArrayList<>(); + for (MapleInventory iv : inventory) { + for (Item item : iv.list()) { + itemsWithType.add(new Pair<>(item, iv.getType())); + } + } + + // Items + ItemFactory.INVENTORY.saveItems(itemsWithType, id, con); + + // Skills + try (PreparedStatement psSkill = con.prepareStatement("REPLACE INTO skills (characterid, skillid, skilllevel, masterlevel, expiration) VALUES (?, ?, ?, ?, ?)")) { + psSkill.setInt(1, id); + for (Entry skill : skills.entrySet()) { + 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(); + } + + // Saved locations + deleteWhereCharacterId(con, "DELETE FROM savedlocations WHERE characterid = ?"); + 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) { + psLoc.setString(2, savedLocationType.name()); + psLoc.setInt(3, savedLocations[savedLocationType.ordinal()].getMapId()); + psLoc.setInt(4, savedLocations[savedLocationType.ordinal()].getPortal()); + psLoc.addBatch(); + } + } + psLoc.executeBatch(); + } + + deleteWhereCharacterId(con, "DELETE FROM trocklocations WHERE characterid = ?"); + + // 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) { + psVip.setInt(1, getId()); + psVip.setInt(2, trockmaps.get(i)); + psVip.addBatch(); + } + } + psVip.executeBatch(); + } + + // 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) { + psReg.setInt(1, getId()); + psReg.setInt(2, viptrockmaps.get(i)); + psReg.addBatch(); + } + } + psReg.executeBatch(); + } + + // Buddy + deleteWhereCharacterId(con, "DELETE FROM buddies WHERE characterid = ? AND pending = 0"); + 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()) { + psBuddy.setInt(2, entry.getCharacterId()); + psBuddy.setString(3, entry.getGroup()); + psBuddy.addBatch(); + } + } + psBuddy.executeBatch(); + } + + // Area info + deleteWhereCharacterId(con, "DELETE FROM area_info WHERE charid = ?"); + try (PreparedStatement psArea = con.prepareStatement("INSERT INTO area_info (id, charid, area, info) VALUES (DEFAULT, ?, ?, ?)")) { + psArea.setInt(1, id); + + for (Entry 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 = ?"); + try (PreparedStatement psEvent = con.prepareStatement("INSERT INTO eventstats (characterid, name, info) VALUES (?, ?, ?)")) { + psEvent.setInt(1, id); + + for (Map.Entry entry : events.entrySet()) { + psEvent.setString(2, entry.getKey()); + psEvent.setInt(3, entry.getValue().getInfo()); + psEvent.addBatch(); + } + + psEvent.executeBatch(); + } + + deleteQuestProgressWhereCharacterId(con, 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()) { + 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()) { + 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++) { + psMedal.setInt(1, id); + psMedal.setInt(2, rs.getInt(1)); + psMedal.setInt(3, qs.getMedalMaps().get(i)); + psMedal.addBatch(); + } + psMedal.executeBatch(); + } + } + } + + MapleFamilyEntry familyEntry = getFamilyEntry(); //save family rep + if (familyEntry != null) { + 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(); + } + senior = senior.getSenior(); //save one level up as well + if (senior != null && senior.getChr() == null) { + if (senior.saveReputation(con)) { + senior.savedSuccessfully(); + } + } + } + + } + + if (cashshop != null) { + cashshop.save(con); + } + + if (storage != null && usedStorage) { + storage.saveToDB(con); + usedStorage = false; + } + + con.commit(); + } 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(); - } } } @@ -8910,16 +8800,14 @@ public class MapleCharacter extends AbstractMapleCharacterObject { } public static void sendNote(String to, String from, String msg, byte fame) throws SQLException { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("INSERT INTO notes (`to`, `from`, `message`, `timestamp`, `fame`) VALUES (?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) { + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("INSERT INTO notes (`to`, `from`, `message`, `timestamp`, `fame`) VALUES (?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) { ps.setString(1, to); ps.setString(2, from); ps.setString(3, msg); ps.setLong(4, Server.getInstance().getCurrentTime()); ps.setByte(5, fame); ps.executeUpdate(); - } finally { - con.close(); } } @@ -9033,16 +8921,11 @@ public class MapleCharacter extends AbstractMapleCharacterObject { } public void setHasMerchant(boolean set) { - try { - Connection con = DatabaseConnection.getConnection(); - - try (PreparedStatement ps = con.prepareStatement("UPDATE characters SET HasMerchant = ? WHERE id = ?")) { - ps.setInt(1, set ? 1 : 0); - ps.setInt(2, id); - ps.executeUpdate(); - } - - con.close(); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE characters SET HasMerchant = ? WHERE id = ?")) { + ps.setInt(1, set ? 1 : 0); + ps.setInt(2, id); + ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } @@ -9050,19 +8933,13 @@ public class MapleCharacter extends AbstractMapleCharacterObject { } public void addMerchantMesos(int add) { - int newAmount; - - try { - newAmount = (int) Math.min((long) merchantmeso + add, Integer.MAX_VALUE); - - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("UPDATE characters SET MerchantMesos = ? WHERE id = ?", Statement.RETURN_GENERATED_KEYS)) { - ps.setInt(1, newAmount); - ps.setInt(2, id); - ps.executeUpdate(); - } - - con.close(); + final int newAmount = (int) Math.min((long) merchantmeso + add, Integer.MAX_VALUE); + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE characters SET MerchantMesos = ? WHERE id = ?", Statement.RETURN_GENERATED_KEYS)) { + ps.setInt(1, newAmount); + ps.setInt(2, id); + ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); return; @@ -9071,14 +8948,11 @@ public class MapleCharacter extends AbstractMapleCharacterObject { } public void setMerchantMeso(int set) { - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("UPDATE characters SET MerchantMesos = ? WHERE id = ?", Statement.RETURN_GENERATED_KEYS)) { - ps.setInt(1, set); - ps.setInt(2, id); - ps.executeUpdate(); - } - con.close(); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE characters SET MerchantMesos = ? WHERE id = ?", Statement.RETURN_GENERATED_KEYS)) { + ps.setInt(1, set); + ps.setInt(2, id); + ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); return; @@ -9350,16 +9224,13 @@ public class MapleCharacter extends AbstractMapleCharacterObject { public void changeName(String name) { FredrickProcessor.removeFredrickReminders(this.getId()); - + this.name = name; - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("UPDATE `characters` SET `name` = ? WHERE `id` = ?"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE `characters` SET `name` = ? WHERE `id` = ?")) { ps.setString(1, name); ps.setInt(2, id); ps.executeUpdate(); - ps.close(); - con.close(); } catch (SQLException e) { e.printStackTrace(); } @@ -9771,22 +9642,17 @@ public class MapleCharacter extends AbstractMapleCharacterObject { public void showHint(String msg, int length) { client.announceHint(msg, length); } - + public void showNote() { - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("SELECT * FROM notes WHERE `to` = ? AND `deleted` = 0", - ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { - ps.setString(1, this.getName()); - try (ResultSet rs = ps.executeQuery()) { - rs.last(); - int count = rs.getRow(); - rs.first(); - client.announce(MaplePacketCreator.showNotes(rs, count)); - } + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT * FROM notes WHERE `to` = ? AND `deleted` = 0", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { + ps.setString(1, this.getName()); + try (ResultSet rs = ps.executeQuery()) { + rs.last(); + int count = rs.getRow(); + rs.first(); + client.announce(MaplePacketCreator.showNotes(rs, count)); } - - con.close(); } catch (SQLException e) { e.printStackTrace(); } @@ -10336,18 +10202,15 @@ public class MapleCharacter extends AbstractMapleCharacterObject { public void block(int reason, int days, String desc) { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, days); - Timestamp TS = new Timestamp(cal.getTimeInMillis()); - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("UPDATE accounts SET banreason = ?, tempban = ?, greason = ? WHERE id = ?")) { - ps.setString(1, desc); - ps.setTimestamp(2, TS); - ps.setInt(3, reason); - ps.setInt(4, accountid); - ps.executeUpdate(); - } finally { - con.close(); - } + final Timestamp TS = new Timestamp(cal.getTimeInMillis()); + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE accounts SET banreason = ?, tempban = ?, greason = ? WHERE id = ?")) { + ps.setString(1, desc); + ps.setTimestamp(2, TS); + ps.setInt(3, reason); + ps.setInt(4, accountid); + ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } @@ -10668,11 +10531,12 @@ public class MapleCharacter extends AbstractMapleCharacterObject { }, 5 * 60 * 1000); } } - + public void logOff() { this.loggedIn = false; - try (Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("UPDATE characters SET lastLogoutTime=? WHERE id=?")) { + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE characters SET lastLogoutTime=? WHERE id=?")) { ps.setTimestamp(1, new Timestamp(System.currentTimeMillis())); ps.setInt(2, getId()); ps.executeUpdate(); @@ -10786,43 +10650,51 @@ public class MapleCharacter extends AbstractMapleCharacterObject { long currentTimeMillis = System.currentTimeMillis(); try (PreparedStatement ps = con.prepareStatement("SELECT completionTime FROM namechanges WHERE characterid=?")) { //double check, just in case ps.setInt(1, getId()); - ResultSet rs = ps.executeQuery(); - while(rs.next()) { - Timestamp completedTimestamp = rs.getTimestamp("completionTime"); - if(completedTimestamp == null) return false; //pending - else if(completedTimestamp.getTime() + YamlConfig.config.server.NAME_CHANGE_COOLDOWN > currentTimeMillis) return false; + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + Timestamp completedTimestamp = rs.getTimestamp("completionTime"); + if (completedTimestamp == null) { + return false; //pending + } else if (completedTimestamp.getTime() + YamlConfig.config.server.NAME_CHANGE_COOLDOWN > currentTimeMillis) { + return false; + } + } } - } catch(SQLException e) { + } catch (SQLException e) { e.printStackTrace(); FilePrinter.printError(FilePrinter.CHANGE_CHARACTER_NAME, e, "Failed to register name change for character " + getName() + "."); return false; } - try (PreparedStatement ps = con.prepareStatement("INSERT INTO namechanges (characterid, old, new) VALUES (?, ?, ?)")){ - ps.setInt(1, getId()); - ps.setString(2, getName()); - ps.setString(3, newName); - ps.executeUpdate(); - this.pendingNameChange = true; - return true; + + try (PreparedStatement ps = con.prepareStatement("INSERT INTO namechanges (characterid, old, new) VALUES (?, ?, ?)")) { + ps.setInt(1, getId()); + ps.setString(2, getName()); + ps.setString(3, newName); + ps.executeUpdate(); + this.pendingNameChange = true; + return true; } catch (SQLException e) { e.printStackTrace(); FilePrinter.printError(FilePrinter.CHANGE_CHARACTER_NAME, e, "Failed to register name change for character " + getName() + "."); } - } catch(SQLException e) { + } catch (SQLException e) { e.printStackTrace(); FilePrinter.printError(FilePrinter.CHANGE_CHARACTER_NAME, e, "Failed to get DB connection."); } return false; } - + public boolean cancelPendingNameChange() { try (Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("DELETE FROM namechanges WHERE characterid=? AND completionTime IS NULL")) { + PreparedStatement ps = con.prepareStatement("DELETE FROM namechanges WHERE characterid=? AND completionTime IS NULL")) { ps.setInt(1, getId()); int affectedRows = ps.executeUpdate(); - if(affectedRows > 0) pendingNameChange = false; + if (affectedRows > 0) { + pendingNameChange = false; + } return affectedRows > 0; //rows affected - } catch(SQLException e) { + } catch (SQLException e) { e.printStackTrace(); FilePrinter.printError(FilePrinter.CHANGE_CHARACTER_NAME, e, "Failed to cancel name change for character " + getName() + "."); return false; @@ -10830,26 +10702,36 @@ public class MapleCharacter extends AbstractMapleCharacterObject { } public void doPendingNameChange() { //called on logout - if(!pendingNameChange) return; + if (!pendingNameChange) { + return; + } + try (Connection con = DatabaseConnection.getConnection()) { int nameChangeId = -1; String newName = null; try (PreparedStatement ps = con.prepareStatement("SELECT * FROM namechanges WHERE characterid = ? AND completionTime IS NULL")) { ps.setInt(1, getId()); - ResultSet rs = ps.executeQuery(); - if(!rs.next()) return; - nameChangeId = rs.getInt("id"); - newName = rs.getString("new"); - } catch(SQLException e) { + try (ResultSet rs = ps.executeQuery()) { + if (!rs.next()) { + return; + } + nameChangeId = rs.getInt("id"); + newName = rs.getString("new"); + } + } catch (SQLException e) { e.printStackTrace(); FilePrinter.printError(FilePrinter.CHANGE_CHARACTER_NAME, e, "Failed to retrieve pending name changes for character " + getName() + "."); } + con.setAutoCommit(false); boolean success = doNameChange(con, getId(), getName(), newName, nameChangeId); - if(!success) con.rollback(); - else FilePrinter.print(FilePrinter.CHANGE_CHARACTER_NAME, "Name change applied : from \"" + getName() + "\" to \"" + newName + "\" at " + Calendar.getInstance().getTime().toString()); + if (!success) { + con.rollback(); + } else { + FilePrinter.print(FilePrinter.CHANGE_CHARACTER_NAME, "Name change applied : from \"" + getName() + "\" to \"" + newName + "\" at " + Calendar.getInstance().getTime().toString()); + } con.setAutoCommit(true); - } catch(SQLException e) { + } catch (SQLException e) { e.printStackTrace(); FilePrinter.printError(FilePrinter.CHANGE_CHARACTER_NAME, e, "Failed to get DB connection."); } @@ -10859,9 +10741,11 @@ public class MapleCharacter extends AbstractMapleCharacterObject { try (Connection con = DatabaseConnection.getConnection()) { con.setAutoCommit(false); boolean success = doNameChange(con, characterId, oldName, newName, nameChangeId); - if(!success) con.rollback(); + if (!success) { + con.rollback(); + } con.setAutoCommit(true); - } catch(SQLException e) { + } catch (SQLException e) { e.printStackTrace(); FilePrinter.printError(FilePrinter.CHANGE_CHARACTER_NAME, e, "Failed to get DB connection."); } @@ -10872,20 +10756,22 @@ public class MapleCharacter extends AbstractMapleCharacterObject { ps.setString(1, newName); ps.setInt(2, characterId); ps.executeUpdate(); - } catch(SQLException e) { + } catch (SQLException e) { e.printStackTrace(); FilePrinter.printError(FilePrinter.CHANGE_CHARACTER_NAME, e, "Character ID : " + characterId); return false; } + try (PreparedStatement ps = con.prepareStatement("UPDATE rings SET partnername = ? WHERE partnername = ?")) { ps.setString(1, newName); ps.setString(2, oldName); ps.executeUpdate(); - } catch(SQLException e) { + } catch (SQLException e) { e.printStackTrace(); FilePrinter.printError(FilePrinter.CHANGE_CHARACTER_NAME, e, "Character ID : " + characterId); return false; } + /*try (PreparedStatement ps = con.prepareStatement("UPDATE playernpcs SET name = ? WHERE name = ?")) { ps.setString(1, newName); ps.setString(2, oldName); @@ -10895,6 +10781,7 @@ public class MapleCharacter extends AbstractMapleCharacterObject { FilePrinter.printError(FilePrinter.CHANGE_CHARACTER_NAME, e, "Character ID : " + characterId); return false; } + try (PreparedStatement ps = con.prepareStatement("UPDATE gifts SET `from` = ? WHERE `from` = ?")) { ps.setString(1, newName); ps.setString(2, oldName); @@ -10913,6 +10800,7 @@ public class MapleCharacter extends AbstractMapleCharacterObject { FilePrinter.printError(FilePrinter.CHANGE_CHARACTER_NAME, e, "Character ID : " + characterId); return false; } + try (PreparedStatement ps = con.prepareStatement("UPDATE dueypackages SET SenderName = ? WHERE SenderName = ?")) { ps.setString(1, newName); ps.setString(2, oldName); @@ -10922,6 +10810,7 @@ public class MapleCharacter extends AbstractMapleCharacterObject { FilePrinter.printError(FilePrinter.CHANGE_CHARACTER_NAME, e, "Character ID : " + characterId); return false; } + try (PreparedStatement ps = con.prepareStatement("UPDATE inventoryitems SET owner = ? WHERE owner = ?")) { //GMS doesn't do this ps.setString(1, newName); ps.setString(2, oldName); @@ -10931,6 +10820,7 @@ public class MapleCharacter extends AbstractMapleCharacterObject { FilePrinter.printError(FilePrinter.CHANGE_CHARACTER_NAME, e, "Character ID : " + characterId); return false; } + try (PreparedStatement ps = con.prepareStatement("UPDATE mts_items SET owner = ? WHERE owner = ?")) { //GMS doesn't do this ps.setString(1, newName); ps.setString(2, oldName); @@ -10940,6 +10830,7 @@ public class MapleCharacter extends AbstractMapleCharacterObject { FilePrinter.printError(FilePrinter.CHANGE_CHARACTER_NAME, e, "Character ID : " + characterId); return false; } + try (PreparedStatement ps = con.prepareStatement("UPDATE newyear SET sendername = ? WHERE sendername = ?")) { ps.setString(1, newName); ps.setString(2, oldName); @@ -10949,6 +10840,7 @@ public class MapleCharacter extends AbstractMapleCharacterObject { FilePrinter.printError(FilePrinter.CHANGE_CHARACTER_NAME, e, "Character ID : " + characterId); return false; } + try (PreparedStatement ps = con.prepareStatement("UPDATE newyear SET receivername = ? WHERE receivername = ?")) { ps.setString(1, newName); ps.setString(2, oldName); @@ -10958,6 +10850,7 @@ public class MapleCharacter extends AbstractMapleCharacterObject { FilePrinter.printError(FilePrinter.CHANGE_CHARACTER_NAME, e, "Character ID : " + characterId); return false; } + try (PreparedStatement ps = con.prepareStatement("UPDATE notes SET `to` = ? WHERE `to` = ?")) { ps.setString(1, newName); ps.setString(2, oldName); @@ -10967,6 +10860,7 @@ public class MapleCharacter extends AbstractMapleCharacterObject { FilePrinter.printError(FilePrinter.CHANGE_CHARACTER_NAME, e, "Character ID : " + characterId); return false; } + try (PreparedStatement ps = con.prepareStatement("UPDATE notes SET `from` = ? WHERE `from` = ?")) { ps.setString(1, newName); ps.setString(2, oldName); @@ -10976,6 +10870,7 @@ public class MapleCharacter extends AbstractMapleCharacterObject { FilePrinter.printError(FilePrinter.CHANGE_CHARACTER_NAME, e, "Character ID : " + characterId); return false; } + try (PreparedStatement ps = con.prepareStatement("UPDATE nxcode SET retriever = ? WHERE retriever = ?")) { ps.setString(1, newName); ps.setString(2, oldName); @@ -10985,12 +10880,13 @@ public class MapleCharacter extends AbstractMapleCharacterObject { FilePrinter.printError(FilePrinter.CHANGE_CHARACTER_NAME, e, "Character ID : " + characterId); return false; }*/ - if(nameChangeId != -1) { + + if (nameChangeId != -1) { try (PreparedStatement ps = con.prepareStatement("UPDATE namechanges SET completionTime = ? WHERE id = ?")) { ps.setTimestamp(1, new Timestamp(System.currentTimeMillis())); ps.setInt(2, nameChangeId); ps.executeUpdate(); - } catch(SQLException e) { + } catch (SQLException e) { e.printStackTrace(); FilePrinter.printError(FilePrinter.CHANGE_CHARACTER_NAME, e, "Character ID : " + characterId); return false; @@ -11068,27 +10964,31 @@ public class MapleCharacter extends AbstractMapleCharacterObject { try (PreparedStatement ps = con.prepareStatement("SELECT completionTime FROM worldtransfers WHERE characterid=?")) { //double check, just in case ps.setInt(1, getId()); ResultSet rs = ps.executeQuery(); - while(rs.next()) { + while (rs.next()) { Timestamp completedTimestamp = rs.getTimestamp("completionTime"); - if(completedTimestamp == null) return false; //pending - else if(completedTimestamp.getTime() + YamlConfig.config.server.WORLD_TRANSFER_COOLDOWN > currentTimeMillis) return false; + if (completedTimestamp == null) { + return false; //pending + } else if (completedTimestamp.getTime() + YamlConfig.config.server.WORLD_TRANSFER_COOLDOWN > currentTimeMillis) { + return false; + } } - } catch(SQLException e) { + } catch (SQLException e) { e.printStackTrace(); FilePrinter.printError(FilePrinter.WORLD_TRANSFER, e, "Failed to register world transfer for character " + getName() + "."); return false; } - try (PreparedStatement ps = con.prepareStatement("INSERT INTO worldtransfers (characterid, `from`, `to`) VALUES (?, ?, ?)")){ - ps.setInt(1, getId()); - ps.setInt(2, getWorld()); - ps.setInt(3, newWorld); - ps.executeUpdate(); - return true; + + try (PreparedStatement ps = con.prepareStatement("INSERT INTO worldtransfers (characterid, `from`, `to`) VALUES (?, ?, ?)")) { + ps.setInt(1, getId()); + ps.setInt(2, getWorld()); + ps.setInt(3, newWorld); + ps.executeUpdate(); + return true; } catch (SQLException e) { e.printStackTrace(); FilePrinter.printError(FilePrinter.WORLD_TRANSFER, e, "Failed to register world transfer for character " + getName() + "."); } - } catch(SQLException e) { + } catch (SQLException e) { e.printStackTrace(); FilePrinter.printError(FilePrinter.WORLD_TRANSFER, e, "Failed to get DB connection."); } @@ -11097,11 +10997,11 @@ public class MapleCharacter extends AbstractMapleCharacterObject { public boolean cancelPendingWorldTranfer() { try (Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("DELETE FROM worldtransfers WHERE characterid=? AND completionTime IS NULL")) { + PreparedStatement ps = con.prepareStatement("DELETE FROM worldtransfers WHERE characterid=? AND completionTime IS NULL")) { ps.setInt(1, getId()); int affectedRows = ps.executeUpdate(); return affectedRows > 0; //rows affected - } catch(SQLException e) { + } catch (SQLException e) { e.printStackTrace(); FilePrinter.printError(FilePrinter.WORLD_TRANSFER, e, "Failed to cancel pending world transfer for character " + getName() + "."); return false; @@ -11167,11 +11067,8 @@ public class MapleCharacter extends AbstractMapleCharacterObject { } public int getRewardPoints() { - Connection con = null; - PreparedStatement ps = null; - try { - con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("SELECT rewardpoints FROM accounts WHERE id=?;"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT rewardpoints FROM accounts WHERE id=?;")) { ps.setInt(1, accountid); ResultSet resultSet = ps.executeQuery(); int point = -1; @@ -11181,27 +11078,18 @@ public class MapleCharacter extends AbstractMapleCharacterObject { return point; } catch (SQLException e) { e.printStackTrace(); - } finally { - try { ps.close(); } catch (Exception e) { /* ignored */ } - try { con.close(); } catch (Exception e) { /* ignored */ } } return -1; } public void setRewardPoints(int value) { - Connection con = null; - PreparedStatement ps = null; - try { - con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("UPDATE accounts SET rewardpoints=? WHERE id=?;"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE accounts SET rewardpoints=? WHERE id=?;")) { ps.setInt(1, value); ps.setInt(2, accountid); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); - } finally { - try { ps.close(); } catch (Exception e) { /* ignored */ } - try { con.close(); } catch (Exception e) { /* ignored */ } } } @@ -11210,19 +11098,14 @@ public class MapleCharacter extends AbstractMapleCharacterObject { yellowMessage("Rebirth system is not enabled!"); throw new NotEnabledException(); } - Connection con = null; - PreparedStatement ps = null; - try { - con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("UPDATE characters SET reborns=? WHERE id=?;"); + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE characters SET reborns=? WHERE id=?;")) { ps.setInt(1, value); ps.setInt(2, id); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); - } finally { - try { ps.close(); } catch (Exception e) { /* ignored */ } - try { con.close(); } catch (Exception e) { /* ignored */ } } } @@ -11235,20 +11118,17 @@ public class MapleCharacter extends AbstractMapleCharacterObject { yellowMessage("Rebirth system is not enabled!"); throw new NotEnabledException(); } - Connection con = null; - PreparedStatement ps = null; - try { - con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("SELECT reborns FROM characters WHERE id=?;"); + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT reborns FROM characters WHERE id=?;")) { ps.setInt(1, id); - ResultSet resultSet = ps.executeQuery(); - resultSet.next(); - return resultSet.getInt(1); + + try (ResultSet rs = ps.executeQuery()) { + rs.next(); + return rs.getInt(1); + } } catch (SQLException e) { e.printStackTrace(); - } finally { - try { ps.close(); } catch (Exception e) { /* ignored */ } - try { con.close(); } catch (Exception e) { /* ignored */ } } throw new RuntimeException(); } @@ -11429,15 +11309,12 @@ public class MapleCharacter extends AbstractMapleCharacterObject { public void setLanguage(int num) { getClient().setLanguage(num); - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("UPDATE accounts SET language = ? WHERE id = ?")) { - ps.setInt(1, num); - ps.setInt(2, getClient().getAccID()); - ps.executeUpdate(); - } finally { - con.close(); - } + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE accounts SET language = ? WHERE id = ?")) { + ps.setInt(1, num); + ps.setInt(2, getClient().getAccID()); + ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } diff --git a/src/main/java/client/MapleClient.java b/src/main/java/client/MapleClient.java index 8f131fa660..7195a4133b 100644 --- a/src/main/java/client/MapleClient.java +++ b/src/main/java/client/MapleClient.java @@ -21,47 +21,21 @@ along with this program. If not, see . */ package client; -import java.io.*; -import java.net.InetAddress; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.sql.*; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.Semaphore; -import java.util.concurrent.locks.Lock; - +import client.inventory.MapleInventoryType; import config.YamlConfig; +import constants.game.GameConstants; import jdk.nashorn.api.scripting.NashornScriptEngine; -import tools.*; - import net.server.Server; +import net.server.audit.locks.MonitoredLockType; +import net.server.audit.locks.factory.MonitoredReentrantLockFactory; +import net.server.channel.Channel; +import net.server.coordinator.login.MapleLoginBypassCoordinator; import net.server.coordinator.session.MapleSessionCoordinator; import net.server.coordinator.session.MapleSessionCoordinator.AntiMulticlientResult; -import net.server.channel.Channel; import net.server.guild.MapleGuild; import net.server.guild.MapleGuildCharacter; -import net.server.world.MapleMessengerCharacter; -import net.server.world.MapleParty; -import net.server.world.MaplePartyCharacter; -import net.server.world.PartyOperation; -import net.server.world.World; - +import net.server.world.*; import org.apache.mina.core.session.IoSession; - -import client.inventory.MapleInventoryType; -import constants.game.GameConstants; import scripting.AbstractPlayerInteraction; import scripting.event.EventInstanceManager; import scripting.event.EventManager; @@ -69,13 +43,23 @@ import scripting.npc.NPCConversationManager; import scripting.npc.NPCScriptManager; import scripting.quest.QuestActionManager; import scripting.quest.QuestScriptManager; -import server.life.MapleMonster; import server.ThreadManager; -import server.maps.*; +import server.life.MapleMonster; +import server.maps.FieldLimit; +import server.maps.MapleMap; +import server.maps.MapleMiniDungeonInfo; +import tools.*; -import net.server.audit.locks.MonitoredLockType; -import net.server.audit.locks.factory.MonitoredReentrantLockFactory; -import net.server.coordinator.login.MapleLoginBypassCoordinator; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.InetAddress; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.*; +import java.util.Date; +import java.util.*; +import java.util.concurrent.Semaphore; +import java.util.concurrent.locks.Lock; public class MapleClient { @@ -193,20 +177,17 @@ public class MapleClient { } private List loadCharactersInternal(int worldId) { - PreparedStatement ps; List chars = new ArrayList<>(15); - try { - Connection con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("SELECT id, name FROM characters WHERE accountid = ? AND world = ?"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT id, name FROM characters WHERE accountid = ? AND world = ?")) { ps.setInt(1, this.getAccID()); ps.setInt(2, worldId); + try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { chars.add(new CharNameAndId(rs.getString("name"), rs.getInt("id"))); } } - ps.close(); - con.close(); } catch (SQLException e) { e.printStackTrace(); } @@ -219,40 +200,35 @@ public class MapleClient { public boolean hasBannedIP() { boolean ret = false; - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("SELECT COUNT(*) FROM ipbans WHERE ? LIKE CONCAT(ip, '%')")) { - ps.setString(1, session.getRemoteAddress().toString()); - try (ResultSet rs = ps.executeQuery()) { - rs.next(); - if (rs.getInt(1) > 0) { - ret = true; - } + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT COUNT(*) FROM ipbans WHERE ? LIKE CONCAT(ip, '%')")) { + ps.setString(1, session.getRemoteAddress().toString()); + try (ResultSet rs = ps.executeQuery()) { + rs.next(); + if (rs.getInt(1) > 0) { + ret = true; } } - con.close(); } catch (SQLException e) { - e.printStackTrace(); + e.printStackTrace(); } return ret; } - public int getVoteTime(){ - if (voteTime != -1){ + public int getVoteTime() { + if (voteTime != -1) { return voteTime; } - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("SELECT date FROM bit_votingrecords WHERE UPPER(account) = UPPER(?)")) { - ps.setString(1, accountName); - try (ResultSet rs = ps.executeQuery()) { - if (!rs.next()) { - return -1; - } - voteTime = rs.getInt("date"); + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT date FROM bit_votingrecords WHERE UPPER(account) = UPPER(?)")) { + ps.setString(1, accountName); + try (ResultSet rs = ps.executeQuery()) { + if (!rs.next()) { + return -1; } + voteTime = rs.getInt("date"); } - con.close(); } catch (SQLException e) { FilePrinter.printError("hasVotedAlready.txt", e); return -1; @@ -270,40 +246,28 @@ public class MapleClient { int difference = (timeNow - getVoteTime()); return difference < 86400 && difference > 0; } - + public boolean hasBannedHWID() { - if(hwid == null) { - return false; - } - + if (hwid == null) { + return false; + } + boolean ret = false; - PreparedStatement ps = null; - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("SELECT COUNT(*) FROM hwidbans WHERE hwid LIKE ?"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT COUNT(*) FROM hwidbans WHERE hwid LIKE ?")) { ps.setString(1, hwid); - ResultSet rs = ps.executeQuery(); - if(rs != null && rs.next()) { - if(rs.getInt(1) > 0) - ret = true; + + try (ResultSet rs = ps.executeQuery()) { + if (rs != null && rs.next()) { + if (rs.getInt(1) > 0) { + ret = true; + } + } } } catch (SQLException e) { e.printStackTrace(); - } finally { - try { - if(ps != null && !ps.isClosed()) { - ps.close(); - } - - if(con != null && !con.isClosed()) { - con.close(); - } - } catch (SQLException e){ - e.printStackTrace(); - } } - + return ret; } @@ -313,59 +277,54 @@ public class MapleClient { } boolean ret = false; int i; - try { - StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM macbans WHERE mac IN ("); - for (i = 0; i < macs.size(); i++) { - sql.append("?"); - if (i != macs.size() - 1) { - sql.append(", "); + StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM macbans WHERE mac IN ("); + for (i = 0; i < macs.size(); i++) { + sql.append("?"); + if (i != macs.size() - 1) { + sql.append(", "); + } + } + sql.append(")"); + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement(sql.toString())) { + i = 0; + for (String mac : macs) { + ps.setString(++i, mac); + } + try (ResultSet rs = ps.executeQuery()) { + rs.next(); + if (rs.getInt(1) > 0) { + ret = true; } } - sql.append(")"); - - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement(sql.toString())) { - i = 0; - for (String mac : macs) { - i++; - ps.setString(i, mac); - } - try (ResultSet rs = ps.executeQuery()) { - rs.next(); - if (rs.getInt(1) > 0) { - ret = true; - } - } - } finally { - con.close(); - } } catch (Exception e) { - e.printStackTrace(); + e.printStackTrace(); } + return ret; } - + private void loadHWIDIfNescessary() throws SQLException { - if(hwid == null) { - Connection con = DatabaseConnection.getConnection(); - try(PreparedStatement ps = con.prepareStatement("SELECT hwid FROM accounts WHERE id = ?")) { + if (hwid == null) { + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT hwid FROM accounts WHERE id = ?")) { ps.setInt(1, accId); - try(ResultSet rs = ps.executeQuery()) { - if(rs.next()) { + + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { hwid = rs.getString("hwid"); } } - } finally { - con.close(); - } + } } } // TODO: Recode to close statements... private void loadMacsIfNescessary() throws SQLException { if (macs.isEmpty()) { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("SELECT macs FROM accounts WHERE id = ?")) { + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT macs FROM accounts WHERE id = ?")) { ps.setInt(1, accId); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { @@ -376,70 +335,56 @@ public class MapleClient { } } } - } finally { - con.close(); - } - } - } - - public void banHWID() { - PreparedStatement ps = null; - Connection con = null; - try { - loadHWIDIfNescessary(); - - con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("INSERT INTO hwidbans (hwid) VALUES (?)"); - ps.setString(1, hwid); - ps.executeUpdate(); - } catch (SQLException e) { - e.printStackTrace(); - } finally { - try { - if(ps != null && !ps.isClosed()) { - ps.close(); - } - if(con != null && !con.isClosed()) { - con.close(); - } - } catch (SQLException e) { - e.printStackTrace(); } } } + public void banHWID() { + try { + loadHWIDIfNescessary(); + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("INSERT INTO hwidbans (hwid) VALUES (?)")) { + ps.setString(1, hwid); + ps.executeUpdate(); + } + } catch (SQLException e) { + e.printStackTrace(); + } + } + public void banMacs() { - Connection con = null; try { loadMacsIfNescessary(); - - con = DatabaseConnection.getConnection(); + List filtered = new LinkedList<>(); - try (PreparedStatement ps = con.prepareStatement("SELECT filter FROM macfilters"); ResultSet rs = ps.executeQuery()) { - while (rs.next()) { - filtered.add(rs.getString("filter")); + try (Connection con = DatabaseConnection.getConnection()) { + try (PreparedStatement ps = con.prepareStatement("SELECT filter FROM macfilters"); + ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + filtered.add(rs.getString("filter")); + } } - } - try (PreparedStatement ps = con.prepareStatement("INSERT INTO macbans (mac, aid) VALUES (?, ?)")) { - for (String mac : macs) { - boolean matched = false; - for (String filter : filtered) { - if (mac.matches(filter)) { - matched = true; - break; + + try (PreparedStatement ps = con.prepareStatement("INSERT INTO macbans (mac, aid) VALUES (?, ?)")) { + for (String mac : macs) { + boolean matched = false; + for (String filter : filtered) { + if (mac.matches(filter)) { + matched = true; + break; + } + } + if (!matched) { + ps.setString(1, mac); + ps.setString(2, String.valueOf(getAccID())); + ps.executeUpdate(); } } - if (!matched) { - ps.setString(1, mac); - ps.setString(2, String.valueOf(getAccID())); - ps.executeUpdate(); - } } } - - con.close(); } catch (SQLException e) { - e.printStackTrace(); + e.printStackTrace(); } } @@ -460,17 +405,13 @@ public class MapleClient { public void setPin(String pin) { this.pin = pin; - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("UPDATE accounts SET pin = ? WHERE id = ?")) { - ps.setString(1, pin); - ps.setInt(2, accId); - ps.executeUpdate(); - } finally { - con.close(); - } + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE accounts SET pin = ? WHERE id = ?")) { + ps.setString(1, pin); + ps.setInt(2, accId); + ps.executeUpdate(); } catch (SQLException e) { - e.printStackTrace(); + e.printStackTrace(); } } @@ -497,17 +438,13 @@ public class MapleClient { public void setPic(String pic) { this.pic = pic; - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("UPDATE accounts SET pic = ? WHERE id = ?")) { - ps.setString(1, pic); - ps.setInt(2, accId); - ps.executeUpdate(); - } finally { - con.close(); - } + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE accounts SET pic = ? WHERE id = ?")) { + ps.setString(1, pic); + ps.setInt(2, accId); + ps.executeUpdate(); } catch (SQLException e) { - e.printStackTrace(); + e.printStackTrace(); } } @@ -534,128 +471,109 @@ public class MapleClient { public int login(String login, String pwd, String nibbleHwid) { int loginok = 5; - + loginattempt++; - if (loginattempt > 4) { - loggedIn = false; + if (loginattempt > 4) { + loggedIn = false; MapleSessionCoordinator.getInstance().closeSession(session, false); - return 6; // thanks Survival_Project for finding out an issue with AUTOMATIC_REGISTER here + return 6; // thanks Survival_Project for finding out an issue with AUTOMATIC_REGISTER here } - - Connection con = null; - PreparedStatement ps = null; - ResultSet rs = null; - try { - con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("SELECT id, password, gender, banned, pin, pic, characterslots, tos, language FROM accounts WHERE name = ?"); + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT id, password, gender, banned, pin, pic, characterslots, tos, language FROM accounts WHERE name = ?")) { ps.setString(1, login); - rs = ps.executeQuery(); - accId = -2; - if (rs.next()) { - accId = rs.getInt("id"); - if (accId <= 0) { - FilePrinter.printError(FilePrinter.LOGIN_EXCEPTION, "Tried to login with accid " + accId); - return 15; - } - - boolean banned = (rs.getByte("banned") == 1); - gmlevel = 0; - pin = rs.getString("pin"); - pic = rs.getString("pic"); - gender = rs.getByte("gender"); - characterSlots = rs.getByte("characterslots"); - lang = rs.getInt("language"); - String passhash = rs.getString("password"); - byte tos = rs.getByte("tos"); - ps.close(); - rs.close(); + try (ResultSet rs = ps.executeQuery()) { + accId = -2; + if (rs.next()) { + accId = rs.getInt("id"); + if (accId <= 0) { + FilePrinter.printError(FilePrinter.LOGIN_EXCEPTION, "Tried to login with accid " + accId); + return 15; + } - if (banned) { - return 3; - } + boolean banned = (rs.getByte("banned") == 1); + gmlevel = 0; + pin = rs.getString("pin"); + pic = rs.getString("pic"); + gender = rs.getByte("gender"); + characterSlots = rs.getByte("characterslots"); + lang = rs.getInt("language"); + String passhash = rs.getString("password"); + byte tos = rs.getByte("tos"); - if (getLoginState() > LOGIN_NOTLOGGEDIN) { // already loggedin - loggedIn = false; - loginok = 7; - } else if (passhash.charAt(0) == '$' && passhash.charAt(1) == '2' && BCrypt.checkpw(pwd, passhash)) { - loginok = (tos == 0) ? 23 : 0; - } else if (pwd.equals(passhash) || checkHash(passhash, "SHA-1", pwd) || checkHash(passhash, "SHA-512", pwd)) { - // thanks GabrielSin for detecting some no-bcrypt inconsistencies here - loginok = (tos == 0) ? (!YamlConfig.config.server.BCRYPT_MIGRATION ? 23 : -23) : (!YamlConfig.config.server.BCRYPT_MIGRATION ? 0 : -10); // migrate to bcrypt + if (banned) { + return 3; + } + + if (getLoginState() > LOGIN_NOTLOGGEDIN) { // already loggedin + loggedIn = false; + loginok = 7; + } else if (passhash.charAt(0) == '$' && passhash.charAt(1) == '2' && BCrypt.checkpw(pwd, passhash)) { + loginok = (tos == 0) ? 23 : 0; + } else if (pwd.equals(passhash) || checkHash(passhash, "SHA-1", pwd) || checkHash(passhash, "SHA-512", pwd)) { + // thanks GabrielSin for detecting some no-bcrypt inconsistencies here + loginok = (tos == 0) ? (!YamlConfig.config.server.BCRYPT_MIGRATION ? 23 : -23) : (!YamlConfig.config.server.BCRYPT_MIGRATION ? 0 : -10); // migrate to bcrypt + } else { + loggedIn = false; + loginok = 4; + } } else { - loggedIn = false; - loginok = 4; + accId = -3; } - } else { - accId = -3; - } + } } catch (SQLException e) { e.printStackTrace(); - } finally { - try { - if (ps != null && !ps.isClosed()) { - ps.close(); - } - if (rs != null && !rs.isClosed()) { - rs.close(); - } - if (con != null && !con.isClosed()) { - con.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } } - + if (loginok == 0 || loginok == 4) { - AntiMulticlientResult res = MapleSessionCoordinator.getInstance().attemptLoginSession(session, nibbleHwid, accId, loginok == 4); - - switch (res) { - case SUCCESS: - if (loginok == 0) { - loginattempt = 0; - } - - return loginok; + AntiMulticlientResult res = MapleSessionCoordinator.getInstance().attemptLoginSession(session, nibbleHwid, accId, loginok == 4); - case REMOTE_LOGGEDIN: - return 17; + switch (res) { + case SUCCESS: + if (loginok == 0) { + loginattempt = 0; + } - case REMOTE_REACHED_LIMIT: - return 13; + return loginok; - case REMOTE_PROCESSING: - return 10; - - case MANY_ACCOUNT_ATTEMPTS: - return 16; + case REMOTE_LOGGEDIN: + return 17; - default: - return 8; - } + case REMOTE_REACHED_LIMIT: + return 13; + + case REMOTE_PROCESSING: + return 10; + + case MANY_ACCOUNT_ATTEMPTS: + return 16; + + default: + return 8; + } } else { - return loginok; - } + return loginok; + } } public Calendar getTempBanCalendarFromDB() { - Connection con = null; - PreparedStatement ps = null; - ResultSet rs = null; final Calendar lTempban = Calendar.getInstance(); - try { - con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("SELECT `tempban` FROM accounts WHERE id = ?"); - ps.setInt(1, getAccID()); - rs = ps.executeQuery(); - if (!rs.next()) { - return null; - } - final Timestamp tempban = rs.getTimestamp("tempban"); - if (tempban.toLocalDateTime().equals(DefaultDates.getTempban())) { - return null; + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT `tempban` FROM accounts WHERE id = ?")) { + ps.setInt(1, getAccID()); + + final Timestamp tempban; + try (ResultSet rs = ps.executeQuery()) { + if (!rs.next()) { + return null; + } + + tempban = rs.getTimestamp("tempban"); + if (tempban.toLocalDateTime().equals(DefaultDates.getTempban())) { + return null; + } } lTempban.setTimeInMillis(tempban.getTime()); @@ -663,21 +581,8 @@ public class MapleClient { return lTempban; } catch (SQLException e) { e.printStackTrace(); - } finally { - try { - if (ps != null) { - ps.close(); - } - if (rs != null) { - rs.close(); - } - if (con != null && !con.isClosed()) { - con.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } } + return null;//why oh why!?! } @@ -704,40 +609,25 @@ public class MapleClient { public void updateHWID(String newHwid) { String[] split = newHwid.split("_"); - if(split.length > 1 && split[1].length() == 8) { + if (split.length > 1 && split[1].length() == 8) { StringBuilder hwid = new StringBuilder(); - String convert = split[1]; - + String convert = split[1]; + int len = convert.length(); - for(int i=len-2; i>=0; i -= 2) { + for (int i = len - 2; i >= 0; i -= 2) { hwid.append(convert.substring(i, i + 2)); } hwid.insert(4, "-"); - + this.hwid = hwid.toString(); - - PreparedStatement ps = null; - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("UPDATE accounts SET hwid = ? WHERE id = ?"); + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE accounts SET hwid = ? WHERE id = ?")) { ps.setString(1, this.hwid); ps.setInt(2, accId); ps.executeUpdate(); - ps.close(); } catch (SQLException e) { e.printStackTrace(); - } finally { - try { - if(ps != null && !ps.isClosed()) { - ps.close(); - } - if(con != null && !con.isClosed()) { - con.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } } } else { this.disconnect(false, false); // Invalid HWID... @@ -748,7 +638,6 @@ public class MapleClient { macs.addAll(Arrays.asList(macData.split(", "))); StringBuilder newMacData = new StringBuilder(); Iterator iter = macs.iterator(); - PreparedStatement ps = null; while (iter.hasNext()) { String cur = iter.next(); newMacData.append(cur); @@ -756,27 +645,14 @@ public class MapleClient { newMacData.append(", "); } } - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("UPDATE accounts SET macs = ? WHERE id = ?"); + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE accounts SET macs = ? WHERE id = ?")) { ps.setString(1, newMacData.toString()); ps.setInt(2, accId); ps.executeUpdate(); - ps.close(); } catch (SQLException e) { e.printStackTrace(); - } finally { - try { - if (ps != null && !ps.isClosed()) { - ps.close(); - } - if (con != null && !con.isClosed()) { - con.close(); - } - } catch (SQLException ex) { - ex.printStackTrace(); - } } } @@ -787,32 +663,29 @@ public class MapleClient { public int getAccID() { return accId; } - - public void updateLoginState(int newstate) { - // rules out possibility of multiple account entries - if (newstate == LOGIN_LOGGEDIN) { - MapleSessionCoordinator.getInstance().updateOnlineSession(this.getSession()); - } - - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("UPDATE accounts SET loggedin = ?, lastlogin = ? WHERE id = ?")) { - // using sql currenttime here could potentially break the login, thanks Arnah for pointing this out - - ps.setInt(1, newstate); - ps.setTimestamp(2, new java.sql.Timestamp(Server.getInstance().getCurrentTime())); - ps.setInt(3, getAccID()); - ps.executeUpdate(); - } - con.close(); + + public void updateLoginState(int newstate) { + // rules out possibility of multiple account entries + if (newstate == LOGIN_LOGGEDIN) { + MapleSessionCoordinator.getInstance().updateOnlineSession(this.getSession()); + } + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE accounts SET loggedin = ?, lastlogin = ? WHERE id = ?")) { + // using sql currenttime here could potentially break the login, thanks Arnah for pointing this out + + ps.setInt(1, newstate); + ps.setTimestamp(2, new java.sql.Timestamp(Server.getInstance().getCurrentTime())); + ps.setInt(3, getAccID()); + ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } - + if (newstate == LOGIN_NOTLOGGEDIN) { loggedIn = false; serverTransition = false; - setAccID(0); + setAccID(0); } else { serverTransition = (newstate == LOGIN_SERVER_TRANSITION); loggedIn = !serverTransition; @@ -820,45 +693,43 @@ public class MapleClient { } public int getLoginState() { // 0 = LOGIN_NOTLOGGEDIN, 1= LOGIN_SERVER_TRANSITION, 2 = LOGIN_LOGGEDIN - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT loggedin, lastlogin, birthday FROM accounts WHERE id = ?"); - ps.setInt(1, getAccID()); - ResultSet rs = ps.executeQuery(); - if (!rs.next()) { - rs.close(); - ps.close(); - throw new RuntimeException("getLoginState - MapleClient AccID: " + getAccID()); - } - - birthday = Calendar.getInstance(); - try { - birthday.setTime(rs.getDate("birthday")); - } catch(SQLException e) {} - - int state = rs.getInt("loggedin"); - if (state == LOGIN_SERVER_TRANSITION) { - if (rs.getTimestamp("lastlogin").getTime() + 30000 < Server.getInstance().getCurrentTime()) { - int accountId = accId; - state = LOGIN_NOTLOGGEDIN; - updateLoginState(MapleClient.LOGIN_NOTLOGGEDIN); // ACCID = 0, issue found thanks to Tochi & K u ssss o & Thora & Omo Oppa - this.setAccID(accountId); + try (Connection con = DatabaseConnection.getConnection()) { + int state; + try (PreparedStatement ps = con.prepareStatement("SELECT loggedin, lastlogin, birthday FROM accounts WHERE id = ?")) { + ps.setInt(1, getAccID()); + + try (ResultSet rs = ps.executeQuery()) { + if (!rs.next()) { + throw new RuntimeException("getLoginState - MapleClient AccID: " + getAccID()); + } + + birthday = Calendar.getInstance(); + try { + birthday.setTime(rs.getDate("birthday")); + } catch (SQLException e) { + } + + state = rs.getInt("loggedin"); + if (state == LOGIN_SERVER_TRANSITION) { + if (rs.getTimestamp("lastlogin").getTime() + 30000 < Server.getInstance().getCurrentTime()) { + int accountId = accId; + state = LOGIN_NOTLOGGEDIN; + updateLoginState(MapleClient.LOGIN_NOTLOGGEDIN); // ACCID = 0, issue found thanks to Tochi & K u ssss o & Thora & Omo Oppa + this.setAccID(accountId); + } + } } } - rs.close(); - ps.close(); if (state == LOGIN_LOGGEDIN) { loggedIn = true; } else if (state == LOGIN_SERVER_TRANSITION) { - ps = con.prepareStatement("UPDATE accounts SET loggedin = 0 WHERE id = ?"); - ps.setInt(1, getAccID()); - ps.executeUpdate(); - ps.close(); + try (PreparedStatement ps2 = con.prepareStatement("UPDATE accounts SET loggedin = 0 WHERE id = ?")) { + ps2.setInt(1, getAccID()); + ps2.executeUpdate(); + } } else { loggedIn = false; } - - con.close(); return state; } catch (SQLException e) { loggedIn = false; @@ -1196,32 +1067,32 @@ public class MapleClient { } public boolean acceptToS() { - boolean disconnectForBeingAFaggot = false; if (accountName == null) { return true; } - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT `tos` FROM accounts WHERE id = ?"); - ps.setInt(1, accId); - ResultSet rs = ps.executeQuery(); - if (rs.next()) { - if (rs.getByte("tos") == 1) { - disconnectForBeingAFaggot = true; + boolean disconnect = false; + try (Connection con = DatabaseConnection.getConnection()) { + try (PreparedStatement ps = con.prepareStatement("SELECT `tos` FROM accounts WHERE id = ?")) { + ps.setInt(1, accId); + + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + if (rs.getByte("tos") == 1) { + disconnect = true; + } + } } } - ps.close(); - rs.close(); - ps = con.prepareStatement("UPDATE accounts SET tos = 1 WHERE id = ?"); - ps.setInt(1, accId); - ps.executeUpdate(); - ps.close(); - con.close(); + + try (PreparedStatement ps = con.prepareStatement("UPDATE accounts SET tos = 1 WHERE id = ?")) { + ps.setInt(1, accId); + ps.executeUpdate(); + } } catch (SQLException e) { - e.printStackTrace(); + e.printStackTrace(); } - return disconnectForBeingAFaggot; + return disconnect; } public void checkChar(int accid) { /// issue with multiple chars from same account login found by shavit, resinate @@ -1240,23 +1111,19 @@ public class MapleClient { } } - public int getVotePoints(){ + public int getVotePoints() { int points = 0; - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT `votepoints` FROM accounts WHERE id = ?"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT `votepoints` FROM accounts WHERE id = ?")) { ps.setInt(1, accId); - ResultSet rs = ps.executeQuery(); - if (rs.next()) { - points = rs.getInt("votepoints"); + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + points = rs.getInt("votepoints"); + } } - ps.close(); - rs.close(); - - con.close(); } catch (SQLException e) { - e.printStackTrace(); + e.printStackTrace(); } votePoints = points; return votePoints; @@ -1278,15 +1145,11 @@ public class MapleClient { } private void saveVotePoints() { - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("UPDATE accounts SET votepoints = ? WHERE id = ?")) { - ps.setInt(1, votePoints); - ps.setInt(2, accId); - ps.executeUpdate(); - } - - con.close(); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE accounts SET votepoints = ? WHERE id = ?")) { + ps.setInt(1, votePoints); + ps.setInt(2, accId); + ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } @@ -1373,22 +1236,17 @@ public class MapleClient { public boolean canGainCharacterSlot() { return characterSlots < 15; } - - public synchronized boolean gainCharacterSlot() { + + public synchronized boolean gainCharacterSlot() { if (canGainCharacterSlot()) { - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - - try (PreparedStatement ps = con.prepareStatement("UPDATE accounts SET characterslots = ? WHERE id = ?")) { - ps.setInt(1, this.characterSlots += 1); - ps.setInt(2, accId); - ps.executeUpdate(); - } - - con.close(); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE accounts SET characterslots = ? WHERE id = ?")) { + ps.setInt(1, this.characterSlots += 1); + ps.setInt(2, accId); + ps.executeUpdate(); + } catch (SQLException e) { - e.printStackTrace(); + e.printStackTrace(); } return true; } @@ -1396,33 +1254,17 @@ public class MapleClient { } public final byte getGReason() { - Connection con = null; - PreparedStatement ps = null; - ResultSet rs = null; - try { - con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("SELECT `greason` FROM `accounts` WHERE id = ?"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT `greason` FROM `accounts` WHERE id = ?")) { ps.setInt(1, accId); - rs = ps.executeQuery(); - if (rs.next()) { - return rs.getByte("greason"); + + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + return rs.getByte("greason"); + } } } catch (SQLException e) { e.printStackTrace(); - } finally { - try { - if (ps != null) { - ps.close(); - } - if (rs != null) { - rs.close(); - } - if (con != null) { - con.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } } return 0; } @@ -1433,18 +1275,14 @@ public class MapleClient { public void setGender(byte m) { this.gender = m; - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("UPDATE accounts SET gender = ? WHERE id = ?")) { - ps.setByte(1, gender); - ps.setInt(2, accId); - ps.executeUpdate(); - } - - con.close(); + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE accounts SET gender = ? WHERE id = ?")) { + ps.setByte(1, gender); + ps.setInt(2, accId); + ps.executeUpdate(); } catch (SQLException e) { - e.printStackTrace(); + e.printStackTrace(); } } diff --git a/src/main/java/client/MapleRing.java b/src/main/java/client/MapleRing.java index 53111f3fb7..a7634b2f7f 100644 --- a/src/main/java/client/MapleRing.java +++ b/src/main/java/client/MapleRing.java @@ -21,13 +21,14 @@ */ package client; +import client.inventory.manipulator.MapleCashidGenerator; +import tools.DatabaseConnection; +import tools.Pair; + import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import tools.Pair; -import tools.DatabaseConnection; -import client.inventory.manipulator.MapleCashidGenerator; /** * @@ -50,18 +51,16 @@ public class MapleRing implements Comparable { } public static MapleRing loadFromDb(int ringId) { - try { - MapleRing ret = null; - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT * FROM rings WHERE id = ?"); // Get ring details.. + MapleRing ret = null; + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT * FROM rings WHERE id = ?")) { ps.setInt(1, ringId); - ResultSet rs = ps.executeQuery(); - if (rs.next()) { - ret = new MapleRing(ringId, rs.getInt("partnerRingId"), rs.getInt("partnerChrId"), rs.getInt("itemid"), rs.getString("partnerName")); + + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + ret = new MapleRing(ringId, rs.getInt("partnerRingId"), rs.getInt("partnerChrId"), rs.getInt("itemid"), rs.getString("partnerName")); + } } - rs.close(); - ps.close(); - con.close(); return ret; } catch (SQLException ex) { ex.printStackTrace(); @@ -75,32 +74,30 @@ public class MapleRing implements Comparable { return; } - Connection con = DatabaseConnection.getConnection(); - - PreparedStatement ps = con.prepareStatement("DELETE FROM rings WHERE id=?"); - ps.setInt(1, ring.getRingId()); - ps.addBatch(); - - ps.setInt(1, ring.getPartnerRingId()); - ps.addBatch(); - - ps.executeBatch(); - ps.close(); - - MapleCashidGenerator.freeCashId(ring.getRingId()); - MapleCashidGenerator.freeCashId(ring.getPartnerRingId()); - - ps = con.prepareStatement("UPDATE inventoryequipment SET ringid=-1 WHERE ringid=?"); - ps.setInt(1, ring.getRingId()); - ps.addBatch(); - - ps.setInt(1, ring.getPartnerRingId()); - ps.addBatch(); - - ps.executeBatch(); - ps.close(); - - con.close(); + try (Connection con = DatabaseConnection.getConnection()) { + try (PreparedStatement ps = con.prepareStatement("DELETE FROM rings WHERE id=?")) { + ps.setInt(1, ring.getRingId()); + ps.addBatch(); + + ps.setInt(1, ring.getPartnerRingId()); + ps.addBatch(); + + ps.executeBatch(); + } + + MapleCashidGenerator.freeCashId(ring.getRingId()); + MapleCashidGenerator.freeCashId(ring.getPartnerRingId()); + + try (PreparedStatement ps = con.prepareStatement("UPDATE inventoryequipment SET ringid=-1 WHERE ringid=?")) { + ps.setInt(1, ring.getRingId()); + ps.addBatch(); + + ps.setInt(1, ring.getPartnerRingId()); + ps.addBatch(); + + ps.executeBatch(); + } + } } catch (SQLException ex) { ex.printStackTrace(); } @@ -113,29 +110,30 @@ public class MapleRing implements Comparable { } else if (partner2 == null) { return new Pair<>(-2, -2); } - + int[] ringID = new int[2]; ringID[0] = MapleCashidGenerator.generateCashId(); ringID[1] = MapleCashidGenerator.generateCashId(); - - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("INSERT INTO rings (id, itemid, partnerRingId, partnerChrId, partnername) VALUES (?, ?, ?, ?, ?)"); - ps.setInt(1, ringID[0]); - ps.setInt(2, itemid); - ps.setInt(3, ringID[1]); - ps.setInt(4, partner2.getId()); - ps.setString(5, partner2.getName()); - ps.executeUpdate(); - ps.close(); - ps = con.prepareStatement("INSERT INTO rings (id, itemid, partnerRingId, partnerChrId, partnername) VALUES (?, ?, ?, ?, ?)"); - ps.setInt(1, ringID[1]); - ps.setInt(2, itemid); - ps.setInt(3, ringID[0]); - ps.setInt(4, partner1.getId()); - ps.setString(5, partner1.getName()); - ps.executeUpdate(); - ps.close(); - con.close(); + + try (Connection con = DatabaseConnection.getConnection()) { + try (PreparedStatement ps = con.prepareStatement("INSERT INTO rings (id, itemid, partnerRingId, partnerChrId, partnername) VALUES (?, ?, ?, ?, ?)")) { + ps.setInt(1, ringID[0]); + ps.setInt(2, itemid); + ps.setInt(3, ringID[1]); + ps.setInt(4, partner2.getId()); + ps.setString(5, partner2.getName()); + ps.executeUpdate(); + } + + try (PreparedStatement ps = con.prepareStatement("INSERT INTO rings (id, itemid, partnerRingId, partnerChrId, partnername) VALUES (?, ?, ?, ?, ?)")) { + ps.setInt(1, ringID[1]); + ps.setInt(2, itemid); + ps.setInt(3, ringID[0]); + ps.setInt(4, partner1.getId()); + ps.setString(5, partner1.getName()); + ps.executeUpdate(); + } + } return new Pair<>(ringID[0], ringID[1]); } catch (SQLException ex) { ex.printStackTrace(); diff --git a/src/main/java/client/MonsterBook.java b/src/main/java/client/MonsterBook.java index 95f320b298..1e614cf32d 100644 --- a/src/main/java/client/MonsterBook.java +++ b/src/main/java/client/MonsterBook.java @@ -21,22 +21,19 @@ */ package client; +import net.server.audit.locks.MonitoredLockType; +import net.server.audit.locks.factory.MonitoredReentrantLockFactory; +import tools.DatabaseConnection; +import tools.MaplePacketCreator; + import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.locks.Lock; import java.util.concurrent.Semaphore; -import tools.DatabaseConnection; -import tools.MaplePacketCreator; -import net.server.audit.locks.MonitoredLockType; -import net.server.audit.locks.factory.MonitoredReentrantLockFactory; +import java.util.concurrent.locks.Lock; public final class MonsterBook { private static final Semaphore semaphore = new Semaphore(10); @@ -158,30 +155,28 @@ public final class MonsterBook { public void loadCards(final int charid) throws SQLException { lock.lock(); - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("SELECT cardid, level FROM monsterbook WHERE charid = ? ORDER BY cardid ASC")) { - ps.setInt(1, charid); - try (ResultSet rs = ps.executeQuery()) { - int cardid, level; - while (rs.next()) { - cardid = rs.getInt("cardid"); - level = rs.getInt("level"); - if (cardid / 1000 >= 2388) { - specialCard++; - } else { - normalCard++; - } - cards.put(cardid, level); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT cardid, level FROM monsterbook WHERE charid = ? ORDER BY cardid ASC")) { + ps.setInt(1, charid); + + try (ResultSet rs = ps.executeQuery()) { + int cardid; + int level; + while (rs.next()) { + cardid = rs.getInt("cardid"); + level = rs.getInt("level"); + if (cardid / 1000 >= 2388) { + specialCard++; + } else { + normalCard++; } + cards.put(cardid, level); } } - - con.close(); } finally { lock.unlock(); } - + calculateLevel(); } @@ -224,45 +219,37 @@ public final class MonsterBook { public void saveCards(final int charid) { Set> cardSet = getCardSet(); - + if (cardSet.isEmpty()) { return; } - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("DELETE FROM monsterbook WHERE charid = ?"); - ps.setInt(1, charid); - ps.execute(); - ps.close(); - - ps = con.prepareStatement(getSaveString(charid, cardSet)); - ps.execute(); - ps.close(); - con.close(); + + try (Connection con = DatabaseConnection.getConnection()) { + try (PreparedStatement ps = con.prepareStatement("DELETE FROM monsterbook WHERE charid = ?")) { + ps.setInt(1, charid); + ps.executeUpdate(); + } + + try (PreparedStatement ps = con.prepareStatement(getSaveString(charid, cardSet))) { + ps.executeUpdate(); + } } catch (SQLException e) { e.printStackTrace(); } } public static int[] getCardTierSize() { - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT COUNT(*) FROM monstercarddata GROUP BY floor(cardid / 1000);", - ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - ResultSet rs = ps.executeQuery(); - + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT COUNT(*) FROM monstercarddata GROUP BY floor(cardid / 1000);", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + ResultSet rs = ps.executeQuery()) { rs.last(); int[] tierSizes = new int[rs.getRow()]; rs.beforeFirst(); - + while (rs.next()) { tierSizes[rs.getRow() - 1] = rs.getInt(1); } - - rs.close(); - ps.close(); - con.close(); - + return tierSizes; } catch (SQLException e) { e.printStackTrace(); diff --git a/src/main/java/client/command/commands/gm1/WhoDropsCommand.java b/src/main/java/client/command/commands/gm1/WhoDropsCommand.java index 449f20e731..ee4ed99760 100644 --- a/src/main/java/client/command/commands/gm1/WhoDropsCommand.java +++ b/src/main/java/client/command/commands/gm1/WhoDropsCommand.java @@ -24,8 +24,8 @@ package client.command.commands.gm1; import client.MapleCharacter; -import client.command.Command; import client.MapleClient; +import client.command.Command; import server.MapleItemInformationProvider; import server.life.MapleMonsterInformationProvider; import tools.DatabaseConnection; @@ -48,31 +48,29 @@ public class WhoDropsCommand extends Command { player.dropMessage(5, "Please do @whodrops "); return; } - + if (c.tryacquireClient()) { try { String searchString = player.getLastCommandMessage(); String output = ""; Iterator> listIterator = MapleItemInformationProvider.getInstance().getItemDataByName(searchString).iterator(); - if(listIterator.hasNext()) { + if (listIterator.hasNext()) { int count = 1; - while(listIterator.hasNext() && count <= 3) { + while (listIterator.hasNext() && count <= 3) { Pair data = listIterator.next(); output += "#b" + data.getRight() + "#k is dropped by:\r\n"; - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT dropperid FROM drop_data WHERE itemid = ? LIMIT 50"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT dropperid FROM drop_data WHERE itemid = ? LIMIT 50")) { ps.setInt(1, data.getLeft()); - ResultSet rs = ps.executeQuery(); - while(rs.next()) { - String resultName = MapleMonsterInformationProvider.getInstance().getMobNameFromId(rs.getInt("dropperid")); - if (resultName != null) { - output += resultName + ", "; + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + String resultName = MapleMonsterInformationProvider.getInstance().getMobNameFromId(rs.getInt("dropperid")); + if (resultName != null) { + output += resultName + ", "; + } } } - rs.close(); - ps.close(); - con.close(); } catch (Exception e) { player.dropMessage(6, "There was a problem retrieving the required data. Please try again."); e.printStackTrace(); @@ -85,7 +83,7 @@ public class WhoDropsCommand extends Command { player.dropMessage(5, "The item you searched for doesn't exist."); return; } - + c.getAbstractPlayerInteraction().npcTalk(9010000, output); } finally { c.releaseClient(); diff --git a/src/main/java/client/command/commands/gm3/BanCommand.java b/src/main/java/client/command/commands/gm3/BanCommand.java index cbc2d1087e..bfb3e55aaf 100644 --- a/src/main/java/client/command/commands/gm3/BanCommand.java +++ b/src/main/java/client/command/commands/gm3/BanCommand.java @@ -23,9 +23,9 @@ */ package client.command.commands.gm3; -import client.command.Command; -import client.MapleClient; import client.MapleCharacter; +import client.MapleClient; +import client.command.Command; import net.server.Server; import server.TimerManager; import tools.DatabaseConnection; @@ -54,19 +54,15 @@ public class BanCommand extends Command { String readableTargetName = MapleCharacter.makeMapleReadable(target.getName()); String ip = target.getClient().getSession().getRemoteAddress().toString().split(":")[0]; //Ban ip - PreparedStatement ps = null; - try { - Connection con = DatabaseConnection.getConnection(); + try (Connection con = DatabaseConnection.getConnection()) { if (ip.matches("/[0-9]{1,3}\\..*")) { - ps = con.prepareStatement("INSERT INTO ipbans VALUES (DEFAULT, ?, ?)"); - ps.setString(1, ip); - ps.setString(2, String.valueOf(target.getClient().getAccID())); + try (PreparedStatement ps = con.prepareStatement("INSERT INTO ipbans VALUES (DEFAULT, ?, ?)")) { + ps.setString(1, ip); + ps.setString(2, String.valueOf(target.getClient().getAccID())); - ps.executeUpdate(); - ps.close(); + ps.executeUpdate(); + } } - - con.close(); } catch (SQLException ex) { ex.printStackTrace(); c.getPlayer().message("Error occured while banning IP address"); diff --git a/src/main/java/client/command/commands/gm3/UnBanCommand.java b/src/main/java/client/command/commands/gm3/UnBanCommand.java index b859fef3dc..878e4fa2fd 100644 --- a/src/main/java/client/command/commands/gm3/UnBanCommand.java +++ b/src/main/java/client/command/commands/gm3/UnBanCommand.java @@ -23,9 +23,9 @@ */ package client.command.commands.gm3; -import client.command.Command; -import client.MapleClient; import client.MapleCharacter; +import client.MapleClient; +import client.command.Command; import tools.DatabaseConnection; import java.sql.Connection; @@ -44,20 +44,20 @@ public class UnBanCommand extends Command { return; } - try { - Connection con = DatabaseConnection.getConnection(); + try (Connection con = DatabaseConnection.getConnection()) { int aid = MapleCharacter.getAccountIdByName(params[0]); - PreparedStatement p = con.prepareStatement("UPDATE accounts SET banned = -1 WHERE id = " + aid); - p.executeUpdate(); + try (PreparedStatement p = con.prepareStatement("UPDATE accounts SET banned = -1 WHERE id = " + aid)) { + p.executeUpdate(); + } - p = con.prepareStatement("DELETE FROM ipbans WHERE aid = " + aid); - p.executeUpdate(); + try (PreparedStatement p = con.prepareStatement("DELETE FROM ipbans WHERE aid = " + aid)) { + p.executeUpdate(); + } - p = con.prepareStatement("DELETE FROM macbans WHERE aid = " + aid); - p.executeUpdate(); - - con.close(); + try (PreparedStatement p = con.prepareStatement("DELETE FROM macbans WHERE aid = " + aid)) { + p.executeUpdate(); + } } catch (Exception e) { e.printStackTrace(); player.message("Failed to unban " + params[0]); diff --git a/src/main/java/client/command/commands/gm4/PmobCommand.java b/src/main/java/client/command/commands/gm4/PmobCommand.java index 77a0391120..28a9f5911a 100644 --- a/src/main/java/client/command/commands/gm4/PmobCommand.java +++ b/src/main/java/client/command/commands/gm4/PmobCommand.java @@ -23,20 +23,20 @@ */ package client.command.commands.gm4; +import client.MapleCharacter; +import client.MapleClient; +import client.command.Command; +import net.server.channel.Channel; +import server.life.MapleLifeFactory; +import server.life.MapleMonster; +import server.maps.MapleMap; +import tools.DatabaseConnection; + +import java.awt.*; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; -import net.server.channel.Channel; -import server.life.MapleLifeFactory; -import server.maps.MapleMap; -import client.command.Command; -import client.MapleCharacter; -import client.MapleClient; -import java.awt.Point; -import server.life.MapleMonster; -import tools.DatabaseConnection; - public class PmobCommand extends Command { { setDescription(""); @@ -54,12 +54,12 @@ public class PmobCommand extends Command { int mapId = player.getMapId(); int mobId = Integer.parseInt(params[0]); int mobTime = (params.length > 1) ? Integer.parseInt(params[1]) : -1; - + Point checkpos = player.getMap().getGroundBelow(player.getPosition()); int xpos = checkpos.x; int ypos = checkpos.y; int fh = player.getMap().getFootholds().findBelow(checkpos).getId(); - + MapleMonster mob = MapleLifeFactory.getMonster(mobId); if (mob != null && !mob.getName().equals("MISSINGNO")) { mob.setPosition(checkpos); @@ -67,9 +67,8 @@ public class PmobCommand extends Command { mob.setRx0(xpos + 50); mob.setRx1(xpos - 50); mob.setFh(fh); - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("INSERT INTO plife ( life, f, fh, cy, rx0, rx1, type, x, y, world, map, mobtime, hide ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("INSERT INTO plife ( life, f, fh, cy, rx0, rx1, type, x, y, world, map, mobtime, hide ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )")) { ps.setInt(1, mobId); ps.setInt(2, 0); ps.setInt(3, fh); @@ -84,15 +83,13 @@ public class PmobCommand extends Command { ps.setInt(12, mobTime); ps.setInt(13, 0); ps.executeUpdate(); - ps.close(); - con.close(); - - for (Channel ch: player.getWorldServer().getChannels()) { + + for (Channel ch : player.getWorldServer().getChannels()) { MapleMap map = ch.getMapFactory().getMap(mapId); map.addMonsterSpawn(mob, mobTime, -1); map.addAllMonsterSpawn(mob, mobTime, -1); } - + player.yellowMessage("Pmob created."); } catch (SQLException e) { e.printStackTrace(); diff --git a/src/main/java/client/command/commands/gm4/PmobRemoveCommand.java b/src/main/java/client/command/commands/gm4/PmobRemoveCommand.java index 2a7c1a52ab..e6e925f80d 100644 --- a/src/main/java/client/command/commands/gm4/PmobRemoveCommand.java +++ b/src/main/java/client/command/commands/gm4/PmobRemoveCommand.java @@ -23,6 +23,15 @@ */ package client.command.commands.gm4; +import client.MapleCharacter; +import client.MapleClient; +import client.command.Command; +import net.server.channel.Channel; +import server.maps.MapleMap; +import tools.DatabaseConnection; +import tools.Pair; + +import java.awt.*; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -30,15 +39,6 @@ import java.sql.SQLException; import java.util.LinkedList; import java.util.List; -import net.server.channel.Channel; -import server.maps.MapleMap; -import client.command.Command; -import client.MapleCharacter; -import client.MapleClient; -import java.awt.Point; -import tools.DatabaseConnection; -import tools.Pair; - public class PmobRemoveCommand extends Command { { setDescription(""); @@ -47,19 +47,17 @@ public class PmobRemoveCommand extends Command { @Override public void execute(MapleClient c, String[] params) { MapleCharacter player = c.getPlayer(); - + int mapId = player.getMapId(); int mobId = params.length > 0 ? Integer.parseInt(params[0]) : -1; - + Point pos = player.getPosition(); int xpos = pos.x; int ypos = pos.y; - + List>> toRemove = new LinkedList<>(); - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps; - + try (Connection con = DatabaseConnection.getConnection()) { + final PreparedStatement ps; if (mobId > -1) { String select = "SELECT * FROM plife WHERE world = ? AND map = ? AND type LIKE ? AND life = ?"; ps = con.prepareStatement(select, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); @@ -78,28 +76,26 @@ public class PmobRemoveCommand extends Command { ps.setInt(6, ypos - 50); ps.setInt(7, ypos + 50); } - - ResultSet rs = ps.executeQuery(); - while (true) { - rs.beforeFirst(); - if (!rs.next()) { - break; + + try (ResultSet rs = ps.executeQuery()) { + while (true) { + rs.beforeFirst(); + if (!rs.next()) { + break; + } + + toRemove.add(new Pair<>(rs.getInt("life"), new Pair<>(rs.getInt("x"), rs.getInt("y")))); + rs.deleteRow(); } - - toRemove.add(new Pair<>(rs.getInt("life"), new Pair<>(rs.getInt("x"), rs.getInt("y")))); - rs.deleteRow(); } - - rs.close(); ps.close(); - con.close(); } catch (SQLException e) { e.printStackTrace(); player.dropMessage(5, "Failed to remove pmob from the database."); } - + if (!toRemove.isEmpty()) { - for (Channel ch: player.getWorldServer().getChannels()) { + for (Channel ch : player.getWorldServer().getChannels()) { MapleMap map = ch.getMapFactory().getMap(mapId); for (Pair> r : toRemove) { @@ -108,7 +104,7 @@ public class PmobRemoveCommand extends Command { } } } - + player.yellowMessage("Cleared " + toRemove.size() + " pmob placements."); } } \ No newline at end of file diff --git a/src/main/java/client/command/commands/gm4/PnpcCommand.java b/src/main/java/client/command/commands/gm4/PnpcCommand.java index 2edb89452c..2e52507dc4 100644 --- a/src/main/java/client/command/commands/gm4/PnpcCommand.java +++ b/src/main/java/client/command/commands/gm4/PnpcCommand.java @@ -23,21 +23,21 @@ */ package client.command.commands.gm4; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; - +import client.MapleCharacter; +import client.MapleClient; +import client.command.Command; import net.server.channel.Channel; import server.life.MapleLifeFactory; import server.life.MapleNPC; -import client.command.Command; -import client.MapleCharacter; -import client.MapleClient; -import java.awt.Point; import server.maps.MapleMap; import tools.DatabaseConnection; import tools.MaplePacketCreator; +import java.awt.*; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; + public class PnpcCommand extends Command { { setDescription(""); @@ -50,7 +50,7 @@ public class PnpcCommand extends Command { player.yellowMessage("Syntax: !pnpc "); return; } - + // command suggestion thanks to HighKey21, none, bibiko94 (TAYAMO), asafgb int mapId = player.getMapId(); int npcId = Integer.parseInt(params[0]); @@ -58,18 +58,17 @@ public class PnpcCommand extends Command { player.dropMessage(5, "This map already contains the specified NPC."); return; } - + MapleNPC npc = MapleLifeFactory.getNPC(npcId); - + Point checkpos = player.getMap().getGroundBelow(player.getPosition()); int xpos = checkpos.x; int ypos = checkpos.y; int fh = player.getMap().getFootholds().findBelow(checkpos).getId(); - + if (npc != null && !npc.getName().equals("MISSINGNO")) { - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("INSERT INTO plife ( life, f, fh, cy, rx0, rx1, type, x, y, world, map, mobtime, hide ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("INSERT INTO plife ( life, f, fh, cy, rx0, rx1, type, x, y, world, map, mobtime, hide ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )")) { ps.setInt(1, npcId); ps.setInt(2, 0); ps.setInt(3, fh); @@ -84,17 +83,15 @@ public class PnpcCommand extends Command { ps.setInt(12, -1); ps.setInt(13, 0); ps.executeUpdate(); - ps.close(); - con.close(); - - for (Channel ch: player.getWorldServer().getChannels()) { + + for (Channel ch : player.getWorldServer().getChannels()) { npc = MapleLifeFactory.getNPC(npcId); npc.setPosition(checkpos); npc.setCy(ypos); npc.setRx0(xpos + 50); npc.setRx1(xpos - 50); npc.setFh(fh); - + MapleMap map = ch.getMapFactory().getMap(mapId); map.addMapObject(npc); map.broadcastMessage(MaplePacketCreator.spawnNPC(npc)); diff --git a/src/main/java/client/command/commands/gm4/PnpcRemoveCommand.java b/src/main/java/client/command/commands/gm4/PnpcRemoveCommand.java index 485da4e83b..9d8b87d88c 100644 --- a/src/main/java/client/command/commands/gm4/PnpcRemoveCommand.java +++ b/src/main/java/client/command/commands/gm4/PnpcRemoveCommand.java @@ -23,22 +23,22 @@ */ package client.command.commands.gm4; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; - -import net.server.channel.Channel; -import client.command.Command; import client.MapleCharacter; import client.MapleClient; -import java.awt.Point; -import java.sql.ResultSet; -import java.util.LinkedList; -import java.util.List; +import client.command.Command; +import net.server.channel.Channel; import server.maps.MapleMap; import tools.DatabaseConnection; import tools.Pair; +import java.awt.*; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.LinkedList; +import java.util.List; + public class PnpcRemoveCommand extends Command { { setDescription(""); @@ -56,10 +56,8 @@ public class PnpcRemoveCommand extends Command { int ypos = pos.y; List>> toRemove = new LinkedList<>(); - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps; - + try (Connection con = DatabaseConnection.getConnection()) { + final PreparedStatement ps; if (npcId > -1) { String select = "SELECT * FROM plife WHERE world = ? AND map = ? AND type LIKE ? AND life = ?"; ps = con.prepareStatement(select, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); @@ -79,20 +77,19 @@ public class PnpcRemoveCommand extends Command { ps.setInt(7, ypos + 50); } - ResultSet rs = ps.executeQuery(); - while (true) { - rs.beforeFirst(); - if (!rs.next()) { - break; + try (ResultSet rs = ps.executeQuery()) { + while (true) { + rs.beforeFirst(); + if (!rs.next()) { + break; + } + + toRemove.add(new Pair<>(rs.getInt("life"), new Pair<>(rs.getInt("x"), rs.getInt("y")))); + rs.deleteRow(); } - - toRemove.add(new Pair<>(rs.getInt("life"), new Pair<>(rs.getInt("x"), rs.getInt("y")))); - rs.deleteRow(); } - - rs.close(); + ps.close(); - con.close(); } catch (SQLException e) { e.printStackTrace(); player.dropMessage(5, "Failed to remove pNPC from the database."); diff --git a/src/main/java/client/inventory/ItemFactory.java b/src/main/java/client/inventory/ItemFactory.java index 7ece9b334b..955bbb0531 100644 --- a/src/main/java/client/inventory/ItemFactory.java +++ b/src/main/java/client/inventory/ItemFactory.java @@ -20,19 +20,16 @@ */ package client.inventory; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.locks.Lock; import net.server.audit.locks.MonitoredLockType; import net.server.audit.locks.factory.MonitoredReentrantLockFactory; import tools.DatabaseConnection; import tools.Pair; +import java.sql.*; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.locks.Lock; + /** * * @author Flav @@ -149,11 +146,8 @@ public enum ItemFactory { private List> loadItemsCommon(int id, boolean login) throws SQLException { List> items = new ArrayList<>(); - - PreparedStatement ps = null; - ResultSet rs = null; - Connection con = DatabaseConnection.getConnection(); - try { + + try (Connection con = DatabaseConnection.getConnection()) { StringBuilder query = new StringBuilder(); query.append("SELECT * FROM `inventoryitems` LEFT JOIN `inventoryequipment` USING(`inventoryitemid`) WHERE `type` = ? AND `"); query.append(account ? "accountid" : "characterid").append("` = ?"); @@ -162,149 +156,117 @@ public enum ItemFactory { query.append(" AND `inventorytype` = ").append(MapleInventoryType.EQUIPPED.getType()); } - ps = con.prepareStatement(query.toString()); - ps.setInt(1, value); - ps.setInt(2, id); - rs = ps.executeQuery(); + try (PreparedStatement ps = con.prepareStatement(query.toString())) { + ps.setInt(1, value); + ps.setInt(2, id); - while (rs.next()) { - MapleInventoryType mit = MapleInventoryType.getByType(rs.getByte("inventorytype")); + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + MapleInventoryType mit = MapleInventoryType.getByType(rs.getByte("inventorytype")); - if (mit.equals(MapleInventoryType.EQUIP) || mit.equals(MapleInventoryType.EQUIPPED)) { - items.add(new Pair(loadEquipFromResultSet(rs), mit)); - } else { - int petid = rs.getInt("petid"); - if (rs.wasNull()) { - petid = -1; + if (mit.equals(MapleInventoryType.EQUIP) || mit.equals(MapleInventoryType.EQUIPPED)) { + items.add(new Pair<>(loadEquipFromResultSet(rs), mit)); + } else { + int petid = rs.getInt("petid"); + if (rs.wasNull()) { + petid = -1; + } + + Item item = new Item(rs.getInt("itemid"), (byte) rs.getInt("position"), (short) rs.getInt("quantity"), petid); + item.setOwner(rs.getString("owner")); + item.setExpiration(rs.getLong("expiration")); + item.setGiftFrom(rs.getString("giftFrom")); + item.setFlag((short) rs.getInt("flag")); + items.add(new Pair<>(item, mit)); + } } - - Item item = new Item(rs.getInt("itemid"), (byte) rs.getInt("position"), (short) rs.getInt("quantity"), petid); - item.setOwner(rs.getString("owner")); - item.setExpiration(rs.getLong("expiration")); - item.setGiftFrom(rs.getString("giftFrom")); - item.setFlag((short) rs.getInt("flag")); - items.add(new Pair<>(item, mit)); } } - - rs.close(); - ps.close(); - con.close(); - } finally { - if (rs != null && !rs.isClosed()) { - rs.close(); - } - if (ps != null && !ps.isClosed()) { - ps.close(); - } - if (con != null && !con.isClosed()) { - con.close(); - } } return items; } private void saveItemsCommon(List> items, int id, Connection con) throws SQLException { - PreparedStatement ps = null; - PreparedStatement pse = null; - ResultSet rs = null; - Lock lock = locks[id % lockCount]; lock.lock(); try { StringBuilder query = new StringBuilder(); query.append("DELETE `inventoryitems`, `inventoryequipment` FROM `inventoryitems` LEFT JOIN `inventoryequipment` USING(`inventoryitemid`) WHERE `type` = ? AND `"); query.append(account ? "accountid" : "characterid").append("` = ?"); - ps = con.prepareStatement(query.toString()); - ps.setInt(1, value); - ps.setInt(2, id); - ps.executeUpdate(); - ps.close(); - ps = con.prepareStatement("INSERT INTO `inventoryitems` VALUES (DEFAULT, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); - if (!items.isEmpty()) { - for (Pair pair : items) { - Item item = pair.getLeft(); - MapleInventoryType mit = pair.getRight(); - ps.setInt(1, value); - ps.setString(2, account ? null : String.valueOf(id)); - ps.setString(3, account ? String.valueOf(id) : null); - ps.setInt(4, item.getItemId()); - ps.setInt(5, mit.getType()); - ps.setInt(6, item.getPosition()); - ps.setInt(7, item.getQuantity()); - ps.setString(8, item.getOwner()); - ps.setInt(9, item.getPetId()); // thanks Daddy Egg for alerting a case of unique petid constraint breach getting raised - ps.setInt(10, item.getFlag()); - ps.setLong(11, item.getExpiration()); - ps.setString(12, item.getGiftFrom()); - ps.executeUpdate(); + try (PreparedStatement ps = con.prepareStatement(query.toString())) { + ps.setInt(1, value); + ps.setInt(2, id); + ps.executeUpdate(); + } - pse = con.prepareStatement("INSERT INTO `inventoryequipment` VALUES (DEFAULT, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); + try (PreparedStatement psItem = con.prepareStatement("INSERT INTO `inventoryitems` VALUES (DEFAULT, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) { + if (!items.isEmpty()) { + for (Pair pair : items) { + Item item = pair.getLeft(); + MapleInventoryType mit = pair.getRight(); + psItem.setInt(1, value); + psItem.setString(2, account ? null : String.valueOf(id)); + psItem.setString(3, account ? String.valueOf(id) : null); + psItem.setInt(4, item.getItemId()); + psItem.setInt(5, mit.getType()); + psItem.setInt(6, item.getPosition()); + psItem.setInt(7, item.getQuantity()); + psItem.setString(8, item.getOwner()); + psItem.setInt(9, item.getPetId()); // thanks Daddy Egg for alerting a case of unique petid constraint breach getting raised + psItem.setInt(10, item.getFlag()); + psItem.setLong(11, item.getExpiration()); + psItem.setString(12, item.getGiftFrom()); + psItem.executeUpdate(); - if (mit.equals(MapleInventoryType.EQUIP) || mit.equals(MapleInventoryType.EQUIPPED)) { - rs = ps.getGeneratedKeys(); + if (mit.equals(MapleInventoryType.EQUIP) || mit.equals(MapleInventoryType.EQUIPPED)) { + try (PreparedStatement psEquip = con.prepareStatement("INSERT INTO `inventoryequipment` VALUES (DEFAULT, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) { + try (ResultSet rs = psItem.getGeneratedKeys()) { + if (!rs.next()) { + throw new RuntimeException("Inserting item failed."); + } - if (!rs.next()) { - throw new RuntimeException("Inserting item failed."); + psEquip.setInt(1, rs.getInt(1)); + } + + Equip equip = (Equip) item; + psEquip.setInt(2, equip.getUpgradeSlots()); + psEquip.setInt(3, equip.getLevel()); + psEquip.setInt(4, equip.getStr()); + psEquip.setInt(5, equip.getDex()); + psEquip.setInt(6, equip.getInt()); + psEquip.setInt(7, equip.getLuk()); + psEquip.setInt(8, equip.getHp()); + psEquip.setInt(9, equip.getMp()); + psEquip.setInt(10, equip.getWatk()); + psEquip.setInt(11, equip.getMatk()); + psEquip.setInt(12, equip.getWdef()); + psEquip.setInt(13, equip.getMdef()); + psEquip.setInt(14, equip.getAcc()); + psEquip.setInt(15, equip.getAvoid()); + psEquip.setInt(16, equip.getHands()); + psEquip.setInt(17, equip.getSpeed()); + psEquip.setInt(18, equip.getJump()); + psEquip.setInt(19, 0); + psEquip.setInt(20, equip.getVicious()); + psEquip.setInt(21, equip.getItemLevel()); + psEquip.setInt(22, equip.getItemExp()); + psEquip.setInt(23, equip.getRingId()); + psEquip.executeUpdate(); + } } - - pse.setInt(1, rs.getInt(1)); - rs.close(); - - Equip equip = (Equip) item; - pse.setInt(2, equip.getUpgradeSlots()); - pse.setInt(3, equip.getLevel()); - pse.setInt(4, equip.getStr()); - pse.setInt(5, equip.getDex()); - pse.setInt(6, equip.getInt()); - pse.setInt(7, equip.getLuk()); - pse.setInt(8, equip.getHp()); - pse.setInt(9, equip.getMp()); - pse.setInt(10, equip.getWatk()); - pse.setInt(11, equip.getMatk()); - pse.setInt(12, equip.getWdef()); - pse.setInt(13, equip.getMdef()); - pse.setInt(14, equip.getAcc()); - pse.setInt(15, equip.getAvoid()); - pse.setInt(16, equip.getHands()); - pse.setInt(17, equip.getSpeed()); - pse.setInt(18, equip.getJump()); - pse.setInt(19, 0); - pse.setInt(20, equip.getVicious()); - pse.setInt(21, equip.getItemLevel()); - pse.setInt(22, equip.getItemExp()); - pse.setInt(23, equip.getRingId()); - pse.executeUpdate(); } - - pse.close(); } } - - ps.close(); } finally { - if (ps != null && !ps.isClosed()) { - ps.close(); - } - if (pse != null && !pse.isClosed()) { - pse.close(); - } - if(rs != null && !rs.isClosed()) { - rs.close(); - } - lock.unlock(); } } private List> loadItemsMerchant(int id, boolean login) throws SQLException { List> items = new ArrayList<>(); - - PreparedStatement ps = null, ps2 = null; - ResultSet rs = null, rs2 = null; - Connection con = DatabaseConnection.getConnection(); - try { + + try (Connection con = DatabaseConnection.getConnection()) { StringBuilder query = new StringBuilder(); query.append("SELECT * FROM `inventoryitems` LEFT JOIN `inventoryequipment` USING(`inventoryitemid`) WHERE `type` = ? AND `"); query.append(account ? "accountid" : "characterid").append("` = ?"); @@ -313,99 +275,78 @@ public enum ItemFactory { query.append(" AND `inventorytype` = ").append(MapleInventoryType.EQUIPPED.getType()); } - ps = con.prepareStatement(query.toString()); - ps.setInt(1, value); - ps.setInt(2, id); - rs = ps.executeQuery(); + try (PreparedStatement ps = con.prepareStatement(query.toString())) { + ps.setInt(1, value); + ps.setInt(2, id); - while (rs.next()) { - ps2 = con.prepareStatement("SELECT `bundles` FROM `inventorymerchant` WHERE `inventoryitemid` = ?"); - ps2.setInt(1, rs.getInt("inventoryitemid")); - rs2 = ps2.executeQuery(); - - short bundles = 0; - if(rs2.next()) { - bundles = rs2.getShort("bundles"); - } - - MapleInventoryType mit = MapleInventoryType.getByType(rs.getByte("inventorytype")); + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + short bundles = 0; + try (PreparedStatement psBundle = con.prepareStatement("SELECT `bundles` FROM `inventorymerchant` WHERE `inventoryitemid` = ?")) { + psBundle.setInt(1, rs.getInt("inventoryitemid")); - if (mit.equals(MapleInventoryType.EQUIP) || mit.equals(MapleInventoryType.EQUIPPED)) { - items.add(new Pair(loadEquipFromResultSet(rs), mit)); - } else { - if(bundles > 0) { - int petid = rs.getInt("petid"); - if (rs.wasNull()) { - petid = -1; + try (ResultSet rs2 = psBundle.executeQuery()) { + if (rs2.next()) { + bundles = rs2.getShort("bundles"); + } + } + } + + MapleInventoryType mit = MapleInventoryType.getByType(rs.getByte("inventorytype")); + + if (mit.equals(MapleInventoryType.EQUIP) || mit.equals(MapleInventoryType.EQUIPPED)) { + items.add(new Pair(loadEquipFromResultSet(rs), mit)); + } else { + if (bundles > 0) { + int petid = rs.getInt("petid"); + if (rs.wasNull()) { + petid = -1; + } + + Item item = new Item(rs.getInt("itemid"), (byte) rs.getInt("position"), (short) (bundles * rs.getInt("quantity")), petid); + item.setOwner(rs.getString("owner")); + item.setExpiration(rs.getLong("expiration")); + item.setGiftFrom(rs.getString("giftFrom")); + item.setFlag((short) rs.getInt("flag")); + items.add(new Pair<>(item, mit)); + } } - - Item item = new Item(rs.getInt("itemid"), (byte) rs.getInt("position"), (short)(bundles * rs.getInt("quantity")), petid); - item.setOwner(rs.getString("owner")); - item.setExpiration(rs.getLong("expiration")); - item.setGiftFrom(rs.getString("giftFrom")); - item.setFlag((short) rs.getInt("flag")); - items.add(new Pair<>(item, mit)); } } - - rs2.close(); - ps2.close(); - } - - rs.close(); - ps.close(); - con.close(); - } finally { - if (rs2 != null && !rs2.isClosed()) { - rs2.close(); - } - if (ps2 != null && !ps2.isClosed()) { - ps2.close(); - } - if (rs != null && !rs.isClosed()) { - rs.close(); - } - if (ps != null && !ps.isClosed()) { - ps.close(); - } - if (con != null && !con.isClosed()) { - con.close(); } } return items; } private void saveItemsMerchant(List> items, List bundlesList, int id, Connection con) throws SQLException { - PreparedStatement ps = null; - PreparedStatement pse = null; - ResultSet rs = null; - Lock lock = locks[id % lockCount]; lock.lock(); try { - ps = con.prepareStatement("DELETE FROM `inventorymerchant` WHERE `characterid` = ?"); - ps.setInt(1, id); - ps.executeUpdate(); - ps.close(); - + try (PreparedStatement ps = con.prepareStatement("DELETE FROM `inventorymerchant` WHERE `characterid` = ?")) { + ps.setInt(1, id); + ps.executeUpdate(); + } + StringBuilder query = new StringBuilder(); query.append("DELETE `inventoryitems`, `inventoryequipment` FROM `inventoryitems` LEFT JOIN `inventoryequipment` USING(`inventoryitemid`) WHERE `type` = ? AND `"); query.append(account ? "accountid" : "characterid").append("` = ?"); - ps = con.prepareStatement(query.toString()); - ps.setInt(1, value); - ps.setInt(2, id); - ps.executeUpdate(); - ps.close(); - ps = con.prepareStatement("INSERT INTO `inventoryitems` VALUES (DEFAULT, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); - if (!items.isEmpty()) { - int i = 0; - for (Pair pair : items) { - Item item = pair.getLeft(); - Short bundles = bundlesList.get(i); - MapleInventoryType mit = pair.getRight(); - i++; - + try (PreparedStatement ps = con.prepareStatement(query.toString())) { + ps.setInt(1, value); + ps.setInt(2, id); + ps.executeUpdate(); + } + + int i = 0; + for (Pair pair : items) { + final Item item = pair.getLeft(); + final Short bundles = bundlesList.get(i); + final MapleInventoryType mit = pair.getRight(); + i++; + + final int genKey; + // Item + try (PreparedStatement ps = con.prepareStatement("INSERT INTO `inventoryitems` VALUES (DEFAULT, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) { ps.setInt(1, value); ps.setString(2, account ? null : String.valueOf(id)); ps.setString(3, account ? String.valueOf(id) : null); @@ -420,67 +361,56 @@ public enum ItemFactory { ps.setString(12, item.getGiftFrom()); ps.executeUpdate(); - rs = ps.getGeneratedKeys(); - if (!rs.next()) { - throw new RuntimeException("Inserting item failed."); + try (ResultSet rs = ps.getGeneratedKeys()) { + if (!rs.next()) { + throw new RuntimeException("Inserting item failed."); + } + + genKey = rs.getInt(1); } + } - int genKey = rs.getInt(1); - rs.close(); - - pse = con.prepareStatement("INSERT INTO `inventorymerchant` VALUES (DEFAULT, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); - pse.setInt(1, genKey); - pse.setInt(2, id); - pse.setInt(3, bundles); - pse.executeUpdate(); - pse.close(); + // Merchant + try (PreparedStatement ps = con.prepareStatement("INSERT INTO `inventorymerchant` VALUES (DEFAULT, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) { + ps.setInt(1, genKey); + ps.setInt(2, id); + ps.setInt(3, bundles); + ps.executeUpdate(); + } + + // Equipment + if (mit.equals(MapleInventoryType.EQUIP) || mit.equals(MapleInventoryType.EQUIPPED)) { + try (PreparedStatement ps = con.prepareStatement("INSERT INTO `inventoryequipment` VALUES (DEFAULT, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) { + ps.setInt(1, genKey); - if (mit.equals(MapleInventoryType.EQUIP) || mit.equals(MapleInventoryType.EQUIPPED)) { - pse = con.prepareStatement("INSERT INTO `inventoryequipment` VALUES (DEFAULT, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); - pse.setInt(1, genKey); - Equip equip = (Equip) item; - pse.setInt(2, equip.getUpgradeSlots()); - pse.setInt(3, equip.getLevel()); - pse.setInt(4, equip.getStr()); - pse.setInt(5, equip.getDex()); - pse.setInt(6, equip.getInt()); - pse.setInt(7, equip.getLuk()); - pse.setInt(8, equip.getHp()); - pse.setInt(9, equip.getMp()); - pse.setInt(10, equip.getWatk()); - pse.setInt(11, equip.getMatk()); - pse.setInt(12, equip.getWdef()); - pse.setInt(13, equip.getMdef()); - pse.setInt(14, equip.getAcc()); - pse.setInt(15, equip.getAvoid()); - pse.setInt(16, equip.getHands()); - pse.setInt(17, equip.getSpeed()); - pse.setInt(18, equip.getJump()); - pse.setInt(19, 0); - pse.setInt(20, equip.getVicious()); - pse.setInt(21, equip.getItemLevel()); - pse.setInt(22, equip.getItemExp()); - pse.setInt(23, equip.getRingId()); - pse.executeUpdate(); - - pse.close(); + ps.setInt(2, equip.getUpgradeSlots()); + ps.setInt(3, equip.getLevel()); + ps.setInt(4, equip.getStr()); + ps.setInt(5, equip.getDex()); + ps.setInt(6, equip.getInt()); + ps.setInt(7, equip.getLuk()); + ps.setInt(8, equip.getHp()); + ps.setInt(9, equip.getMp()); + ps.setInt(10, equip.getWatk()); + ps.setInt(11, equip.getMatk()); + ps.setInt(12, equip.getWdef()); + ps.setInt(13, equip.getMdef()); + ps.setInt(14, equip.getAcc()); + ps.setInt(15, equip.getAvoid()); + ps.setInt(16, equip.getHands()); + ps.setInt(17, equip.getSpeed()); + ps.setInt(18, equip.getJump()); + ps.setInt(19, 0); + ps.setInt(20, equip.getVicious()); + ps.setInt(21, equip.getItemLevel()); + ps.setInt(22, equip.getItemExp()); + ps.setInt(23, equip.getRingId()); + ps.executeUpdate(); } } } - - ps.close(); } finally { - if (ps != null && !ps.isClosed()) { - ps.close(); - } - if (pse != null && !pse.isClosed()) { - pse.close(); - } - if(rs != null && !rs.isClosed()) { - rs.close(); - } - lock.unlock(); } } diff --git a/src/main/java/client/inventory/MaplePet.java b/src/main/java/client/inventory/MaplePet.java index f26944c5fa..8596328df1 100644 --- a/src/main/java/client/inventory/MaplePet.java +++ b/src/main/java/client/inventory/MaplePet.java @@ -21,23 +21,24 @@ */ package client.inventory; +import client.MapleCharacter; +import client.inventory.manipulator.MapleCashidGenerator; import constants.game.ExpTable; -import java.awt.Point; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; -import tools.DatabaseConnection; import server.MapleItemInformationProvider; import server.movement.AbsoluteLifeMovement; import server.movement.LifeMovement; import server.movement.LifeMovementFragment; -import client.MapleCharacter; -import client.inventory.manipulator.MapleCashidGenerator; -import java.sql.Connection; +import tools.DatabaseConnection; import tools.MaplePacketCreator; import tools.Pair; +import java.awt.*; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; + /** * * @author Matze @@ -75,22 +76,20 @@ public class MaplePet extends Item { } public static MaplePet loadFromDb(int itemid, short position, int petid) { - try { - MaplePet ret = new MaplePet(itemid, position, petid); - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT name, level, closeness, fullness, summoned, flag FROM pets WHERE petid = ?"); // Get pet details.. + MaplePet ret = new MaplePet(itemid, position, petid); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT name, level, closeness, fullness, summoned, flag FROM pets WHERE petid = ?")) { // Get the pet details... ps.setInt(1, petid); - ResultSet rs = ps.executeQuery(); - rs.next(); - ret.setName(rs.getString("name")); - ret.setCloseness(Math.min(rs.getInt("closeness"), 30000)); - ret.setLevel((byte) Math.min(rs.getByte("level"), 30)); - ret.setFullness(Math.min(rs.getInt("fullness"), 100)); - ret.setSummoned(rs.getInt("summoned") == 1); - ret.setPetFlag(rs.getInt("flag")); - rs.close(); - ps.close(); - con.close(); + + try (ResultSet rs = ps.executeQuery()) { + rs.next(); + ret.setName(rs.getString("name")); + ret.setCloseness(Math.min(rs.getInt("closeness"), 30000)); + ret.setLevel((byte) Math.min(rs.getByte("level"), 30)); + ret.setFullness(Math.min(rs.getInt("fullness"), 100)); + ret.setSummoned(rs.getInt("summoned") == 1); + ret.setPetFlag(rs.getInt("flag")); + } return ret; } catch (SQLException e) { e.printStackTrace(); @@ -99,16 +98,11 @@ public class MaplePet extends Item { } public static void deleteFromDb(MapleCharacter owner, int petid) { - try { - Connection con = DatabaseConnection.getConnection(); - - PreparedStatement ps = con.prepareStatement("DELETE FROM pets WHERE `petid` = ?"); // thanks Vcoc for detecting petignores remaining after deletion + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("DELETE FROM pets WHERE `petid` = ?")) { + // thanks Vcoc for detecting petignores remaining after deletion ps.setInt(1, petid); - ps.executeUpdate(); - ps.close(); - - con.close(); - + owner.resetExcluded(petid); MapleCashidGenerator.freeCashId(petid); } catch (SQLException ex) { @@ -117,9 +111,8 @@ public class MaplePet extends Item { } public void saveToDb() { - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("UPDATE pets SET name = ?, level = ?, closeness = ?, fullness = ?, summoned = ?, flag = ? WHERE petid = ?"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE pets SET name = ?, level = ?, closeness = ?, fullness = ?, summoned = ?, flag = ? WHERE petid = ?")) { ps.setString(1, getName()); ps.setInt(2, getLevel()); ps.setInt(3, getCloseness()); @@ -128,23 +121,18 @@ public class MaplePet extends Item { ps.setInt(6, getPetFlag()); ps.setInt(7, getUniqueId()); ps.executeUpdate(); - ps.close(); - con.close(); } catch (SQLException e) { e.printStackTrace(); } } public static int createPet(int itemid) { - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("INSERT INTO pets (petid, name, level, closeness, fullness, summoned, flag) VALUES (?, ?, 1, 0, 100, 0, 0)"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("INSERT INTO pets (petid, name, level, closeness, fullness, summoned, flag) VALUES (?, ?, 1, 0, 100, 0, 0)")) { int ret = MapleCashidGenerator.generateCashId(); ps.setInt(1, ret); ps.setString(2, MapleItemInformationProvider.getInstance().getName(itemid)); ps.executeUpdate(); - ps.close(); - con.close(); return ret; } catch (SQLException e) { e.printStackTrace(); @@ -153,9 +141,8 @@ public class MaplePet extends Item { } public static int createPet(int itemid, byte level, int closeness, int fullness) { - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("INSERT INTO pets (petid, name, level, closeness, fullness, summoned, flag) VALUES (?, ?, ?, ?, ?, 0, 0)"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("INSERT INTO pets (petid, name, level, closeness, fullness, summoned, flag) VALUES (?, ?, ?, ?, ?, 0, 0)")) { int ret = MapleCashidGenerator.generateCashId(); ps.setInt(1, ret); ps.setString(2, MapleItemInformationProvider.getInstance().getName(itemid)); @@ -163,8 +150,6 @@ public class MaplePet extends Item { ps.setInt(4, closeness); ps.setInt(5, fullness); ps.executeUpdate(); - ps.close(); - con.close(); return ret; } catch (SQLException e) { e.printStackTrace(); diff --git a/src/main/java/client/inventory/manipulator/MapleCashidGenerator.java b/src/main/java/client/inventory/manipulator/MapleCashidGenerator.java index 4345518d43..274c2fdb8c 100644 --- a/src/main/java/client/inventory/manipulator/MapleCashidGenerator.java +++ b/src/main/java/client/inventory/manipulator/MapleCashidGenerator.java @@ -19,65 +19,50 @@ */ package client.inventory.manipulator; +import tools.DatabaseConnection; + import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashSet; import java.util.Set; -import tools.DatabaseConnection; /** - * * @author RonanLana */ public class MapleCashidGenerator { - + private final static Set existentCashids = new HashSet<>(10000); private static Integer runningCashid = 0; - + private static void loadExistentCashIdsFromQuery(Connection con, String query) throws SQLException { - PreparedStatement ps = con.prepareStatement(query); - ResultSet rs = ps.executeQuery(); - - while (rs.next()) { - int id = rs.getInt(1); - if (!rs.wasNull()) { - existentCashids.add(id); + try (PreparedStatement ps = con.prepareStatement(query); + ResultSet rs = ps.executeQuery()) { + + while (rs.next()) { + int id = rs.getInt(1); + if (!rs.wasNull()) { + existentCashids.add(id); + } } } - - rs.close(); - ps.close(); } - + public static synchronized void loadExistentCashIdsFromDb() { - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - + try (Connection con = DatabaseConnection.getConnection()) { loadExistentCashIdsFromQuery(con, "SELECT id FROM rings"); loadExistentCashIdsFromQuery(con, "SELECT petid FROM pets"); - - con.close(); } catch (SQLException ex) { ex.printStackTrace(); - } finally { - try { - if (con != null && !con.isClosed()) { - con.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } } - + runningCashid = 0; do { runningCashid++; // hopefully the id will never surpass the allotted amount for pets/rings? } while (existentCashids.contains(runningCashid)); } - + private static void getNextAvailableCashId() { runningCashid++; if (runningCashid >= 777000000) { @@ -85,23 +70,23 @@ public class MapleCashidGenerator { loadExistentCashIdsFromDb(); } } - + public static synchronized int generateCashId() { while (true) { if (!existentCashids.contains(runningCashid)) { int ret = runningCashid; getNextAvailableCashId(); - + // existentCashids.add(ret)... no need to do this since the wrap over already refetches already used cashids from the DB return ret; } - + getNextAvailableCashId(); } } - + public static synchronized void freeCashId(int cashId) { existentCashids.remove(cashId); } - + } diff --git a/src/main/java/client/processor/npc/DueyProcessor.java b/src/main/java/client/processor/npc/DueyProcessor.java index 0cc17d4636..a0c71d3eaf 100644 --- a/src/main/java/client/processor/npc/DueyProcessor.java +++ b/src/main/java/client/processor/npc/DueyProcessor.java @@ -34,16 +34,6 @@ import client.inventory.manipulator.MapleInventoryManipulator; import client.inventory.manipulator.MapleKarmaManipulator; import config.YamlConfig; import constants.inventory.ItemConstants; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.util.Calendar; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; import net.server.channel.Channel; import server.DueyPackage; import server.MapleItemInformationProvider; @@ -53,12 +43,17 @@ import tools.FilePrinter; import tools.MaplePacketCreator; import tools.Pair; +import java.sql.*; +import java.util.Calendar; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + /** - * * @author RonanLana - synchronization of Duey modules */ public class DueyProcessor { - + public enum Actions { TOSERVER_RECV_ITEM(0x00), TOSERVER_SEND_ITEM(0x02), @@ -84,7 +79,7 @@ public class DueyProcessor { TOCLIENT_RECV_PACKAGE_MSG(0x1B); final byte code; - private Actions(int code) { + Actions(int code) { this.code = (byte) code; } @@ -92,90 +87,56 @@ public class DueyProcessor { return code; } } - + private static Pair getAccountCharacterIdFromCNAME(String name) { - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT id,accountid FROM characters WHERE name = ?"); + Pair ids = null; + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT id,accountid FROM characters WHERE name = ?")) { ps.setString(1, name); - - Pair id_ = null; + try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { - id_ = new Pair<>(rs.getInt("accountid"), rs.getInt("id")); + ids = new Pair<>(rs.getInt("accountid"), rs.getInt("id")); } } - ps.close(); - con.close(); - return id_; } catch (SQLException e) { e.printStackTrace(); } - return null; + + return ids; } - + private static void showDueyNotification(MapleClient c, MapleCharacter player) { - Connection con = null; - PreparedStatement ps = null; - PreparedStatement pss = null; - ResultSet rs = null; - try { - con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("SELECT SenderName, Type FROM dueypackages WHERE ReceiverId = ? AND Checked = 1 ORDER BY Type DESC"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT SenderName, Type FROM dueypackages WHERE ReceiverId = ? AND Checked = 1 ORDER BY Type DESC")) { + ps.setInt(1, player.getId()); - rs = ps.executeQuery(); - if (rs.next()) { - try { - Connection con2 = DatabaseConnection.getConnection(); - pss = con2.prepareStatement("UPDATE dueypackages SET Checked = 0 where ReceiverId = ?"); - pss.setInt(1, player.getId()); - pss.executeUpdate(); - pss.close(); - con2.close(); - - c.announce(MaplePacketCreator.sendDueyParcelReceived(rs.getString("SenderName"), rs.getInt("Type") == 1)); - } catch (SQLException e) { - e.printStackTrace(); + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + try (PreparedStatement ps2 = con.prepareStatement("UPDATE dueypackages SET Checked = 0 where ReceiverId = ?")) { + ps2.setInt(1, player.getId()); + ps2.executeUpdate(); + + c.announce(MaplePacketCreator.sendDueyParcelReceived(rs.getString("SenderName"), rs.getInt("Type") == 1)); + } } } } catch (SQLException e) { e.printStackTrace(); - } finally { - try { - if (rs != null) { - rs.close(); - } - if (pss != null) { - pss.close(); - } - if (ps != null) { - ps.close(); - } - if (con != null) { - con.close(); - } - } catch (SQLException ex) { - ex.printStackTrace(); - } } } private static void deletePackageFromInventoryDB(Connection con, int packageId) throws SQLException { ItemFactory.DUEY.saveItems(new LinkedList>(), packageId, con); } - + private static void removePackageFromDB(int packageId) { - try { - Connection con = DatabaseConnection.getConnection(); - - PreparedStatement ps = con.prepareStatement("DELETE FROM dueypackages WHERE PackageId = ?"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("DELETE FROM dueypackages WHERE PackageId = ?")) { ps.setInt(1, packageId); ps.executeUpdate(); - ps.close(); - + deletePackageFromInventoryDB(con, packageId); - - con.close(); } catch (SQLException e) { e.printStackTrace(); } @@ -184,123 +145,102 @@ public class DueyProcessor { private static DueyPackage getPackageFromDB(ResultSet rs) { try { int packageId = rs.getInt("PackageId"); - + List> dueyItems = ItemFactory.DUEY.loadItems(packageId, false); DueyPackage dueypack; - + if (!dueyItems.isEmpty()) { // in a duey package there's only one item dueypack = new DueyPackage(packageId, dueyItems.get(0).getLeft()); } else { dueypack = new DueyPackage(packageId); } - + dueypack.setSender(rs.getString("SenderName")); dueypack.setMesos(rs.getInt("Mesos")); dueypack.setSentTime(rs.getTimestamp("TimeStamp"), rs.getBoolean("Type")); dueypack.setMessage(rs.getString("Message")); - + return dueypack; } catch (SQLException sqle) { sqle.printStackTrace(); return null; } } - + private static List loadPackages(MapleCharacter chr) { List packages = new LinkedList<>(); - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("SELECT * FROM dueypackages dp WHERE ReceiverId = ?")) { - ps.setInt(1, chr.getId()); - try (ResultSet rs = ps.executeQuery()) { - while (rs.next()) { - DueyPackage dueypack = getPackageFromDB(rs); - if (dueypack == null) continue; - - packages.add(dueypack); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT * FROM dueypackages dp WHERE ReceiverId = ?")) { + ps.setInt(1, chr.getId()); + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + DueyPackage dueypack = getPackageFromDB(rs); + if (dueypack == null) { + continue; } + + packages.add(dueypack); } } - - con.close(); + } catch (SQLException e) { e.printStackTrace(); } - + return packages; } - - private static int createPackage(int mesos, String message, String sender, int toCid, boolean quick) { - try { - Connection con = null; - PreparedStatement ps = null; - ResultSet rs = null; - - try { - con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("INSERT INTO `dueypackages` (ReceiverId, SenderName, Mesos, TimeStamp, Message, Type, Checked) VALUES (?, ?, ?, ?, ?, ?, 1)", Statement.RETURN_GENERATED_KEYS); - ps.setInt(1, toCid); - ps.setString(2, sender); - ps.setInt(3, mesos); - ps.setTimestamp(4, new Timestamp(System.currentTimeMillis())); - ps.setString(5, message); - ps.setInt(6, quick ? 1 : 0); - int updateRows = ps.executeUpdate(); - if (updateRows < 1) { - FilePrinter.printError(FilePrinter.INSERT_CHAR, "Error trying to create package [mesos: " + mesos + ", " + sender + ", quick: " + quick + ", to CharacterId: " + toCid + "]"); - return -1; - } - - int packageId; - rs = ps.getGeneratedKeys(); + private static int createPackage(int mesos, String message, String sender, int toCid, boolean quick) { + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("INSERT INTO `dueypackages` (ReceiverId, SenderName, Mesos, TimeStamp, Message, Type, Checked) VALUES (?, ?, ?, ?, ?, ?, 1)", Statement.RETURN_GENERATED_KEYS)) { + ps.setInt(1, toCid); + ps.setString(2, sender); + ps.setInt(3, mesos); + ps.setTimestamp(4, new Timestamp(System.currentTimeMillis())); + ps.setString(5, message); + ps.setInt(6, quick ? 1 : 0); + + int updateRows = ps.executeUpdate(); + if (updateRows < 1) { + FilePrinter.printError(FilePrinter.INSERT_CHAR, "Error trying to create package [mesos: " + mesos + ", " + sender + ", quick: " + quick + ", to CharacterId: " + toCid + "]"); + return -1; + } + + final int packageId; + try (ResultSet rs = ps.getGeneratedKeys()) { if (rs.next()) { packageId = rs.getInt(1); } else { FilePrinter.printError(FilePrinter.INSERT_CHAR, "Failed inserting package [mesos: " + mesos + ", " + sender + ", quick: " + quick + ", to CharacterId: " + toCid + "]"); return -1; } - - return packageId; - } finally { - if (rs != null && !rs.isClosed()) { - rs.close(); - } - - if (ps != null && !ps.isClosed()) { - ps.close(); - } - - if (con != null && !con.isClosed()) { - con.close(); - } } + + return packageId; } catch (SQLException sqle) { sqle.printStackTrace(); } - + return -1; } - + private static boolean insertPackageItem(int packageId, Item item) { - try { - Pair dueyItem = new Pair<>(item, MapleInventoryType.getByType(item.getItemType())); - Connection con = DatabaseConnection.getConnection(); + Pair dueyItem = new Pair<>(item, MapleInventoryType.getByType(item.getItemType())); + try (Connection con = DatabaseConnection.getConnection()) { ItemFactory.DUEY.saveItems(Collections.singletonList(dueyItem), packageId, con); - con.close(); - return true; } catch (SQLException sqle) { sqle.printStackTrace(); - - return false; } + + return false; } - + private static int addPackageItemFromInventory(int packageId, MapleClient c, byte invTypeId, short itemPos, short amount) { if (invTypeId > 0) { MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance(); - + MapleInventoryType invType = MapleInventoryType.getByType(invTypeId); MapleInventory inv = c.getPlayer().getInventory(invType); @@ -326,18 +266,18 @@ public class DueyProcessor { } finally { inv.unlockInventory(); } - + MapleKarmaManipulator.toggleKarmaFlagToUntradeable(item); item.setQuantity(amount); - + if (!insertPackageItem(packageId, item)) { return 1; } } - + return 0; } - + public static void dueySendItem(MapleClient c, byte invTypeId, short itemPos, short amount, int sendMesos, String sendMessage, String recipient, boolean quick) { if (c.tryacquireClient()) { try { @@ -350,7 +290,7 @@ public class DueyProcessor { c.disconnect(true, false); return; } - + long finalcost = (long) sendMesos + fee; if (finalcost < 0 || finalcost > Integer.MAX_VALUE || (amount < 1 && sendMesos == 0)) { AutobanFactory.PACKET_EDIT.alert(c.getPlayer(), c.getPlayer().getName() + " tried to packet edit with duey."); @@ -358,7 +298,7 @@ public class DueyProcessor { c.disconnect(true, false); return; } - + Pair accIdCid; if (c.getPlayer().getMeso() >= finalcost) { accIdCid = getAccountCharacterIdFromCNAME(recipient); @@ -376,24 +316,24 @@ public class DueyProcessor { c.announce(MaplePacketCreator.sendDueyMSG(DueyProcessor.Actions.TOCLIENT_SEND_NOT_ENOUGH_MESOS.getCode())); return; } - + int recipientCid = accIdCid.getRight(); if (recipientCid == -1) { c.announce(MaplePacketCreator.sendDueyMSG(DueyProcessor.Actions.TOCLIENT_SEND_NAME_DOES_NOT_EXIST.getCode())); return; } - + if (quick) { MapleInventoryManipulator.removeById(c, MapleInventoryType.CASH, 5330000, (short) 1, false, false); } - + int packageId = createPackage(sendMesos, sendMessage, c.getPlayer().getName(), recipientCid, quick); if (packageId == -1) { c.announce(MaplePacketCreator.sendDueyMSG(DueyProcessor.Actions.TOCLIENT_SEND_ENABLE_ACTIONS.getCode())); return; } c.getPlayer().gainMeso((int) -finalcost, false); - + int res = addPackageItemFromInventory(packageId, c, invTypeId, itemPos, amount); if (res == 0) { c.announce(MaplePacketCreator.sendDueyMSG(DueyProcessor.Actions.TOCLIENT_SEND_SUCCESSFULLY_SENT.getCode())); @@ -402,19 +342,19 @@ public class DueyProcessor { } else { c.announce(MaplePacketCreator.sendDueyMSG(DueyProcessor.Actions.TOCLIENT_SEND_INCORRECT_REQUEST.getCode())); } - + MapleClient rClient = null; int channel = c.getWorldServer().find(recipient); if (channel > -1) { Channel rcserv = c.getWorldServer().getChannel(channel); - if(rcserv != null) { + if (rcserv != null) { MapleCharacter rChr = rcserv.getPlayerStorage().getCharacterByName(recipient); - if(rChr != null) { + if (rChr != null) { rClient = rChr.getClient(); } } } - + if (rClient != null && rClient.isLoggedIn() && !rClient.getPlayer().isAwayFromWorld()) { showDueyNotification(rClient, rClient.getPlayer()); } @@ -423,7 +363,7 @@ public class DueyProcessor { } } } - + public static void dueyRemovePackage(MapleClient c, int packageid, boolean playerRemove) { if (c.tryacquireClient()) { try { @@ -434,31 +374,29 @@ public class DueyProcessor { } } } - + public static void dueyClaimPackage(MapleClient c, int packageId) { if (c.tryacquireClient()) { try { try { DueyPackage dp = null; - - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("SELECT * FROM dueypackages dp WHERE PackageId = ?")) { + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT * FROM dueypackages dp WHERE PackageId = ?")) { ps.setInt(1, packageId); - + try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { dp = getPackageFromDB(rs); } } } - con.close(); - + if (dp == null) { c.announce(MaplePacketCreator.sendDueyMSG(Actions.TOCLIENT_RECV_UNKNOWN_ERROR.getCode())); FilePrinter.printError(FilePrinter.EXPLOITS + c.getPlayer().getName() + ".txt", c.getPlayer().getName() + " tried to receive package from duey with id " + packageId); return; } - + if (dp.isDeliveringTime()) { c.announce(MaplePacketCreator.sendDueyMSG(Actions.TOCLIENT_RECV_UNKNOWN_ERROR.getCode())); return; @@ -470,10 +408,10 @@ public class DueyProcessor { c.announce(MaplePacketCreator.sendDueyMSG(Actions.TOCLIENT_RECV_UNKNOWN_ERROR.getCode())); return; } - + if (!MapleInventoryManipulator.checkSpace(c, dpItem.getItemId(), dpItem.getQuantity(), dpItem.getOwner())) { int itemid = dpItem.getItemId(); - if(MapleItemInformationProvider.getInstance().isPickupRestricted(itemid) && c.getPlayer().getInventory(ItemConstants.getInventoryType(itemid)).findById(itemid) != null) { + if (MapleItemInformationProvider.getInstance().isPickupRestricted(itemid) && c.getPlayer().getInventory(ItemConstants.getInventoryType(itemid)).findById(itemid) != null) { c.announce(MaplePacketCreator.sendDueyMSG(Actions.TOCLIENT_RECV_RECEIVER_WITH_UNIQUE.getCode())); } else { c.announce(MaplePacketCreator.sendDueyMSG(Actions.TOCLIENT_RECV_NO_FREE_SLOTS.getCode())); @@ -484,9 +422,9 @@ public class DueyProcessor { MapleInventoryManipulator.addFromDrop(c, dpItem, false); } } - + c.getPlayer().gainMeso(dp.getMesos(), false); - + dueyRemovePackage(c, packageId, false); } catch (SQLException e) { e.printStackTrace(); @@ -496,17 +434,17 @@ public class DueyProcessor { } } } - + public static void dueySendTalk(MapleClient c, boolean quickDelivery) { if (c.tryacquireClient()) { try { long timeNow = System.currentTimeMillis(); - if(timeNow - c.getPlayer().getNpcCooldown() < YamlConfig.config.server.BLOCK_NPC_RACE_CONDT) { + if (timeNow - c.getPlayer().getNpcCooldown() < YamlConfig.config.server.BLOCK_NPC_RACE_CONDT) { c.announce(MaplePacketCreator.enableActions()); return; } c.getPlayer().setNpcCooldown(timeNow); - + if (quickDelivery) { c.announce(MaplePacketCreator.sendDuey(0x1A, null)); } else { @@ -517,43 +455,39 @@ public class DueyProcessor { } } } - + public static void dueyCreatePackage(Item item, int mesos, String sender, int recipientCid) { int packageId = createPackage(mesos, null, sender, recipientCid, false); if (packageId != -1) { insertPackageItem(packageId, item); } } - + public static void runDueyExpireSchedule() { - try { - Calendar c = Calendar.getInstance(); - c.add(Calendar.DATE, -30); - - Timestamp ts = new Timestamp(c.getTime().getTime()); - - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT `PackageId` FROM dueypackages WHERE `TimeStamp` < ?"); - ps.setTimestamp(1, ts); - + Calendar c = Calendar.getInstance(); + c.add(Calendar.DATE, -30); + final Timestamp ts = new Timestamp(c.getTime().getTime()); + + try (Connection con = DatabaseConnection.getConnection()){ List toRemove = new LinkedList<>(); - try (ResultSet rs = ps.executeQuery()) { - while (rs.next()) { - toRemove.add(rs.getInt("PackageId")); + try (PreparedStatement ps = con.prepareStatement("SELECT `PackageId` FROM dueypackages WHERE `TimeStamp` < ?")) { + ps.setTimestamp(1, ts); + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + toRemove.add(rs.getInt("PackageId")); + } } } - ps.close(); - + for (Integer pid : toRemove) { removePackageFromDB(pid); } - - ps = con.prepareStatement("DELETE FROM dueypackages WHERE `TimeStamp` < ?"); - ps.setTimestamp(1, ts); - ps.executeUpdate(); - ps.close(); - - con.close(); + + try (PreparedStatement ps = con.prepareStatement("DELETE FROM dueypackages WHERE `TimeStamp` < ?")) { + ps.setTimestamp(1, ts); + ps.executeUpdate(); + } } catch (SQLException e) { e.printStackTrace(); } diff --git a/src/main/java/client/processor/npc/FredrickProcessor.java b/src/main/java/client/processor/npc/FredrickProcessor.java index 3b807b6552..3b8f0dfa2c 100644 --- a/src/main/java/client/processor/npc/FredrickProcessor.java +++ b/src/main/java/client/processor/npc/FredrickProcessor.java @@ -29,15 +29,7 @@ import client.inventory.Item; import client.inventory.ItemFactory; import client.inventory.MapleInventory; import client.inventory.MapleInventoryType; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.util.LinkedList; -import java.util.List; import client.inventory.manipulator.MapleInventoryManipulator; -import java.util.Collections; import net.server.Server; import net.server.world.World; import server.MapleItemInformationProvider; @@ -47,6 +39,11 @@ import tools.FilePrinter; import tools.MaplePacketCreator; import tools.Pair; +import java.sql.*; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + /** * * @author RonanLana - synchronization of Fredrick modules and operation results @@ -100,10 +97,8 @@ public class FredrickProcessor { } public static void removeFredrickLog(int cid) { - try { - Connection con = DatabaseConnection.getConnection(); + try (Connection con = DatabaseConnection.getConnection()) { removeFredrickLog(con, cid); - con.close(); } catch (SQLException sqle) { sqle.printStackTrace(); } @@ -112,22 +107,19 @@ public class FredrickProcessor { private static void removeFredrickLog(Connection con, int cid) throws SQLException { try (PreparedStatement ps = con.prepareStatement("DELETE FROM `fredstorage` WHERE `cid` = ?")) { ps.setInt(1, cid); - ps.execute(); + ps.executeUpdate(); } } public static void insertFredrickLog(int cid) { - try { - Connection con = DatabaseConnection.getConnection(); - + try (Connection con = DatabaseConnection.getConnection()) { + removeFredrickLog(con, cid); try (PreparedStatement ps = con.prepareStatement("INSERT INTO `fredstorage` (`cid`, `daynotes`, `timestamp`) VALUES (?, 0, ?)")) { ps.setInt(1, cid); ps.setTimestamp(2, new Timestamp(System.currentTimeMillis())); - ps.execute(); + ps.executeUpdate(); } - - con.close(); } catch (SQLException sqle) { sqle.printStackTrace(); } @@ -145,64 +137,59 @@ public class FredrickProcessor { expiredCnames.add(name); } } - - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("DELETE FROM `notes` WHERE `from` LIKE ? AND `to` LIKE ?")) { - ps.setString(1, "FREDRICK"); - - for (String cname : expiredCnames) { - ps.setString(2, cname); - ps.executeBatch(); - } + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("DELETE FROM `notes` WHERE `from` LIKE ? AND `to` LIKE ?")) { + ps.setString(1, "FREDRICK"); + + for (String cname : expiredCnames) { + ps.setString(2, cname); + ps.executeBatch(); } - con.close(); } catch (SQLException e) { e.printStackTrace(); } } public static void runFredrickSchedule() { - try { - Connection con = DatabaseConnection.getConnection(); - + try (Connection con = DatabaseConnection.getConnection()) { List> expiredCids = new LinkedList<>(); List, Integer>> notifCids = new LinkedList<>(); - try (PreparedStatement ps = con.prepareStatement("SELECT * FROM fredstorage f LEFT JOIN (SELECT id, name, world, lastLogoutTime FROM characters) AS c ON c.id = f.cid")) { - try (ResultSet rs = ps.executeQuery()) { - long curTime = System.currentTimeMillis(); - - while (rs.next()) { - int cid = rs.getInt("cid"); - int world = rs.getInt("world"); - Timestamp ts = rs.getTimestamp("timestamp"); - int daynotes = Math.min(dailyReminders.length - 1, rs.getInt("daynotes")); - - int elapsedDays = timestampElapsedDays(ts, curTime); - if (elapsedDays > 100) { - expiredCids.add(new Pair<>(cid, world)); - } else { - int notifDay = dailyReminders[daynotes]; - - if (elapsedDays >= notifDay) { - do { - daynotes++; - notifDay = dailyReminders[daynotes]; - } while (elapsedDays >= notifDay); - - Timestamp logoutTs = rs.getTimestamp("lastLogoutTime"); - int inactivityDays = timestampElapsedDays(logoutTs, curTime); - - if (inactivityDays < 7 || daynotes >= dailyReminders.length - 1) { // don't spam inactive players - String name = rs.getString("name"); - notifCids.add(new Pair<>(new Pair<>(cid, name), daynotes)); - } + try (PreparedStatement ps = con.prepareStatement("SELECT * FROM fredstorage f LEFT JOIN (SELECT id, name, world, lastLogoutTime FROM characters) AS c ON c.id = f.cid"); + ResultSet rs = ps.executeQuery()) { + long curTime = System.currentTimeMillis(); + + while (rs.next()) { + int cid = rs.getInt("cid"); + int world = rs.getInt("world"); + Timestamp ts = rs.getTimestamp("timestamp"); + int daynotes = Math.min(dailyReminders.length - 1, rs.getInt("daynotes")); + + int elapsedDays = timestampElapsedDays(ts, curTime); + if (elapsedDays > 100) { + expiredCids.add(new Pair<>(cid, world)); + } else { + int notifDay = dailyReminders[daynotes]; + + if (elapsedDays >= notifDay) { + do { + daynotes++; + notifDay = dailyReminders[daynotes]; + } while (elapsedDays >= notifDay); + + Timestamp logoutTs = rs.getTimestamp("lastLogoutTime"); + int inactivityDays = timestampElapsedDays(logoutTs, curTime); + + if (inactivityDays < 7 || daynotes >= dailyReminders.length - 1) { // don't spam inactive players + String name = rs.getString("name"); + notifCids.add(new Pair<>(new Pair<>(cid, name), daynotes)); } } } } + } - + if (!expiredCids.isEmpty()) { try (PreparedStatement ps = con.prepareStatement("DELETE FROM `inventoryitems` WHERE `type` = ? AND `characterid` = ?")) { ps.setInt(1, ItemFactory.MERCHANT.getValue()); @@ -211,15 +198,15 @@ public class FredrickProcessor { ps.setInt(2, cid.getLeft()); ps.addBatch(); } - + ps.executeBatch(); } - + try (PreparedStatement ps = con.prepareStatement("UPDATE `characters` SET `MerchantMesos` = 0 WHERE `id` = ?")) { for (Pair cid : expiredCids) { ps.setInt(1, cid.getLeft()); ps.addBatch(); - + World wserv = Server.getInstance().getWorld(cid.getRight()); if (wserv != null) { MapleCharacter chr = wserv.getPlayerStorage().getCharacterById(cid.getLeft()); @@ -228,52 +215,48 @@ public class FredrickProcessor { } } } - + ps.executeBatch(); } - + removeFredrickReminders(expiredCids); - + try (PreparedStatement ps = con.prepareStatement("DELETE FROM `fredstorage` WHERE `cid` = ?")) { for (Pair cid : expiredCids) { ps.setInt(1, cid.getLeft()); ps.addBatch(); } - + ps.executeBatch(); } } - + if (!notifCids.isEmpty()) { try (PreparedStatement ps = con.prepareStatement("UPDATE `fredstorage` SET `daynotes` = ? WHERE `cid` = ?")) { for (Pair, Integer> cid : notifCids) { ps.setInt(1, cid.getRight()); ps.setInt(2, cid.getLeft().getLeft()); ps.addBatch(); - + String msg = fredrickReminderMessage(cid.getRight() - 1); MapleCharacter.sendNote(cid.getLeft().getRight(), "FREDRICK", msg, (byte) 0); } - + ps.executeBatch(); } } - - con.close(); } catch (SQLException e) { e.printStackTrace(); } } private static boolean deleteFredrickItems(int cid) { - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("DELETE FROM `inventoryitems` WHERE `type` = ? AND `characterid` = ?")) { - ps.setInt(1, ItemFactory.MERCHANT.getValue()); - ps.setInt(2, cid); - ps.execute(); - } - con.close(); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("DELETE FROM `inventoryitems` WHERE `type` = ? AND `characterid` = ?")) { + ps.setInt(1, ItemFactory.MERCHANT.getValue()); + ps.setInt(2, cid); + ps.executeUpdate(); + return true; } catch (SQLException e) { e.printStackTrace(); diff --git a/src/main/java/net/server/Server.java b/src/main/java/net/server/Server.java index 27b8025f26..96c5577383 100644 --- a/src/main/java/net/server/Server.java +++ b/src/main/java/net/server/Server.java @@ -21,28 +21,22 @@ */ package net.server; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.security.Security; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collections; -import java.util.HashSet; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.locks.Lock; - +import client.MapleCharacter; +import client.MapleClient; +import client.MapleFamily; +import client.SkillFactory; +import client.command.CommandsExecutor; +import client.inventory.Item; +import client.inventory.ItemFactory; +import client.inventory.manipulator.MapleCashidGenerator; +import client.newyear.NewYearCardRecord; import config.YamlConfig; +import constants.game.GameConstants; +import constants.inventory.ItemConstants; +import constants.net.OpcodeConstants; +import constants.net.ServerConstants; +import net.MapleServerHandler; +import net.mina.MapleCodecFactory; import net.server.audit.ThreadTracker; import net.server.audit.locks.MonitoredLockType; import net.server.audit.locks.MonitoredReadLock; @@ -51,28 +45,13 @@ import net.server.audit.locks.MonitoredWriteLock; import net.server.audit.locks.factory.MonitoredReadLockFactory; import net.server.audit.locks.factory.MonitoredReentrantLockFactory; import net.server.audit.locks.factory.MonitoredWriteLockFactory; - -import net.MapleServerHandler; -import net.mina.MapleCodecFactory; import net.server.channel.Channel; import net.server.coordinator.session.MapleSessionCoordinator; import net.server.guild.MapleAlliance; import net.server.guild.MapleGuild; import net.server.guild.MapleGuildCharacter; -import net.server.task.BossLogTask; -import net.server.task.CharacterDiseaseTask; -import net.server.task.CouponTask; -import net.server.task.EventRecallCoordinatorTask; -import net.server.task.DueyFredrickTask; -import net.server.task.InvitationTask; -import net.server.task.LoginCoordinatorTask; -import net.server.task.LoginStorageTask; -import net.server.task.RankingCommandTask; -import net.server.task.RankingLoginTask; -import net.server.task.ReleaseLockTask; -import net.server.task.RespawnTask; +import net.server.task.*; import net.server.world.World; - import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.buffer.SimpleBufferAllocator; import org.apache.mina.core.filterchain.IoFilter; @@ -80,21 +59,6 @@ import org.apache.mina.core.service.IoAcceptor; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.transport.socket.nio.NioSocketAcceptor; - -import client.MapleClient; -import client.MapleFamily; -import client.MapleCharacter; -import client.SkillFactory; -import client.command.CommandsExecutor; -import client.inventory.Item; -import client.inventory.ItemFactory; -import client.inventory.manipulator.MapleCashidGenerator; -import client.newyear.NewYearCardRecord; -import constants.inventory.ItemConstants; -import constants.game.GameConstants; -import constants.net.OpcodeConstants; -import constants.net.ServerConstants; -import java.util.TimeZone; import server.CashShop.CashItemFactory; import server.MapleSkillbookInformationProvider; import server.ThreadManager; @@ -107,21 +71,33 @@ import tools.DatabaseConnection; import tools.FilePrinter; import tools.Pair; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.security.Security; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.*; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.locks.Lock; + public class Server { - + private static Server instance = null; - + public static Server getInstance() { if (instance == null) { instance = new Server(); } return instance; } - + private static final Set activeFly = new HashSet<>(); private static final Map couponRates = new HashMap<>(30); private static final List activeCoupons = new LinkedList<>(); - + private IoAcceptor acceptor; private List> channels = new LinkedList<>(); private List worlds = new ArrayList<>(); @@ -133,53 +109,53 @@ public class Server { private List> worldRecommendedList = new LinkedList<>(); private final Map guilds = new HashMap<>(100); private final Map inLoginState = new HashMap<>(100); - + private final PlayerBuffStorage buffStorage = new PlayerBuffStorage(); private final Map alliances = new HashMap<>(100); private final Map newyears = new HashMap<>(); private final List processDiseaseAnnouncePlayers = new LinkedList<>(); private final List registeredDiseaseAnnouncePlayers = new LinkedList<>(); - + private final List>> playerRanking = new LinkedList<>(); - + private final Lock srvLock = MonitoredReentrantLockFactory.createLock(MonitoredLockType.SERVER); private final Lock disLock = MonitoredReentrantLockFactory.createLock(MonitoredLockType.SERVER_DISEASES); - + private final MonitoredReentrantReadWriteLock wldLock = new MonitoredReentrantReadWriteLock(MonitoredLockType.SERVER_WORLDS, true); private final MonitoredReadLock wldRLock = MonitoredReadLockFactory.createLock(wldLock); private final MonitoredWriteLock wldWLock = MonitoredWriteLockFactory.createLock(wldLock); - + private final MonitoredReentrantReadWriteLock lgnLock = new MonitoredReentrantReadWriteLock(MonitoredLockType.SERVER_LOGIN, true); private final MonitoredReadLock lgnRLock = MonitoredReadLockFactory.createLock(lgnLock); private final MonitoredWriteLock lgnWLock = MonitoredWriteLockFactory.createLock(lgnLock); - + private final AtomicLong currentTime = new AtomicLong(0); private long serverCurrentTime = 0; - + private boolean availableDeveloperRoom = false; private boolean online = false; public static long uptime = System.currentTimeMillis(); - + public int getCurrentTimestamp() { return (int) (Server.getInstance().getCurrentTime() - Server.uptime); } - + public long getCurrentTime() { // returns a slightly delayed time value, under frequency of UPDATE_INTERVAL return serverCurrentTime; } - + public void updateCurrentTime() { serverCurrentTime = currentTime.addAndGet(YamlConfig.config.server.UPDATE_INTERVAL); } - + public long forceUpdateCurrentTime() { long timeNow = System.currentTimeMillis(); serverCurrentTime = timeNow; currentTime.set(timeNow); - + return timeNow; } - + public boolean isOnline() { return online; } @@ -187,50 +163,50 @@ public class Server { public List> worldRecommendedList() { return worldRecommendedList; } - + public void setNewYearCard(NewYearCardRecord nyc) { newyears.put(nyc.getId(), nyc); } - + public NewYearCardRecord getNewYearCard(int cardid) { return newyears.get(cardid); } - + public NewYearCardRecord removeNewYearCard(int cardid) { return newyears.remove(cardid); } - + public void setAvailableDeveloperRoom() { availableDeveloperRoom = true; } - + public boolean canEnterDeveloperRoom() { return availableDeveloperRoom; } private void loadPlayerNpcMapStepFromDb() { - try { - List wlist = this.getWorlds(); - - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT * FROM playernpcs_field"); - - ResultSet rs = ps.executeQuery(); - while(rs.next()) { - int world = rs.getInt("world"), map = rs.getInt("map"), step = rs.getInt("step"), podium = rs.getInt("podium"); - + final List wlist = this.getWorlds(); + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT * FROM playernpcs_field"); + ResultSet rs = ps.executeQuery()) { + + while (rs.next()) { + int world = rs.getInt("world"); + int map = rs.getInt("map"); + int step = rs.getInt("step"); + int podium = rs.getInt("podium"); + World w = wlist.get(world); - if(w != null) w.setPlayerNpcMapData(map, step, podium); + if (w != null) { + w.setPlayerNpcMapData(map, step, podium); + } } - - rs.close(); - ps.close(); - con.close(); } catch (SQLException e) { e.printStackTrace(); } } - + public World getWorld(int id) { wldRLock.lock(); try { @@ -252,7 +228,7 @@ public class Server { wldRLock.unlock(); } } - + public int getWorldsSize() { wldRLock.lock(); try { @@ -261,11 +237,11 @@ public class Server { wldRLock.unlock(); } } - + public Channel getChannel(int world, int channel) { try { return this.getWorld(world).getChannel(channel); - } catch(NullPointerException npe) { + } catch (NullPointerException npe) { return null; } } @@ -273,11 +249,11 @@ public class Server { public List getChannelsFromWorld(int world) { try { return this.getWorld(world).getChannels(); - } catch(NullPointerException npe) { + } catch (NullPointerException npe) { return new ArrayList<>(0); } } - + public List getAllChannels() { try { List channelz = new ArrayList<>(); @@ -287,11 +263,11 @@ public class Server { } } return channelz; - } catch(NullPointerException npe) { + } catch (NullPointerException npe) { return new ArrayList<>(0); } } - + public Set getOpenChannels(int world) { wldRLock.lock(); try { @@ -300,7 +276,7 @@ public class Server { wldRLock.unlock(); } } - + private String getIP(int world, int channel) { wldRLock.lock(); try { @@ -309,7 +285,7 @@ public class Server { wldRLock.unlock(); } } - + public String[] getInetSocket(int world, int channel) { try { return getIP(world, channel).split(":"); @@ -317,8 +293,8 @@ public class Server { return null; } } - - + + private void dumpData() { wldRLock.lock(); try { @@ -331,31 +307,37 @@ public class Server { wldRLock.unlock(); } } - + public int addChannel(int worldid) { World world; Map channelInfo; int channelid; - + wldRLock.lock(); try { - if(worldid >= worlds.size()) return -3; - + if (worldid >= worlds.size()) { + return -3; + } + channelInfo = channels.get(worldid); - if(channelInfo == null) return -3; - + if (channelInfo == null) { + return -3; + } + channelid = channelInfo.size(); - if(channelid >= YamlConfig.config.server.CHANNEL_SIZE) return -2; - + if (channelid >= YamlConfig.config.server.CHANNEL_SIZE) { + return -2; + } + channelid++; world = this.getWorld(worldid); } finally { wldRLock.unlock(); } - + Channel channel = new Channel(worldid, channelid, getCurrentTime()); channel.setServerMessage(YamlConfig.config.worlds.get(worldid).why_am_i_recommended); - + if (world.addChannel(channel)) { wldWLock.lock(); try { @@ -364,15 +346,15 @@ public class Server { wldWLock.unlock(); } } - + return channelid; } - + public int addWorld() { int newWorld = initWorld(); - if(newWorld > -1) { + if (newWorld > -1) { installWorldPlayerRanking(newWorld); - + Set accounts; lgnRLock.lock(); try { @@ -380,29 +362,29 @@ public class Server { } finally { lgnRLock.unlock(); } - - for(Integer accId : accounts) { + + for (Integer accId : accounts) { loadAccountCharactersView(accId, 0, newWorld); } } - + return newWorld; } - + private int initWorld() { int i; - + wldRLock.lock(); try { i = worlds.size(); - - if(i >= YamlConfig.config.server.WLDLIST_SIZE) { + + if (i >= YamlConfig.config.server.WLDLIST_SIZE) { return -1; } } finally { wldRLock.unlock(); } - + System.out.println("Starting world " + i); int exprate = YamlConfig.config.worlds.get(i).exp_rate; @@ -421,7 +403,7 @@ public class Server { flag, event_message, exprate, droprate, bossdroprate, mesorate, questrate, travelrate, fishingrate); - + Map channelInfo = new HashMap<>(); long bootTime = getCurrentTime(); for (int j = 1; j <= YamlConfig.config.worlds.get(i).channels; j++) { @@ -431,10 +413,10 @@ public class Server { world.addChannel(channel); channelInfo.put(channelid, channel.getIP()); } - + boolean canDeploy; - - wldWLock.lock(); // thanks Ashen for noticing a deadlock issue when trying to deploy a channel + + wldWLock.lock(); // thanks Ashen for noticing a deadlock issue when trying to deploy a channel try { canDeploy = world.getId() == worlds.size(); if (canDeploy) { @@ -445,10 +427,10 @@ public class Server { } finally { wldWLock.unlock(); } - + if (canDeploy) { world.setServerMessage(YamlConfig.config.worlds.get(i).server_message); - + System.out.println("Finished loading world " + i + "\r\n"); return i; } else { @@ -457,57 +439,61 @@ public class Server { return -2; } } - + public boolean removeChannel(int worldid) { //lol don't! World world; - + wldRLock.lock(); try { - if(worldid >= worlds.size()) return false; + if (worldid >= worlds.size()) { + return false; + } world = worlds.get(worldid); } finally { wldRLock.unlock(); } - + if (world != null) { int channel = world.removeChannel(); wldWLock.lock(); try { Map m = channels.get(worldid); - if(m != null) m.remove(channel); + if (m != null) { + m.remove(channel); + } } finally { wldWLock.unlock(); } return channel > -1; } - + return false; } - + public boolean removeWorld() { //lol don't! World w; int worldid; - + wldRLock.lock(); try { worldid = worlds.size() - 1; - if(worldid < 0) { + if (worldid < 0) { return false; } - + w = worlds.get(worldid); } finally { wldRLock.unlock(); } - - if(w == null || !w.canUninstall()) { + + if (w == null || !w.canUninstall()) { return false; } - + removeWorldPlayerRanking(); w.shutdown(); - + wldWLock.lock(); try { if (worldid == worlds.size() - 1) { @@ -518,10 +504,10 @@ public class Server { } finally { wldWLock.unlock(); } - + return true; } - + private void resetServerWorlds() { // thanks maple006 for noticing proprietary lists assigned to null wldWLock.lock(); try { @@ -532,96 +518,96 @@ public class Server { wldWLock.unlock(); } } - + private static long getTimeLeftForNextHour() { Calendar nextHour = Calendar.getInstance(); nextHour.add(Calendar.HOUR, 1); nextHour.set(Calendar.MINUTE, 0); nextHour.set(Calendar.SECOND, 0); - + return Math.max(0, nextHour.getTimeInMillis() - System.currentTimeMillis()); } - + public static long getTimeLeftForNextDay() { Calendar nextDay = Calendar.getInstance(); nextDay.add(Calendar.DAY_OF_MONTH, 1); nextDay.set(Calendar.HOUR_OF_DAY, 0); nextDay.set(Calendar.MINUTE, 0); nextDay.set(Calendar.SECOND, 0); - + return Math.max(0, nextDay.getTimeInMillis() - System.currentTimeMillis()); } - + public Map getCouponRates() { return couponRates; } - - public static void cleanNxcodeCoupons(Connection con) throws SQLException { - if (!YamlConfig.config.server.USE_CLEAR_OUTDATED_COUPONS) return; - - long timeClear = System.currentTimeMillis() - 14 * 24 * 60 * 60 * 1000; - - PreparedStatement ps = con.prepareStatement("SELECT * FROM nxcode WHERE expiration <= ?"); - ps.setLong(1, timeClear); - ResultSet rs = ps.executeQuery(); - if (!rs.isLast()) { - PreparedStatement ps2 = con.prepareStatement("DELETE FROM nxcode_items WHERE codeid = ?"); - while (rs.next()) { - ps2.setInt(1, rs.getInt("id")); - ps2.addBatch(); + public static void cleanNxcodeCoupons(Connection con) throws SQLException { + if (!YamlConfig.config.server.USE_CLEAR_OUTDATED_COUPONS) { + return; + } + + long timeClear = System.currentTimeMillis() - 14 * 24 * 60 * 60 * 1000; + + try (PreparedStatement ps = con.prepareStatement("SELECT * FROM nxcode WHERE expiration <= ?")) { + ps.setLong(1, timeClear); + + try (ResultSet rs = ps.executeQuery()) { + if (!rs.isLast()) { + try (PreparedStatement ps2 = con.prepareStatement("DELETE FROM nxcode_items WHERE codeid = ?")) { + while (rs.next()) { + ps2.setInt(1, rs.getInt("id")); + ps2.addBatch(); + } + ps2.executeBatch(); + } + + try (PreparedStatement ps2 = con.prepareStatement("DELETE FROM nxcode WHERE expiration <= ?")) { + ps2.setLong(1, timeClear); + ps2.executeUpdate(); + } + } } - ps2.executeBatch(); - ps2.close(); - - ps2 = con.prepareStatement("DELETE FROM nxcode WHERE expiration <= ?"); - ps2.setLong(1, timeClear); - ps2.executeUpdate(); - ps2.close(); } - - rs.close(); - ps.close(); } - + private void loadCouponRates(Connection c) throws SQLException { - PreparedStatement ps = c.prepareStatement("SELECT couponid, rate FROM nxcoupons"); - ResultSet rs = ps.executeQuery(); - - while(rs.next()) { - int cid = rs.getInt("couponid"); - int rate = rs.getInt("rate"); - - couponRates.put(cid, rate); + try (PreparedStatement ps = c.prepareStatement("SELECT couponid, rate FROM nxcoupons"); + ResultSet rs = ps.executeQuery()) { + + while (rs.next()) { + int cid = rs.getInt("couponid"); + int rate = rs.getInt("rate"); + + couponRates.put(cid, rate); + } } - - rs.close(); - ps.close(); } - + public List getActiveCoupons() { synchronized (activeCoupons) { return activeCoupons; } } - + public void commitActiveCoupons() { - for(World world: getWorlds()) { - for(MapleCharacter chr: world.getPlayerStorage().getAllCharacters()) { - if(!chr.isLoggedin()) continue; + for (World world : getWorlds()) { + for (MapleCharacter chr : world.getPlayerStorage().getAllCharacters()) { + if (!chr.isLoggedin()) { + continue; + } chr.updateCouponRates(); } } } - + public void toggleCoupon(Integer couponId) { - if(ItemConstants.isRateCoupon(couponId)) { + if (ItemConstants.isRateCoupon(couponId)) { synchronized (activeCoupons) { - if(activeCoupons.contains(couponId)) { + if (activeCoupons.contains(couponId)) { activeCoupons.remove(couponId); - } - else { + } else { activeCoupons.add(couponId); } @@ -629,7 +615,7 @@ public class Server { } } } - + public void updateActiveCoupons() throws SQLException { synchronized (activeCoupons) { activeCoupons.clear(); @@ -638,9 +624,7 @@ public class Server { int weekDay = c.get(Calendar.DAY_OF_WEEK); int hourDay = c.get(Calendar.HOUR_OF_DAY); - Connection con = null; - try { - con = DatabaseConnection.getConnection(); + try (Connection con = DatabaseConnection.getConnection()) { int weekdayMask = (1 << weekDay); PreparedStatement ps = con.prepareStatement("SELECT couponid FROM nxcoupons WHERE (activeday & ?) = ? AND starthour <= ? AND endhour > ?"); @@ -649,29 +633,17 @@ public class Server { ps.setInt(3, hourDay); ps.setInt(4, hourDay); - ResultSet rs = ps.executeQuery(); - while(rs.next()) { - activeCoupons.add(rs.getInt("couponid")); + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + activeCoupons.add(rs.getInt("couponid")); + } } - - rs.close(); - ps.close(); - - con.close(); } catch (SQLException ex) { ex.printStackTrace(); - - try { - if(con != null && !con.isClosed()) { - con.close(); - } - } catch (SQLException ex2) { - ex2.printStackTrace(); - } } } } - + public void runAnnouncePlayerDiseasesSchedule() { List processDiseaseAnnounceClients; disLock.lock(); @@ -681,20 +653,20 @@ public class Server { } finally { disLock.unlock(); } - - while(!processDiseaseAnnounceClients.isEmpty()) { + + while (!processDiseaseAnnounceClients.isEmpty()) { MapleClient c = processDiseaseAnnounceClients.remove(0); MapleCharacter player = c.getPlayer(); - if(player != null && player.isLoggedinWorld()) { + if (player != null && player.isLoggedinWorld()) { player.announceDiseases(); player.collectDiseases(); } } - + disLock.lock(); try { // this is to force the system to wait for at least one complete tick before releasing disease info for the registered clients - while(!registeredDiseaseAnnouncePlayers.isEmpty()) { + while (!registeredDiseaseAnnouncePlayers.isEmpty()) { MapleClient c = registeredDiseaseAnnouncePlayers.remove(0); processDiseaseAnnouncePlayers.add(c); } @@ -702,7 +674,7 @@ public class Server { disLock.unlock(); } } - + public void registerAnnouncePlayerDiseases(MapleClient c) { disLock.lock(); try { @@ -711,7 +683,7 @@ public class Server { disLock.unlock(); } } - + public List> getWorldPlayerRanking(int worldid) { wldRLock.lock(); try { @@ -720,17 +692,17 @@ public class Server { wldRLock.unlock(); } } - + private void installWorldPlayerRanking(int worldid) { List>>> ranking = updatePlayerRankingFromDB(worldid); - if(!ranking.isEmpty()) { + if (!ranking.isEmpty()) { wldWLock.lock(); try { if (!YamlConfig.config.server.USE_WHOLE_SERVER_RANKING) { - for(int i = playerRanking.size(); i <= worldid; i++) { + for (int i = playerRanking.size(); i <= worldid; i++) { playerRanking.add(new ArrayList>(0)); } - + playerRanking.add(worldid, ranking.get(0).getRight()); } else { playerRanking.add(0, ranking.get(0).getRight()); @@ -740,22 +712,22 @@ public class Server { } } } - + private void removeWorldPlayerRanking() { if (!YamlConfig.config.server.USE_WHOLE_SERVER_RANKING) { wldWLock.lock(); try { - if(playerRanking.size() < worlds.size()) { + if (playerRanking.size() < worlds.size()) { return; } - + playerRanking.remove(playerRanking.size() - 1); } finally { wldWLock.unlock(); } } else { List>>> ranking = updatePlayerRankingFromDB(-1 * (this.getWorldsSize() - 2)); // update ranking list - + wldWLock.lock(); try { playerRanking.add(0, ranking.get(0).getRight()); @@ -764,18 +736,18 @@ public class Server { } } } - + public void updateWorldPlayerRanking() { List>>> rankUpdates = updatePlayerRankingFromDB(-1 * (this.getWorldsSize() - 1)); - if(!rankUpdates.isEmpty()) { + if (!rankUpdates.isEmpty()) { wldWLock.lock(); try { if (!YamlConfig.config.server.USE_WHOLE_SERVER_RANKING) { - for(int i = playerRanking.size(); i <= rankUpdates.get(rankUpdates.size() - 1).getLeft(); i++) { + for (int i = playerRanking.size(); i <= rankUpdates.get(rankUpdates.size() - 1).getLeft(); i++) { playerRanking.add(new ArrayList>(0)); } - - for(Pair>> wranks : rankUpdates) { + + for (Pair>> wranks : rankUpdates) { playerRanking.set(wranks.getLeft(), wranks.getRight()); } } else { @@ -786,27 +758,23 @@ public class Server { } } } - + private void initWorldPlayerRanking() { if (YamlConfig.config.server.USE_WHOLE_SERVER_RANKING) { playerRanking.add(new ArrayList>(0)); - } + } updateWorldPlayerRanking(); } - + private static List>>> updatePlayerRankingFromDB(int worldid) { List>>> rankSystem = new ArrayList<>(); List> rankUpdate = new ArrayList<>(0); - - PreparedStatement ps = null; - ResultSet rs = null; - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - + + try (Connection con = DatabaseConnection.getConnection()) { + String worldQuery; if (!YamlConfig.config.server.USE_WHOLE_SERVER_RANKING) { - if(worldid >= 0) { + if (worldid >= 0) { worldQuery = (" AND `characters`.`world` = " + worldid); } else { worldQuery = (" AND `characters`.`world` >= 0 AND `characters`.`world` <= " + -worldid); @@ -814,119 +782,102 @@ public class Server { } else { worldQuery = (" AND `characters`.`world` >= 0 AND `characters`.`world` <= " + Math.abs(worldid)); } - - ps = con.prepareStatement("SELECT `characters`.`name`, `characters`.`level`, `characters`.`world` FROM `characters` LEFT JOIN accounts ON accounts.id = characters.accountid WHERE `characters`.`gm` < 2 AND `accounts`.`banned` = '0'" + worldQuery + " ORDER BY " + (!YamlConfig.config.server.USE_WHOLE_SERVER_RANKING ? "world, " : "") + "level DESC, exp DESC, lastExpGainTime ASC LIMIT 50"); - rs = ps.executeQuery(); - - if (!YamlConfig.config.server.USE_WHOLE_SERVER_RANKING) { - int currentWorld = -1; - while(rs.next()) { - int rsWorld = rs.getInt("world"); - if(currentWorld < rsWorld) { - currentWorld = rsWorld; - rankUpdate = new ArrayList<>(50); - rankSystem.add(new Pair<>(rsWorld, rankUpdate)); - } - rankUpdate.add(new Pair<>(rs.getString("name"), rs.getInt("level"))); - } - } else { - rankUpdate = new ArrayList<>(50); - rankSystem.add(new Pair<>(0, rankUpdate)); - - while(rs.next()) { - rankUpdate.add(new Pair<>(rs.getString("name"), rs.getInt("level"))); + try (PreparedStatement ps = con.prepareStatement("SELECT `characters`.`name`, `characters`.`level`, `characters`.`world` FROM `characters` LEFT JOIN accounts ON accounts.id = characters.accountid WHERE `characters`.`gm` < 2 AND `accounts`.`banned` = '0'" + worldQuery + " ORDER BY " + (!YamlConfig.config.server.USE_WHOLE_SERVER_RANKING ? "world, " : "") + "level DESC, exp DESC, lastExpGainTime ASC LIMIT 50"); + ResultSet rs = ps.executeQuery()) { + + if (!YamlConfig.config.server.USE_WHOLE_SERVER_RANKING) { + int currentWorld = -1; + while (rs.next()) { + int rsWorld = rs.getInt("world"); + if (currentWorld < rsWorld) { + currentWorld = rsWorld; + rankUpdate = new ArrayList<>(50); + rankSystem.add(new Pair<>(rsWorld, rankUpdate)); + } + + rankUpdate.add(new Pair<>(rs.getString("name"), rs.getInt("level"))); + } + } else { + rankUpdate = new ArrayList<>(50); + rankSystem.add(new Pair<>(0, rankUpdate)); + + while (rs.next()) { + rankUpdate.add(new Pair<>(rs.getString("name"), rs.getInt("level"))); + } } } - - ps.close(); - rs.close(); - con.close(); - } catch(SQLException ex) { + } catch (SQLException ex) { ex.printStackTrace(); - } finally { - try { - if(ps != null && !ps.isClosed()) { - ps.close(); - } - if(rs != null && !rs.isClosed()) { - rs.close(); - } - if(con != null && !con.isClosed()) { - con.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } } - + return rankSystem; } - + public void init() { System.out.println("Cosmic v" + ServerConstants.VERSION + " starting up.\r\n"); - - if(YamlConfig.config.server.SHUTDOWNHOOK) { + + if (YamlConfig.config.server.SHUTDOWNHOOK) { Runtime.getRuntime().addShutdownHook(new Thread(shutdown(false))); } if (!DatabaseConnection.initializeConnectionPool()) { throw new IllegalStateException("Failed to initiate a connection to the database"); } - + TimeZone.setDefault(TimeZone.getTimeZone(YamlConfig.config.server.TIMEZONE)); - - Connection c = null; - try { - c = DatabaseConnection.getConnection(); - PreparedStatement ps = c.prepareStatement("UPDATE accounts SET loggedin = 0"); - ps.executeUpdate(); - ps.close(); - ps = c.prepareStatement("UPDATE characters SET HasMerchant = 0"); - ps.executeUpdate(); - ps.close(); - - cleanNxcodeCoupons(c); - loadCouponRates(c); + + try (Connection con = DatabaseConnection.getConnection()) { + try (PreparedStatement ps = con.prepareStatement("UPDATE accounts SET loggedin = 0")) { + ps.executeUpdate(); + } + + try (PreparedStatement ps = con.prepareStatement("UPDATE characters SET HasMerchant = 0")) { + ps.executeUpdate(); + } + + cleanNxcodeCoupons(con); + loadCouponRates(con); updateActiveCoupons(); - - c.close(); } catch (SQLException sqle) { sqle.printStackTrace(); } + applyAllNameChanges(); // -- name changes can be missed by INSTANT_NAME_CHANGE -- applyAllWorldTransfers(); //MaplePet.clearMissingPetsFromDb(); // thanks Optimist for noticing this taking too long to run MapleCashidGenerator.loadExistentCashIdsFromDb(); - + ThreadManager.getInstance().start(); initializeTimelyTasks(); // aggregated method for timely tasks thanks to lxconan - + long timeToTake = System.currentTimeMillis(); SkillFactory.loadAllSkills(); System.out.println("Skills loaded in " + ((System.currentTimeMillis() - timeToTake) / 1000.0) + " seconds"); timeToTake = System.currentTimeMillis(); - + CashItemFactory.getSpecialCashItems(); System.out.println("Items loaded in " + ((System.currentTimeMillis() - timeToTake) / 1000.0) + " seconds"); - - timeToTake = System.currentTimeMillis(); - MapleQuest.loadAllQuest(); - System.out.println("Quest loaded in " + ((System.currentTimeMillis() - timeToTake) / 1000.0) + " seconds\r\n"); - + + timeToTake = System.currentTimeMillis(); + MapleQuest.loadAllQuest(); + System.out.println("Quest loaded in " + ((System.currentTimeMillis() - timeToTake) / 1000.0) + " seconds\r\n"); + NewYearCardRecord.startPendingNewYearCardRequests(); - - if(YamlConfig.config.server.USE_THREAD_TRACKER) ThreadTracker.getInstance().registerThreadTrackerTask(); - + + if (YamlConfig.config.server.USE_THREAD_TRACKER) { + ThreadTracker.getInstance().registerThreadTrackerTask(); + } + try { Integer worldCount = Math.min(GameConstants.WORLD_NAMES.length, YamlConfig.config.server.WORLDS); - + for (int i = 0; i < worldCount; i++) { initWorld(); } initWorldPlayerRanking(); - + MaplePlayerNPCFactory.loadFactoryMetadata(); loadPlayerNpcMapStepFromDb(); } catch (Exception e) { @@ -934,17 +885,17 @@ public class Server { System.out.println("[SEVERE] Syntax error in 'world.ini'."); System.exit(0); } - + System.out.println(); - - if(YamlConfig.config.server.USE_FAMILY_SYSTEM) { + + if (YamlConfig.config.server.USE_FAMILY_SYSTEM) { timeToTake = System.currentTimeMillis(); MapleFamily.loadAllFamilies(); System.out.println("Families loaded in " + ((System.currentTimeMillis() - timeToTake) / 1000.0) + " seconds\r\n"); } - + System.out.println(); - + IoBuffer.setUseDirectBuffer(false); // join IO operations performed by lxconan IoBuffer.setAllocator(new SimpleBufferAllocator()); acceptor = new NioSocketAcceptor(); @@ -956,27 +907,27 @@ public class Server { } catch (IOException ex) { ex.printStackTrace(); } - + System.out.println("Listening on port 8484\r\n\r\n"); - + System.out.println("Cosmic is now online.\r\n"); online = true; - + MapleSkillbookInformationProvider.getInstance(); OpcodeConstants.generateOpcodeNames(); CommandsExecutor.getInstance(); - + for (Channel ch : this.getAllChannels()) { ch.reloadEventScriptManager(); } } - + private void initializeTimelyTasks() { TimerManager tMan = TimerManager.getInstance(); tMan.start(); tMan.register(tMan.purge(), YamlConfig.config.server.PURGING_INTERVAL);//Purging ftw... disconnectIdlesOnLoginTask(); - + long timeLeft = getTimeLeftForNextHour(); tMan.register(new CharacterDiseaseTask(), YamlConfig.config.server.UPDATE_INTERVAL, YamlConfig.config.server.UPDATE_INTERVAL); tMan.register(new ReleaseLockTask(), 2 * 60 * 1000, 2 * 60 * 1000); @@ -989,7 +940,7 @@ public class Server { tMan.register(new DueyFredrickTask(), 60 * 60 * 1000, timeLeft); tMan.register(new InvitationTask(), 30 * 1000, 30 * 1000); tMan.register(new RespawnTask(), YamlConfig.config.server.RESPAWN_INTERVAL, YamlConfig.config.server.RESPAWN_INTERVAL); - + timeLeft = getTimeLeftForNextDay(); MapleExpeditionBossLog.resetBossLogTable(); tMan.register(new BossLogTask(), 24 * 60 * 60 * 1000, timeLeft); @@ -1096,50 +1047,50 @@ public class Server { } return false; } - + public int createGuild(int leaderId, String name) { return MapleGuild.createGuild(leaderId, name); } - + public MapleGuild getGuildByName(String name) { synchronized (guilds) { - for(MapleGuild mg: guilds.values()) { - if(mg.getName().equalsIgnoreCase(name)) { + for (MapleGuild mg : guilds.values()) { + if (mg.getName().equalsIgnoreCase(name)) { return mg; } } - + return null; } } - + public MapleGuild getGuild(int id) { synchronized (guilds) { if (guilds.get(id) != null) { return guilds.get(id); } - + return null; } } public MapleGuild getGuild(int id, int world) { - return getGuild(id, world, null); + return getGuild(id, world, null); } - + public MapleGuild getGuild(int id, int world, MapleCharacter mc) { synchronized (guilds) { MapleGuild g = guilds.get(id); if (g != null) { return g; } - + g = new MapleGuild(id, world); if (g.getId() == -1) { return null; } - - if(mc != null) { + + if (mc != null) { MapleGuildCharacter mgc = g.getMGC(mc.getId()); if (mgc != null) { mc.setMGC(mgc); @@ -1147,15 +1098,15 @@ public class Server { } else { FilePrinter.printError(FilePrinter.GUILD_CHAR_ERROR, "Could not find " + mc.getName() + " when loading guild " + id + "."); } - + g.setOnline(mc.getId(), true, mc.getClient().getChannel()); } - + guilds.put(id, g); return g; } } - + public void setGuildMemberOnline(MapleCharacter mc, boolean bOnline, int channel) { MapleGuild g = getGuild(mc.getGuildId(), mc.getWorld(), mc); g.setOnline(mc.getId(), bOnline, channel); @@ -1177,7 +1128,7 @@ public class Server { } return false; } - + public void resetAllianceGuildPlayersRank(int gId) { guilds.get(gId).resetAllianceGuildPlayersRank(); } @@ -1260,14 +1211,14 @@ public class Server { g.gainGP(amount); } } - + public void guildMessage(int gid, byte[] packet) { guildMessage(gid, packet, -1); } - + public void guildMessage(int gid, byte[] packet, int exception) { MapleGuild g = guilds.get(gid); - if(g != null) { + if (g != null) { g.broadcast(packet, exception); } } @@ -1284,9 +1235,11 @@ public class Server { disbandGuild(mc.getMGC().getGuildId()); } } - + public void deleteGuildCharacter(MapleGuildCharacter mgc) { - if(mgc.getCharacter() != null) setGuildMemberOnline(mgc.getCharacter(), false, (byte) -1); + if (mgc.getCharacter() != null) { + setGuildMemberOnline(mgc.getCharacter(), false, (byte) -1); + } if (mgc.getGuildRank() > 1) { leaveGuild(mgc); } else { @@ -1316,30 +1269,30 @@ public class Server { ch.broadcastGMPacket(packet); } } - + public boolean isGmOnline(int world) { for (Channel ch : getChannelsFromWorld(world)) { - for (MapleCharacter player : ch.getPlayerStorage().getAllCharacters()) { - if (player.isGM()){ - return true; - } - } + for (MapleCharacter player : ch.getPlayerStorage().getAllCharacters()) { + if (player.isGM()) { + return true; + } + } } return false; } - + public void changeFly(Integer accountid, boolean canFly) { - if(canFly) { + if (canFly) { activeFly.add(accountid); } else { activeFly.remove(accountid); } } - + public boolean canFly(Integer accountid) { return activeFly.contains(accountid); } - + public int getCharacterWorld(Integer chrid) { lgnRLock.lock(); try { @@ -1349,7 +1302,7 @@ public class Server { lgnRLock.unlock(); } } - + public boolean haveCharacterEntry(Integer accountid, Integer chrid) { lgnRLock.lock(); try { @@ -1359,7 +1312,7 @@ public class Server { lgnRLock.unlock(); } } - + public short getAccountCharacterCount(Integer accountid) { lgnRLock.lock(); try { @@ -1368,24 +1321,24 @@ public class Server { lgnRLock.unlock(); } } - + public short getAccountWorldCharacterCount(Integer accountid, Integer worldid) { lgnRLock.lock(); try { short count = 0; - - for(Integer chr : accountChars.get(accountid)) { - if(worldChars.get(chr).equals(worldid)) { + + for (Integer chr : accountChars.get(accountid)) { + if (worldChars.get(chr).equals(worldid)) { count++; } } - + return count; } finally { lgnRLock.unlock(); } } - + private Set getAccountCharacterEntries(Integer accountid) { lgnRLock.lock(); try { @@ -1394,73 +1347,83 @@ public class Server { lgnRLock.unlock(); } } - + public void updateCharacterEntry(MapleCharacter chr) { MapleCharacter chrView = chr.generateCharacterEntry(); - + lgnWLock.lock(); try { World wserv = this.getWorld(chrView.getWorld()); - if(wserv != null) wserv.registerAccountCharacterView(chrView.getAccountID(), chrView); - } finally { - lgnWLock.unlock(); - } - } - - public void createCharacterEntry(MapleCharacter chr) { - Integer accountid = chr.getAccountID(), chrid = chr.getId(), world = chr.getWorld(); - - lgnWLock.lock(); - try { - accountCharacterCount.put(accountid, (short)(accountCharacterCount.get(accountid) + 1)); - - Set accChars = accountChars.get(accountid); - accChars.add(chrid); - - worldChars.put(chrid, world); - - MapleCharacter chrView = chr.generateCharacterEntry(); - - World wserv = this.getWorld(chrView.getWorld()); - if(wserv != null) wserv.registerAccountCharacterView(chrView.getAccountID(), chrView); - } finally { - lgnWLock.unlock(); - } - } - - public void deleteCharacterEntry(Integer accountid, Integer chrid) { - lgnWLock.lock(); - try { - accountCharacterCount.put(accountid, (short)(accountCharacterCount.get(accountid) - 1)); - - Set accChars = accountChars.get(accountid); - accChars.remove(chrid); - - Integer world = worldChars.remove(chrid); - if(world != null) { - World wserv = this.getWorld(world); - if(wserv != null) wserv.unregisterAccountCharacterView(accountid, chrid); + if (wserv != null) { + wserv.registerAccountCharacterView(chrView.getAccountID(), chrView); } } finally { lgnWLock.unlock(); } } - + + public void createCharacterEntry(MapleCharacter chr) { + Integer accountid = chr.getAccountID(), chrid = chr.getId(), world = chr.getWorld(); + + lgnWLock.lock(); + try { + accountCharacterCount.put(accountid, (short) (accountCharacterCount.get(accountid) + 1)); + + Set accChars = accountChars.get(accountid); + accChars.add(chrid); + + worldChars.put(chrid, world); + + MapleCharacter chrView = chr.generateCharacterEntry(); + + World wserv = this.getWorld(chrView.getWorld()); + if (wserv != null) { + wserv.registerAccountCharacterView(chrView.getAccountID(), chrView); + } + } finally { + lgnWLock.unlock(); + } + } + + public void deleteCharacterEntry(Integer accountid, Integer chrid) { + lgnWLock.lock(); + try { + accountCharacterCount.put(accountid, (short) (accountCharacterCount.get(accountid) - 1)); + + Set accChars = accountChars.get(accountid); + accChars.remove(chrid); + + Integer world = worldChars.remove(chrid); + if (world != null) { + World wserv = this.getWorld(world); + if (wserv != null) { + wserv.unregisterAccountCharacterView(accountid, chrid); + } + } + } finally { + lgnWLock.unlock(); + } + } + public void transferWorldCharacterEntry(MapleCharacter chr, Integer toWorld) { // used before setting the new worldid on the character object lgnWLock.lock(); try { Integer chrid = chr.getId(), accountid = chr.getAccountID(), world = worldChars.get(chr.getId()); - if(world != null) { + if (world != null) { World wserv = this.getWorld(world); - if(wserv != null) wserv.unregisterAccountCharacterView(accountid, chrid); + if (wserv != null) { + wserv.unregisterAccountCharacterView(accountid, chrid); + } } - + worldChars.put(chrid, toWorld); - + MapleCharacter chrView = chr.generateCharacterEntry(); - + World wserv = this.getWorld(toWorld); - if(wserv != null) wserv.registerAccountCharacterView(chrView.getAccountID(), chrView); + if (wserv != null) { + wserv.registerAccountCharacterView(chrView.getAccountID(), chrView); + } } finally { lgnWLock.unlock(); } @@ -1482,25 +1445,27 @@ public class Server { } } */ - + public Pair>, List>>> loadAccountCharlist(Integer accountId, int visibleWorlds) { List wlist = this.getWorlds(); - if(wlist.size() > visibleWorlds) wlist = wlist.subList(0, visibleWorlds); - + if (wlist.size() > visibleWorlds) { + wlist = wlist.subList(0, visibleWorlds); + } + List>> accChars = new ArrayList<>(wlist.size() + 1); int chrTotal = 0; List lastwchars = null; - + lgnRLock.lock(); try { - for(World w : wlist) { + for (World w : wlist) { List wchars = w.getAccountCharactersView(accountId); - if(wchars == null) { - if(!accountChars.containsKey(accountId)) { + if (wchars == null) { + if (!accountChars.containsKey(accountId)) { accountCharacterCount.put(accountId, (short) 0); accountChars.put(accountId, new HashSet()); // not advisable at all to write on the map on a read-protected environment } // yet it's known there's no problem since no other point in the source does - } else if(!wchars.isEmpty()) { // this action. + } else if (!wchars.isEmpty()) { // this action. lastwchars = wchars; accChars.add(new Pair<>(w.getId(), wchars)); @@ -1510,84 +1475,83 @@ public class Server { } finally { lgnRLock.unlock(); } - + return new Pair<>(new Pair<>(chrTotal, lastwchars), accChars); } - + private static Pair>> loadAccountCharactersViewFromDb(int accId, int wlen) { short characterCount = 0; List> wchars = new ArrayList<>(wlen); - for(int i = 0; i < wlen; i++) wchars.add(i, new LinkedList()); - + for (int i = 0; i < wlen; i++) { + wchars.add(i, new LinkedList()); + } + List chars = new LinkedList<>(); int curWorld = 0; try { List> accEquips = ItemFactory.loadEquippedItems(accId, true, true); Map> accPlayerEquips = new HashMap<>(); - - for(Pair ae : accEquips) { + + for (Pair ae : accEquips) { List playerEquips = accPlayerEquips.get(ae.getRight()); - if(playerEquips == null) { + if (playerEquips == null) { playerEquips = new LinkedList<>(); accPlayerEquips.put(ae.getRight(), playerEquips); } - + playerEquips.add(ae.getLeft()); } - - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("SELECT * FROM characters WHERE accountid = ? ORDER BY world, id")) { + + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT * FROM characters WHERE accountid = ? ORDER BY world, id")) { ps.setInt(1, accId); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { characterCount++; - - int cworld = rs.getByte("world"); - if(cworld >= wlen) continue; - if(cworld > curWorld) { + int cworld = rs.getByte("world"); + if (cworld >= wlen) { + continue; + } + + if (cworld > curWorld) { wchars.add(curWorld, chars); curWorld = cworld; chars = new LinkedList<>(); } - + Integer cid = rs.getInt("id"); chars.add(MapleCharacter.loadCharacterEntryFromDB(rs, accPlayerEquips.get(cid))); } } } - con.close(); - + wchars.add(curWorld, chars); } catch (SQLException sqle) { sqle.printStackTrace(); } - + return new Pair<>(characterCount, wchars); } - + public void loadAllAccountsCharactersView() { - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT id FROM accounts"); - ResultSet rs = ps.executeQuery(); - + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT id FROM accounts"); + ResultSet rs = ps.executeQuery()) { + while (rs.next()) { int accountId = rs.getInt("id"); if (isFirstAccountLogin(accountId)) { loadAccountCharactersView(accountId, 0, 0); } } - - rs.close(); - ps.close(); - con.close(); } catch (SQLException se) { se.printStackTrace(); } } - + private boolean isFirstAccountLogin(Integer accId) { lgnRLock.lock(); try { @@ -1596,52 +1560,55 @@ public class Server { lgnRLock.unlock(); } } - + private static void applyAllNameChanges() { try (Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT * FROM namechanges WHERE completionTime IS NULL")) { - ResultSet rs = ps.executeQuery(); + PreparedStatement ps = con.prepareStatement("SELECT * FROM namechanges WHERE completionTime IS NULL"); + ResultSet rs = ps.executeQuery()) { List> changedNames = new LinkedList>(); //logging only - while(rs.next()) { + while (rs.next()) { con.setAutoCommit(false); int nameChangeId = rs.getInt("id"); int characterId = rs.getInt("characterId"); String oldName = rs.getString("old"); String newName = rs.getString("new"); - boolean success = MapleCharacter.doNameChange(con, characterId, oldName, newName, nameChangeId); - if(!success) con.rollback(); //discard changes - else changedNames.add(new Pair(oldName, newName)); + boolean success = MapleCharacter.doNameChange(con, characterId, oldName, newName, nameChangeId); + if (!success) { + con.rollback(); //discard changes + } else { + changedNames.add(new Pair(oldName, newName)); + } con.setAutoCommit(true); } //log - for(Pair namePair : changedNames) { + for (Pair namePair : changedNames) { FilePrinter.print(FilePrinter.CHANGE_CHARACTER_NAME, "Name change applied : from \"" + namePair.getLeft() + "\" to \"" + namePair.getRight() + "\" at " + Calendar.getInstance().getTime().toString()); } - } catch(SQLException e) { + } catch (SQLException e) { e.printStackTrace(); FilePrinter.printError(FilePrinter.CHANGE_CHARACTER_NAME, e, "Failed to retrieve list of pending name changes."); } } - + private static void applyAllWorldTransfers() { try (Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT * FROM worldtransfers WHERE completionTime IS NULL", - ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) { - ResultSet rs = ps.executeQuery(); + PreparedStatement ps = con.prepareStatement("SELECT * FROM worldtransfers WHERE completionTime IS NULL", + ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + ResultSet rs = ps.executeQuery()) { List removedTransfers = new LinkedList(); - while(rs.next()) { + while (rs.next()) { int nameChangeId = rs.getInt("id"); int characterId = rs.getInt("characterId"); int oldWorld = rs.getInt("from"); int newWorld = rs.getInt("to"); String reason = MapleCharacter.checkWorldTransferEligibility(con, characterId, oldWorld, newWorld); //check if character is still eligible - if(reason != null) { + if (reason != null) { removedTransfers.add(nameChangeId); FilePrinter.print(FilePrinter.WORLD_TRANSFER, "World transfer cancelled : Character ID " + characterId + " at " + Calendar.getInstance().getTime().toString() + ", Reason : " + reason); try (PreparedStatement delPs = con.prepareStatement("DELETE FROM worldtransfers WHERE id = ?")) { delPs.setInt(1, nameChangeId); delPs.executeUpdate(); - } catch(SQLException e) { + } catch (SQLException e) { e.printStackTrace(); FilePrinter.printError(FilePrinter.WORLD_TRANSFER, e, "Failed to delete world transfer for character ID " + characterId); } @@ -1649,36 +1616,41 @@ public class Server { } rs.beforeFirst(); List>> worldTransfers = new LinkedList>>(); //logging only > - while(rs.next()) { + while (rs.next()) { con.setAutoCommit(false); int nameChangeId = rs.getInt("id"); - if(removedTransfers.contains(nameChangeId)) continue; + if (removedTransfers.contains(nameChangeId)) { + continue; + } int characterId = rs.getInt("characterId"); int oldWorld = rs.getInt("from"); int newWorld = rs.getInt("to"); boolean success = MapleCharacter.doWorldTransfer(con, characterId, oldWorld, newWorld, nameChangeId); - if(!success) con.rollback(); - else worldTransfers.add(new Pair>(characterId, new Pair(oldWorld, newWorld))); + if (!success) { + con.rollback(); + } else { + worldTransfers.add(new Pair>(characterId, new Pair(oldWorld, newWorld))); + } con.setAutoCommit(true); } //log - for(Pair> worldTransferPair : worldTransfers) { + for (Pair> worldTransferPair : worldTransfers) { int charId = worldTransferPair.getLeft(); int oldWorld = worldTransferPair.getRight().getLeft(); int newWorld = worldTransferPair.getRight().getRight(); FilePrinter.print(FilePrinter.WORLD_TRANSFER, "World transfer applied : Character ID " + charId + " from World " + oldWorld + " to World " + newWorld + " at " + Calendar.getInstance().getTime().toString()); } - } catch(SQLException e) { + } catch (SQLException e) { e.printStackTrace(); FilePrinter.printError(FilePrinter.WORLD_TRANSFER, e, "Failed to retrieve list of pending world transfers."); } } - + public void loadAccountCharacters(MapleClient c) { Integer accId = c.getAccID(); if (!isFirstAccountLogin(accId)) { Set accWorlds = new HashSet<>(); - + lgnRLock.lock(); try { for (Integer chrid : getAccountCharacterEntries(accId)) { @@ -1687,69 +1659,73 @@ public class Server { } finally { lgnRLock.unlock(); } - + int gmLevel = 0; for (Integer aw : accWorlds) { World wserv = this.getWorld(aw); - + if (wserv != null) { for (MapleCharacter chr : wserv.getAllCharactersView()) { - if (gmLevel < chr.gmLevel()) gmLevel = chr.gmLevel(); + if (gmLevel < chr.gmLevel()) { + gmLevel = chr.gmLevel(); + } } } } - + c.setGMLevel(gmLevel); return; } - + int gmLevel = loadAccountCharactersView(c.getAccID(), 0, 0); c.setGMLevel(gmLevel); } - + private int loadAccountCharactersView(Integer accId, int gmLevel, int fromWorldid) { // returns the maximum gmLevel found List wlist = this.getWorlds(); Pair>> accCharacters = loadAccountCharactersViewFromDb(accId, wlist.size()); - + lgnWLock.lock(); try { List> accChars = accCharacters.getRight(); accountCharacterCount.put(accId, accCharacters.getLeft()); - + Set chars = accountChars.get(accId); - if(chars == null) { + if (chars == null) { chars = new HashSet<>(5); } - + for (int wid = fromWorldid; wid < wlist.size(); wid++) { World w = wlist.get(wid); List wchars = accChars.get(wid); w.loadAccountCharactersView(accId, wchars); - + for (MapleCharacter chr : wchars) { int cid = chr.getId(); - if (gmLevel < chr.gmLevel()) gmLevel = chr.gmLevel(); - + if (gmLevel < chr.gmLevel()) { + gmLevel = chr.gmLevel(); + } + chars.add(cid); worldChars.put(cid, wid); } } - + accountChars.put(accId, chars); } finally { lgnWLock.unlock(); } - + return gmLevel; } - + public void loadAccountStorages(MapleClient c) { int accountId = c.getAccID(); Set accWorlds = new HashSet<>(); lgnWLock.lock(); try { Set chars = accountChars.get(accountId); - + for (Integer cid : chars) { Integer worldid = worldChars.get(cid); if (worldid != null) { @@ -1759,7 +1735,7 @@ public class Server { } finally { lgnWLock.unlock(); } - + List worldList = this.getWorlds(); for (Integer worldid : accWorlds) { if (worldid < worldList.size()) { @@ -1768,14 +1744,14 @@ public class Server { } } } - + private static String getRemoteHost(MapleClient client) { return MapleSessionCoordinator.getSessionRemoteHost(client.getSession()); } - + public void setCharacteridInTransition(MapleClient client, int charId) { String remoteIp = getRemoteHost(client); - + lgnWLock.lock(); try { transitioningChars.put(remoteIp, charId); @@ -1783,14 +1759,14 @@ public class Server { lgnWLock.unlock(); } } - + public boolean validateCharacteridInTransition(MapleClient client, int charId) { if (!YamlConfig.config.server.USE_IP_VALIDATION) { return true; } - + String remoteIp = getRemoteHost(client); - + lgnWLock.lock(); try { Integer cid = transitioningChars.remove(remoteIp); @@ -1799,14 +1775,14 @@ public class Server { lgnWLock.unlock(); } } - + public Integer freeCharacteridInTransition(MapleClient client) { if (!YamlConfig.config.server.USE_IP_VALIDATION) { return null; } - + String remoteIp = getRemoteHost(client); - + lgnWLock.lock(); try { return transitioningChars.remove(remoteIp); @@ -1814,14 +1790,14 @@ public class Server { lgnWLock.unlock(); } } - + public boolean hasCharacteridInTransition(MapleClient client) { if (!YamlConfig.config.server.USE_IP_VALIDATION) { return true; } - + String remoteIp = getRemoteHost(client); - + lgnRLock.lock(); try { return transitioningChars.containsKey(remoteIp); @@ -1829,7 +1805,7 @@ public class Server { lgnRLock.unlock(); } } - + public void registerLoginState(MapleClient c) { srvLock.lock(); try { @@ -1838,7 +1814,7 @@ public class Server { srvLock.unlock(); } } - + public void unregisterLoginState(MapleClient c) { srvLock.lock(); try { @@ -1847,36 +1823,36 @@ public class Server { srvLock.unlock(); } } - + private void disconnectIdlesOnLoginState() { List toDisconnect = new LinkedList<>(); - + srvLock.lock(); try { long timeNow = System.currentTimeMillis(); - - for(Entry mc : inLoginState.entrySet()) { - if(timeNow > mc.getValue()) { + + for (Entry mc : inLoginState.entrySet()) { + if (timeNow > mc.getValue()) { toDisconnect.add(mc.getKey()); } } - - for(MapleClient c : toDisconnect) { + + for (MapleClient c : toDisconnect) { inLoginState.remove(c); } } finally { srvLock.unlock(); } - + for (MapleClient c : toDisconnect) { // thanks Lei for pointing a deadlock issue with srvLock - if(c.isLoggedIn()) { + if (c.isLoggedIn()) { c.disconnect(false, false); } else { MapleSessionCoordinator.getInstance().closeSession(c.getSession(), true); } } } - + private void disconnectIdlesOnLoginTask() { TimerManager.getInstance().register(new Runnable() { @Override @@ -1885,7 +1861,7 @@ public class Server { } }, 300000); } - + public final Runnable shutdown(final boolean restart) {//no player should be online when trying to shutdown! return new Runnable() { @Override @@ -1894,10 +1870,12 @@ public class Server { } }; } - + private synchronized void shutdownInternal(boolean restart) { System.out.println((restart ? "Restarting" : "Shutting down") + " the server!\r\n"); - if (getWorlds() == null) return;//already shutdown + if (getWorlds() == null) { + return;//already shutdown + } for (World w : getWorlds()) { w.shutdown(); } @@ -1923,7 +1901,9 @@ public class Server { List allChannels = getAllChannels(); - if(YamlConfig.config.server.USE_THREAD_TRACKER) ThreadTracker.getInstance().cancelThreadTrackerTask(); + if (YamlConfig.config.server.USE_THREAD_TRACKER) { + ThreadTracker.getInstance().cancelThreadTrackerTask(); + } for (Channel ch : allChannels) { while (!ch.finishedShutdown()) { @@ -1935,13 +1915,13 @@ public class Server { } } } - + resetServerWorlds(); - + ThreadManager.getInstance().stop(); TimerManager.getInstance().purge(); TimerManager.getInstance().stop(); - + System.out.println("Worlds + Channels are offline."); acceptor.unbind(); acceptor = null; diff --git a/src/main/java/net/server/channel/handlers/BBSOperationHandler.java b/src/main/java/net/server/channel/handlers/BBSOperationHandler.java index be4e545506..83682555b0 100644 --- a/src/main/java/net/server/channel/handlers/BBSOperationHandler.java +++ b/src/main/java/net/server/channel/handlers/BBSOperationHandler.java @@ -23,15 +23,16 @@ package net.server.channel.handlers; import client.MapleCharacter; import client.MapleClient; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; import net.AbstractMaplePacketHandler; import tools.DatabaseConnection; import tools.MaplePacketCreator; import tools.data.input.SeekableLittleEndianAccessor; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + public final class BBSOperationHandler extends AbstractMaplePacketHandler { private String correctLength(String in, int maxSize) { @@ -96,17 +97,14 @@ public final class BBSOperationHandler extends AbstractMaplePacketHandler { } private static void listBBSThreads(MapleClient c, int start) { - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("SELECT * FROM bbs_threads WHERE guildid = ? ORDER BY localthreadid DESC", - ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) { - ps.setInt(1, c.getPlayer().getGuildId()); - try (ResultSet rs = ps.executeQuery()) { - c.announce(MaplePacketCreator.BBSThreadList(rs, start)); - } + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT * FROM bbs_threads WHERE guildid = ? ORDER BY localthreadid DESC", + ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) { + + ps.setInt(1, c.getPlayer().getGuildId()); + try (ResultSet rs = ps.executeQuery()) { + c.announce(MaplePacketCreator.BBSThreadList(rs, start)); } - - con.close(); } catch (SQLException se) { se.printStackTrace(); } @@ -116,33 +114,34 @@ public final class BBSOperationHandler extends AbstractMaplePacketHandler { if (c.getPlayer().getGuildId() <= 0) { return; } - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT threadid FROM bbs_threads WHERE guildid = ? AND localthreadid = ?"); - ps.setInt(1, c.getPlayer().getGuildId()); - ps.setInt(2, localthreadid); - ResultSet threadRS = ps.executeQuery(); - if (!threadRS.next()) { - threadRS.close(); - ps.close(); - return; + try (Connection con = DatabaseConnection.getConnection()) { + final int threadid; + try (PreparedStatement ps = con.prepareStatement("SELECT threadid FROM bbs_threads WHERE guildid = ? AND localthreadid = ?")) { + ps.setInt(1, c.getPlayer().getGuildId()); + ps.setInt(2, localthreadid); + + try (ResultSet threadRS = ps.executeQuery()) { + if (!threadRS.next()) { + return; + } + + threadid = threadRS.getInt("threadid"); + } } - int threadid = threadRS.getInt("threadid"); - threadRS.close(); - ps.close(); - ps = con.prepareStatement("INSERT INTO bbs_replies " + "(`threadid`, `postercid`, `timestamp`, `content`) VALUES " + "(?, ?, ?, ?)"); - ps.setInt(1, threadid); - ps.setInt(2, c.getPlayer().getId()); - ps.setLong(3, currentServerTime()); - ps.setString(4, text); - ps.execute(); - ps.close(); - ps = con.prepareStatement("UPDATE bbs_threads SET replycount = replycount + 1 WHERE threadid = ?"); - ps.setInt(1, threadid); - ps.execute(); - ps.close(); - con.close(); + + try (PreparedStatement ps = con.prepareStatement("INSERT INTO bbs_replies " + "(`threadid`, `postercid`, `timestamp`, `content`) VALUES " + "(?, ?, ?, ?)")) { + ps.setInt(1, threadid); + ps.setInt(2, c.getPlayer().getId()); + ps.setLong(3, currentServerTime()); + ps.setString(4, text); + ps.executeUpdate(); + } + + try (PreparedStatement ps = con.prepareStatement("UPDATE bbs_threads SET replycount = replycount + 1 WHERE threadid = ?")) { + ps.setInt(1, threadid); + ps.executeUpdate(); + } + displayThread(c, localthreadid); } catch (SQLException se) { se.printStackTrace(); @@ -154,20 +153,19 @@ public final class BBSOperationHandler extends AbstractMaplePacketHandler { if (chr.getGuildId() < 1) { return; } - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("UPDATE bbs_threads SET `name` = ?, `timestamp` = ?, " + "`icon` = ?, " + "`startpost` = ? WHERE guildid = ? AND localthreadid = ? AND (postercid = ? OR ?)")) { - ps.setString(1, title); - ps.setLong(2, currentServerTime()); - ps.setInt(3, icon); - ps.setString(4, text); - ps.setInt(5, chr.getGuildId()); - ps.setInt(6, localthreadid); - ps.setInt(7, chr.getId()); - ps.setBoolean(8, chr.getGuildRank() < 3); - ps.execute(); - } - con.close(); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE bbs_threads SET `name` = ?, `timestamp` = ?, " + "`icon` = ?, " + "`startpost` = ? WHERE guildid = ? AND localthreadid = ? AND (postercid = ? OR ?)")) { + + ps.setString(1, title); + ps.setLong(2, currentServerTime()); + ps.setInt(3, icon); + ps.setString(4, text); + ps.setInt(5, chr.getGuildId()); + ps.setInt(6, localthreadid); + ps.setInt(7, chr.getId()); + ps.setBoolean(8, chr.getGuildRank() < 3); + ps.execute(); + displayThread(client, localthreadid); } catch (SQLException se) { se.printStackTrace(); @@ -180,29 +178,28 @@ public final class BBSOperationHandler extends AbstractMaplePacketHandler { return; } int nextId = 0; - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps; + try (Connection con = DatabaseConnection.getConnection()) { if (!bNotice) { - ps = con.prepareStatement("SELECT MAX(localthreadid) AS lastLocalId FROM bbs_threads WHERE guildid = ?"); - ps.setInt(1, chr.getGuildId()); - try (ResultSet rs = ps.executeQuery()) { - rs.next(); - nextId = rs.getInt("lastLocalId") + 1; + try (PreparedStatement ps = con.prepareStatement("SELECT MAX(localthreadid) AS lastLocalId FROM bbs_threads WHERE guildid = ?")) { + ps.setInt(1, chr.getGuildId()); + try (ResultSet rs = ps.executeQuery()) { + rs.next(); + nextId = rs.getInt("lastLocalId") + 1; + } } - ps.close(); } - ps = con.prepareStatement("INSERT INTO bbs_threads " + "(`postercid`, `name`, `timestamp`, `icon`, `startpost`, " + "`guildid`, `localthreadid`) " + "VALUES(?, ?, ?, ?, ?, ?, ?)"); - ps.setInt(1, chr.getId()); - ps.setString(2, title); - ps.setLong(3, currentServerTime()); - ps.setInt(4, icon); - ps.setString(5, text); - ps.setInt(6, chr.getGuildId()); - ps.setInt(7, nextId); - ps.execute(); - ps.close(); - con.close(); + + try (PreparedStatement ps = con.prepareStatement("INSERT INTO bbs_threads (`postercid`, `name`, `timestamp`, `icon`, `startpost`, `guildid`, `localthreadid`) VALUES(?, ?, ?, ?, ?, ?, ?)")) { + ps.setInt(1, chr.getId()); + ps.setString(2, title); + ps.setLong(3, currentServerTime()); + ps.setInt(4, icon); + ps.setString(5, text); + ps.setInt(6, chr.getGuildId()); + ps.setInt(7, nextId); + ps.executeUpdate(); + } + displayThread(client, nextId); } catch (SQLException se) { se.printStackTrace(); @@ -215,35 +212,36 @@ public final class BBSOperationHandler extends AbstractMaplePacketHandler { if (mc.getGuildId() <= 0) { return; } - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT threadid, postercid FROM bbs_threads WHERE guildid = ? AND localthreadid = ?"); - ps.setInt(1, mc.getGuildId()); - ps.setInt(2, localthreadid); - ResultSet threadRS = ps.executeQuery(); - if (!threadRS.next()) { - threadRS.close(); - ps.close(); - return; + + try (Connection con = DatabaseConnection.getConnection()) { + + final int threadid; + try (PreparedStatement ps = con.prepareStatement("SELECT threadid, postercid FROM bbs_threads WHERE guildid = ? AND localthreadid = ?")) { + ps.setInt(1, mc.getGuildId()); + ps.setInt(2, localthreadid); + + try (ResultSet threadRS = ps.executeQuery()) { + if (!threadRS.next()) { + return; + } + + if (mc.getId() != threadRS.getInt("postercid") && mc.getGuildRank() > 2) { + return; + } + + threadid = threadRS.getInt("threadid"); + } } - if (mc.getId() != threadRS.getInt("postercid") && mc.getGuildRank() > 2) { - threadRS.close(); - ps.close(); - return; + + try (PreparedStatement ps = con.prepareStatement("DELETE FROM bbs_replies WHERE threadid = ?")) { + ps.setInt(1, threadid); + ps.executeUpdate(); + } + + try (PreparedStatement ps = con.prepareStatement("DELETE FROM bbs_threads WHERE threadid = ?")) { + ps.setInt(1, threadid); + ps.executeUpdate(); } - int threadid = threadRS.getInt("threadid"); - ps.close(); - ps = con.prepareStatement("DELETE FROM bbs_replies WHERE threadid = ?"); - ps.setInt(1, threadid); - ps.execute(); - ps.close(); - ps = con.prepareStatement("DELETE FROM bbs_threads WHERE threadid = ?"); - ps.setInt(1, threadid); - ps.execute(); - threadRS.close(); - ps.close(); - con.close(); } catch (SQLException se) { se.printStackTrace(); } @@ -254,35 +252,36 @@ public final class BBSOperationHandler extends AbstractMaplePacketHandler { if (mc.getGuildId() <= 0) { return; } - int threadid; - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT postercid, threadid FROM bbs_replies WHERE replyid = ?"); - ps.setInt(1, replyid); - ResultSet rs = ps.executeQuery(); - if (!rs.next()) { - rs.close(); - ps.close(); - return; + + final int threadid; + try (Connection con = DatabaseConnection.getConnection()) { + + try (PreparedStatement ps = con.prepareStatement("SELECT postercid, threadid FROM bbs_replies WHERE replyid = ?")) { + ps.setInt(1, replyid); + + try (ResultSet rs = ps.executeQuery()) { + if (!rs.next()) { + return; + } + + if (mc.getId() != rs.getInt("postercid") && mc.getGuildRank() > 2) { + return; + } + + threadid = rs.getInt("threadid"); + } } - if (mc.getId() != rs.getInt("postercid") && mc.getGuildRank() > 2) { - rs.close(); - ps.close(); - return; + + try (PreparedStatement ps = con.prepareStatement("DELETE FROM bbs_replies WHERE replyid = ?")) { + ps.setInt(1, replyid); + ps.executeUpdate(); } - threadid = rs.getInt("threadid"); - rs.close(); - ps.close(); - ps = con.prepareStatement("DELETE FROM bbs_replies WHERE replyid = ?"); - ps.setInt(1, replyid); - ps.execute(); - ps.close(); - ps = con.prepareStatement("UPDATE bbs_threads SET replycount = replycount - 1 WHERE threadid = ?"); - ps.setInt(1, threadid); - ps.execute(); - ps.close(); - con.close(); + + try (PreparedStatement ps = con.prepareStatement("UPDATE bbs_threads SET replycount = replycount - 1 WHERE threadid = ?")) { + ps.setInt(1, threadid); + ps.executeUpdate(); + } + displayThread(client, threadid, false); } catch (SQLException se) { se.printStackTrace(); @@ -298,9 +297,9 @@ public final class BBSOperationHandler extends AbstractMaplePacketHandler { if (mc.getGuildId() <= 0) { return; } - Connection con; - try { - con = DatabaseConnection.getConnection(); + + try (Connection con = DatabaseConnection.getConnection()) { + // TODO clean up this block and use try-with-resources PreparedStatement ps2; try (PreparedStatement ps = con.prepareStatement("SELECT * FROM bbs_threads WHERE guildid = ? AND " + (bIsThreadIdLocal ? "local" : "") + "threadid = ?")) { ps.setInt(1, mc.getGuildId()); @@ -324,8 +323,6 @@ public final class BBSOperationHandler extends AbstractMaplePacketHandler { if (ps2 != null) { ps2.close(); } - - con.close(); } catch (SQLException se) { se.printStackTrace(); } catch (RuntimeException re) {//btw we get this everytime for some reason, but replies work! diff --git a/src/main/java/net/server/channel/handlers/BuddylistModifyHandler.java b/src/main/java/net/server/channel/handlers/BuddylistModifyHandler.java index f7f1d6aedd..b0633904a8 100644 --- a/src/main/java/net/server/channel/handlers/BuddylistModifyHandler.java +++ b/src/main/java/net/server/channel/handlers/BuddylistModifyHandler.java @@ -61,18 +61,19 @@ public class BuddylistModifyHandler extends AbstractMaplePacketHandler { } private CharacterIdNameBuddyCapacity getCharacterIdAndNameFromDatabase(String name) throws SQLException { - Connection con = DatabaseConnection.getConnection(); - CharacterIdNameBuddyCapacity ret; - try (PreparedStatement ps = con.prepareStatement("SELECT id, name, buddyCapacity FROM characters WHERE name LIKE ?")) { + CharacterIdNameBuddyCapacity ret = null; + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT id, name, buddyCapacity FROM characters WHERE name LIKE ?")) { ps.setString(1, name); + try (ResultSet rs = ps.executeQuery()) { - ret = null; if (rs.next()) { ret = new CharacterIdNameBuddyCapacity(rs.getInt("id"), rs.getString("name"), rs.getInt("buddyCapacity")); } } } - con.close(); + return ret; } @@ -110,27 +111,30 @@ public class BuddylistModifyHandler extends AbstractMaplePacketHandler { if (channel != -1) { buddyAddResult = world.requestBuddyAdd(addName, c.getChannel(), player.getId(), player.getName()); } else { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT COUNT(*) as buddyCount FROM buddies WHERE characterid = ? AND pending = 0"); - ps.setInt(1, charWithId.getId()); - ResultSet rs = ps.executeQuery(); - if (!rs.next()) { - throw new RuntimeException("Result set expected"); - } else if (rs.getInt("buddyCount") >= charWithId.getBuddyCapacity()) { - buddyAddResult = BuddyAddResult.BUDDYLIST_FULL; + try (Connection con = DatabaseConnection.getConnection()) { + try (PreparedStatement ps = con.prepareStatement("SELECT COUNT(*) as buddyCount FROM buddies WHERE characterid = ? AND pending = 0")) { + ps.setInt(1, charWithId.getId()); + + try (ResultSet rs = ps.executeQuery()) { + if (!rs.next()) { + throw new RuntimeException("Result set expected"); + } else if (rs.getInt("buddyCount") >= charWithId.getBuddyCapacity()) { + buddyAddResult = BuddyAddResult.BUDDYLIST_FULL; + } + } + } + + try (PreparedStatement ps = con.prepareStatement("SELECT pending FROM buddies WHERE characterid = ? AND buddyid = ?")) { + ps.setInt(1, charWithId.getId()); + ps.setInt(2, player.getId()); + + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + buddyAddResult = BuddyAddResult.ALREADY_ON_LIST; + } + } + } } - rs.close(); - ps.close(); - ps = con.prepareStatement("SELECT pending FROM buddies WHERE characterid = ? AND buddyid = ?"); - ps.setInt(1, charWithId.getId()); - ps.setInt(2, player.getId()); - rs = ps.executeQuery(); - if (rs.next()) { - buddyAddResult = BuddyAddResult.ALREADY_ON_LIST; - } - rs.close(); - ps.close(); - con.close(); } if (buddyAddResult == BuddyAddResult.BUDDYLIST_FULL) { c.announce(MaplePacketCreator.serverNotice(1, "\"" + addName + "\"'s Buddylist is full")); @@ -142,13 +146,12 @@ public class BuddylistModifyHandler extends AbstractMaplePacketHandler { displayChannel = channel; notifyRemoteChannel(c, channel, otherCid, ADDED); } else if (buddyAddResult != BuddyAddResult.ALREADY_ON_LIST && channel == -1) { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("INSERT INTO buddies (characterid, `buddyid`, `pending`) VALUES (?, ?, 1)")) { + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("INSERT INTO buddies (characterid, `buddyid`, `pending`) VALUES (?, ?, 1)")) { ps.setInt(1, charWithId.getId()); ps.setInt(2, player.getId()); ps.executeUpdate(); } - con.close(); } buddylist.put(new BuddylistEntry(charWithId.getName(), group, otherCid, displayChannel, true)); c.announce(MaplePacketCreator.updateBuddylist(buddylist.getBuddies())); @@ -171,16 +174,16 @@ public class BuddylistModifyHandler extends AbstractMaplePacketHandler { String otherName = null; MapleCharacter otherChar = c.getChannelServer().getPlayerStorage().getCharacterById(otherCid); if (otherChar == null) { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("SELECT name FROM characters WHERE id = ?")) { + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT name FROM characters WHERE id = ?")) { ps.setInt(1, otherCid); + try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { otherName = rs.getString("name"); } } } - con.close(); } else { otherName = otherChar.getName(); } diff --git a/src/main/java/net/server/channel/handlers/CouponCodeHandler.java b/src/main/java/net/server/channel/handlers/CouponCodeHandler.java index 2dfb6f86e4..0baa0106e4 100644 --- a/src/main/java/net/server/channel/handlers/CouponCodeHandler.java +++ b/src/main/java/net/server/channel/handlers/CouponCodeHandler.java @@ -23,20 +23,10 @@ */ package net.server.channel.handlers; -import client.MapleClient; import client.MapleCharacter; +import client.MapleClient; import client.inventory.Item; import client.inventory.manipulator.MapleInventoryManipulator; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; import net.AbstractMaplePacketHandler; import net.server.Server; import server.CashShop; @@ -47,6 +37,13 @@ import tools.MaplePacketCreator; import tools.Pair; import tools.data.input.SeekableLittleEndianAccessor; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.*; +import java.util.Map.Entry; + /** * * @author Penguins (Acrylic) @@ -58,34 +55,33 @@ public final class CouponCodeHandler extends AbstractMaplePacketHandler { Map couponItems = new HashMap<>(); Map couponPoints = new HashMap<>(5); - PreparedStatement ps = con.prepareStatement("SELECT * FROM nxcode_items WHERE codeid = ?"); - ps.setInt(1, codeid); + try (PreparedStatement ps = con.prepareStatement("SELECT * FROM nxcode_items WHERE codeid = ?")) { + ps.setInt(1, codeid); - ResultSet rs = ps.executeQuery(); - while (rs.next()) { - int type = rs.getInt("type"), quantity = rs.getInt("quantity"); - if (type < 5) { - Integer i = couponPoints.get(type); - if (i != null) { - couponPoints.put(type, i + quantity); - } else { - couponPoints.put(type, quantity); - } - } else { - int item = rs.getInt("item"); - - Integer i = couponItems.get(item); - if (i != null) { - couponItems.put(item, i + quantity); - } else { - couponItems.put(item, quantity); + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + int type = rs.getInt("type"), quantity = rs.getInt("quantity"); + if (type < 5) { + Integer i = couponPoints.get(type); + if (i != null) { + couponPoints.put(type, i + quantity); + } else { + couponPoints.put(type, quantity); + } + } else { + int item = rs.getInt("item"); + + Integer i = couponItems.get(item); + if (i != null) { + couponItems.put(item, i + quantity); + } else { + couponItems.put(item, quantity); + } + } } } } - rs.close(); - ps.close(); - List>> ret = new LinkedList<>(); if (!couponItems.isEmpty()) { for (Entry e : couponItems.entrySet()) { @@ -122,44 +118,43 @@ public final class CouponCodeHandler extends AbstractMaplePacketHandler { if (!c.attemptCsCoupon()) { return new Pair<>(-5, null); } - - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT * FROM nxcode WHERE code = ?"); - ps.setString(1, code); - - ResultSet rs = ps.executeQuery(); - if (!rs.next()) { - return new Pair<>(-1, null); + + try (Connection con = DatabaseConnection.getConnection()) { + try (PreparedStatement ps = con.prepareStatement("SELECT * FROM nxcode WHERE code = ?")) { + ps.setString(1, code); + + try (ResultSet rs = ps.executeQuery()) { + if (!rs.next()) { + return new Pair<>(-1, null); + } + + if (rs.getString("retriever") != null) { + return new Pair<>(-2, null); + } + + if (rs.getLong("expiration") < Server.getInstance().getCurrentTime()) { + return new Pair<>(-3, null); + } + + final int codeid = rs.getInt("id"); + + ret = getNXCodeItems(chr, con, codeid); + if (ret == null) { + return new Pair<>(-4, null); + } + } + } + + try (PreparedStatement ps = con.prepareStatement("UPDATE nxcode SET retriever = ? WHERE code = ?")) { + ps.setString(1, chr.getName()); + ps.setString(2, code); + ps.executeUpdate(); + } } - - if (rs.getString("retriever") != null) { - return new Pair<>(-2, null); - } - - if (rs.getLong("expiration") < Server.getInstance().getCurrentTime()) { - return new Pair<>(-3, null); - } - - int codeid = rs.getInt("id"); - rs.close(); - ps.close(); - - ret = getNXCodeItems(chr, con, codeid); - if (ret == null) { - return new Pair<>(-4, null); - } - - ps = con.prepareStatement("UPDATE nxcode SET retriever = ? WHERE code = ?"); - ps.setString(1, chr.getName()); - ps.setString(2, code); - ps.executeUpdate(); - - ps.close(); - con.close(); } catch (SQLException ex) { ex.printStackTrace(); } - + c.resetCsCoupon(); return new Pair<>(0, ret); } diff --git a/src/main/java/net/server/channel/handlers/EnterMTSHandler.java b/src/main/java/net/server/channel/handlers/EnterMTSHandler.java index 402e84ead9..6cd496cae0 100644 --- a/src/main/java/net/server/channel/handlers/EnterMTSHandler.java +++ b/src/main/java/net/server/channel/handlers/EnterMTSHandler.java @@ -21,19 +21,12 @@ */ package net.server.channel.handlers; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import config.YamlConfig; import client.MapleCharacter; import client.MapleClient; import client.inventory.Equip; import client.inventory.Item; import client.processor.action.BuybackProcessor; +import config.YamlConfig; import net.AbstractMaplePacketHandler; import net.server.Server; import server.MTSItemInfo; @@ -43,6 +36,13 @@ import tools.DatabaseConnection; import tools.MaplePacketCreator; import tools.data.input.SeekableLittleEndianAccessor; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + public final class EnterMTSHandler extends AbstractMaplePacketHandler { @Override @@ -120,15 +120,75 @@ public final class EnterMTSHandler extends AbstractMaplePacketHandler { c.announce(MaplePacketCreator.showMTSCash(c.getPlayer())); List items = new ArrayList<>(); int pages = 0; - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT * FROM mts_items WHERE tab = 1 AND transfer = 0 ORDER BY id DESC LIMIT 16, 16"); - ResultSet rs = ps.executeQuery(); + try (Connection con = DatabaseConnection.getConnection();) { + try (PreparedStatement ps = con.prepareStatement("SELECT * FROM mts_items WHERE tab = 1 AND transfer = 0 ORDER BY id DESC LIMIT 16, 16"); + ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + if (rs.getInt("type") != 1) { + Item i = new Item(rs.getInt("itemid"), (short) 0, (short) rs.getInt("quantity")); + i.setOwner(rs.getString("owner")); + items.add(new MTSItemInfo(i, rs.getInt("price") + 100 + (int) (rs.getInt("price") * 0.1), rs.getInt("id"), rs.getInt("seller"), rs.getString("sellername"), rs.getString("sell_ends"))); + } else { + Equip equip = new Equip(rs.getInt("itemid"), (byte) rs.getInt("position"), -1); + equip.setOwner(rs.getString("owner")); + equip.setQuantity((short) 1); + equip.setAcc((short) rs.getInt("acc")); + equip.setAvoid((short) rs.getInt("avoid")); + equip.setDex((short) rs.getInt("dex")); + equip.setHands((short) rs.getInt("hands")); + equip.setHp((short) rs.getInt("hp")); + equip.setInt((short) rs.getInt("int")); + equip.setJump((short) rs.getInt("jump")); + equip.setVicious((short) rs.getInt("vicious")); + equip.setFlag((short) rs.getInt("flag")); + equip.setLuk((short) rs.getInt("luk")); + equip.setMatk((short) rs.getInt("matk")); + equip.setMdef((short) rs.getInt("mdef")); + equip.setMp((short) rs.getInt("mp")); + equip.setSpeed((short) rs.getInt("speed")); + equip.setStr((short) rs.getInt("str")); + equip.setWatk((short) rs.getInt("watk")); + equip.setWdef((short) rs.getInt("wdef")); + equip.setUpgradeSlots((byte) rs.getInt("upgradeslots")); + equip.setLevel((byte) rs.getInt("level")); + equip.setItemLevel(rs.getByte("itemlevel")); + equip.setItemExp(rs.getInt("itemexp")); + equip.setRingId(rs.getInt("ringid")); + equip.setExpiration(rs.getLong("expiration")); + equip.setGiftFrom(rs.getString("giftFrom")); + + items.add(new MTSItemInfo((Item) equip, rs.getInt("price") + 100 + (int) (rs.getInt("price") * 0.1), rs.getInt("id"), rs.getInt("seller"), rs.getString("sellername"), rs.getString("sell_ends"))); + } + } + } + + try (PreparedStatement ps = con.prepareStatement("SELECT COUNT(*) FROM mts_items"); + ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + pages = (int) Math.ceil(rs.getInt(1) / 16); + } + } + } catch (SQLException e) { + e.printStackTrace(); + } + c.announce(MaplePacketCreator.sendMTS(items, 1, 0, 0, pages)); + c.announce(MaplePacketCreator.transferInventory(getTransfer(chr.getId()))); + c.announce(MaplePacketCreator.notYetSoldInv(getNotYetSold(chr.getId()))); + } + } + + private List getNotYetSold(int cid) { + List items = new ArrayList<>(); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT * FROM mts_items WHERE seller = ? AND transfer = 0 ORDER BY id DESC")) { + ps.setInt(1, cid); + + try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { if (rs.getInt("type") != 1) { Item i = new Item(rs.getInt("itemid"), (short) 0, (short) rs.getInt("quantity")); i.setOwner(rs.getString("owner")); - items.add(new MTSItemInfo(i, rs.getInt("price") + 100 + (int) (rs.getInt("price") * 0.1), rs.getInt("id"), rs.getInt("seller"), rs.getString("sellername"), rs.getString("sell_ends"))); + items.add(new MTSItemInfo((Item) i, rs.getInt("price"), rs.getInt("id"), rs.getInt("seller"), rs.getString("sellername"), rs.getString("sell_ends"))); } else { Equip equip = new Equip(rs.getInt("itemid"), (byte) rs.getInt("position"), -1); equip.setOwner(rs.getString("owner")); @@ -141,7 +201,6 @@ public final class EnterMTSHandler extends AbstractMaplePacketHandler { equip.setInt((short) rs.getInt("int")); equip.setJump((short) rs.getInt("jump")); equip.setVicious((short) rs.getInt("vicious")); - equip.setFlag((short) rs.getInt("flag")); equip.setLuk((short) rs.getInt("luk")); equip.setMatk((short) rs.getInt("matk")); equip.setMdef((short) rs.getInt("mdef")); @@ -155,78 +214,13 @@ public final class EnterMTSHandler extends AbstractMaplePacketHandler { equip.setItemLevel(rs.getByte("itemlevel")); equip.setItemExp(rs.getInt("itemexp")); equip.setRingId(rs.getInt("ringid")); + equip.setFlag((short) rs.getInt("flag")); equip.setExpiration(rs.getLong("expiration")); equip.setGiftFrom(rs.getString("giftFrom")); - - items.add(new MTSItemInfo((Item) equip, rs.getInt("price") + 100 + (int) (rs.getInt("price") * 0.1), rs.getInt("id"), rs.getInt("seller"), rs.getString("sellername"), rs.getString("sell_ends"))); - } - } - rs.close(); - ps.close(); - - ps = con.prepareStatement("SELECT COUNT(*) FROM mts_items"); - rs = ps.executeQuery(); - if (rs.next()) { - pages = (int) Math.ceil(rs.getInt(1) / 16); - } - rs.close(); - ps.close(); - con.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - c.announce(MaplePacketCreator.sendMTS(items, 1, 0, 0, pages)); - c.announce(MaplePacketCreator.transferInventory(getTransfer(chr.getId()))); - c.announce(MaplePacketCreator.notYetSoldInv(getNotYetSold(chr.getId()))); - } - } - - private List getNotYetSold(int cid) { - List items = new ArrayList<>(); - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("SELECT * FROM mts_items WHERE seller = ? AND transfer = 0 ORDER BY id DESC")) { - ps.setInt(1, cid); - try (ResultSet rs = ps.executeQuery()) { - while (rs.next()) { - if (rs.getInt("type") != 1) { - Item i = new Item(rs.getInt("itemid"), (short) 0, (short) rs.getInt("quantity")); - i.setOwner(rs.getString("owner")); - items.add(new MTSItemInfo((Item) i, rs.getInt("price"), rs.getInt("id"), rs.getInt("seller"), rs.getString("sellername"), rs.getString("sell_ends"))); - } else { - Equip equip = new Equip(rs.getInt("itemid"), (byte) rs.getInt("position"), -1); - equip.setOwner(rs.getString("owner")); - equip.setQuantity((short) 1); - equip.setAcc((short) rs.getInt("acc")); - equip.setAvoid((short) rs.getInt("avoid")); - equip.setDex((short) rs.getInt("dex")); - equip.setHands((short) rs.getInt("hands")); - equip.setHp((short) rs.getInt("hp")); - equip.setInt((short) rs.getInt("int")); - equip.setJump((short) rs.getInt("jump")); - equip.setVicious((short) rs.getInt("vicious")); - equip.setLuk((short) rs.getInt("luk")); - equip.setMatk((short) rs.getInt("matk")); - equip.setMdef((short) rs.getInt("mdef")); - equip.setMp((short) rs.getInt("mp")); - equip.setSpeed((short) rs.getInt("speed")); - equip.setStr((short) rs.getInt("str")); - equip.setWatk((short) rs.getInt("watk")); - equip.setWdef((short) rs.getInt("wdef")); - equip.setUpgradeSlots((byte) rs.getInt("upgradeslots")); - equip.setLevel((byte) rs.getInt("level")); - equip.setItemLevel(rs.getByte("itemlevel")); - equip.setItemExp(rs.getInt("itemexp")); - equip.setRingId(rs.getInt("ringid")); - equip.setFlag((short) rs.getInt("flag")); - equip.setExpiration(rs.getLong("expiration")); - equip.setGiftFrom(rs.getString("giftFrom")); - items.add(new MTSItemInfo((Item) equip, rs.getInt("price"), rs.getInt("id"), rs.getInt("seller"), rs.getString("sellername"), rs.getString("sell_ends"))); - } + items.add(new MTSItemInfo((Item) equip, rs.getInt("price"), rs.getInt("id"), rs.getInt("seller"), rs.getString("sellername"), rs.getString("sell_ends"))); } } } - con.close(); } catch (SQLException e) { e.printStackTrace(); } @@ -235,50 +229,48 @@ public final class EnterMTSHandler extends AbstractMaplePacketHandler { private List getTransfer(int cid) { List items = new ArrayList<>(); - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("SELECT * FROM mts_items WHERE transfer = 1 AND seller = ? ORDER BY id DESC")) { - ps.setInt(1, cid); - try (ResultSet rs = ps.executeQuery()) { - while (rs.next()) { - if (rs.getInt("type") != 1) { - Item i = new Item(rs.getInt("itemid"), (short) 0, (short) rs.getInt("quantity")); - i.setOwner(rs.getString("owner")); - items.add(new MTSItemInfo((Item) i, rs.getInt("price"), rs.getInt("id"), rs.getInt("seller"), rs.getString("sellername"), rs.getString("sell_ends"))); - } else { - Equip equip = new Equip(rs.getInt("itemid"), (byte) rs.getInt("position"), -1); - equip.setOwner(rs.getString("owner")); - equip.setQuantity((short) 1); - equip.setAcc((short) rs.getInt("acc")); - equip.setAvoid((short) rs.getInt("avoid")); - equip.setDex((short) rs.getInt("dex")); - equip.setHands((short) rs.getInt("hands")); - equip.setHp((short) rs.getInt("hp")); - equip.setInt((short) rs.getInt("int")); - equip.setJump((short) rs.getInt("jump")); - equip.setVicious((short) rs.getInt("vicious")); - equip.setLuk((short) rs.getInt("luk")); - equip.setMatk((short) rs.getInt("matk")); - equip.setMdef((short) rs.getInt("mdef")); - equip.setMp((short) rs.getInt("mp")); - equip.setSpeed((short) rs.getInt("speed")); - equip.setStr((short) rs.getInt("str")); - equip.setWatk((short) rs.getInt("watk")); - equip.setWdef((short) rs.getInt("wdef")); - equip.setUpgradeSlots((byte) rs.getInt("upgradeslots")); - equip.setLevel((byte) rs.getInt("level")); - equip.setItemLevel(rs.getByte("itemlevel")); - equip.setItemExp(rs.getInt("itemexp")); - equip.setRingId(rs.getInt("ringid")); - equip.setFlag((short) rs.getInt("flag")); - equip.setExpiration(rs.getLong("expiration")); - equip.setGiftFrom(rs.getString("giftFrom")); - items.add(new MTSItemInfo((Item) equip, rs.getInt("price"), rs.getInt("id"), rs.getInt("seller"), rs.getString("sellername"), rs.getString("sell_ends"))); - } + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT * FROM mts_items WHERE transfer = 1 AND seller = ? ORDER BY id DESC")) { + ps.setInt(1, cid); + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + if (rs.getInt("type") != 1) { + Item i = new Item(rs.getInt("itemid"), (short) 0, (short) rs.getInt("quantity")); + i.setOwner(rs.getString("owner")); + items.add(new MTSItemInfo((Item) i, rs.getInt("price"), rs.getInt("id"), rs.getInt("seller"), rs.getString("sellername"), rs.getString("sell_ends"))); + } else { + Equip equip = new Equip(rs.getInt("itemid"), (byte) rs.getInt("position"), -1); + equip.setOwner(rs.getString("owner")); + equip.setQuantity((short) 1); + equip.setAcc((short) rs.getInt("acc")); + equip.setAvoid((short) rs.getInt("avoid")); + equip.setDex((short) rs.getInt("dex")); + equip.setHands((short) rs.getInt("hands")); + equip.setHp((short) rs.getInt("hp")); + equip.setInt((short) rs.getInt("int")); + equip.setJump((short) rs.getInt("jump")); + equip.setVicious((short) rs.getInt("vicious")); + equip.setLuk((short) rs.getInt("luk")); + equip.setMatk((short) rs.getInt("matk")); + equip.setMdef((short) rs.getInt("mdef")); + equip.setMp((short) rs.getInt("mp")); + equip.setSpeed((short) rs.getInt("speed")); + equip.setStr((short) rs.getInt("str")); + equip.setWatk((short) rs.getInt("watk")); + equip.setWdef((short) rs.getInt("wdef")); + equip.setUpgradeSlots((byte) rs.getInt("upgradeslots")); + equip.setLevel((byte) rs.getInt("level")); + equip.setItemLevel(rs.getByte("itemlevel")); + equip.setItemExp(rs.getInt("itemexp")); + equip.setRingId(rs.getInt("ringid")); + equip.setFlag((short) rs.getInt("flag")); + equip.setExpiration(rs.getLong("expiration")); + equip.setGiftFrom(rs.getString("giftFrom")); + items.add(new MTSItemInfo((Item) equip, rs.getInt("price"), rs.getInt("id"), rs.getInt("seller"), rs.getString("sellername"), rs.getString("sell_ends"))); } } } - con.close(); } catch (SQLException e) { e.printStackTrace(); } diff --git a/src/main/java/net/server/channel/handlers/NoteActionHandler.java b/src/main/java/net/server/channel/handlers/NoteActionHandler.java index b5d1d45c18..9c7689bc38 100644 --- a/src/main/java/net/server/channel/handlers/NoteActionHandler.java +++ b/src/main/java/net/server/channel/handlers/NoteActionHandler.java @@ -21,16 +21,16 @@ */ package net.server.channel.handlers; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - +import client.MapleClient; import net.AbstractMaplePacketHandler; import tools.DatabaseConnection; import tools.MaplePacketCreator; import tools.data.input.SeekableLittleEndianAccessor; -import client.MapleClient; + import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; public final class NoteActionHandler extends AbstractMaplePacketHandler { @Override @@ -40,11 +40,12 @@ public final class NoteActionHandler extends AbstractMaplePacketHandler { String charname = slea.readMapleAsciiString(); String message = slea.readMapleAsciiString(); try { - if (c.getPlayer().getCashShop().isOpened()) + if (c.getPlayer().getCashShop().isOpened()) { c.announce(MaplePacketCreator.showCashInventory(c)); - - c.getPlayer().sendNote(charname, message, (byte) 1); - c.getPlayer().getCashShop().decreaseNotes(); + } + + c.getPlayer().sendNote(charname, message, (byte) 1); + c.getPlayer().getCashShop().decreaseNotes(); } catch (SQLException e) { e.printStackTrace(); } @@ -56,21 +57,22 @@ public final class NoteActionHandler extends AbstractMaplePacketHandler { for (int i = 0; i < num; i++) { int id = slea.readInt(); slea.readByte(); //Fame, but we read it from the database :) - PreparedStatement ps; - try { - Connection con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("SELECT `fame` FROM notes WHERE id=? AND deleted=0"); - ps.setInt(1, id); - ResultSet rs = ps.executeQuery(); - if (rs.next()) - fame += rs.getInt("fame"); - rs.close(); - ps = con.prepareStatement("UPDATE notes SET `deleted` = 1 WHERE id = ?"); - ps.setInt(1, id); - ps.executeUpdate(); - ps.close(); - con.close(); + try (Connection con = DatabaseConnection.getConnection()) { + try (PreparedStatement ps = con.prepareStatement("SELECT `fame` FROM notes WHERE id=? AND deleted=0")) { + ps.setInt(1, id); + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + fame += rs.getInt("fame"); + } + + } + } + + try (PreparedStatement ps = con.prepareStatement("UPDATE notes SET `deleted` = 1 WHERE id = ?")) { + ps.setInt(1, id); + ps.executeUpdate(); + } } catch (SQLException e) { e.printStackTrace(); } diff --git a/src/main/java/net/server/channel/handlers/PlayerLoggedinHandler.java b/src/main/java/net/server/channel/handlers/PlayerLoggedinHandler.java index c9137b68b3..593369416a 100644 --- a/src/main/java/net/server/channel/handlers/PlayerLoggedinHandler.java +++ b/src/main/java/net/server/channel/handlers/PlayerLoggedinHandler.java @@ -21,60 +21,41 @@ */ package net.server.channel.handlers; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map.Entry; - +import client.*; +import client.inventory.*; +import client.keybind.MapleKeyBinding; import config.YamlConfig; +import constants.game.GameConstants; +import constants.game.ScriptableNPCConstants; import net.AbstractMaplePacketHandler; import net.server.PlayerBuffValueHolder; import net.server.Server; import net.server.channel.Channel; import net.server.channel.CharacterIdChannelPair; +import net.server.coordinator.session.MapleSessionCoordinator; +import net.server.coordinator.world.MapleEventRecallCoordinator; import net.server.guild.MapleAlliance; import net.server.guild.MapleGuild; import net.server.world.MaplePartyCharacter; import net.server.world.PartyOperation; import net.server.world.World; +import org.apache.mina.core.session.IoSession; +import scripting.event.EventInstanceManager; +import server.life.MobSkill; import tools.DatabaseConnection; import tools.FilePrinter; import tools.MaplePacketCreator; import tools.Pair; import tools.data.input.SeekableLittleEndianAccessor; -import client.BuddyList; -import client.BuddylistEntry; -import client.CharacterNameAndId; -import client.MapleCharacter; -import client.MapleClient; -import client.MapleDisease; -import client.MapleFamily; -import client.MapleFamilyEntry; -import client.keybind.MapleKeyBinding; -import client.MapleMount; -import client.SkillFactory; -import client.inventory.Equip; -import client.inventory.Item; -import client.inventory.MapleInventory; -import client.inventory.MapleInventoryType; -import client.inventory.MaplePet; -import constants.game.GameConstants; -import constants.game.ScriptableNPCConstants; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import net.server.coordinator.world.MapleEventRecallCoordinator; -import net.server.coordinator.session.MapleSessionCoordinator; -import org.apache.mina.core.session.IoSession; -import server.life.MobSkill; -import scripting.event.EventInstanceManager; import tools.packets.Wedding; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.*; +import java.util.Map.Entry; + public final class PlayerLoggedinHandler extends AbstractMaplePacketHandler { private static Set attemptingLoginAccounts = new HashSet<>(); @@ -443,48 +424,22 @@ public final class PlayerLoggedinHandler extends AbstractMaplePacketHandler { } private static void showDueyNotification(MapleClient c, MapleCharacter player) { - Connection con = null; - PreparedStatement ps = null; - PreparedStatement pss = null; - ResultSet rs = null; - try { - con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("SELECT Type FROM dueypackages WHERE ReceiverId = ? AND Checked = 1 ORDER BY Type DESC"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT Type FROM dueypackages WHERE ReceiverId = ? AND Checked = 1 ORDER BY Type DESC")) { ps.setInt(1, player.getId()); - rs = ps.executeQuery(); - if (rs.next()) { - try { - Connection con2 = DatabaseConnection.getConnection(); - pss = con2.prepareStatement("UPDATE dueypackages SET Checked = 0 WHERE ReceiverId = ?"); - pss.setInt(1, player.getId()); - pss.executeUpdate(); - pss.close(); - con2.close(); - - c.announce(MaplePacketCreator.sendDueyParcelNotification(rs.getInt("Type") == 1)); - } catch (SQLException e) { - e.printStackTrace(); + + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + try (PreparedStatement ps2 = con.prepareStatement("UPDATE dueypackages SET Checked = 0 WHERE ReceiverId = ?")){ + ps2.setInt(1, player.getId()); + ps2.executeUpdate(); + + c.announce(MaplePacketCreator.sendDueyParcelNotification(rs.getInt("Type") == 1)); + } } } } catch (SQLException e) { e.printStackTrace(); - } finally { - try { - if (rs != null) { - rs.close(); - } - if (pss != null) { - pss.close(); - } - if (ps != null) { - ps.close(); - } - if (con != null) { - con.close(); - } - } catch (SQLException ex) { - ex.printStackTrace(); - } } } diff --git a/src/main/java/net/server/channel/handlers/ReportHandler.java b/src/main/java/net/server/channel/handlers/ReportHandler.java index 17a28596d4..2cc21962f1 100644 --- a/src/main/java/net/server/channel/handlers/ReportHandler.java +++ b/src/main/java/net/server/channel/handlers/ReportHandler.java @@ -21,19 +21,19 @@ */ package net.server.channel.handlers; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.util.Calendar; - +import client.MapleCharacter; +import client.MapleClient; import net.AbstractMaplePacketHandler; import net.server.Server; import tools.DatabaseConnection; import tools.MaplePacketCreator; import tools.data.input.SeekableLittleEndianAccessor; -import client.MapleCharacter; -import client.MapleClient; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.Calendar; /* * @@ -84,10 +84,8 @@ public final class ReportHandler extends AbstractMaplePacketHandler { public void addReport(int reporterid, int victimid, int reason, String description, String chatlog) { Calendar calendar = Calendar.getInstance(); Timestamp currentTimestamp = new java.sql.Timestamp(calendar.getTime().getTime()); - Connection con; - try { - con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("INSERT INTO reports (`reporttime`, `reporterid`, `victimid`, `reason`, `chatlog`, `description`) VALUES (?, ?, ?, ?, ?, ?)"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("INSERT INTO reports (`reporttime`, `reporterid`, `victimid`, `reason`, `chatlog`, `description`) VALUES (?, ?, ?, ?, ?, ?)")) { ps.setString(1, currentTimestamp.toGMTString().toString()); ps.setInt(2, reporterid); ps.setInt(3, victimid); @@ -96,8 +94,6 @@ public final class ReportHandler extends AbstractMaplePacketHandler { ps.setString(6, description); ps.addBatch(); ps.executeBatch(); - ps.close(); - con.close(); } catch (SQLException ex) { ex.printStackTrace(); } diff --git a/src/main/java/net/server/channel/handlers/RingActionHandler.java b/src/main/java/net/server/channel/handlers/RingActionHandler.java index ab1db998fc..08a063ea9b 100644 --- a/src/main/java/net/server/channel/handlers/RingActionHandler.java +++ b/src/main/java/net/server/channel/handlers/RingActionHandler.java @@ -21,13 +21,8 @@ */ package net.server.channel.handlers; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -import client.MapleClient; import client.MapleCharacter; +import client.MapleClient; import client.MapleRing; import client.inventory.Equip; import client.inventory.Item; @@ -35,16 +30,21 @@ import client.inventory.MapleInventoryType; import client.inventory.manipulator.MapleInventoryManipulator; import client.processor.npc.DueyProcessor; import net.AbstractMaplePacketHandler; -import net.server.world.World; import net.server.channel.Channel; -import server.MapleItemInformationProvider; +import net.server.world.World; import scripting.event.EventInstanceManager; +import server.MapleItemInformationProvider; import tools.DatabaseConnection; -import tools.Pair; import tools.MaplePacketCreator; +import tools.Pair; import tools.data.input.SeekableLittleEndianAccessor; import tools.packets.Wedding; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + /** * @author Jvlaple * @author Ronan - major overhaul on Ring handling mechanics @@ -131,47 +131,41 @@ public final class RingActionHandler extends AbstractMaplePacketHandler { } private static void eraseEngagementOffline(int characterId) { - try { - Connection con = DatabaseConnection.getConnection(); + try (Connection con = DatabaseConnection.getConnection()) { eraseEngagementOffline(characterId, con); - con.close(); - } catch(SQLException sqle) { + } catch (SQLException sqle) { sqle.printStackTrace(); } } private static void eraseEngagementOffline(int characterId, Connection con) throws SQLException { - PreparedStatement ps = con.prepareStatement("UPDATE characters SET marriageItemId=-1, partnerId=-1 WHERE id=?"); - ps.setInt(1, characterId); - ps.executeUpdate(); - - ps.close(); + try (PreparedStatement ps = con.prepareStatement("UPDATE characters SET marriageItemId=-1, partnerId=-1 WHERE id=?")) { + ps.setInt(1, characterId); + ps.executeUpdate(); + } } private static void breakEngagementOffline(int characterId) { - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT marriageItemId FROM characters WHERE id=?"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT marriageItemId FROM characters WHERE id=?")) { ps.setInt(1, characterId); - ResultSet rs = ps.executeQuery(); - if (rs.next()) { - int marriageItemId = rs.getInt("marriageItemId"); - - if (marriageItemId > 0) { - PreparedStatement ps2 = con.prepareStatement("UPDATE inventoryitems SET expiration=0 WHERE itemid=? AND characterid=?"); - ps2.setInt(1, marriageItemId); - ps2.setInt(2, characterId); - - ps2.executeUpdate(); - ps2.close(); + + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + int marriageItemId = rs.getInt("marriageItemId"); + + if (marriageItemId > 0) { + try (PreparedStatement ps2 = con.prepareStatement("UPDATE inventoryitems SET expiration=0 WHERE itemid=? AND characterid=?")) { + ps2.setInt(1, marriageItemId); + ps2.setInt(2, characterId); + + ps2.executeUpdate(); + } + } } } - rs.close(); - ps.close(); - + eraseEngagementOffline(characterId, con); - - con.close(); } catch (SQLException ex) { System.out.println("Error updating offline breakup " + ex.getMessage()); } diff --git a/src/main/java/net/server/channel/handlers/WhisperHandler.java b/src/main/java/net/server/channel/handlers/WhisperHandler.java index 816bf60d5f..6799f2524d 100644 --- a/src/main/java/net/server/channel/handlers/WhisperHandler.java +++ b/src/main/java/net/server/channel/handlers/WhisperHandler.java @@ -21,10 +21,9 @@ */ package net.server.channel.handlers; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - +import client.MapleCharacter; +import client.MapleClient; +import client.autoban.AutobanFactory; import config.YamlConfig; import net.AbstractMaplePacketHandler; import net.server.world.World; @@ -33,10 +32,11 @@ import tools.FilePrinter; import tools.LogHelper; import tools.MaplePacketCreator; import tools.data.input.SeekableLittleEndianAccessor; -import client.MapleCharacter; -import client.MapleClient; -import client.autoban.AutobanFactory; + import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; /** * @@ -101,20 +101,18 @@ public final class WhisperHandler extends AbstractMaplePacketHandler { c.announce(MaplePacketCreator.getFindReply(victim.getName(), victim.getMap().getId(), 1)); } } else if (c.getPlayer().isGM()) { // not found - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT gm FROM characters WHERE name = ?"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT gm FROM characters WHERE name = ?")) { ps.setString(1, recipient); - ResultSet rs = ps.executeQuery(); - if (rs.next()) { - if (rs.getInt("gm") >= c.getPlayer().gmLevel()) { - c.announce(MaplePacketCreator.getWhisperReply(recipient, (byte) 0)); - return; + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + if (rs.getInt("gm") >= c.getPlayer().gmLevel()) { + c.announce(MaplePacketCreator.getWhisperReply(recipient, (byte) 0)); + return; + } } } - rs.close(); - ps.close(); - con.close(); + byte channel = (byte) (c.getWorldServer().find(recipient) - 1); if (channel > -1) { c.announce(MaplePacketCreator.getFindReply(recipient, channel, 3)); diff --git a/src/main/java/net/server/coordinator/session/MapleSessionCoordinator.java b/src/main/java/net/server/coordinator/session/MapleSessionCoordinator.java index 9f2f171552..2cb7d3880c 100644 --- a/src/main/java/net/server/coordinator/session/MapleSessionCoordinator.java +++ b/src/main/java/net/server/coordinator/session/MapleSessionCoordinator.java @@ -19,14 +19,13 @@ */ package net.server.coordinator.session; -import net.server.coordinator.login.LoginStorage; import client.MapleCharacter; import client.MapleClient; import config.YamlConfig; - import net.server.Server; import net.server.audit.locks.MonitoredLockType; import net.server.audit.locks.factory.MonitoredReentrantLockFactory; +import net.server.coordinator.login.LoginStorage; import org.apache.mina.core.session.IoSession; import tools.DatabaseConnection; @@ -34,16 +33,8 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.LinkedList; -import java.util.List; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; @@ -148,10 +139,9 @@ public class MapleSessionCoordinator { } private static boolean associateHwidAccountIfAbsent(String remoteHwid, int accountId) { - try { - Connection con = DatabaseConnection.getConnection(); + try (Connection con = DatabaseConnection.getConnection()) { int hwidCount = 0; - + try (PreparedStatement ps = con.prepareStatement("SELECT SQL_CACHE hwid FROM hwidaccounts WHERE accountid = ?")) { ps.setInt(1, accountId); try (ResultSet rs = ps.executeQuery()) { @@ -160,7 +150,7 @@ public class MapleSessionCoordinator { if (rsHwid.contentEquals(remoteHwid)) { return false; } - + hwidCount++; } } @@ -169,8 +159,6 @@ public class MapleSessionCoordinator { registerAccessAccount(con, remoteHwid, accountId); return true; } - } finally { - con.close(); } } catch (SQLException ex) { ex.printStackTrace(); @@ -180,12 +168,12 @@ public class MapleSessionCoordinator { } private static boolean attemptAccessAccount(String nibbleHwid, int accountId, boolean routineCheck) { - try { - Connection con = DatabaseConnection.getConnection(); + try (Connection con = DatabaseConnection.getConnection()) { int hwidCount = 0; try (PreparedStatement ps = con.prepareStatement("SELECT SQL_CACHE * FROM hwidaccounts WHERE accountid = ?")) { ps.setInt(1, accountId); + try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { String rsHwid = rs.getString("hwid"); @@ -207,8 +195,6 @@ public class MapleSessionCoordinator { if (hwidCount < YamlConfig.config.server.MAX_ALLOWED_ACCOUNT_HWID) { return true; } - } finally { - con.close(); } } catch (SQLException ex) { ex.printStackTrace(); @@ -563,17 +549,13 @@ public class MapleSessionCoordinator { } public void runUpdateHwidHistory() { - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("DELETE FROM hwidaccounts WHERE expiresat < CURRENT_TIMESTAMP")) { - ps.execute(); - } finally { - con.close(); - } + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("DELETE FROM hwidaccounts WHERE expiresat < CURRENT_TIMESTAMP")) { + ps.executeUpdate(); } catch (SQLException ex) { ex.printStackTrace(); } - + long timeNow = Server.getInstance().getCurrentTime(); List toRemove = new LinkedList<>(); for (Entry cht : cachedHostTimeout.entrySet()) { @@ -581,7 +563,7 @@ public class MapleSessionCoordinator { toRemove.add(cht.getKey()); } } - + if (!toRemove.isEmpty()) { for (String s : toRemove) { cachedHostHwids.remove(s); diff --git a/src/main/java/net/server/guild/MapleAlliance.java b/src/main/java/net/server/guild/MapleAlliance.java index 56a44597a4..3aa405f2e7 100644 --- a/src/main/java/net/server/guild/MapleAlliance.java +++ b/src/main/java/net/server/guild/MapleAlliance.java @@ -21,13 +21,6 @@ */ package net.server.guild; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.ResultSet; -import java.util.LinkedList; -import java.util.List; - import client.MapleCharacter; import client.MapleClient; import net.server.Server; @@ -39,19 +32,25 @@ import net.server.world.MaplePartyCharacter; import tools.DatabaseConnection; import tools.MaplePacketCreator; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.LinkedList; +import java.util.List; + /** - * * @author XoticStory * @author Ronan */ public class MapleAlliance { final private List guilds = new LinkedList<>(); - + private int allianceId = -1; private int capacity; private String name; private String notice = ""; - private String rankTitles[] = new String[5]; + private String[] rankTitles = new String[5]; public MapleAlliance(String name, int id) { this.name = name; @@ -61,36 +60,33 @@ public class MapleAlliance { rankTitles[i] = ranks[i]; } } - + public static boolean canBeUsedAllianceName(String name) { if (name.contains(" ") || name.length() > 12) { return false; } - try { - ResultSet rs; - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("SELECT name FROM alliance WHERE name = ?")) { - ps.setString(1, name); - rs = ps.executeQuery(); + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT name FROM alliance WHERE name = ?")) { + ps.setString(1, name); + + try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { - ps.close(); - rs.close(); return false; } } - rs.close(); - con.close(); + return true; } catch (SQLException e) { e.printStackTrace(); return false; } } - + private static List getPartyGuildMasters(MapleParty party) { List mcl = new LinkedList<>(); - for(MaplePartyCharacter mpc: party.getMembers()) { + for (MaplePartyCharacter mpc : party.getMembers()) { MapleCharacter chr = mpc.getPlayer(); if (chr != null) { MapleCharacter lchr = party.getLeader().getPlayer(); @@ -100,9 +96,9 @@ public class MapleAlliance { } } - if(!mcl.isEmpty() && !mcl.get(0).isPartyLeader()) { - for(int i = 1; i < mcl.size(); i++) { - if(mcl.get(i).isPartyLeader()) { + if (!mcl.isEmpty() && !mcl.get(0).isPartyLeader()) { + for (int i = 1; i < mcl.size(); i++) { + if (mcl.get(i).isPartyLeader()) { MapleCharacter temp = mcl.get(0); mcl.set(0, mcl.get(i)); mcl.set(i, temp); @@ -115,19 +111,24 @@ public class MapleAlliance { public static MapleAlliance createAlliance(MapleParty party, String name) { List guildMasters = getPartyGuildMasters(party); - if(guildMasters.size() != 2) return null; + if (guildMasters.size() != 2) { + return null; + } List guilds = new LinkedList<>(); - for(MapleCharacter mc: guildMasters) guilds.add(mc.getGuildId()); + for (MapleCharacter mc : guildMasters) { + guilds.add(mc.getGuildId()); + } MapleAlliance alliance = MapleAlliance.createAllianceOnDb(guilds, name); - if(alliance != null) { + if (alliance != null) { alliance.setCapacity(guilds.size()); - for(Integer g: guilds) + for (Integer g : guilds) { alliance.addGuild(g); - + } + int id = alliance.getId(); try { - for(int i = 0; i < guildMasters.size(); i++) { + for (int i = 0; i < guildMasters.size(); i++) { Server.getInstance().setGuildAllianceId(guilds.get(i), id); Server.getInstance().resetAllianceGuildPlayersRank(guilds.get(i)); @@ -138,7 +139,7 @@ public class MapleAlliance { } Server.getInstance().addAlliance(id, alliance); - + int worldid = guildMasters.get(0).getWorld(); Server.getInstance().allianceMessage(id, MaplePacketCreator.updateAllianceInfo(alliance, worldid), -1, -1); Server.getInstance().allianceMessage(id, MaplePacketCreator.getGuildAlliances(alliance, worldid), -1, -1); // thanks Vcoc for noticing guilds from other alliances being visually stacked here due to this not being updated @@ -150,40 +151,34 @@ public class MapleAlliance { return alliance; } - + public static MapleAlliance createAllianceOnDb(List guilds, String name) { // will create an alliance, where the first guild listed is the leader and the alliance name MUST BE already checked for unicity. - + int id = -1; - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("INSERT INTO `alliance` (`name`) VALUES (?)", PreparedStatement.RETURN_GENERATED_KEYS); - - ps.setString(1, name); - ps.executeUpdate(); - try (ResultSet rs = ps.getGeneratedKeys()) { - rs.next(); - id = rs.getInt(1); - } - - for(int i = 0; i < guilds.size(); i++) { - int guild = guilds.get(i); - - ps = con.prepareStatement("INSERT INTO `allianceguilds` (`allianceid`, `guildid`) VALUES (?, ?)"); - ps.setInt(1, id); - ps.setInt(2, guild); + try (Connection con = DatabaseConnection.getConnection()) { + try (PreparedStatement ps = con.prepareStatement("INSERT INTO `alliance` (`name`) VALUES (?)", PreparedStatement.RETURN_GENERATED_KEYS)) { + ps.setString(1, name); ps.executeUpdate(); - ps.close(); + try (ResultSet rs = ps.getGeneratedKeys()) { + rs.next(); + id = rs.getInt(1); + } + } + + for (int guild : guilds) { + try (PreparedStatement ps = con.prepareStatement("INSERT INTO `allianceguilds` (`allianceid`, `guildid`) VALUES (?, ?)")) { + ps.setInt(1, id); + ps.setInt(2, guild); + ps.executeUpdate(); + } } - - ps.close(); - con.close(); } catch (SQLException e) { e.printStackTrace(); return null; } - - return (new MapleAlliance(name, id)); + + return new MapleAlliance(name, id); } public static MapleAlliance loadAlliance(int id) { @@ -191,183 +186,144 @@ public class MapleAlliance { return null; } MapleAlliance alliance = new MapleAlliance(null, -1); - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT * FROM alliance WHERE id = ?"); - ps.setInt(1, id); - ResultSet rs = ps.executeQuery(); - if (!rs.next()) { - rs.close(); - ps.close(); - con.close(); - return null; + try (Connection con = DatabaseConnection.getConnection()) { + + try (PreparedStatement ps = con.prepareStatement("SELECT * FROM alliance WHERE id = ?")) { + ps.setInt(1, id); + + try (ResultSet rs = ps.executeQuery()) { + if (!rs.next()) { + return null; + } + + alliance.allianceId = id; + alliance.capacity = rs.getInt("capacity"); + alliance.name = rs.getString("name"); + alliance.notice = rs.getString("notice"); + + String[] ranks = new String[5]; + ranks[0] = rs.getString("rank1"); + ranks[1] = rs.getString("rank2"); + ranks[2] = rs.getString("rank3"); + ranks[3] = rs.getString("rank4"); + ranks[4] = rs.getString("rank5"); + alliance.rankTitles = ranks; + } } - alliance.allianceId = id; - alliance.capacity = rs.getInt("capacity"); - alliance.name = rs.getString("name"); - alliance.notice = rs.getString("notice"); - - String ranks[] = new String[5]; - ranks[0] = rs.getString("rank1"); - ranks[1] = rs.getString("rank2"); - ranks[2] = rs.getString("rank3"); - ranks[3] = rs.getString("rank4"); - ranks[4] = rs.getString("rank5"); - alliance.rankTitles = ranks; - - ps.close(); - rs.close(); - - ps = con.prepareStatement("SELECT guildid FROM allianceguilds WHERE allianceid = ?"); - ps.setInt(1, id); - rs = ps.executeQuery(); - - while(rs.next()) { - alliance.addGuild(rs.getInt("guildid")); + + try (PreparedStatement ps = con.prepareStatement("SELECT guildid FROM allianceguilds WHERE allianceid = ?")) { + ps.setInt(1, id); + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + alliance.addGuild(rs.getInt("guildid")); + } + } } - - ps.close(); - rs.close(); - con.close(); } catch (SQLException e) { e.printStackTrace(); } + return alliance; } public void saveToDB() { - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("UPDATE `alliance` SET capacity = ?, notice = ?, rank1 = ?, rank2 = ?, rank3 = ?, rank4 = ?, rank5 = ? WHERE id = ?"); - ps.setInt(1, this.capacity); - ps.setString(2, this.notice); - - ps.setString(3, this.rankTitles[0]); - ps.setString(4, this.rankTitles[1]); - ps.setString(5, this.rankTitles[2]); - ps.setString(6, this.rankTitles[3]); - ps.setString(7, this.rankTitles[4]); - - ps.setInt(8, this.allianceId); - ps.executeUpdate(); - ps.close(); - - ps = con.prepareStatement("DELETE FROM `allianceguilds` WHERE allianceid = ?"); - ps.setInt(1, this.allianceId); - ps.executeUpdate(); - ps.close(); - - for(int i = 0; i < guilds.size(); i++) { - int guild = guilds.get(i); - - ps = con.prepareStatement("INSERT INTO `allianceguilds` (`allianceid`, `guildid`) VALUES (?, ?)"); - ps.setInt(1, this.allianceId); - ps.setInt(2, guild); + try (Connection con = DatabaseConnection.getConnection()) { + + try (PreparedStatement ps = con.prepareStatement("UPDATE `alliance` SET capacity = ?, notice = ?, rank1 = ?, rank2 = ?, rank3 = ?, rank4 = ?, rank5 = ? WHERE id = ?")) { + ps.setInt(1, this.capacity); + ps.setString(2, this.notice); + + ps.setString(3, this.rankTitles[0]); + ps.setString(4, this.rankTitles[1]); + ps.setString(5, this.rankTitles[2]); + ps.setString(6, this.rankTitles[3]); + ps.setString(7, this.rankTitles[4]); + + ps.setInt(8, this.allianceId); ps.executeUpdate(); - ps.close(); } - - con.close(); + + try (PreparedStatement ps = con.prepareStatement("DELETE FROM `allianceguilds` WHERE allianceid = ?")) { + ps.setInt(1, this.allianceId); + ps.executeUpdate(); + } + + for (int guild : guilds) { + try (PreparedStatement ps = con.prepareStatement("INSERT INTO `allianceguilds` (`allianceid`, `guildid`) VALUES (?, ?)")) { + ps.setInt(1, this.allianceId); + ps.setInt(2, guild); + ps.executeUpdate(); + } + } } catch (SQLException e) { e.printStackTrace(); } } - + public static void disbandAlliance(int allianceId) { - PreparedStatement ps = null; - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - - ps = con.prepareStatement("DELETE FROM `alliance` WHERE id = ?"); - ps.setInt(1, allianceId); - ps.executeUpdate(); - ps.close(); - - ps = con.prepareStatement("DELETE FROM `allianceguilds` WHERE allianceid = ?"); - ps.setInt(1, allianceId); - ps.executeUpdate(); - ps.close(); - - con.close(); + try (Connection con = DatabaseConnection.getConnection()) { + + try (PreparedStatement ps = con.prepareStatement("DELETE FROM `alliance` WHERE id = ?")) { + ps.setInt(1, allianceId); + ps.executeUpdate(); + } + + try (PreparedStatement ps = con.prepareStatement("DELETE FROM `allianceguilds` WHERE allianceid = ?")) { + ps.setInt(1, allianceId); + ps.executeUpdate(); + } + Server.getInstance().allianceMessage(allianceId, MaplePacketCreator.disbandAlliance(allianceId), -1, -1); Server.getInstance().disbandAlliance(allianceId); } catch (SQLException sqle) { sqle.printStackTrace(); - } finally { - try { - if (ps != null && !ps.isClosed()) { - ps.close(); - } - if (con != null && !con.isClosed()) { - con.close(); - } - } catch (SQLException ex) { - ex.printStackTrace(); - } } } - + private static void removeGuildFromAllianceOnDb(int guildId) { - PreparedStatement ps = null; - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - - ps = con.prepareStatement("DELETE FROM `allianceguilds` WHERE guildid = ?"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("DELETE FROM `allianceguilds` WHERE guildid = ?")) { ps.setInt(1, guildId); ps.executeUpdate(); - ps.close(); - - con.close(); } catch (SQLException sqle) { sqle.printStackTrace(); - } finally { - try { - if (ps != null && !ps.isClosed()) { - ps.close(); - } - if (con != null && !con.isClosed()) { - con.close(); - } - } catch (SQLException ex) { - ex.printStackTrace(); - } } } - + public static boolean removeGuildFromAlliance(int allianceId, int guildId, int worldId) { Server srv = Server.getInstance(); MapleAlliance alliance = srv.getAlliance(allianceId); - + if (alliance.getLeader().getGuildId() == guildId) { return false; } - + srv.allianceMessage(alliance.getId(), MaplePacketCreator.removeGuildFromAlliance(alliance, guildId, worldId), -1, -1); srv.removeGuildFromAlliance(alliance.getId(), guildId); removeGuildFromAllianceOnDb(guildId); - + srv.allianceMessage(alliance.getId(), MaplePacketCreator.getGuildAlliances(alliance, worldId), -1, -1); srv.allianceMessage(alliance.getId(), MaplePacketCreator.allianceNotice(alliance.getId(), alliance.getNotice()), -1, -1); srv.guildMessage(guildId, MaplePacketCreator.disbandAlliance(alliance.getId())); - + alliance.dropMessage("[" + srv.getGuild(guildId, worldId).getName() + "] guild has left the union."); return true; } - + public void updateAlliancePackets(MapleCharacter chr) { if (allianceId > 0) { this.broadcastMessage(MaplePacketCreator.updateAllianceInfo(this, chr.getWorld())); this.broadcastMessage(MaplePacketCreator.allianceNotice(this.getId(), this.getNotice())); } } - + public boolean removeGuild(int gid) { synchronized (guilds) { int index = getGuildIndex(gid); - if(index == -1) return false; - + if (index == -1) { + return false; + } + guilds.remove(index); return true; } @@ -375,8 +331,10 @@ public class MapleAlliance { public boolean addGuild(int gid) { synchronized (guilds) { - if(guilds.size() == capacity || getGuildIndex(gid) > -1) return false; - + if (guilds.size() == capacity || getGuildIndex(gid) > -1) { + return false; + } + guilds.add(gid); return true; } @@ -392,7 +350,7 @@ public class MapleAlliance { return -1; } } - + public void setRankTitle(String[] ranks) { rankTitles = ranks; } @@ -400,9 +358,9 @@ public class MapleAlliance { public String getRankTitle(int rank) { return rankTitles[rank - 1]; } - + public List getGuilds() { - synchronized(guilds) { + synchronized (guilds) { List guilds_ = new LinkedList<>(); for (int guild : guilds) { if (guild != -1) { @@ -412,7 +370,7 @@ public class MapleAlliance { return guilds_; } } - + public String getAllianceNotice() { return notice; } @@ -420,7 +378,7 @@ public class MapleAlliance { public String getNotice() { return notice; } - + public void setNotice(String notice) { this.notice = notice; } @@ -432,11 +390,11 @@ public class MapleAlliance { public void setCapacity(int newCapacity) { this.capacity = newCapacity; } - + public int getCapacity() { return this.capacity; } - + public int getId() { return allianceId; } @@ -444,40 +402,42 @@ public class MapleAlliance { public String getName() { return name; } - + public MapleGuildCharacter getLeader() { - synchronized(guilds) { - for(Integer gId: guilds) { + synchronized (guilds) { + for (Integer gId : guilds) { MapleGuild guild = Server.getInstance().getGuild(gId); MapleGuildCharacter mgc = guild.getMGC(guild.getLeaderId()); - if(mgc.getAllianceRank() == 1) return mgc; + if (mgc.getAllianceRank() == 1) { + return mgc; + } } return null; } } - + public void dropMessage(String message) { dropMessage(5, message); } - + public void dropMessage(int type, String message) { - synchronized(guilds) { - for(Integer gId: guilds) { + synchronized (guilds) { + for (Integer gId : guilds) { MapleGuild guild = Server.getInstance().getGuild(gId); guild.dropMessage(type, message); } } } - + public void broadcastMessage(byte[] packet) { Server.getInstance().allianceMessage(allianceId, packet, -1, -1); } - + public static void sendInvitation(MapleClient c, String targetGuildName, int allianceId) { MapleGuild mg = Server.getInstance().getGuildByName(targetGuildName); - if(mg == null) { + if (mg == null) { c.getPlayer().dropMessage(5, "The entered guild does not exist."); } else { if (mg.getAllianceId() > 0) { @@ -496,28 +456,28 @@ public class MapleAlliance { } } } - + public static boolean answerInvitation(int targetId, String targetGuildName, int allianceId, boolean answer) { MapleInviteResult res = MapleInviteCoordinator.answerInvite(InviteType.ALLIANCE, targetId, allianceId, answer); - + String msg; MapleCharacter sender = res.from; switch (res.result) { case ACCEPTED: return true; - + case DENIED: msg = "[" + targetGuildName + "] guild has denied your guild alliance invitation."; break; - + default: msg = "The guild alliance request has not been accepted, since the invitation expired."; } - + if (sender != null) { sender.dropMessage(5, msg); } - + return false; } } diff --git a/src/main/java/net/server/guild/MapleGuild.java b/src/main/java/net/server/guild/MapleGuild.java index 73d7edc7e8..398c808e46 100644 --- a/src/main/java/net/server/guild/MapleGuild.java +++ b/src/main/java/net/server/guild/MapleGuild.java @@ -24,44 +24,35 @@ package net.server.guild; import client.MapleCharacter; import client.MapleClient; import config.YamlConfig; +import net.server.PlayerStorage; +import net.server.Server; +import net.server.audit.locks.MonitoredLockType; +import net.server.audit.locks.factory.MonitoredReentrantLockFactory; +import net.server.channel.Channel; +import net.server.coordinator.matchchecker.MapleMatchCheckerCoordinator; +import net.server.coordinator.world.MapleInviteCoordinator; +import net.server.coordinator.world.MapleInviteCoordinator.InviteType; +import net.server.coordinator.world.MapleInviteCoordinator.MapleInviteResult; +import tools.DatabaseConnection; +import tools.MaplePacketCreator; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.HashSet; -import java.util.Set; - +import java.util.*; import java.util.concurrent.locks.Lock; -import net.server.audit.locks.factory.MonitoredReentrantLockFactory; - -import net.server.PlayerStorage; -import net.server.Server; -import net.server.channel.Channel; -import tools.DatabaseConnection; -import tools.MaplePacketCreator; -import net.server.audit.locks.MonitoredLockType; -import net.server.coordinator.world.MapleInviteCoordinator; -import net.server.coordinator.world.MapleInviteCoordinator.InviteType; -import net.server.coordinator.world.MapleInviteCoordinator.MapleInviteResult; -import net.server.coordinator.matchchecker.MapleMatchCheckerCoordinator; public class MapleGuild { - + private enum BCOp { NONE, DISBAND, EMBLEMCHANGE } - + private final List members; private final Lock membersLock = MonitoredReentrantLockFactory.createLock(MonitoredLockType.GUILD, true); - - private String rankTitles[] = new String[5]; // 1 = master, 2 = jr, 5 = lowest member + + private String[] rankTitles = new String[5]; // 1 = master, 2 = jr, 5 = lowest member private String name, notice; private int id, gp, logo, logoColor, leader, capacity, logoBG, logoBGColor, signature, allianceId; private int world; @@ -71,49 +62,44 @@ public class MapleGuild { public MapleGuild(int guildid, int world) { this.world = world; members = new ArrayList<>(); - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT * FROM guilds WHERE guildid = " + guildid); - ResultSet rs = ps.executeQuery(); - if (!rs.next()) { - id = -1; - ps.close(); - rs.close(); - return; + + try (Connection con = DatabaseConnection.getConnection()) { + try (PreparedStatement ps = con.prepareStatement("SELECT * FROM guilds WHERE guildid = " + guildid); + ResultSet rs = ps.executeQuery()) { + if (!rs.next()) { + id = -1; + return; + } + id = guildid; + name = rs.getString("name"); + gp = rs.getInt("GP"); + logo = rs.getInt("logo"); + logoColor = rs.getInt("logoColor"); + logoBG = rs.getInt("logoBG"); + logoBGColor = rs.getInt("logoBGColor"); + capacity = rs.getInt("capacity"); + for (int i = 1; i <= 5; i++) { + rankTitles[i - 1] = rs.getString("rank" + i + "title"); + } + leader = rs.getInt("leader"); + notice = rs.getString("notice"); + signature = rs.getInt("signature"); + allianceId = rs.getInt("allianceId"); } - id = guildid; - name = rs.getString("name"); - gp = rs.getInt("GP"); - logo = rs.getInt("logo"); - logoColor = rs.getInt("logoColor"); - logoBG = rs.getInt("logoBG"); - logoBGColor = rs.getInt("logoBGColor"); - capacity = rs.getInt("capacity"); - for (int i = 1; i <= 5; i++) { - rankTitles[i - 1] = rs.getString("rank" + i + "title"); + + try (PreparedStatement ps = con.prepareStatement("SELECT id, name, level, job, guildrank, allianceRank FROM characters WHERE guildid = ? ORDER BY guildrank ASC, name ASC")) { + ps.setInt(1, guildid); + + try (ResultSet rs = ps.executeQuery()) { + if (!rs.next()) { + return; + } + + do { + members.add(new MapleGuildCharacter(null, rs.getInt("id"), rs.getInt("level"), rs.getString("name"), (byte) -1, world, rs.getInt("job"), rs.getInt("guildrank"), guildid, false, rs.getInt("allianceRank"))); + } while (rs.next()); + } } - leader = rs.getInt("leader"); - notice = rs.getString("notice"); - signature = rs.getInt("signature"); - allianceId = rs.getInt("allianceId"); - ps.close(); - rs.close(); - ps = con.prepareStatement("SELECT id, name, level, job, guildrank, allianceRank FROM characters WHERE guildid = ? ORDER BY guildrank ASC, name ASC"); - ps.setInt(1, guildid); - rs = ps.executeQuery(); - if (!rs.next()) { - rs.close(); - ps.close(); - return; - } - do { - members.add(new MapleGuildCharacter(null, rs.getInt("id"), rs.getInt("level"), rs.getString("name"), (byte) -1, world, rs.getInt("job"), rs.getInt("guildrank"), guildid, false, rs.getInt("allianceRank"))); - } while (rs.next()); - - ps.close(); - rs.close(); - con.close(); } catch (SQLException se) { se.printStackTrace(); System.out.println("Unable to read guild information from sql: " + se); @@ -137,32 +123,33 @@ public class MapleGuild { } } } - + membersLock.lock(); try { for (MapleGuildCharacter mgc : members) { if (!mgc.isOnline()) { continue; } - + List chl; synchronized (notifications) { chl = notifications.get(mgc.getChannel()); } - if (chl != null) chl.add(mgc.getId()); + if (chl != null) { + chl.add(mgc.getId()); + } //Unable to connect to Channel... error was here } } finally { membersLock.unlock(); } - + bDirty = false; } public void writeToDB(boolean bDisband) { - try { - Connection con = DatabaseConnection.getConnection(); - + try (Connection con = DatabaseConnection.getConnection()) { + if (!bDisband) { StringBuilder builder = new StringBuilder(); builder.append("UPDATE guilds SET GP = ?, logo = ?, logoColor = ?, logoBG = ?, logoBGColor = ?, "); @@ -182,18 +169,19 @@ public class MapleGuild { ps.setInt(11, capacity); ps.setString(12, notice); ps.setInt(13, this.id); - ps.execute(); + ps.executeUpdate(); } } else { - PreparedStatement ps = con.prepareStatement("UPDATE characters SET guildid = 0, guildrank = 5 WHERE guildid = ?"); - ps.setInt(1, this.id); - ps.execute(); - ps.close(); - ps = con.prepareStatement("DELETE FROM guilds WHERE guildid = ?"); - ps.setInt(1, this.id); - ps.execute(); - ps.close(); - + try (PreparedStatement ps = con.prepareStatement("UPDATE characters SET guildid = 0, guildrank = 5 WHERE guildid = ?")) { + ps.setInt(1, this.id); + ps.executeUpdate(); + } + + try (PreparedStatement ps = con.prepareStatement("DELETE FROM guilds WHERE guildid = ?")) { + ps.setInt(1, this.id); + ps.executeUpdate(); + } + membersLock.lock(); try { this.broadcast(MaplePacketCreator.guildDisband(this.id)); @@ -201,8 +189,6 @@ public class MapleGuild { membersLock.unlock(); } } - - con.close(); } catch (SQLException se) { se.printStackTrace(); } @@ -215,7 +201,7 @@ public class MapleGuild { public int getLeaderId() { return leader; } - + public int setLeaderId(int charId) { return leader = charId; } @@ -286,40 +272,46 @@ public class MapleGuild { public void broadcastNameChanged() { PlayerStorage ps = Server.getInstance().getWorld(world).getPlayerStorage(); - + for (MapleGuildCharacter mgc : getMembers()) { MapleCharacter chr = ps.getCharacterById(mgc.getId()); - if (chr == null || !chr.isLoggedinWorld()) continue; + if (chr == null || !chr.isLoggedinWorld()) { + continue; + } byte[] packet = MaplePacketCreator.guildNameChanged(chr.getId(), this.getName()); chr.getMap().broadcastMessage(chr, packet); } } - + public void broadcastEmblemChanged() { PlayerStorage ps = Server.getInstance().getWorld(world).getPlayerStorage(); - + for (MapleGuildCharacter mgc : getMembers()) { MapleCharacter chr = ps.getCharacterById(mgc.getId()); - if (chr == null || !chr.isLoggedinWorld()) continue; - + if (chr == null || !chr.isLoggedinWorld()) { + continue; + } + byte[] packet = MaplePacketCreator.guildMarkChanged(chr.getId(), this); chr.getMap().broadcastMessage(chr, packet); } } - + public void broadcastInfoChanged() { PlayerStorage ps = Server.getInstance().getWorld(world).getPlayerStorage(); - + for (MapleGuildCharacter mgc : getMembers()) { MapleCharacter chr = ps.getCharacterById(mgc.getId()); - if (chr == null || !chr.isLoggedinWorld()) continue; - + if (chr == null || !chr.isLoggedinWorld()) { + continue; + } + byte[] packet = MaplePacketCreator.showGuildInfo(chr); chr.announce(packet); } } - + public void broadcast(final byte[] packet) { broadcast(packet, -1, BCOp.NONE); } @@ -372,16 +364,16 @@ public class MapleGuild { membersLock.unlock(); } } - + public void dropMessage(String message) { dropMessage(5, message); } - + public void dropMessage(int type, String message) { membersLock.lock(); try { for (MapleGuildCharacter mgc : members) { - if(mgc.getCharacter() != null) { + if (mgc.getCharacter() != null) { mgc.getCharacter().dropMessage(type, message); } } @@ -389,7 +381,7 @@ public class MapleGuild { membersLock.unlock(); } } - + public void broadcastMessage(byte[] packet) { Server.getInstance().guildMessage(id, packet); } @@ -431,41 +423,40 @@ public class MapleGuild { } public static int createGuild(int leaderId, String name) { - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT guildid FROM guilds WHERE name = ?"); - ps.setString(1, name); - ResultSet rs = ps.executeQuery(); - if (rs.next()) { - ps.close(); - rs.close(); - return 0; + try (Connection con = DatabaseConnection.getConnection()) { + + try (PreparedStatement ps = con.prepareStatement("SELECT guildid FROM guilds WHERE name = ?")) { + ps.setString(1, name); + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + return 0; + } + } } - ps.close(); - rs.close(); - - ps = con.prepareStatement("INSERT INTO guilds (`leader`, `name`, `signature`) VALUES (?, ?, ?)"); - ps.setInt(1, leaderId); - ps.setString(2, name); - ps.setInt(3, (int) System.currentTimeMillis()); - ps.execute(); - ps.close(); - - ps = con.prepareStatement("SELECT guildid FROM guilds WHERE leader = ?"); - ps.setInt(1, leaderId); - rs = ps.executeQuery(); - rs.next(); - int guildId = rs.getInt("guildid"); - rs.close(); - ps.close(); - - ps = con.prepareStatement("UPDATE characters SET guildid = ? WHERE id = ?"); - ps.setInt(1, guildId); - ps.setInt(2, leaderId); - ps.executeUpdate(); - ps.close(); - - con.close(); + + try (PreparedStatement ps = con.prepareStatement("INSERT INTO guilds (`leader`, `name`, `signature`) VALUES (?, ?, ?)")) { + ps.setInt(1, leaderId); + ps.setString(2, name); + ps.setInt(3, (int) System.currentTimeMillis()); + ps.executeUpdate(); + } + + final int guildId; + try (PreparedStatement ps = con.prepareStatement("SELECT guildid FROM guilds WHERE leader = ?")) { + ps.setInt(1, leaderId); + + try (ResultSet rs = ps.executeQuery()) { + rs.next(); + guildId = rs.getInt("guildid"); + } + } + + try (PreparedStatement ps = con.prepareStatement("UPDATE characters SET guildid = ? WHERE id = ?")) { + ps.setInt(1, guildId); + ps.setInt(2, leaderId); + ps.executeUpdate(); + } + return guildId; } catch (Exception e) { e.printStackTrace(); @@ -487,7 +478,7 @@ public class MapleGuild { break; } } - + this.broadcast(MaplePacketCreator.newGuildMember(mgc)); return 1; } finally { @@ -521,17 +512,13 @@ public class MapleGuild { if (mgc.isOnline()) { Server.getInstance().getWorld(mgc.getWorld()).setGuildAndRank(cid, 0, 5); } else { - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("INSERT INTO notes (`to`, `from`, `message`, `timestamp`) VALUES (?, ?, ?, ?)")) { - ps.setString(1, mgc.getName()); - ps.setString(2, initiator.getName()); - ps.setString(3, "You have been expelled from the guild."); - ps.setLong(4, System.currentTimeMillis()); - ps.executeUpdate(); - } - - con.close(); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("INSERT INTO notes (`to`, `from`, `message`, `timestamp`) VALUES (?, ?, ?, ?)")) { + ps.setString(1, mgc.getName()); + ps.setString(2, initiator.getName()); + ps.setString(3, "You have been expelled from the guild."); + ps.setLong(4, System.currentTimeMillis()); + ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); System.out.println("expelMember - MapleGuild " + e); @@ -564,7 +551,7 @@ public class MapleGuild { membersLock.unlock(); } } - + public void changeRank(MapleGuildCharacter mgc, int newRank) { try { if (mgc.isOnline()) { @@ -578,7 +565,7 @@ public class MapleGuild { re.printStackTrace(); return; } - + membersLock.lock(); try { this.broadcast(MaplePacketCreator.changeRank(mgc)); @@ -586,11 +573,11 @@ public class MapleGuild { membersLock.unlock(); } } - + public void setGuildNotice(String notice) { this.notice = notice; this.writeToDB(false); - + membersLock.lock(); try { this.broadcast(MaplePacketCreator.guildNotice(this.id, notice)); @@ -634,24 +621,24 @@ public class MapleGuild { public void changeRankTitle(String[] ranks) { System.arraycopy(ranks, 0, rankTitles, 0, 5); - + membersLock.lock(); try { this.broadcast(MaplePacketCreator.rankTitleChange(this.id, ranks)); } finally { membersLock.unlock(); } - + this.writeToDB(false); } public void disbandGuild() { - if(allianceId > 0) { + if (allianceId > 0) { if (!MapleAlliance.removeGuildFromAlliance(allianceId, id, world)) { MapleAlliance.disbandAlliance(allianceId); } } - + membersLock.lock(); try { this.writeToDB(true); @@ -667,7 +654,7 @@ public class MapleGuild { this.logo = logo; this.logoColor = logocolor; this.writeToDB(false); - + membersLock.lock(); try { this.broadcast(null, -1, BCOp.EMBLEMCHANGE); @@ -696,14 +683,14 @@ public class MapleGuild { } capacity += 5; this.writeToDB(false); - + membersLock.lock(); try { this.broadcast(MaplePacketCreator.guildCapacityChange(this.id, this.capacity)); } finally { membersLock.unlock(); } - + return true; } @@ -713,8 +700,8 @@ public class MapleGuild { this.guildMessage(MaplePacketCreator.updateGP(this.id, this.gp)); this.guildMessage(MaplePacketCreator.getGPMessage(amount)); } - - public void removeGP(int amount){ + + public void removeGP(int amount) { this.gp -= amount; this.writeToDB(false); this.guildMessage(MaplePacketCreator.updateGP(this.id, this.gp)); @@ -728,7 +715,7 @@ public class MapleGuild { if (mc.getGuildId() > 0) { return MapleGuildResponse.ALREADY_IN_GUILD; } - + MapleCharacter sender = c.getPlayer(); if (MapleInviteCoordinator.createInvite(InviteType.GUILD, sender, sender.getGuildId(), mc.getId())) { mc.getClient().announce(MaplePacketCreator.guildInvite(sender.getGuildId(), sender.getName())); @@ -737,55 +724,49 @@ public class MapleGuild { return MapleGuildResponse.MANAGING_INVITE; } } - + public static boolean answerInvitation(int targetId, String targetName, int guildId, boolean answer) { MapleInviteResult res = MapleInviteCoordinator.answerInvite(InviteType.GUILD, targetId, guildId, answer); - + MapleGuildResponse mgr; MapleCharacter sender = res.from; switch (res.result) { case ACCEPTED: return true; - + case DENIED: mgr = MapleGuildResponse.DENIED_INVITE; break; - + default: mgr = MapleGuildResponse.NOT_FOUND_INVITE; } - + if (mgr != null && sender != null) { sender.announce(mgr.getPacket(targetName)); } return false; } - + public static Set getEligiblePlayersForGuild(MapleCharacter guildLeader) { Set guildMembers = new HashSet<>(); guildMembers.add(guildLeader); - + MapleMatchCheckerCoordinator mmce = guildLeader.getWorldServer().getMatchCheckerCoordinator(); for (MapleCharacter chr : guildLeader.getMap().getAllPlayers()) { if (chr.getParty() == null && chr.getGuild() == null && mmce.getMatchConfirmationLeaderid(chr.getId()) == -1) { guildMembers.add(chr); } } - + return guildMembers; } - + public static void displayGuildRanks(MapleClient c, int npcid) { - try { - ResultSet rs; - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("SELECT `name`, `GP`, `logoBG`, `logoBGColor`, `logo`, `logoColor` FROM guilds ORDER BY `GP` DESC LIMIT 50", - ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) { - rs = ps.executeQuery(); - c.announce(MaplePacketCreator.showGuildRanks(npcid, rs)); - } - rs.close(); - con.close(); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT `name`, `GP`, `logoBG`, `logoBGColor`, `logo`, `logoColor` FROM guilds ORDER BY `GP` DESC LIMIT 50", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + ResultSet rs = ps.executeQuery()) { + c.announce(MaplePacketCreator.showGuildRanks(npcid, rs)); } catch (SQLException e) { e.printStackTrace(); System.out.println("failed to display guild ranks. " + e); @@ -798,41 +779,35 @@ public class MapleGuild { public void setAllianceId(int aid) { this.allianceId = aid; - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("UPDATE guilds SET allianceId = ? WHERE guildid = ?")) { - ps.setInt(1, aid); - ps.setInt(2, id); - ps.executeUpdate(); - } - - con.close(); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE guilds SET allianceId = ? WHERE guildid = ?")) { + ps.setInt(1, aid); + ps.setInt(2, id); + ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } - + public void resetAllianceGuildPlayersRank() { try { membersLock.lock(); try { - for(MapleGuildCharacter mgc: members) { - if(mgc.isOnline()) { + for (MapleGuildCharacter mgc : members) { + if (mgc.isOnline()) { mgc.setAllianceRank(5); } } } finally { membersLock.unlock(); } - - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("UPDATE characters SET allianceRank = ? WHERE guildid = ?")) { + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE characters SET allianceRank = ? WHERE guildid = ?")) { ps.setInt(1, 5); ps.setInt(2, id); ps.executeUpdate(); } - - con.close(); } catch (SQLException e) { e.printStackTrace(); } @@ -840,7 +815,7 @@ public class MapleGuild { public static int getIncreaseGuildCost(int size) { int cost = YamlConfig.config.server.EXPAND_GUILD_BASE_COST + Math.max(0, (size - 15) / 5) * YamlConfig.config.server.EXPAND_GUILD_TIER_COST; - + if (size > 30) { return Math.min(YamlConfig.config.server.EXPAND_GUILD_MAX_COST, Math.max(cost, 5000000)); } else { diff --git a/src/main/java/net/server/handlers/login/DeleteCharHandler.java b/src/main/java/net/server/handlers/login/DeleteCharHandler.java index ef066d107d..a57c1db128 100644 --- a/src/main/java/net/server/handlers/login/DeleteCharHandler.java +++ b/src/main/java/net/server/handlers/login/DeleteCharHandler.java @@ -21,11 +21,6 @@ */ package net.server.handlers.login; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - import client.MapleClient; import client.MapleFamily; import net.AbstractMaplePacketHandler; @@ -35,55 +30,65 @@ import tools.FilePrinter; import tools.MaplePacketCreator; import tools.data.input.SeekableLittleEndianAccessor; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + public final class DeleteCharHandler extends AbstractMaplePacketHandler { @Override public final void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) { - String pic = slea.readMapleAsciiString(); - int cid = slea.readInt(); - if (c.checkPic(pic)) { - //check for family, guild leader, pending marriage, world transfer - try (Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT `world`, `guildid`, `guildrank`, `familyId` FROM characters WHERE id = ?"); - PreparedStatement ps2 = con.prepareStatement("SELECT COUNT(*) as rowcount FROM worldtransfers WHERE `characterid` = ? AND completionTime IS NULL")) { - ps.setInt(1, cid); - ResultSet rs = ps.executeQuery(); - if(!rs.next()) throw new SQLException("Character record does not exist."); - int world = rs.getInt("world"); - int guildId = rs.getInt("guildid"); - int guildRank = rs.getInt("guildrank"); - int familyId = rs.getInt("familyId"); - if(guildId != 0 && guildRank <= 1) { - c.announce(MaplePacketCreator.deleteCharResponse(cid, 0x16)); - return; - } else if(familyId != -1) { - MapleFamily family = Server.getInstance().getWorld(world).getFamily(familyId); - if(family != null && family.getTotalMembers() > 1) { - c.announce(MaplePacketCreator.deleteCharResponse(cid, 0x1D)); - return; - } - } - rs.close(); - ps2.setInt(1, cid); - rs = ps2.executeQuery(); - rs.next(); - if(rs.getInt("rowcount") > 0) { - c.announce(MaplePacketCreator.deleteCharResponse(cid, 0x1A)); - return; - } - } catch(SQLException e) { - e.printStackTrace(); - c.announce(MaplePacketCreator.deleteCharResponse(cid, 0x09)); - return; - } - if(c.deleteCharacter(cid, c.getAccID())) { - FilePrinter.print(FilePrinter.DELETED_CHAR + c.getAccountName() + ".txt", c.getAccountName() + " deleted CID: " + cid); - c.announce(MaplePacketCreator.deleteCharResponse(cid, 0)); - } else { - c.announce(MaplePacketCreator.deleteCharResponse(cid, 0x09)); - } - } else { - c.announce(MaplePacketCreator.deleteCharResponse(cid, 0x14)); - } - } + String pic = slea.readMapleAsciiString(); + int cid = slea.readInt(); + if (c.checkPic(pic)) { + //check for family, guild leader, pending marriage, world transfer + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT `world`, `guildid`, `guildrank`, `familyId` FROM characters WHERE id = ?"); + PreparedStatement ps2 = con.prepareStatement("SELECT COUNT(*) as rowcount FROM worldtransfers WHERE `characterid` = ? AND completionTime IS NULL")) { + ps.setInt(1, cid); + + try (ResultSet rs = ps.executeQuery()) { + if (!rs.next()) { + throw new SQLException("Character record does not exist."); + } + int world = rs.getInt("world"); + int guildId = rs.getInt("guildid"); + int guildRank = rs.getInt("guildrank"); + int familyId = rs.getInt("familyId"); + if (guildId != 0 && guildRank <= 1) { + c.announce(MaplePacketCreator.deleteCharResponse(cid, 0x16)); + return; + } else if (familyId != -1) { + MapleFamily family = Server.getInstance().getWorld(world).getFamily(familyId); + if (family != null && family.getTotalMembers() > 1) { + c.announce(MaplePacketCreator.deleteCharResponse(cid, 0x1D)); + return; + } + } + } + + ps2.setInt(1, cid); + try (ResultSet rs = ps2.executeQuery()) { + rs.next(); + if (rs.getInt("rowcount") > 0) { + c.announce(MaplePacketCreator.deleteCharResponse(cid, 0x1A)); + return; + } + } + } catch (SQLException e) { + e.printStackTrace(); + c.announce(MaplePacketCreator.deleteCharResponse(cid, 0x09)); + return; + } + if (c.deleteCharacter(cid, c.getAccID())) { + FilePrinter.print(FilePrinter.DELETED_CHAR + c.getAccountName() + ".txt", c.getAccountName() + " deleted CID: " + cid); + c.announce(MaplePacketCreator.deleteCharResponse(cid, 0)); + } else { + c.announce(MaplePacketCreator.deleteCharResponse(cid, 0x09)); + } + } else { + c.announce(MaplePacketCreator.deleteCharResponse(cid, 0x14)); + } + } } diff --git a/src/main/java/net/server/handlers/login/LoginPasswordHandler.java b/src/main/java/net/server/handlers/login/LoginPasswordHandler.java index 3039be8627..fa0cca8fa3 100644 --- a/src/main/java/net/server/handlers/login/LoginPasswordHandler.java +++ b/src/main/java/net/server/handlers/login/LoginPasswordHandler.java @@ -21,26 +21,25 @@ */ package net.server.handlers.login; -import java.sql.*; -import java.time.LocalDateTime; -import java.util.Calendar; - import client.DefaultDates; +import client.MapleClient; import config.YamlConfig; import net.MaplePacketHandler; import net.server.Server; +import net.server.coordinator.session.MapleSessionCoordinator; +import org.apache.mina.core.session.IoSession; import tools.BCrypt; import tools.DatabaseConnection; import tools.HexTool; import tools.MaplePacketCreator; import tools.data.input.SeekableLittleEndianAccessor; -import client.MapleClient; import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import net.server.coordinator.session.MapleSessionCoordinator; -import org.apache.mina.core.session.IoSession; +import java.sql.*; +import java.util.Calendar; public final class LoginPasswordHandler implements MaplePacketHandler { @@ -51,14 +50,14 @@ public final class LoginPasswordHandler implements MaplePacketHandler { private static String hashpwSHA512(String pwd) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest digester = MessageDigest.getInstance("SHA-512"); - digester.update(pwd.getBytes("UTF-8"), 0, pwd.length()); + digester.update(pwd.getBytes(StandardCharsets.UTF_8), 0, pwd.length()); return HexTool.toString(digester.digest()).replace(" ", "").toLowerCase(); } private static String getRemoteIp(IoSession session) { return MapleSessionCoordinator.getSessionRemoteAddress(session); } - + @Override public final void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) { String remoteHost = getRemoteIp(c.getSession()); @@ -80,53 +79,47 @@ public final class LoginPasswordHandler implements MaplePacketHandler { c.announce(MaplePacketCreator.getLoginFailed(14)); // thanks Alchemist for noting remoteHost could be null return; } - + String login = slea.readMapleAsciiString(); String pwd = slea.readMapleAsciiString(); c.setAccountName(login); - + slea.skip(6); // localhost masked the initial part with zeroes... byte[] hwidNibbles = slea.read(4); String nibbleHwid = HexTool.toCompressedString(hwidNibbles); int loginok = c.login(login, pwd, nibbleHwid); - - Connection con = null; - PreparedStatement ps = null; + if (YamlConfig.config.server.AUTOMATIC_REGISTER && loginok == 5) { - try { - con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("INSERT INTO accounts (name, password, birthday, tempban) VALUES (?, ?, ?, ?);", Statement.RETURN_GENERATED_KEYS); //Jayd: Added birthday, tempban + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("INSERT INTO accounts (name, password, birthday, tempban) VALUES (?, ?, ?, ?);", Statement.RETURN_GENERATED_KEYS)) { //Jayd: Added birthday, tempban ps.setString(1, login); ps.setString(2, YamlConfig.config.server.BCRYPT_MIGRATION ? BCrypt.hashpw(pwd, BCrypt.gensalt(12)) : hashpwSHA512(pwd)); ps.setDate(3, Date.valueOf(DefaultDates.getBirthday())); ps.setTimestamp(4, Timestamp.valueOf(DefaultDates.getTempban())); ps.executeUpdate(); - - ResultSet rs = ps.getGeneratedKeys(); - rs.next(); - c.setAccID(rs.getInt(1)); - rs.close(); + + try (ResultSet rs = ps.getGeneratedKeys()) { + rs.next(); + c.setAccID(rs.getInt(1)); + } } catch (SQLException | NoSuchAlgorithmException | UnsupportedEncodingException e) { c.setAccID(-1); e.printStackTrace(); } finally { - disposeSql(con, ps); loginok = c.login(login, pwd, nibbleHwid); } } if (YamlConfig.config.server.BCRYPT_MIGRATION && (loginok <= -10)) { // -10 means migration to bcrypt, -23 means TOS wasn't accepted - try { - con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("UPDATE accounts SET password = ? WHERE name = ?;"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE accounts SET password = ? WHERE name = ?;")) { ps.setString(1, BCrypt.hashpw(pwd, BCrypt.gensalt(12))); ps.setString(2, login); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { - disposeSql(con, ps); loginok = (loginok == -10) ? 0 : 23; } } @@ -157,22 +150,8 @@ public final class LoginPasswordHandler implements MaplePacketHandler { } } - private static void login(MapleClient c){ + private static void login(MapleClient c) { c.announce(MaplePacketCreator.getAuthSuccess(c));//why the fk did I do c.getAccountName()? Server.getInstance().registerLoginState(c); } - - private static void disposeSql(Connection con, PreparedStatement ps) { - try { - if (con != null) { - con.close(); - } - - if (ps != null) { - ps.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } } diff --git a/src/main/java/net/server/task/RankingLoginTask.java b/src/main/java/net/server/task/RankingLoginTask.java index b5d0d74309..0828158c67 100644 --- a/src/main/java/net/server/task/RankingLoginTask.java +++ b/src/main/java/net/server/task/RankingLoginTask.java @@ -21,14 +21,15 @@ */ package net.server.task; +import client.MapleJob; +import config.YamlConfig; +import net.server.Server; +import tools.DatabaseConnection; + import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import client.MapleJob; -import config.YamlConfig; -import tools.DatabaseConnection; -import net.server.Server; /** * @author Matze @@ -36,13 +37,14 @@ import net.server.Server; * @author Ronan */ public class RankingLoginTask implements Runnable { - private Connection con; private long lastUpdate = System.currentTimeMillis(); private void resetMoveRank(boolean job) throws SQLException { - String query = "UPDATE characters SET " + (job == true ? "jobRankMove = 0" : "rankMove = 0"); - PreparedStatement reset = con.prepareStatement(query); - reset.executeUpdate(); + String query = "UPDATE characters SET " + (job ? "jobRankMove = 0" : "rankMove = 0"); + try (Connection con = DatabaseConnection.getConnection()) { + PreparedStatement reset = con.prepareStatement(query); + reset.executeUpdate(); + } } private void updateRanking(int job, int world) throws SQLException { @@ -51,66 +53,63 @@ public class RankingLoginTask implements Runnable { sqlCharSelect += "AND c.job DIV 100 = ? "; } sqlCharSelect += "ORDER BY c.level DESC , c.exp DESC , c.lastExpGainTime ASC, c.fame DESC , c.meso DESC"; - - PreparedStatement charSelect = con.prepareStatement(sqlCharSelect); - charSelect.setInt(1, world); - if (job != -1) { - charSelect.setInt(2, job); - } - ResultSet rs = charSelect.executeQuery(); - PreparedStatement ps = con.prepareStatement("UPDATE characters SET " + (job != -1 ? "jobRank = ?, jobRankMove = ? " : "rank = ?, rankMove = ? ") + "WHERE id = ?"); - int rank = 0; - - while (rs.next()) { - int rankMove = 0; - rank++; - if (rs.getLong("lastlogin") < lastUpdate || rs.getInt("loggedin") > 0) { - rankMove = rs.getInt((job != -1 ? "jobRankMove" : "rankMove")); + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement charSelect = con.prepareStatement(sqlCharSelect)) { + charSelect.setInt(1, world); + if (job != -1) { + charSelect.setInt(2, job); + } + + try (ResultSet rs = charSelect.executeQuery(); + PreparedStatement ps = con.prepareStatement("UPDATE characters SET " + (job != -1 ? "jobRank = ?, jobRankMove = ? " : "rank = ?, rankMove = ? ") + "WHERE id = ?")) { + int rank = 0; + + while (rs.next()) { + int rankMove = 0; + rank++; + if (rs.getLong("lastlogin") < lastUpdate || rs.getInt("loggedin") > 0) { + rankMove = rs.getInt((job != -1 ? "jobRankMove" : "rankMove")); + } + rankMove += rs.getInt((job != -1 ? "jobRank" : "rank")) - rank; + ps.setInt(1, rank); + ps.setInt(2, rankMove); + ps.setInt(3, rs.getInt("id")); + ps.executeUpdate(); + } } - rankMove += rs.getInt((job != -1 ? "jobRank" : "rank")) - rank; - ps.setInt(1, rank); - ps.setInt(2, rankMove); - ps.setInt(3, rs.getInt("id")); - ps.executeUpdate(); } - - rs.close(); - charSelect.close(); - ps.close(); } @Override public void run() { - try { - con = DatabaseConnection.getConnection(); + try (Connection con = DatabaseConnection.getConnection()) { con.setAutoCommit(false); - - if(YamlConfig.config.server.USE_REFRESH_RANK_MOVE == true) { - resetMoveRank(true); - resetMoveRank(false); - } - - for(int j = 0; j < Server.getInstance().getWorldsSize(); j++) { - updateRanking(-1, j); //overall ranking - for (int i = 0; i <= MapleJob.getMax(); i++) { - updateRanking(i, j); - } - con.commit(); - } - - con.setAutoCommit(true); - lastUpdate = System.currentTimeMillis(); - con.close(); - } catch (SQLException ex) { - ex.printStackTrace(); - + try { - con.rollback(); + if (YamlConfig.config.server.USE_REFRESH_RANK_MOVE) { + resetMoveRank(true); + resetMoveRank(false); + } + + for (int j = 0; j < Server.getInstance().getWorldsSize(); j++) { + updateRanking(-1, j); //overall ranking + for (int i = 0; i <= MapleJob.getMax(); i++) { + updateRanking(i, j); + } + con.commit(); + } + + con.setAutoCommit(true); + lastUpdate = System.currentTimeMillis(); + } catch (SQLException ex) { + con.rollback(); + throw ex; + } finally { con.setAutoCommit(true); - if(!con.isClosed()) con.close(); - } catch (SQLException ex2) { - ex2.printStackTrace(); } + } catch (SQLException e) { + e.printStackTrace(); } } } diff --git a/src/main/java/net/server/world/World.java b/src/main/java/net/server/world/World.java index 82e8cd7e3c..855bcaeb54 100644 --- a/src/main/java/net/server/world/World.java +++ b/src/main/java/net/server/world/World.java @@ -29,84 +29,43 @@ import client.MapleCharacter; import client.MapleFamily; import config.YamlConfig; import constants.game.GameConstants; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.LinkedList; -import java.util.List; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.SortedMap; -import java.util.TreeMap; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicInteger; - -import java.util.Set; -import java.util.HashSet; -import java.util.PriorityQueue; -import java.util.WeakHashMap; -import java.util.concurrent.ScheduledFuture; - -import scripting.event.EventInstanceManager; -import server.MapleStorage; -import server.TimerManager; -import server.maps.AbstractMapleMapObject; -import server.maps.MapleHiredMerchant; -import server.maps.MapleMap; -import server.maps.MapleMiniDungeon; -import server.maps.MapleMiniDungeonInfo; -import server.maps.MaplePlayerShop; -import server.maps.MaplePlayerShopItem; import net.server.PlayerStorage; import net.server.Server; import net.server.audit.LockCollector; -import net.server.audit.locks.MonitoredLockType; -import net.server.audit.locks.MonitoredReadLock; -import net.server.audit.locks.MonitoredReentrantLock; -import net.server.audit.locks.MonitoredReentrantReadWriteLock; -import net.server.audit.locks.MonitoredWriteLock; +import net.server.audit.locks.*; import net.server.audit.locks.factory.MonitoredReadLockFactory; import net.server.audit.locks.factory.MonitoredReentrantLockFactory; import net.server.audit.locks.factory.MonitoredWriteLockFactory; import net.server.channel.Channel; import net.server.channel.CharacterIdChannelPair; +import net.server.coordinator.matchchecker.MapleMatchCheckerCoordinator; +import net.server.coordinator.partysearch.MaplePartySearchCoordinator; import net.server.coordinator.world.MapleInviteCoordinator; import net.server.coordinator.world.MapleInviteCoordinator.InviteResult; import net.server.coordinator.world.MapleInviteCoordinator.InviteType; -import net.server.coordinator.matchchecker.MapleMatchCheckerCoordinator; -import net.server.coordinator.partysearch.MaplePartySearchCoordinator; import net.server.guild.MapleGuild; import net.server.guild.MapleGuildCharacter; import net.server.guild.MapleGuildSummary; import net.server.services.BaseService; import net.server.services.ServicesManager; import net.server.services.type.WorldServices; -import net.server.task.CharacterAutosaverTask; -import net.server.task.FamilyDailyResetTask; -import net.server.task.FishingTask; -import net.server.task.HiredMerchantTask; -import net.server.task.MapOwnershipTask; -import net.server.task.MountTirednessTask; -import net.server.task.PartySearchTask; -import net.server.task.PetFullnessTask; -import net.server.task.ServerMessageTask; -import net.server.task.TimedMapObjectTask; -import net.server.task.TimeoutTask; -import net.server.task.WeddingReservationTask; +import net.server.task.*; +import scripting.event.EventInstanceManager; +import server.MapleStorage; +import server.TimerManager; +import server.maps.*; import tools.DatabaseConnection; import tools.MaplePacketCreator; import tools.Pair; import tools.packets.Fishing; +import java.sql.*; +import java.util.*; +import java.util.Map.Entry; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.atomic.AtomicInteger; + /** * * @author kevintjuh93 @@ -693,16 +652,12 @@ public class World { } public void setOfflineGuildStatus(int guildid, int guildrank, int cid) { - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("UPDATE characters SET guildid = ?, guildrank = ? WHERE id = ?")) { - ps.setInt(1, guildid); - ps.setInt(2, guildrank); - ps.setInt(3, cid); - ps.execute(); - } - - con.close(); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE characters SET guildid = ?, guildrank = ? WHERE id = ?")) { + ps.setInt(1, guildid); + ps.setInt(2, guildrank); + ps.setInt(3, cid); + ps.executeUpdate(); } catch (SQLException se) { se.printStackTrace(); } @@ -1808,42 +1763,42 @@ public class World { } private static void executePlayerNpcMapDataUpdate(Connection con, boolean isPodium, Map pnpcData, int value, int worldid, int mapid) throws SQLException { - PreparedStatement ps; - if(pnpcData.containsKey(mapid)) { - ps = con.prepareStatement("UPDATE playernpcs_field SET " + (isPodium ? "podium" : "step") + " = ? WHERE world = ? AND map = ?"); + final String query; + if (pnpcData.containsKey(mapid)) { + query = "UPDATE playernpcs_field SET " + (isPodium ? "podium" : "step") + " = ? WHERE world = ? AND map = ?"; } else { - ps = con.prepareStatement("INSERT INTO playernpcs_field (" + (isPodium ? "podium" : "step") + ", world, map) VALUES (?, ?, ?)"); + query = "INSERT INTO playernpcs_field (" + (isPodium ? "podium" : "step") + ", world, map) VALUES (?, ?, ?)"; } - ps.setInt(1, value); - ps.setInt(2, worldid); - ps.setInt(3, mapid); - ps.executeUpdate(); - - ps.close(); + try (PreparedStatement ps = con.prepareStatement(query)) { + ps.setInt(1, value); + ps.setInt(2, worldid); + ps.setInt(3, mapid); + ps.executeUpdate(); + } } private void setPlayerNpcMapData(int mapid, int step, int podium, boolean silent) { - if(!silent) { - try { - Connection con = DatabaseConnection.getConnection(); - - if(step != -1) { + if (!silent) { + try (Connection con = DatabaseConnection.getConnection()) { + if (step != -1) { executePlayerNpcMapDataUpdate(con, false, pnpcStep, step, id, mapid); } - - if(podium != -1) { + + if (podium != -1) { executePlayerNpcMapDataUpdate(con, true, pnpcPodium, podium, id, mapid); } - - con.close(); } catch (SQLException e) { e.printStackTrace(); } } - - if(step != -1) pnpcStep.put(mapid, (byte) step); - if(podium != -1) pnpcPodium.put(mapid, (short) podium); + + if (step != -1) { + pnpcStep.put(mapid, (byte) step); + } + if (podium != -1) { + pnpcPodium.put(mapid, (short) podium); + } } public int getPlayerNpcMapStep(int mapid) { @@ -1945,12 +1900,11 @@ public class World { } private static Pair> getRelationshipCoupleFromDb(int id, boolean usingMarriageId) { - try { - Connection con = DatabaseConnection.getConnection(); + try (Connection con = DatabaseConnection.getConnection()) { Integer mid = null, hid = null, wid = null; - + PreparedStatement ps; - if(usingMarriageId) { + if (usingMarriageId) { ps = con.prepareStatement("SELECT * FROM marriages WHERE marriageid = ?"); ps.setInt(1, id); } else { @@ -1958,18 +1912,17 @@ public class World { ps.setInt(1, id); ps.setInt(2, id); } - - ResultSet rs = ps.executeQuery(); - if(rs.next()) { - mid = rs.getInt("marriageid"); - hid = rs.getInt("husbandid"); - wid = rs.getInt("wifeid"); + + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + mid = rs.getInt("marriageid"); + hid = rs.getInt("husbandid"); + wid = rs.getInt("wifeid"); + } } - - rs.close(); + ps.close(); - con.close(); - + return (mid == null) ? null : new Pair<>(mid, new Pair<>(hid, wid)); } catch (SQLException se) { se.printStackTrace(); @@ -1985,22 +1938,17 @@ public class World { } private static int addRelationshipToDb(int groomId, int brideId) { - try { - Connection con = DatabaseConnection.getConnection(); - - PreparedStatement ps = con.prepareStatement("INSERT INTO marriages (husbandid, wifeid) VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("INSERT INTO marriages (husbandid, wifeid) VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS)) { ps.setInt(1, groomId); ps.setInt(2, brideId); ps.executeUpdate(); - ResultSet rs = ps.getGeneratedKeys(); - rs.next(); - int ret = rs.getInt(1); - - rs.close(); - ps.close(); - con.close(); - return ret; + try (ResultSet rs = ps.getGeneratedKeys()) { + rs.next(); + int ret = rs.getInt(1); + return ret; + } } catch (SQLException se) { se.printStackTrace(); return -1; @@ -2017,14 +1965,10 @@ public class World { } private static void deleteRelationshipFromDb(int playerId) { - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("DELETE FROM marriages WHERE marriageid = ?"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("DELETE FROM marriages WHERE marriageid = ?")) { ps.setInt(1, playerId); ps.executeUpdate(); - - ps.close(); - con.close(); } catch (SQLException se) { se.printStackTrace(); } diff --git a/src/main/java/scripting/portal/PortalPlayerInteraction.java b/src/main/java/scripting/portal/PortalPlayerInteraction.java index ad23c6703b..59589d6c47 100644 --- a/src/main/java/scripting/portal/PortalPlayerInteraction.java +++ b/src/main/java/scripting/portal/PortalPlayerInteraction.java @@ -22,16 +22,17 @@ package scripting.portal; import client.MapleClient; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; import scripting.AbstractPlayerInteraction; import scripting.map.MapScriptManager; import server.maps.MaplePortal; import tools.DatabaseConnection; import tools.MaplePacketCreator; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + public class PortalPlayerInteraction extends AbstractPlayerInteraction { private MaplePortal portal; @@ -44,49 +45,31 @@ public class PortalPlayerInteraction extends AbstractPlayerInteraction { public MaplePortal getPortal() { return portal; } - + public void runMapScript() { MapScriptManager msm = MapScriptManager.getInstance(); msm.runMapScript(c, "onUserEnter/" + portal.getScriptName(), false); } public boolean hasLevel30Character() { - PreparedStatement ps = null; - ResultSet rs = null; - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("SELECT `level` FROM `characters` WHERE accountid = ?"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT `level` FROM `characters` WHERE accountid = ?")) { ps.setInt(1, getPlayer().getAccountID()); - rs = ps.executeQuery(); - while (rs.next()) { - if (rs.getInt("level") >= 30) { - ps.close(); - rs.close(); - return true; + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + if (rs.getInt("level") >= 30) { + return true; + } } } } catch (SQLException sqle) { sqle.printStackTrace(); - } finally { - try { - if (ps != null && !ps.isClosed()) { - ps.close(); - } - if (rs != null && !rs.isClosed()) { - rs.close(); - } - if (con != null && !con.isClosed()) { - con.close(); - } - } catch (SQLException ex) { - ex.printStackTrace(); - } } - + return getPlayer().getLevel() >= 30; } - + public void blockPortal() { c.getPlayer().blockPortal(getPortal().getScriptName()); } diff --git a/src/main/java/scripting/reactor/ReactorScriptManager.java b/src/main/java/scripting/reactor/ReactorScriptManager.java index 7fcb1acacc..737bb21235 100644 --- a/src/main/java/scripting/reactor/ReactorScriptManager.java +++ b/src/main/java/scripting/reactor/ReactorScriptManager.java @@ -22,6 +22,14 @@ along with this program. If not, see . package scripting.reactor; import client.MapleClient; +import jdk.nashorn.api.scripting.NashornScriptEngine; +import scripting.AbstractScriptManager; +import server.maps.MapleReactor; +import server.maps.ReactorDropEntry; +import tools.DatabaseConnection; +import tools.FilePrinter; + +import javax.script.ScriptException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -29,14 +37,6 @@ import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; -import javax.script.ScriptException; - -import jdk.nashorn.api.scripting.NashornScriptEngine; -import scripting.AbstractScriptManager; -import server.maps.MapleReactor; -import server.maps.ReactorDropEntry; -import tools.DatabaseConnection; -import tools.FilePrinter; /** * @author Lerk @@ -83,8 +83,7 @@ public class ReactorScriptManager extends AbstractScriptManager { List ret = drops.get(rid); if (ret == null) { ret = new LinkedList<>(); - try { - Connection con = DatabaseConnection.getConnection(); + try (Connection con = DatabaseConnection.getConnection()) { try (PreparedStatement ps = con.prepareStatement("SELECT itemid, chance, questid FROM reactordrops WHERE reactorid = ? AND chance >= 0")) { ps.setInt(1, rid); try (ResultSet rs = ps.executeQuery()) { @@ -93,8 +92,6 @@ public class ReactorScriptManager extends AbstractScriptManager { } } } - - con.close(); } catch (Throwable e) { FilePrinter.printError(FilePrinter.REACTOR + rid + ".txt", e); } diff --git a/src/main/java/server/CashShop.java b/src/main/java/server/CashShop.java index 1eb541e05d..cdf024f316 100644 --- a/src/main/java/server/CashShop.java +++ b/src/main/java/server/CashShop.java @@ -21,36 +21,27 @@ along with this program. If not, see . */ package server; -import java.io.File; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.locks.Lock; - +import client.inventory.*; import config.YamlConfig; +import constants.inventory.ItemConstants; import net.server.Server; +import net.server.audit.locks.MonitoredLockType; import net.server.audit.locks.factory.MonitoredReentrantLockFactory; - import provider.MapleData; import provider.MapleDataProvider; import provider.MapleDataProviderFactory; import provider.MapleDataTool; import tools.DatabaseConnection; import tools.Pair; -import client.inventory.Equip; -import client.inventory.Item; -import client.inventory.ItemFactory; -import client.inventory.MapleInventoryType; -import client.inventory.MaplePet; -import constants.inventory.ItemConstants; -import java.util.Collections; -import net.server.audit.locks.MonitoredLockType; + +import java.io.File; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.*; +import java.util.Map.Entry; +import java.util.concurrent.locks.Lock; /* * @author Flav @@ -99,7 +90,7 @@ public class CashShop { if (ItemConstants.isPet(itemId)) { petid = MaplePet.createPet(itemId); } - + if (ItemConstants.getInventoryType(itemId).equals(MapleInventoryType.EQUIP)) { item = MapleItemInformationProvider.getInstance().getEquipById(itemId); } else { @@ -107,28 +98,28 @@ public class CashShop { } if (ItemConstants.EXPIRING_ITEMS) { - if(period == 1) { - if(itemId == 5211048 || itemId == 5360042) { // 4 Hour 2X coupons, the period is 1, but we don't want them to last a day. - item.setExpiration(Server.getInstance().getCurrentTime() + (1000 * 60 * 60 * 4)); + if (period == 1) { + if (itemId == 5211048 || itemId == 5360042) { // 4 Hour 2X coupons, the period is 1, but we don't want them to last a day. + item.setExpiration(Server.getInstance().getCurrentTime() + (1000 * 60 * 60 * 4)); /* } else if(itemId == 5211047 || itemId == 5360014) { // 3 Hour 2X coupons, unused as of now item.setExpiration(Server.getInstance().getCurrentTime() + (1000 * 60 * 60 * 3)); */ - } else if(itemId == 5211060) { // 2 Hour 3X coupons. - item.setExpiration(Server.getInstance().getCurrentTime() + (1000 * 60 * 60 * 2)); - } else { - item.setExpiration(Server.getInstance().getCurrentTime() + (1000 * 60 * 60 * 24)); - } + } else if (itemId == 5211060) { // 2 Hour 3X coupons. + item.setExpiration(Server.getInstance().getCurrentTime() + (1000 * 60 * 60 * 2)); } else { - item.setExpiration(Server.getInstance().getCurrentTime() + (1000 * 60 * 60 * 24 * period)); + item.setExpiration(Server.getInstance().getCurrentTime() + (1000 * 60 * 60 * 24)); } + } else { + item.setExpiration(Server.getInstance().getCurrentTime() + (1000 * 60 * 60 * 24 * period)); + } } - + item.setSN(sn); return item; } } - + public static class SpecialCashItem { private int sn, modifier; private byte info; //? @@ -181,43 +172,33 @@ public class CashShop { packages.put(Integer.parseInt(cashPackage.getName()), cPackage); } - - for(Entry e : items.entrySet()) { - if(e.getValue().isOnSale()) { + + for (Entry e : items.entrySet()) { + if (e.getValue().isOnSale()) { randomitemsns.add(e.getKey()); } } - - PreparedStatement ps = null; - ResultSet rs = null; - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("SELECT * FROM specialcashitems"); - rs = ps.executeQuery(); + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT * FROM specialcashitems"); + ResultSet rs = ps.executeQuery()) { while (rs.next()) { specialcashitems.add(new SpecialCashItem(rs.getInt("sn"), rs.getInt("modifier"), rs.getByte("info"))); } } catch (SQLException ex) { ex.printStackTrace(); - } finally { - try { - if (rs != null && !rs.isClosed()) rs.close(); - if (ps != null && !ps.isClosed()) ps.close(); - if (con != null && !con.isClosed()) con.close(); - } catch (SQLException ex) { - ex.printStackTrace(); - } } } public static CashItem getRandomCashItem() { - if(randomitemsns.isEmpty()) return null; - - int rnd = (int)(Math.random() * randomitemsns.size()); + if (randomitemsns.isEmpty()) { + return null; + } + + int rnd = (int) (Math.random() * randomitemsns.size()); return items.get(randomitemsns.get(rnd)); } - + public static CashItem getItem(int sn) { return items.get(sn); } @@ -239,33 +220,21 @@ public class CashShop { public static List getSpecialCashItems() { return specialcashitems; } - + public static void reloadSpecialCashItems() {//Yay? specialcashitems.clear(); - PreparedStatement ps = null; - ResultSet rs = null; - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("SELECT * FROM specialcashitems"); - rs = ps.executeQuery(); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT * FROM specialcashitems"); + ResultSet rs = ps.executeQuery()) { while (rs.next()) { specialcashitems.add(new SpecialCashItem(rs.getInt("sn"), rs.getInt("modifier"), rs.getByte("info"))); } } catch (SQLException ex) { ex.printStackTrace(); - } finally { - try { - if (rs != null && !rs.isClosed()) rs.close(); - if (ps != null && !ps.isClosed()) ps.close(); - if (con != null && !con.isClosed()) con.close(); - } catch (SQLException ex) { - ex.printStackTrace(); - } - } + } } } - + private int accountId, characterId, nxCredit, maplePoint, nxPrepaid; private boolean opened; private ItemFactory factory; @@ -290,42 +259,32 @@ public class CashShop { factory = ItemFactory.CASH_OVERALL; } - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = null; - ResultSet rs = null; - try { - ps = con.prepareStatement("SELECT `nxCredit`, `maplePoint`, `nxPrepaid` FROM `accounts` WHERE `id` = ?"); - ps.setInt(1, accountId); - rs = ps.executeQuery(); + try (Connection con = DatabaseConnection.getConnection()) { + try (PreparedStatement ps = con.prepareStatement("SELECT `nxCredit`, `maplePoint`, `nxPrepaid` FROM `accounts` WHERE `id` = ?")) { + ps.setInt(1, accountId); - if (rs.next()) { - this.nxCredit = rs.getInt("nxCredit"); - this.maplePoint = rs.getInt("maplePoint"); - this.nxPrepaid = rs.getInt("nxPrepaid"); + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + this.nxCredit = rs.getInt("nxCredit"); + this.maplePoint = rs.getInt("maplePoint"); + this.nxPrepaid = rs.getInt("nxPrepaid"); + } + } } - rs.close(); - ps.close(); - for (Pair item : factory.loadItems(accountId, false)) { inventory.add(item.getLeft()); } - ps = con.prepareStatement("SELECT `sn` FROM `wishlists` WHERE `charid` = ?"); - ps.setInt(1, characterId); - rs = ps.executeQuery(); + try (PreparedStatement ps = con.prepareStatement("SELECT `sn` FROM `wishlists` WHERE `charid` = ?")) { + ps.setInt(1, characterId); - while (rs.next()) { - wishList.add(rs.getInt("sn")); + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + wishList.add(rs.getInt("sn")); + } + } } - - rs.close(); - ps.close(); - con.close(); - } finally { - if (ps != null && !ps.isClosed()) ps.close(); - if (rs != null && !rs.isClosed()) rs.close(); - if (con != null && !con.isClosed()) con.close(); } } @@ -355,10 +314,12 @@ public class CashShop { break; } } - + public void gainCash(int type, CashItem buyItem, int world) { gainCash(type, -buyItem.getPrice()); - if(!YamlConfig.config.server.USE_ENFORCE_ITEM_SUGGESTION) Server.getInstance().getWorld(world).addCashItemBought(buyItem.getSN()); + if (!YamlConfig.config.server.USE_ENFORCE_ITEM_SUGGESTION) { + Server.getInstance().getWorld(world).addCashItemBought(buyItem.getSN()); + } } public boolean isOpened() { @@ -388,7 +349,7 @@ public class CashShop { } else { isRing = false; } - + if ((item.getPetId() > -1 ? item.getPetId() : isRing ? equip.getRingId() : item.getCashId()) == cashId) { return item; } @@ -432,70 +393,58 @@ public class CashShop { } public void gift(int recipient, String from, String message, int sn, int ringid) { - PreparedStatement ps = null; - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("INSERT INTO `gifts` VALUES (DEFAULT, ?, ?, ?, ?, ?)"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("INSERT INTO `gifts` VALUES (DEFAULT, ?, ?, ?, ?, ?)")) { ps.setInt(1, recipient); ps.setString(2, from); ps.setString(3, message); ps.setInt(4, sn); ps.setInt(5, ringid); ps.executeUpdate(); - con.close(); } catch (SQLException sqle) { sqle.printStackTrace(); - } finally { - try { - if (ps != null && !ps.isClosed()) ps.close(); - if (con != null && !con.isClosed()) con.close(); - } catch (SQLException ex) { - ex.printStackTrace(); - } } } public List> loadGifts() { List> gifts = new ArrayList<>(); - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT * FROM `gifts` WHERE `to` = ?"); - ps.setInt(1, characterId); - ResultSet rs = ps.executeQuery(); + try (Connection con = DatabaseConnection.getConnection()) { - while (rs.next()) { - notes++; - CashItem cItem = CashItemFactory.getItem(rs.getInt("sn")); - Item item = cItem.toItem(); - Equip equip = null; - item.setGiftFrom(rs.getString("from")); - if (item.getInventoryType().equals(MapleInventoryType.EQUIP)) { - equip = (Equip) item; - equip.setRingId(rs.getInt("ringid")); - gifts.add(new Pair(equip, rs.getString("message"))); - } else - gifts.add(new Pair<>(item, rs.getString("message"))); + try (PreparedStatement ps = con.prepareStatement("SELECT * FROM `gifts` WHERE `to` = ?")) { + ps.setInt(1, characterId); - if (CashItemFactory.isPackage(cItem.getItemId())) { //Packages never contains a ring - for (Item packageItem : CashItemFactory.getPackage(cItem.getItemId())) { - packageItem.setGiftFrom(rs.getString("from")); - addToInventory(packageItem); + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + notes++; + CashItem cItem = CashItemFactory.getItem(rs.getInt("sn")); + Item item = cItem.toItem(); + Equip equip = null; + item.setGiftFrom(rs.getString("from")); + if (item.getInventoryType().equals(MapleInventoryType.EQUIP)) { + equip = (Equip) item; + equip.setRingId(rs.getInt("ringid")); + gifts.add(new Pair<>(equip, rs.getString("message"))); + } else { + gifts.add(new Pair<>(item, rs.getString("message"))); + } + + if (CashItemFactory.isPackage(cItem.getItemId())) { //Packages never contains a ring + for (Item packageItem : CashItemFactory.getPackage(cItem.getItemId())) { + packageItem.setGiftFrom(rs.getString("from")); + addToInventory(packageItem); + } + } else { + addToInventory(equip == null ? item : equip); + } } - } else { - addToInventory(equip == null ? item : equip); } } - rs.close(); - ps.close(); - ps = con.prepareStatement("DELETE FROM `gifts` WHERE `to` = ?"); - ps.setInt(1, characterId); - ps.executeUpdate(); - ps.close(); - con.close(); + try (PreparedStatement ps = con.prepareStatement("DELETE FROM `gifts` WHERE `to` = ?")) { + ps.setInt(1, characterId); + ps.executeUpdate(); + } } catch (SQLException sqle) { sqle.printStackTrace(); } @@ -512,13 +461,14 @@ public class CashShop { } public void save(Connection con) throws SQLException { - PreparedStatement ps = con.prepareStatement("UPDATE `accounts` SET `nxCredit` = ?, `maplePoint` = ?, `nxPrepaid` = ? WHERE `id` = ?"); - ps.setInt(1, nxCredit); - ps.setInt(2, maplePoint); - ps.setInt(3, nxPrepaid); - ps.setInt(4, accountId); - ps.executeUpdate(); - ps.close(); + try (PreparedStatement ps = con.prepareStatement("UPDATE `accounts` SET `nxCredit` = ?, `maplePoint` = ?, `nxPrepaid` = ? WHERE `id` = ?")) { + ps.setInt(1, nxCredit); + ps.setInt(2, maplePoint); + ps.setInt(3, nxPrepaid); + ps.setInt(4, accountId); + ps.executeUpdate(); + } + List> itemsWithType = new ArrayList<>(); List inv = getInventory(); @@ -527,53 +477,55 @@ public class CashShop { } factory.saveItems(itemsWithType, accountId, con); - ps = con.prepareStatement("DELETE FROM `wishlists` WHERE `charid` = ?"); - ps.setInt(1, characterId); - ps.executeUpdate(); - ps.close(); - ps = con.prepareStatement("INSERT INTO `wishlists` VALUES (DEFAULT, ?, ?)"); - ps.setInt(1, characterId); - for (int sn : wishList) { - ps.setInt(2, sn); + try (PreparedStatement ps = con.prepareStatement("DELETE FROM `wishlists` WHERE `charid` = ?")) { + ps.setInt(1, characterId); ps.executeUpdate(); } - ps.close(); + try (PreparedStatement ps = con.prepareStatement("INSERT INTO `wishlists` VALUES (DEFAULT, ?, ?)")) { + ps.setInt(1, characterId); + + for (int sn : wishList) { + // TODO: batch insert + ps.setInt(2, sn); + ps.executeUpdate(); + } + } } - + private Item getCashShopItemByItemid(int itemid) { lock.lock(); try { - for(Item it : inventory) { - if(it.getItemId() == itemid) { + for (Item it : inventory) { + if (it.getItemId() == itemid) { return it; } } } finally { lock.unlock(); } - + return null; } - + public synchronized Pair openCashShopSurprise() { Item css = getCashShopItemByItemid(5222000); - - if(css != null) { + + if (css != null) { CashItem cItem = CashItemFactory.getRandomCashItem(); - - if(cItem != null) { - if(css.getQuantity() > 1) { + + if (cItem != null) { + if (css.getQuantity() > 1) { /* if(NOT ENOUGH SPACE) { looks like we're not dealing with cash inventory limit whatsoever, k then return null; } */ - + css.setQuantity((short) (css.getQuantity() - 1)); } else { removeFromInventory(css); } - + Item item = cItem.toItem(); addToInventory(item); @@ -585,7 +537,7 @@ public class CashShop { return null; } } - + public static Item generateCouponItem(int itemId, short quantity) { CashItem it = new CashItem(77777777, itemId, 7777, ItemConstants.isPet(itemId) ? 30 : 0, quantity, true); return it.toItem(); diff --git a/src/main/java/server/MapleItemInformationProvider.java b/src/main/java/server/MapleItemInformationProvider.java index e8b8dab9ff..5078655ab0 100644 --- a/src/main/java/server/MapleItemInformationProvider.java +++ b/src/main/java/server/MapleItemInformationProvider.java @@ -21,55 +21,29 @@ */ package server; -import java.io.File; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.HashSet; - -import config.YamlConfig; -import net.server.Server; -import provider.MapleData; -import provider.MapleDataDirectoryEntry; -import provider.MapleDataFileEntry; -import provider.MapleDataProvider; -import provider.MapleDataProviderFactory; -import provider.MapleDataTool; -import tools.DatabaseConnection; -import tools.FilePrinter; -import tools.MaplePacketCreator; -import tools.Pair; -import tools.Randomizer; -import client.MapleCharacter; -import client.MapleClient; -import client.MapleJob; -import client.Skill; -import client.SkillFactory; +import client.*; import client.autoban.AutobanFactory; -import client.inventory.Equip; -import client.inventory.Item; -import client.inventory.MapleInventory; -import client.inventory.MapleInventoryType; -import client.inventory.MapleWeaponType; +import client.inventory.*; +import config.YamlConfig; import constants.inventory.EquipSlot; import constants.inventory.ItemConstants; import constants.skills.Assassin; import constants.skills.Gunslinger; import constants.skills.NightWalker; -import java.sql.Connection; +import net.server.Server; +import provider.*; import server.MakerItemFactory.MakerItemCreateEntry; -import server.life.MapleMonsterInformationProvider; import server.life.MapleLifeFactory; -import tools.StringUtil; +import server.life.MapleMonsterInformationProvider; +import tools.*; + +import java.io.File; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.*; +import java.util.Map.Entry; /** * @@ -1407,35 +1381,14 @@ public class MapleItemInformationProvider { } private void loadCardIdData() { - PreparedStatement ps = null; - ResultSet rs = null; - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("SELECT cardid, mobid FROM monstercarddata"); - rs = ps.executeQuery(); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT cardid, mobid FROM monstercarddata"); + ResultSet rs = ps.executeQuery()) { while (rs.next()) { monsterBookID.put(rs.getInt(1), rs.getInt(2)); } - rs.close(); - ps.close(); - con.close(); } catch (SQLException e) { e.printStackTrace(); - } finally { - try { - if (rs != null && !rs.isClosed()) { - rs.close(); - } - if (ps != null && !ps.isClosed()) { - ps.close(); - } - if (con != null && !con.isClosed()) { - con.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } } } @@ -1915,25 +1868,25 @@ public class MapleItemInformationProvider { public Pair getMakerReagentStatUpgrade(int itemId) { try { Pair statUpgd = statUpgradeMakerCache.get(itemId); - if(statUpgd != null) { + if (statUpgd != null) { return statUpgd; - } else if(statUpgradeMakerCache.containsKey(itemId)) { + } else if (statUpgradeMakerCache.containsKey(itemId)) { return null; } - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT stat, value FROM makerreagentdata WHERE itemid = ?"); - ps.setInt(1, itemId); - ResultSet rs = ps.executeQuery(); - if(rs.next()) { - String statType = rs.getString("stat"); - int statGain = rs.getInt("value"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT stat, value FROM makerreagentdata WHERE itemid = ?")) { + ps.setInt(1, itemId); - statUpgd = new Pair<>(statType, statGain); + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + String statType = rs.getString("stat"); + int statGain = rs.getInt("value"); + + statUpgd = new Pair<>(statType, statGain); + } + } } - rs.close(); - ps.close(); - con.close(); statUpgradeMakerCache.put(itemId, statUpgd); return statUpgd; @@ -1946,23 +1899,23 @@ public class MapleItemInformationProvider { public int getMakerCrystalFromLeftover(Integer leftoverId) { try { Integer itemid = mobCrystalMakerCache.get(leftoverId); - if(itemid != null) { + if (itemid != null) { return itemid; } itemid = -1; - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT dropperid FROM drop_data WHERE itemid = ? ORDER BY dropperid;"); - ps.setInt(1, leftoverId); - ResultSet rs = ps.executeQuery(); - if(rs.next()) { - int dropperid = rs.getInt("dropperid"); - itemid = getCrystalForLevel(MapleLifeFactory.getMonsterLevel(dropperid) - 1); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT dropperid FROM drop_data WHERE itemid = ? ORDER BY dropperid;")) { + ps.setInt(1, leftoverId); + + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + int dropperid = rs.getInt("dropperid"); + itemid = getCrystalForLevel(MapleLifeFactory.getMonsterLevel(dropperid) - 1); + } + } } - rs.close(); - ps.close(); - con.close(); mobCrystalMakerCache.put(leftoverId, itemid); return itemid; @@ -1979,34 +1932,35 @@ public class MapleItemInformationProvider { if ((makerEntry = makerItemCache.get(toCreate)) != null) { return new MakerItemCreateEntry(makerEntry); } else { - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT req_level, req_maker_level, req_meso, quantity FROM makercreatedata WHERE itemid = ?"); - ps.setInt(1, toCreate); - ResultSet rs = ps.executeQuery(); + try (Connection con = DatabaseConnection.getConnection()) { int reqLevel = -1; int reqMakerLevel = -1; int cost = -1; int toGive = -1; - if (rs.next()) { - reqLevel = rs.getInt("req_level"); - reqMakerLevel = rs.getInt("req_maker_level"); - cost = rs.getInt("req_meso"); - toGive = rs.getInt("quantity"); + try (PreparedStatement ps = con.prepareStatement("SELECT req_level, req_maker_level, req_meso, quantity FROM makercreatedata WHERE itemid = ?")) { + ps.setInt(1, toCreate); + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + reqLevel = rs.getInt("req_level"); + reqMakerLevel = rs.getInt("req_maker_level"); + cost = rs.getInt("req_meso"); + toGive = rs.getInt("quantity"); + } + } } - ps.close(); - rs.close(); + makerEntry = new MakerItemCreateEntry(cost, reqLevel, reqMakerLevel); makerEntry.addGainItem(toCreate, toGive); - ps = con.prepareStatement("SELECT req_item, count FROM makerrecipedata WHERE itemid = ?"); - ps.setInt(1, toCreate); - rs = ps.executeQuery(); - while (rs.next()) { - makerEntry.addReqItem(rs.getInt("req_item"), rs.getInt("count")); + + try (PreparedStatement ps = con.prepareStatement("SELECT req_item, count FROM makerrecipedata WHERE itemid = ?")) { + ps.setInt(1, toCreate); + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + makerEntry.addReqItem(rs.getInt("req_item"), rs.getInt("count")); + } + } } - rs.close(); - ps.close(); - con.close(); makerItemCache.put(toCreate, new MakerItemCreateEntry(makerEntry)); } catch (SQLException sqle) { sqle.printStackTrace(); @@ -2039,21 +1993,16 @@ public class MapleItemInformationProvider { public List> getMakerDisassembledItems(Integer itemId) { List> items = new LinkedList<>(); - - Connection con; - try { - con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT req_item, count FROM makerrecipedata WHERE itemid = ? AND req_item >= 4260000 AND req_item < 4270000"); + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT req_item, count FROM makerrecipedata WHERE itemid = ? AND req_item >= 4260000 AND req_item < 4270000")) { ps.setInt(1, itemId); - ResultSet rs = ps.executeQuery(); - while (rs.next()) { - items.add(new Pair<>(rs.getInt("req_item"), rs.getInt("count") / 2)); // return to the player half of the crystals needed + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + items.add(new Pair<>(rs.getInt("req_item"), rs.getInt("count") / 2)); // return to the player half of the crystals needed + } } - - rs.close(); - ps.close(); - con.close(); } catch (Exception e) { e.printStackTrace(); } @@ -2063,22 +2012,17 @@ public class MapleItemInformationProvider { public int getMakerDisassembledFee(Integer itemId) { int fee = -1; - Connection con; - try { - con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT req_meso FROM makercreatedata WHERE itemid = ?"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT req_meso FROM makercreatedata WHERE itemid = ?")) { ps.setInt(1, itemId); - ResultSet rs = ps.executeQuery(); - if(rs.next()) { // cost is 13.6363~ % of the original value, trim by 1000. - float val = (float) (rs.getInt("req_meso") * 0.13636363636364); - fee = (int) (val / 1000); - fee *= 1000; + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { // cost is 13.6363~ % of the original value, trim by 1000. + float val = (float) (rs.getInt("req_meso") * 0.13636363636364); + fee = (int) (val / 1000); + fee *= 1000; + } } - - rs.close(); - ps.close(); - con.close(); } catch (Exception e) { e.printStackTrace(); } @@ -2108,21 +2052,18 @@ public class MapleItemInformationProvider { public Set getWhoDrops(Integer itemId) { Set list = new HashSet<>(); - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT dropperid FROM drop_data WHERE itemid = ? LIMIT 50"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT dropperid FROM drop_data WHERE itemid = ? LIMIT 50")) { ps.setInt(1, itemId); - ResultSet rs = ps.executeQuery(); - while(rs.next()) { - String resultName = MapleMonsterInformationProvider.getInstance().getMobNameFromId(rs.getInt("dropperid")); - if (!resultName.isEmpty()) { - list.add(resultName); + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + String resultName = MapleMonsterInformationProvider.getInstance().getMobNameFromId(rs.getInt("dropperid")); + if (!resultName.isEmpty()) { + list.add(resultName); + } } } - rs.close(); - ps.close(); - con.close(); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/server/MapleMarriage.java b/src/main/java/server/MapleMarriage.java index 1fcae81703..3f9110b846 100644 --- a/src/main/java/server/MapleMarriage.java +++ b/src/main/java/server/MapleMarriage.java @@ -19,23 +19,24 @@ */ package server; -import client.MapleClient; import client.MapleCharacter; +import client.MapleClient; import client.inventory.Item; import client.inventory.ItemFactory; import client.inventory.MapleInventory; import client.inventory.MapleInventoryType; import client.inventory.manipulator.MapleInventoryManipulator; import scripting.event.EventInstanceManager; +import scripting.event.EventManager; +import tools.DatabaseConnection; +import tools.Pair; + import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; -import scripting.event.EventManager; -import tools.DatabaseConnection; -import tools.Pair; /** * @@ -118,10 +119,8 @@ public class MapleMarriage extends EventInstanceManager { public static boolean claimGiftItems(MapleClient c, MapleCharacter chr) { List gifts = loadGiftItemsFromDb(c, chr.getId()); if (MapleInventory.checkSpot(chr, gifts)) { - try { - Connection con = DatabaseConnection.getConnection(); - ItemFactory.MARRIAGE_GIFTS.saveItems(new LinkedList>(), chr.getId(), con); - con.close(); + try (Connection con = DatabaseConnection.getConnection()) { + ItemFactory.MARRIAGE_GIFTS.saveItems(new LinkedList<>(), chr.getId(), con); } catch (SQLException sqle) { sqle.printStackTrace(); } @@ -159,11 +158,9 @@ public class MapleMarriage extends EventInstanceManager { for (Item it : giftItems) { items.add(new Pair<>(it, it.getInventoryType())); } - - try { - Connection con = DatabaseConnection.getConnection(); + + try (Connection con = DatabaseConnection.getConnection()) { ItemFactory.MARRIAGE_GIFTS.saveItems(items, cid, con); - con.close(); } catch (SQLException sqle) { sqle.printStackTrace(); } diff --git a/src/main/java/server/MapleShop.java b/src/main/java/server/MapleShop.java index 3c75335311..97f722f6b9 100644 --- a/src/main/java/server/MapleShop.java +++ b/src/main/java/server/MapleShop.java @@ -21,12 +21,15 @@ */ package server; -import client.inventory.manipulator.MapleInventoryManipulator; import client.MapleClient; import client.inventory.Item; import client.inventory.MapleInventoryType; import client.inventory.MaplePet; +import client.inventory.manipulator.MapleInventoryManipulator; import constants.inventory.ItemConstants; +import tools.DatabaseConnection; +import tools.MaplePacketCreator; + import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -35,8 +38,6 @@ import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; -import tools.DatabaseConnection; -import tools.MaplePacketCreator; /** * @@ -238,48 +239,48 @@ public class MapleShop { public static MapleShop createFromDB(int id, boolean isShopId) { MapleShop ret = null; int shopId; - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps; + try (Connection con = DatabaseConnection.getConnection()) { + final String query; if (isShopId) { - ps = con.prepareStatement("SELECT * FROM shops WHERE shopid = ?"); + query = "SELECT * FROM shops WHERE shopid = ?"; } else { - ps = con.prepareStatement("SELECT * FROM shops WHERE npcid = ?"); + query = "SELECT * FROM shops WHERE npcid = ?"; } - ps.setInt(1, id); - ResultSet rs = ps.executeQuery(); - if (rs.next()) { - shopId = rs.getInt("shopid"); - ret = new MapleShop(shopId, rs.getInt("npcid")); - rs.close(); - ps.close(); - } else { - rs.close(); - ps.close(); - con.close(); - return null; - } - ps = con.prepareStatement("SELECT itemid, price, pitch FROM shopitems WHERE shopid = ? ORDER BY position DESC"); - ps.setInt(1, shopId); - rs = ps.executeQuery(); - List recharges = new ArrayList<>(rechargeableItems); - while (rs.next()) { - if (ItemConstants.isRechargeable(rs.getInt("itemid"))) { - MapleShopItem starItem = new MapleShopItem((short) 1, rs.getInt("itemid"), rs.getInt("price"), rs.getInt("pitch")); - ret.addItem(starItem); - if (rechargeableItems.contains(starItem.getItemId())) { - recharges.remove(Integer.valueOf(starItem.getItemId())); + + try (PreparedStatement ps = con.prepareStatement(query)) { + ps.setInt(1, id); + + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + shopId = rs.getInt("shopid"); + ret = new MapleShop(shopId, rs.getInt("npcid")); + } else { + return null; } - } else { - ret.addItem(new MapleShopItem((short) 1000, rs.getInt("itemid"), rs.getInt("price"), rs.getInt("pitch"))); } } - for (Integer recharge : recharges) { - ret.addItem(new MapleShopItem((short) 1000, recharge.intValue(), 0, 0)); + + try (PreparedStatement ps = con.prepareStatement("SELECT itemid, price, pitch FROM shopitems WHERE shopid = ? ORDER BY position DESC")) { + ps.setInt(1, shopId); + + try (ResultSet rs = ps.executeQuery()) { + List recharges = new ArrayList<>(rechargeableItems); + while (rs.next()) { + if (ItemConstants.isRechargeable(rs.getInt("itemid"))) { + MapleShopItem starItem = new MapleShopItem((short) 1, rs.getInt("itemid"), rs.getInt("price"), rs.getInt("pitch")); + ret.addItem(starItem); + if (rechargeableItems.contains(starItem.getItemId())) { + recharges.remove(Integer.valueOf(starItem.getItemId())); + } + } else { + ret.addItem(new MapleShopItem((short) 1000, rs.getInt("itemid"), rs.getInt("price"), rs.getInt("pitch"))); + } + } + for (Integer recharge : recharges) { + ret.addItem(new MapleShopItem((short) 1000, recharge.intValue(), 0, 0)); + } + } } - rs.close(); - ps.close(); - con.close(); } catch (SQLException e) { e.printStackTrace(); } diff --git a/src/main/java/server/MapleSkillbookInformationProvider.java b/src/main/java/server/MapleSkillbookInformationProvider.java index fdc2f4ab21..444f3563dc 100644 --- a/src/main/java/server/MapleSkillbookInformationProvider.java +++ b/src/main/java/server/MapleSkillbookInformationProvider.java @@ -19,22 +19,6 @@ */ package server; -import java.io.File; -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Scanner; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import client.MapleCharacter; import provider.MapleData; import provider.MapleDataProvider; @@ -42,6 +26,16 @@ import provider.MapleDataProviderFactory; import provider.MapleDataTool; import tools.DatabaseConnection; +import java.io.File; +import java.io.IOException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + /** * * @author RonanLana @@ -165,25 +159,18 @@ public class MapleSkillbookInformationProvider { } private static void fetchSkillbooksFromReactors() { - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - - PreparedStatement ps = con.prepareStatement("SELECT itemid FROM reactordrops WHERE itemid >= ? AND itemid < ?;"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT itemid FROM reactordrops WHERE itemid >= ? AND itemid < ?;")) { ps.setInt(1, skillbookMinItemid); ps.setInt(2, skillbookMaxItemid); - ResultSet rs = ps.executeQuery(); - if (rs.isBeforeFirst()) { - while(rs.next()) { - foundSkillbooks.put(rs.getInt("itemid"), SkillBookEntry.REACTOR); + try (ResultSet rs = ps.executeQuery()) { + if (rs.isBeforeFirst()) { + while (rs.next()) { + foundSkillbooks.put(rs.getInt("itemid"), SkillBookEntry.REACTOR); + } } } - - rs.close(); - ps.close(); - - con.close(); } catch (SQLException sqle) { sqle.printStackTrace(); } diff --git a/src/main/java/server/MapleStorage.java b/src/main/java/server/MapleStorage.java index f1dd374fb8..60ff667f5f 100644 --- a/src/main/java/server/MapleStorage.java +++ b/src/main/java/server/MapleStorage.java @@ -23,29 +23,24 @@ import client.inventory.Item; import client.inventory.ItemFactory; import client.inventory.MapleInventoryType; import constants.game.GameConstants; +import net.server.audit.locks.MonitoredLockType; +import net.server.audit.locks.factory.MonitoredReentrantLockFactory; +import provider.MapleData; +import provider.MapleDataProvider; +import provider.MapleDataProviderFactory; +import provider.MapleDataTool; +import tools.DatabaseConnection; +import tools.FilePrinter; +import tools.MaplePacketCreator; +import tools.Pair; + import java.io.File; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.concurrent.locks.Lock; -import provider.MapleData; -import provider.MapleDataProvider; -import provider.MapleDataProviderFactory; -import provider.MapleDataTool; -import net.server.audit.locks.factory.MonitoredReentrantLockFactory; -import tools.DatabaseConnection; -import tools.MaplePacketCreator; -import tools.Pair; -import net.server.audit.locks.MonitoredLockType; -import tools.FilePrinter; /** * @@ -70,39 +65,34 @@ public class MapleStorage { } private static MapleStorage create(int id, int world) throws SQLException { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("INSERT INTO storages (accountid, world, slots, meso) VALUES (?, ?, 4, 0)")) { + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("INSERT INTO storages (accountid, world, slots, meso) VALUES (?, ?, 4, 0)")) { ps.setInt(1, id); ps.setInt(2, world); ps.executeUpdate(); } - con.close(); - + return loadOrCreateFromDB(id, world); } public static MapleStorage loadOrCreateFromDB(int id, int world) { - try { - MapleStorage ret; - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT storageid, slots, meso FROM storages WHERE accountid = ? AND world = ?"); + MapleStorage ret; + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT storageid, slots, meso FROM storages WHERE accountid = ? AND world = ?")) { ps.setInt(1, id); ps.setInt(2, world); - - ResultSet rs = ps.executeQuery(); - if (rs.next()) { - ret = new MapleStorage(rs.getInt("storageid"), (byte) rs.getInt("slots"), rs.getInt("meso")); - for (Pair item : ItemFactory.STORAGE.loadItems(ret.id, false)) { - ret.items.add(item.getLeft()); + + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + ret = new MapleStorage(rs.getInt("storageid"), (byte) rs.getInt("slots"), rs.getInt("meso")); + for (Pair item : ItemFactory.STORAGE.loadItems(ret.id, false)) { + ret.items.add(item.getLeft()); + } + } else { + ret = create(id, world); } - } else { - ret = create(id, world); } - - rs.close(); - ps.close(); - con.close(); - + return ret; } catch (SQLException ex) { // exceptions leading to deploy null storages found thanks to Jefe FilePrinter.printError(FilePrinter.STORAGE, ex, "SQL error occurred when trying to load storage for accountid " + id + ", world " + GameConstants.WORLD_NAMES[world]); diff --git a/src/main/java/server/expeditions/MapleExpeditionBossLog.java b/src/main/java/server/expeditions/MapleExpeditionBossLog.java index 613aec1b0e..9907e65c0e 100644 --- a/src/main/java/server/expeditions/MapleExpeditionBossLog.java +++ b/src/main/java/server/expeditions/MapleExpeditionBossLog.java @@ -19,19 +19,15 @@ */ package server.expeditions; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.util.Calendar; -import java.util.LinkedList; -import java.util.List; - import config.YamlConfig; import tools.DatabaseConnection; import tools.Pair; +import java.sql.*; +import java.util.Calendar; +import java.util.LinkedList; +import java.util.List; + /** * * @author Conrad @@ -123,18 +119,14 @@ public class MapleExpeditionBossLog { private static void resetBossLogTable(boolean week, Calendar c) { List> resetTimestamps = BossLogEntry.getBossLogResetTimestamps(c, week); - try { - Connection con = DatabaseConnection.getConnection(); - + try (Connection con = DatabaseConnection.getConnection()) { for (Pair p : resetTimestamps) { - PreparedStatement ps = con.prepareStatement("DELETE FROM " + getBossLogTable(week) + " WHERE attempttime <= ? AND bosstype LIKE ?"); - ps.setTimestamp(1, p.getLeft()); - ps.setString(2, p.getRight().name()); - ps.executeUpdate(); - ps.close(); + try (PreparedStatement ps = con.prepareStatement("DELETE FROM " + getBossLogTable(week) + " WHERE attempttime <= ? AND bosstype LIKE ?")) { + ps.setTimestamp(1, p.getLeft()); + ps.setString(2, p.getRight().name()); + ps.executeUpdate(); + } } - - con.close(); } catch (SQLException e) { e.printStackTrace(); } @@ -146,21 +138,18 @@ public class MapleExpeditionBossLog { private static int countPlayerEntries(int cid, BossLogEntry boss) { int ret_count = 0; - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps; - ps = con.prepareStatement("SELECT COUNT(*) FROM " + getBossLogTable(boss.week) + " WHERE characterid = ? AND bosstype LIKE ?"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT COUNT(*) FROM " + getBossLogTable(boss.week) + " WHERE characterid = ? AND bosstype LIKE ?")) { ps.setInt(1, cid); ps.setString(2, boss.name()); - ResultSet rs = ps.executeQuery(); - if (rs.next()) { - ret_count = rs.getInt(1); - } else { - ret_count = -1; + + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + ret_count = rs.getInt(1); + } else { + ret_count = -1; + } } - rs.close(); - ps.close(); - con.close(); return ret_count; } catch (SQLException e) { e.printStackTrace(); @@ -169,14 +158,11 @@ public class MapleExpeditionBossLog { } private static void insertPlayerEntry(int cid, BossLogEntry boss) { - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("INSERT INTO " + getBossLogTable(boss.week) + " (characterid, bosstype) VALUES (?,?)"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("INSERT INTO " + getBossLogTable(boss.week) + " (characterid, bosstype) VALUES (?,?)")) { ps.setInt(1, cid); ps.setString(2, boss.name()); ps.executeUpdate(); - ps.close(); - con.close(); } catch (SQLException e) { e.printStackTrace(); } diff --git a/src/main/java/server/life/MapleMonsterInformationProvider.java b/src/main/java/server/life/MapleMonsterInformationProvider.java index 565dc3b325..ee0956a080 100644 --- a/src/main/java/server/life/MapleMonsterInformationProvider.java +++ b/src/main/java/server/life/MapleMonsterInformationProvider.java @@ -22,18 +22,6 @@ package server.life; import config.YamlConfig; import constants.inventory.ItemConstants; -import java.io.File; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; import provider.MapleData; import provider.MapleDataProvider; import provider.MapleDataProviderFactory; @@ -43,6 +31,13 @@ import tools.DatabaseConnection; import tools.Pair; import tools.Randomizer; +import java.io.File; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.*; + public class MapleMonsterInformationProvider { // Author : LightPepsi @@ -92,45 +87,20 @@ public class MapleMonsterInformationProvider { } private void retrieveGlobal() { - PreparedStatement ps = null; - ResultSet rs = null; - Connection con = null; - - try { - con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("SELECT * FROM drop_data_global WHERE chance > 0"); - rs = ps.executeQuery(); - + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT * FROM drop_data_global WHERE chance > 0"); + ResultSet rs = ps.executeQuery()) { while (rs.next()) { - globaldrops.add( - new MonsterGlobalDropEntry( - rs.getInt("itemid"), - rs.getInt("chance"), - rs.getByte("continent"), - rs.getInt("minimum_quantity"), - rs.getInt("maximum_quantity"), - rs.getShort("questid"))); + globaldrops.add(new MonsterGlobalDropEntry( + rs.getInt("itemid"), + rs.getInt("chance"), + rs.getByte("continent"), + rs.getInt("minimum_quantity"), + rs.getInt("maximum_quantity"), + rs.getShort("questid"))); } - - rs.close(); - ps.close(); - con.close(); } catch (SQLException e) { System.err.println("Error retrieving drop" + e); - } finally { - try { - if (ps != null && !ps.isClosed()) { - ps.close(); - } - if (rs != null && !rs.isClosed()) { - rs.close(); - } - if (con != null && !con.isClosed()) { - con.close(); - } - } catch (SQLException ignore) { - ignore.printStackTrace(); - } } } @@ -182,40 +152,21 @@ public class MapleMonsterInformationProvider { return drops.get(monsterId); } final List ret = new LinkedList<>(); - - PreparedStatement ps = null; - ResultSet rs = null; - Connection con = null; - try { - con = DatabaseConnection.getConnection(); - ps = con.prepareStatement("SELECT itemid, chance, minimum_quantity, maximum_quantity, questid FROM drop_data WHERE dropperid = ?"); + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT itemid, chance, minimum_quantity, maximum_quantity, questid FROM drop_data WHERE dropperid = ?")) { ps.setInt(1, monsterId); - rs = ps.executeQuery(); - while (rs.next()) { - ret.add(new MonsterDropEntry(rs.getInt("itemid"), rs.getInt("chance"), rs.getInt("minimum_quantity"), rs.getInt("maximum_quantity"), rs.getShort("questid"))); + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + ret.add(new MonsterDropEntry(rs.getInt("itemid"), rs.getInt("chance"), rs.getInt("minimum_quantity"), rs.getInt("maximum_quantity"), rs.getShort("questid"))); + } } - - con.close(); } catch (SQLException e) { e.printStackTrace(); return ret; - } finally { - try { - if (ps != null && !ps.isClosed()) { - ps.close(); - } - if (rs != null && !rs.isClosed()) { - rs.close(); - } - if (con != null && !con.isClosed()) { - con.close(); - } - } catch (SQLException ignore) { - ignore.printStackTrace(); - return ret; - } } + drops.put(monsterId, ret); return ret; } diff --git a/src/main/java/server/life/MaplePlayerNPC.java b/src/main/java/server/life/MaplePlayerNPC.java index 86164d3a95..c37b0efa37 100644 --- a/src/main/java/server/life/MaplePlayerNPC.java +++ b/src/main/java/server/life/MaplePlayerNPC.java @@ -21,32 +21,17 @@ */ package server.life; -import config.YamlConfig; -import server.life.positioner.MaplePlayerNPCPositioner; -import server.life.positioner.MaplePlayerNPCPodium; -import java.awt.Point; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; import client.MapleCharacter; import client.MapleClient; import client.inventory.Item; import client.inventory.MapleInventoryType; +import config.YamlConfig; import constants.game.GameConstants; import net.server.Server; import net.server.channel.Channel; import net.server.world.World; +import server.life.positioner.MaplePlayerNPCPodium; +import server.life.positioner.MaplePlayerNPCPositioner; import server.maps.AbstractMapleMapObject; import server.maps.MapleMap; import server.maps.MapleMapObject; @@ -55,6 +40,12 @@ import tools.DatabaseConnection; import tools.MaplePacketCreator; import tools.Pair; +import java.awt.*; +import java.sql.*; +import java.util.List; +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; + /** * * @author XoticStory @@ -65,18 +56,18 @@ public class MaplePlayerNPC extends AbstractMapleMapObject { private static final AtomicInteger runningOverallRank = new AtomicInteger(); private static final List runningWorldRank = new ArrayList<>(); private static final Map, AtomicInteger> runningWorldJobRank = new HashMap<>(); - + private Map equips = new HashMap<>(); private int scriptId, face, hair, gender, job; private byte skin; private String name = ""; private int dir, FH, RX0, RX1, CY; private int worldRank, overallRank, worldJobRank, overallJobRank; - + static { getRunningMetadata(); } - + public MaplePlayerNPC(String name, int scriptId, int face, int hair, int gender, byte skin, Map equips, int dir, int FH, int RX0, int RX1, int CX, int CY, int oid) { this.equips = equips; this.scriptId = scriptId; @@ -91,11 +82,11 @@ public class MaplePlayerNPC extends AbstractMapleMapObject { this.RX1 = RX1; this.CY = CY; this.job = 7777; // supposed to be developer - + setPosition(new Point(CX, CY)); setObjectId(oid); } - + public MaplePlayerNPC(ResultSet rs) { try { CY = rs.getInt("cy"); @@ -109,26 +100,26 @@ public class MaplePlayerNPC extends AbstractMapleMapObject { RX0 = rs.getInt("rx0"); RX1 = rs.getInt("rx1"); scriptId = rs.getInt("scriptid"); - + worldRank = rs.getInt("worldrank"); overallRank = rs.getInt("overallrank"); worldJobRank = rs.getInt("worldjobrank"); overallJobRank = GameConstants.getOverallJobRankByScriptId(scriptId); job = rs.getInt("job"); - + setPosition(new Point(rs.getInt("x"), CY)); setObjectId(rs.getInt("id")); - - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT equippos, equipid FROM playernpcs_equip WHERE npcid = ?"); - ps.setInt(1, rs.getInt("id")); - ResultSet rs2 = ps.executeQuery(); - while (rs2.next()) { - equips.put(rs2.getShort("equippos"), rs2.getInt("equipid")); + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT equippos, equipid FROM playernpcs_equip WHERE npcid = ?")) { + ps.setInt(1, rs.getInt("id")); + + try (ResultSet rs2 = ps.executeQuery()) { + while (rs2.next()) { + equips.put(rs2.getShort("equippos"), rs2.getInt("equipid")); + } + } } - rs2.close(); - ps.close(); - con.close(); } catch (SQLException e) { e.printStackTrace(); } @@ -145,11 +136,11 @@ public class MaplePlayerNPC extends AbstractMapleMapObject { public int getJob() { return job; } - + public int getDirection() { return dir; } - + public int getFH() { return FH; } @@ -181,7 +172,7 @@ public class MaplePlayerNPC extends AbstractMapleMapObject { public int getHair() { return hair; } - + public int getGender() { return gender; } @@ -189,19 +180,19 @@ public class MaplePlayerNPC extends AbstractMapleMapObject { public int getWorldRank() { return worldRank; } - + public int getOverallRank() { return overallRank; } - + public int getWorldJobRank() { return worldJobRank; } - + public int getOverallJobRank() { return overallJobRank; } - + @Override public MapleMapObjectType getType() { return MapleMapObjectType.PLAYER_NPC; @@ -212,118 +203,101 @@ public class MaplePlayerNPC extends AbstractMapleMapObject { client.announce(MaplePacketCreator.spawnPlayerNPC(this)); client.announce(MaplePacketCreator.getPlayerNPC(this)); } - + @Override public void sendDestroyData(MapleClient client) { client.announce(MaplePacketCreator.removeNPCController(this.getObjectId())); client.announce(MaplePacketCreator.removePlayerNPC(this.getObjectId())); } - + private static void getRunningMetadata() { - try { - Connection con = DatabaseConnection.getConnection(); - + try (Connection con = DatabaseConnection.getConnection()) { getRunningOverallRanks(con); getRunningWorldRanks(con); getRunningWorldJobRanks(con); - - con.close(); } catch (SQLException e) { e.printStackTrace(); } } - - private static void getRunningOverallRanks(Connection con) throws SQLException { - PreparedStatement ps = con.prepareStatement("SELECT max(overallrank) FROM playernpcs"); - ResultSet rs = ps.executeQuery(); - if(rs.next()) { - runningOverallRank.set(rs.getInt(1) + 1); - } else { - runningOverallRank.set(1); + private static void getRunningOverallRanks(Connection con) throws SQLException { + try (PreparedStatement ps = con.prepareStatement("SELECT max(overallrank) FROM playernpcs"); + ResultSet rs = ps.executeQuery()) { + + if (rs.next()) { + runningOverallRank.set(rs.getInt(1) + 1); + } else { + runningOverallRank.set(1); + } } - - rs.close(); - ps.close(); } private static void getRunningWorldRanks(Connection con) throws SQLException { int numWorlds = Server.getInstance().getWorldsSize(); - for(int i = 0; i < numWorlds; i++) { + for (int i = 0; i < numWorlds; i++) { runningWorldRank.add(new AtomicInteger(1)); } - - PreparedStatement ps = con.prepareStatement("SELECT world, max(worldrank) FROM playernpcs GROUP BY world ORDER BY world"); - ResultSet rs = ps.executeQuery(); - while(rs.next()) { - int wid = rs.getInt(1); - if(wid < numWorlds) { - runningWorldRank.get(wid).set(rs.getInt(2) + 1); + try (PreparedStatement ps = con.prepareStatement("SELECT world, max(worldrank) FROM playernpcs GROUP BY world ORDER BY world"); + ResultSet rs = ps.executeQuery()) { + + while (rs.next()) { + int wid = rs.getInt(1); + if (wid < numWorlds) { + runningWorldRank.get(wid).set(rs.getInt(2) + 1); + } } } - - rs.close(); - ps.close(); } - - private static void getRunningWorldJobRanks(Connection con) throws SQLException { - PreparedStatement ps = con.prepareStatement("SELECT world, job, max(worldjobrank) FROM playernpcs GROUP BY world, job ORDER BY world, job"); - ResultSet rs = ps.executeQuery(); - while(rs.next()) { - runningWorldJobRank.put(new Pair<>(rs.getInt(1), rs.getInt(2)), new AtomicInteger(rs.getInt(3) + 1)); + private static void getRunningWorldJobRanks(Connection con) throws SQLException { + try (PreparedStatement ps = con.prepareStatement("SELECT world, job, max(worldjobrank) FROM playernpcs GROUP BY world, job ORDER BY world, job"); + ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + runningWorldJobRank.put(new Pair<>(rs.getInt(1), rs.getInt(2)), new AtomicInteger(rs.getInt(3) + 1)); + } } - - rs.close(); - ps.close(); } - + private static int getAndIncrementRunningWorldJobRanks(int world, int job) { AtomicInteger wjr = runningWorldJobRank.get(new Pair<>(world, job)); if(wjr == null) { wjr = new AtomicInteger(1); runningWorldJobRank.put(new Pair<>(world, job), wjr); } - + return wjr.getAndIncrement(); } - + public static boolean canSpawnPlayerNpc(String name, int mapid) { boolean ret = true; - - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT name FROM playernpcs WHERE name LIKE ? AND map = ?"); + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT name FROM playernpcs WHERE name LIKE ? AND map = ?")) { ps.setString(1, name); ps.setInt(2, mapid); - - ResultSet rs = ps.executeQuery(); - if(rs.next()) { - ret = false; + + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + ret = false; + } } - - rs.close(); - ps.close(); - con.close(); } catch (SQLException e) { e.printStackTrace(); } - + return ret; } - + public void updatePlayerNPCPosition(MapleMap map, Point newPos) { setPosition(newPos); RX0 = newPos.x + 50; RX1 = newPos.x - 50; CY = newPos.y; FH = map.getFootholds().findBelow(newPos).getId(); - - try { - Connection con = DatabaseConnection.getConnection(); - - PreparedStatement ps = con.prepareStatement("UPDATE playernpcs SET x = ?, cy = ?, fh = ?, rx0 = ?, rx1 = ? WHERE id = ?"); + + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE playernpcs SET x = ?, cy = ?, fh = ?, rx0 = ?, rx1 = ? WHERE id = ?")) { ps.setInt(1, newPos.x); ps.setInt(2, CY); ps.setInt(3, FH); @@ -331,225 +305,222 @@ public class MaplePlayerNPC extends AbstractMapleMapObject { ps.setInt(5, RX1); ps.setInt(6, getObjectId()); ps.executeUpdate(); - - ps.close(); - con.close(); } catch (SQLException e) { e.printStackTrace(); } } - + private static void fetchAvailableScriptIdsFromDb(byte branch, List list) { try { int branchLen = (branch < 26) ? 100 : 400; int branchSid = 9900000 + (branch * 100); int nextBranchSid = branchSid + branchLen; - Set usedScriptIds = new HashSet<>(); - - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT scriptid FROM playernpcs WHERE scriptid >= ? AND scriptid < ? ORDER BY scriptid"); - ps.setInt(1, branchSid); - ps.setInt(2, nextBranchSid); - - ResultSet rs = ps.executeQuery(); - while(rs.next()) { - usedScriptIds.add(rs.getInt(1)); - } - - List availables = new ArrayList<>(20); - int j = 0; - for(int i = branchSid; i < nextBranchSid; i++) { - if(!usedScriptIds.contains(i)) { - if (MaplePlayerNPCFactory.isExistentScriptid(i)) { // thanks Ark, Zein, geno, Ariel, JrCl0wn for noticing client crashes due to use of missing scriptids - availables.add(i); - j++; - if(j == 20) { - break; + List availables = new ArrayList<>(20); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT scriptid FROM playernpcs WHERE scriptid >= ? AND scriptid < ? ORDER BY scriptid")) { + ps.setInt(1, branchSid); + ps.setInt(2, nextBranchSid); + + Set usedScriptIds = new HashSet<>(); + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + usedScriptIds.add(rs.getInt(1)); + } + } + + int j = 0; + for (int i = branchSid; i < nextBranchSid; i++) { + if (!usedScriptIds.contains(i)) { + if (MaplePlayerNPCFactory.isExistentScriptid(i)) { // thanks Ark, Zein, geno, Ariel, JrCl0wn for noticing client crashes due to use of missing scriptids + availables.add(i); + j++; + + if (j == 20) { + break; + } + } else { + break; // after this point no more scriptids expected... } - } else { - break; // after this point no more scriptids expected... } } } - rs.close(); - ps.close(); - con.close(); - - for(int i = availables.size() - 1; i >= 0; i--) { + for (int i = availables.size() - 1; i >= 0; i--) { list.add(availables.get(i)); } - } catch(SQLException sqle) { + } catch (SQLException sqle) { sqle.printStackTrace(); } } - + private static int getNextScriptId(byte branch) { List availablesBranch = availablePlayerNpcScriptIds.get(branch); - + if(availablesBranch == null) { availablesBranch = new ArrayList<>(20); availablePlayerNpcScriptIds.put(branch, availablesBranch); } - + if(availablesBranch.isEmpty()) { fetchAvailableScriptIdsFromDb(branch, availablesBranch); - + if(availablesBranch.isEmpty()) { return -1; } } - + return availablesBranch.remove(availablesBranch.size() - 1); } - + private static MaplePlayerNPC createPlayerNPCInternal(MapleMap map, Point pos, MapleCharacter chr) { int mapId = map.getId(); - - if(!canSpawnPlayerNpc(chr.getName(), mapId)) { + + if (!canSpawnPlayerNpc(chr.getName(), mapId)) { return null; } - + byte branch = GameConstants.getHallOfFameBranch(chr.getJob(), mapId); - + int scriptId = getNextScriptId(branch); if (scriptId == -1) { return null; } - - if(pos == null) { - if(GameConstants.isPodiumHallOfFameMap(map.getId())) { + + if (pos == null) { + if (GameConstants.isPodiumHallOfFameMap(map.getId())) { pos = MaplePlayerNPCPodium.getNextPlayerNpcPosition(map); } else { pos = MaplePlayerNPCPositioner.getNextPlayerNpcPosition(map); } - - if(pos == null) { + + if (pos == null) { return null; } } - - if(YamlConfig.config.server.USE_DEBUG) System.out.println("GOT SID " + scriptId + " POS " + pos); - + + if (YamlConfig.config.server.USE_DEBUG) { + System.out.println("GOT SID " + scriptId + " POS " + pos); + } + int worldId = chr.getWorld(); int jobId = (chr.getJob().getId() / 100) * 100; - + MaplePlayerNPC ret; - int npcId; - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT * FROM playernpcs WHERE scriptid = ?"); - ps.setInt(1, scriptId); - ResultSet rs = ps.executeQuery(); - if (!rs.next()) { // creates new playernpc if scriptid doesn't exist - rs.close(); - ps.close(); + try (Connection con = DatabaseConnection.getConnection()) { + boolean createNew = false; + try (PreparedStatement ps = con.prepareStatement("SELECT * FROM playernpcs WHERE scriptid = ?")) { + ps.setInt(1, scriptId); - ps = con.prepareStatement("INSERT INTO playernpcs (name, hair, face, skin, gender, x, cy, world, map, scriptid, dir, fh, rx0, rx1, worldrank, overallrank, worldjobrank, job) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); - ps.setString(1, chr.getName()); - ps.setInt(2, chr.getHair()); - ps.setInt(3, chr.getFace()); - ps.setInt(4, chr.getSkinColor().getId()); - ps.setInt(5, chr.getGender()); - ps.setInt(6, pos.x); - ps.setInt(7, pos.y); - ps.setInt(8, worldId); - ps.setInt(9, mapId); - ps.setInt(10, scriptId); - ps.setInt(11, 1); // default direction - ps.setInt(12, map.getFootholds().findBelow(pos).getId()); - ps.setInt(13, pos.x + 50); - ps.setInt(14, pos.x - 50); - ps.setInt(15, runningWorldRank.get(worldId).getAndIncrement()); - ps.setInt(16, runningOverallRank.getAndIncrement()); - ps.setInt(17, getAndIncrementRunningWorldJobRanks(worldId, jobId)); - ps.setInt(18, jobId); - - ps.executeUpdate(); - - rs = ps.getGeneratedKeys(); - rs.next(); - npcId = rs.getInt(1); - rs.close(); - ps.close(); - - ps = con.prepareStatement("INSERT INTO playernpcs_equip (npcid, equipid, equippos) VALUES (?, ?, ?)"); - ps.setInt(1, npcId); - for (Item equip : chr.getInventory(MapleInventoryType.EQUIPPED)) { - int position = Math.abs(equip.getPosition()); - if ((position < 12 && position > 0) || (position > 100 && position < 112)) { - ps.setInt(2, equip.getItemId()); - ps.setInt(3, equip.getPosition()); - ps.addBatch(); + try (ResultSet rs = ps.executeQuery()) { + if (!rs.next()) { + createNew = true; } } - ps.executeBatch(); - ps.close(); + } - ps = con.prepareStatement("SELECT * FROM playernpcs WHERE id = ?"); - ps.setInt(1, npcId); - rs = ps.executeQuery(); + if (createNew) { // creates new playernpc if scriptid doesn't exist + final int npcId; + try (PreparedStatement ps = con.prepareStatement("INSERT INTO playernpcs (name, hair, face, skin, gender, x, cy, world, map, scriptid, dir, fh, rx0, rx1, worldrank, overallrank, worldjobrank, job) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) { + ps.setString(1, chr.getName()); + ps.setInt(2, chr.getHair()); + ps.setInt(3, chr.getFace()); + ps.setInt(4, chr.getSkinColor().getId()); + ps.setInt(5, chr.getGender()); + ps.setInt(6, pos.x); + ps.setInt(7, pos.y); + ps.setInt(8, worldId); + ps.setInt(9, mapId); + ps.setInt(10, scriptId); + ps.setInt(11, 1); // default direction + ps.setInt(12, map.getFootholds().findBelow(pos).getId()); + ps.setInt(13, pos.x + 50); + ps.setInt(14, pos.x - 50); + ps.setInt(15, runningWorldRank.get(worldId).getAndIncrement()); + ps.setInt(16, runningOverallRank.getAndIncrement()); + ps.setInt(17, getAndIncrementRunningWorldJobRanks(worldId, jobId)); + ps.setInt(18, jobId); + ps.executeUpdate(); - rs.next(); - ret = new MaplePlayerNPC(rs); + try (ResultSet rs = ps.getGeneratedKeys()) { + rs.next(); + npcId = rs.getInt(1); + } + } + + try (PreparedStatement ps = con.prepareStatement("INSERT INTO playernpcs_equip (npcid, equipid, equippos) VALUES (?, ?, ?)")) { + ps.setInt(1, npcId); + + for (Item equip : chr.getInventory(MapleInventoryType.EQUIPPED)) { + int position = Math.abs(equip.getPosition()); + if ((position < 12 && position > 0) || (position > 100 && position < 112)) { + ps.setInt(2, equip.getItemId()); + ps.setInt(3, equip.getPosition()); + ps.addBatch(); + } + } + ps.executeBatch(); + } + + try (PreparedStatement ps = con.prepareStatement("SELECT * FROM playernpcs WHERE id = ?")) { + ps.setInt(1, npcId); + + try (ResultSet rs = ps.executeQuery()) { + rs.next(); + ret = new MaplePlayerNPC(rs); + } + } } else { ret = null; } - rs.close(); - ps.close(); - con.close(); - return ret; } catch (SQLException e) { e.printStackTrace(); return null; } } - + private static List removePlayerNPCInternal(MapleMap map, MapleCharacter chr) { Set updateMapids = new HashSet<>(); - + List mapids = new LinkedList<>(); mapids.add(chr.getWorld()); - - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT id, map FROM playernpcs WHERE name LIKE ?" + (map != null ? " AND map = ?" : "")); - ps.setString(1, chr.getName()); - if(map != null) ps.setInt(2, map.getId()); - - ResultSet rs = ps.executeQuery(); - while(rs.next()) { - updateMapids.add(rs.getInt("map")); - int npcId = rs.getInt("id"); - - PreparedStatement ps2 = con.prepareStatement("DELETE FROM playernpcs WHERE id = ?"); - ps2.setInt(1, npcId); - ps2.executeUpdate(); - ps2.close(); - ps2 = con.prepareStatement("DELETE FROM playernpcs_equip WHERE npcid = ?"); - ps2.setInt(1, npcId); - ps2.executeUpdate(); - ps2.close(); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT id, map FROM playernpcs WHERE name LIKE ?" + (map != null ? " AND map = ?" : ""))) { + ps.setString(1, chr.getName()); + if (map != null) { + ps.setInt(2, map.getId()); + } + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + updateMapids.add(rs.getInt("map")); + int npcId = rs.getInt("id"); + + try (PreparedStatement ps2 = con.prepareStatement("DELETE FROM playernpcs WHERE id = ?")) { + ps2.setInt(1, npcId); + ps2.executeUpdate(); + } + + try (PreparedStatement ps2 = con.prepareStatement("DELETE FROM playernpcs_equip WHERE npcid = ?")) { + ps2.setInt(1, npcId); + ps2.executeUpdate(); + } + } } - - rs.close(); - ps.close(); - con.close(); } catch (SQLException e) { e.printStackTrace(); } - - for(Integer i : updateMapids) { + + for (Integer i : updateMapids) { mapids.add(i); } - + return mapids; } - + private static synchronized Pair> processPlayerNPCInternal(MapleMap map, Point pos, MapleCharacter chr, boolean create) { if(create) { return new Pair<>(createPlayerNPCInternal(map, pos, chr), null); @@ -557,52 +528,52 @@ public class MaplePlayerNPC extends AbstractMapleMapObject { return new Pair<>(null, removePlayerNPCInternal(map, chr)); } } - + public static boolean spawnPlayerNPC(int mapid, MapleCharacter chr) { return spawnPlayerNPC(mapid, null, chr); } - + public static boolean spawnPlayerNPC(int mapid, Point pos, MapleCharacter chr) { if(chr == null) return false; - + MaplePlayerNPC pn = processPlayerNPCInternal(chr.getClient().getChannelServer().getMapFactory().getMap(mapid), pos, chr, true).getLeft(); if(pn != null) { for (Channel channel : Server.getInstance().getChannelsFromWorld(chr.getWorld())) { MapleMap m = channel.getMapFactory().getMap(mapid); - + m.addPlayerNPCMapObject(pn); m.broadcastMessage(MaplePacketCreator.spawnPlayerNPC(pn)); m.broadcastMessage(MaplePacketCreator.getPlayerNPC(pn)); } - + return true; } else { return false; } } - + private static MaplePlayerNPC getPlayerNPCFromWorldMap(String name, int world, int map) { World wserv = Server.getInstance().getWorld(world); for(MapleMapObject pnpcObj : wserv.getChannel(1).getMapFactory().getMap(map).getMapObjectsInRange(new Point(0, 0), Double.POSITIVE_INFINITY, Arrays.asList(MapleMapObjectType.PLAYER_NPC))) { MaplePlayerNPC pn = (MaplePlayerNPC) pnpcObj; - + if(name.contentEquals(pn.getName()) && pn.getScriptId() < 9977777) { return pn; } } - + return null; } - + public static void removePlayerNPC(MapleCharacter chr) { if(chr == null) return; - + List updateMapids = processPlayerNPCInternal(null, null, chr, false).getRight(); int worldid = updateMapids.remove(0); - + for (Integer mapid : updateMapids) { MaplePlayerNPC pn = getPlayerNPCFromWorldMap(chr.getName(), worldid, mapid); - + if(pn != null) { for (Channel channel : Server.getInstance().getChannelsFromWorld(worldid)) { MapleMap m = channel.getMapFactory().getMap(mapid); @@ -614,37 +585,36 @@ public class MaplePlayerNPC extends AbstractMapleMapObject { } } } - + public static void multicastSpawnPlayerNPC(int mapid, int world) { World wserv = Server.getInstance().getWorld(world); if (wserv == null) return; - + MapleClient c = new MapleClient(null, null, null); // mock client c.setWorld(world); c.setChannel(1); - + for(MapleCharacter mc : wserv.loadAndGetAllCharactersView()) { mc.setClient(c); spawnPlayerNPC(mapid, mc); } } - + public static void removeAllPlayerNPC() { - try { - Connection con = DatabaseConnection.getConnection(); - - PreparedStatement ps = con.prepareStatement("SELECT DISTINCT world, map FROM playernpcs"); - ResultSet rs = ps.executeQuery(); - + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT DISTINCT world, map FROM playernpcs"); + ResultSet rs = ps.executeQuery()) { int wsize = Server.getInstance().getWorldsSize(); - while(rs.next()) { + while (rs.next()) { int world = rs.getInt("world"), map = rs.getInt("map"); - if(world >= wsize) continue; - + if (world >= wsize) { + continue; + } + for (Channel channel : Server.getInstance().getChannelsFromWorld(world)) { MapleMap m = channel.getMapFactory().getMap(map); - - for(MapleMapObject pnpcObj : m.getMapObjectsInRange(new Point(0, 0), Double.POSITIVE_INFINITY, Arrays.asList(MapleMapObjectType.PLAYER_NPC))) { + + for (MapleMapObject pnpcObj : m.getMapObjectsInRange(new Point(0, 0), Double.POSITIVE_INFINITY, Arrays.asList(MapleMapObjectType.PLAYER_NPC))) { MaplePlayerNPC pn = (MaplePlayerNPC) pnpcObj; m.removeMapObject(pnpcObj); m.broadcastMessage(MaplePacketCreator.removeNPCController(pn.getObjectId())); @@ -652,27 +622,22 @@ public class MaplePlayerNPC extends AbstractMapleMapObject { } } } - - rs.close(); - ps.close(); - - ps = con.prepareStatement("DELETE FROM playernpcs"); - ps.executeUpdate(); - ps.close(); - ps = con.prepareStatement("DELETE FROM playernpcs_equip"); - ps.executeUpdate(); - ps.close(); - - ps = con.prepareStatement("DELETE FROM playernpcs_field"); - ps.executeUpdate(); - ps.close(); - - for(World w : Server.getInstance().getWorlds()) { + try (PreparedStatement ps2 = con.prepareStatement("DELETE FROM playernpcs")) { + ps2.executeUpdate(); + } + + try (PreparedStatement ps2 = con.prepareStatement("DELETE FROM playernpcs_equip")) { + ps2.executeUpdate(); + } + + try (PreparedStatement ps2 = con.prepareStatement("DELETE FROM playernpcs_field")) { + ps2.executeUpdate(); + } + + for (World w : Server.getInstance().getWorlds()) { w.resetPlayerNpcMapData(); } - - con.close(); } catch (SQLException e) { e.printStackTrace(); } diff --git a/src/main/java/server/maps/MapleHiredMerchant.java b/src/main/java/server/maps/MapleHiredMerchant.java index c87619d310..a9ff095737 100644 --- a/src/main/java/server/maps/MapleHiredMerchant.java +++ b/src/main/java/server/maps/MapleHiredMerchant.java @@ -31,6 +31,15 @@ import client.inventory.manipulator.MapleInventoryManipulator; import client.inventory.manipulator.MapleKarmaManipulator; import client.processor.npc.FredrickProcessor; import config.YamlConfig; +import net.server.Server; +import net.server.audit.locks.MonitoredLockType; +import net.server.audit.locks.factory.MonitoredReentrantLockFactory; +import server.MapleItemInformationProvider; +import server.MapleTrade; +import tools.DatabaseConnection; +import tools.MaplePacketCreator; +import tools.Pair; + import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -41,14 +50,6 @@ import java.util.LinkedList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Lock; -import net.server.audit.locks.factory.MonitoredReentrantLockFactory; -import net.server.Server; -import server.MapleItemInformationProvider; -import tools.DatabaseConnection; -import tools.MaplePacketCreator; -import tools.Pair; -import net.server.audit.locks.MonitoredLockType; -import server.MapleTrade; /** * @@ -294,9 +295,7 @@ public class MapleHiredMerchant extends AbstractMapleMapObject { if (owner != null) { owner.addMerchantMesos(price); } else { - try { - Connection con = DatabaseConnection.getConnection(); - + try (Connection con = DatabaseConnection.getConnection()) { long merchantMesos = 0; try (PreparedStatement ps = con.prepareStatement("SELECT MerchantMesos FROM characters WHERE id = ?")) { ps.setInt(1, ownerId); @@ -313,8 +312,6 @@ public class MapleHiredMerchant extends AbstractMapleMapObject { ps.setInt(2, ownerId); ps.executeUpdate(); } - - con.close(); } catch (Exception e) { e.printStackTrace(); } @@ -350,23 +347,23 @@ public class MapleHiredMerchant extends AbstractMapleMapObject { //Server.getInstance().getChannel(world, channel).removeHiredMerchant(ownerId); map.broadcastMessage(MaplePacketCreator.removeHiredMerchantBox(getOwnerId())); map.removeMapObject(this); - + MapleCharacter owner = Server.getInstance().getWorld(world).getPlayerStorage().getCharacterById(ownerId); - + visitorLock.lock(); try { setOpen(false); removeAllVisitors(); - - if(owner != null && owner.isLoggedinWorld() && this == owner.getHiredMerchant()) { + + if (owner != null && owner.isLoggedinWorld() && this == owner.getHiredMerchant()) { closeOwnerMerchant(owner); } } finally { visitorLock.unlock(); } - + Server.getInstance().getWorld(world).unregisterHiredMerchant(this); - + try { saveItems(true); synchronized (items) { @@ -375,22 +372,18 @@ public class MapleHiredMerchant extends AbstractMapleMapObject { } catch (SQLException ex) { ex.printStackTrace(); } - - MapleCharacter player = Server.getInstance().getWorld(world).getPlayerStorage().getCharacterById(ownerId); - if(player != null) { - player.setHasMerchant(false); - } else { - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("UPDATE characters SET HasMerchant = 0 WHERE id = ?", PreparedStatement.RETURN_GENERATED_KEYS); - ps.setInt(1, ownerId); - ps.executeUpdate(); - ps.close(); - con.close(); - } catch (SQLException ex) { - ex.printStackTrace(); - } + MapleCharacter player = Server.getInstance().getWorld(world).getPlayerStorage().getCharacterById(ownerId); + if (player != null) { + player.setHasMerchant(false); + } else { + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE characters SET HasMerchant = 0 WHERE id = ?", PreparedStatement.RETURN_GENERATED_KEYS)) { + ps.setInt(1, ownerId); + ps.executeUpdate(); + } catch (SQLException ex) { + ex.printStackTrace(); + } } map = null; @@ -407,7 +400,7 @@ public class MapleHiredMerchant extends AbstractMapleMapObject { map.removeMapObject(this); map.broadcastMessage(MaplePacketCreator.removeHiredMerchantBox(ownerId)); c.getChannelServer().removeHiredMerchant(ownerId); - + this.removeAllVisitors(); this.removeOwner(c.getPlayer()); @@ -415,7 +408,7 @@ public class MapleHiredMerchant extends AbstractMapleMapObject { List copyItems = getItems(); if (check(c.getPlayer(), copyItems) && !timeout) { for (MaplePlayerShopItem mpsi : copyItems) { - if(mpsi.isExist()) { + if (mpsi.isExist()) { if (mpsi.getItem().getInventoryType().equals(MapleInventoryType.EQUIP)) { MapleInventoryManipulator.addFromDrop(c, mpsi.getItem(), false); } else { @@ -434,20 +427,19 @@ public class MapleHiredMerchant extends AbstractMapleMapObject { } catch (Exception e) { e.printStackTrace(); } - + // thanks Rohenn for noticing a possible dupe scenario on closing shop MapleCharacter player = c.getWorldServer().getPlayerStorage().getCharacterById(ownerId); - if(player != null) { - player.setHasMerchant(false); + if (player != null) { + player.setHasMerchant(false); } else { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("UPDATE characters SET HasMerchant = 0 WHERE id = ?", PreparedStatement.RETURN_GENERATED_KEYS)) { - ps.setInt(1, ownerId); - ps.executeUpdate(); - } - con.close(); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("UPDATE characters SET HasMerchant = 0 WHERE id = ?", PreparedStatement.RETURN_GENERATED_KEYS)) { + ps.setInt(1, ownerId); + ps.executeUpdate(); + } } - + if (YamlConfig.config.server.USE_ENFORCE_MERCHANT_SAVE) { c.getPlayer().saveCharToDB(false); } @@ -458,7 +450,7 @@ public class MapleHiredMerchant extends AbstractMapleMapObject { } catch (Exception e) { e.printStackTrace(); } - + Server.getInstance().getWorld(world).unregisterHiredMerchant(this); } @@ -646,10 +638,10 @@ public class MapleHiredMerchant extends AbstractMapleMapObject { bundles.add(newBundle); } } - - Connection con = DatabaseConnection.getConnection(); - ItemFactory.MERCHANT.saveItems(itemsWithType, bundles, this.ownerId, con); - con.close(); + + try (Connection con = DatabaseConnection.getConnection()) { + ItemFactory.MERCHANT.saveItems(itemsWithType, bundles, this.ownerId, con); + } FredrickProcessor.insertFredrickLog(this.ownerId); } diff --git a/src/main/java/server/maps/MapleMapFactory.java b/src/main/java/server/maps/MapleMapFactory.java index 660a290115..3736c3b3b9 100644 --- a/src/main/java/server/maps/MapleMapFactory.java +++ b/src/main/java/server/maps/MapleMapFactory.java @@ -21,8 +21,17 @@ */ package server.maps; -import java.awt.Point; -import java.awt.Rectangle; +import provider.MapleData; +import provider.MapleDataProvider; +import provider.MapleDataProviderFactory; +import provider.MapleDataTool; +import scripting.event.EventInstanceManager; +import server.life.*; +import server.partyquest.GuardianSpawnPoint; +import tools.DatabaseConnection; +import tools.StringUtil; + +import java.awt.*; import java.io.File; import java.sql.Connection; import java.sql.PreparedStatement; @@ -31,19 +40,6 @@ import java.sql.SQLException; import java.util.HashMap; import java.util.LinkedList; import java.util.List; -import provider.MapleData; -import provider.MapleDataProvider; -import provider.MapleDataProviderFactory; -import provider.MapleDataTool; -import server.life.AbstractLoadedMapleLife; -import server.life.MapleLifeFactory; -import server.life.MapleMonster; -import server.life.MaplePlayerNPC; -import server.life.MaplePlayerNPCFactory; -import scripting.event.EventInstanceManager; -import server.partyquest.GuardianSpawnPoint; -import tools.DatabaseConnection; -import tools.StringUtil; public class MapleMapFactory { @@ -84,33 +80,29 @@ public class MapleMapFactory { } private static void loadLifeFromDb(MapleMap map) { - try { - Connection con = DatabaseConnection.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT * FROM plife WHERE map = ? and world = ?"); + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT * FROM plife WHERE map = ? and world = ?")) { ps.setInt(1, map.getId()); ps.setInt(2, map.getWorld()); - ResultSet rs = ps.executeQuery(); - while (rs.next()) { - int id = rs.getInt("life"); - String type = rs.getString("type"); - int cy = rs.getInt("cy"); - int f = rs.getInt("f"); - int fh = rs.getInt("fh"); - int rx0 = rs.getInt("rx0"); - int rx1 = rs.getInt("rx1"); - int x = rs.getInt("x"); - int y = rs.getInt("y"); - int hide = rs.getInt("hide"); - int mobTime = rs.getInt("mobtime"); - int team = rs.getInt("team"); + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + int id = rs.getInt("life"); + String type = rs.getString("type"); + int cy = rs.getInt("cy"); + int f = rs.getInt("f"); + int fh = rs.getInt("fh"); + int rx0 = rs.getInt("rx0"); + int rx1 = rs.getInt("rx1"); + int x = rs.getInt("x"); + int y = rs.getInt("y"); + int hide = rs.getInt("hide"); + int mobTime = rs.getInt("mobtime"); + int team = rs.getInt("team"); - loadLifeRaw(map, id, type, cy, f, fh, rx0, rx1, x, y, hide, mobTime, team); + loadLifeRaw(map, id, type, cy, f, fh, rx0, rx1, x, y, hide, mobTime, team); + } } - - rs.close(); - ps.close(); - con.close(); } catch (SQLException sqle) { sqle.printStackTrace(); } @@ -243,18 +235,16 @@ public class MapleMapFactory { map.setSeats(seats); } if (event == null) { - try { - Connection con = DatabaseConnection.getConnection(); - try (PreparedStatement ps = con.prepareStatement("SELECT * FROM playernpcs WHERE map = ? AND world = ?")) { - ps.setInt(1, mapid); - ps.setInt(2, world); - try (ResultSet rs = ps.executeQuery()) { - while (rs.next()) { - map.addPlayerNPCMapObject(new MaplePlayerNPC(rs)); - } + try (Connection con = DatabaseConnection.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT * FROM playernpcs WHERE map = ? AND world = ?")) { + ps.setInt(1, mapid); + ps.setInt(2, world); + + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + map.addPlayerNPCMapObject(new MaplePlayerNPC(rs)); } } - con.close(); } catch (SQLException e) { e.printStackTrace(); }