Ver código fonte

BETA: Reworking Connection closing by using try-with-resource:
* Using Statement instead !PreparedStatement where parameters are not required.
* Minor change in formatter settings to give proper format to try-with-resource statement.
* Fixed many resource leaks.

Zoey76 13 anos atrás
pai
commit
2d60198ee1
100 arquivos alterados com 2368 adições e 4893 exclusões
  1. 2 2
      L2J_Server_BETA/.settings/org.eclipse.jdt.core.prefs
  2. 1 1
      L2J_Server_BETA/.settings/org.eclipse.jdt.ui.prefs
  3. 3 1
      L2J_Server_BETA/java/com/l2jserver/L2DatabaseFactory.java
  4. 10 17
      L2J_Server_BETA/java/com/l2jserver/gameserver/LoginServerThread.java
  5. 60 99
      L2J_Server_BETA/java/com/l2jserver/gameserver/SevenSigns.java
  6. 112 133
      L2J_Server_BETA/java/com/l2jserver/gameserver/SevenSignsFestival.java
  7. 68 115
      L2J_Server_BETA/java/com/l2jserver/gameserver/TradeController.java
  8. 5 13
      L2J_Server_BETA/java/com/l2jserver/gameserver/cache/CrestCache.java
  9. 1 1
      L2J_Server_BETA/java/com/l2jserver/gameserver/cache/HtmCache.java
  10. 38 72
      L2J_Server_BETA/java/com/l2jserver/gameserver/communitybbs/BB/Forum.java
  11. 38 70
      L2J_Server_BETA/java/com/l2jserver/gameserver/communitybbs/BB/Post.java
  12. 17 36
      L2J_Server_BETA/java/com/l2jserver/gameserver/communitybbs/BB/Topic.java
  13. 7 16
      L2J_Server_BETA/java/com/l2jserver/gameserver/communitybbs/Manager/ForumsBBSManager.java
  14. 35 76
      L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/CharNameTable.java
  15. 93 132
      L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/CharSummonTable.java
  16. 4 12
      L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/CharTemplateTable.java
  17. 41 81
      L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/ClanTable.java
  18. 52 73
      L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/HelperBuffTable.java
  19. 5 18
      L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/HerbDropTable.java
  20. 2 9
      L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/ItemTable.java
  21. 20 28
      L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/LevelUpData.java
  22. 51 71
      L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/NpcBufferTable.java
  23. 59 114
      L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/NpcTable.java
  24. 57 74
      L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/OfflineTradersTable.java
  25. 13 22
      L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/PetNameTable.java
  26. 8 35
      L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/SpawnTable.java
  27. 50 53
      L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/SummonItemsData.java
  28. 29 43
      L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/SummonSkillsTable.java
  29. 32 47
      L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/TeleportLocationTable.java
  30. 0 1
      L2J_Server_BETA/java/com/l2jserver/gameserver/idfactory/BitSetIDFactory.java
  31. 1 7
      L2J_Server_BETA/java/com/l2jserver/gameserver/idfactory/CompactionIDFactory.java
  32. 32 56
      L2J_Server_BETA/java/com/l2jserver/gameserver/idfactory/IdFactory.java
  33. 1 7
      L2J_Server_BETA/java/com/l2jserver/gameserver/idfactory/StackIDFactory.java
  34. 18 44
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/AirShipManager.java
  35. 2 14
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/AuctionManager.java
  36. 1 7
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/CHSiegeManager.java
  37. 2 15
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/CastleManager.java
  38. 1 8
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/CastleManorManager.java
  39. 1 7
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/ClanHallManager.java
  40. 1 9
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/CoupleManager.java
  41. 45 79
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/CursedWeaponsManager.java
  42. 1 8
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/DimensionalRiftManager.java
  43. 1 8
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/FortManager.java
  44. 1 7
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/FortSiegeGuardManager.java
  45. 1 7
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/FortSiegeManager.java
  46. 5 44
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/FourSepulchersManager.java
  47. 13 29
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/GlobalVariablesManager.java
  48. 71 92
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/GrandBossManager.java
  49. 1 7
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/HellboundManager.java
  50. 4 21
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/InstanceManager.java
  51. 16 29
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/ItemAuctionManager.java
  52. 5 28
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/ItemsOnGroundManager.java
  53. 12 73
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/MailManager.java
  54. 1 7
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/MercTicketManager.java
  55. 3 21
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/RaidBossPointsManager.java
  56. 9 42
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/RaidBossSpawnManager.java
  57. 4 28
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/SiegeGuardManager.java
  58. 1 7
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/SiegeManager.java
  59. 14 52
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/TerritoryWarManager.java
  60. 91 142
      L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/games/Lottery.java
  61. 13 20
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/AutoChatHandler.java
  62. 1 9
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/AutoSpawnHandler.java
  63. 14 23
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/BlockList.java
  64. 3 16
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/CursedWeapon.java
  65. 153 300
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/L2Clan.java
  66. 3 23
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/L2ClanMember.java
  67. 19 41
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/L2ContactList.java
  68. 1 7
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/L2TradeList.java
  69. 6 33
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/L2UIKeysSettings.java
  70. 3 23
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/MacroList.java
  71. 3 23
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/ShortCuts.java
  72. 98 351
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/actor/instance/L2PcInstance.java
  73. 40 76
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/actor/instance/L2PetInstance.java
  74. 75 89
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/actor/instance/L2ServitorInstance.java
  75. 61 120
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/entity/Auction.java
  76. 84 207
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/entity/Castle.java
  77. 4 24
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/entity/ClanHall.java
  78. 4 30
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/entity/Couple.java
  79. 15 104
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/entity/Fort.java
  80. 29 56
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/entity/FortSiege.java
  81. 9 63
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/entity/Hero.java
  82. 45 80
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/entity/Siege.java
  83. 2 9
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/entity/clanhall/AuctionableHall.java
  84. 35 53
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/entity/clanhall/ClanHallSiegeEngine.java
  85. 2 9
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/entity/clanhall/SiegableHall.java
  86. 15 32
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/itemauction/ItemAuction.java
  87. 17 31
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/itemauction/ItemAuctionInstance.java
  88. 23 31
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/itemcontainer/Inventory.java
  89. 20 28
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/itemcontainer/ItemContainer.java
  90. 18 27
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/itemcontainer/Mail.java
  91. 15 23
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/itemcontainer/PcInventory.java
  92. 51 101
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/items/instance/L2ItemInstance.java
  93. 68 166
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/olympiad/Olympiad.java
  94. 2 9
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/olympiad/OlympiadGameNormal.java
  95. 76 148
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/quest/Quest.java
  96. 13 33
      L2J_Server_BETA/java/com/l2jserver/gameserver/model/quest/QuestState.java
  97. 42 67
      L2J_Server_BETA/java/com/l2jserver/gameserver/network/L2GameClient.java
  98. 4 11
      L2J_Server_BETA/java/com/l2jserver/gameserver/network/clientpackets/RequestAnswerFriendInvite.java
  99. 7 15
      L2J_Server_BETA/java/com/l2jserver/gameserver/network/clientpackets/RequestDestroyItem.java
  100. 3 12
      L2J_Server_BETA/java/com/l2jserver/gameserver/network/clientpackets/RequestFriendDel.java

+ 2 - 2
L2J_Server_BETA/.settings/org.eclipse.jdt.core.prefs

@@ -124,7 +124,7 @@ org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=48
 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=0
 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=0
 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=0
-org.eclipse.jdt.core.formatter.alignment_for_assignment=0
+org.eclipse.jdt.core.formatter.alignment_for_assignment=4
 org.eclipse.jdt.core.formatter.alignment_for_binary_expression=0
 org.eclipse.jdt.core.formatter.alignment_for_compact_if=0
 org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=0
@@ -134,7 +134,7 @@ org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0
 org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16
 org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=0
 org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=0
-org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=53
+org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=81
 org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=0
 org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=0
 org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=48

+ 1 - 1
L2J_Server_BETA/.settings/org.eclipse.jdt.ui.prefs

@@ -52,7 +52,7 @@ cleanup.use_this_for_non_static_method_access_only_if_necessary=true
 cleanup_profile=_L2J Clean Up v0.2
 cleanup_settings_version=2
 eclipse.preferences.version=1
-formatter_profile=_L2J Formatter v0.1
+formatter_profile=_L2J Formatter v0.3
 formatter_settings_version=12
 org.eclipse.jdt.ui.exception.name=e
 org.eclipse.jdt.ui.gettersetter.use.is=true

+ 3 - 1
L2J_Server_BETA/java/com/l2jserver/L2DatabaseFactory.java

@@ -328,8 +328,10 @@ public class L2DatabaseFactory
 	
 	/**
 	 * Close the connection.
-	 * @param con the con
+	 * @param con the con the connection
+	 * @deprecated now database connections are closed using try-with-resoruce.
 	 */
+	@Deprecated
 	public static void close(Connection con)
 	{
 		if (con == null)

+ 10 - 17
L2J_Server_BETA/java/com/l2jserver/gameserver/LoginServerThread.java

@@ -628,24 +628,21 @@ public class LoginServerThread extends Thread
 	 */
 	private void getCharsOnServer(String account)
 	{
-		Connection con = null;
+		
 		int chars = 0;
 		List<Long> charToDel = new ArrayList<>();
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement("SELECT deletetime FROM characters WHERE account_name=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement("SELECT deletetime FROM characters WHERE account_name=?"))
+			ps.setString(1, account);
+			try (ResultSet rs = ps.executeQuery())
 			{
-				ps.setString(1, account);
-				try (ResultSet rs = ps.executeQuery())
+				while (rs.next())
 				{
-					while (rs.next())
-					{
-						chars++;
-						long delTime = rs.getLong("deletetime");
-						if (delTime != 0)
-							charToDel.add(delTime);
-					}
+					chars++;
+					long delTime = rs.getLong("deletetime");
+					if (delTime != 0)
+						charToDel.add(delTime);
 				}
 			}
 		}
@@ -653,10 +650,6 @@ public class LoginServerThread extends Thread
 		{
 			_log.log(Level.WARNING, "Exception: getCharsOnServer: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
 		ReplyCharacters rec = new ReplyCharacters(account, chars, charToDel);
 		try

+ 60 - 99
L2J_Server_BETA/java/com/l2jserver/gameserver/SevenSigns.java

@@ -747,10 +747,8 @@ public class SevenSigns
 	 */
 	protected void restoreSevenSignsData()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			try (Statement s = con.createStatement();
 				ResultSet rs = s.executeQuery(LOAD_DATA))
 			{
@@ -776,6 +774,7 @@ public class SevenSigns
 					_signsPlayerData.put(charObjId, sevenDat);
 				}
 			}
+			
 			try (Statement s = con.createStatement();
 				ResultSet rs = s.executeQuery(LOAD_STATUS))
 			{
@@ -810,11 +809,6 @@ public class SevenSigns
 		{
 			_log.log(Level.SEVERE, "SevenSigns: Unable to load Seven Signs data from database: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
-		
 		// Festival data is loaded now after the Seven Signs engine data.
 	}
 	
@@ -827,28 +821,24 @@ public class SevenSigns
 		if (Config.DEBUG)
 			_log.info("SevenSigns: Saving data to disk.");
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement(UPDATE_PLAYER))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement(UPDATE_PLAYER))
+			for (StatsSet sevenDat : _signsPlayerData.values())
 			{
-				for (StatsSet sevenDat : _signsPlayerData.values())
+				ps.setString(1, sevenDat.getString("cabal"));
+				ps.setInt(2, sevenDat.getInteger("seal"));
+				ps.setInt(3, sevenDat.getInteger("red_stones"));
+				ps.setInt(4, sevenDat.getInteger("green_stones"));
+				ps.setInt(5, sevenDat.getInteger("blue_stones"));
+				ps.setDouble(6, sevenDat.getDouble("ancient_adena_amount"));
+				ps.setDouble(7, sevenDat.getDouble("contribution_score"));
+				ps.setInt(8, sevenDat.getInteger("charId"));
+				ps.execute();
+				ps.clearParameters();
+				if (Config.DEBUG)
 				{
-					ps.setString(1, sevenDat.getString("cabal"));
-					ps.setInt(2, sevenDat.getInteger("seal"));
-					ps.setInt(3, sevenDat.getInteger("red_stones"));
-					ps.setInt(4, sevenDat.getInteger("green_stones"));
-					ps.setInt(5, sevenDat.getInteger("blue_stones"));
-					ps.setDouble(6, sevenDat.getDouble("ancient_adena_amount"));
-					ps.setDouble(7, sevenDat.getDouble("contribution_score"));
-					ps.setInt(8, sevenDat.getInteger("charId"));
-					ps.execute();
-					ps.clearParameters();
-					if (Config.DEBUG)
-					{
-						_log.info("SevenSigns: Updated data in database for char ID " + sevenDat.getInteger("charId") + " (" + sevenDat.getString("cabal") + ")");
-					}
+					_log.info("SevenSigns: Updated data in database for char ID " + sevenDat.getInteger("charId") + " (" + sevenDat.getString("cabal") + ")");
 				}
 			}
 		}
@@ -856,10 +846,6 @@ public class SevenSigns
 		{
 			_log.log(Level.SEVERE, "SevenSigns: Unable to save data to database: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public final void saveSevenSignsData(int objectId)
@@ -868,67 +854,55 @@ public class SevenSigns
 		if (sevenDat == null)
 			return;
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement(UPDATE_PLAYER))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement(UPDATE_PLAYER))
-			{
-				ps.setString(1, sevenDat.getString("cabal"));
-				ps.setInt(2, sevenDat.getInteger("seal"));
-				ps.setInt(3, sevenDat.getInteger("red_stones"));
-				ps.setInt(4, sevenDat.getInteger("green_stones"));
-				ps.setInt(5, sevenDat.getInteger("blue_stones"));
-				ps.setDouble(6, sevenDat.getDouble("ancient_adena_amount"));
-				ps.setDouble(7, sevenDat.getDouble("contribution_score"));
-				ps.setInt(8, sevenDat.getInteger("charId"));
-				ps.execute();
-			}
+			ps.setString(1, sevenDat.getString("cabal"));
+			ps.setInt(2, sevenDat.getInteger("seal"));
+			ps.setInt(3, sevenDat.getInteger("red_stones"));
+			ps.setInt(4, sevenDat.getInteger("green_stones"));
+			ps.setInt(5, sevenDat.getInteger("blue_stones"));
+			ps.setDouble(6, sevenDat.getDouble("ancient_adena_amount"));
+			ps.setDouble(7, sevenDat.getDouble("contribution_score"));
+			ps.setInt(8, sevenDat.getInteger("charId"));
+			ps.execute();
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.SEVERE, "SevenSigns: Unable to save data to database: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public final void saveSevenSignsStatus()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement(UPDATE_STATUS))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement(UPDATE_STATUS))
+			ps.setInt(1, _currentCycle);
+			ps.setInt(2, _activePeriod);
+			ps.setInt(3, _previousWinner);
+			ps.setDouble(4, _dawnStoneScore);
+			ps.setInt(5, _dawnFestivalScore);
+			ps.setDouble(6, _duskStoneScore);
+			ps.setInt(7, _duskFestivalScore);
+			ps.setInt(8, _signsSealOwners.get(SEAL_AVARICE));
+			ps.setInt(9, _signsSealOwners.get(SEAL_GNOSIS));
+			ps.setInt(10, _signsSealOwners.get(SEAL_STRIFE));
+			ps.setInt(11, _signsDawnSealTotals.get(SEAL_AVARICE));
+			ps.setInt(12, _signsDawnSealTotals.get(SEAL_GNOSIS));
+			ps.setInt(13, _signsDawnSealTotals.get(SEAL_STRIFE));
+			ps.setInt(14, _signsDuskSealTotals.get(SEAL_AVARICE));
+			ps.setInt(15, _signsDuskSealTotals.get(SEAL_GNOSIS));
+			ps.setInt(16, _signsDuskSealTotals.get(SEAL_STRIFE));
+			ps.setInt(17, SevenSignsFestival.getInstance().getCurrentFestivalCycle());
+			
+			for (int i = 0; i < SevenSignsFestival.FESTIVAL_COUNT; i++)
 			{
-				ps.setInt(1, _currentCycle);
-				ps.setInt(2, _activePeriod);
-				ps.setInt(3, _previousWinner);
-				ps.setDouble(4, _dawnStoneScore);
-				ps.setInt(5, _dawnFestivalScore);
-				ps.setDouble(6, _duskStoneScore);
-				ps.setInt(7, _duskFestivalScore);
-				ps.setInt(8, _signsSealOwners.get(SEAL_AVARICE));
-				ps.setInt(9, _signsSealOwners.get(SEAL_GNOSIS));
-				ps.setInt(10, _signsSealOwners.get(SEAL_STRIFE));
-				ps.setInt(11, _signsDawnSealTotals.get(SEAL_AVARICE));
-				ps.setInt(12, _signsDawnSealTotals.get(SEAL_GNOSIS));
-				ps.setInt(13, _signsDawnSealTotals.get(SEAL_STRIFE));
-				ps.setInt(14, _signsDuskSealTotals.get(SEAL_AVARICE));
-				ps.setInt(15, _signsDuskSealTotals.get(SEAL_GNOSIS));
-				ps.setInt(16, _signsDuskSealTotals.get(SEAL_STRIFE));
-				ps.setInt(17, SevenSignsFestival.getInstance().getCurrentFestivalCycle());
-				
-				for (int i = 0; i < SevenSignsFestival.FESTIVAL_COUNT; i++)
-				{
-					ps.setInt(18 + i, SevenSignsFestival.getInstance().getAccumulatedBonus(i));
-				}
-				_lastSave = Calendar.getInstance();
-				ps.setLong(18 + SevenSignsFestival.FESTIVAL_COUNT, _lastSave.getTimeInMillis());
-				ps.execute();
+				ps.setInt(18 + i, SevenSignsFestival.getInstance().getAccumulatedBonus(i));
 			}
+			_lastSave = Calendar.getInstance();
+			ps.setLong(18 + SevenSignsFestival.FESTIVAL_COUNT, _lastSave.getTimeInMillis());
+			ps.execute();
 			if (Config.DEBUG)
 				_log.info("SevenSigns: Updated data in database.");
 		}
@@ -936,10 +910,6 @@ public class SevenSigns
 		{
 			_log.log(Level.SEVERE, "SevenSigns: Unable to save data to database: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -1003,30 +973,21 @@ public class SevenSigns
 			_signsPlayerData.put(objectId, currPlayerData);
 			
 			// Update data in database, as we have a new player signing up.
-			Connection con = null;
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+				PreparedStatement ps = con.prepareStatement(INSERT_PLAYER))
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
-				try (PreparedStatement ps = con.prepareStatement(INSERT_PLAYER))
-				{
-					ps.setInt(1, objectId);
-					ps.setString(2, getCabalShortName(chosenCabal));
-					ps.setInt(3, chosenSeal);
-					ps.execute();
-				}
+				ps.setInt(1, objectId);
+				ps.setString(2, getCabalShortName(chosenCabal));
+				ps.setInt(3, chosenSeal);
+				ps.execute();
 				
 				if (Config.DEBUG)
-					_log.info("SevenSigns: Inserted data in DB for char ID " + currPlayerData.getInteger("charId") + " ("
-							+ currPlayerData.getString("cabal") + ")");
+					_log.info("SevenSigns: Inserted data in DB for char ID " + currPlayerData.getInteger("charId") + " (" + currPlayerData.getString("cabal") + ")");
 			}
 			catch (SQLException e)
 			{
 				_log.log(Level.SEVERE, "SevenSigns: Failed to save data: " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 		}
 		
 		// Increasing Seal total score for the player chosen Seal.

+ 112 - 133
L2J_Server_BETA/java/com/l2jserver/gameserver/SevenSignsFestival.java

@@ -936,81 +936,78 @@ public class SevenSignsFestival implements SpawnListener
 		if (Config.DEBUG)
 			_log.info("SevenSignsFestival: Restoring festival data. Current SS Cycle: " + _signsCycle);
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			Statement s = con.createStatement();
+			ResultSet rs = s.executeQuery("SELECT festivalId, cabal, cycle, date, score, members " + "FROM seven_signs_festival"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (Statement s = con.createStatement();
-				ResultSet rs = s.executeQuery("SELECT festivalId, cabal, cycle, date, score, members " + "FROM seven_signs_festival"))
+			while (rs.next())
 			{
-				while (rs.next())
-				{
-					int festivalCycle = rs.getInt("cycle");
-					int festivalId = rs.getInt("festivalId");
-					String cabal = rs.getString("cabal");
-					
-					StatsSet festivalDat = new StatsSet();
-					festivalDat.set("festivalId", festivalId);
-					festivalDat.set("cabal", cabal);
-					festivalDat.set("cycle", festivalCycle);
-					festivalDat.set("date", rs.getString("date"));
-					festivalDat.set("score", rs.getInt("score"));
-					festivalDat.set("members", rs.getString("members"));
-					
-					if (Config.DEBUG)
-						_log.info("SevenSignsFestival: Loaded data from DB for (Cycle = " + festivalCycle + ", Oracle = " + cabal
-								+ ", Festival = " + getFestivalName(festivalId));
-					
-					if (cabal.equals("dawn"))
-						festivalId += FESTIVAL_COUNT;
-					
-					Map<Integer, StatsSet> tempData = _festivalData.get(festivalCycle);
-					
-					if (tempData == null)
-						tempData = new FastMap<>();
-					
-					tempData.put(festivalId, festivalDat);
-					_festivalData.put(festivalCycle, tempData);
-				}
-			}
-			
-			StringBuilder query = new StringBuilder();
-			query.append("SELECT festival_cycle, ");
-			
-			for (int i = 0; i < FESTIVAL_COUNT - 1; i++)
-			{
-				query.append("accumulated_bonus");
-				query.append(String.valueOf(i));
-				query.append(", ");
-			}
+				int festivalCycle = rs.getInt("cycle");
+				int festivalId = rs.getInt("festivalId");
+				String cabal = rs.getString("cabal");
 				
+				StatsSet festivalDat = new StatsSet();
+				festivalDat.set("festivalId", festivalId);
+				festivalDat.set("cabal", cabal);
+				festivalDat.set("cycle", festivalCycle);
+				festivalDat.set("date", rs.getString("date"));
+				festivalDat.set("score", rs.getInt("score"));
+				festivalDat.set("members", rs.getString("members"));
+				
+				if (Config.DEBUG)
+					_log.info("SevenSignsFestival: Loaded data from DB for (Cycle = " + festivalCycle + ", Oracle = " + cabal
+							+ ", Festival = " + getFestivalName(festivalId));
+				
+				if (cabal.equals("dawn"))
+					festivalId += FESTIVAL_COUNT;
+				
+				Map<Integer, StatsSet> tempData = _festivalData.get(festivalCycle);
+				
+				if (tempData == null)
+					tempData = new FastMap<>();
+				
+				tempData.put(festivalId, festivalDat);
+				_festivalData.put(festivalCycle, tempData);
+			}
+		}
+		catch (SQLException e)
+		{
+			_log.log(Level.SEVERE, "SevenSignsFestival: Failed to load configuration: " + e.getMessage(), e);
+		}
+		
+		StringBuilder query = new StringBuilder();
+		query.append("SELECT festival_cycle, ");
+		
+		for (int i = 0; i < FESTIVAL_COUNT - 1; i++)
+		{
 			query.append("accumulated_bonus");
-			query.append(String.valueOf(FESTIVAL_COUNT - 1));
-			query.append(' ');
-			query.append("FROM seven_signs_status WHERE id=0");
+			query.append(String.valueOf(i));
+			query.append(", ");
+		}
 			
-			try (Statement s = con.createStatement();
-				ResultSet rs = s.executeQuery(query.toString()))
+		query.append("accumulated_bonus");
+		query.append(String.valueOf(FESTIVAL_COUNT - 1));
+		query.append(' ');
+		query.append("FROM seven_signs_status WHERE id=0");
+		
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			Statement s = con.createStatement();
+			ResultSet rs = s.executeQuery(query.toString()))
+		{
+			while (rs.next())
 			{
-				while (rs.next())
-				{
-					_festivalCycle = rs.getInt("festival_cycle");
-					
-					for (int i = 0; i < FESTIVAL_COUNT; i++)
-						_accumulatedBonuses.add(i, rs.getInt("accumulated_bonus" + String.valueOf(i)));
-				}
+				_festivalCycle = rs.getInt("festival_cycle");
+				
+				for (int i = 0; i < FESTIVAL_COUNT; i++)
+					_accumulatedBonuses.add(i, rs.getInt("accumulated_bonus" + String.valueOf(i)));
 			}
-			if (Config.DEBUG)
-				_log.info("SevenSignsFestival: Loaded data from database.");
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.SEVERE, "SevenSignsFestival: Failed to load configuration: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
+		if (Config.DEBUG)
+			_log.info("SevenSignsFestival: Loaded data from database.");
 	}
 	
 	/**
@@ -1023,69 +1020,60 @@ public class SevenSignsFestival implements SpawnListener
 	 */
 	public void saveFestivalData(boolean updateSettings)
 	{
-		Connection con = null;
-		
 		if (Config.DEBUG)
 			_log.info("SevenSignsFestival: Saving festival data to disk.");
 		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement psUpdate = con.prepareStatement("UPDATE seven_signs_festival SET date=?, score=?, members=? WHERE cycle=? AND cabal=? AND festivalId=?");
+			PreparedStatement psInsert = con.prepareStatement("INSERT INTO seven_signs_festival (festivalId, cabal, cycle, date, score, members) VALUES (?,?,?,?,?,?)"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement psUpdate = con.prepareStatement("UPDATE seven_signs_festival SET date=?, score=?, members=? WHERE cycle=? AND cabal=? AND festivalId=?");
-				PreparedStatement psInsert = con.prepareStatement("INSERT INTO seven_signs_festival (festivalId, cabal, cycle, date, score, members) VALUES (?,?,?,?,?,?)"))
+			for (Map<Integer, StatsSet> currCycleData : _festivalData.values())
 			{
-				for (Map<Integer, StatsSet> currCycleData : _festivalData.values())
+				for (StatsSet festivalDat : currCycleData.values())
 				{
-					for (StatsSet festivalDat : currCycleData.values())
+					int festivalCycle = festivalDat.getInteger("cycle");
+					int festivalId = festivalDat.getInteger("festivalId");
+					String cabal = festivalDat.getString("cabal");
+					
+					// Try to update an existing record.
+					psUpdate.setLong(1, Long.valueOf(festivalDat.getString("date")));
+					psUpdate.setInt(2, festivalDat.getInteger("score"));
+					psUpdate.setString(3, festivalDat.getString("members"));
+					psUpdate.setInt(4, festivalCycle);
+					psUpdate.setString(5, cabal);
+					psUpdate.setInt(6, festivalId);
+					
+					// If there was no record to update, assume it doesn't exist and add a new one,
+					// otherwise continue with the next record to store.
+					if (psUpdate.executeUpdate() > 0)
 					{
-						int festivalCycle = festivalDat.getInteger("cycle");
-						int festivalId = festivalDat.getInteger("festivalId");
-						String cabal = festivalDat.getString("cabal");
-						
-						// Try to update an existing record.
-						psUpdate.setLong(1, Long.valueOf(festivalDat.getString("date")));
-						psUpdate.setInt(2, festivalDat.getInteger("score"));
-						psUpdate.setString(3, festivalDat.getString("members"));
-						psUpdate.setInt(4, festivalCycle);
-						psUpdate.setString(5, cabal);
-						psUpdate.setInt(6, festivalId);
-						
-						// If there was no record to update, assume it doesn't exist and add a new one,
-						// otherwise continue with the next record to store.
-						if (psUpdate.executeUpdate() > 0)
-						{
-							if (Config.DEBUG)
-								_log.info("SevenSignsFestival: Updated data in DB (Cycle = " + festivalCycle + ", Cabal = " + cabal + ", FestID = " + festivalId + ")");
-							continue;
-						}
-						
-						psInsert.setInt(1, festivalId);
-						psInsert.setString(2, cabal);
-						psInsert.setInt(3, festivalCycle);
-						psInsert.setLong(4, Long.valueOf(festivalDat.getString("date")));
-						psInsert.setInt(5, festivalDat.getInteger("score"));
-						psInsert.setString(6, festivalDat.getString("members"));
-						psInsert.execute();
-						psInsert.clearParameters();
-						
 						if (Config.DEBUG)
-							_log.info("SevenSignsFestival: Inserted data in DB (Cycle = " + festivalCycle + ", Cabal = " + cabal + ", FestID = " + festivalId + ")");
+							_log.info("SevenSignsFestival: Updated data in DB (Cycle = " + festivalCycle + ", Cabal = " + cabal + ", FestID = " + festivalId + ")");
+						continue;
 					}
+					
+					psInsert.setInt(1, festivalId);
+					psInsert.setString(2, cabal);
+					psInsert.setInt(3, festivalCycle);
+					psInsert.setLong(4, Long.valueOf(festivalDat.getString("date")));
+					psInsert.setInt(5, festivalDat.getInteger("score"));
+					psInsert.setString(6, festivalDat.getString("members"));
+					psInsert.execute();
+					psInsert.clearParameters();
+					
+					if (Config.DEBUG)
+						_log.info("SevenSignsFestival: Inserted data in DB (Cycle = " + festivalCycle + ", Cabal = " + cabal + ", FestID = " + festivalId + ")");
 				}
 			}
-			
-			// Updates Seven Signs DB data also, so call only if really necessary.
-			if (updateSettings)
-				SevenSigns.getInstance().saveSevenSignsStatus();
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.SEVERE, "SevenSignsFestival: Failed to save configuration: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
+		
+		// Updates Seven Signs DB data also, so call only if really necessary.
+		if (updateSettings)
+			SevenSigns.getInstance().saveSevenSignsStatus();
 	}
 	
 	/**
@@ -1151,30 +1139,25 @@ public class SevenSignsFestival implements SpawnListener
 		}
 		else
 		{
-			Connection con = null;
-			
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+				PreparedStatement ps = con.prepareStatement(GET_CLAN_NAME))
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
-				try (PreparedStatement ps = con.prepareStatement(GET_CLAN_NAME))
+				ps.setString(1, partyMemberName);
+				try (ResultSet rs = ps.executeQuery())
 				{
-					ps.setString(1, partyMemberName);
-					try (ResultSet rs = ps.executeQuery())
+					if (rs.next())
 					{
-						if (rs.next())
+						String clanName = rs.getString("clan_name");
+						if (clanName != null)
 						{
-							String clanName = rs.getString("clan_name");
-							if (clanName != null)
+							L2Clan clan = ClanTable.getInstance().getClanByName(clanName);
+							if (clan != null)
 							{
-								L2Clan clan = ClanTable.getInstance().getClanByName(clanName);
-								if (clan != null)
-								{
-									clan.addReputationScore(Config.FESTIVAL_WIN_POINTS, true);
-									SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.CLAN_MEMBER_C1_WAS_IN_HIGHEST_RANKED_PARTY_IN_FESTIVAL_OF_DARKNESS_AND_GAINED_S2_REPUTATION);
-									sm.addString(partyMemberName);
-									sm.addNumber(Config.FESTIVAL_WIN_POINTS);
-									clan.broadcastToOnlineMembers(sm);
-								}
+								clan.addReputationScore(Config.FESTIVAL_WIN_POINTS, true);
+								SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.CLAN_MEMBER_C1_WAS_IN_HIGHEST_RANKED_PARTY_IN_FESTIVAL_OF_DARKNESS_AND_GAINED_S2_REPUTATION);
+								sm.addString(partyMemberName);
+								sm.addNumber(Config.FESTIVAL_WIN_POINTS);
+								clan.broadcastToOnlineMembers(sm);
 							}
 						}
 					}
@@ -1184,10 +1167,6 @@ public class SevenSignsFestival implements SpawnListener
 			{
 				_log.log(Level.WARNING, "Could not get clan name of " + partyMemberName + ": " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 		}
 	}
 	

+ 68 - 115
L2J_Server_BETA/java/com/l2jserver/gameserver/TradeController.java

@@ -45,26 +45,6 @@ public class TradeController
 	private int _nextListId;
 	private Map<Integer, L2TradeList> _lists = new FastMap<>();
 	
-	//**
-	// * Task launching the function for restore count of Item (Clan Hall) 
-	// */
-	/*public class RestoreCount implements Runnable
-	{
-		private int _timer;
-		
-		public RestoreCount(int time)
-		{
-			_timer = time;
-		}
-		
-		public void run()
-		{
-			restoreCount(_timer);
-			dataTimerSave(_timer);
-			ThreadPoolManager.getInstance().scheduleGeneral(new RestoreCount(_timer), (long)_timer*60*60*1000);
-		}
-	}*/
-	
 	public static TradeController getInstance()
 	{
 		return SingletonHolder._instance;
@@ -73,87 +53,82 @@ public class TradeController
 	protected TradeController()
 	{
 		_lists.clear();
-		Connection con = null;
-		
 		// Initialize Shop buy list
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			Statement s = con.createStatement();
+			ResultSet rs1 = s.executeQuery("SELECT  shop_id, npc_id FROM merchant_shopids"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (Statement s = con.createStatement();
-				ResultSet rs1 = s.executeQuery("SELECT  shop_id, npc_id FROM merchant_shopids"))
+			int itemId, price, maxCount, currentCount, time;
+			long saveTimer;
+			try (PreparedStatement ps = con.prepareStatement("SELECT item_id, price, shop_id, "
+					+ L2DatabaseFactory.getInstance().safetyString("order")
+					+ ", count, currentCount, time, savetimer FROM merchant_buylists WHERE shop_id=? ORDER BY "
+					+ L2DatabaseFactory.getInstance().safetyString("order") + " ASC"))
 			{
-				int itemId, price, maxCount, currentCount, time;
-				long saveTimer;
-				try (PreparedStatement ps = con.prepareStatement("SELECT item_id, price, shop_id, "
-						+ L2DatabaseFactory.getInstance().safetyString("order")
-						+ ", count, currentCount, time, savetimer FROM merchant_buylists WHERE shop_id=? ORDER BY "
-						+ L2DatabaseFactory.getInstance().safetyString("order") + " ASC"))
+				while (rs1.next())
 				{
-					while (rs1.next())
+					ps.setString(1, String.valueOf(rs1.getInt("shop_id")));
+					try (ResultSet rs2 = ps.executeQuery())
 					{
-						ps.setString(1, String.valueOf(rs1.getInt("shop_id")));
-						try (ResultSet rs2 = ps.executeQuery())
+						ps.clearParameters();
+						
+						int shopId = rs1.getInt("shop_id");
+						L2TradeList buy1 = new L2TradeList(shopId);
+						
+						while (rs2.next())
 						{
-							ps.clearParameters();
+							itemId = rs2.getInt("item_id");
+							price = rs2.getInt("price");
+							maxCount = rs2.getInt("count");
+							currentCount = rs2.getInt("currentCount");
+							time = rs2.getInt("time");
+							saveTimer = rs2.getLong("saveTimer");
 							
-							int shopId = rs1.getInt("shop_id");
-							L2TradeList buy1 = new L2TradeList(shopId);
+							L2TradeItem item = new L2TradeItem(shopId, itemId);
+							if (ItemTable.getInstance().getTemplate(itemId) == null)
+							{
+								_log.warning("Skipping itemId: " + itemId + " on buylistId: " + buy1.getListId() + ", missing data for that item.");
+								continue;
+							}
 							
-							while (rs2.next())
+							if (price <= -1)
 							{
-								itemId = rs2.getInt("item_id");
-								price = rs2.getInt("price");
-								maxCount = rs2.getInt("count");
-								currentCount = rs2.getInt("currentCount");
-								time = rs2.getInt("time");
-								saveTimer = rs2.getLong("saveTimer");
-								
-								L2TradeItem item = new L2TradeItem(shopId, itemId);
-								if (ItemTable.getInstance().getTemplate(itemId) == null)
-								{
-									_log.warning("Skipping itemId: " + itemId + " on buylistId: " + buy1.getListId() + ", missing data for that item.");
-									continue;
-								}
-								
-								if (price <= -1)
-								{
-									price = ItemTable.getInstance().getTemplate(itemId).getReferencePrice();
-								}
-								
-								if (Config.DEBUG)
-								{
-									// debug
-									double diff = ((double) (price)) / ItemTable.getInstance().getTemplate(itemId).getReferencePrice();
-									if (diff < 0.8 || diff > 1.2)
-									{
-										_log.severe("PRICING DEBUG: TradeListId: " + buy1.getListId() + " -  ItemId: " + itemId + " ("
-												+ ItemTable.getInstance().getTemplate(itemId).getName() + ") diff: " + diff + " - Price: " + price
-												+ " - Reference: " + ItemTable.getInstance().getTemplate(itemId).getReferencePrice());
-									}
-								}
-								
-								item.setPrice(price);
-								
-								item.setRestoreDelay(time);
-								item.setNextRestoreTime(saveTimer);
-								item.setMaxCount(maxCount);
-								
-								if (currentCount > -1)
-								{
-									item.setCurrentCount(currentCount);
-								}
-								else
+								price = ItemTable.getInstance().getTemplate(itemId).getReferencePrice();
+							}
+							
+							if (Config.DEBUG)
+							{
+								// debug
+								double diff = ((double) (price)) / ItemTable.getInstance().getTemplate(itemId).getReferencePrice();
+								if (diff < 0.8 || diff > 1.2)
 								{
-									item.setCurrentCount(maxCount);
+									_log.severe("PRICING DEBUG: TradeListId: " + buy1.getListId() + " -  ItemId: " + itemId + " ("
+											+ ItemTable.getInstance().getTemplate(itemId).getName() + ") diff: " + diff + " - Price: " + price
+											+ " - Reference: " + ItemTable.getInstance().getTemplate(itemId).getReferencePrice());
 								}
-								
-								buy1.addItem(item);
 							}
 							
-							buy1.setNpcId(rs1.getString("npc_id"));
-							_lists.put(buy1.getListId(), buy1);
-							_nextListId = Math.max(_nextListId, buy1.getListId() + 1);
+							item.setPrice(price);
+							
+							item.setRestoreDelay(time);
+							item.setNextRestoreTime(saveTimer);
+							item.setMaxCount(maxCount);
+							
+							if (currentCount > -1)
+							{
+								item.setCurrentCount(currentCount);
+							}
+							else
+							{
+								item.setCurrentCount(maxCount);
+							}
+							
+							buy1.addItem(item);
 						}
+						
+						buy1.setNpcId(rs1.getString("npc_id"));
+						_lists.put(buy1.getListId(), buy1);
+						_nextListId = Math.max(_nextListId, buy1.getListId() + 1);
 					}
 				}
 			}
@@ -164,21 +139,15 @@ public class TradeController
 			// problem with initializing spawn, go to next one
 			_log.log(Level.WARNING, "TradeController: Buylists could not be initialized: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
 		// If enabled, initialize the custom buy list
 		if (Config.CUSTOM_MERCHANT_TABLES)
 		{
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+				Statement s = con.createStatement();
+				ResultSet rset1 = s.executeQuery("SELECT  shop_id, npc_id FROM custom_merchant_shopids"))
 			{
 				int initialSize = _lists.size();
-				con = L2DatabaseFactory.getInstance().getConnection();
-				PreparedStatement statement1 = con.prepareStatement("SELECT  shop_id, npc_id FROM custom_merchant_shopids");
-				ResultSet rset1 = statement1.executeQuery();
-				
 				int itemId, price, maxCount, currentCount, time;
 				long saveTimer;
 				PreparedStatement statement = con.prepareStatement("SELECT item_id, price, shop_id, "
@@ -254,7 +223,6 @@ public class TradeController
 				}
 				statement.close();
 				rset1.close();
-				statement1.close();
 				
 				_log.info("TradeController: Loaded " + (_lists.size() - initialSize) + " Custom Buylists.");
 				
@@ -264,10 +232,6 @@ public class TradeController
 				// problem with initializing spawn, go to next one
 				_log.log(Level.WARNING, "TradeController: Buylists could not be initialized: " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 		}
 	}
 	
@@ -294,19 +258,13 @@ public class TradeController
 	
 	public void dataCountStore()
 	{
-		Connection con = null;
-		int listId;
-		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("UPDATE merchant_buylists SET currentCount = ? WHERE item_id = ? AND shop_id = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("UPDATE merchant_buylists SET currentCount=? WHERE item_id=? AND shop_id=?");
 			for (L2TradeList list : _lists.values())
 			{
 				if (list.hasLimitedStockItem())
 				{
-					listId = list.getListId();
-					
 					for (L2TradeItem item : list.getItems())
 					{
 						long currentCount;
@@ -314,23 +272,18 @@ public class TradeController
 						{
 							statement.setLong(1, currentCount);
 							statement.setInt(2, item.getItemId());
-							statement.setInt(3, listId);
+							statement.setInt(3, list.getListId());
 							statement.executeUpdate();
 							statement.clearParameters();
 						}
 					}
 				}
 			}
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, "TradeController: Could not store Count Item: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**

+ 5 - 13
L2J_Server_BETA/java/com/l2jserver/gameserver/cache/CrestCache.java

@@ -219,25 +219,17 @@ public class CrestCache
 				file.renameTo(new File(Config.DATAPACK_ROOT, "data/crests/Crest_" + newId + ".bmp"));
 				_log.info("Renamed Clan crest to new format: Crest_" + newId + ".bmp");
 				
-				Connection con = null;
-				try
+				try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+					PreparedStatement ps = con.prepareStatement("UPDATE clan_data SET crest_id = ? WHERE clan_id = ?"))
 				{
-					con = L2DatabaseFactory.getInstance().getConnection();
-					try (PreparedStatement ps = con.prepareStatement("UPDATE clan_data SET crest_id = ? WHERE clan_id = ?"))
-					{
-						ps.setInt(1, newId);
-						ps.setInt(2, clan.getClanId());
-						ps.executeUpdate();
-					}
+					ps.setInt(1, newId);
+					ps.setInt(2, clan.getClanId());
+					ps.executeUpdate();
 				}
 				catch (SQLException e)
 				{
 					_log.log(Level.WARNING, "Could not update the crest id:" + e.getMessage(), e);
 				}
-				finally
-				{
-					L2DatabaseFactory.close(con);
-				}
 				clan.setCrestId(newId);
 			}
 			else

+ 1 - 1
L2J_Server_BETA/java/com/l2jserver/gameserver/cache/HtmCache.java

@@ -124,7 +124,7 @@ public class HtmCache
 		final int hashcode = relpath.hashCode();
 		String content = null;
 		try (FileInputStream fis = new FileInputStream(file);
-			BufferedInputStream bis = new BufferedInputStream(fis);)
+			BufferedInputStream bis = new BufferedInputStream(fis))
 		{
 			final int bytes = bis.available();
 			byte[] raw = new byte[bytes];

+ 38 - 72
L2J_Server_BETA/java/com/l2jserver/gameserver/communitybbs/BB/Forum.java

@@ -99,29 +99,22 @@ public class Forum
 		_loaded = true;
 	}
 	
-	/**
-	 *
-	 */
 	private void load()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement("SELECT * FROM forums WHERE forum_id=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement("SELECT * FROM forums WHERE forum_id=?"))
+			ps.setInt(1, _forumId);
+			try (ResultSet rs = ps.executeQuery())
 			{
-				ps.setInt(1, _forumId);
-				try (ResultSet rs = ps.executeQuery())
+				if (rs.next())
 				{
-					if (rs.next())
-					{
-						_forumName = rs.getString("forum_name");
-						//_ForumParent = result.getInt("forum_parent");
-						_forumPost = rs.getInt("forum_post");
-						_forumType = rs.getInt("forum_type");
-						_forumPerm = rs.getInt("forum_perm");
-						_ownerID = rs.getInt("forum_owner_id");
-					}
+					_forumName = rs.getString("forum_name");
+					//_ForumParent = result.getInt("forum_parent");
+					_forumPost = rs.getInt("forum_post");
+					_forumType = rs.getInt("forum_type");
+					_forumPerm = rs.getInt("forum_perm");
+					_ownerID = rs.getInt("forum_owner_id");
 				}
 			}
 		}
@@ -129,27 +122,20 @@ public class Forum
 		{
 			_log.log(Level.WARNING, "Data error on Forum " + _forumId + " : " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement("SELECT * FROM topic WHERE topic_forum_id=? ORDER BY topic_id DESC"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement("SELECT * FROM topic WHERE topic_forum_id=? ORDER BY topic_id DESC"))
+			ps.setInt(1, _forumId);
+			try (ResultSet rs = ps.executeQuery())
 			{
-				ps.setInt(1, _forumId);
-				try (ResultSet rs = ps.executeQuery())
+				while (rs.next())
 				{
-					while (rs.next())
+					Topic t = new Topic(Topic.ConstructorType.RESTORE, rs.getInt("topic_id"), rs.getInt("topic_forum_id"), rs.getString("topic_name"), rs.getLong("topic_date"), rs.getString("topic_ownername"), rs.getInt("topic_ownerid"), rs.getInt("topic_type"), rs.getInt("topic_reply"));
+					_topic.put(t.getID(), t);
+					if (t.getID() > TopicBBSManager.getInstance().getMaxID(this))
 					{
-						Topic t = new Topic(Topic.ConstructorType.RESTORE, rs.getInt("topic_id"), rs.getInt("topic_forum_id"), rs.getString("topic_name"), rs.getLong("topic_date"), rs.getString("topic_ownername"), rs.getInt("topic_ownerid"), rs.getInt("topic_type"), rs.getInt("topic_reply"));
-						_topic.put(t.getID(), t);
-						if (t.getID() > TopicBBSManager.getInstance().getMaxID(this))
-						{
-							TopicBBSManager.getInstance().setMaxID(t.getID(), this);
-						}
+						TopicBBSManager.getInstance().setMaxID(t.getID(), this);
 					}
 				}
 			}
@@ -158,29 +144,21 @@ public class Forum
 		{
 			_log.log(Level.WARNING, "Data error on Forum " + _forumId + " : " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void getChildren()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement("SELECT forum_id FROM forums WHERE forum_parent=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement("SELECT forum_id FROM forums WHERE forum_parent=?"))
+			ps.setInt(1, _forumId);
+			try (ResultSet rs = ps.executeQuery())
 			{
-				ps.setInt(1, _forumId);
-				try (ResultSet rs = ps.executeQuery())
+				while (rs.next())
 				{
-					while (rs.next())
-					{
-						Forum f = new Forum(rs.getInt("forum_id"), this);
-						_children.add(f);
-						ForumsBBSManager.getInstance().addForum(f);
-					}
+					Forum f = new Forum(rs.getInt("forum_id"), this);
+					_children.add(f);
+					ForumsBBSManager.getInstance().addForum(f);
 				}
 			}
 		}
@@ -188,10 +166,6 @@ public class Forum
 		{
 			_log.log(Level.WARNING, "Data error on Forum (children): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public int getTopicSize()
@@ -260,30 +234,22 @@ public class Forum
 	
 	public void insertIntoDb()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement("INSERT INTO forums (forum_id,forum_name,forum_parent,forum_post,forum_type,forum_perm,forum_owner_id) VALUES (?,?,?,?,?,?,?)"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement("INSERT INTO forums (forum_id,forum_name,forum_parent,forum_post,forum_type,forum_perm,forum_owner_id) VALUES (?,?,?,?,?,?,?)"))
-			{
-				ps.setInt(1, _forumId);
-				ps.setString(2, _forumName);
-				ps.setInt(3, _fParent.getID());
-				ps.setInt(4, _forumPost);
-				ps.setInt(5, _forumType);
-				ps.setInt(6, _forumPerm);
-				ps.setInt(7, _ownerID);
-				ps.execute();
-			}
+			ps.setInt(1, _forumId);
+			ps.setString(2, _forumName);
+			ps.setInt(3, _fParent.getID());
+			ps.setInt(4, _forumPost);
+			ps.setInt(5, _forumType);
+			ps.setInt(6, _forumPerm);
+			ps.setInt(7, _ownerID);
+			ps.execute();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Error while saving new Forum to db " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**

+ 38 - 70
L2J_Server_BETA/java/com/l2jserver/gameserver/communitybbs/BB/Post.java

@@ -73,30 +73,22 @@ public class Post
 	
 	public void insertindb(CPost cp)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement("INSERT INTO posts (post_id,post_owner_name,post_ownerid,post_date,post_topic_id,post_forum_id,post_txt) values (?,?,?,?,?,?,?)"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement("INSERT INTO posts (post_id,post_owner_name,post_ownerid,post_date,post_topic_id,post_forum_id,post_txt) values (?,?,?,?,?,?,?)"))
-			{
-				ps.setInt(1, cp.postId);
-				ps.setString(2, cp.postOwner);
-				ps.setInt(3, cp.postOwnerId);
-				ps.setLong(4, cp.postDate);
-				ps.setInt(5, cp.postTopicId);
-				ps.setInt(6, cp.postForumId);
-				ps.setString(7, cp.postTxt);
-				ps.execute();
-			}
+			ps.setInt(1, cp.postId);
+			ps.setString(2, cp.postOwner);
+			ps.setInt(3, cp.postOwnerId);
+			ps.setLong(4, cp.postDate);
+			ps.setInt(5, cp.postTopicId);
+			ps.setInt(6, cp.postForumId);
+			ps.setString(7, cp.postTxt);
+			ps.execute();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Error while saving new Post to db " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public Post(Topic t)
@@ -121,25 +113,17 @@ public class Post
 	public void deleteme(Topic t)
 	{
 		PostBBSManager.getInstance().delPostByTopic(t);
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement("DELETE FROM posts WHERE post_forum_id=? AND post_topic_id=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement("DELETE FROM posts WHERE post_forum_id=? AND post_topic_id=?"))
-			{
-				ps.setInt(1, t.getForumID());
-				ps.setInt(2, t.getID());
-				ps.execute();
-			}
+			ps.setInt(1, t.getForumID());
+			ps.setInt(2, t.getID());
+			ps.execute();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Error while deleting post: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -147,28 +131,24 @@ public class Post
 	 */
 	private void load(Topic t)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement("SELECT * FROM posts WHERE post_forum_id=? AND post_topic_id=? ORDER BY post_id ASC"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement("SELECT * FROM posts WHERE post_forum_id=? AND post_topic_id=? ORDER BY post_id ASC"))
+			ps.setInt(1, t.getForumID());
+			ps.setInt(2, t.getID());
+			try (ResultSet rs = ps.executeQuery())
 			{
-				ps.setInt(1, t.getForumID());
-				ps.setInt(2, t.getID());
-				try (ResultSet rs = ps.executeQuery())
+				while(rs.next())
 				{
-					while(rs.next())
-					{
-						CPost cp = new CPost();
-						cp.postId = rs.getInt("post_id");
-						cp.postOwner = rs.getString("post_owner_name");
-						cp.postOwnerId = rs.getInt("post_ownerid");
-						cp.postDate = rs.getLong("post_date");
-						cp.postTopicId = rs.getInt("post_topic_id");
-						cp.postForumId = rs.getInt("post_forum_id");
-						cp.postTxt = rs.getString("post_txt");
-						_post.add(cp);
-					}
+					CPost cp = new CPost();
+					cp.postId = rs.getInt("post_id");
+					cp.postOwner = rs.getString("post_owner_name");
+					cp.postOwnerId = rs.getInt("post_ownerid");
+					cp.postDate = rs.getLong("post_date");
+					cp.postTopicId = rs.getInt("post_topic_id");
+					cp.postForumId = rs.getInt("post_forum_id");
+					cp.postTxt = rs.getString("post_txt");
+					_post.add(cp);
 				}
 			}
 		}
@@ -176,10 +156,6 @@ public class Post
 		{
 			_log.log(Level.WARNING, "Data error on Post " + t.getForumID() + "/"+t.getID()+" : " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -187,27 +163,19 @@ public class Post
 	 */
 	public void updatetxt(int i)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement("UPDATE posts SET post_txt=? WHERE post_id=? AND post_topic_id=? AND post_forum_id=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement("UPDATE posts SET post_txt=? WHERE post_id=? AND post_topic_id=? AND post_forum_id=?"))
-			{
-				CPost cp = getCPost(i);
-				ps.setString(1, cp.postTxt);
-				ps.setInt(2, cp.postId);
-				ps.setInt(3, cp.postTopicId);
-				ps.setInt(4, cp.postForumId);
-				ps.execute();
-			}
+			CPost cp = getCPost(i);
+			ps.setString(1, cp.postTxt);
+			ps.setInt(2, cp.postId);
+			ps.setInt(3, cp.postTopicId);
+			ps.setInt(4, cp.postForumId);
+			ps.execute();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Error while saving new Post to db " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 }

+ 17 - 36
L2J_Server_BETA/java/com/l2jserver/gameserver/communitybbs/BB/Topic.java

@@ -25,8 +25,8 @@ import com.l2jserver.gameserver.communitybbs.Manager.TopicBBSManager;
 
 public class Topic
 {
+	private static final Logger _log = Logger.getLogger(Topic.class.getName());
 	
-	private static Logger _log = Logger.getLogger(Topic.class.getName());
 	public static final int MORMAL = 0;
 	public static final int MEMO = 1;
 	
@@ -69,36 +69,25 @@ public class Topic
 		}
 	}
 	
-	/**
-	 *
-	 */
 	public void insertindb()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement("INSERT INTO topic (topic_id,topic_forum_id,topic_name,topic_date,topic_ownername,topic_ownerid,topic_type,topic_reply) values (?,?,?,?,?,?,?,?)"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement("INSERT INTO topic (topic_id,topic_forum_id,topic_name,topic_date,topic_ownername,topic_ownerid,topic_type,topic_reply) values (?,?,?,?,?,?,?,?)"))
-			{
-				ps.setInt(1, _id);
-				ps.setInt(2, _forumId);
-				ps.setString(3, _topicName);
-				ps.setLong(4, _date);
-				ps.setString(5, _ownerName);
-				ps.setInt(6, _ownerId);
-				ps.setInt(7, _type);
-				ps.setInt(8, _cReply);
-				ps.execute();
-			}
+			ps.setInt(1, _id);
+			ps.setInt(2, _forumId);
+			ps.setString(3, _topicName);
+			ps.setLong(4, _date);
+			ps.setString(5, _ownerName);
+			ps.setInt(6, _ownerId);
+			ps.setInt(7, _type);
+			ps.setInt(8, _cReply);
+			ps.execute();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Error while saving new Topic to db " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public enum ConstructorType
@@ -140,25 +129,17 @@ public class Topic
 	{
 		TopicBBSManager.getInstance().delTopic(this);
 		f.rmTopicByID(getID());
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement("DELETE FROM topic WHERE topic_id=? AND topic_forum_id=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement("DELETE FROM topic WHERE topic_id=? AND topic_forum_id=?"))
-			{
-				ps.setInt(1, getID());
-				ps.setInt(2, f.getID());
-				ps.execute();
-			}
+			ps.setInt(1, getID());
+			ps.setInt(2, f.getID());
+			ps.execute();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Error while deleting topic: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**

+ 7 - 16
L2J_Server_BETA/java/com/l2jserver/gameserver/communitybbs/Manager/ForumsBBSManager.java

@@ -48,30 +48,21 @@ public class ForumsBBSManager extends BaseBBSManager
 	protected ForumsBBSManager()
 	{
 		_table = new FastList<>();
-		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			Statement s = con.createStatement();
+			ResultSet rs = s.executeQuery("SELECT forum_id FROM forums WHERE forum_type = 0"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (Statement s = con.createStatement();
-				ResultSet rs = s.executeQuery("SELECT forum_id FROM forums WHERE forum_type = 0"))
+			while (rs.next())
 			{
-				while (rs.next())
-				{
-					int forumId = rs.getInt("forum_id");
-					Forum f = new Forum(forumId, null);
-					addForum(f);
-				}
+				int forumId = rs.getInt("forum_id");
+				Forum f = new Forum(forumId, null);
+				addForum(f);
 			}
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Data error on Forum (root): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**

+ 35 - 76
L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/CharNameTable.java

@@ -101,20 +101,16 @@ public class CharNameTable
 		int id = -1;
 		int accessLevel = 0;
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement("SELECT charId,accesslevel FROM characters WHERE char_name=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement("SELECT charId,accesslevel FROM characters WHERE char_name=?"))
+			ps.setString(1, name);
+			try (ResultSet rs = ps.executeQuery())
 			{
-				ps.setString(1, name);
-				try (ResultSet rs = ps.executeQuery())
+				while (rs.next())
 				{
-					while (rs.next())
-					{
-						id = rs.getInt(1);
-						accessLevel = rs.getInt(2);
-					}
+					id = rs.getInt(1);
+					accessLevel = rs.getInt(2);
 				}
 			}
 		}
@@ -122,10 +118,6 @@ public class CharNameTable
 		{
 			_log.log(Level.WARNING, "Could not check existing char name: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
 		if (id > 0)
 		{
@@ -150,20 +142,16 @@ public class CharNameTable
 			return null;
 		
 		int accessLevel = 0;
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement("SELECT char_name,accesslevel FROM characters WHERE charId=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement("SELECT char_name,accesslevel FROM characters WHERE charId=?"))
+			ps.setInt(1, id);
+			try (ResultSet rset = ps.executeQuery())
 			{
-				ps.setInt(1, id);
-				try (ResultSet rset = ps.executeQuery())
+				while (rset.next())
 				{
-					while (rset.next())
-					{
-						name = rset.getString(1);
-						accessLevel = rset.getInt(2);
-					}
+					name = rset.getString(1);
+					accessLevel = rset.getInt(2);
 				}
 			}
 		}
@@ -171,10 +159,7 @@ public class CharNameTable
 		{
 			_log.log(Level.WARNING, "Could not check existing char id: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
+		
 		if (name != null && !name.isEmpty())
 		{
 			_chars.put(id, name);
@@ -196,48 +181,34 @@ public class CharNameTable
 	public synchronized boolean doesCharNameExist(String name)
 	{
 		boolean result = true;
-		Connection con = null;
-		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement("SELECT account_name FROM characters WHERE char_name=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement("SELECT account_name FROM characters WHERE char_name=?"))
+			ps.setString(1, name);
+			try (ResultSet rs = ps.executeQuery())
 			{
-				ps.setString(1, name);
-				try (ResultSet rs = ps.executeQuery())
-				{
-					result = rs.next();
-				}
+				result = rs.next();
 			}
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.WARNING, "Could not check existing charname: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		return result;
 	}
 	
 	public int accountCharNumber(String account)
 	{
-		Connection con = null;
 		int number = 0;
-		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement("SELECT COUNT(char_name) FROM characters WHERE account_name=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement("SELECT COUNT(char_name) FROM characters WHERE account_name=?"))
+			ps.setString(1, account);
+			try (ResultSet rset = ps.executeQuery())
 			{
-				ps.setString(1, account);
-				try (ResultSet rset = ps.executeQuery())
+				while (rset.next())
 				{
-					while (rset.next())
-					{
-						number = rset.getInt(1);
-					}
+					number = rset.getInt(1);
 				}
 			}
 		}
@@ -245,10 +216,6 @@ public class CharNameTable
 		{
 			_log.log(Level.WARNING, "Could not check existing char number: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		return number;
 	}
 	
@@ -257,31 +224,23 @@ public class CharNameTable
 		String name;
 		int id = -1;
 		int accessLevel = 0;
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			Statement s = con.createStatement();
+			ResultSet rs = s.executeQuery("SELECT charId,char_name,accesslevel FROM characters"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (Statement s = con.createStatement();
-				ResultSet rs = s.executeQuery("SELECT charId,char_name,accesslevel FROM characters"))
+			while (rs.next())
 			{
-				while (rs.next())
-				{
-					id = rs.getInt(1);
-					name = rs.getString(2);
-					accessLevel = rs.getInt(3);
-					_chars.put(id, name);
-					_accessLevels.put(id, accessLevel);
-				}
+				id = rs.getInt(1);
+				name = rs.getString(2);
+				accessLevel = rs.getInt(3);
+				_chars.put(id, name);
+				_accessLevels.put(id, accessLevel);
 			}
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.WARNING, "Could not load char name: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		_log.info(getClass().getSimpleName()+": Loaded "+_chars.size()+" char names.");
 	}
 	

+ 93 - 132
L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/CharSummonTable.java

@@ -62,53 +62,38 @@ public class CharSummonTable
 	
 	public void init()
 	{
-		Connection con = null;
 		if (Config.RESTORE_SERVITOR_ON_RECONNECT)
 		{
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+				Statement s = con.createStatement();
+				ResultSet rs = s.executeQuery(INIT_SUMMONS))
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
-				try (Statement s = con.createStatement();
-					ResultSet rs = s.executeQuery(INIT_SUMMONS))
+				while (rs.next())
 				{
-					while (rs.next())
-					{
-						_servitors.put(rs.getInt("ownerId"), rs.getInt("summonSkillId"));
-					}
+					_servitors.put(rs.getInt("ownerId"), rs.getInt("summonSkillId"));
 				}
 			}
 			catch (Exception e)
 			{
 				_log.log(Level.SEVERE, "Error while loading saved summons", e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 		}
 		
 		if (Config.RESTORE_PET_ON_RECONNECT)
 		{
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+				Statement s = con.createStatement();
+				ResultSet rs = s.executeQuery(INIT_PET))
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
-				try (Statement s = con.createStatement();
-					ResultSet rs = s.executeQuery(INIT_PET))
+				while (rs.next())
 				{
-					while (rs.next())
-					{
-						_pets.put(rs.getInt("ownerId"), rs.getInt("item_obj_id"));
-					}
+					_pets.put(rs.getInt("ownerId"), rs.getInt("item_obj_id"));
 				}
 			}
 			catch (Exception e)
 			{
 				_log.log(Level.SEVERE, "Error while loading saved summons", e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 		}
 	}
 	
@@ -126,113 +111,101 @@ public class CharSummonTable
 	{
 		if (summon == null || summon.getTimeRemaining() <= 0)
 			return;
+		_servitors.put(summon.getOwner().getObjectId(), summon.getReferenceSkill());
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement(SAVE_SUMMON))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement(SAVE_SUMMON))
-			{
-				ps.setInt(1, summon.getOwner().getObjectId());
-				ps.setInt(2, summon.getReferenceSkill());
-				ps.setInt(3, (int) Math.round(summon.getCurrentHp()));
-				ps.setInt(4, (int) Math.round(summon.getCurrentMp()));
-				ps.setInt(5, summon.getTimeRemaining());
-				ps.execute();
-			}
-			_servitors.put(summon.getOwner().getObjectId(), summon.getReferenceSkill());
+			ps.setInt(1, summon.getOwner().getObjectId());
+			ps.setInt(2, summon.getReferenceSkill());
+			ps.setInt(3, (int) Math.round(summon.getCurrentHp()));
+			ps.setInt(4, (int) Math.round(summon.getCurrentMp()));
+			ps.setInt(5, summon.getTimeRemaining());
+			ps.execute();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, "Failed to store summon [SummonId: " + summon.getNpcId() + "] from Char [CharId: " + summon.getOwner().getObjectId() + "] data", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
+			
 	}
 	
 	public void restoreServitor(L2PcInstance activeChar)
 	{
-		Connection con = null;
-		try
+		int skillId = _servitors.get(activeChar.getObjectId());
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement(LOAD_SUMMON))
 		{
-			int skillId = _servitors.get(activeChar.getObjectId());
-			
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement(LOAD_SUMMON))
+			ps.setInt(1, activeChar.getObjectId());
+			ps.setInt(2, skillId);
+			try (ResultSet rs = ps.executeQuery())
 			{
-				ps.setInt(1, activeChar.getObjectId());
-				ps.setInt(2, skillId);
-				try (ResultSet rs = ps.executeQuery())
-				{
+			
+				L2NpcTemplate summonTemplate;
+				L2ServitorInstance summon;
+				L2SkillSummon skill;
 				
-					L2NpcTemplate summonTemplate;
-					L2ServitorInstance summon;
-					L2SkillSummon skill;
+				while (rs.next())
+				{
+					int curHp = rs.getInt("curHp");
+					int curMp = rs.getInt("curMp");
+					int time = rs.getInt("time");
 					
-					while (rs.next())
+					skill = (L2SkillSummon) SkillTable.getInstance().getInfo(skillId, activeChar.getSkillLevel(skillId));
+					if (skill == null)
 					{
-						int curHp = rs.getInt("curHp");
-						int curMp = rs.getInt("curMp");
-						int time = rs.getInt("time");
-						
-						skill = (L2SkillSummon) SkillTable.getInstance().getInfo(skillId, activeChar.getSkillLevel(skillId));
-						if (skill == null)
-						{
-							removeServitor(activeChar);
-							return;
-						}
-						
-						summonTemplate = NpcTable.getInstance().getTemplate(skill.getNpcId());
-						if (summonTemplate == null)
-						{
-							_log.warning("[CharSummonTable] Summon attemp for nonexisting Skill ID:" + skillId);
-							return;
-						}
-						
-						final int id = IdFactory.getInstance().getNextId();
-						if (summonTemplate.isType("L2SiegeSummon"))
-						{
-							summon = new L2SiegeSummonInstance(id, summonTemplate, activeChar, skill);
-						}
-						else if (summonTemplate.isType("L2MerchantSummon"))
-						{
-							// TODO: Confirm L2Merchant summon = new L2MerchantSummonInstance(id, summonTemplate, activeChar, skill);
-							summon = new L2ServitorInstance(id, summonTemplate, activeChar, skill);
-						}
-						else
-						{
-							summon = new L2ServitorInstance(id, summonTemplate, activeChar, skill);
-						}
-						
-						summon.setName(summonTemplate.getName());
-						summon.setTitle(activeChar.getName());
-						summon.setExpPenalty(skill.getExpPenalty());
-						summon.setSharedElementals(skill.getInheritElementals());
-						summon.setSharedElementalsValue(skill.getElementalSharePercent());
-						
-						if (summon.getLevel() >= ExperienceTable.getInstance().getMaxPetLevel())
-						{
-							summon.getStat().setExp(ExperienceTable.getInstance().getExpForLevel(ExperienceTable.getInstance().getMaxPetLevel()-1));
-							_log.warning("Summon (" + summon.getName() + ") NpcID: " + summon.getNpcId() + " has a level above "+ExperienceTable.getInstance().getMaxPetLevel()+". Please rectify.");
-						}
-						else
-						{
-							summon.getStat().setExp(ExperienceTable.getInstance().getExpForLevel(summon.getLevel() % ExperienceTable.getInstance().getMaxPetLevel()));
-						}
-						summon.setCurrentHp(curHp);
-						summon.setCurrentMp(curMp);
-						summon.setHeading(activeChar.getHeading());
-						summon.setRunning();
-						if (!(summon instanceof L2MerchantSummonInstance))
-							activeChar.setPet(summon);
-						
-						summon.setTimeRemaining(time);
-						
-						//L2World.getInstance().storeObject(summon);
-						summon.spawnMe(activeChar.getX() + 20, activeChar.getY() + 20, activeChar.getZ());
+						removeServitor(activeChar);
+						return;
 					}
+					
+					summonTemplate = NpcTable.getInstance().getTemplate(skill.getNpcId());
+					if (summonTemplate == null)
+					{
+						_log.warning("[CharSummonTable] Summon attemp for nonexisting Skill ID:" + skillId);
+						return;
+					}
+					
+					final int id = IdFactory.getInstance().getNextId();
+					if (summonTemplate.isType("L2SiegeSummon"))
+					{
+						summon = new L2SiegeSummonInstance(id, summonTemplate, activeChar, skill);
+					}
+					else if (summonTemplate.isType("L2MerchantSummon"))
+					{
+						// TODO: Confirm L2Merchant summon = new L2MerchantSummonInstance(id, summonTemplate, activeChar, skill);
+						summon = new L2ServitorInstance(id, summonTemplate, activeChar, skill);
+					}
+					else
+					{
+						summon = new L2ServitorInstance(id, summonTemplate, activeChar, skill);
+					}
+					
+					summon.setName(summonTemplate.getName());
+					summon.setTitle(activeChar.getName());
+					summon.setExpPenalty(skill.getExpPenalty());
+					summon.setSharedElementals(skill.getInheritElementals());
+					summon.setSharedElementalsValue(skill.getElementalSharePercent());
+					
+					if (summon.getLevel() >= ExperienceTable.getInstance().getMaxPetLevel())
+					{
+						summon.getStat().setExp(ExperienceTable.getInstance().getExpForLevel(ExperienceTable.getInstance().getMaxPetLevel()-1));
+						_log.warning("Summon (" + summon.getName() + ") NpcID: " + summon.getNpcId() + " has a level above "+ExperienceTable.getInstance().getMaxPetLevel()+". Please rectify.");
+					}
+					else
+					{
+						summon.getStat().setExp(ExperienceTable.getInstance().getExpForLevel(summon.getLevel() % ExperienceTable.getInstance().getMaxPetLevel()));
+					}
+					summon.setCurrentHp(curHp);
+					summon.setCurrentMp(curMp);
+					summon.setHeading(activeChar.getHeading());
+					summon.setRunning();
+					if (!(summon instanceof L2MerchantSummonInstance))
+						activeChar.setPet(summon);
+					
+					summon.setTimeRemaining(time);
+					
+					//L2World.getInstance().storeObject(summon);
+					summon.spawnMe(activeChar.getX() + 20, activeChar.getY() + 20, activeChar.getZ());
 				}
 			}
 		}
@@ -240,33 +213,21 @@ public class CharSummonTable
 		{
 			_log.log(Level.WARNING, "[CharSummonTable]: Summon cannot be restored: ", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public void removeServitor(L2PcInstance activeChar)
 	{
-		Connection con = null;
-		try
+		_servitors.remove(activeChar.getObjectId());
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement(REMOVE_SUMMON))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement(REMOVE_SUMMON))
-			{
-				ps.setInt(1, activeChar.getObjectId());
-				ps.execute();
-			}
-			_servitors.remove(activeChar.getObjectId());
+			ps.setInt(1, activeChar.getObjectId());
+			ps.execute();
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.WARNING, "[CharSummonTable]: Summon cannot be removed: ", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public void restorePet(L2PcInstance activeChar)

+ 4 - 12
L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/CharTemplateTable.java

@@ -15,9 +15,9 @@
 package com.l2jserver.gameserver.datatables;
 
 import java.sql.Connection;
-import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
+import java.sql.Statement;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.logging.Level;
@@ -40,12 +40,10 @@ public final class CharTemplateTable
 	
 	protected CharTemplateTable()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			Statement s = con.createStatement();
+			ResultSet rset = s.executeQuery("SELECT * FROM char_templates, lvlupgain WHERE char_templates.classId = lvlupgain.classId ORDER BY char_templates.ClassId"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			final PreparedStatement statement = con.prepareStatement("SELECT * FROM char_templates, lvlupgain WHERE char_templates.classId = lvlupgain.classId ORDER BY char_templates.ClassId");
-			final ResultSet rset = statement.executeQuery();
 			StatsSet set;
 			int cId;
 			while (rset.next())
@@ -95,18 +93,12 @@ public final class CharTemplateTable
 				final L2PcTemplate ct = new L2PcTemplate(set);
 				_charTemplates.put(ClassId.getClassId(cId), ct);
 			}
-			rset.close();
-			statement.close();
 			_log.info("CharTemplateTable: Loaded " + _charTemplates.size() + " Character Templates.");
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.SEVERE, "Failed loading char templates", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public L2PcTemplate getTemplate(final ClassId classId)

+ 41 - 81
L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/ClanTable.java

@@ -86,36 +86,27 @@ public class ClanTable
 			ForumsBBSManager.getInstance().initRoot();
 		
 		L2Clan clan;
-		Connection con = null;
-		try
-		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			// Count the clans
-			int clanCount = 0;
-			try (Statement s = con.createStatement();
-				ResultSet rs = s.executeQuery("SELECT clan_id FROM clan_data"))
+		// Count the clans
+		int clanCount = 0;
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			Statement s = con.createStatement();
+			ResultSet rs = s.executeQuery("SELECT clan_id FROM clan_data"))
+		{
+			while (rs.next())
 			{
-				while (rs.next())
-				{
-					int clanId = rs.getInt("clan_id");
-					_clans.put(clanId, new L2Clan(clanId));
-					clan = getClan(clanId);
-					if (clan.getDissolvingExpiryTime() != 0)
-						scheduleRemoveClan(clan.getClanId());
-					clanCount++;
-				}
+				int clanId = rs.getInt("clan_id");
+				_clans.put(clanId, new L2Clan(clanId));
+				clan = getClan(clanId);
+				if (clan.getDissolvingExpiryTime() != 0)
+					scheduleRemoveClan(clan.getClanId());
+				clanCount++;
 			}
-			_log.info("Restored " + clanCount + " clans from the database.");
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, "Error restoring ClanTable.", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
-		
+		_log.info("Restored " + clanCount + " clans from the database.");
 		allianceCheck();
 		restorewars();
 	}
@@ -267,10 +258,8 @@ public class ClanTable
 		_clans.remove(clanId);
 		IdFactory.getInstance().releaseId(clanId);
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("DELETE FROM clan_data WHERE clan_id=?");
 			statement.setInt(1, clanId);
 			statement.execute();
@@ -332,10 +321,6 @@ public class ClanTable
 		{
 			_log.log(Level.SEVERE, "Error removing clan from DB.", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public void scheduleRemoveClan(final int clanId)
@@ -383,27 +368,20 @@ public class ClanTable
 		clan2.setAttackerClan(clan1);
 		clan1.broadcastClanStatus();
 		clan2.broadcastClanStatus();
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement("REPLACE INTO clan_wars (clan1, clan2, wantspeace1, wantspeace2) VALUES(?,?,?,?)"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement("REPLACE INTO clan_wars (clan1, clan2, wantspeace1, wantspeace2) VALUES(?,?,?,?)"))
-			{
-				ps.setInt(1, clanId1);
-				ps.setInt(2, clanId2);
-				ps.setInt(3, 0);
-				ps.setInt(4, 0);
-				ps.execute();
-			}
+			ps.setInt(1, clanId1);
+			ps.setInt(2, clanId2);
+			ps.setInt(3, 0);
+			ps.setInt(4, 0);
+			ps.execute();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, "Error storing clan wars data.", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
+		
 		//SystemMessage msg = SystemMessage.getSystemMessage(SystemMessageId.WAR_WITH_THE_S1_CLAN_HAS_BEGUN);
 		//
 		SystemMessage msg = SystemMessage.getSystemMessage(SystemMessageId.CLAN_WAR_DECLARED_AGAINST_S1_IF_KILLED_LOSE_LOW_EXP);
@@ -442,29 +420,19 @@ public class ClanTable
 		//	if(player.getPlayerInstance()!=null)
 		//			player.getPlayerInstance().setWantsPeace(0);
 		//}
-		Connection con = null;
-		try
+		
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement("DELETE FROM clan_wars WHERE clan1=? AND clan2=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement("DELETE FROM clan_wars WHERE clan1=? AND clan2=?"))
-			{
-				ps.setInt(1, clanId1);
-				ps.setInt(2, clanId2);
-				ps.execute();
-			}
-			//statement = con.prepareStatement("DELETE FROM clan_wars WHERE clan1=? AND clan2=?");
-			//statement.setInt(1,clanId2);
-			//statement.setInt(2,clanId1);
-			//statement.execute();
+			ps.setInt(1, clanId1);
+			ps.setInt(2, clanId2);
+			ps.execute();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, "Error removing clan wars data.", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
+		
 		//SystemMessage msg = SystemMessage.getSystemMessage(SystemMessageId.WAR_WITH_THE_S1_CLAN_HAS_ENDED);
 		SystemMessage msg = SystemMessage.getSystemMessage(SystemMessageId.WAR_AGAINST_S1_HAS_STOPPED);
 		msg.addString(clan2.getName());
@@ -499,36 +467,28 @@ public class ClanTable
 	
 	private void restorewars()
 	{
-		Connection con = null;
 		L2Clan clan1, clan2;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			Statement statement = con.createStatement();
+			ResultSet rset = statement.executeQuery("SELECT clan1, clan2 FROM clan_wars"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (Statement statement = con.createStatement();
-				ResultSet rset = statement.executeQuery("SELECT clan1, clan2 FROM clan_wars"))
+			while (rset.next())
 			{
-				while (rset.next())
+				clan1 = getClan(rset.getInt("clan1"));
+				clan2 = getClan(rset.getInt("clan2"));
+				if (clan1 != null && clan2 != null)
 				{
-					clan1 = getClan(rset.getInt("clan1"));
-					clan2 = getClan(rset.getInt("clan2"));
-					if (clan1 != null && clan2 != null)
-					{
-						clan1.setEnemyClan(rset.getInt("clan2"));
-						clan2.setAttackerClan(rset.getInt("clan1"));
-					}
-					else
-						_log.log(Level.WARNING, "[ClanTable]: restorewars one of clans is null clan1:" + clan1 + " clan2:" + clan2);
+					clan1.setEnemyClan(rset.getInt("clan2"));
+					clan2.setAttackerClan(rset.getInt("clan1"));
 				}
+				else
+					_log.log(Level.WARNING, "[ClanTable]: restorewars one of clans is null clan1:" + clan1 + " clan2:" + clan2);
 			}
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, "Error restoring clan wars data.", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**

+ 52 - 73
L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/HelperBuffTable.java

@@ -76,91 +76,70 @@ public class HelperBuffTable
 	 */
 	private void restoreHelperBuffData()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			Statement s = con.createStatement();
+			ResultSet HelperBuffData = s.executeQuery("SELECT * FROM helper_buff_list"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (Statement s = con.createStatement();
-				ResultSet rs = s.executeQuery("SELECT * FROM helper_buff_list"))
+			while (HelperBuffData.next())
 			{
-				fillHelperBuffTable(rs);
-			}
-		}
-		catch (Exception e)
-		{
-			_log.log(Level.SEVERE, "Table helper_buff_list not found : Update your DataPack! Error : " + e.getMessage(), e);
-		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
-	}
-	
-	/**
-	 * Load the Newbie Helper Buff list from SQL Table helper_buff_list
-	 * @param HelperBuffData
-	 * @throws Exception
-	 */
-	private void fillHelperBuffTable(ResultSet HelperBuffData) throws Exception
-	{
-		
-		while (HelperBuffData.next())
-		{
-			StatsSet helperBuffDat = new StatsSet();
-			int id = HelperBuffData.getInt("id");
-			
-			helperBuffDat.set("id", id);
-			helperBuffDat.set("skillID", HelperBuffData.getInt("skill_id"));
-			helperBuffDat.set("skillLevel", HelperBuffData.getInt("skill_level"));
-			helperBuffDat.set("lowerLevel", HelperBuffData.getInt("lower_level"));
-			helperBuffDat.set("upperLevel", HelperBuffData.getInt("upper_level"));
-			helperBuffDat.set("isMagicClass", HelperBuffData.getString("is_magic_class"));
-			helperBuffDat.set("forSummon", HelperBuffData.getString("forSummon"));
-			
-			// Calulate the range level in wich player must be to obtain buff from Newbie Helper
-			if ("false".equals(HelperBuffData.getString("is_magic_class")))
-			{
-				if (HelperBuffData.getInt("lower_level") < _physicClassLowestLevel)
-				{
-					_physicClassLowestLevel = HelperBuffData.getInt("lower_level");
-				}
+				StatsSet helperBuffDat = new StatsSet();
+				int id = HelperBuffData.getInt("id");
 				
-				if (HelperBuffData.getInt("upper_level") > _physicClassHighestLevel)
-				{
-					_physicClassHighestLevel = HelperBuffData.getInt("upper_level");
-				}
-			}
-			else
-			{
-				if (HelperBuffData.getInt("lower_level") < _magicClassLowestLevel)
-				{
-					_magicClassLowestLevel = HelperBuffData.getInt("lower_level");
-				}
+				helperBuffDat.set("id", id);
+				helperBuffDat.set("skillID", HelperBuffData.getInt("skill_id"));
+				helperBuffDat.set("skillLevel", HelperBuffData.getInt("skill_level"));
+				helperBuffDat.set("lowerLevel", HelperBuffData.getInt("lower_level"));
+				helperBuffDat.set("upperLevel", HelperBuffData.getInt("upper_level"));
+				helperBuffDat.set("isMagicClass", HelperBuffData.getString("is_magic_class"));
+				helperBuffDat.set("forSummon", HelperBuffData.getString("forSummon"));
 				
-				if (HelperBuffData.getInt("upper_level") > _magicClassHighestLevel)
+				// Calulate the range level in wich player must be to obtain buff from Newbie Helper
+				if ("false".equals(HelperBuffData.getString("is_magic_class")))
 				{
-					_magicClassHighestLevel = HelperBuffData.getInt("upper_level");
+					if (HelperBuffData.getInt("lower_level") < _physicClassLowestLevel)
+					{
+						_physicClassLowestLevel = HelperBuffData.getInt("lower_level");
+					}
+					
+					if (HelperBuffData.getInt("upper_level") > _physicClassHighestLevel)
+					{
+						_physicClassHighestLevel = HelperBuffData.getInt("upper_level");
+					}
 				}
-			}
-			if ("true".equals(HelperBuffData.getString("forSummon")))
-			{
-				if (HelperBuffData.getInt("lower_level") < _servitorLowestLevel)
+				else
 				{
-					_servitorLowestLevel = HelperBuffData.getInt("lower_level");
+					if (HelperBuffData.getInt("lower_level") < _magicClassLowestLevel)
+					{
+						_magicClassLowestLevel = HelperBuffData.getInt("lower_level");
+					}
+					
+					if (HelperBuffData.getInt("upper_level") > _magicClassHighestLevel)
+					{
+						_magicClassHighestLevel = HelperBuffData.getInt("upper_level");
+					}
 				}
-				
-				if (HelperBuffData.getInt("upper_level") > _servitorHighestLevel)
+				if ("true".equals(HelperBuffData.getString("forSummon")))
 				{
-					_servitorHighestLevel = HelperBuffData.getInt("upper_level");
+					if (HelperBuffData.getInt("lower_level") < _servitorLowestLevel)
+					{
+						_servitorLowestLevel = HelperBuffData.getInt("lower_level");
+					}
+					
+					if (HelperBuffData.getInt("upper_level") > _servitorHighestLevel)
+					{
+						_servitorHighestLevel = HelperBuffData.getInt("upper_level");
+					}
 				}
+				// Add this Helper Buff to the Helper Buff List
+				L2HelperBuff template = new L2HelperBuff(helperBuffDat);
+				_helperBuff.add(template);
 			}
-			// Add this Helper Buff to the Helper Buff List
-			L2HelperBuff template = new L2HelperBuff(helperBuffDat);
-			_helperBuff.add(template);
+			_log.info("Helper Buff Table: Loaded " + _helperBuff.size() + " Templates.");
+		}
+		catch (Exception e)
+		{
+			_log.log(Level.SEVERE, "Table helper_buff_list not found : Update your DataPack! Error : " + e.getMessage(), e);
 		}
-		
-		_log.info("Helper Buff Table: Loaded " + _helperBuff.size() + " Templates.");
-		
 	}
 	
 	/**

+ 5 - 18
L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/HerbDropTable.java

@@ -50,21 +50,15 @@ public class HerbDropTable
 		restoreData();
 	}
 	
-	/**
-	 *
-	 */
 	private void restoreData()
 	{
-		Connection con = null;
-		try
-		{
-			con = L2DatabaseFactory.getInstance().getConnection();
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT "
-					+ L2DatabaseFactory.getInstance().safetyString(new String[] { "groupId", "itemId", "min", "max", "category", "chance" })
-					+ " FROM herb_droplist_groups ORDER BY groupId, chance DESC");
-			ResultSet dropData = statement.executeQuery();
+				+ L2DatabaseFactory.getInstance().safetyString(new String[] { "groupId", "itemId", "min", "max", "category", "chance" })
+				+ " FROM herb_droplist_groups ORDER BY groupId, chance DESC");
+			ResultSet dropData = statement.executeQuery())
+		{
 			L2DropData dropDat = null;
-			
 			while (dropData.next())
 			{
 				int groupId = dropData.getInt("groupId");
@@ -109,18 +103,11 @@ public class HerbDropTable
 					category.add(cat);
 				}
 			}
-			
-			dropData.close();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, "HerbDroplistGroupsTable: Error reading Herb dropdata. ", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public FastList<L2DropCategory> getHerbDroplist(int groupId)

+ 2 - 9
L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/ItemTable.java

@@ -424,24 +424,17 @@ public class ItemTable
 			// if it's a pet control item, delete the pet as well
 			if (item.getItem().isPetItem())
 			{
-				Connection con = null;
-				try
+				try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+					PreparedStatement statement = con.prepareStatement("DELETE FROM pets WHERE item_obj_id=?"))
 				{
 					// Delete the pet in db
-					con = L2DatabaseFactory.getInstance().getConnection();
-					PreparedStatement statement = con.prepareStatement("DELETE FROM pets WHERE item_obj_id=?");
 					statement.setInt(1, item.getObjectId());
 					statement.execute();
-					statement.close();
 				}
 				catch (Exception e)
 				{
 					_log.log(Level.WARNING, "could not delete pet objectid:", e);
 				}
-				finally
-				{
-					L2DatabaseFactory.close(con);
-				}
 			}
 		}
 	}

+ 20 - 28
L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/LevelUpData.java

@@ -59,42 +59,34 @@ public class LevelUpData
 	protected LevelUpData()
 	{
 		_lvlTable = new TIntObjectHashMap<>();
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			Statement s = con.createStatement();
+			ResultSet rs = s.executeQuery(SELECT_ALL))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (Statement s = con.createStatement();
-				ResultSet rs = s.executeQuery(SELECT_ALL))
+			L2LvlupData lvlDat;
+			while (rs.next())
 			{
-				L2LvlupData lvlDat;
-				while (rs.next())
-				{
-					lvlDat = new L2LvlupData();
-					lvlDat.setClassid(rs.getInt(CLASS_ID));
-					lvlDat.setClassLvl(rs.getInt(CLASS_LVL));
-					lvlDat.setClassHpBase(rs.getFloat(HP_BASE));
-					lvlDat.setClassHpAdd(rs.getFloat(HP_ADD));
-					lvlDat.setClassHpModifier(rs.getFloat(HP_MOD));
-					lvlDat.setClassCpBase(rs.getFloat(CP_BASE));
-					lvlDat.setClassCpAdd(rs.getFloat(CP_ADD));
-					lvlDat.setClassCpModifier(rs.getFloat(CP_MOD));
-					lvlDat.setClassMpBase(rs.getFloat(MP_BASE));
-					lvlDat.setClassMpAdd(rs.getFloat(MP_ADD));
-					lvlDat.setClassMpModifier(rs.getFloat(MP_MOD));
-					
-					_lvlTable.put(lvlDat.getClassid(), lvlDat);
-				}
+				lvlDat = new L2LvlupData();
+				lvlDat.setClassid(rs.getInt(CLASS_ID));
+				lvlDat.setClassLvl(rs.getInt(CLASS_LVL));
+				lvlDat.setClassHpBase(rs.getFloat(HP_BASE));
+				lvlDat.setClassHpAdd(rs.getFloat(HP_ADD));
+				lvlDat.setClassHpModifier(rs.getFloat(HP_MOD));
+				lvlDat.setClassCpBase(rs.getFloat(CP_BASE));
+				lvlDat.setClassCpAdd(rs.getFloat(CP_ADD));
+				lvlDat.setClassCpModifier(rs.getFloat(CP_MOD));
+				lvlDat.setClassMpBase(rs.getFloat(MP_BASE));
+				lvlDat.setClassMpAdd(rs.getFloat(MP_ADD));
+				lvlDat.setClassMpModifier(rs.getFloat(MP_MOD));
+				
+				_lvlTable.put(lvlDat.getClassid(), lvlDat);
 			}
-			_log.info("LevelUpData: Loaded " + _lvlTable.size() + " Character Level Up Templates.");
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, "Error loading Level Up data.", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
+		_log.info("LevelUpData: Loaded " + _lvlTable.size() + " Character Level Up Templates.");
 	}
 	
 	/**

+ 51 - 71
L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/NpcBufferTable.java

@@ -18,8 +18,9 @@ import gnu.trove.map.hash.TIntIntHashMap;
 import gnu.trove.map.hash.TIntObjectHashMap;
 
 import java.sql.Connection;
-import java.sql.PreparedStatement;
 import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
 import java.util.logging.Level;
 import java.util.logging.Logger;
 
@@ -70,20 +71,60 @@ public class NpcBufferTable
 	
 	protected NpcBufferTable()
 	{
-		Connection con = null;
 		int skillCount = 0;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			Statement s = con.createStatement();
+			ResultSet rset = s.executeQuery("SELECT `npc_id`,`skill_id`,`skill_level`,`skill_fee_id`,`skill_fee_amount`,`buff_group` FROM `npc_buffer` ORDER BY `npc_id` ASC"))
 		{
-			try
+			int lastNpcId = 0;
+			NpcBufferSkills skills = null;
+			
+			while (rset.next())
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
+				int npcId = rset.getInt("npc_id");
+				int skillId = rset.getInt("skill_id");
+				int skillLevel = rset.getInt("skill_level");
+				int skillFeeId = rset.getInt("skill_fee_id");
+				int skillFeeAmount = rset.getInt("skill_fee_amount");
+				int buffGroup = rset.getInt("buff_group");
 				
-				PreparedStatement statement = con.prepareStatement("SELECT `npc_id`,`skill_id`,`skill_level`,`skill_fee_id`,`skill_fee_amount`,`buff_group` FROM `npc_buffer` ORDER BY `npc_id` ASC");
-				ResultSet rset = statement.executeQuery();
+				if (npcId != lastNpcId)
+				{
+					if (lastNpcId != 0)
+					{
+						_buffers.put(lastNpcId, skills);
+					}
+					
+					skills = new NpcBufferSkills(npcId);
+					skills.addSkill(skillId, skillLevel, skillFeeId, skillFeeAmount, buffGroup);
+				}
+				else if (skills != null)
+				{
+					skills.addSkill(skillId, skillLevel, skillFeeId, skillFeeAmount, buffGroup);
+				}
 				
+				lastNpcId = npcId;
+				skillCount++;
+			}
+			
+			if (lastNpcId != 0)
+			{
+				_buffers.put(lastNpcId, skills);
+			}
+		}
+		catch (SQLException e)
+		{
+			_log.log(Level.SEVERE, "NpcBufferTable: Error reading npc_buffer table: " + e.getMessage(), e);
+		}
+		
+		if (Config.CUSTOM_NPCBUFFER_TABLES)
+		{
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+				Statement s = con.createStatement();
+				ResultSet rset = s.executeQuery("SELECT `npc_id`,`skill_id`,`skill_level`,`skill_fee_id`,`skill_fee_amount`,`buff_group` FROM `custom_npc_buffer` ORDER BY `npc_id` ASC"))
+			{
 				int lastNpcId = 0;
 				NpcBufferSkills skills = null;
-				
 				while (rset.next())
 				{
 					int npcId = rset.getInt("npc_id");
@@ -107,7 +148,6 @@ public class NpcBufferTable
 					{
 						skills.addSkill(skillId, skillLevel, skillFeeId, skillFeeAmount, buffGroup);
 					}
-					
 					lastNpcId = npcId;
 					skillCount++;
 				}
@@ -116,71 +156,11 @@ public class NpcBufferTable
 				{
 					_buffers.put(lastNpcId, skills);
 				}
-				rset.close();
-				statement.close();
 			}
-			catch (Exception e)
+			catch (SQLException e)
 			{
-				_log.log(Level.SEVERE, "NpcBufferTable: Error reading npc_buffer table: " + e.getMessage(), e);
+				_log.log(Level.SEVERE, "NpcBufferTable: Error reading custom_npc_buffer table: " + e.getMessage(), e);
 			}
-			
-			if (Config.CUSTOM_NPCBUFFER_TABLES)
-			{
-				try
-				{
-					if (con == null)
-					{
-						con = L2DatabaseFactory.getInstance().getConnection();
-					}
-					PreparedStatement statement = con.prepareStatement("SELECT `npc_id`,`skill_id`,`skill_level`,`skill_fee_id`,`skill_fee_amount`,`buff_group` FROM `custom_npc_buffer` ORDER BY `npc_id` ASC");
-					ResultSet rset = statement.executeQuery();
-					
-					int lastNpcId = 0;
-					NpcBufferSkills skills = null;
-					
-					while (rset.next())
-					{
-						int npcId = rset.getInt("npc_id");
-						int skillId = rset.getInt("skill_id");
-						int skillLevel = rset.getInt("skill_level");
-						int skillFeeId = rset.getInt("skill_fee_id");
-						int skillFeeAmount = rset.getInt("skill_fee_amount");
-						int buffGroup = rset.getInt("buff_group");
-						
-						if (npcId != lastNpcId)
-						{
-							if (lastNpcId != 0)
-							{
-								_buffers.put(lastNpcId, skills);
-							}
-							
-							skills = new NpcBufferSkills(npcId);
-							skills.addSkill(skillId, skillLevel, skillFeeId, skillFeeAmount, buffGroup);
-						}
-						else if (skills != null)
-						{
-							skills.addSkill(skillId, skillLevel, skillFeeId, skillFeeAmount, buffGroup);
-						}
-						lastNpcId = npcId;
-						skillCount++;
-					}
-					
-					if (lastNpcId != 0)
-					{
-						_buffers.put(lastNpcId, skills);
-					}
-					rset.close();
-					statement.close();
-				}
-				catch (Exception e)
-				{
-					_log.log(Level.SEVERE, "NpcBufferTable: Error reading custom_npc_buffer table: " + e.getMessage(), e);
-				}
-			}
-		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
 		}
 		_log.info("NpcBufferSkillIdsTable: Loaded " + _buffers.size() + " buffers and " + skillCount + " skills.");
 	}

+ 59 - 114
L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/NpcTable.java

@@ -63,6 +63,12 @@ public class NpcTable
 	private static final String SELECT_NPC_ELEMENTALS_ALL = "SELECT * FROM npc_elementals ORDER BY npc_id";
 	private static final String SELECT_NPC_ELEMENTALS_BY_ID = "SELECT * FROM npc_elementals WHERE npc_id = ?";
 	
+	private static final String SELECT_SKILL_LEARN_ALL = "SELECT * FROM skill_learn";
+	private static final String SELECT_SKILL_LEARN_BY_ID = "SELECT * FROM skill_learn WHERE npc_id = ?";
+	
+	private static final String SELECT_MINION_ALL = "SELECT * FROM minions ORDER BY boss_id";
+	private static final String SELECT_MINION_BY_ID = "SELECT * FROM minions WHERE boss_id = ?";
+	
 	// Custom SQL queries
 	private static final String CUSTOM_SELECT_NPC_ALL = "SELECT * FROM custom_npc ORDER BY id";
 	private static final String CUSTOM_SELECT_NPC_BY_ID = "SELECT * FROM custom_npc WHERE id = ?";
@@ -262,10 +268,8 @@ public class NpcTable
 			}
 		}
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			int updated = 0;
 			final int npcId = npc.getInteger("npcId");
 			if (Config.CUSTOM_NPC_TABLE)
@@ -284,10 +288,6 @@ public class NpcTable
 		{
 			_log.log(Level.WARNING, getClass().getSimpleName() + ": Could not store new NPC data in database: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -457,10 +457,8 @@ public class NpcTable
 	 */
 	public void loadNpcs(int id)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			int count = loadNpcs(con, id, false);
 			int ccount = 0;
 			if (Config.CUSTOM_NPC_TABLE)
@@ -473,10 +471,6 @@ public class NpcTable
 		{
 			_log.log(Level.SEVERE, getClass().getSimpleName() + ": Error reading NPC AI Data: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -522,10 +516,8 @@ public class NpcTable
 	 */
 	public void loadNpcsSkills(int id)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			int count = loadNpcsSkills(con, id, false);
 			int ccount = 0;
 			if (Config.CUSTOM_NPC_SKILLS_TABLE)
@@ -538,10 +530,6 @@ public class NpcTable
 		{
 			_log.log(Level.SEVERE, getClass().getSimpleName() + ": Error reading NPC AI Data: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -610,10 +598,8 @@ public class NpcTable
 	 */
 	public void loadNpcsDrop(int id)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			int count = loadNpcsDrop(con, id, false);
 			int ccount = 0;
 			if (Config.CUSTOM_DROPLIST_TABLE)
@@ -626,10 +612,6 @@ public class NpcTable
 		{
 			_log.log(Level.SEVERE, getClass().getSimpleName() + ": Error reading NPC AI Data: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -694,55 +676,42 @@ public class NpcTable
 	 */
 	private void loadNpcsSkillLearn(int id)
 	{
-		Connection con = null;
-		try
+		final String query = (id > 0) ? SELECT_SKILL_LEARN_BY_ID : SELECT_SKILL_LEARN_ALL;
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement(query))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement;
 			if (id > 0)
 			{
-				statement = con.prepareStatement("SELECT * FROM skill_learn WHERE npc_id = ?");
 				statement.setInt(1, id);
 			}
-			else
-			{
-				statement = con.prepareStatement("SELECT * FROM skill_learn");
-			}
-			
-			ResultSet rset = statement.executeQuery();
 			
-			int cont = 0;
-			int npcId;
-			int classId;
-			L2NpcTemplate npc;
-			while (rset.next())
+			int count = 0;
+			try (ResultSet rs = statement.executeQuery())
 			{
-				npcId = rset.getInt("npc_id");
-				classId = rset.getInt("class_id");
-				npc = getTemplate(npcId);
-				if (npc == null)
+				int npcId;
+				int classId;
+				L2NpcTemplate npc;
+				while (rs.next())
 				{
-					_log.warning(getClass().getSimpleName() + ": Error getting NPC template ID " + npcId + " while trying to load skill trainer data.");
-					continue;
+					npcId = rs.getInt("npc_id");
+					classId = rs.getInt("class_id");
+					npc = getTemplate(npcId);
+					if (npc == null)
+					{
+						_log.warning(getClass().getSimpleName() + ": Error getting NPC template ID " + npcId + " while trying to load skill trainer data.");
+						continue;
+					}
+					
+					count++;
+					npc.addTeachInfo(ClassId.getClassId(classId));
 				}
-				
-				cont++;
-				npc.addTeachInfo(ClassId.getClassId(classId));
 			}
-			
-			rset.close();
-			statement.close();
-			
-			_log.info(getClass().getSimpleName() + ": Loaded " + cont + " Skill Learn.");
+			_log.info(getClass().getSimpleName() + ": Loaded " + count + " Skill Learn.");
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, getClass().getSimpleName() + ": Error reading NPC trainer data.", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -751,58 +720,46 @@ public class NpcTable
 	 */
 	public void loadMinions(int id)
 	{
-		Connection con = null;
-		try
+		final String query = (id > 0) ? SELECT_MINION_BY_ID : SELECT_MINION_ALL;
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement(query))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = null;
-			
 			if (id > 0)
 			{
-				statement = con.prepareStatement("SELECT * FROM minions WHERE boss_id = ?");
 				statement.setInt(1, id);
 			}
-			else
-			{
-				statement = con.prepareStatement("SELECT * FROM minions ORDER BY boss_id");
-			}
 			
-			ResultSet rset = statement.executeQuery();
-			
-			L2MinionData minionDat = null;
-			L2NpcTemplate npcDat = null;
-			int cnt = 0;
-			int raidId;
-			while (rset.next())
+			int count = 0;
+			try (ResultSet rset = statement.executeQuery())
 			{
-				raidId = rset.getInt("boss_id");
-				npcDat = _npcs.get(raidId);
-				if (npcDat == null)
+				L2MinionData minionDat = null;
+				L2NpcTemplate npcDat = null;
+				
+				int raidId;
+				while (rset.next())
 				{
-					_log.warning(getClass().getSimpleName() + ": Minion references undefined boss NPC. Boss NpcId: " + raidId);
-					continue;
+					raidId = rset.getInt("boss_id");
+					npcDat = _npcs.get(raidId);
+					if (npcDat == null)
+					{
+						_log.warning(getClass().getSimpleName() + ": Minion references undefined boss NPC. Boss NpcId: " + raidId);
+						continue;
+					}
+					
+					minionDat = new L2MinionData();
+					minionDat.setMinionId(rset.getInt("minion_id"));
+					minionDat.setAmountMin(rset.getInt("amount_min"));
+					minionDat.setAmountMax(rset.getInt("amount_max"));
+					npcDat.addRaidData(minionDat);
+					count++;
 				}
-				
-				minionDat = new L2MinionData();
-				minionDat.setMinionId(rset.getInt("minion_id"));
-				minionDat.setAmountMin(rset.getInt("amount_min"));
-				minionDat.setAmountMax(rset.getInt("amount_max"));
-				npcDat.addRaidData(minionDat);
-				cnt++;
 			}
-			
-			rset.close();
-			statement.close();
-			_log.info(getClass().getSimpleName() + ": Loaded " + cnt + " Minions.");
+			_log.info(getClass().getSimpleName() + ": Loaded " + count + " Minions.");
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, getClass().getSimpleName() + ": Error loading minion data.", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -811,10 +768,8 @@ public class NpcTable
 	 */
 	public void loadNpcsAI(int id)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			int count = loadNpcAi(con, id, false);
 			int ccount = 0;
 			if (Config.CUSTOM_NPC_TABLE)
@@ -827,10 +782,6 @@ public class NpcTable
 		{
 			_log.log(Level.SEVERE, getClass().getSimpleName() + ": Error reading NPC AI Data: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -909,10 +860,8 @@ public class NpcTable
 	 */
 	public void loadNpcsElement(int id)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			int count = loadNpcsElement(con, id, false);
 			int ccount = 0;
 			if (Config.CUSTOM_NPC_TABLE)
@@ -925,10 +874,6 @@ public class NpcTable
 		{
 			_log.log(Level.SEVERE, getClass().getSimpleName() + ": Error reading NPC AI Data: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -949,7 +894,7 @@ public class NpcTable
 				ps.setInt(1, id);
 			}
 			
-			try (ResultSet rset = ps.executeQuery();)
+			try (ResultSet rset = ps.executeQuery())
 			{
 				L2NpcTemplate npcDat = null;
 				int npcId;

+ 57 - 74
L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/OfflineTradersTable.java

@@ -17,6 +17,7 @@ package com.l2jserver.gameserver.datatables;
 import java.sql.Connection;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
+import java.sql.Statement;
 import java.util.Calendar;
 import java.util.logging.Level;
 import java.util.logging.Logger;
@@ -46,20 +47,15 @@ public class OfflineTradersTable
 	
 	public static void storeOffliners()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement stm1 = con.prepareStatement(CLEAR_OFFLINE_TABLE);
+			PreparedStatement stm2 = con.prepareStatement(CLEAR_OFFLINE_TABLE_ITEMS);
+			PreparedStatement stm3 = con.prepareStatement(SAVE_OFFLINE_STATUS);
+			PreparedStatement stm_items = con.prepareStatement(SAVE_ITEMS))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement stm = con.prepareStatement(CLEAR_OFFLINE_TABLE);
-			stm.execute();
-			stm.close();
-			stm = con.prepareStatement(CLEAR_OFFLINE_TABLE_ITEMS);
-			stm.execute();
-			stm.close();
-			
+			stm1.execute();
+			stm2.execute();
 			con.setAutoCommit(false); // avoid halfway done
-			stm = con.prepareStatement(SAVE_OFFLINE_STATUS);
-			PreparedStatement stm_items = con.prepareStatement(SAVE_ITEMS);
 			
 			//TextBuilder items = TextBuilder.newInstance();
 			for (L2PcInstance pc : L2World.getInstance().getAllPlayersArray())
@@ -68,9 +64,9 @@ public class OfflineTradersTable
 				{
 					if ((pc.getPrivateStoreType() != L2PcInstance.STORE_PRIVATE_NONE) && (pc.getClient() == null || pc.getClient().isDetached()))
 					{
-						stm.setInt(1, pc.getObjectId()); //Char Id
-						stm.setLong(2, pc.getOfflineStartTime());
-						stm.setInt(3, pc.getPrivateStoreType()); //store type
+						stm3.setInt(1, pc.getObjectId()); //Char Id
+						stm3.setLong(2, pc.getOfflineStartTime());
+						stm3.setInt(3, pc.getPrivateStoreType()); //store type
 						String title = null;
 						
 						switch (pc.getPrivateStoreType())
@@ -118,9 +114,9 @@ public class OfflineTradersTable
 									stm_items.clearParameters();
 								}
 						}
-						stm.setString(4, title);
-						stm.executeUpdate();
-						stm.clearParameters();
+						stm3.setString(4, title);
+						stm3.executeUpdate();
+						stm3.clearParameters();
 						con.commit(); // flush
 					}
 				}
@@ -129,30 +125,22 @@ public class OfflineTradersTable
 					_log.log(Level.WARNING, "OfflineTradersTable[storeTradeItems()]: Error while saving offline trader: " + pc.getObjectId() + " " + e, e);
 				}
 			}
-			stm.close();
-			stm_items.close();
 			_log.info("Offline traders stored.");
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING,"OfflineTradersTable[storeTradeItems()]: Error while saving offline traders: " + e,e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public static void restoreOfflineTraders()
 	{
 		_log.info("Loading offline traders...");
-		Connection con = null;
 		int nTraders = 0;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			Statement stm = con.createStatement();
+			ResultSet rs = stm.executeQuery(LOAD_OFFLINE_STATUS))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement stm = con.prepareStatement(LOAD_OFFLINE_STATUS);
-			ResultSet rs = stm.executeQuery();
 			while (rs.next())
 			{
 				long time = rs.getLong("time");
@@ -184,43 +172,43 @@ public class OfflineTradersTable
 					player.setOfflineStartTime(time);
 					player.spawnMe(player.getX(), player.getY(), player.getZ());
 					LoginServerThread.getInstance().addGameServerLogin(player.getAccountName(), client);
-					PreparedStatement stm_items = con.prepareStatement(LOAD_OFFLINE_ITEMS);
-					stm_items.setInt(1, player.getObjectId());
-					ResultSet items = stm_items.executeQuery();
-					
-					switch (type)
+					try (PreparedStatement stm_items = con.prepareStatement(LOAD_OFFLINE_ITEMS))
 					{
-						case L2PcInstance.STORE_PRIVATE_BUY:
-							while (items.next())
-							{
-								if (player.getBuyList().addItemByItemId(items.getInt(2), items.getLong(3), items.getLong(4)) == null)
-									throw new NullPointerException();
-							}
-							player.getBuyList().setTitle(rs.getString("title"));
-							break;
-						case L2PcInstance.STORE_PRIVATE_SELL:
-						case L2PcInstance.STORE_PRIVATE_PACKAGE_SELL:
-							while (items.next())
-							{
-								if (player.getSellList().addItem(items.getInt(2), items.getLong(3), items.getLong(4)) == null)
-									throw new NullPointerException();
-							}
-							player.getSellList().setTitle(rs.getString("title"));
-							player.getSellList().setPackaged(type == L2PcInstance.STORE_PRIVATE_PACKAGE_SELL);
-							break;
-						case L2PcInstance.STORE_PRIVATE_MANUFACTURE:
-							L2ManufactureList createList = new L2ManufactureList();
-							while (items.next())
+						stm_items.setInt(1, player.getObjectId());
+						try (ResultSet items = stm_items.executeQuery())
+						{
+							switch (type)
 							{
-								createList.add(new L2ManufactureItem(items.getInt(2), items.getLong(4)));
+								case L2PcInstance.STORE_PRIVATE_BUY:
+									while (items.next())
+									{
+										if (player.getBuyList().addItemByItemId(items.getInt(2), items.getLong(3), items.getLong(4)) == null)
+											throw new NullPointerException();
+									}
+									player.getBuyList().setTitle(rs.getString("title"));
+									break;
+								case L2PcInstance.STORE_PRIVATE_SELL:
+								case L2PcInstance.STORE_PRIVATE_PACKAGE_SELL:
+									while (items.next())
+									{
+										if (player.getSellList().addItem(items.getInt(2), items.getLong(3), items.getLong(4)) == null)
+											throw new NullPointerException();
+									}
+									player.getSellList().setTitle(rs.getString("title"));
+									player.getSellList().setPackaged(type == L2PcInstance.STORE_PRIVATE_PACKAGE_SELL);
+									break;
+								case L2PcInstance.STORE_PRIVATE_MANUFACTURE:
+									L2ManufactureList createList = new L2ManufactureList();
+									while (items.next())
+									{
+										createList.add(new L2ManufactureItem(items.getInt(2), items.getLong(4)));
+									}
+									player.setCreateList(createList);
+									player.getCreateList().setStoreName(rs.getString("title"));
+									break;
 							}
-							player.setCreateList(createList);
-							player.getCreateList().setStoreName(rs.getString("title"));
-							break;
+						}
 					}
-					items.close();
-					stm_items.close();
-					
 					player.sitDown();
 					if (Config.OFFLINE_SET_NAME_COLOR)
 						player.getAppearance().setNameColor(Config.OFFLINE_NAME_COLOR);
@@ -239,23 +227,18 @@ public class OfflineTradersTable
 					}
 				}
 			}
-			rs.close();
-			stm.close();
+			
 			_log.info("Loaded: " +nTraders+ " offline trader(s)");
-			stm = con.prepareStatement(CLEAR_OFFLINE_TABLE);
-			stm.execute();
-			stm.close();
-			stm = con.prepareStatement(CLEAR_OFFLINE_TABLE_ITEMS);
-			stm.execute();
-			stm.close();
+			
+			try (Statement stm1 = con.createStatement())
+			{
+				stm1.execute(CLEAR_OFFLINE_TABLE);
+				stm1.execute(CLEAR_OFFLINE_TABLE_ITEMS);
+			}
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "OfflineTradersTable[loadOffliners()]: Error while loading offline traders: ",e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 }

+ 13 - 22
L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/PetNameTable.java

@@ -39,36 +39,27 @@ public class PetNameTable
 	public boolean doesPetNameExist(String name, int petNpcId)
 	{
 		boolean result = true;
-		Connection con = null;
-		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement("SELECT name FROM pets p, items i WHERE p.item_obj_id = i.object_id AND name=? AND i.item_id IN (?)"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement("SELECT name FROM pets p, items i WHERE p.item_obj_id = i.object_id AND name=? AND i.item_id IN (?)"))
+			ps.setString(1, name);
+			StringBuilder cond = new StringBuilder();
+			for (int it : PetDataTable.getPetItemsByNpc(petNpcId))
+			{
+				if (!cond.toString().isEmpty())
+					cond.append(", ");
+				cond.append(it);
+			}
+			ps.setString(2, cond.toString());
+			try (ResultSet rs = ps.executeQuery())
 			{
-				ps.setString(1, name);
-				StringBuilder cond = new StringBuilder();
-				for (int it : PetDataTable.getPetItemsByNpc(petNpcId))
-				{
-					if (!cond.toString().isEmpty())
-						cond.append(", ");
-					cond.append(it);
-				}
-				ps.setString(2, cond.toString());
-				try (ResultSet rs = ps.executeQuery())
-				{
-					result = rs.next();
-				}
+				result = rs.next();
 			}
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.WARNING, "Could not check existing petname:" + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		return result;
 	}
 	

+ 8 - 35
L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/SpawnTable.java

@@ -40,7 +40,7 @@ public class SpawnTable
 {
 	private static Logger _log = Logger.getLogger(SpawnTable.class.getName());
 	
-	private FastSet<L2Spawn> _spawntable = new FastSet<L2Spawn>().shared();
+	private FastSet<L2Spawn> _spawntable = new FastSet<>();
 	private int _npcSpawnCount;
 	private int _customSpawnCount;
 	
@@ -51,6 +51,7 @@ public class SpawnTable
 	
 	protected SpawnTable()
 	{
+		_spawntable.shared();
 		if (!Config.ALT_DEV_NO_SPAWNS)
 			fillSpawnTable();
 	}
@@ -62,11 +63,8 @@ public class SpawnTable
 	
 	private void fillSpawnTable()
 	{
-		Connection con = null;
-		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT count, npc_templateid, locx, locy, locz, heading, respawn_delay, loc_id, periodOfDay FROM spawnlist");
 			ResultSet rset = statement.executeQuery();
 			
@@ -133,18 +131,13 @@ public class SpawnTable
 			// problem with initializing spawn, go to next one
 			_log.log(Level.WARNING, "SpawnTable: Spawn could not be initialized: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
 		_log.info("SpawnTable: Loaded " + _spawntable.size() + " Npc Spawn Locations.");
 		
 		if (Config.CUSTOM_SPAWNLIST_TABLE)
 		{
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
 				PreparedStatement statement = con.prepareStatement("SELECT count, npc_templateid, locx, locy, locz, heading, respawn_delay, loc_id, periodOfDay FROM custom_spawnlist");
 				ResultSet rset = statement.executeQuery();
 				
@@ -212,10 +205,6 @@ public class SpawnTable
 				// problem with initializing spawn, go to next one
 				_log.log(Level.WARNING, "CustomSpawnTable: Spawn could not be initialized: " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 			_log.info("CustomSpawnTable: Loaded " + _customSpawnCount + " Npc Spawn Locations.");
 			
 		}
@@ -237,12 +226,9 @@ public class SpawnTable
 			else
 				spawnTable = "spawnlist";
 			
-			Connection con = null;
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+				PreparedStatement statement = con.prepareStatement("INSERT INTO " + spawnTable + "(count,npc_templateid,locx,locy,locz,heading,respawn_delay,loc_id) values(?,?,?,?,?,?,?,?)"))
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
-				PreparedStatement statement = con.prepareStatement("INSERT INTO " + spawnTable
-						+ "(count,npc_templateid,locx,locy,locz,heading,respawn_delay,loc_id) values(?,?,?,?,?,?,?,?)");
 				statement.setInt(1, spawn.getAmount());
 				statement.setInt(2, spawn.getNpcid());
 				statement.setInt(3, spawn.getLocx());
@@ -252,17 +238,12 @@ public class SpawnTable
 				statement.setInt(7, spawn.getRespawnDelay() / 1000);
 				statement.setInt(8, spawn.getLocation());
 				statement.execute();
-				statement.close();
 			}
 			catch (Exception e)
 			{
 				// problem with storing spawn
 				_log.log(Level.WARNING, "SpawnTable: Could not store spawn in the DB:" + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 		}
 	}
 	
@@ -273,29 +254,21 @@ public class SpawnTable
 		
 		if (updateDb)
 		{
-			Connection con = null;
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+				PreparedStatement statement = con.prepareStatement("DELETE FROM " + (spawn.isCustom() ? "custom_spawnlist" : "spawnlist") + " WHERE locx=? AND locy=? AND locz=? AND npc_templateid=? AND heading=?"))
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
-				PreparedStatement statement = con.prepareStatement("DELETE FROM "
-						+ (spawn.isCustom() ? "custom_spawnlist" : "spawnlist") + " WHERE locx=? AND locy=? AND locz=? AND npc_templateid=? AND heading=?");
 				statement.setInt(1, spawn.getLocx());
 				statement.setInt(2, spawn.getLocy());
 				statement.setInt(3, spawn.getLocz());
 				statement.setInt(4, spawn.getNpcid());
 				statement.setInt(5, spawn.getHeading());
 				statement.execute();
-				statement.close();
 			}
 			catch (Exception e)
 			{
 				// problem with deleting spawn
 				_log.log(Level.WARNING, "SpawnTable: Spawn " + spawn + " could not be removed from DB: " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 		}
 	}
 	

+ 50 - 53
L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/SummonItemsData.java

@@ -38,67 +38,64 @@ public class SummonItemsData
 	
 	protected SummonItemsData()
 	{
-		Scanner s;
-		try
+		try (Scanner s = new Scanner(new File(Config.DATAPACK_ROOT + "/data/summon_items.csv")))
 		{
-			s = new Scanner(new File(Config.DATAPACK_ROOT + "/data/summon_items.csv"));
-		}
-		catch (Exception e)
-		{
-			_log.warning("Summon items data: Can not find '" + Config.DATAPACK_ROOT + "/data/summon_items.csv'");
-			return;
-		}
-		
-		int lineCount = 0;
-		
-		while (s.hasNextLine())
-		{
-			lineCount++;
-			
-			String line = s.nextLine();
+			int lineCount = 0;
 			
-			if (line.startsWith("#"))
+			while (s.hasNextLine())
 			{
-				continue;
-			}
-			else if (line.isEmpty())
-			{
-				continue;
-			}
-			
-			String[] lineSplit = line.split(";");
-			boolean ok = true;
-			int itemID = 0, npcID = 0;
-			byte summonType = 0;
-			int despawn = -1;
-			
-			try
-			{
-				itemID = Integer.parseInt(lineSplit[0]);
-				npcID = Integer.parseInt(lineSplit[1]);
-				summonType = Byte.parseByte(lineSplit[2]);
-				if (summonType == 0)
+				lineCount++;
+				
+				String line = s.nextLine();
+				
+				if (line.startsWith("#"))
 				{
-					despawn = Integer.parseInt(lineSplit[3]);
+					continue;
 				}
-			}
-			catch (Exception e)
-			{
-				_log.warning("Summon items data: Error in line " + lineCount + " -> incomplete/invalid data or wrong seperator!");
-				_log.warning("		" + line);
-				ok = false;
-			}
-			
-			if (!ok)
-			{
-				continue;
+				else if (line.isEmpty())
+				{
+					continue;
+				}
+				
+				String[] lineSplit = line.split(";");
+				boolean ok = true;
+				int itemID = 0, npcID = 0;
+				byte summonType = 0;
+				int despawn = -1;
+				
+				try
+				{
+					itemID = Integer.parseInt(lineSplit[0]);
+					npcID = Integer.parseInt(lineSplit[1]);
+					summonType = Byte.parseByte(lineSplit[2]);
+					if (summonType == 0)
+					{
+						despawn = Integer.parseInt(lineSplit[3]);
+					}
+				}
+				catch (Exception e)
+				{
+					_log.warning("Summon items data: Error in line " + lineCount + " -> incomplete/invalid data or wrong seperator!");
+					_log.warning("		" + line);
+					ok = false;
+				}
+				
+				if (!ok)
+				{
+					continue;
+				}
+				
+				L2SummonItem summonitem = new L2SummonItem(itemID, npcID, summonType, despawn);
+				_summonitems.put(itemID, summonitem);
 			}
 			
-			L2SummonItem summonitem = new L2SummonItem(itemID, npcID, summonType, despawn);
-			_summonitems.put(itemID, summonitem);
+			_log.info("Summon items data: Loaded " + _summonitems.size() + " summon items.");
+		}
+		catch (Exception e)
+		{
+			_log.warning("Summon items data: Can not find '" + Config.DATAPACK_ROOT + "/data/summon_items.csv'");
+			return;
 		}
-		
-		_log.info("Summon items data: Loaded " + _summonitems.size() + " summon items.");
 	}
 	
 	public L2SummonItem getSummonItem(int itemId)

+ 29 - 43
L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/SummonSkillsTable.java

@@ -54,60 +54,46 @@ public class SummonSkillsTable
 	{
 		int npcId = 0;
 		int count = 0;
-		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try
+			PreparedStatement statement = con.prepareStatement("SELECT id FROM npc WHERE type IN ('L2Pet','L2BabyPet','L2SiegeSummon') ORDER BY id");
+			ResultSet petlist = statement.executeQuery();
+			Map<Integer, L2PetSkillLearn> map;
+			L2PetSkillLearn skillLearn;
+			
+			PreparedStatement statement2 = con.prepareStatement("SELECT minLvl, skillId, skillLvl FROM pets_skills where templateId=? ORDER BY skillId, skillLvl");
+			while (petlist.next())
 			{
-				PreparedStatement statement = con.prepareStatement("SELECT id FROM npc WHERE type IN ('L2Pet','L2BabyPet','L2SiegeSummon') ORDER BY id");
-				ResultSet petlist = statement.executeQuery();
-				Map<Integer, L2PetSkillLearn> map;
-				L2PetSkillLearn skillLearn;
+				map = new FastMap<>();
+				npcId = petlist.getInt("id");
+				statement2.setInt(1, npcId);
+				ResultSet skilltree = statement2.executeQuery();
+				statement2.clearParameters();
 				
-				PreparedStatement statement2 = con.prepareStatement("SELECT minLvl, skillId, skillLvl FROM pets_skills where templateId=? ORDER BY skillId, skillLvl");
-				while (petlist.next())
+				while (skilltree.next())
 				{
-					map = new FastMap<>();
-					npcId = petlist.getInt("id");
-					statement2.setInt(1, npcId);
-					ResultSet skilltree = statement2.executeQuery();
-					statement2.clearParameters();
-					
-					while (skilltree.next())
-					{
-						int id = skilltree.getInt("skillId");
-						int lvl = skilltree.getInt("skillLvl");
-						int minLvl = skilltree.getInt("minLvl");
-						
-						skillLearn = new L2PetSkillLearn(id, lvl, minLvl);
-						map.put(SkillTable.getSkillHashCode(id, lvl + 1), skillLearn);
-					}
-					_skillTrees.put(npcId, map);
-					skilltree.close();
+					int id = skilltree.getInt("skillId");
+					int lvl = skilltree.getInt("skillLvl");
+					int minLvl = skilltree.getInt("minLvl");
 					
-					count += map.size();
-					_log.fine("PetSkillsTable: skill tree for pet " + npcId + " has " + map.size() + " skills");
+					skillLearn = new L2PetSkillLearn(id, lvl, minLvl);
+					map.put(SkillTable.getSkillHashCode(id, lvl + 1), skillLearn);
 				}
-				statement2.close();
-				petlist.close();
-				statement.close();
-			}
-			catch (Exception e)
-			{
-				_log.log(Level.SEVERE, "Error while creating pet skill tree (Pet ID " + npcId + "): " + e.getMessage(), e);
+				_skillTrees.put(npcId, map);
+				skilltree.close();
+				
+				count += map.size();
+				_log.fine("PetSkillsTable: skill tree for pet " + npcId + " has " + map.size() + " skills");
 			}
-			_log.info("PetSkillsTable: Loaded " + count + " skills.");
+			statement2.close();
+			petlist.close();
+			statement.close();
 		}
 		catch (Exception e)
 		{
-			_log.log(Level.SEVERE, "Error while loading pet skills tables: " + e.getMessage(), e);
-		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
+			_log.log(Level.SEVERE, "Error while creating pet skill tree (Pet ID " + npcId + "): " + e.getMessage(), e);
 		}
+		_log.info("PetSkillsTable: Loaded " + count + " skills.");
 	}
 	
 	public int getAvailableLevel(L2Summon cha, int skillId)

+ 32 - 47
L2J_Server_BETA/java/com/l2jserver/gameserver/datatables/TeleportLocationTable.java

@@ -50,19 +50,43 @@ public class TeleportLocationTable
 	public void reloadAll()
 	{
 		_teleports = new TIntObjectHashMap<>();
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			Statement s = con.createStatement();
+			ResultSet rs = s.executeQuery("SELECT id, loc_x, loc_y, loc_z, price, fornoble, itemId FROM teleport"))
+		{
+			L2TeleportLocation teleport;
+			while (rs.next())
+			{
+				teleport = new L2TeleportLocation();
+				
+				teleport.setTeleId(rs.getInt("id"));
+				teleport.setLocX(rs.getInt("loc_x"));
+				teleport.setLocY(rs.getInt("loc_y"));
+				teleport.setLocZ(rs.getInt("loc_z"));
+				teleport.setPrice(rs.getInt("price"));
+				teleport.setIsForNoble(rs.getInt("fornoble") == 1);
+				teleport.setItemId(rs.getInt("itemId"));
+				
+				_teleports.put(teleport.getTeleId(), teleport);
+			}
+			_log.info("TeleportLocationTable: Loaded " + _teleports.size() + " Teleport Location Templates.");
+		}
+		catch (Exception e)
+		{
+			_log.log(Level.SEVERE, "Error loading Teleport Table.", e);
+		}
 		
-		Connection con = null;
-		try
+		if (Config.CUSTOM_TELEPORT_TABLE)
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (Statement s = con.createStatement();
-				ResultSet rs = s.executeQuery("SELECT id, loc_x, loc_y, loc_z, price, fornoble, itemId FROM teleport"))
+			int _cTeleCount = _teleports.size();
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+				Statement s = con.createStatement();
+				ResultSet rs = s.executeQuery("SELECT id, loc_x, loc_y, loc_z, price, fornoble, itemId FROM custom_teleport"))
 			{
 				L2TeleportLocation teleport;
 				while (rs.next())
 				{
 					teleport = new L2TeleportLocation();
-					
 					teleport.setTeleId(rs.getInt("id"));
 					teleport.setLocX(rs.getInt("loc_x"));
 					teleport.setLocY(rs.getInt("loc_y"));
@@ -73,55 +97,16 @@ public class TeleportLocationTable
 					
 					_teleports.put(teleport.getTeleId(), teleport);
 				}
-			}
-			_log.info("TeleportLocationTable: Loaded " + _teleports.size() + " Teleport Location Templates.");
-		}
-		catch (Exception e)
-		{
-			_log.log(Level.SEVERE, "Error loading Teleport Table.", e);
-		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
-		
-		if (Config.CUSTOM_TELEPORT_TABLE)
-		{
-			try
-			{
-				con = L2DatabaseFactory.getInstance().getConnection();
-				int _cTeleCount = _teleports.size();
-				try (Statement s = con.createStatement();
-					ResultSet rs = s.executeQuery("SELECT id, loc_x, loc_y, loc_z, price, fornoble, itemId FROM custom_teleport"))
-				{
-					L2TeleportLocation teleport;
-					
-					while (rs.next())
-					{
-						teleport = new L2TeleportLocation();
-						teleport.setTeleId(rs.getInt("id"));
-						teleport.setLocX(rs.getInt("loc_x"));
-						teleport.setLocY(rs.getInt("loc_y"));
-						teleport.setLocZ(rs.getInt("loc_z"));
-						teleport.setPrice(rs.getInt("price"));
-						teleport.setIsForNoble(rs.getInt("fornoble") == 1);
-						teleport.setItemId(rs.getInt("itemId"));
-						
-						_teleports.put(teleport.getTeleId(), teleport);
-					}
-				}
 				_cTeleCount = _teleports.size() - _cTeleCount;
 				if (_cTeleCount > 0)
+				{
 					_log.info("TeleportLocationTable: Loaded " + _cTeleCount + " Custom Teleport Location Templates.");
+				}
 			}
 			catch (Exception e)
 			{
 				_log.log(Level.WARNING, "Error while creating custom teleport table " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 		}
 	}
 	

+ 0 - 1
L2J_Server_BETA/java/com/l2jserver/gameserver/idfactory/BitSetIDFactory.java

@@ -43,7 +43,6 @@ public class BitSetIDFactory extends IdFactory
 				}
 			}
 		}
-		
 	}
 	
 	protected BitSetIDFactory()

+ 1 - 7
L2J_Server_BETA/java/com/l2jserver/gameserver/idfactory/CompactionIDFactory.java

@@ -37,10 +37,8 @@ public class CompactionIDFactory extends IdFactory
 		_curOID = FIRST_OID;
 		_freeSize = 0;
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			// con.createStatement().execute("drop table if exists tmp_obj_id");
 			
 			int[] tmp_obj_ids = extractUsedObjectIDTable();
@@ -58,10 +56,6 @@ public class CompactionIDFactory extends IdFactory
 		{
 			_log.severe(getClass().getSimpleName() + ": Could not initialize properly: " + e.getMessage());
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private int insertUntil(int[] tmp_obj_ids, int idx, int N, Connection con) throws SQLException

+ 32 - 56
L2J_Server_BETA/java/com/l2jserver/gameserver/idfactory/IdFactory.java

@@ -158,24 +158,16 @@ public abstract class IdFactory
 	 */
 	private void setAllCharacterOffline()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			Statement s = con.createStatement())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (Statement s = con.createStatement())
-			{
-				s.executeUpdate("UPDATE characters SET online = 0");
-			}
+			s.executeUpdate("UPDATE characters SET online = 0");
 			_log.info("Updated characters online status.");
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.WARNING, "Could not update characters online status: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -183,14 +175,11 @@ public abstract class IdFactory
 	 */
 	private void cleanUpDB()
 	{
-		Connection con = null;
-		Statement stmt = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			Statement stmt = con.createStatement())
 		{
 			long cleanupStart = System.currentTimeMillis();
 			int cleanCount = 0;
-			con = L2DatabaseFactory.getInstance().getConnection();
-			stmt = con.createStatement();
 			// Misc/Account Related
 			// Please read the descriptions above each before uncommenting them. If you are still
 			// unsure of what exactly it does, leave it commented out. This is for those who know
@@ -289,66 +278,46 @@ public abstract class IdFactory
 			stmt.executeUpdate("UPDATE fort SET owner=0 WHERE owner NOT IN (SELECT clan_id FROM clan_data);");
 			
 			_log.info("Cleaned " + cleanCount + " elements from database in " + ((System.currentTimeMillis() - cleanupStart) / 1000) + " s");
-			stmt.close();
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.WARNING, "Could not clean up database: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void cleanInvalidWeddings()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			Statement s = con.createStatement())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (Statement s = con.createStatement())
-			{
-				s.executeUpdate("DELETE FROM mods_wedding WHERE player1Id NOT IN (SELECT charId FROM characters)");
-				s.executeUpdate("DELETE FROM mods_wedding WHERE player2Id NOT IN (SELECT charId FROM characters)");
-			}
+			s.executeUpdate("DELETE FROM mods_wedding WHERE player1Id NOT IN (SELECT charId FROM characters)");
+			s.executeUpdate("DELETE FROM mods_wedding WHERE player2Id NOT IN (SELECT charId FROM characters)");
 			_log.info("Cleaned up invalid Weddings.");
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.WARNING, "Could not clean up invalid Weddings: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void cleanUpTimeStamps()
 	{
-		Connection con = null;
-		PreparedStatement stmt = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
 			int cleanCount = 0;
-			con = L2DatabaseFactory.getInstance().getConnection();
 			for (String line : TIMESTAMPS_CLEAN)
 			{
-				stmt = con.prepareStatement(line);
-				stmt.setLong(1, System.currentTimeMillis());
-				cleanCount += stmt.executeUpdate();
-				stmt.close();
+				try (PreparedStatement stmt = con.prepareStatement(line))
+				{
+					stmt.setLong(1, System.currentTimeMillis());
+					cleanCount += stmt.executeUpdate();
+				}
 			}
-			
 			_log.info("Cleaned " + cleanCount + " expired timestamps from database.");
 		}
 		catch (SQLException e)
 		{
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -358,12 +327,8 @@ public abstract class IdFactory
 	 */
 	protected final int[] extractUsedObjectIDTable() throws Exception
 	{
-		Connection con = null;
-		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			Statement statement = null;
 			ResultSet rset = null;
 			
@@ -373,56 +338,67 @@ public abstract class IdFactory
 			rset = statement.executeQuery("SELECT COUNT(*) FROM characters");
 			rset.next();
 			temp.ensureCapacity(rset.getInt(1));
+			rset.close();
+			
 			rset = statement.executeQuery("SELECT charId FROM characters");
 			while (rset.next())
 			{
 				temp.add(rset.getInt(1));
 			}
+			rset.close();
 			
 			rset = statement.executeQuery("SELECT COUNT(*) FROM items");
 			rset.next();
 			temp.ensureCapacity(temp.size() + rset.getInt(1));
+			rset.close();
+			
 			rset = statement.executeQuery("SELECT object_id FROM items");
 			while (rset.next())
 			{
 				temp.add(rset.getInt(1));
 			}
+			rset.close();
 			
 			rset = statement.executeQuery("SELECT COUNT(*) FROM clan_data");
 			rset.next();
 			temp.ensureCapacity(temp.size() + rset.getInt(1));
+			rset.close();
+			
 			rset = statement.executeQuery("SELECT clan_id FROM clan_data");
 			while (rset.next())
 			{
 				temp.add(rset.getInt(1));
 			}
+			rset.close();
 			
 			rset = statement.executeQuery("SELECT COUNT(*) FROM itemsonground");
 			rset.next();
 			temp.ensureCapacity(temp.size() + rset.getInt(1));
+			rset.close();
+			
 			rset = statement.executeQuery("SELECT object_id FROM itemsonground");
 			while (rset.next())
 			{
 				temp.add(rset.getInt(1));
 			}
+			rset.close();
 			
 			rset = statement.executeQuery("SELECT COUNT(*) FROM messages");
 			rset.next();
 			temp.ensureCapacity(temp.size() + rset.getInt(1));
+			rset.close();
+			
 			rset = statement.executeQuery("SELECT messageId FROM messages");
 			while (rset.next())
 			{
 				temp.add(rset.getInt(1));
 			}
+			rset.close();
+			statement.close();
 			
 			temp.sort();
-			
 			return temp.toArray();
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public boolean isInitialized()

+ 1 - 7
L2J_Server_BETA/java/com/l2jserver/gameserver/idfactory/StackIDFactory.java

@@ -40,10 +40,8 @@ public class StackIDFactory extends IdFactory
 		_curOID = FIRST_OID;
 		_tempOID = FIRST_OID;
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			// con.createStatement().execute("drop table if exists tmp_obj_id");
 			
 			int[] tmp_obj_ids = extractUsedObjectIDTable();
@@ -67,10 +65,6 @@ public class StackIDFactory extends IdFactory
 		{
 			_log.severe(getClass().getSimpleName() + ": Could not be initialized properly:" + e.getMessage());
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private int insertUntil(int[] tmp_obj_ids, int idx, int N, Connection con) throws SQLException

+ 18 - 44
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/AirShipManager.java

@@ -168,17 +168,12 @@ public class AirShipManager
 			
 			_airShipsInfo.put(ownerId, info);
 			
-			Connection con = null;
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+				PreparedStatement ps = con.prepareStatement(ADD_DB))
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
-				
-				try (PreparedStatement ps = con.prepareStatement(ADD_DB))
-				{
-					ps.setInt(1, ownerId);
-					ps.setInt(2, info.getInteger("fuel"));
-					ps.executeUpdate();
-				}
+				ps.setInt(1, ownerId);
+				ps.setInt(2, info.getInteger("fuel"));
+				ps.executeUpdate();
 			}
 			catch (SQLException e)
 			{
@@ -188,10 +183,6 @@ public class AirShipManager
 			{
 				_log.log(Level.WARNING, getClass().getSimpleName()+": Error while initializing: " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 		}
 	}
 	
@@ -255,20 +246,16 @@ public class AirShipManager
 	
 	private void load()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			Statement s = con.createStatement();
+			ResultSet rs = s.executeQuery(LOAD_DB))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (Statement s = con.createStatement();
-				ResultSet rs = s.executeQuery(LOAD_DB))
+			StatsSet info;
+			while (rs.next())
 			{
-				StatsSet info;
-				while (rs.next())
-				{
-					info = new StatsSet();
-					info.set("fuel", rs.getInt("fuel"));
-					_airShipsInfo.put(rs.getInt("owner_id"), info);
-				}
+				info = new StatsSet();
+				info.set("fuel", rs.getInt("fuel"));
+				_airShipsInfo.put(rs.getInt("owner_id"), info);
 			}
 		}
 		catch (SQLException e)
@@ -279,11 +266,6 @@ public class AirShipManager
 		{
 			_log.log(Level.WARNING, getClass().getSimpleName()+": Error while initializing: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
-		
 		_log.info(getClass().getSimpleName()+": Loaded " + _airShipsInfo.size() + " private airships");
 	}
 	
@@ -293,16 +275,12 @@ public class AirShipManager
 		if (info == null)
 			return;
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement(UPDATE_DB))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement(UPDATE_DB))
-			{
-				ps.setInt(1, info.getInteger("fuel"));
-				ps.setInt(2, ownerId);
-				ps.executeUpdate();
-			}
+			ps.setInt(1, info.getInteger("fuel"));
+			ps.setInt(2, ownerId);
+			ps.executeUpdate();
 		}
 		catch (SQLException e)
 		{
@@ -312,10 +290,6 @@ public class AirShipManager
 		{
 			_log.log(Level.WARNING, getClass().getSimpleName()+": Error while save: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private static class AirShipTeleportList

+ 2 - 14
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/AuctionManager.java

@@ -98,10 +98,8 @@ public class AuctionManager
 	
 	private final void load()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT id FROM auction ORDER BY id");
 			ResultSet rs = statement.executeQuery();
 			while (rs.next())
@@ -114,10 +112,6 @@ public class AuctionManager
 		{
 			_log.log(Level.WARNING, "Exception: AuctionManager.load(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public final Auction getAuction(int auctionId)
@@ -163,10 +157,8 @@ public class AuctionManager
 			return;
 		}
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("INSERT INTO `auction` VALUES " + ITEM_INIT_DATA[i]);
 			statement.execute();
 			statement.close();
@@ -177,10 +169,6 @@ public class AuctionManager
 		{
 			_log.log(Level.SEVERE, "Exception: Auction.initNPC(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private static class SingletonHolder

+ 1 - 7
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/CHSiegeManager.java

@@ -51,10 +51,8 @@ public final class CHSiegeManager
 	
 	private final void loadClanHalls()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement(SQL_LOAD_HALLS);
 			ResultSet rs = statement.executeQuery();
 			
@@ -86,10 +84,6 @@ public final class CHSiegeManager
 		{
 			_log.warning("CHSiegeManager: Could not load siegable clan halls!:");
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public FastMap<Integer, SiegableHall> getConquerableHalls()

+ 2 - 15
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/CastleManager.java

@@ -225,10 +225,8 @@ public class CastleManager implements InstanceListManager
 				}
 			}
 			// else offline-player circlet removal
-			Connection con = null;
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
 				PreparedStatement statement = con.prepareStatement("DELETE FROM items WHERE owner_id = ? and item_id = ?");
 				statement.setInt(1, member.getObjectId());
 				statement.setInt(2, circletId);
@@ -239,21 +237,14 @@ public class CastleManager implements InstanceListManager
 			{
 				_log.log(Level.WARNING, "Failed to remove castle circlets offline for player " + member.getName() + ": " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 		}
 	}
 	
 	@Override
 	public void loadInstances()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			PreparedStatement statement = con.prepareStatement("SELECT id FROM castle ORDER BY id");
 			ResultSet rs = statement.executeQuery();
 			
@@ -270,10 +261,6 @@ public class CastleManager implements InstanceListManager
 		{
 			_log.log(Level.WARNING, "Exception: loadCastleData(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	@Override

+ 1 - 8
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/CastleManorManager.java

@@ -202,11 +202,8 @@ public class CastleManorManager
 	
 	private void load()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			// Get Connection
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statementProduction = con.prepareStatement(CASTLE_MANOR_LOAD_PRODUCTION);
 			PreparedStatement statementProcure = con.prepareStatement(CASTLE_MANOR_LOAD_PROCURE);
 			for (Castle castle : CastleManager.getInstance().getCastles())
@@ -270,10 +267,6 @@ public class CastleManorManager
 		{
 			_log.info("Error restoring manor data: " + e.getMessage());
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void init()

+ 1 - 7
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/ClanHallManager.java

@@ -77,11 +77,9 @@ public final class ClanHallManager
 	/** Load All Clan Hall */
 	private final void load()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
 			int id, ownerId, lease;
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT * FROM clanhall ORDER BY id");
 			ResultSet rs = statement.executeQuery();
 			while (rs.next())
@@ -127,10 +125,6 @@ public final class ClanHallManager
 		{
 			_log.log(Level.WARNING, "Exception: ClanHallManager.load(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public static final Map<Integer, ClanHall> getAllClanHalls()

+ 1 - 9
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/CoupleManager.java

@@ -55,11 +55,8 @@ public class CoupleManager
 	
 	private final void load()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			PreparedStatement statement = con.prepareStatement("SELECT id FROM mods_wedding ORDER BY id");
 			ResultSet rs = statement.executeQuery();
 			
@@ -77,11 +74,6 @@ public class CoupleManager
 		{
 			_log.log(Level.SEVERE, "Exception: CoupleManager.load(): " + e.getMessage(), e);
 		}
-		
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public final Couple getCouple(int coupleId)

+ 45 - 79
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/CursedWeaponsManager.java

@@ -179,12 +179,9 @@ public class CursedWeaponsManager
 	{
 		if (Config.DEBUG)
 			_log.info("  Restoring ... ");
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
 			// Retrieve the L2PcInstance from the characters table of the database
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			PreparedStatement statement = con.prepareStatement("SELECT itemId, charId, playerKarma, playerPkKills, nbKills, endTime FROM cursed_weapons");
 			ResultSet rset = statement.executeQuery();
 			while (rset.next())
@@ -215,10 +212,6 @@ public class CursedWeaponsManager
 		{
 			_log.log(Level.WARNING, "Could not restore CursedWeapons data: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private final void controlPlayers()
@@ -226,77 +219,61 @@ public class CursedWeaponsManager
 		if (Config.DEBUG)
 			_log.info("  Checking players ... ");
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			// Retrieve the L2PcInstance from the characters table of the database
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = null;
-			ResultSet rset = null;
-			
 			// TODO: See comments below...
 			// This entire for loop should NOT be necessary, since it is already handled by
 			// CursedWeapon.endOfLife().  However, if we indeed *need* to duplicate it for safety,
 			// then we'd better make sure that it FULLY cleans up inactive cursed weapons!
 			// Undesired effects result otherwise, such as player with no zariche but with karma
-			// or a lost-child entry in the cursedweapons table, without a corresponding one in items...
-			for (CursedWeapon cw : _cursedWeapons.values())
+			// or a lost-child entry in the cursed weapons table, without a corresponding one in items...
+			
+			// Retrieve the L2PcInstance from the characters table of the database
+			try (PreparedStatement statement = con.prepareStatement("SELECT owner_id FROM items WHERE item_id=?"))
 			{
-				if (cw.isActivated())
-					continue;
-				
-				// Do an item check to be sure that the cursed weapon isn't hold by someone
-				int itemId = cw.getItemId();
-				try
+				for (CursedWeapon cw : _cursedWeapons.values())
 				{
-					statement = con.prepareStatement("SELECT owner_id FROM items WHERE item_id=?");
-					statement.setInt(1, itemId);
-					rset = statement.executeQuery();
+					if (cw.isActivated())
+						continue;
 					
-					if (rset.next())
+					// Do an item check to be sure that the cursed weapon isn't hold by someone
+					int itemId = cw.getItemId();
+					statement.setInt(1, itemId);
+					try (ResultSet rset = statement.executeQuery())
 					{
-						// A player has the cursed weapon in his inventory ...
-						int playerId = rset.getInt("owner_id");
-						_log.info("PROBLEM : Player " + playerId + " owns the cursed weapon " + itemId + " but he shouldn't.");
-						
-						// Delete the item
-						statement.close();
-						statement = con.prepareStatement("DELETE FROM items WHERE owner_id=? AND item_id=?");
-						statement.setInt(1, playerId);
-						statement.setInt(2, itemId);
-						if (statement.executeUpdate() != 1)
-						{
-							_log.warning("Error while deleting cursed weapon " + itemId + " from userId " + playerId);
-						}
-						statement.close();
-						
-						// Delete the skill
-						/*
-						statement = con.prepareStatement("DELETE FROM character_skills WHERE charId=? AND skill_id=");
-						statement.setInt(1, playerId);
-						statement.setInt(2, cw.getSkillId());
-						if (statement.executeUpdate() != 1)
+						if (rset.next())
 						{
-							_log.warning("Error while deleting cursed weapon "+itemId+" skill from userId "+playerId);
-						}
-						 */
-						// Restore the player's old karma and pk count
-						statement = con.prepareStatement("UPDATE characters SET karma=?, pkkills=? WHERE charId=?");
-						statement.setInt(1, cw.getPlayerKarma());
-						statement.setInt(2, cw.getPlayerPkKills());
-						statement.setInt(3, playerId);
-						if (statement.executeUpdate() != 1)
-						{
-							_log.warning("Error while updating karma & pkkills for userId " + cw.getPlayerId());
+							// A player has the cursed weapon in his inventory ...
+							int playerId = rset.getInt("owner_id");
+							_log.info("PROBLEM : Player " + playerId + " owns the cursed weapon " + itemId + " but he shouldn't.");
+							
+							// Delete the item
+							try (PreparedStatement delete = con.prepareStatement("DELETE FROM items WHERE owner_id=? AND item_id=?"))
+							{
+								delete.setInt(1, playerId);
+								delete.setInt(2, itemId);
+								if (delete.executeUpdate() != 1)
+								{
+									_log.warning("Error while deleting cursed weapon " + itemId + " from userId " + playerId);
+								}
+							}
+							
+							// Restore the player's old karma and pk count
+							try (PreparedStatement update = con.prepareStatement("UPDATE characters SET karma=?, pkkills=? WHERE charId=?"))
+							{
+								update.setInt(1, cw.getPlayerKarma());
+								update.setInt(2, cw.getPlayerPkKills());
+								update.setInt(3, playerId);
+								if (update.executeUpdate() != 1)
+								{
+									_log.warning("Error while updating karma & pkkills for userId " + cw.getPlayerId());
+								}
+							}
+							// clean up the cursed weapons table.
+							removeFromDb(itemId);
 						}
-						// clean up the cursedweapons table.
-						removeFromDb(itemId);
 					}
-					rset.close();
-					statement.close();
-				}
-				catch (SQLException sqlE)
-				{
+					statement.clearParameters();
 				}
 			}
 		}
@@ -306,10 +283,7 @@ public class CursedWeaponsManager
 				_log.log(Level.WARNING, "Could not check CursedWeapons data: " + e.getMessage(), e);
 			return;
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
+		
 		if (Config.DEBUG)
 			_log.info("DONE");
 	}
@@ -416,26 +390,18 @@ public class CursedWeaponsManager
 	
 	public static void removeFromDb(int itemId)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			// Delete datas
 			PreparedStatement statement = con.prepareStatement("DELETE FROM cursed_weapons WHERE itemId = ?");
 			statement.setInt(1, itemId);
 			statement.executeUpdate();
-			
 			statement.close();
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.SEVERE, "CursedWeaponsManager: Failed to remove data: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public void saveData()

+ 1 - 8
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/DimensionalRiftManager.java

@@ -77,11 +77,8 @@ public class DimensionalRiftManager
 	
 	private void loadRooms()
 	{
-		Connection con = null;
-		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT * FROM dimensional_rift");
 			ResultSet rs = statement.executeQuery();
 			
@@ -116,10 +113,6 @@ public class DimensionalRiftManager
 		{
 			_log.log(Level.WARNING, "Can't load Dimension Rift zones. " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
 		int typeSize = _rooms.keys().length;
 		int roomSize = 0;

+ 1 - 8
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/FortManager.java

@@ -152,11 +152,8 @@ public class FortManager implements InstanceListManager
 	@Override
 	public void loadInstances()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			PreparedStatement statement = con.prepareStatement("SELECT id FROM fort ORDER BY id");
 			ResultSet rs = statement.executeQuery();
 			
@@ -178,10 +175,6 @@ public class FortManager implements InstanceListManager
 		{
 			_log.log(Level.WARNING, "Exception: loadFortData(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	@Override

+ 1 - 7
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/FortSiegeGuardManager.java

@@ -101,10 +101,8 @@ public class FortSiegeGuardManager
 	void loadSiegeGuard()
 	{
 		_siegeGuards.clear();
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT * FROM fort_siege_guards Where fortId = ? ");
 			statement.setInt(1, getFort().getFortId());
 			ResultSet rs = statement.executeQuery();
@@ -142,10 +140,6 @@ public class FortSiegeGuardManager
 		{
 			_log.log(Level.WARNING, "Error loading siege guard for fort " + getFort().getName() + ": " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public final Fort getFort()

+ 1 - 7
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/FortSiegeManager.java

@@ -114,11 +114,9 @@ public class FortSiegeManager
 		if (clan == null)
 			return false;
 		
-		Connection con = null;
 		boolean register = false;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT clan_id FROM fortsiege_clans where clan_id=? and fort_id=?");
 			statement.setInt(1, clan.getClanId());
 			statement.setInt(2, fortid);
@@ -137,10 +135,6 @@ public class FortSiegeManager
 		{
 			_log.log(Level.WARNING, "Exception: checkIsRegistered(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		return register;
 	}
 	

+ 5 - 44
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/FourSepulchersManager.java

@@ -408,13 +408,10 @@ public class FourSepulchersManager
 	
 	private void loadMysteriousBox()
 	{
-		Connection con = null;
-		
 		_mysteriousBoxSpawns.clear();
 		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT id, count, npc_templateid, locx, locy, locz, heading, respawn_delay, key_npc_id FROM four_sepulchers_spawnlist Where spawntype = ? ORDER BY id");
 			statement.setInt(1, 0);
 			ResultSet rset = statement.executeQuery();
@@ -454,10 +451,6 @@ public class FourSepulchersManager
 			// problem with initializing spawn, go to next one
 			_log.log(Level.WARNING, "FourSepulchersManager.LoadMysteriousBox: Spawn could not be initialized: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void initKeyBoxSpawns()
@@ -500,12 +493,8 @@ public class FourSepulchersManager
 		_physicalMonsters.clear();
 		
 		int loaded = 0;
-		Connection con = null;
-		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			PreparedStatement statement1 = con.prepareStatement("SELECT Distinct key_npc_id FROM four_sepulchers_spawnlist Where spawntype = ? ORDER BY key_npc_id");
 			statement1.setInt(1, 1);
 			ResultSet rset1 = statement1.executeQuery();
@@ -562,10 +551,6 @@ public class FourSepulchersManager
 			// problem with initializing spawn, go to next one
 			_log.log(Level.WARNING, "FourSepulchersManager.LoadPhysicalMonsters: Spawn could not be initialized: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void loadMagicalMonsters()
@@ -574,12 +559,8 @@ public class FourSepulchersManager
 		_magicalMonsters.clear();
 		
 		int loaded = 0;
-		Connection con = null;
-		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			PreparedStatement statement1 = con.prepareStatement("SELECT Distinct key_npc_id FROM four_sepulchers_spawnlist Where spawntype = ? ORDER BY key_npc_id");
 			statement1.setInt(1, 2);
 			ResultSet rset1 = statement1.executeQuery();
@@ -636,10 +617,6 @@ public class FourSepulchersManager
 			// problem with initializing spawn, go to next one
 			_log.log(Level.WARNING, "FourSepulchersManager.LoadMagicalMonsters: Spawn could not be initialized: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void loadDukeMonsters()
@@ -648,12 +625,8 @@ public class FourSepulchersManager
 		_archonSpawned.clear();
 		
 		int loaded = 0;
-		Connection con = null;
-		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			PreparedStatement statement1 = con.prepareStatement("SELECT Distinct key_npc_id FROM four_sepulchers_spawnlist Where spawntype = ? ORDER BY key_npc_id");
 			statement1.setInt(1, 5);
 			ResultSet rset1 = statement1.executeQuery();
@@ -711,10 +684,6 @@ public class FourSepulchersManager
 			// problem with initializing spawn, go to next one
 			_log.log(Level.WARNING, "FourSepulchersManager.LoadDukeMonsters: Spawn could not be initialized: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void loadEmperorsGraveMonsters()
@@ -723,12 +692,8 @@ public class FourSepulchersManager
 		_emperorsGraveNpcs.clear();
 		
 		int loaded = 0;
-		Connection con = null;
-		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			PreparedStatement statement1 = con.prepareStatement("SELECT Distinct key_npc_id FROM four_sepulchers_spawnlist Where spawntype = ? ORDER BY key_npc_id");
 			statement1.setInt(1, 6);
 			ResultSet rset1 = statement1.executeQuery();
@@ -785,10 +750,6 @@ public class FourSepulchersManager
 			// problem with initializing spawn, go to next one
 			_log.log(Level.WARNING, "FourSepulchersManager.LoadEmperorsGraveMonsters: Spawn could not be initialized: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	protected void initLocationShadowSpawns()

+ 13 - 29
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/GlobalVariablesManager.java

@@ -17,13 +17,16 @@ package com.l2jserver.gameserver.instancemanager;
 import java.sql.Connection;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
-import java.util.Map;
+import java.sql.Statement;
 import java.util.logging.Logger;
 
 import javolution.util.FastMap;
 
 import com.l2jserver.L2DatabaseFactory;
 
+/**
+ * @author Gigiikun
+ */
 public class GlobalVariablesManager
 {
 	private static final Logger _log = Logger.getLogger(GlobalVariablesManager.class.getName());
@@ -31,24 +34,20 @@ public class GlobalVariablesManager
 	private static final String LOAD_VAR = "SELECT var,value FROM global_variables";
 	private static final String SAVE_VAR = "INSERT INTO global_variables (var,value) VALUES (?,?) ON DUPLICATE KEY UPDATE value=?";
 	
-	private final Map<String, String> _variablesMap;
+	private final FastMap<String, String> _variablesMap = new FastMap<>();
 	
 	protected GlobalVariablesManager()
 	{
-		_variablesMap = new FastMap<>();
-		
+		_variablesMap.shared();
 		loadVars();
 	}
 	
 	private final void loadVars()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			Statement statement = con.createStatement();
+			ResultSet rset = statement.executeQuery(LOAD_VAR))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement(LOAD_VAR);
-			ResultSet rset = statement.executeQuery();
-			
 			String var, value;
 			while (rset.next())
 			{
@@ -57,47 +56,32 @@ public class GlobalVariablesManager
 				
 				_variablesMap.put(var, value);
 			}
-			
-			rset.close();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.warning("GlobalVariablesManager: problem while loading variables: " + e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public final void saveVars()
 	{
-		Connection con = null;
-		PreparedStatement statement = null;
-		try
+		
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement(SAVE_VAR))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			statement = con.prepareStatement(SAVE_VAR);
-
 			for(String var : _variablesMap.keySet())
 			{
 				statement.setString(1, var);
 				statement.setString(2, _variablesMap.get(var));
 				statement.setString(3, _variablesMap.get(var));
 				statement.execute();
+				statement.clearParameters();
 			}
-			statement.close();
-			_log.info("GlobalVariablesManager: Database updated.");
 		}
 		catch (Exception e)
 		{
 			_log.warning("GlobalVariablesManager: problem while saving variables: " + e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public void storeVariable(String var, String value)

+ 71 - 92
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/GrandBossManager.java

@@ -112,11 +112,8 @@ public class GrandBossManager
 		_bosses = new FastMap<>();
 		_storedInfo = new TIntObjectHashMap<>();
 		_bossStatus = new TIntIntHashMap();
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			PreparedStatement statement = con.prepareStatement("SELECT * from grandboss_data ORDER BY boss_id");
 			ResultSet rset = statement.executeQuery();
 			while (rset.next())
@@ -158,10 +155,6 @@ public class GrandBossManager
 		{
 			_log.log(Level.WARNING, "Error while initializing GrandBossManager: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -169,8 +162,6 @@ public class GrandBossManager
 	 */
 	public void initZones()
 	{
-		Connection con = null;
-		
 		FastMap<Integer, L2FastList<Integer>> zones = new FastMap<>();
 		
 		if (_zones == null)
@@ -186,10 +177,8 @@ public class GrandBossManager
 			zones.put(zone.getId(), new L2FastList<Integer>());
 		}
 		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			PreparedStatement statement = con.prepareStatement("SELECT * from grandboss_list ORDER BY player_id");
 			ResultSet rset = statement.executeQuery();
 			
@@ -213,10 +202,6 @@ public class GrandBossManager
 		{
 			_log.log(Level.WARNING, "Error while initializing GrandBoss zones: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
 		for (L2BossZone zone : _zones)
 		{
@@ -329,126 +314,120 @@ public class GrandBossManager
 	
 	private void storeToDb()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement delete = con.prepareStatement(DELETE_GRAND_BOSS_LIST))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
+			delete.executeUpdate();
 			
-			PreparedStatement statement = con.prepareStatement(DELETE_GRAND_BOSS_LIST);
-			statement.executeUpdate();
-			statement.close();
-			
-			statement = con.prepareStatement(INSERT_GRAND_BOSS_LIST);
-			for (L2BossZone zone : _zones)
+			try (PreparedStatement insert = con.prepareStatement(INSERT_GRAND_BOSS_LIST))
 			{
-				if (zone == null)
-					continue;
-				Integer id = zone.getId();
-				L2FastList<Integer> list = zone.getAllowedPlayers();
-				if (list == null || list.isEmpty())
-					continue;
-				for (Integer player : list)
+				for (L2BossZone zone : _zones)
 				{
-					statement.setInt(1, player);
-					statement.setInt(2, id);
-					statement.executeUpdate();
-					statement.clearParameters();
+					if (zone == null)
+						continue;
+					Integer id = zone.getId();
+					L2FastList<Integer> list = zone.getAllowedPlayers();
+					if (list == null || list.isEmpty())
+						continue;
+					for (Integer player : list)
+					{
+						insert.setInt(1, player);
+						insert.setInt(2, id);
+						insert.executeUpdate();
+						insert.clearParameters();
+					}
 				}
 			}
-			statement.close();
-			
 			for (Integer bossId : _storedInfo.keys())
 			{
 				final L2GrandBossInstance boss = _bosses.get(bossId);
 				StatsSet info = _storedInfo.get(bossId);
 				if (boss == null || info == null)
 				{
-					statement = con.prepareStatement(UPDATE_GRAND_BOSS_DATA2);
-					statement.setInt(1, _bossStatus.get(bossId));
-					statement.setInt(2, bossId);
+					try (PreparedStatement update = con.prepareStatement(UPDATE_GRAND_BOSS_DATA2))
+					{
+						update.setInt(1, _bossStatus.get(bossId));
+						update.setInt(2, bossId);
+						update.executeUpdate();
+						update.clearParameters();
+					}
 				}
 				else
 				{
-					statement = con.prepareStatement(UPDATE_GRAND_BOSS_DATA);
-					statement.setInt(1, boss.getX());
-					statement.setInt(2, boss.getY());
-					statement.setInt(3, boss.getZ());
-					statement.setInt(4, boss.getHeading());
-					statement.setLong(5, info.getLong("respawn_time"));
-					double hp = boss.getCurrentHp();
-					double mp = boss.getCurrentMp();
-					if (boss.isDead())
+					try (PreparedStatement update = con.prepareStatement(UPDATE_GRAND_BOSS_DATA))
 					{
-						hp = boss.getMaxHp();
-						mp = boss.getMaxMp();
+						update.setInt(1, boss.getX());
+						update.setInt(2, boss.getY());
+						update.setInt(3, boss.getZ());
+						update.setInt(4, boss.getHeading());
+						update.setLong(5, info.getLong("respawn_time"));
+						double hp = boss.getCurrentHp();
+						double mp = boss.getCurrentMp();
+						if (boss.isDead())
+						{
+							hp = boss.getMaxHp();
+							mp = boss.getMaxMp();
+						}
+						update.setDouble(6, hp);
+						update.setDouble(7, mp);
+						update.setInt(8, _bossStatus.get(bossId));
+						update.setInt(9, bossId);
+						update.executeUpdate();
+						update.clearParameters();
 					}
-					statement.setDouble(6, hp);
-					statement.setDouble(7, mp);
-					statement.setInt(8, _bossStatus.get(bossId));
-					statement.setInt(9, bossId);
 				}
-				statement.executeUpdate();
-				statement.clearParameters();
-				statement.close();
 			}
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.WARNING, "GrandBossManager: Couldn't store grandbosses to database:" + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void updateDb(int bossId, boolean statusOnly)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = null;
 			L2GrandBossInstance boss = _bosses.get(bossId);
 			StatsSet info = _storedInfo.get(bossId);
 			
 			if (statusOnly || boss == null || info == null)
 			{
-				statement = con.prepareStatement(UPDATE_GRAND_BOSS_DATA2);
-				statement.setInt(1, _bossStatus.get(bossId));
-				statement.setInt(2, bossId);
+				try (PreparedStatement statement = con.prepareStatement(UPDATE_GRAND_BOSS_DATA2))
+				{
+					statement.setInt(1, _bossStatus.get(bossId));
+					statement.setInt(2, bossId);
+					statement.executeUpdate();
+				}
 			}
 			else
 			{
-				statement = con.prepareStatement(UPDATE_GRAND_BOSS_DATA);
-				statement.setInt(1, boss.getX());
-				statement.setInt(2, boss.getY());
-				statement.setInt(3, boss.getZ());
-				statement.setInt(4, boss.getHeading());
-				statement.setLong(5, info.getLong("respawn_time"));
-				double hp = boss.getCurrentHp();
-				double mp = boss.getCurrentMp();
-				if (boss.isDead())
+				try (PreparedStatement statement = con.prepareStatement(UPDATE_GRAND_BOSS_DATA))
 				{
-					hp = boss.getMaxHp();
-					mp = boss.getMaxMp();
+					statement.setInt(1, boss.getX());
+					statement.setInt(2, boss.getY());
+					statement.setInt(3, boss.getZ());
+					statement.setInt(4, boss.getHeading());
+					statement.setLong(5, info.getLong("respawn_time"));
+					double hp = boss.getCurrentHp();
+					double mp = boss.getCurrentMp();
+					if (boss.isDead())
+					{
+						hp = boss.getMaxHp();
+						mp = boss.getMaxMp();
+					}
+					statement.setDouble(6, hp);
+					statement.setDouble(7, mp);
+					statement.setInt(8, _bossStatus.get(bossId));
+					statement.setInt(9, bossId);
+					statement.executeUpdate();
 				}
-				statement.setDouble(6, hp);
-				statement.setDouble(7, mp);
-				statement.setInt(8, _bossStatus.get(bossId));
-				statement.setInt(9, bossId);
 			}
-			statement.executeUpdate();
-			statement.close();
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.WARNING, "GrandBossManager: Couldn't update grandbosses to database:" + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**

+ 1 - 7
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/HellboundManager.java

@@ -259,10 +259,8 @@ public class HellboundManager
 	
 	private final void loadSpawns()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			final PreparedStatement statement = con.prepareStatement(LOAD_SPAWNS);
 			final ResultSet rset = statement.executeQuery();
 			
@@ -307,10 +305,6 @@ public class HellboundManager
 		{
 			_log.warning("HellboundManager: problem while loading spawns: " + e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		_log.config("HellboundManager: Loaded " + _population.size() + " npc spawn locations.");
 	}
 	

+ 4 - 21
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/InstanceManager.java

@@ -113,10 +113,9 @@ public class InstanceManager extends DocumentParser
 		{
 			restoreInstanceTimes(playerObjId);
 		}
-		Connection con = null;
-		try
+		
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement(ADD_INSTANCE_TIME);
 			statement.setInt(1, playerObjId);
 			statement.setInt(2, id);
@@ -130,10 +129,6 @@ public class InstanceManager extends DocumentParser
 		{
 			_log.warning(getClass().getSimpleName() + ": Could not insert character instance time data: " + e.getMessage());
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -142,10 +137,8 @@ public class InstanceManager extends DocumentParser
 	 */
 	public void deleteInstanceTime(int playerObjId, int id)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement(DELETE_INSTANCE_TIME);
 			statement.setInt(1, playerObjId);
 			statement.setInt(2, id);
@@ -157,10 +150,6 @@ public class InstanceManager extends DocumentParser
 		{
 			_log.warning(getClass().getSimpleName() + ": Could not delete character instance time data: " + e.getMessage());
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -173,10 +162,8 @@ public class InstanceManager extends DocumentParser
 			return; // already restored
 		}
 		_playerInstanceTimes.put(playerObjId, new FastMap<Integer, Long>());
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement(RESTORE_INSTANCE_TIMES);
 			statement.setInt(1, playerObjId);
 			ResultSet rset = statement.executeQuery();
@@ -202,10 +189,6 @@ public class InstanceManager extends DocumentParser
 		{
 			_log.warning(getClass().getSimpleName() + ": Could not delete character instance time data: " + e.getMessage());
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**

+ 16 - 29
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/ItemAuctionManager.java

@@ -21,6 +21,7 @@ import java.sql.Connection;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
+import java.sql.Statement;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.logging.Level;
 import java.util.logging.Logger;
@@ -61,27 +62,17 @@ public final class ItemAuctionManager
 			return;
 		}
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			Statement statement = con.createStatement();
+			ResultSet rset = statement.executeQuery("SELECT auctionId FROM item_auction ORDER BY auctionId DESC LIMIT 0, 1"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("SELECT auctionId FROM item_auction ORDER BY auctionId DESC LIMIT 0, 1");
-			ResultSet rset = statement.executeQuery();
-			
 			if (rset.next())
 				_auctionIds.set(rset.getInt(1) + 1);
-			
-			rset.close();
-			statement.close();
 		}
 		catch (final SQLException e)
 		{
 			_log.log(Level.SEVERE, "ItemAuctionManager: Failed loading auctions.", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
 		final File file = new File(Config.DATAPACK_ROOT + "/data/ItemAuctions.xml");
 		if (!file.exists())
@@ -146,28 +137,24 @@ public final class ItemAuctionManager
 	
 	public static final void deleteAuction(final int auctionId)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("DELETE FROM item_auction WHERE auctionId=?");
-			statement.setInt(1, auctionId);
-			statement.execute();
-			statement.close();
+			try (PreparedStatement statement = con.prepareStatement("DELETE FROM item_auction WHERE auctionId=?"))
+			{
+				statement.setInt(1, auctionId);
+				statement.execute();
+			}
 			
-			statement = con.prepareStatement("DELETE FROM item_auction_bid WHERE auctionId=?");
-			statement.setInt(1, auctionId);
-			statement.execute();
-			statement.close();
+			try (PreparedStatement statement = con.prepareStatement("DELETE FROM item_auction_bid WHERE auctionId=?"))
+			{
+				statement.setInt(1, auctionId);
+				statement.execute();
+			}
 		}
-		catch (final SQLException e)
+		catch (SQLException e)
 		{
 			_log.log(Level.SEVERE, "L2ItemAuctionManagerInstance: Failed deleting auction: " + auctionId, e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private static class SingletonHolder

+ 5 - 28
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/ItemsOnGroundManager.java

@@ -78,8 +78,7 @@ public class ItemsOnGroundManager
 		// if DestroyPlayerDroppedItem was previously false, items currently protected will be added to ItemsAutoDestroy
 		if (Config.DESTROY_DROPPED_PLAYER_ITEM)
 		{
-			Connection con = null;
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 			{
 				String str = null;
 				if (!Config.DESTROY_EQUIPABLE_PLAYER_ITEM)
@@ -92,7 +91,6 @@ public class ItemsOnGroundManager
 					// Recycle all items including equip-able
 					str = "update itemsonground set drop_time=? where drop_time=-1";
 				}
-				con = L2DatabaseFactory.getInstance().getConnection();
 				PreparedStatement statement = con.prepareStatement(str);
 				statement.setLong(1, System.currentTimeMillis());
 				statement.execute();
@@ -102,18 +100,12 @@ public class ItemsOnGroundManager
 			{
 				_log.log(Level.SEVERE, "Error while updating table ItemsOnGround " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 		}
 		
 		// Add items to world
-		Connection con = null;
 		L2ItemInstance item;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT object_id,item_id,count,enchant_level,x,y,z,drop_time,equipable FROM itemsonground");
 			ResultSet rset;
 			int count = 0;
@@ -163,10 +155,7 @@ public class ItemsOnGroundManager
 		{
 			_log.log(Level.SEVERE, "Error while loading ItemsOnGround " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
+		
 		if (Config.EMPTY_DROPPED_ITEM_TABLE_AFTER_LOAD)
 		{
 			emptyTable();
@@ -202,10 +191,8 @@ public class ItemsOnGroundManager
 	
 	public void emptyTable()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("DELETE FROM itemsonground");
 			statement.execute();
 			statement.close();
@@ -214,10 +201,6 @@ public class ItemsOnGroundManager
 		{
 			_log.log(Level.SEVERE, "Error while cleaning table ItemsOnGround " + e1.getMessage(), e1);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	protected class StoreInDb extends Thread
@@ -241,10 +224,8 @@ public class ItemsOnGroundManager
 				return;
 			}
 			
-			Connection con = null;
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
 				PreparedStatement statement = con.prepareStatement("INSERT INTO itemsonground(object_id,item_id,count,enchant_level,x,y,z,drop_time,equipable) VALUES(?,?,?,?,?,?,?,?,?)");
 				
 				for (L2ItemInstance item : _items)
@@ -284,10 +265,6 @@ public class ItemsOnGroundManager
 			{
 				_log.log(Level.SEVERE, "SQL error while storing items on ground: " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 			
 			if (Config.DEBUG)
 			{

+ 12 - 73
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/MailManager.java

@@ -57,11 +57,8 @@ public class MailManager
 	private void load()
 	{
 		int count = 0;
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			PreparedStatement statement = con.prepareStatement("SELECT * FROM messages ORDER BY expiration");
 			// stmt2 = con.prepareStatement("SELECT * FROM attachments WHERE messageId = ?");
 			
@@ -90,10 +87,6 @@ public class MailManager
 		{
 			_log.log(Level.WARNING, "Mail Manager: Error loading from database:" + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		_log.info("Mail Manager: Successfully loaded " + count + " messages.");
 	}
 	
@@ -175,11 +168,8 @@ public class MailManager
 	public void sendMessage(Message msg)
 	{
 		_messages.put(msg.getId(), msg);
-		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement stmt = Message.getStatement(msg, con);
 			stmt.execute();
 			stmt.close();
@@ -188,10 +178,6 @@ public class MailManager
 		{
 			_log.log(Level.WARNING, "Mail Manager: Error saving message:" + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
 		final L2PcInstance receiver = L2World.getInstance().getPlayer(msg.getReceiverId());
 		if (receiver != null)
@@ -253,10 +239,8 @@ public class MailManager
 	
 	public final void markAsReadInDb(int msgId)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement stmt = con.prepareStatement("UPDATE messages SET isUnread = 'false' WHERE messageId = ?");
 			stmt.setInt(1, msgId);
 			stmt.execute();
@@ -266,108 +250,63 @@ public class MailManager
 		{
 			_log.log(Level.WARNING, "Mail Manager: Error marking as read message:" + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public final void markAsDeletedBySenderInDb(int msgId)
 	{
-		Connection con = null;
-		PreparedStatement stmt = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement stmt = con.prepareStatement("UPDATE messages SET isDeletedBySender = 'true' WHERE messageId = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
-			stmt = con.prepareStatement("UPDATE messages SET isDeletedBySender = 'true' WHERE messageId = ?");
-			
 			stmt.setInt(1, msgId);
-			
 			stmt.execute();
-			stmt.close();
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.WARNING, "Mail Manager: Error marking as deleted by sender message:" + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public final void markAsDeletedByReceiverInDb(int msgId)
 	{
-		Connection con = null;
-		PreparedStatement stmt = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement stmt = con.prepareStatement("UPDATE messages SET isDeletedByReceiver = 'true' WHERE messageId = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
-			stmt = con.prepareStatement("UPDATE messages SET isDeletedByReceiver = 'true' WHERE messageId = ?");
-			
 			stmt.setInt(1, msgId);
-			
 			stmt.execute();
-			stmt.close();
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.WARNING, "Mail Manager: Error marking as deleted by receiver message:" + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public final void removeAttachmentsInDb(int msgId)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement stmt = con.prepareStatement("UPDATE messages SET hasAttachments = 'false' WHERE messageId = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
-			PreparedStatement stmt = con.prepareStatement("UPDATE messages SET hasAttachments = 'false' WHERE messageId = ?");
-			
 			stmt.setInt(1, msgId);
-			
 			stmt.execute();
-			stmt.close();
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.WARNING, "Mail Manager: Error removing attachments in message:" + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public final void deleteMessageInDb(int msgId)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement stmt = con.prepareStatement("DELETE FROM messages WHERE messageId = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
-			PreparedStatement stmt = con.prepareStatement("DELETE FROM messages WHERE messageId = ?");
-			
 			stmt.setInt(1, msgId);
-			
 			stmt.execute();
-			stmt.close();
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.WARNING, "Mail Manager: Error deleting message:" + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
+		
 		_messages.remove(msgId);
 		IdFactory.getInstance().releaseId(msgId);
 	}

+ 1 - 7
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/MercTicketManager.java

@@ -133,10 +133,8 @@ public class MercTicketManager
 	 */
 	private final void load()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT * FROM castle_siege_guards Where isHired = 1");
 			ResultSet rs = statement.executeQuery();
 			
@@ -193,10 +191,6 @@ public class MercTicketManager
 		{
 			_log.log(Level.WARNING, "Exception: loadMercenaryData(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**

+ 3 - 21
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/RaidBossPointsManager.java

@@ -62,10 +62,8 @@ public class RaidBossPointsManager
 	private final void init()
 	{
 		_list = new FastMap<>();
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT `charId`,`boss_id`,`points` FROM `character_raid_points`");
 			ResultSet rset = statement.executeQuery();
 			while(rset.next())
@@ -89,18 +87,12 @@ public class RaidBossPointsManager
 		{
 			_log.log(Level.WARNING, "RaidPointsManager: Couldnt load raid points ", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public final void updatePointsInDB(L2PcInstance player, int raidId, int points)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("REPLACE INTO character_raid_points (`charId`,`boss_id`,`points`) VALUES (?,?,?)");
 			statement.setInt(1, player.getObjectId());
 			statement.setInt(2, raidId);
@@ -112,10 +104,6 @@ public class RaidBossPointsManager
 		{
 			_log.log(Level.WARNING, "could not update char raid points:", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public final void addPoints(L2PcInstance player, int bossId, int points)
@@ -161,10 +149,8 @@ public class RaidBossPointsManager
 	
 	public final void cleanUp()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			final PreparedStatement statement = con.prepareStatement("DELETE from character_raid_points WHERE charId > 0");
 			statement.executeUpdate();
 			statement.close();
@@ -174,10 +160,6 @@ public class RaidBossPointsManager
 		{
 			_log.log(Level.WARNING, "could not clean raid points: ", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public final int calculateRanking(int playerObjId)

+ 9 - 42
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/RaidBossSpawnManager.java

@@ -73,14 +73,10 @@ public class RaidBossSpawnManager
 		_storedInfo = new FastMap<>();
 		_spawns = new FastMap<>();
 		
-		Connection con = null;
-		try
-		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT * FROM raidboss_spawnlist ORDER BY boss_id");
-			ResultSet rset = statement.executeQuery();
-			
+			ResultSet rset = statement.executeQuery())
+		{
 			L2Spawn spawnDat;
 			L2NpcTemplate template;
 			long respawnTime;
@@ -109,9 +105,6 @@ public class RaidBossSpawnManager
 			
 			_log.info("RaidBossSpawnManager: Loaded " + _bosses.size() + " Instances");
 			_log.info("RaidBossSpawnManager: Scheduled " + _schedules.size() + " Instances");
-			
-			rset.close();
-			statement.close();
 		}
 		catch (SQLException e)
 		{
@@ -121,10 +114,6 @@ public class RaidBossSpawnManager
 		{
 			_log.log(Level.WARNING, "Error while initializing RaidBossSpawnManager: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private static class SpawnSchedule implements Runnable
@@ -266,11 +255,9 @@ public class RaidBossSpawnManager
 		
 		if (storeInDb)
 		{
-			Connection con = null;
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+				PreparedStatement statement = con.prepareStatement("INSERT INTO raidboss_spawnlist (boss_id,amount,loc_x,loc_y,loc_z,heading,respawn_time,currentHp,currentMp) VALUES(?,?,?,?,?,?,?,?,?)"))
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
-				PreparedStatement statement = con.prepareStatement("INSERT INTO raidboss_spawnlist (boss_id,amount,loc_x,loc_y,loc_z,heading,respawn_time,currentHp,currentMp) VALUES(?,?,?,?,?,?,?,?,?)");
 				statement.setInt(1, spawnDat.getNpcid());
 				statement.setInt(2, spawnDat.getAmount());
 				statement.setInt(3, spawnDat.getLocx());
@@ -281,17 +268,12 @@ public class RaidBossSpawnManager
 				statement.setDouble(8, currentHP);
 				statement.setDouble(9, currentMP);
 				statement.execute();
-				statement.close();
 			}
 			catch (Exception e)
 			{
 				// problem with storing spawn
 				_log.log(Level.WARNING, "RaidBossSpawnManager: Could not store raidboss #" + bossId + " in the DB:" + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 		}
 	}
 	
@@ -323,35 +305,25 @@ public class RaidBossSpawnManager
 		
 		if (updateDb)
 		{
-			Connection con = null;
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+				PreparedStatement statement = con.prepareStatement("DELETE FROM raidboss_spawnlist WHERE boss_id=?"))
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
-				PreparedStatement statement = con.prepareStatement("DELETE FROM raidboss_spawnlist WHERE boss_id=?");
 				statement.setInt(1, bossId);
 				statement.execute();
-				statement.close();
 			}
 			catch (Exception e)
 			{
 				// problem with deleting spawn
 				_log.log(Level.WARNING, "RaidBossSpawnManager: Could not remove raidboss #" + bossId + " from DB: " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 		}
 	}
 	
 	private void updateDb()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("UPDATE raidboss_spawnlist SET respawn_time = ?, currentHP = ?, currentMP = ? WHERE boss_id = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("UPDATE raidboss_spawnlist SET respawn_time = ?, currentHP = ?, currentMP = ? WHERE boss_id = ?");
-			
 			for (Integer bossId : _storedInfo.keySet())
 			{
 				if (bossId == null)
@@ -384,16 +356,11 @@ public class RaidBossSpawnManager
 					_log.log(Level.WARNING, "RaidBossSpawnManager: Couldnt update raidboss_spawnlist table " + e.getMessage(), e);
 				}
 			}
-			statement.close();
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.WARNING, "SQL error while updating RaidBoss spawn to database: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public String[] getAllRaidBossStatus()

+ 4 - 28
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/SiegeGuardManager.java

@@ -102,10 +102,8 @@ public class SiegeGuardManager
 	 */
 	public void removeMerc(int npcId, int x, int y, int z)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("Delete From castle_siege_guards Where npcId = ? And x = ? AND y = ? AND z = ? AND isHired = 1");
 			statement.setInt(1, npcId);
 			statement.setInt(2, x);
@@ -118,10 +116,6 @@ public class SiegeGuardManager
 		{
 			_log.log(Level.WARNING, "Error deleting hired siege guard at " + x + ',' + y + ',' + z + ": " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -129,10 +123,8 @@ public class SiegeGuardManager
 	 */
 	public void removeMercs()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("Delete From castle_siege_guards Where castleId = ? And isHired = 1");
 			statement.setInt(1, getCastle().getCastleId());
 			statement.execute();
@@ -142,10 +134,6 @@ public class SiegeGuardManager
 		{
 			_log.log(Level.WARNING, "Error deleting hired siege guard for castle " + getCastle().getName() + ": " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -200,10 +188,8 @@ public class SiegeGuardManager
 	 */
 	private void loadSiegeGuard()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT * FROM castle_siege_guards Where castleId = ? And isHired = ?");
 			statement.setInt(1, getCastle().getCastleId());
 			if (getCastle().getOwnerId() > 0) // If castle is owned by a clan, then don't spawn default guards
@@ -243,10 +229,6 @@ public class SiegeGuardManager
 		{
 			_log.log(Level.WARNING, "Error loading siege guard for castle " + getCastle().getName() + ": " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -260,10 +242,8 @@ public class SiegeGuardManager
 	 */
 	private void saveSiegeGuard(int x, int y, int z, int heading, int npcId, int isHire)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("Insert Into castle_siege_guards (castleId, npcId, x, y, z, heading, respawnDelay, isHired) Values (?, ?, ?, ?, ?, ?, ?, ?)");
 			statement.setInt(1, getCastle().getCastleId());
 			statement.setInt(2, npcId);
@@ -280,10 +260,6 @@ public class SiegeGuardManager
 		{
 			_log.log(Level.WARNING, "Error adding siege guard for castle " + getCastle().getName() + ": " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public final Castle getCastle()

+ 1 - 7
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/SiegeManager.java

@@ -118,11 +118,9 @@ public class SiegeManager
 		if (clan.getCastleId() > 0)
 			return true;
 		
-		Connection con = null;
 		boolean register = false;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT clan_id FROM siege_clans where clan_id=? and castle_id=?");
 			statement.setInt(1, clan.getClanId());
 			statement.setInt(2, castleid);
@@ -141,10 +139,6 @@ public class SiegeManager
 		{
 			_log.log(Level.WARNING, "Exception: checkIsRegistered(): " + e.getMessage() ,e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		return register;
 	}
 	

+ 14 - 52
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/TerritoryWarManager.java

@@ -66,6 +66,10 @@ public class TerritoryWarManager implements Siegable
 {
 	private static final Logger _log = Logger.getLogger(TerritoryWarManager.class.getName());
 	
+	// SQL
+	private static final String DELETE = "DELETE FROM territory_registrations WHERE castleId = ? and registeredId = ?";
+	private static final String INSERT = "INSERT INTO territory_registrations (castleId, registeredId) values (?, ?)";
+	
 	public static final TerritoryWarManager getInstance()
 	{
 		return SingletonHolder._instance;
@@ -656,36 +660,24 @@ public class TerritoryWarManager implements Siegable
 	
 	private void changeRegistration(int castleId, int objId, boolean delete)
 	{
-		Connection con = null;
-		try
+		final String query = delete ? DELETE : INSERT;
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement(query))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement;
-			if (delete)
-				statement = con.prepareStatement("DELETE FROM territory_registrations WHERE castleId=? and registeredId=?");
-			else
-				statement = con.prepareStatement("INSERT INTO territory_registrations (castleId, registeredId) values (?,?)");
 			statement.setInt(1, castleId);
 			statement.setInt(2, objId);
 			statement.execute();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Exception: Territory War registration: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void updateTerritoryData(Territory ter)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("UPDATE territories SET ownedWardIds=? WHERE territoryId=?");
 			StringBuilder wardList = new StringBuilder();
 			for (int i : ter.getOwnedWardIds())
@@ -699,15 +691,10 @@ public class TerritoryWarManager implements Siegable
 		{
 			_log.log(Level.WARNING, "Exception: Territory Data update: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private final void load()
 	{
-		
 		try (InputStream is = new FileInputStream(new File(Config.TW_CONFIGURATION_FILE)))
 		{
 			L2Properties territoryWarSettings = new L2Properties();
@@ -726,10 +713,8 @@ public class TerritoryWarManager implements Siegable
 			MINTWBADGEFORSTRIDERS = Integer.decode(territoryWarSettings.getProperty("MinTerritoryBadgeForStriders", "50"));
 			MINTWBADGEFORBIGSTRIDER = Integer.decode(territoryWarSettings.getProperty("MinTerritoryBadgeForBigStrider", "80"));
 			
-			Connection con = null;
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
 				PreparedStatement statement = con.prepareStatement("SELECT * FROM territory_spawnlist");
 				ResultSet rs = statement.executeQuery();
 				
@@ -763,13 +748,9 @@ public class TerritoryWarManager implements Siegable
 			{
 				_log.log(Level.WARNING, "Territory War Manager: SpawnList error: " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
-			try
+			
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
 				PreparedStatement statement = con.prepareStatement("SELECT * FROM territories");
 				ResultSet rs = statement.executeQuery();
 				
@@ -804,13 +785,10 @@ public class TerritoryWarManager implements Siegable
 			{
 				_log.log(Level.WARNING, "Territory War Manager: territory list error(): " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
-			try
+			
+			
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
 				PreparedStatement statement = con.prepareStatement("SELECT * FROM territory_registrations");
 				ResultSet rs = statement.executeQuery();
 				
@@ -838,10 +816,6 @@ public class TerritoryWarManager implements Siegable
 			{
 				_log.log(Level.WARNING, "Territory War Manager: registration list error: " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 		}
 		catch (Exception e)
 		{
@@ -1513,14 +1487,12 @@ public class TerritoryWarManager implements Siegable
 	@Override
 	public void startSiege()
 	{
-		// TODO Auto-generated method stub
 		throw new UnsupportedOperationException();
 	}
 	
 	@Override
 	public void endSiege()
 	{
-		// TODO Auto-generated method stub
 		throw new UnsupportedOperationException();
 	}
 	
@@ -1533,70 +1505,60 @@ public class TerritoryWarManager implements Siegable
 	@Override
 	public L2SiegeClan getAttackerClan(L2Clan clan)
 	{
-		// TODO Auto-generated method stub
 		throw new UnsupportedOperationException();
 	}
 	
 	@Override
 	public List<L2SiegeClan> getAttackerClans()
 	{
-		// TODO Auto-generated method stub
 		throw new UnsupportedOperationException();
 	}
 	
 	@Override
 	public List<L2PcInstance> getAttackersInZone()
 	{
-		// TODO Auto-generated method stub
 		throw new UnsupportedOperationException();
 	}
 	
 	@Override
 	public boolean checkIsAttacker(L2Clan clan)
 	{
-		// TODO Auto-generated method stub
 		throw new UnsupportedOperationException();
 	}
 	
 	@Override
 	public L2SiegeClan getDefenderClan(int clanId)
 	{
-		// TODO Auto-generated method stub
 		throw new UnsupportedOperationException();
 	}
 	
 	@Override
 	public L2SiegeClan getDefenderClan(L2Clan clan)
 	{
-		// TODO Auto-generated method stub
 		throw new UnsupportedOperationException();
 	}
 	
 	@Override
 	public List<L2SiegeClan> getDefenderClans()
 	{
-		// TODO Auto-generated method stub
 		throw new UnsupportedOperationException();
 	}
 	
 	@Override
 	public boolean checkIsDefender(L2Clan clan)
 	{
-		// TODO Auto-generated method stub
 		throw new UnsupportedOperationException();
 	}
 	
 	@Override
 	public List<L2Npc> getFlag(L2Clan clan)
 	{
-		// TODO Auto-generated method stub
 		throw new UnsupportedOperationException();
 	}
 	
 	@Override
 	public Calendar getSiegeDate()
 	{
-		// TODO Auto-generated method stub
 		throw new UnsupportedOperationException();
 	}
 	

+ 91 - 142
L2J_Server_BETA/java/com/l2jserver/gameserver/instancemanager/games/Lottery.java

@@ -18,6 +18,7 @@ import java.sql.Connection;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
+import java.sql.Statement;
 import java.util.Calendar;
 import java.util.logging.Level;
 import java.util.logging.Logger;
@@ -87,10 +88,8 @@ public class Lottery
 	public void increasePrize(long count)
 	{
 		_prize += count;
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement(UPDATE_PRICE);
 			statement.setLong(1, getPrize());
 			statement.setLong(2, getPrize());
@@ -102,10 +101,6 @@ public class Lottery
 		{
 			_log.log(Level.WARNING, "Lottery: Could not increase current lottery prize: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public boolean isSellableTickets()
@@ -128,14 +123,11 @@ public class Lottery
 		@Override
 		public void run()
 		{
-			Connection con = null;
-			PreparedStatement statement;
-			try
+			
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+				Statement statement = con.createStatement();
+				ResultSet rset = statement.executeQuery(SELECT_LAST_LOTTERY))
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
-				statement = con.prepareStatement(SELECT_LAST_LOTTERY);
-				ResultSet rset = statement.executeQuery();
-				
 				if (rset.next())
 				{
 					_number = rset.getInt("idnr");
@@ -153,8 +145,6 @@ public class Lottery
 						if (_enddate <= System.currentTimeMillis() + 2 * MINUTE)
 						{
 							(new finishLottery()).run();
-							rset.close();
-							statement.close();
 							return;
 						}
 						
@@ -168,23 +158,15 @@ public class Lottery
 								_isSellingTickets = true;
 								ThreadPoolManager.getInstance().scheduleGeneral(new stopSellingTickets(), _enddate - System.currentTimeMillis() - 10 * MINUTE);
 							}
-							rset.close();
-							statement.close();
 							return;
 						}
 					}
 				}
-				rset.close();
-				statement.close();
 			}
 			catch (SQLException e)
 			{
 				_log.log(Level.WARNING, "Lottery: Could not restore lottery data: " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 			
 			if (Config.DEBUG)
 				_log.info("Lottery: Starting ticket sell for lottery #" + getId() + ".");
@@ -213,26 +195,20 @@ public class Lottery
 			ThreadPoolManager.getInstance().scheduleGeneral(new stopSellingTickets(), _enddate - System.currentTimeMillis() - 10 * MINUTE);
 			ThreadPoolManager.getInstance().scheduleGeneral(new finishLottery(), _enddate - System.currentTimeMillis());
 			
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+				PreparedStatement statement = con.prepareStatement(INSERT_LOTTERY))
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
-				statement = con.prepareStatement(INSERT_LOTTERY);
 				statement.setInt(1, 1);
 				statement.setInt(2, getId());
 				statement.setLong(3, getEndDate());
 				statement.setLong(4, getPrize());
 				statement.setLong(5, getPrize());
 				statement.execute();
-				statement.close();
 			}
 			catch (SQLException e)
 			{
 				_log.log(Level.WARNING, "Lottery: Could not store new lottery data: " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 		}
 	}
 	
@@ -309,61 +285,53 @@ public class Lottery
 			int count3 = 0;
 			int count4 = 0;
 			
-			Connection con = null;
-			PreparedStatement statement;
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+				PreparedStatement statement = con.prepareStatement(SELECT_LOTTERY_ITEM))
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
-				statement = con.prepareStatement(SELECT_LOTTERY_ITEM);
 				statement.setInt(1, getId());
-				ResultSet rset = statement.executeQuery();
-				
-				while (rset.next())
+				try (ResultSet rset = statement.executeQuery())
 				{
-					int curenchant = rset.getInt("enchant_level") & enchant;
-					int curtype2 = rset.getInt("custom_type2") & type2;
-					
-					if (curenchant == 0 && curtype2 == 0)
-						continue;
-					
-					int count = 0;
-					
-					for (int i = 1; i <= 16; i++)
+					while (rset.next())
 					{
-						int val = curenchant / 2;
+						int curenchant = rset.getInt("enchant_level") & enchant;
+						int curtype2 = rset.getInt("custom_type2") & type2;
 						
-						if (val != Math.round((double) curenchant / 2))
-							count++;
+						if (curenchant == 0 && curtype2 == 0)
+							continue;
 						
-						int val2 = curtype2 / 2;
+						int count = 0;
 						
-						if (val2 != (double) curtype2 / 2)
-							count++;
+						for (int i = 1; i <= 16; i++)
+						{
+							int val = curenchant / 2;
+							
+							if (val != Math.round((double) curenchant / 2))
+								count++;
+							
+							int val2 = curtype2 / 2;
+							
+							if (val2 != (double) curtype2 / 2)
+								count++;
+							
+							curenchant = val;
+							curtype2 = val2;
+						}
 						
-						curenchant = val;
-						curtype2 = val2;
+						if (count == 5)
+							count1++;
+						else if (count == 4)
+							count2++;
+						else if (count == 3)
+							count3++;
+						else if (count > 0)
+							count4++;
 					}
-					
-					if (count == 5)
-						count1++;
-					else if (count == 4)
-						count2++;
-					else if (count == 3)
-						count3++;
-					else if (count > 0)
-						count4++;
 				}
-				rset.close();
-				statement.close();
 			}
 			catch (SQLException e)
 			{
 				_log.log(Level.WARNING, "Lottery: Could restore lottery data: " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 			
 			long prize4 = count4 * Config.ALT_LOTTERY_2_AND_1_NUMBER_PRIZE;
 			long prize1 = 0;
@@ -410,10 +378,9 @@ public class Lottery
 				Announcements.getInstance().announceToAll(sm);
 			}
 			
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+				PreparedStatement statement = con.prepareStatement(UPDATE_LOTTERY))
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
-				statement = con.prepareStatement(UPDATE_LOTTERY);
 				statement.setLong(1, getPrize());
 				statement.setLong(2, newprize);
 				statement.setInt(3, enchant);
@@ -423,16 +390,11 @@ public class Lottery
 				statement.setLong(7, prize3);
 				statement.setInt(8, getId());
 				statement.execute();
-				statement.close();
 			}
 			catch (SQLException e)
 			{
 				_log.log(Level.WARNING, "Lottery: Could not store finished lottery data: " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 			
 			ThreadPoolManager.getInstance().scheduleGeneral(new startLottery(), MINUTE);
 			_number++;
@@ -482,79 +444,66 @@ public class Lottery
 	public long[] checkTicket(int id, int enchant, int type2)
 	{
 		long res[] = { 0, 0 };
-		
-		Connection con = null;
-		PreparedStatement statement;
-		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement(SELECT_LOTTERY_TICKET))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			statement = con.prepareStatement(SELECT_LOTTERY_TICKET);
 			statement.setInt(1, id);
-			ResultSet rset = statement.executeQuery();
-			
-			if (rset.next())
+			try (ResultSet rset = statement.executeQuery())
 			{
-				int curenchant = rset.getInt("number1") & enchant;
-				int curtype2 = rset.getInt("number2") & type2;
-				
-				if (curenchant == 0 && curtype2 == 0)
-				{
-					rset.close();
-					statement.close();
-					return res;
-				}
-				
-				int count = 0;
-				
-				for (int i = 1; i <= 16; i++)
-				{
-					int val = curenchant / 2;
-					if (val != Math.round((double) curenchant / 2))
-						count++;
-					int val2 = curtype2 / 2;
-					if (val2 != (double) curtype2 / 2)
-						count++;
-					curenchant = val;
-					curtype2 = val2;
-				}
-				
-				switch (count)
+				if (rset.next())
 				{
-					case 0:
-						break;
-					case 5:
-						res[0] = 1;
-						res[1] = rset.getLong("prize1");
-						break;
-					case 4:
-						res[0] = 2;
-						res[1] = rset.getLong("prize2");
-						break;
-					case 3:
-						res[0] = 3;
-						res[1] = rset.getLong("prize3");
-						break;
-					default:
-						res[0] = 4;
-						res[1] = 200;
+					int curenchant = rset.getInt("number1") & enchant;
+					int curtype2 = rset.getInt("number2") & type2;
+					
+					if (curenchant == 0 && curtype2 == 0)
+					{
+						return res;
+					}
+					
+					int count = 0;
+					
+					for (int i = 1; i <= 16; i++)
+					{
+						int val = curenchant / 2;
+						if (val != Math.round((double) curenchant / 2))
+							count++;
+						int val2 = curtype2 / 2;
+						if (val2 != (double) curtype2 / 2)
+							count++;
+						curenchant = val;
+						curtype2 = val2;
+					}
+					
+					switch (count)
+					{
+						case 0:
+							break;
+						case 5:
+							res[0] = 1;
+							res[1] = rset.getLong("prize1");
+							break;
+						case 4:
+							res[0] = 2;
+							res[1] = rset.getLong("prize2");
+							break;
+						case 3:
+							res[0] = 3;
+							res[1] = rset.getLong("prize3");
+							break;
+						default:
+							res[0] = 4;
+							res[1] = 200;
+					}
+					
+					if (Config.DEBUG)
+						_log.warning("count: " + count + ", id: " + id + ", enchant: " + enchant + ", type2: " + type2);
 				}
-				
-				if (Config.DEBUG)
-					_log.warning("count: " + count + ", id: " + id + ", enchant: " + enchant + ", type2: " + type2);
 			}
-			
-			rset.close();
-			statement.close();
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.WARNING, "Lottery: Could not check lottery ticket #" + id + ": " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		return res;
 	}
 	

+ 13 - 20
L2J_Server_BETA/java/com/l2jserver/gameserver/model/AutoChatHandler.java

@@ -64,11 +64,8 @@ public class AutoChatHandler implements SpawnListener
 	private void restoreChatData()
 	{
 		int numLoaded = 0;
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			PreparedStatement statement = con.prepareStatement("SELECT * FROM auto_chat ORDER BY groupId ASC");
 			ResultSet rs = statement.executeQuery();
 			
@@ -78,20 +75,20 @@ public class AutoChatHandler implements SpawnListener
 				numLoaded++;
 				
 				statement2.setInt(1, rs.getInt("groupId"));
-				ResultSet rs2 = statement2.executeQuery();
-				statement2.clearParameters();
-				
-				rs2.last();
-				String[] chatTexts = new String[rs2.getRow()];
-				int i = 0;
-				rs2.beforeFirst();
-				
-				while (rs2.next())
+				try (ResultSet rs2 = statement2.executeQuery())
 				{
-					chatTexts[i++] = rs2.getString("chatText");
+					statement2.clearParameters();
+					rs2.last();
+					String[] chatTexts = new String[rs2.getRow()];
+					int i = 0;
+					rs2.beforeFirst();
+					
+					while (rs2.next())
+					{
+						chatTexts[i++] = rs2.getString("chatText");
+					}
+					registerGlobalChat(rs.getInt("npcId"), chatTexts, rs.getLong("chatDelay"));
 				}
-				
-				registerGlobalChat(rs.getInt("npcId"), chatTexts, rs.getLong("chatDelay"));
 			}
 			statement2.close();
 			rs.close();
@@ -104,10 +101,6 @@ public class AutoChatHandler implements SpawnListener
 		{
 			_log.log(Level.WARNING, "AutoSpawnHandler: Could not restore chat data: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public void reload()

+ 1 - 9
L2J_Server_BETA/java/com/l2jserver/gameserver/model/AutoSpawnHandler.java

@@ -122,12 +122,8 @@ public class AutoSpawnHandler
 	private void restoreSpawnData()
 	{
 		int numLoaded = 0;
-		Connection con = null;
-		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			// Restore spawn group data, then the location data.
 			PreparedStatement statement = con.prepareStatement("SELECT * FROM random_spawn ORDER BY groupId ASC");
 			ResultSet rs = statement.executeQuery();
@@ -166,10 +162,6 @@ public class AutoSpawnHandler
 		{
 			_log.log(Level.WARNING, "AutoSpawnHandler: Could not restore spawn data: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**

+ 14 - 23
L2J_Server_BETA/java/com/l2jserver/gameserver/model/BlockList.java

@@ -71,12 +71,10 @@ public class BlockList
 	
 	private static List<Integer> loadList(int ObjId)
 	{
-		Connection con = null;
 		List<Integer> list = new FastList<>();
 		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT friendId FROM character_friends WHERE charId=? AND relation=1");
 			statement.setInt(1, ObjId);
 			ResultSet rset = statement.executeQuery();
@@ -97,43 +95,36 @@ public class BlockList
 		{
 			_log.log(Level.WARNING, "Error found in " + ObjId + " FriendList while loading BlockList: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		return list;
 	}
 	
 	private void updateInDB(int targetId, boolean state)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement;
 			if (state) //add
 			{
-				statement = con.prepareStatement("INSERT INTO character_friends (charId, friendId, relation) VALUES (?, ?, 1)");
-				statement.setInt(1, _owner.getObjectId());
-				statement.setInt(2, targetId);
+				try (PreparedStatement statement = con.prepareStatement("INSERT INTO character_friends (charId, friendId, relation) VALUES (?, ?, 1)"))
+				{
+					statement.setInt(1, _owner.getObjectId());
+					statement.setInt(2, targetId);
+					statement.execute();
+				}
 			}
 			else //remove
 			{
-				statement = con.prepareStatement("DELETE FROM character_friends WHERE charId=? AND friendId=? AND relation=1");
-				statement.setInt(1, _owner.getObjectId());
-				statement.setInt(2, targetId);
+				try (PreparedStatement statement = con.prepareStatement("DELETE FROM character_friends WHERE charId=? AND friendId=? AND relation=1"))
+				{
+					statement.setInt(1, _owner.getObjectId());
+					statement.setInt(2, targetId);
+					statement.execute();
+				}
 			}
-			statement.execute();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Could not add block player: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public boolean isInBlockList(L2PcInstance target)

+ 3 - 16
L2J_Server_BETA/java/com/l2jserver/gameserver/model/CursedWeapon.java

@@ -127,11 +127,8 @@ public class CursedWeapon
 				// Remove from Db
 				_log.info(_name + " being removed offline." );
 				
-				Connection con = null;
-				try
+				try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 				{
-					con = L2DatabaseFactory.getInstance().getConnection();
-					
 					// Delete the item
 					PreparedStatement statement = con.prepareStatement("DELETE FROM items WHERE owner_id=? AND item_id=?");
 					statement.setInt(1, _playerId);
@@ -167,10 +164,6 @@ public class CursedWeapon
 				{
 					_log.log(Level.WARNING, "Could not delete : " + e.getMessage(), e);
 				}
-				finally
-				{
-					L2DatabaseFactory.close(con);
-				}
 			}
 		} else
 		{
@@ -475,15 +468,13 @@ public class CursedWeapon
 		if (Config.DEBUG)
 			_log.info("CursedWeapon: Saving data to disk.");
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			// Delete previous datas
 			PreparedStatement statement = con.prepareStatement("DELETE FROM cursed_weapons WHERE itemId = ?");
 			statement.setInt(1, _itemId);
 			statement.executeUpdate();
+			statement.close();
 			
 			if (_isActivated)
 			{
@@ -502,10 +493,6 @@ public class CursedWeapon
 		{
 			_log.log(Level.SEVERE, "CursedWeapon: Failed to save data.", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public void dropIt(L2Character killer)

+ 153 - 300
L2J_Server_BETA/java/com/l2jserver/gameserver/model/L2Clan.java

@@ -816,24 +816,17 @@ public class L2Clan
 	 */
 	public void updateClanScoreInDB()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("UPDATE clan_data SET reputation_score=? WHERE clan_id=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			final PreparedStatement statement = con.prepareStatement("UPDATE clan_data SET reputation_score=? WHERE clan_id=?");
 			statement.setInt(1, getReputationScore());
 			statement.setInt(2, getClanId());
 			statement.execute();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Exception on updateClanScoreInDb(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -852,10 +845,8 @@ public class L2Clan
 	 */
 	public void updateClanInDB()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			final PreparedStatement statement = con.prepareStatement("UPDATE clan_data SET leader_id=?,ally_id=?,ally_name=?,reputation_score=?,ally_penalty_expiry_time=?,ally_penalty_type=?,char_penalty_expiry_time=?,dissolving_expiry_time=? WHERE clan_id=?");
 			statement.setInt(1, getLeaderId());
 			statement.setInt(2, getAllyId());
@@ -875,10 +866,6 @@ public class L2Clan
 		{
 			_log.log(Level.SEVERE, "Error saving clan: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -898,10 +885,8 @@ public class L2Clan
 	 */
 	public void store()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			final PreparedStatement statement = con.prepareStatement("INSERT INTO clan_data (clan_id,clan_name,clan_level,hasCastle,ally_id,ally_name,leader_id,crest_id,crest_large_id,ally_crest_id) values (?,?,?,?,?,?,?,?,?,?)");
 			statement.setInt(1, getClanId());
 			statement.setString(2, getName());
@@ -922,10 +907,6 @@ public class L2Clan
 		{
 			_log.log(Level.SEVERE, "Error saving new clan: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -935,10 +916,8 @@ public class L2Clan
 	 */
 	private void removeMemberInDatabase(L2ClanMember member, long clanJoinExpiryTime, long clanCreateExpiryTime)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("UPDATE characters SET clanid=0, title=?, clan_join_expiry_time=?, clan_create_expiry_time=?, clan_privs=0, wantspeace=0, subpledge=0, lvl_joined_academy=0, apprentice=0, sponsor=0 WHERE charId=?");
 			statement.setString(1, "");
 			statement.setLong(2, clanJoinExpiryTime);
@@ -963,19 +942,13 @@ public class L2Clan
 		{
 			_log.log(Level.SEVERE, "Error removing clan member: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	@SuppressWarnings("unused")
 	private void updateWarsInDB()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			final PreparedStatement statement = con.prepareStatement("UPDATE clan_wars SET wantspeace1=? WHERE clan1=?");
 			statement.setInt(1, 0);
 			statement.setInt(2, 0);
@@ -985,70 +958,66 @@ public class L2Clan
 		{
 			_log.log(Level.SEVERE, "Error updating clan wars data: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void restore()
 	{
 		//restorewars();
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("SELECT clan_name,clan_level,hasCastle,ally_id,ally_name,leader_id,crest_id,crest_large_id,ally_crest_id,reputation_score,auction_bid_at,ally_penalty_expiry_time,ally_penalty_type,char_penalty_expiry_time,dissolving_expiry_time FROM clan_data where clan_id=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("SELECT clan_name,clan_level,hasCastle,ally_id,ally_name,leader_id,crest_id,crest_large_id,ally_crest_id,reputation_score,auction_bid_at,ally_penalty_expiry_time,ally_penalty_type,char_penalty_expiry_time,dissolving_expiry_time FROM clan_data where clan_id=?");
 			statement.setInt(1, getClanId());
-			final ResultSet clanData = statement.executeQuery();
-			
-			if (clanData.next())
+			try (ResultSet clanData = statement.executeQuery())
 			{
-				setName(clanData.getString("clan_name"));
-				setLevel(clanData.getInt("clan_level"));
-				setCastleId(clanData.getInt("hasCastle"));
-				setAllyId(clanData.getInt("ally_id"));
-				setAllyName(clanData.getString("ally_name"));
-				setAllyPenaltyExpiryTime(clanData.getLong("ally_penalty_expiry_time"), clanData.getInt("ally_penalty_type"));
-				if (getAllyPenaltyExpiryTime() < System.currentTimeMillis())
-				{
-					setAllyPenaltyExpiryTime(0, 0);
-				}
-				setCharPenaltyExpiryTime(clanData.getLong("char_penalty_expiry_time"));
-				if (getCharPenaltyExpiryTime() + Config.ALT_CLAN_JOIN_DAYS * 86400000L < System.currentTimeMillis()) //24*60*60*1000 = 86400000
+				if (clanData.next())
 				{
-					setCharPenaltyExpiryTime(0);
-				}
-				setDissolvingExpiryTime(clanData.getLong("dissolving_expiry_time"));
-				
-				setCrestId(clanData.getInt("crest_id"));
-				setCrestLargeId(clanData.getInt("crest_large_id"));
-				setAllyCrestId(clanData.getInt("ally_crest_id"));
-				
-				setReputationScore(clanData.getInt("reputation_score"), false);
-				setAuctionBiddedAt(clanData.getInt("auction_bid_at"), false);
-				
-				final int leaderId = (clanData.getInt("leader_id"));
-				
-				statement.clearParameters();
-				statement = con.prepareStatement("SELECT char_name,level,classid,charId,title,power_grade,subpledge,apprentice,sponsor,sex,race FROM characters WHERE clanid=?");
-				statement.setInt(1, getClanId());
-				final ResultSet clanMembers = statement.executeQuery();
-				
-				L2ClanMember member = null;
-				while (clanMembers.next())
-				{
-					member = new L2ClanMember(this, clanMembers.getString("char_name"), clanMembers.getInt("level"), clanMembers.getInt("classid"), clanMembers.getInt("charId"), clanMembers.getInt("subpledge"), clanMembers.getInt("power_grade"), clanMembers.getString("title"), (clanMembers.getInt("sex") != 0), clanMembers.getInt("race"));
-					if (member.getObjectId() == leaderId)
-						setLeader(member);
-					else
-						addClanMember(member);
-					member.initApprenticeAndSponsor(clanMembers.getInt("apprentice"), clanMembers.getInt("sponsor"));
+					setName(clanData.getString("clan_name"));
+					setLevel(clanData.getInt("clan_level"));
+					setCastleId(clanData.getInt("hasCastle"));
+					setAllyId(clanData.getInt("ally_id"));
+					setAllyName(clanData.getString("ally_name"));
+					setAllyPenaltyExpiryTime(clanData.getLong("ally_penalty_expiry_time"), clanData.getInt("ally_penalty_type"));
+					if (getAllyPenaltyExpiryTime() < System.currentTimeMillis())
+					{
+						setAllyPenaltyExpiryTime(0, 0);
+					}
+					setCharPenaltyExpiryTime(clanData.getLong("char_penalty_expiry_time"));
+					if (getCharPenaltyExpiryTime() + Config.ALT_CLAN_JOIN_DAYS * 86400000L < System.currentTimeMillis()) //24*60*60*1000 = 86400000
+					{
+						setCharPenaltyExpiryTime(0);
+					}
+					setDissolvingExpiryTime(clanData.getLong("dissolving_expiry_time"));
+					
+					setCrestId(clanData.getInt("crest_id"));
+					setCrestLargeId(clanData.getInt("crest_large_id"));
+					setAllyCrestId(clanData.getInt("ally_crest_id"));
+					
+					setReputationScore(clanData.getInt("reputation_score"), false);
+					setAuctionBiddedAt(clanData.getInt("auction_bid_at"), false);
+					
+					final int leaderId = (clanData.getInt("leader_id"));
+					
+					statement.clearParameters();
+					
+					try (PreparedStatement select = con.prepareStatement("SELECT char_name,level,classid,charId,title,power_grade,subpledge,apprentice,sponsor,sex,race FROM characters WHERE clanid=?"))
+					{
+						select.setInt(1, getClanId());
+						try (ResultSet clanMembers = select.executeQuery())
+						{
+							L2ClanMember member = null;
+							while (clanMembers.next())
+							{
+								member = new L2ClanMember(this, clanMembers.getString("char_name"), clanMembers.getInt("level"), clanMembers.getInt("classid"), clanMembers.getInt("charId"), clanMembers.getInt("subpledge"), clanMembers.getInt("power_grade"), clanMembers.getString("title"), (clanMembers.getInt("sex") != 0), clanMembers.getInt("race"));
+								if (member.getObjectId() == leaderId)
+									setLeader(member);
+								else
+									addClanMember(member);
+								member.initApprenticeAndSponsor(clanMembers.getInt("apprentice"), clanMembers.getInt("sponsor"));
+							}
+						}
+					}
 				}
-				clanMembers.close();
 			}
-			clanData.close();
-			statement.close();
 			
 			if (Config.DEBUG && getName() != null)
 				_log.info("Restored clan data for \"" + getName() + "\" from database.");
@@ -1062,39 +1031,27 @@ public class L2Clan
 		{
 			_log.log(Level.SEVERE, "Error restoring clan data: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void restoreNotice()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("SELECT enabled,notice FROM clan_notices WHERE clan_id=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			final PreparedStatement statement = con.prepareStatement("SELECT enabled,notice FROM clan_notices WHERE clan_id=?");
 			statement.setInt(1, getClanId());
-			final ResultSet noticeData = statement.executeQuery();
-			
-			while (noticeData.next())
+			try (ResultSet noticeData = statement.executeQuery())
 			{
-				_noticeEnabled = noticeData.getBoolean("enabled");
-				_notice = noticeData.getString("notice");
+				while (noticeData.next())
+				{
+					_noticeEnabled = noticeData.getBoolean("enabled");
+					_notice = noticeData.getString("notice");
+				}
 			}
-			
-			noticeData.close();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, "Error restoring clan notice: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void storeNotice(String notice, boolean enabled)
@@ -1105,11 +1062,9 @@ public class L2Clan
 		if (notice.length() > MAX_NOTICE_LENGTH)
 			notice = notice.substring(0, MAX_NOTICE_LENGTH - 1);
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("INSERT INTO clan_notices (clan_id,notice,enabled) values (?,?,?) ON DUPLICATE KEY UPDATE notice=?,enabled=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			final PreparedStatement statement = con.prepareStatement("INSERT INTO clan_notices (clan_id,notice,enabled) values (?,?,?) ON DUPLICATE KEY UPDATE notice=?,enabled=?");
 			statement.setInt(1, getClanId());
 			statement.setString(2, notice);
 			if (enabled)
@@ -1122,16 +1077,11 @@ public class L2Clan
 			else
 				statement.setString(5, "false");
 			statement.execute();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Error could not store clan notice: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
 		_notice = notice;
 		_noticeEnabled = enabled;
@@ -1161,50 +1111,42 @@ public class L2Clan
 	
 	private void restoreSkills()
 	{
-		Connection con = null;
-		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("SELECT skill_id,skill_level,sub_pledge_id FROM clan_skills WHERE clan_id=?"))
 		{
 			// Retrieve all skills of this L2PcInstance from the database
-			con = L2DatabaseFactory.getInstance().getConnection();
-			final PreparedStatement statement = con.prepareStatement("SELECT skill_id,skill_level,sub_pledge_id FROM clan_skills WHERE clan_id=?");
 			statement.setInt(1, getClanId());
-			final ResultSet rset = statement.executeQuery();
-			
-			// Go though the recordset of this SQL query
-			while (rset.next())
+			try (ResultSet rset = statement.executeQuery())
 			{
-				int id = rset.getInt("skill_id");
-				int level = rset.getInt("skill_level");
-				// Create a L2Skill object for each record
-				L2Skill skill = SkillTable.getInstance().getInfo(id, level);
-				// Add the L2Skill object to the L2Clan _skills
-				int subType = rset.getInt("sub_pledge_id");
-				
-				if (subType == -2)
-					_skills.put(skill.getId(), skill);
-				else if (subType == 0)
-					_subPledgeSkills.put(skill.getId(), skill);
-				else
+				// Go though the recordset of this SQL query
+				while (rset.next())
 				{
-					SubPledge subunit = _subPledges.get(subType);
-					if (subunit != null)
-						subunit.addNewSkill(skill);
+					int id = rset.getInt("skill_id");
+					int level = rset.getInt("skill_level");
+					// Create a L2Skill object for each record
+					L2Skill skill = SkillTable.getInstance().getInfo(id, level);
+					// Add the L2Skill object to the L2Clan _skills
+					int subType = rset.getInt("sub_pledge_id");
+					
+					if (subType == -2)
+						_skills.put(skill.getId(), skill);
+					else if (subType == 0)
+						_subPledgeSkills.put(skill.getId(), skill);
 					else
-						_log.info("Missing subpledge "+subType+" for clan "+this+", skill skipped.");
+					{
+						SubPledge subunit = _subPledges.get(subType);
+						if (subunit != null)
+							subunit.addNewSkill(skill);
+						else
+							_log.info("Missing subpledge "+subType+" for clan "+this+", skill skipped.");
+					}
 				}
 			}
-			rset.close();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, "Error restoring clan skills: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -1258,8 +1200,6 @@ public class L2Clan
 	public L2Skill addNewSkill(L2Skill newSkill, int subType)
 	{
 		L2Skill oldSkill = null;
-		Connection con = null;
-		
 		if (newSkill != null)
 		{
 			
@@ -1279,37 +1219,35 @@ public class L2Clan
 				}
 			}
 			
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
-				PreparedStatement statement;
 				if (oldSkill != null)
 				{
-					statement = con.prepareStatement("UPDATE clan_skills SET skill_level=? WHERE skill_id=? AND clan_id=?");
-					statement.setInt(1, newSkill.getLevel());
-					statement.setInt(2, oldSkill.getId());
-					statement.setInt(3, getClanId());
+					try (PreparedStatement statement = con.prepareStatement("UPDATE clan_skills SET skill_level=? WHERE skill_id=? AND clan_id=?"))
+					{
+						statement.setInt(1, newSkill.getLevel());
+						statement.setInt(2, oldSkill.getId());
+						statement.setInt(3, getClanId());
+						statement.execute();
+					}
 				}
 				else
 				{
-					statement = con.prepareStatement("INSERT INTO clan_skills (clan_id,skill_id,skill_level,skill_name,sub_pledge_id) VALUES (?,?,?,?,?)");
-					statement.setInt(1, getClanId());
-					statement.setInt(2, newSkill.getId());
-					statement.setInt(3, newSkill.getLevel());
-					statement.setString(4, newSkill.getName());
-					statement.setInt(5, subType);
+					try (PreparedStatement statement = con.prepareStatement("INSERT INTO clan_skills (clan_id,skill_id,skill_level,skill_name,sub_pledge_id) VALUES (?,?,?,?,?)"))
+					{
+						statement.setInt(1, getClanId());
+						statement.setInt(2, newSkill.getId());
+						statement.setInt(3, newSkill.getLevel());
+						statement.setString(4, newSkill.getName());
+						statement.setInt(5, subType);
+						statement.execute();
+					}
 				}
-				statement.execute();
-				statement.close();
 			}
 			catch (Exception e)
 			{
 				_log.log(Level.WARNING, "Error could not store clan skills: " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 			
 			SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.CLAN_SKILL_S1_ADDED);
 			sm.addSkillName(newSkill.getId());
@@ -1652,35 +1590,28 @@ public class L2Clan
 	
 	private void restoreSubPledges()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("SELECT sub_pledge_id,name,leader_id FROM clan_subpledges WHERE clan_id=?"))
 		{
 			// Retrieve all subpledges of this clan from the database
-			con = L2DatabaseFactory.getInstance().getConnection();
-			final PreparedStatement statement = con.prepareStatement("SELECT sub_pledge_id,name,leader_id FROM clan_subpledges WHERE clan_id=?");
 			statement.setInt(1, getClanId());
-			final ResultSet rset = statement.executeQuery();
-			
-			while (rset.next())
+			try (ResultSet rset = statement.executeQuery())
 			{
-				int id = rset.getInt("sub_pledge_id");
-				String name = rset.getString("name");
-				int leaderId = rset.getInt("leader_id");
-				// Create a SubPledge object for each record
-				SubPledge pledge = new SubPledge(id, name, leaderId);
-				_subPledges.put(id, pledge);
+				while (rset.next())
+				{
+					int id = rset.getInt("sub_pledge_id");
+					String name = rset.getString("name");
+					int leaderId = rset.getInt("leader_id");
+					// Create a SubPledge object for each record
+					SubPledge pledge = new SubPledge(id, name, leaderId);
+					_subPledges.put(id, pledge);
+				}
 			}
-			rset.close();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Could not restore clan sub-units: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -1754,11 +1685,9 @@ public class L2Clan
 			return null;
 		}
 		
-		Connection con = null;
-		try
-		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			final PreparedStatement statement = con.prepareStatement("INSERT INTO clan_subpledges (clan_id,sub_pledge_id,name,leader_id) values (?,?,?,?)");
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("INSERT INTO clan_subpledges (clan_id,sub_pledge_id,name,leader_id) values (?,?,?,?)"))
+		{ 
 			statement.setInt(1, getClanId());
 			statement.setInt(2, pledgeType);
 			statement.setString(3, subPledgeName);
@@ -1767,7 +1696,6 @@ public class L2Clan
 			else
 				statement.setInt(4, 0);
 			statement.execute();
-			statement.close();
 			
 			subPledge = new SubPledge(pledgeType, subPledgeName, leaderId);
 			_subPledges.put(pledgeType, subPledge);
@@ -1790,10 +1718,7 @@ public class L2Clan
 		{
 			_log.log(Level.SEVERE, "Error saving sub clan data: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
+		
 		broadcastToOnlineMembers(new PledgeShowInfoUpdate(_leader.getClan()));
 		broadcastToOnlineMembers(new PledgeReceiveSubPledgeCreated(subPledge, _leader.getClan()));
 		return subPledge;
@@ -1831,17 +1756,14 @@ public class L2Clan
 	
 	public void updateSubPledgeInDB(int pledgeType)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("UPDATE clan_subpledges SET leader_id=?, name=? WHERE clan_id=? AND sub_pledge_id=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			final PreparedStatement statement = con.prepareStatement("UPDATE clan_subpledges SET leader_id=?, name=? WHERE clan_id=? AND sub_pledge_id=?");
 			statement.setInt(1, getSubPledge(pledgeType).getLeaderId());
 			statement.setString(2, getSubPledge(pledgeType).getName());
 			statement.setInt(3, getClanId());
 			statement.setInt(4, pledgeType);
 			statement.execute();
-			statement.close();
 			if (Config.DEBUG)
 				_log.fine("Subpledge updated in db: " + getClanId());
 		}
@@ -1849,47 +1771,36 @@ public class L2Clan
 		{
 			_log.log(Level.SEVERE, "Error updating subpledge: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void restoreRankPrivs()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("SELECT privs,rank,party FROM clan_privs WHERE clan_id=?"))
 		{
 			// Retrieve all skills of this L2PcInstance from the database
-			con = L2DatabaseFactory.getInstance().getConnection();
-			final PreparedStatement statement = con.prepareStatement("SELECT privs,rank,party FROM clan_privs WHERE clan_id=?");
 			statement.setInt(1, getClanId());
 			//_log.warning("clanPrivs restore for ClanId : "+getClanId());
-			final ResultSet rset = statement.executeQuery();
-			
-			// Go though the recordset of this SQL query
-			while (rset.next())
+			try (ResultSet rset = statement.executeQuery())
 			{
-				int rank = rset.getInt("rank");
-				//int party = rset.getInt("party");
-				int privileges = rset.getInt("privs");
-				// Create a SubPledge object for each record
-				if (rank == -1)
-					continue;
-				
-				_privs.get(rank).setPrivs(privileges);
+				// Go though the recordset of this SQL query
+				while (rset.next())
+				{
+					int rank = rset.getInt("rank");
+					//int party = rset.getInt("party");
+					int privileges = rset.getInt("privs");
+					// Create a SubPledge object for each record
+					if (rank == -1)
+						continue;
+					
+					_privs.get(rank).setPrivs(privileges);
+				}
 			}
-			rset.close();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, "Error restoring clan privs by rank: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public void initializePrivs()
@@ -1900,7 +1811,6 @@ public class L2Clan
 			privs = new RankPrivs(i, 0, CP_NOTHING);
 			_privs.put(i, privs);
 		}
-		
 	}
 	
 	public int getRankPrivs(int rank)
@@ -1916,29 +1826,22 @@ public class L2Clan
 		{
 			_privs.get(rank).setPrivs(privs);
 			
-			Connection con = null;
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+				PreparedStatement statement = con.prepareStatement("INSERT INTO clan_privs (clan_id,rank,party,privs) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE privs = ?"))
 			{
-				//_log.warning("requested store clan privs in db for rank: "+rank+", privs: "+privs);
 				// Retrieve all skills of this L2PcInstance from the database
-				con = L2DatabaseFactory.getInstance().getConnection();
-				final PreparedStatement statement = con.prepareStatement("INSERT INTO clan_privs (clan_id,rank,party,privs) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE privs = ?");
 				statement.setInt(1, getClanId());
 				statement.setInt(2, rank);
 				statement.setInt(3, 0);
 				statement.setInt(4, privs);
 				statement.setInt(5, privs);
 				statement.execute();
-				statement.close();
 			}
 			catch (Exception e)
 			{
 				_log.log(Level.WARNING, "Could not store clan privs for rank: " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
+			
 			for (L2ClanMember cm : getMembers())
 			{
 				if (cm.isOnline())
@@ -1956,30 +1859,20 @@ public class L2Clan
 		{
 			_privs.put(rank, new RankPrivs(rank, 0, privs));
 			
-			Connection con = null;
-			
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+				PreparedStatement statement = con.prepareStatement("INSERT INTO clan_privs (clan_id,rank,party,privs) VALUES (?,?,?,?)"))
 			{
-				//_log.warning("requested store clan new privs in db for rank: "+rank);
 				// Retrieve all skills of this L2PcInstance from the database
-				con = L2DatabaseFactory.getInstance().getConnection();
-				final PreparedStatement statement = con.prepareStatement("INSERT INTO clan_privs (clan_id,rank,party,privs) VALUES (?,?,?,?)");
 				statement.setInt(1, getClanId());
 				statement.setInt(2, rank);
 				statement.setInt(3, 0);
 				statement.setInt(4, privs);
-				
 				statement.execute();
-				statement.close();
 			}
 			catch (Exception e)
 			{
 				_log.log(Level.WARNING, "Could not create new rank and store clan privs for rank: " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 		}
 	}
 	
@@ -2078,25 +1971,17 @@ public class L2Clan
 		
 		if (storeInDb)
 		{
-			Connection con = null;
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+				PreparedStatement statement = con.prepareStatement("UPDATE clan_data SET auction_bid_at=? WHERE clan_id=?"))
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
-				final PreparedStatement statement = con.prepareStatement("UPDATE clan_data SET auction_bid_at=? WHERE clan_id=?");
 				statement.setInt(1, id);
 				statement.setInt(2, getClanId());
-				
 				statement.execute();
-				statement.close();
 			}
 			catch (Exception e)
 			{
 				_log.log(Level.WARNING, "Could not store auction for clan: " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 		}
 	}
 	
@@ -2658,25 +2543,17 @@ public class L2Clan
 	
 	public void changeLevel(int level)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("UPDATE clan_data SET clan_level = ? WHERE clan_id = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			final PreparedStatement statement = con.prepareStatement("UPDATE clan_data SET clan_level = ? WHERE clan_id = ?");
 			statement.setInt(1, level);
 			statement.setInt(2, getClanId());
-			
 			statement.execute();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "could not increase clan level:" + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
 		setLevel(level);
 		
@@ -2721,25 +2598,17 @@ public class L2Clan
 		
 		setCrestId(crestId);
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("UPDATE clan_data SET crest_id = ? WHERE clan_id = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			final PreparedStatement statement = con.prepareStatement("UPDATE clan_data SET crest_id = ? WHERE clan_id = ?");
 			statement.setInt(1, crestId);
 			statement.setInt(2, getClanId());
-			
 			statement.executeUpdate();
-			statement.close();
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.WARNING, "Could not update crest for clan " + getName() + " [" + getClanId() + "] : " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
 		for (L2PcInstance member : getOnlineMembers(0))
 			member.broadcastUserInfo();
@@ -2762,25 +2631,17 @@ public class L2Clan
 			allyId = getAllyId();
 		}
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement(sqlStatement))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			final PreparedStatement statement = con.prepareStatement(sqlStatement);
 			statement.setInt(1, crestId);
 			statement.setInt(2, allyId);
-			
 			statement.executeUpdate();
-			statement.close();
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.WARNING, "Could not update ally crest for ally/clan id " + allyId + " : " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
 		if (onlyThisClan)
 		{
@@ -2812,25 +2673,17 @@ public class L2Clan
 		
 		setCrestLargeId(crestId);
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("UPDATE clan_data SET crest_large_id = ? WHERE clan_id = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			final PreparedStatement statement = con.prepareStatement("UPDATE clan_data SET crest_large_id = ? WHERE clan_id = ?");
 			statement.setInt(1, crestId);
 			statement.setInt(2, getClanId());
-			
 			statement.executeUpdate();
-			statement.close();
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.WARNING, "Could not update large crest for clan " + getName() + " [" + getClanId() + "] : " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
 		for (L2PcInstance member : getOnlineMembers(0))
 			member.broadcastUserInfo();

+ 3 - 23
L2J_Server_BETA/java/com/l2jserver/gameserver/model/L2ClanMember.java

@@ -228,11 +228,8 @@ public class L2ClanMember
 	
 	public void updatePledgeType()
 	{
-		Connection con = null;
-		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("UPDATE characters SET subpledge=? WHERE charId=?");
 			statement.setLong(1, _pledgeType);
 			statement.setInt(2, getObjectId());
@@ -243,10 +240,6 @@ public class L2ClanMember
 		{
 			_log.log(Level.WARNING, "Could not update pledge type: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public int getPowerGrade()
@@ -278,11 +271,8 @@ public class L2ClanMember
 	 */
 	public void updatePowerGrade()
 	{
-		Connection con = null;
-		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("UPDATE characters SET power_grade=? WHERE charId=?");
 			statement.setLong(1, _powerGrade);
 			statement.setInt(2, getObjectId());
@@ -293,10 +283,6 @@ public class L2ClanMember
 		{
 			_log.log(Level.WARNING, "Could not update power _grade: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public void initApprenticeAndSponsor(int apprenticeID, int sponsorID)
@@ -623,10 +609,8 @@ public class L2ClanMember
 	
 	public void saveApprenticeAndSponsor(int apprentice, int sponsor)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("UPDATE characters SET apprentice=?,sponsor=? WHERE charId=?");
 			statement.setInt(1, apprentice);
 			statement.setInt(2, sponsor);
@@ -638,9 +622,5 @@ public class L2ClanMember
 		{
 			_log.log(Level.WARNING, "Could not save apprentice/sponsor: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 }

+ 19 - 41
L2J_Server_BETA/java/com/l2jserver/gameserver/model/L2ContactList.java

@@ -61,38 +61,29 @@ public class L2ContactList
 	{
 		_contacts.clear();
 		
-		Connection con = null;
-		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement(QUERY_LOAD))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement(QUERY_LOAD);
 			statement.setInt(1, activeChar.getObjectId());
-			ResultSet rset = statement.executeQuery();
-			
-			int contactId;
-			String contactName;
-			while (rset.next())
+			try (ResultSet rset = statement.executeQuery())
 			{
-				contactId = rset.getInt(1);
-				contactName = CharNameTable.getInstance().getNameById(contactId);
-				if (contactName == null || contactName.equals(activeChar.getName()) || contactId == activeChar.getObjectId())
-					continue;
-				
-				_contacts.add(contactName);
+				int contactId;
+				String contactName;
+				while (rset.next())
+				{
+					contactId = rset.getInt(1);
+					contactName = CharNameTable.getInstance().getNameById(contactId);
+					if (contactName == null || contactName.equals(activeChar.getName()) || contactId == activeChar.getObjectId())
+						continue;
+					
+					_contacts.add(contactName);
+				}
 			}
-			
-			rset.close();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Error found in " + activeChar.getName() + "'s ContactsList: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public boolean add(String name)
@@ -134,15 +125,12 @@ public class L2ContactList
 			}
 		}
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement(QUERY_ADD))
 		{	
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement(QUERY_ADD);
 			statement.setInt(1, activeChar.getObjectId());
 			statement.setInt(2, contactId);
 			statement.execute();
-			statement.close();
 			
 			_contacts.add(name);
 			
@@ -154,10 +142,6 @@ public class L2ContactList
 		{
 			_log.log(Level.WARNING, "Error found in " + activeChar.getName() + "'s ContactsList: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		return true;
 	}
 	
@@ -179,15 +163,13 @@ public class L2ContactList
 		
 		_contacts.remove(name);
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement(QUERY_REMOVE))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement(QUERY_REMOVE);
 			statement.setInt(1, activeChar.getObjectId());
 			statement.setInt(2, contactId);
 			statement.execute();
-			statement.close();
+			
 			SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_SUCCESFULLY_DELETED_FROM_CONTACT_LIST);
 			sm.addString(name);
 			activeChar.sendPacket(sm);
@@ -196,10 +178,6 @@ public class L2ContactList
 		{
 			_log.log(Level.WARNING, "Error found in " + activeChar.getName() + "'s ContactsList: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public List<String> getAllContacts()

+ 1 - 7
L2J_Server_BETA/java/com/l2jserver/gameserver/model/L2TradeList.java

@@ -352,10 +352,8 @@ public class L2TradeList
 		
 		protected void saveDataTimer()
 		{
-			Connection con = null;
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
 				PreparedStatement statement = con.prepareStatement("UPDATE merchant_buylists SET savetimer =? WHERE shop_id =? and item_id =?");
 				statement.setLong(1, _nextRestoreTime);
 				statement.setInt(2, _listId);
@@ -367,10 +365,6 @@ public class L2TradeList
 			{
 				_log.log(Level.SEVERE, "L2TradeItem: Could not update Timer save in Buylist");
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 		}
 	}
 }

+ 6 - 33
L2J_Server_BETA/java/com/l2jserver/gameserver/model/L2UIKeysSettings.java

@@ -107,17 +107,10 @@ public class L2UIKeysSettings
 			}
 		}
 		query = query.substring(0, query.length() - 1) + "; ";
-		
-		Connection con = null;
-		PreparedStatement statement;
-		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement(query))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
-			statement = con.prepareStatement(query);
 			statement.execute();
-			statement.close();
 		}
 		catch (Exception e)
 		{
@@ -135,23 +128,15 @@ public class L2UIKeysSettings
 		}
 		query = query.substring(0, query.length() - 1) + ";";
 		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement(query))
 		{
-			if (con == null)
-				con = L2DatabaseFactory.getInstance().getConnection();
-			
-			statement = con.prepareStatement(query);
 			statement.execute();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Exception: saveInDB(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		_saved = true;
 	}
 	
@@ -163,10 +148,8 @@ public class L2UIKeysSettings
 		
 		_storedCategories = new FastMap<>();
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement stmt = con.prepareStatement("SELECT * FROM character_ui_categories WHERE `charId` = ? ORDER BY `catId`, `order`");
 			stmt.setInt(1, _player.getObjectId());
 			ResultSet rs = stmt.executeQuery();
@@ -184,10 +167,6 @@ public class L2UIKeysSettings
 		{
 			_log.log(Level.WARNING, "Exception: getCatsFromDB(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
 		if (_storedCategories.size() < 1)
 			_storedCategories = UITable.getInstance().getCategories();
@@ -200,10 +179,8 @@ public class L2UIKeysSettings
 		
 		_storedKeys = new FastMap<>();
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement stmt = con.prepareStatement("SELECT * FROM character_ui_actions WHERE `charId` = ? ORDER BY `cat`, `order`");
 			stmt.setInt(1, _player.getObjectId());
 			ResultSet rs = stmt.executeQuery();
@@ -225,10 +202,6 @@ public class L2UIKeysSettings
 		{
 			_log.log(Level.WARNING, "Exception: getKeysFromDB(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
 		if (_storedKeys.size() < 1)
 			_storedKeys = UITable.getInstance().getKeys();

+ 3 - 23
L2J_Server_BETA/java/com/l2jserver/gameserver/model/MacroList.java

@@ -116,11 +116,8 @@ public class MacroList
 	
 	private void registerMacroInDb(L2Macro macro)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			PreparedStatement statement = con.prepareStatement("INSERT INTO character_macroses (charId,id,icon,name,descr,acronym,commands) values(?,?,?,?,?,?,?)");
 			statement.setInt(1, _owner.getObjectId());
 			statement.setInt(2, macro.id);
@@ -157,10 +154,6 @@ public class MacroList
 		{
 			_log.log(Level.WARNING, "could not store macro:", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -168,11 +161,8 @@ public class MacroList
 	 */
 	private void deleteMacroFromDb(L2Macro macro)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			PreparedStatement statement = con.prepareStatement("DELETE FROM character_macroses WHERE charId=? AND id=?");
 			statement.setInt(1, _owner.getObjectId());
 			statement.setInt(2, macro.id);
@@ -183,19 +173,13 @@ public class MacroList
 		{
 			_log.log(Level.WARNING, "could not delete macro:", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public void restore()
 	{
 		_macroses.clear();
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT charId, id, icon, name, descr, acronym, commands FROM character_macroses WHERE charId=?");
 			statement.setInt(1, _owner.getObjectId());
 			ResultSet rset = statement.executeQuery();
@@ -233,9 +217,5 @@ public class MacroList
 		{
 			_log.log(Level.WARNING, "could not store shortcuts:", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 }

+ 3 - 23
L2J_Server_BETA/java/com/l2jserver/gameserver/model/ShortCuts.java

@@ -89,11 +89,8 @@ public class ShortCuts
 			deleteShortCutFromDb(oldShortCut);
 		}
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			PreparedStatement statement = con.prepareStatement("REPLACE INTO character_shortcuts (charId,slot,page,type,shortcut_id,level,class_index) values(?,?,?,?,?,?,?)");
 			statement.setInt(1, _owner.getObjectId());
 			statement.setInt(2, shortcut.getSlot());
@@ -109,10 +106,6 @@ public class ShortCuts
 		{
 			_log.log(Level.WARNING, "Could not store character shortcut: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -165,11 +158,8 @@ public class ShortCuts
 	 */
 	private void deleteShortCutFromDb(L2ShortCut shortcut)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			PreparedStatement statement = con.prepareStatement("DELETE FROM character_shortcuts WHERE charId=? AND slot=? AND page=? AND class_index=?");
 			statement.setInt(1, _owner.getObjectId());
 			statement.setInt(2, shortcut.getSlot());
@@ -182,19 +172,13 @@ public class ShortCuts
 		{
 			_log.log(Level.WARNING, "Could not delete character shortcut: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public void restore()
 	{
 		_shortCuts.clear();
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT charId, slot, page, type, shortcut_id, level FROM character_shortcuts WHERE charId=? AND class_index=?");
 			statement.setInt(1, _owner.getObjectId());
 			statement.setInt(2, _owner.getClassIndex());
@@ -220,10 +204,6 @@ public class ShortCuts
 		{
 			_log.log(Level.WARNING, "Could not restore character shortcuts: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
 		// Verify shortcuts
 		for (L2ShortCut sc : getAllShortCuts())

Diferenças do arquivo suprimidas por serem muito extensas
+ 98 - 351
L2J_Server_BETA/java/com/l2jserver/gameserver/model/actor/instance/L2PcInstance.java


+ 40 - 76
L2J_Server_BETA/java/com/l2jserver/gameserver/model/actor/instance/L2PetInstance.java

@@ -771,23 +771,16 @@ public class L2PetInstance extends L2Summon
 		}
 		
 		// pet control item no longer exists, delete the pet from the db
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("DELETE FROM pets WHERE item_obj_id = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("DELETE FROM pets WHERE item_obj_id=?");
 			statement.setInt(1, getControlObjectId());
 			statement.execute();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_logPet.log(Level.SEVERE, "Failed to delete Pet [ObjectId: " + getObjectId() + "]", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public void dropAllItems()
@@ -832,11 +825,9 @@ public class L2PetInstance extends L2Summon
 	
 	private static L2PetInstance restore(L2ItemInstance control, L2NpcTemplate template, L2PcInstance owner)
 	{
-		Connection con = null;
-		try
+		try  (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
 			L2PetInstance pet;
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT item_obj_id, name, level, curHp, curMp, exp, sp, fed FROM pets WHERE item_obj_id=?");
 			statement.setInt(1, control.getObjectId());
 			ResultSet rset = statement.executeQuery();
@@ -889,12 +880,8 @@ public class L2PetInstance extends L2Summon
 		catch (Exception e)
 		{
 			_logPet.log(Level.WARNING, "Could not restore pet data for owner: " + owner + " - " + e.getMessage(), e);
-			return null;
-		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
 		}
+		return null;
 	}
 	
 	@Override
@@ -935,10 +922,9 @@ public class L2PetInstance extends L2Summon
 			req = "INSERT INTO pets (name,level,curHp,curMp,exp,sp,fed,ownerId,restore,item_obj_id) " + "VALUES (?,?,?,?,?,?,?,?,?,?)";
 		else
 			req = "UPDATE pets SET name=?,level=?,curHp=?,curMp=?,exp=?,sp=?,fed=?,ownerId=?,restore=? " + "WHERE item_obj_id = ?";
-		Connection con = null;
-		try
+		
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement(req);
 			statement.setString(1, getName());
 			statement.setInt(2, getStat().getLevel());
@@ -964,10 +950,6 @@ public class L2PetInstance extends L2Summon
 		{
 			_logPet.log(Level.SEVERE, "Failed to store Pet [ObjectId: " + getObjectId() + "] data", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
 		L2ItemInstance itemInst = getControlItem();
 		if (itemInst != null && itemInst.getEnchantLevel() != getStat().getLevel())
@@ -987,25 +969,19 @@ public class L2PetInstance extends L2Summon
 		if (SummonEffectsTable.getInstance().getPetEffects().contains(getControlObjectId()))
 			SummonEffectsTable.getInstance().getPetEffects().get(getControlObjectId()).clear();
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps1 = con.prepareStatement(DELETE_SKILL_SAVE);
+			PreparedStatement ps2 = con.prepareStatement(ADD_SKILL_SAVE))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			// Delete all current stored effects for summon to avoid dupe
-			PreparedStatement statement = con.prepareStatement(DELETE_SKILL_SAVE);
-			
-			statement.setInt(1, getControlObjectId());
-			statement.execute();
-			statement.close();
+			ps1.setInt(1, getControlObjectId());
+			ps1.execute();
 			
 			int buff_index = 0;
 			
 			final List<Integer> storedSkills = new FastList<>();
 			
 			// Store all effect data along with calculated remaining
-			statement = con.prepareStatement(ADD_SKILL_SAVE);
-			
 			if (storeEffects)
 			{
 				for (L2Effect effect : getAllEffects())
@@ -1030,13 +1006,13 @@ public class L2PetInstance extends L2Summon
 					
 					if (!effect.isHerbEffect() && effect.getInUse() && !skill.isToggle())
 					{
-						statement.setInt(1, getControlObjectId());
-						statement.setInt(2, skill.getId());
-						statement.setInt(3, skill.getLevel());
-						statement.setInt(4, effect.getCount());
-						statement.setInt(5, effect.getTime());
-						statement.setInt(6, ++buff_index);
-						statement.execute();
+						ps2.setInt(1, getControlObjectId());
+						ps2.setInt(2, skill.getId());
+						ps2.setInt(3, skill.getLevel());
+						ps2.setInt(4, effect.getCount());
+						ps2.setInt(5, effect.getTime());
+						ps2.setInt(6, ++buff_index);
+						ps2.execute();
 						
 						if (!SummonEffectsTable.getInstance().getPetEffects().contains(getControlObjectId()))
 							SummonEffectsTable.getInstance().getPetEffects().put(getControlObjectId(), new FastList<SummonEffect>());
@@ -1044,59 +1020,49 @@ public class L2PetInstance extends L2Summon
 						SummonEffectsTable.getInstance().getPetEffects().get(getControlObjectId()).add(SummonEffectsTable.getInstance().new SummonEffect(skill, effect.getCount(), effect.getTime()));
 					}
 				}
-				statement.close();
 			}
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Could not store pet effect data: ", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	@Override
 	public void restoreEffects()
 	{
-		Connection con = null;
-		PreparedStatement statement = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps1 = con.prepareStatement(RESTORE_SKILL_SAVE);
+			PreparedStatement ps2 = con.prepareStatement(DELETE_SKILL_SAVE))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			if (!SummonEffectsTable.getInstance().getPetEffects().contains(getControlObjectId()))
 			{
-				statement = con.prepareStatement(RESTORE_SKILL_SAVE);
-				statement.setInt(1, getControlObjectId());
-				ResultSet rset = statement.executeQuery();
 				
-				while (rset.next())
+				ps1.setInt(1, getControlObjectId());
+				try (ResultSet rset = ps1.executeQuery())
 				{
-					int effectCount = rset.getInt("effect_count");
-					int effectCurTime = rset.getInt("effect_cur_time");
-					
-					final L2Skill skill = SkillTable.getInstance().getInfo(rset.getInt("skill_id"), rset.getInt("skill_level"));
-					if (skill == null)
-						continue;
-					
-					if (skill.hasEffects())
+					while (rset.next())
 					{
-						if (!SummonEffectsTable.getInstance().getPetEffects().contains(getControlObjectId()))
-							SummonEffectsTable.getInstance().getPetEffects().put(getControlObjectId(), new FastList<SummonEffect>());
+						int effectCount = rset.getInt("effect_count");
+						int effectCurTime = rset.getInt("effect_cur_time");
 						
-						SummonEffectsTable.getInstance().getPetEffects().get(getControlObjectId()).add(SummonEffectsTable.getInstance().new SummonEffect(skill, effectCount, effectCurTime));
+						final L2Skill skill = SkillTable.getInstance().getInfo(rset.getInt("skill_id"), rset.getInt("skill_level"));
+						if (skill == null)
+							continue;
+						
+						if (skill.hasEffects())
+						{
+							if (!SummonEffectsTable.getInstance().getPetEffects().contains(getControlObjectId()))
+								SummonEffectsTable.getInstance().getPetEffects().put(getControlObjectId(), new FastList<SummonEffect>());
+							
+							SummonEffectsTable.getInstance().getPetEffects().get(getControlObjectId()).add(SummonEffectsTable.getInstance().new SummonEffect(skill, effectCount, effectCurTime));
+						}
 					}
 				}
-				
-				rset.close();
-				statement.close();
 			}
-			statement = con.prepareStatement(DELETE_SKILL_SAVE);
-			statement.setInt(1, getControlObjectId());
-			statement.executeUpdate();
-			statement.close();
+			
+			ps2.setInt(1, getControlObjectId());
+			ps2.executeUpdate();
 		}
 		catch (Exception e)
 		{
@@ -1104,8 +1070,6 @@ public class L2PetInstance extends L2Summon
 		}
 		finally
 		{
-			L2DatabaseFactory.close(con);
-			
 			if (SummonEffectsTable.getInstance().getPetEffects().get(getControlObjectId()) == null)
 				return;
 			

+ 75 - 89
L2J_Server_BETA/java/com/l2jserver/gameserver/model/actor/instance/L2ServitorInstance.java

@@ -326,84 +326,73 @@ public class L2ServitorInstance extends L2Summon
 			)
 			SummonEffectsTable.getInstance().getServitorEffects(getOwner()).get(getReferenceSkill()).clear();
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement(DELETE_SKILL_SAVE))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			// Delete all current stored effects for summon to avoid dupe
-			PreparedStatement statement = con.prepareStatement(DELETE_SKILL_SAVE);
-			
 			statement.setInt(1, getOwner().getObjectId());
 			statement.setInt(2, getOwner().getClassIndex());
 			statement.setInt(3, getReferenceSkill());
-			
 			statement.execute();
-			statement.close();
 			
 			int buff_index = 0;
 			
 			final List<Integer> storedSkills = new FastList<>();
 			
 			//Store all effect data along with calculated remaining
-			statement = con.prepareStatement(ADD_SKILL_SAVE);
-			
 			if (storeEffects)
 			{
-				for (L2Effect effect : getAllEffects())
+				try (PreparedStatement ps2 = con.prepareStatement(ADD_SKILL_SAVE))
 				{
-					if (effect == null)
-						continue;
-					
-					switch (effect.getEffectType())
+					for (L2Effect effect : getAllEffects())
 					{
-						case HEAL_OVER_TIME:
-						case CPHEAL_OVER_TIME:
-							// TODO: Fix me.
-						case HIDE:
+						if (effect == null)
 							continue;
-					}
-					
-					L2Skill skill = effect.getSkill();
-					if (storedSkills.contains(skill.getReuseHashCode()))
-						continue;
-					
-					storedSkills.add(skill.getReuseHashCode());
-					
-					if (!effect.isHerbEffect() && effect.getInUse() && !skill.isToggle())
-					{
-						statement.setInt(1, getOwner().getObjectId());
-						statement.setInt(2, getOwner().getClassIndex());
-						statement.setInt(3, getReferenceSkill());
-						statement.setInt(4, skill.getId());
-						statement.setInt(5, skill.getLevel());
-						statement.setInt(6, effect.getCount());
-						statement.setInt(7, effect.getTime());
-						statement.setInt(8, ++buff_index);
-						statement.execute();
 						
-						if (!SummonEffectsTable.getInstance().getServitorEffectsOwner().contains(getOwner().getObjectId())) // Check if charId exists in map
-							SummonEffectsTable.getInstance().getServitorEffectsOwner().put(getOwner().getObjectId(), new TIntObjectHashMap<TIntObjectHashMap<List<SummonEffect>>>());
-						if (!SummonEffectsTable.getInstance().getServitorEffectsOwner().get(getOwner().getObjectId()).contains(getOwner().getClassIndex())) // Check if classIndex exists in charId map
-							SummonEffectsTable.getInstance().getServitorEffectsOwner().get(getOwner().getObjectId()).put(getOwner().getClassIndex(), new TIntObjectHashMap<List<SummonEffect>>());
-						if (!SummonEffectsTable.getInstance().getServitorEffects(getOwner()).contains(getReferenceSkill())) // Check is summonSkillId exists in charId+classIndex map
-							SummonEffectsTable.getInstance().getServitorEffects(getOwner()).put(getReferenceSkill(), new FastList<SummonEffect>());
-
-						SummonEffectsTable.getInstance().getServitorEffects(getOwner()).get(getReferenceSkill()).add(SummonEffectsTable.getInstance().new SummonEffect(skill, effect.getCount(), effect.getTime()));
-
+						switch (effect.getEffectType())
+						{
+							case HEAL_OVER_TIME:
+							case CPHEAL_OVER_TIME:
+								// TODO: Fix me.
+							case HIDE:
+								continue;
+						}
+						
+						L2Skill skill = effect.getSkill();
+						if (storedSkills.contains(skill.getReuseHashCode()))
+							continue;
+						
+						storedSkills.add(skill.getReuseHashCode());
+						
+						if (!effect.isHerbEffect() && effect.getInUse() && !skill.isToggle())
+						{
+							ps2.setInt(1, getOwner().getObjectId());
+							ps2.setInt(2, getOwner().getClassIndex());
+							ps2.setInt(3, getReferenceSkill());
+							ps2.setInt(4, skill.getId());
+							ps2.setInt(5, skill.getLevel());
+							ps2.setInt(6, effect.getCount());
+							ps2.setInt(7, effect.getTime());
+							ps2.setInt(8, ++buff_index);
+							ps2.execute();
+							
+							if (!SummonEffectsTable.getInstance().getServitorEffectsOwner().contains(getOwner().getObjectId())) // Check if charId exists in map
+								SummonEffectsTable.getInstance().getServitorEffectsOwner().put(getOwner().getObjectId(), new TIntObjectHashMap<TIntObjectHashMap<List<SummonEffect>>>());
+							if (!SummonEffectsTable.getInstance().getServitorEffectsOwner().get(getOwner().getObjectId()).contains(getOwner().getClassIndex())) // Check if classIndex exists in charId map
+								SummonEffectsTable.getInstance().getServitorEffectsOwner().get(getOwner().getObjectId()).put(getOwner().getClassIndex(), new TIntObjectHashMap<List<SummonEffect>>());
+							if (!SummonEffectsTable.getInstance().getServitorEffects(getOwner()).contains(getReferenceSkill())) // Check is summonSkillId exists in charId+classIndex map
+								SummonEffectsTable.getInstance().getServitorEffects(getOwner()).put(getReferenceSkill(), new FastList<SummonEffect>());
+	
+							SummonEffectsTable.getInstance().getServitorEffects(getOwner()).get(getReferenceSkill()).add(SummonEffectsTable.getInstance().new SummonEffect(skill, effect.getCount(), effect.getTime()));
+						}
 					}
 				}
-				statement.close();
 			}
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Could not store summon effect data: ", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	@Override
@@ -412,55 +401,53 @@ public class L2ServitorInstance extends L2Summon
 		if (getOwner().isInOlympiadMode())
 			return;
 		
-		Connection con = null;
-		PreparedStatement statement = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			if (
 					!SummonEffectsTable.getInstance().getServitorEffectsOwner().contains(getOwner().getObjectId()) ||
 					!SummonEffectsTable.getInstance().getServitorEffectsOwner().get(getOwner().getObjectId()).contains(getOwner().getClassIndex()) ||
 					!SummonEffectsTable.getInstance().getServitorEffects(getOwner()).contains(getReferenceSkill())
 				)
 			{
-				statement = con.prepareStatement(RESTORE_SKILL_SAVE);
-				statement.setInt(1, getOwner().getObjectId());
-				statement.setInt(2, getOwner().getClassIndex());
-				statement.setInt(3, getReferenceSkill());
-				ResultSet rset = statement.executeQuery();
-				
-				while (rset.next())
+				try (PreparedStatement statement = con.prepareStatement(RESTORE_SKILL_SAVE))
 				{
-					int effectCount = rset.getInt("effect_count");
-					int effectCurTime = rset.getInt("effect_cur_time");
-					
-					final L2Skill skill = SkillTable.getInstance().getInfo(rset.getInt("skill_id"), rset.getInt("skill_level"));
-					if (skill == null)
-						continue;
-					
-					if (skill.hasEffects())
+					statement.setInt(1, getOwner().getObjectId());
+					statement.setInt(2, getOwner().getClassIndex());
+					statement.setInt(3, getReferenceSkill());
+					try (ResultSet rset = statement.executeQuery())
 					{
-						if (!SummonEffectsTable.getInstance().getServitorEffectsOwner().contains(getOwner().getObjectId())) // Check if charId exists in map
-							SummonEffectsTable.getInstance().getServitorEffectsOwner().put(getOwner().getObjectId(), new TIntObjectHashMap<TIntObjectHashMap<List<SummonEffect>>>());
-						if (!SummonEffectsTable.getInstance().getServitorEffectsOwner().get(getOwner().getObjectId()).contains(getOwner().getClassIndex())) // Check if classIndex exists in charId map
-							SummonEffectsTable.getInstance().getServitorEffectsOwner().get(getOwner().getObjectId()).put(getOwner().getClassIndex(), new TIntObjectHashMap<List<SummonEffect>>());
-						if (!SummonEffectsTable.getInstance().getServitorEffects(getOwner()).contains(getReferenceSkill())) // Check is summonSkillId exists in charId+classIndex map
-							SummonEffectsTable.getInstance().getServitorEffects(getOwner()).put(getReferenceSkill(), new FastList<SummonEffect>());
-						
-						SummonEffectsTable.getInstance().getServitorEffects(getOwner()).get(getReferenceSkill()).add(SummonEffectsTable.getInstance().new SummonEffect(skill, effectCount, effectCurTime));
+						while (rset.next())
+						{
+							int effectCount = rset.getInt("effect_count");
+							int effectCurTime = rset.getInt("effect_cur_time");
+							
+							final L2Skill skill = SkillTable.getInstance().getInfo(rset.getInt("skill_id"), rset.getInt("skill_level"));
+							if (skill == null)
+								continue;
+							
+							if (skill.hasEffects())
+							{
+								if (!SummonEffectsTable.getInstance().getServitorEffectsOwner().contains(getOwner().getObjectId())) // Check if charId exists in map
+									SummonEffectsTable.getInstance().getServitorEffectsOwner().put(getOwner().getObjectId(), new TIntObjectHashMap<TIntObjectHashMap<List<SummonEffect>>>());
+								if (!SummonEffectsTable.getInstance().getServitorEffectsOwner().get(getOwner().getObjectId()).contains(getOwner().getClassIndex())) // Check if classIndex exists in charId map
+									SummonEffectsTable.getInstance().getServitorEffectsOwner().get(getOwner().getObjectId()).put(getOwner().getClassIndex(), new TIntObjectHashMap<List<SummonEffect>>());
+								if (!SummonEffectsTable.getInstance().getServitorEffects(getOwner()).contains(getReferenceSkill())) // Check is summonSkillId exists in charId+classIndex map
+									SummonEffectsTable.getInstance().getServitorEffects(getOwner()).put(getReferenceSkill(), new FastList<SummonEffect>());
+								
+								SummonEffectsTable.getInstance().getServitorEffects(getOwner()).get(getReferenceSkill()).add(SummonEffectsTable.getInstance().new SummonEffect(skill, effectCount, effectCurTime));
+							}
+						}
 					}
 				}
-				
-				rset.close();
-				statement.close();
 			}
 			
-			statement = con.prepareStatement(DELETE_SKILL_SAVE);
-			statement.setInt(1, getOwner().getObjectId());
-			statement.setInt(2, getOwner().getClassIndex());
-			statement.setInt(3, getReferenceSkill());
-			statement.executeUpdate();
-			statement.close();
+			try (PreparedStatement statement = con.prepareStatement(DELETE_SKILL_SAVE))
+			{
+				statement.setInt(1, getOwner().getObjectId());
+				statement.setInt(2, getOwner().getClassIndex());
+				statement.setInt(3, getReferenceSkill());
+				statement.executeUpdate();
+			}
 		}
 		catch (Exception e)
 		{
@@ -468,7 +455,6 @@ public class L2ServitorInstance extends L2Summon
 		}
 		finally
 		{
-			L2DatabaseFactory.close(con);
 			if (
 					!SummonEffectsTable.getInstance().getServitorEffectsOwner().contains(getOwner().getObjectId()) ||
 					!SummonEffectsTable.getInstance().getServitorEffectsOwner().get(getOwner().getObjectId()).contains(getOwner().getClassIndex()) ||

+ 61 - 120
L2J_Server_BETA/java/com/l2jserver/gameserver/model/entity/Auction.java

@@ -165,40 +165,32 @@ public class Auction
 	/** Load auctions */
 	private void load()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("Select * from auction where id = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
-			PreparedStatement statement = con.prepareStatement("Select * from auction where id = ?");
 			statement.setInt(1, getId());
-			ResultSet rs = statement.executeQuery();
-			
-			while (rs.next())
+			try (ResultSet rs = statement.executeQuery())
 			{
-				_currentBid = rs.getLong("currentBid");
-				_endDate = rs.getLong("endDate");
-				_itemId = rs.getInt("itemId");
-				_itemName = rs.getString("itemName");
-				_itemObjectId = rs.getInt("itemObjectId");
-				_itemType = rs.getString("itemType");
-				_sellerId = rs.getInt("sellerId");
-				_sellerClanName = rs.getString("sellerClanName");
-				_sellerName = rs.getString("sellerName");
-				_startingBid = rs.getLong("startingBid");
+				while (rs.next())
+				{
+					_currentBid = rs.getLong("currentBid");
+					_endDate = rs.getLong("endDate");
+					_itemId = rs.getInt("itemId");
+					_itemName = rs.getString("itemName");
+					_itemObjectId = rs.getInt("itemObjectId");
+					_itemType = rs.getString("itemType");
+					_sellerId = rs.getInt("sellerId");
+					_sellerClanName = rs.getString("sellerClanName");
+					_sellerName = rs.getString("sellerName");
+					_startingBid = rs.getLong("startingBid");
+				}
 			}
-			rs.close();
-			statement.close();
 			loadBid();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Exception: Auction.load(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/** Load bidders **/
@@ -208,36 +200,28 @@ public class Auction
 		_highestBidderName = "";
 		_highestBidderMaxBid = 0;
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("SELECT bidderId, bidderName, maxBid, clan_name, time_bid FROM auction_bid WHERE auctionId = ? ORDER BY maxBid DESC"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
-			PreparedStatement statement = con.prepareStatement("SELECT bidderId, bidderName, maxBid, clan_name, time_bid FROM auction_bid WHERE auctionId = ? ORDER BY maxBid DESC");
 			statement.setInt(1, getId());
-			ResultSet rs = statement.executeQuery();
-			
-			while (rs.next())
+			try (ResultSet rs = statement.executeQuery())
 			{
-				if (rs.isFirst())
+				while (rs.next())
 				{
-					_highestBidderId = rs.getInt("bidderId");
-					_highestBidderName = rs.getString("bidderName");
-					_highestBidderMaxBid = rs.getLong("maxBid");
+					if (rs.isFirst())
+					{
+						_highestBidderId = rs.getInt("bidderId");
+						_highestBidderName = rs.getString("bidderName");
+						_highestBidderMaxBid = rs.getLong("maxBid");
+					}
+					_bidders.put(rs.getInt("bidderId"), new Bidder(rs.getString("bidderName"), rs.getString("clan_name"), rs.getLong("maxBid"), rs.getLong("time_bid")));
 				}
-				_bidders.put(rs.getInt("bidderId"), new Bidder(rs.getString("bidderName"), rs.getString("clan_name"), rs.getLong("maxBid"), rs.getLong("time_bid")));
 			}
-			rs.close();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Exception: Auction.loadBid(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/** Task Manage */
@@ -263,25 +247,17 @@ public class Auction
 	/** Save Auction Data End */
 	private void saveAuctionDate()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("Update auction set endDate = ? where id = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("Update auction set endDate = ? where id = ?");
 			statement.setLong(1, _endDate);
 			statement.setInt(2, _id);
 			statement.execute();
-			
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, "Exception: saveAuctionDate(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -349,36 +325,37 @@ public class Auction
 	 */
 	private void updateInDB(L2PcInstance bidder, long bid)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement;
 			if (getBidders().get(bidder.getClanId()) != null)
 			{
-				statement = con.prepareStatement("UPDATE auction_bid SET bidderId=?, bidderName=?, maxBid=?, time_bid=? WHERE auctionId=? AND bidderId=?");
-				statement.setInt(1, bidder.getClanId());
-				statement.setString(2, bidder.getClan().getLeaderName());
-				statement.setLong(3, bid);
-				statement.setLong(4, System.currentTimeMillis());
-				statement.setInt(5, getId());
-				statement.setInt(6, bidder.getClanId());
+				try (PreparedStatement statement = con.prepareStatement("UPDATE auction_bid SET bidderId=?, bidderName=?, maxBid=?, time_bid=? WHERE auctionId=? AND bidderId=?"))
+				{
+					statement.setInt(1, bidder.getClanId());
+					statement.setString(2, bidder.getClan().getLeaderName());
+					statement.setLong(3, bid);
+					statement.setLong(4, System.currentTimeMillis());
+					statement.setInt(5, getId());
+					statement.setInt(6, bidder.getClanId());
+					statement.execute();
+				}
 			}
 			else
 			{
-				statement = con.prepareStatement("INSERT INTO auction_bid (id, auctionId, bidderId, bidderName, maxBid, clan_name, time_bid) VALUES (?, ?, ?, ?, ?, ?, ?)");
-				statement.setInt(1, IdFactory.getInstance().getNextId());
-				statement.setInt(2, getId());
-				statement.setInt(3, bidder.getClanId());
-				statement.setString(4, bidder.getName());
-				statement.setLong(5, bid);
-				statement.setString(6, bidder.getClan().getName());
-				statement.setLong(7, System.currentTimeMillis());
+				try (PreparedStatement statement = con.prepareStatement("INSERT INTO auction_bid (id, auctionId, bidderId, bidderName, maxBid, clan_name, time_bid) VALUES (?, ?, ?, ?, ?, ?, ?)"))
+				{
+					statement.setInt(1, IdFactory.getInstance().getNextId());
+					statement.setInt(2, getId());
+					statement.setInt(3, bidder.getClanId());
+					statement.setString(4, bidder.getName());
+					statement.setLong(5, bid);
+					statement.setString(6, bidder.getClan().getName());
+					statement.setLong(7, System.currentTimeMillis());
+					statement.execute();
+				}
 				if (L2World.getInstance().getPlayer(_highestBidderName) != null)
 					L2World.getInstance().getPlayer(_highestBidderName).sendMessage("You have been out bidded");
 			}
-			statement.execute();
-			statement.close();
 			
 			_highestBidderId = bidder.getClanId();
 			_highestBidderMaxBid = bid;
@@ -396,33 +373,22 @@ public class Auction
 		{
 			_log.log(Level.SEVERE, "Exception: Auction.updateInDB(L2PcInstance bidder, int bid): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/** Remove bids */
 	private void removeBids()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("DELETE FROM auction_bid WHERE auctionId=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("DELETE FROM auction_bid WHERE auctionId=?");
 			statement.setInt(1, getId());
 			statement.execute();
-			
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, "Exception: Auction.deleteFromDB(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
+		
 		for (Bidder b : _bidders.values())
 		{
 			if (ClanTable.getInstance().getClanByName(b.getClanName()).getHideoutId() == 0)
@@ -441,23 +407,16 @@ public class Auction
 	public void deleteAuctionFromDB()
 	{
 		AuctionManager.getInstance().getAuctions().remove(this);
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("DELETE FROM auction WHERE itemId=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("DELETE FROM auction WHERE itemId=?");
 			statement.setInt(1, _itemId);
 			statement.execute();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, "Exception: Auction.deleteFromDB(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/** End of auction */
@@ -503,27 +462,18 @@ public class Auction
 	 */
 	public synchronized void cancelBid(int bidder)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("DELETE FROM auction_bid WHERE auctionId=? AND bidderId=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement;
-			
-			statement = con.prepareStatement("DELETE FROM auction_bid WHERE auctionId=? AND bidderId=?");
 			statement.setInt(1, getId());
 			statement.setInt(2, bidder);
 			statement.execute();
-			
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, "Exception: Auction.cancelBid(String bidder): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
+		
 		returnItem(_bidders.get(bidder).getClanName(), _bidders.get(bidder).getBid(), true);
 		ClanTable.getInstance().getClanByName(_bidders.get(bidder).getClanName()).setAuctionBiddedAt(0, true);
 		_bidders.clear();
@@ -541,13 +491,9 @@ public class Auction
 	public void confirmAuction()
 	{
 		AuctionManager.getInstance().getAuctions().add(this);
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("INSERT INTO auction (id, sellerId, sellerName, sellerClanName, itemType, itemId, itemObjectId, itemName, itemQuantity, startingBid, currentBid, endDate) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"))
 		{
-			PreparedStatement statement;
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
-			statement = con.prepareStatement("INSERT INTO auction (id, sellerId, sellerName, sellerClanName, itemType, itemId, itemObjectId, itemName, itemQuantity, startingBid, currentBid, endDate) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)");
 			statement.setInt(1, getId());
 			statement.setInt(2, _sellerId);
 			statement.setString(3, _sellerName);
@@ -562,16 +508,11 @@ public class Auction
 			statement.setLong(12, _endDate);
 			statement.execute();
 			statement.close();
-			loadBid();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, "Exception: Auction.load(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**

+ 84 - 207
L2J_Server_BETA/java/com/l2jserver/gameserver/model/entity/Castle.java

@@ -221,13 +221,9 @@ public class Castle
 		
 		public void dbSave()
 		{
-			Connection con = null;
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+				PreparedStatement statement = con.prepareStatement("REPLACE INTO castle_functions (castle_id, type, lvl, lease, rate, endTime) VALUES (?,?,?,?,?,?)"))
 			{
-				PreparedStatement statement;
-				
-				con = L2DatabaseFactory.getInstance().getConnection();
-				statement = con.prepareStatement("REPLACE INTO castle_functions (castle_id, type, lvl, lease, rate, endTime) VALUES (?,?,?,?,?,?)");
 				statement.setInt(1, getCastleId());
 				statement.setInt(2, getType());
 				statement.setInt(3, getLvl());
@@ -235,16 +231,11 @@ public class Castle
 				statement.setLong(5, getRate());
 				statement.setLong(6, getEndTime());
 				statement.execute();
-				statement.close();
 			}
 			catch (Exception e)
 			{
 				_log.log(Level.SEVERE, "Exception: Castle.updateFunctions(int type, int lvl, int lease, long rate, long time, boolean addNew): " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 		}
 	}
 	
@@ -369,30 +360,22 @@ public class Castle
 				_treasury += amount;
 		}
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("UPDATE castle SET treasury = ? WHERE id = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("UPDATE castle SET treasury = ? WHERE id = ?");
 			statement.setLong(1, getTreasury());
 			statement.setInt(2, getCastleId());
 			statement.execute();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		return true;
 	}
 	
 	/**
-	 * Move non clan members off castle area and to nearest town.<BR>
-	 * <BR>
+	 * Move non clan members off castle area and to nearest town.
 	 */
 	public void banishForeigners()
 	{
@@ -631,29 +614,21 @@ public class Castle
 		_taxPercent = taxPercent;
 		_taxRate = _taxPercent / 100.0;
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("UPDATE castle SET taxPercent = ? WHERE id = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("UPDATE castle SET taxPercent = ? WHERE id = ?");
 			statement.setInt(1, taxPercent);
 			statement.setInt(2, getCastleId());
 			statement.execute();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
-	 * Respawn all doors on castle grounds<BR>
-	 * <BR>
+	 * Respawn all doors on castle grounds.
 	 */
 	public void spawnDoor()
 	{
@@ -699,45 +674,41 @@ public class Castle
 	// This method loads castle
 	private void load()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps1 = con.prepareStatement("SELECT * FROM castle WHERE id = ?");
+			PreparedStatement ps2 = con.prepareStatement("SELECT clan_id FROM clan_data WHERE hasCastle = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
-			PreparedStatement statement = con.prepareStatement("Select * from castle where id = ?");
-			statement.setInt(1, getCastleId());
-			ResultSet rs = statement.executeQuery();
-			
-			while (rs.next())
+			ps1.setInt(1, getCastleId());
+			try (ResultSet rs = ps1.executeQuery())
 			{
-				_name = rs.getString("name");
-				// _OwnerId = rs.getInt("ownerId");
-				
-				_siegeDate = Calendar.getInstance();
-				_siegeDate.setTimeInMillis(rs.getLong("siegeDate"));
-				_siegeTimeRegistrationEndDate = Calendar.getInstance();
-				_siegeTimeRegistrationEndDate.setTimeInMillis(rs.getLong("regTimeEnd"));
-				_isTimeRegistrationOver = rs.getBoolean("regTimeOver");
-				
-				_taxPercent = rs.getInt("taxPercent");
-				_treasury = rs.getLong("treasury");
-				
-				_showNpcCrest = rs.getBoolean("showNpcCrest");
-				
-				_bloodAlliance = rs.getInt("bloodAlliance");
+				while (rs.next())
+				{
+					_name = rs.getString("name");
+					// _OwnerId = rs.getInt("ownerId");
+					
+					_siegeDate = Calendar.getInstance();
+					_siegeDate.setTimeInMillis(rs.getLong("siegeDate"));
+					_siegeTimeRegistrationEndDate = Calendar.getInstance();
+					_siegeTimeRegistrationEndDate.setTimeInMillis(rs.getLong("regTimeEnd"));
+					_isTimeRegistrationOver = rs.getBoolean("regTimeOver");
+					
+					_taxPercent = rs.getInt("taxPercent");
+					_treasury = rs.getLong("treasury");
+					
+					_showNpcCrest = rs.getBoolean("showNpcCrest");
+					
+					_bloodAlliance = rs.getInt("bloodAlliance");
+				}
 			}
-			rs.close();
-			statement.close();
-			
 			_taxRate = _taxPercent / 100.0;
 			
-			statement = con.prepareStatement("Select clan_id from clan_data where hasCastle = ?");
-			statement.setInt(1, getCastleId());
-			rs = statement.executeQuery();
-			
-			while (rs.next())
+			ps2.setInt(1, getCastleId());
+			try (ResultSet rs = ps2.executeQuery())
 			{
-				_ownerId = rs.getInt("clan_id");
+				while (rs.next())
+				{
+					_ownerId = rs.getInt("clan_id");
+				}
 			}
 			
 			if (getOwnerId() > 0)
@@ -745,46 +716,32 @@ public class Castle
 				L2Clan clan = ClanTable.getInstance().getClan(getOwnerId()); // Try to find clan instance
 				ThreadPoolManager.getInstance().scheduleGeneral(new CastleUpdater(clan, 1), 3600000); // Schedule owner tasks to start running
 			}
-			rs.close();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Exception: loadCastleData(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/** Load All Functions */
 	private void loadFunctions()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("SELECT * FROM castle_functions WHERE castle_id = ?"))
 		{
-			PreparedStatement statement;
-			ResultSet rs;
-			con = L2DatabaseFactory.getInstance().getConnection();
-			statement = con.prepareStatement("SELECT * FROM castle_functions WHERE castle_id = ?");
 			statement.setInt(1, getCastleId());
-			rs = statement.executeQuery();
-			while (rs.next())
+			try (ResultSet rs = statement.executeQuery())
 			{
-				_function.put(rs.getInt("type"), new CastleFunction(rs.getInt("type"), rs.getInt("lvl"), rs.getInt("lease"), 0, rs.getLong("rate"), rs.getLong("endTime"), true));
+				while (rs.next())
+				{
+					_function.put(rs.getInt("type"), new CastleFunction(rs.getInt("type"), rs.getInt("lvl"), rs.getInt("lease"), 0, rs.getLong("rate"), rs.getLong("endTime"), true));
+				}
 			}
-			rs.close();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, "Exception: Castle.loadFunctions(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -794,24 +751,17 @@ public class Castle
 	public void removeFunction(int functionType)
 	{
 		_function.remove(functionType);
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("DELETE FROM castle_functions WHERE castle_id=? AND type=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("DELETE FROM castle_functions WHERE castle_id=? AND type=?");
 			statement.setInt(1, getCastleId());
 			statement.setInt(2, functionType);
 			statement.execute();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, "Exception: Castle.removeFunctions(int functionType): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public boolean updateFunctions(L2PcInstance player, int type, int lvl, int lease, long rate, boolean addNew)
@@ -873,14 +823,12 @@ public class Castle
 	// This method loads castle door upgrade data from database
 	private void loadDoorUpgrade()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
 			StringBuilder doorIds = new StringBuilder(100);
 			for (L2DoorInstance door : getDoors())
 				doorIds.append(door.getDoorId()).append(',');
 			doorIds.deleteCharAt(doorIds.length()-1);
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("Select * from castle_doorupgrade where doorId in ("+doorIds.toString()+")");
 			ResultSet rs = statement.executeQuery();
 			
@@ -895,22 +843,16 @@ public class Castle
 		{
 			_log.log(Level.WARNING, "Exception: loadCastleDoorUpgrade(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void removeDoorUpgrade()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
 			StringBuilder doorIds = new StringBuilder(100);
 			for (L2DoorInstance door : getDoors())
 				doorIds.append(door.getDoorId()).append(',');
 			doorIds.deleteCharAt(doorIds.length()-1);
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("delete from castle_doorupgrade where doorId in ("+doorIds.toString()+")");
 			statement.execute();
 			statement.close();
@@ -919,18 +861,12 @@ public class Castle
 		{
 			_log.log(Level.WARNING, "Exception: removeDoorUpgrade(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void saveDoorUpgrade(int doorId, int hp, int pDef, int mDef)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("INSERT INTO castle_doorupgrade (doorId, hp, pDef, mDef) values (?,?,?,?)");
 			statement.setInt(1, doorId);
 			statement.setInt(2, hp);
@@ -943,10 +879,6 @@ public class Castle
 		{
 			_log.log(Level.WARNING, "Exception: saveDoorUpgrade(int doorId, int hp, int pDef, int mDef): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void updateOwnerInDB(L2Clan clan)
@@ -959,10 +891,8 @@ public class Castle
 			resetManor();
 		}
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			// NEED TO REMOVE HAS CASTLE FLAG FROM CLAN_DATA
 			// SHOULD BE CHECKED FROM CASTLE TABLE
 			PreparedStatement statement = con.prepareStatement("UPDATE clan_data SET hasCastle = 0 WHERE hasCastle = ?");
@@ -989,10 +919,6 @@ public class Castle
 		{
 			_log.log(Level.WARNING, "Exception: updateOwnerInDB(L2Clan clan): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public final int getCastleId()
@@ -1176,16 +1102,13 @@ public class Castle
 	// save manor production data
 	public void saveSeedData()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
-			PreparedStatement statement = con.prepareStatement(CASTLE_MANOR_DELETE_PRODUCTION);
-			statement.setInt(1, getCastleId());
-			
-			statement.execute();
-			statement.close();
+			try (PreparedStatement ps1 = con.prepareStatement(CASTLE_MANOR_DELETE_PRODUCTION))
+			{
+				ps1.setInt(1, getCastleId());
+				ps1.execute();
+			}
 			
 			if (_production != null)
 			{
@@ -1205,9 +1128,10 @@ public class Castle
 						query.append(',');
 						query.append(values[i]);
 					}
-					statement = con.prepareStatement(query.toString());
-					statement.execute();
-					statement.close();
+					try (PreparedStatement ps2 = con.prepareStatement(query.toString()))
+					{
+						ps2.execute();
+					}
 				}
 			}
 			
@@ -1227,9 +1151,10 @@ public class Castle
 					{
 						query += "," + values[i];
 					}
-					statement = con.prepareStatement(query);
-					statement.execute();
-					statement.close();
+					try (PreparedStatement ps3 = con.prepareStatement(query))
+					{
+						ps3.execute();
+					}
 				}
 			}
 		}
@@ -1237,20 +1162,13 @@ public class Castle
 		{
 			_log.info("Error adding seed production data for castle " + getName() + ": " + e.getMessage());
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	// save manor production data for specified period
 	public void saveSeedData(int period)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			PreparedStatement statement = con.prepareStatement(CASTLE_MANOR_DELETE_PRODUCTION_PERIOD);
 			statement.setInt(1, getCastleId());
 			statement.setInt(2, period);
@@ -1287,24 +1205,19 @@ public class Castle
 		{
 			_log.info("Error adding seed production data for castle " + getName() + ": " + e.getMessage());
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	// save crop procure data
 	public void saveCropData()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
+			try (PreparedStatement ps1 = con.prepareStatement(CASTLE_MANOR_DELETE_PROCURE))
+			{
+				ps1.setInt(1, getCastleId());
+				ps1.execute();
+			}
 			
-			PreparedStatement statement = con.prepareStatement(CASTLE_MANOR_DELETE_PROCURE);
-			statement.setInt(1, getCastleId());
-			statement.execute();
-			statement.close();
 			if (!_procure.isEmpty())
 			{
 				int count = 0;
@@ -1323,9 +1236,10 @@ public class Castle
 						query.append(',');
 						query.append(values[i]);
 					}
-					statement = con.prepareStatement(query.toString());
-					statement.execute();
-					statement.close();
+					try (PreparedStatement ps2 = con.prepareStatement(query.toString()))
+					{
+						ps2.execute();
+					}
 				}
 			}
 			if (!_procureNext.isEmpty())
@@ -1344,9 +1258,10 @@ public class Castle
 					{
 						query += "," + values[i];
 					}
-					statement = con.prepareStatement(query);
-					statement.execute();
-					statement.close();
+					try (PreparedStatement ps3 = con.prepareStatement(query))
+					{
+						ps3.execute();
+					}
 				}
 			}
 		}
@@ -1354,20 +1269,13 @@ public class Castle
 		{
 			_log.info("Error adding crop data for castle " + getName() + ": " + e.getMessage());
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	// save crop procure data for specified period
 	public void saveCropData(int period)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			PreparedStatement statement = con.prepareStatement(CASTLE_MANOR_DELETE_PROCURE_PERIOD);
 			statement.setInt(1, getCastleId());
 			statement.setInt(2, period);
@@ -1406,19 +1314,12 @@ public class Castle
 		{
 			_log.info("Error adding crop data for castle " + getName() + ": " + e.getMessage());
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public void updateCrop(int cropId, long amount, int period)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			PreparedStatement statement = con.prepareStatement(CASTLE_UPDATE_CROP);
 			statement.setLong(1, amount);
 			statement.setInt(2, cropId);
@@ -1431,19 +1332,12 @@ public class Castle
 		{
 			_log.info("Error adding crop data for castle " + getName() + ": " + e.getMessage());
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public void updateSeed(int seedId, long amount, int period)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			PreparedStatement statement = con.prepareStatement(CASTLE_UPDATE_SEED);
 			statement.setLong(1, amount);
 			statement.setInt(2, seedId);
@@ -1456,10 +1350,6 @@ public class Castle
 		{
 			_log.info("Error adding seed production data for castle " + getName() + ": " + e.getMessage());
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public boolean isNextPeriodApproved()
@@ -1499,11 +1389,8 @@ public class Castle
 	
 	public void updateShowNpcCrest()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			PreparedStatement statement = con.prepareStatement("UPDATE castle SET showNpcCrest = ? WHERE id = ?");
 			statement.setString(1, String.valueOf(getShowNpcCrest()));
 			statement.setInt(2, getCastleId());
@@ -1514,10 +1401,6 @@ public class Castle
 		{
 			_log.info("Error saving showNpcCrest for castle " + getName() + ": " + e.getMessage());
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public List<L2Skill> getResidentialSkills()
@@ -1618,10 +1501,8 @@ public class Castle
 	{
 		_bloodAlliance = count;
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("UPDATE castle SET bloodAlliance = ? WHERE id = ?");
 			statement.setInt(1, _bloodAlliance);
 			statement.setInt(2, getCastleId());
@@ -1632,10 +1513,6 @@ public class Castle
 		{
 			_log.log(Level.WARNING, e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	@Override

+ 4 - 24
L2J_Server_BETA/java/com/l2jserver/gameserver/model/entity/ClanHall.java

@@ -176,13 +176,9 @@ public abstract class ClanHall
 		
 		public void dbSave()
 		{
-			Connection con = null;
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 			{
-				PreparedStatement statement;
-				
-				con = L2DatabaseFactory.getInstance().getConnection();
-				statement = con.prepareStatement("REPLACE INTO clanhall_functions (hall_id, type, lvl, lease, rate, endTime) VALUES (?,?,?,?,?,?)");
+				PreparedStatement statement = con.prepareStatement("REPLACE INTO clanhall_functions (hall_id, type, lvl, lease, rate, endTime) VALUES (?,?,?,?,?,?)");
 				statement.setInt(1, getId());
 				statement.setInt(2, getType());
 				statement.setInt(3, getLvl());
@@ -197,10 +193,6 @@ public abstract class ClanHall
 				_log.log(Level.SEVERE, "Exception: ClanHall.updateFunctions(int type, int lvl, int lease, long rate, long time, boolean addNew): "
 						+ e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 		}
 	}
 	
@@ -415,10 +407,8 @@ public abstract class ClanHall
 	/** Load All Functions */
 	protected void loadFunctions()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("Select * from clanhall_functions where hall_id = ?");
 			statement.setInt(1, getId());
 			ResultSet rs = statement.executeQuery();
@@ -433,10 +423,6 @@ public abstract class ClanHall
 		{
 			_log.log(Level.SEVERE, "Exception: ClanHall.loadFunctions(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -446,10 +432,8 @@ public abstract class ClanHall
 	public void removeFunction(int functionType)
 	{
 		_functions.remove(functionType);
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("DELETE FROM clanhall_functions WHERE hall_id=? AND type=?");
 			statement.setInt(1, getId());
 			statement.setInt(2, functionType);
@@ -460,10 +444,6 @@ public abstract class ClanHall
 		{
 			_log.log(Level.SEVERE, "Exception: ClanHall.removeFunctions(int functionType): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public boolean updateFunctions(L2PcInstance player, int type, int lvl, int lease, long rate, boolean addNew)

+ 4 - 30
L2J_Server_BETA/java/com/l2jserver/gameserver/model/entity/Couple.java

@@ -43,14 +43,10 @@ public class Couple
 	{
 		_Id = coupleId;
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
 			PreparedStatement statement;
 			ResultSet rs;
-			
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			statement = con.prepareStatement("SELECT * FROM mods_wedding WHERE id = ?");
 			statement.setInt(1, _Id);
 			rs = statement.executeQuery();
@@ -74,10 +70,6 @@ public class Couple
 		{
 			_log.log(Level.SEVERE, "Exception: Couple.load(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public Couple(L2PcInstance player1, L2PcInstance player2)
@@ -94,10 +86,8 @@ public class Couple
 		_weddingDate = Calendar.getInstance();
 		_weddingDate.setTimeInMillis(Calendar.getInstance().getTimeInMillis());
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement;
 			_Id = IdFactory.getInstance().getNextId();
 			statement = con.prepareStatement("INSERT INTO mods_wedding (id, player1Id, player2Id, married, affianceDate, weddingDate) VALUES (?, ?, ?, ?, ?, ?)");
@@ -114,18 +104,12 @@ public class Couple
 		{
 			_log.log(Level.SEVERE, "Could not create couple: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public void marry()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("UPDATE mods_wedding set married = ?, weddingDate = ? where id = ?");
 			statement.setBoolean(1, true);
 			_weddingDate = Calendar.getInstance();
@@ -139,18 +123,12 @@ public class Couple
 		{
 			_log.log(Level.SEVERE, "Could not marry: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public void divorce()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("DELETE FROM mods_wedding WHERE id=?");
 			statement.setInt(1, _Id);
 			statement.execute();
@@ -160,10 +138,6 @@ public class Couple
 		{
 			_log.log(Level.SEVERE, "Exception: Couple.divorce(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public final int getId()

+ 15 - 104
L2J_Server_BETA/java/com/l2jserver/gameserver/model/entity/Fort.java

@@ -215,13 +215,9 @@ public class Fort
 		
 		public void dbSave()
 		{
-			Connection con = null;
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 			{
-				PreparedStatement statement;
-				
-				con = L2DatabaseFactory.getInstance().getConnection();
-				statement = con.prepareStatement("REPLACE INTO fort_functions (fort_id, type, lvl, lease, rate, endTime) VALUES (?,?,?,?,?,?)");
+				PreparedStatement statement = con.prepareStatement("REPLACE INTO fort_functions (fort_id, type, lvl, lease, rate, endTime) VALUES (?,?,?,?,?,?)");
 				statement.setInt(1, getFortId());
 				statement.setInt(2, getType());
 				statement.setInt(3, getLvl());
@@ -235,10 +231,6 @@ public class Fort
 			{
 				_log.log(Level.SEVERE, "Exception: Fort.updateFunctions(int type, int lvl, int lease, long rate, long time, boolean addNew): " + e.getMessage(), e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 		}
 	}
 	
@@ -540,26 +532,19 @@ public class Fort
 	
 	public void saveFortVariables()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("UPDATE fort SET blood=?, supplyLvL=? WHERE id = ?");
 			statement.setInt(1, _blood);
 			statement.setInt(2, _supplyLvL);
 			statement.setInt(3, getFortId());
 			statement.execute();
 			statement.close();
-			
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Exception: saveFortVariables(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -606,11 +591,8 @@ public class Fort
 	// This method loads fort
 	private void load()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			PreparedStatement statement = con.prepareStatement("SELECT * FROM fort WHERE id = ?");
 			statement.setInt(1, getFortId());
 			ResultSet rs = statement.executeQuery();
@@ -662,21 +644,15 @@ public class Fort
 		{
 			_log.log(Level.WARNING, "Exception: loadFortData(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/** Load All Functions */
 	private void loadFunctions()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
 			PreparedStatement statement;
 			ResultSet rs;
-			con = L2DatabaseFactory.getInstance().getConnection();
 			statement = con.prepareStatement("SELECT * FROM fort_functions WHERE fort_id = ?");
 			statement.setInt(1, getFortId());
 			rs = statement.executeQuery();
@@ -691,10 +667,6 @@ public class Fort
 		{
 			_log.log(Level.SEVERE, "Exception: Fort.loadFunctions(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -704,10 +676,8 @@ public class Fort
 	public void removeFunction(int functionType)
 	{
 		_function.remove(functionType);
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("DELETE FROM fort_functions WHERE fort_id=? AND type=?");
 			statement.setInt(1, getFortId());
 			statement.setInt(2, functionType);
@@ -718,10 +688,6 @@ public class Fort
 		{
 			_log.log(Level.SEVERE, "Exception: Fort.removeFunctions(int functionType): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -809,10 +775,8 @@ public class Fort
 	// This method loads fort door upgrade data from database
 	private void loadDoorUpgrade()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT * FROM fort_doorupgrade WHERE fortId = ?");
 			statement.setInt(1, getFortId());
 			ResultSet rs = statement.executeQuery();
@@ -828,18 +792,12 @@ public class Fort
 		{
 			_log.log(Level.WARNING, "Exception: loadFortDoorUpgrade(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void removeDoorUpgrade()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("DELETE FROM fort_doorupgrade WHERE WHERE fortId = ?");
 			statement.setInt(1, getFortId());
 			statement.execute();
@@ -849,18 +807,12 @@ public class Fort
 		{
 			_log.log(Level.WARNING, "Exception: removeDoorUpgrade(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void saveDoorUpgrade(int doorId, int hp, int pDef, int mDef)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("INSERT INTO fort_doorupgrade (doorId, hp, pDef, mDef) VALUES (?,?,?,?)");
 			statement.setInt(1, doorId);
 			statement.setInt(2, hp);
@@ -873,10 +825,6 @@ public class Fort
 		{
 			_log.log(Level.WARNING, "Exception: saveDoorUpgrade(int doorId, int hp, int pDef, int mDef): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void updateOwnerInDB()
@@ -891,10 +839,8 @@ public class Fort
 		else
 			_lastOwnedTime.setTimeInMillis(0);
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("UPDATE fort SET owner=?,lastOwnedTime=?,state=?,castleId=?,blood=? WHERE id = ?");
 			statement.setInt(1, clanId);
 			statement.setLong(2, _lastOwnedTime.getTimeInMillis());
@@ -938,10 +884,6 @@ public class Fort
 		{
 			_log.log(Level.WARNING, "Exception: updateOwnerInDB(L2Clan clan): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public final int getFortId()
@@ -1089,10 +1031,8 @@ public class Fort
 	{
 		_state = state;
 		_castleId = castleId;
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("UPDATE fort SET state=?,castleId=? WHERE id = ?");
 			statement.setInt(1, getFortState());
 			statement.setInt(2, getCastleId());
@@ -1104,10 +1044,6 @@ public class Fort
 		{
 			_log.log(Level.WARNING, "Exception: setFortState(int state, int castleId): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -1205,11 +1141,8 @@ public class Fort
 	
 	private void initNpcs()
 	{
-		Connection con = null;
-		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT * FROM fort_spawnlist WHERE fortId = ? AND spawnType = ? ");
 			statement.setInt(1, getFortId());
 			statement.setInt(2, 0);
@@ -1248,19 +1181,13 @@ public class Fort
 			// problem with initializing spawn, go to next one
 			_log.log(Level.WARNING, "Fort " + getFortId() + " initNpcs: Spawn could not be initialized: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void initSiegeNpcs()
 	{
-		Connection con = null;
 		_siegeNpcs.clear();
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT id, npcId, x, y, z, heading FROM fort_spawnlist WHERE fortId = ? AND spawnType = ? ORDER BY id");
 			statement.setInt(1, getFortId());
 			statement.setInt(2, 2);
@@ -1295,19 +1222,13 @@ public class Fort
 			// problem with initializing spawn, go to next one
 			_log.log(Level.WARNING, "Fort " + getFortId() + " initSiegeNpcs: Spawn could not be initialized: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void initNpcCommanders()
 	{
-		Connection con = null;
 		_npcCommanders.clear();
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT id, npcId, x, y, z, heading FROM fort_spawnlist WHERE fortId = ? AND spawnType = ? ORDER BY id");
 			statement.setInt(1, getFortId());
 			statement.setInt(2, 1);
@@ -1343,20 +1264,14 @@ public class Fort
 			// problem with initializing spawn, go to next one
 			_log.log(Level.WARNING, "Fort " + getFortId() + " initNpcCommanders: Spawn could not be initialized: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void initSpecialEnvoys()
 	{
-		Connection con = null;
 		_specialEnvoys.clear();
 		_envoyCastles.clear();
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT id, npcId, x, y, z, heading, castleId FROM fort_spawnlist WHERE fortId = ? AND spawnType = ? ORDER BY id");
 			statement.setInt(1, getFortId());
 			statement.setInt(2, 3);
@@ -1395,10 +1310,6 @@ public class Fort
 			// problem with initializing spawn, go to next one
 			_log.log(Level.WARNING, "Fort " + getFortId() + " initSpecialEnvoys: Spawn could not be initialized: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public FastList<L2Skill> getResidentialSkills()

+ 29 - 56
L2J_Server_BETA/java/com/l2jserver/gameserver/model/entity/FortSiege.java

@@ -65,6 +65,10 @@ public class FortSiege implements Siegable
 		All, Attacker, Owner,
 	}
 	
+	// SQL
+	private static final String DELETE_FORT_SIEGECLANS_BY_CLAN_ID = "DELETE FROM fortsiege_clans WHERE fort_id = ? AND clan_id = ?";
+	private static final String DELETE_FORT_SIEGECLANS = "DELETE FROM fortsiege_clans WHERE fort_id = ?";
+	
 	public class ScheduleEndSiegeTask implements Runnable
 	{
 		@Override
@@ -478,20 +482,19 @@ public class FortSiege implements Siegable
 	/** Clear all registered siege clans from database for fort */
 	public void clearSiegeClan()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement("DELETE FROM fortsiege_clans WHERE fort_id=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("DELETE FROM fortsiege_clans WHERE fort_id=?");
-			statement.setInt(1, getFort().getFortId());
-			statement.execute();
-			statement.close();
+			ps.setInt(1, getFort().getFortId());
+			ps.execute();
 			
 			if (getFort().getOwnerClan() != null)
 			{
-				statement = con.prepareStatement("DELETE FROM fortsiege_clans WHERE clan_id=?");
-				statement.setInt(1, getFort().getOwnerClan().getClanId());
-				statement.execute();
+				try (PreparedStatement delete = con.prepareStatement("DELETE FROM fortsiege_clans WHERE clan_id=?"))
+				{
+					delete.setInt(1, getFort().getOwnerClan().getClanId());
+					delete.execute();
+				}
 			}
 			
 			getAttackerClans().clear();
@@ -500,7 +503,7 @@ public class FortSiege implements Siegable
 			if (getIsInProgress())
 				endSiege();
 			
-			// if siege isnt in progress (1hr waiting time till siege starts), cancel waiting time
+			// if siege isn't in progress (1hr waiting time till siege starts), cancel waiting time
 			if (_siegeStartTask != null)
 			{
 				_siegeStartTask.cancel(true);
@@ -511,10 +514,6 @@ public class FortSiege implements Siegable
 		{
 			_log.log(Level.WARNING, "Exception: clearSiegeClan(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/** Set the date for the next siege. */
@@ -699,19 +698,15 @@ public class FortSiege implements Siegable
 	 */
 	private void removeSiegeClan(int clanId)
 	{
-		Connection con = null;
-		PreparedStatement statement = null;
-		try
+		final String query = (clanId != 0) ? DELETE_FORT_SIEGECLANS_BY_CLAN_ID : DELETE_FORT_SIEGECLANS;
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement(query))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			if (clanId != 0)
-				statement = con.prepareStatement("DELETE FROM fortsiege_clans WHERE fort_id=? AND clan_id=?");
-			else
-				statement = con.prepareStatement("DELETE FROM fortsiege_clans WHERE fort_id=?");
-			
 			statement.setInt(1, getFort().getFortId());
 			if (clanId != 0)
+			{
 				statement.setInt(2, clanId);
+			}
 			statement.execute();
 			
 			loadSiegeClan();
@@ -733,10 +728,6 @@ public class FortSiege implements Siegable
 		{
 			_log.log(Level.WARNING, "Exception on removeSiegeClan: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -954,11 +945,9 @@ public class FortSiege implements Siegable
 	/** Load siege clans. */
 	private void loadSiegeClan()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
 			getAttackerClans().clear();
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT clan_id FROM fortsiege_clans WHERE fort_id=?");
 			statement.setInt(1, getFort().getFortId());
 			ResultSet rs = statement.executeQuery();
@@ -973,10 +962,6 @@ public class FortSiege implements Siegable
 		{
 			_log.log(Level.WARNING, "Exception: loadSiegeClan(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/** Remove commanders. */
@@ -1018,24 +1003,17 @@ public class FortSiege implements Siegable
 	/** Save siege date to database. */
 	private void saveSiegeDate()
 	{
-		Connection con = null;
-		PreparedStatement statement = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement("UPDATE fort SET siegeDate = ? WHERE id = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			statement = con.prepareStatement("UPDATE fort SET siegeDate = ? WHERE id = ?");
-			statement.setLong(1, getSiegeDate().getTimeInMillis());
-			statement.setInt(2, getFort().getFortId());
-			statement.execute();
+			ps.setLong(1, getSiegeDate().getTimeInMillis());
+			ps.setInt(2, getFort().getFortId());
+			ps.execute();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Exception: saveSiegeDate(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -1045,14 +1023,13 @@ public class FortSiege implements Siegable
 	private void saveSiegeClan(L2Clan clan)
 	{
 		if (getAttackerClans().size() >= FortSiegeManager.getInstance().getAttackerMaxClans())
+		{
 			return;
+		}
 		
-		Connection con = null;
-		PreparedStatement statement = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("INSERT INTO fortsiege_clans (clan_id,fort_id) values (?,?)"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			statement = con.prepareStatement("INSERT INTO fortsiege_clans (clan_id,fort_id) values (?,?)");
 			statement.setInt(1, clan.getClanId());
 			statement.setInt(2, getFort().getFortId());
 			statement.execute();
@@ -1063,10 +1040,6 @@ public class FortSiege implements Siegable
 		{
 			_log.log(Level.WARNING, "Exception: saveSiegeClan(L2Clan clan): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/** Spawn commanders. */

+ 9 - 63
L2J_Server_BETA/java/com/l2jserver/gameserver/model/entity/Hero.java

@@ -111,10 +111,8 @@ public class Hero
 		_herodiary.clear();
 		_heroMessage.clear();
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement(GET_HEROES);
 			ResultSet rset = statement.executeQuery();
 			PreparedStatement statement2 = con.prepareStatement(GET_CLAN_ALLY);
@@ -165,10 +163,6 @@ public class Hero
 		{
 			_log.log(Level.WARNING, "Hero System: Couldnt load Heroes", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
 		_log.info("Hero System: Loaded " + _heroes.size() + " Heroes.");
 		_log.info("Hero System: Loaded " + _completeHeroes.size() + " all time Heroes.");
@@ -221,11 +215,9 @@ public class Hero
 	 */
 	public void loadMessage(int charId)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
 			String message = null;
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT message FROM heroes WHERE charId=?");
 			statement.setInt(1, charId);
 			ResultSet rset = statement.executeQuery();
@@ -239,20 +231,14 @@ public class Hero
 		{
 			_log.log(Level.WARNING, "Hero System: Couldnt load Hero Message for CharId: " + charId, e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public void loadDiary(int charId)
 	{
 		final List<StatsSet> _diary = new FastList<>();
 		int diaryentries = 0;
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT * FROM  heroes_diary WHERE charId=? ORDER BY time ASC");
 			statement.setInt(1, charId);
 			ResultSet rset = statement.executeQuery();
@@ -302,10 +288,6 @@ public class Hero
 		{
 			_log.log(Level.WARNING, "Hero System: Couldnt load Hero Diary for CharId: " + charId, e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public void loadFights(int charId)
@@ -324,10 +306,8 @@ public class Hero
 		int _losses = 0;
 		int _draws = 0;
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("SELECT * FROM olympiad_fights WHERE (charOneId=? OR charTwoId=?) AND start<? ORDER BY start ASC");
 			statement.setInt(1, charId);
 			statement.setInt(2, charId);
@@ -442,10 +422,6 @@ public class Hero
 		{
 			_log.log(Level.WARNING, "Hero System: Couldnt load Hero fights history for CharId: " + charId, e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public Map<Integer, StatsSet> getHeroes()
@@ -776,10 +752,8 @@ public class Hero
 				loadDiary(charId);
 				_heroMessage.put(charId, "");
 				
-				Connection con = null;
-				try
+				try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 				{
-					con = L2DatabaseFactory.getInstance().getConnection();
 					PreparedStatement statement = con.prepareStatement(GET_CLAN_NAME);
 					statement.setInt(1, charId);
 					ResultSet rset = statement.executeQuery();
@@ -807,10 +781,6 @@ public class Hero
 				{
 					_log.warning("could not get clan name of player with objectId:" + charId + ": " + e);
 				}
-				finally
-				{
-					L2DatabaseFactory.close(con);
-				}
 			}
 		}
 	}
@@ -820,10 +790,8 @@ public class Hero
 		//_herofights = new FastMap<Integer, List<StatsSet>>();
 		//_herocounts = new FastMap<Integer, StatsSet>();
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement;
 			if (setDefault)
 			{
@@ -905,10 +873,6 @@ public class Hero
 		{
 			_log.log(Level.WARNING, "Hero System: Couldnt update Heroes", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public void setHeroGained(int charId)
@@ -965,10 +929,8 @@ public class Hero
 	
 	public void setDiaryData(int charId, int action, int param)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("INSERT INTO heroes_diary (charId, time, action, param) values(?,?,?,?)");
 			statement.setInt(1, charId);
 			statement.setLong(2, System.currentTimeMillis());
@@ -984,10 +946,6 @@ public class Hero
 				_log.log(Level.SEVERE, "SQL exception while saving DiaryData.", e);
 			}
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -1011,10 +969,8 @@ public class Hero
 		if (_heroMessage.get(charId) == null)
 			return;
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("UPDATE heroes SET message=? WHERE charId=?;");
 			statement.setString(1, _heroMessage.get(charId));
 			statement.setInt(2, charId);
@@ -1025,18 +981,12 @@ public class Hero
 		{
 			_log.log(Level.SEVERE, "SQL exception while saving HeroMessage.", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	private void deleteItemsInDb()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement(DELETE_ITEMS);
 			statement.execute();
 			statement.close();
@@ -1045,10 +995,6 @@ public class Hero
 		{
 			_log.log(Level.WARNING, "", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**

+ 45 - 80
L2J_Server_BETA/java/com/l2jserver/gameserver/model/entity/Siege.java

@@ -679,20 +679,19 @@ public class Siege implements Siegable
 	/** Clear all registered siege clans from database for castle */
 	public void clearSiegeClan()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("DELETE FROM siege_clans WHERE castle_id=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("DELETE FROM siege_clans WHERE castle_id=?");
 			statement.setInt(1, getCastle().getCastleId());
 			statement.execute();
-			statement.close();
 			
 			if (getCastle().getOwnerId() > 0)
 			{
-				statement = con.prepareStatement("DELETE FROM siege_clans WHERE clan_id=?");
-				statement.setInt(1, getCastle().getOwnerId());
-				statement.execute();
+				try (PreparedStatement delete = con.prepareStatement("DELETE FROM siege_clans WHERE clan_id=?"))
+				{
+					statement.setInt(1, getCastle().getOwnerId());
+					statement.execute();
+				}
 			}
 			
 			getAttackerClans().clear();
@@ -703,21 +702,14 @@ public class Siege implements Siegable
 		{
 			_log.log(Level.WARNING, "Exception: clearSiegeClan(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/** Clear all siege clans waiting for approval from database for castle */
 	public void clearSiegeWaitingClan()
 	{
-		Connection con = null;
-		PreparedStatement statement = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("DELETE FROM siege_clans WHERE castle_id=? and type = 2"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			statement = con.prepareStatement("DELETE FROM siege_clans WHERE castle_id=? and type = 2");
 			statement.setInt(1, getCastle().getCastleId());
 			statement.execute();
 			
@@ -727,10 +719,6 @@ public class Siege implements Siegable
 		{
 			_log.log(Level.WARNING, "Exception: clearSiegeWaitingClan(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/** Return list of L2PcInstance registered as attacker in the zone. */
@@ -920,12 +908,9 @@ public class Siege implements Siegable
 		if (clanId <= 0)
 			return;
 		
-		Connection con = null;
-		PreparedStatement statement = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("DELETE FROM siege_clans WHERE castle_id=? and clan_id=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			statement = con.prepareStatement("DELETE FROM siege_clans WHERE castle_id=? and clan_id=?");
 			statement.setInt(1, getCastle().getCastleId());
 			statement.setInt(2, clanId);
 			statement.execute();
@@ -936,10 +921,6 @@ public class Siege implements Siegable
 		{
 			_log.log(Level.WARNING, "Exception: removeSiegeClan(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -1147,9 +1128,9 @@ public class Siege implements Siegable
 	/** Load siege clans. */
 	private void loadSiegeClan()
 	{
-		Connection con = null;
-		PreparedStatement statement = null;
-		try
+		
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("SELECT clan_id,type FROM siege_clans where castle_id=?"))
 		{
 			getAttackerClans().clear();
 			getDefenderClans().clear();
@@ -1159,34 +1140,26 @@ public class Siege implements Siegable
 			if (getCastle().getOwnerId() > 0)
 				addDefender(getCastle().getOwnerId(), SiegeClanType.OWNER);
 			
-			ResultSet rs = null;
-			
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
-			statement = con.prepareStatement("SELECT clan_id,type FROM siege_clans where castle_id=?");
 			statement.setInt(1, getCastle().getCastleId());
-			rs = statement.executeQuery();
-			
-			int typeId;
-			while (rs.next())
+			try (ResultSet rs = statement.executeQuery())
 			{
-				typeId = rs.getInt("type");
-				if (typeId == DEFENDER)
-					addDefender(rs.getInt("clan_id"));
-				else if (typeId == ATTACKER)
-					addAttacker(rs.getInt("clan_id"));
-				else if (typeId == DEFENDER_NOT_APPROWED)
-					addDefenderWaiting(rs.getInt("clan_id"));
+				int typeId;
+				while (rs.next())
+				{
+					typeId = rs.getInt("type");
+					if (typeId == DEFENDER)
+						addDefender(rs.getInt("clan_id"));
+					else if (typeId == ATTACKER)
+						addAttacker(rs.getInt("clan_id"));
+					else if (typeId == DEFENDER_NOT_APPROWED)
+						addDefenderWaiting(rs.getInt("clan_id"));
+				}
 			}
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Exception: loadSiegeClan(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/** Remove all control tower spawned. */
@@ -1285,12 +1258,11 @@ public class Siege implements Siegable
 			_scheduledStartSiegeTask.cancel(true);
 			_scheduledStartSiegeTask = ThreadPoolManager.getInstance().scheduleGeneral(new Siege.ScheduleStartSiegeTask(getCastle()), 1000);
 		}
-		Connection con = null;
-		PreparedStatement statement = null;
-		try
+		
+		
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("UPDATE castle SET siegeDate = ?, regTimeEnd = ?, regTimeOver = ?  WHERE id = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			statement = con.prepareStatement("UPDATE castle SET siegeDate = ?, regTimeEnd = ?, regTimeOver = ?  WHERE id = ?");
 			statement.setLong(1, getSiegeDate().getTimeInMillis());
 			statement.setLong(2, getTimeRegistrationOverDate().getTimeInMillis());
 			statement.setString(3, String.valueOf(getIsTimeRegistrationOver()));
@@ -1301,10 +1273,6 @@ public class Siege implements Siegable
 		{
 			_log.log(Level.WARNING, "Exception: saveSiegeDate(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -1319,9 +1287,7 @@ public class Siege implements Siegable
 		if (clan.getCastleId() > 0)
 			return;
 		
-		Connection con = null;
-		PreparedStatement statement = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
 			if (typeId == DEFENDER || typeId == DEFENDER_NOT_APPROWED || typeId == OWNER)
 			{
@@ -1334,22 +1300,25 @@ public class Siege implements Siegable
 					return;
 			}
 			
-			con = L2DatabaseFactory.getInstance().getConnection();
 			if (!isUpdateRegistration)
 			{
-				statement = con.prepareStatement("INSERT INTO siege_clans (clan_id,castle_id,type,castle_owner) values (?,?,?,0)");
-				statement.setInt(1, clan.getClanId());
-				statement.setInt(2, getCastle().getCastleId());
-				statement.setInt(3, typeId);
-				statement.execute();
+				try (PreparedStatement statement = con.prepareStatement("INSERT INTO siege_clans (clan_id,castle_id,type,castle_owner) values (?,?,?,0)"))
+				{
+					statement.setInt(1, clan.getClanId());
+					statement.setInt(2, getCastle().getCastleId());
+					statement.setInt(3, typeId);
+					statement.execute();
+				}
 			}
 			else
 			{
-				statement = con.prepareStatement("UPDATE siege_clans SET type = ? WHERE castle_id = ? AND clan_id = ?");
-				statement.setInt(1, typeId);
-				statement.setInt(2, getCastle().getCastleId());
-				statement.setInt(3, clan.getClanId());
-				statement.execute();
+				try (PreparedStatement statement = con.prepareStatement("UPDATE siege_clans SET type = ? WHERE castle_id = ? AND clan_id = ?"))
+				{
+					statement.setInt(1, typeId);
+					statement.setInt(2, getCastle().getCastleId());
+					statement.setInt(3, clan.getClanId());
+					statement.execute();
+				}
 			}
 			
 			if (typeId == DEFENDER || typeId == OWNER)
@@ -1369,10 +1338,6 @@ public class Siege implements Siegable
 		{
 			_log.log(Level.WARNING, "Exception: saveSiegeClan(L2Clan clan, int typeId, boolean isUpdateRegistration): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/** Set the date for the next siege. */

+ 2 - 9
L2J_Server_BETA/java/com/l2jserver/gameserver/model/entity/clanhall/AuctionableHall.java

@@ -198,25 +198,18 @@ public final class AuctionableHall extends ClanHall
 	@Override
 	public final void updateDb()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("UPDATE clanhall SET ownerId=?, paidUntil=?, paid=? WHERE id=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("UPDATE clanhall SET ownerId=?, paidUntil=?, paid=? WHERE id=?");
 			statement.setInt(1, getOwnerId());
 			statement.setLong(2, getPaidUntil());
 			statement.setInt(3, (getPaid()) ? 1 : 0);
 			statement.setInt(4, getId());
 			statement.execute();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Exception: updateOwnerInDB(L2Clan clan): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 }

+ 35 - 53
L2J_Server_BETA/java/com/l2jserver/gameserver/model/entity/clanhall/ClanHallSiegeEngine.java

@@ -93,53 +93,45 @@ public abstract class ClanHallSiegeEngine extends Quest implements Siegable
 	
 	public void loadAttackers()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement(SQL_LOAD_ATTACKERS))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement(SQL_LOAD_ATTACKERS);
 			statement.setInt(1, _hall.getId());
-			ResultSet rset = statement.executeQuery();
-			while(rset.next())
+			try (ResultSet rset = statement.executeQuery())
 			{
-				final int id = rset.getInt("attacker_id");
-				L2SiegeClan clan = new L2SiegeClan(id, SiegeClanType.ATTACKER);
-				_attackers.put(id, clan);
+				while(rset.next())
+				{
+					final int id = rset.getInt("attacker_id");
+					L2SiegeClan clan = new L2SiegeClan(id, SiegeClanType.ATTACKER);
+					_attackers.put(id, clan);
+				}
 			}
-			rset.close();
-			statement.close();
 		}
 		catch(Exception e)
 		{
 			_log.warning(getName() + ": Could not load siege attackers!:");
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public final void saveAttackers()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement delStatement = con.prepareStatement("DELETE FROM clanhall_siege_attackers WHERE clanhall_id = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
-			PreparedStatement delStatement = con.prepareStatement("DELETE FROM clanhall_siege_attackers WHERE clanhall_id = ?");
 			delStatement.setInt(1, _hall.getId());
 			delStatement.execute();
-			delStatement.close();
 			
 			if(getAttackers().size() > 0)
 			{
-				for(L2SiegeClan clan : getAttackers().values())
+				try (PreparedStatement insert = con.prepareStatement(SQL_SAVE_ATTACKERS))
 				{
-					PreparedStatement insert = con.prepareStatement(SQL_SAVE_ATTACKERS);
-					insert.setInt(1, _hall.getId());
-					insert.setInt(2, clan.getClanId());
-					insert.execute();
-					insert.close();
+					for(L2SiegeClan clan : getAttackers().values())
+					{
+						insert.setInt(1, _hall.getId());
+						insert.setInt(2, clan.getClanId());
+						insert.execute();
+						insert.clearParameters();
+					}
 				}
 			}
 			_log.config(getName()+": Sucessfully saved attackers down to database!");
@@ -148,10 +140,6 @@ public abstract class ClanHallSiegeEngine extends Quest implements Siegable
 		{
 			_log.warning(getName() + ": Couldnt save attacker list!");
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public final void loadGuards()
@@ -159,37 +147,31 @@ public abstract class ClanHallSiegeEngine extends Quest implements Siegable
 		if(_guards == null)
 		{
 			_guards = new FastList<>();
-			Connection con = null;
-			try
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+				PreparedStatement statement = con.prepareStatement(SQL_LOAD_GUARDS))
 			{
-				con = L2DatabaseFactory.getInstance().getConnection();
-				PreparedStatement statement = con.prepareStatement(SQL_LOAD_GUARDS);
 				statement.setInt(1, _hall.getId());
-				ResultSet rset = statement.executeQuery();
-				while(rset.next())
+				try (ResultSet rset = statement.executeQuery())
 				{
-					final int npcId = rset.getInt("npcId");
-					final L2NpcTemplate template = NpcTable.getInstance().getTemplate(npcId);
-					L2Spawn spawn = new L2Spawn(template);
-					spawn.setLocx(rset.getInt("x"));
-					spawn.setLocy(rset.getInt("y"));
-					spawn.setLocz(rset.getInt("z"));
-					spawn.setHeading(rset.getInt("heading"));
-					spawn.setRespawnDelay(rset.getInt("respawnDelay"));
-					spawn.setAmount(1);
-					_guards.add(spawn);
+					while(rset.next())
+					{
+						final int npcId = rset.getInt("npcId");
+						final L2NpcTemplate template = NpcTable.getInstance().getTemplate(npcId);
+						L2Spawn spawn = new L2Spawn(template);
+						spawn.setLocx(rset.getInt("x"));
+						spawn.setLocy(rset.getInt("y"));
+						spawn.setLocz(rset.getInt("z"));
+						spawn.setHeading(rset.getInt("heading"));
+						spawn.setRespawnDelay(rset.getInt("respawnDelay"));
+						spawn.setAmount(1);
+						_guards.add(spawn);
+					}
 				}
-				rset.close();
-				statement.close();
 			}
 			catch(Exception e)
 			{
 				_log.warning(getName() + ": Couldnt load siege guards!:");
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 		}
 	}
 	

+ 2 - 9
L2J_Server_BETA/java/com/l2jserver/gameserver/model/entity/clanhall/SiegableHall.java

@@ -103,25 +103,18 @@ public final class SiegableHall extends ClanHall
 	@Override
 	public final void updateDb()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement(SQL_SAVE))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement(SQL_SAVE);
 			statement.setInt(1, getOwnerId());
 			statement.setLong(2, getNextSiegeTime());
 			statement.setInt(3, getId());
 			statement.execute();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Exception: SiegableHall.updateDb(): " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public final void setSiege(final ClanHallSiegeEngine siegable)

+ 15 - 32
L2J_Server_BETA/java/com/l2jserver/gameserver/model/itemauction/ItemAuction.java

@@ -60,6 +60,10 @@ public final class ItemAuction
 	private ItemAuctionBid _highestBid;
 	private int _lastBidPlayerObjId;
 	
+	// SQL
+	private static final String DELETE_ITEM_AUCTION_BID = "DELETE FROM item_auction_bid WHERE auctionId = ? AND playerObjId = ?";
+	private static final String INSERT_ITEM_AUCTION_BID = "INSERT INTO item_auction_bid (auctionId, playerObjId, playerBid) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE playerBid = ?";
+	
 	public ItemAuction(final int auctionId, final int instanceId, final long startingTime, final long endingTime, final AuctionItem auctionItem)
 	{
 		this(auctionId, instanceId, startingTime, endingTime, auctionItem, new ArrayList<ItemAuctionBid>(), ItemAuctionState.CREATED);
@@ -181,11 +185,9 @@ public final class ItemAuction
 	
 	public final void storeMe()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("INSERT INTO item_auction (auctionId,instanceId,auctionItemId,startingTime,endingTime,auctionStateId) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE auctionStateId=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("INSERT INTO item_auction (auctionId,instanceId,auctionItemId,startingTime,endingTime,auctionStateId) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE auctionStateId=?");
 			statement.setInt(1, _auctionId);
 			statement.setInt(2, _instanceId);
 			statement.setInt(3, _auctionItem.getAuctionItemId());
@@ -194,16 +196,11 @@ public final class ItemAuction
 			statement.setByte(6, _auctionState.getStateId());
 			statement.setByte(7, _auctionState.getStateId());
 			statement.execute();
-			statement.close();
 		}
 		catch (final SQLException e)
 		{
 			_log.log(Level.WARNING, "", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public final int getAndSetLastBidPlayerObjectId(final int playerObjId)
@@ -221,37 +218,23 @@ public final class ItemAuction
 	
 	final void updatePlayerBidInternal(final ItemAuctionBid bid, final boolean delete)
 	{
-		Connection con = null;
-		try
+		final String query = delete ? DELETE_ITEM_AUCTION_BID : INSERT_ITEM_AUCTION_BID;
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement(query))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			final PreparedStatement statement;
-			
-			if (delete)
-			{
-				statement = con.prepareStatement("DELETE FROM item_auction_bid WHERE auctionId=? AND playerObjId=?");
-				statement.setInt(1, _auctionId);
-				statement.setInt(2, bid.getPlayerObjId());
-			}
-			else
+			ps.setInt(1, _auctionId);
+			ps.setInt(2, bid.getPlayerObjId());
+			if (!delete)
 			{
-				statement = con.prepareStatement("INSERT INTO item_auction_bid (auctionId,playerObjId,playerBid) VALUES (?,?,?) ON DUPLICATE KEY UPDATE playerBid=?");
-				statement.setInt(1, _auctionId);
-				statement.setInt(2, bid.getPlayerObjId());
-				statement.setLong(3, bid.getLastBid());
-				statement.setLong(4, bid.getLastBid());
+				ps.setLong(3, bid.getLastBid());
+				ps.setLong(4, bid.getLastBid());
 			}
-			statement.execute();
-			statement.close();
+			ps.execute();
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.WARNING, "", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public final void registerBid(final L2PcInstance player, final long newBid)

+ 17 - 31
L2J_Server_BETA/java/com/l2jserver/gameserver/model/itemauction/ItemAuctionInstance.java

@@ -170,35 +170,31 @@ public final class ItemAuctionInstance
 			throw new IllegalArgumentException("No items defined");
 		}
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement(SELECT_AUCTION_ID_BY_INSTANCE_ID))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			try (PreparedStatement ps = con.prepareStatement(SELECT_AUCTION_ID_BY_INSTANCE_ID))
+			ps.setInt(1, _instanceId);
+			try (ResultSet rset = ps.executeQuery())
 			{
-				ps.setInt(1, _instanceId);
-				try (ResultSet rset = ps.executeQuery())
+				while (rset.next())
 				{
-					while (rset.next())
+					final int auctionId = rset.getInt(1);
+					try
 					{
-						final int auctionId = rset.getInt(1);
-						try
+						final ItemAuction auction = loadAuction(auctionId);
+						if (auction != null)
 						{
-							final ItemAuction auction = loadAuction(auctionId);
-							if (auction != null)
-							{
-								_auctions.put(auctionId, auction);
-							}
-							else
-							{
-								ItemAuctionManager.deleteAuction(auctionId);
-							}
+							_auctions.put(auctionId, auction);
 						}
-						catch (final SQLException e)
+						else
 						{
-							_log.log(Level.WARNING, getClass().getSimpleName() + ": Failed loading auction: " + auctionId, e);
+							ItemAuctionManager.deleteAuction(auctionId);
 						}
 					}
+					catch (final SQLException e)
+					{
+						_log.log(Level.WARNING, getClass().getSimpleName() + ": Failed loading auction: " + auctionId, e);
+					}
 				}
 			}
 		}
@@ -207,10 +203,6 @@ public final class ItemAuctionInstance
 			_log.log(Level.SEVERE, getClass().getSimpleName() + ": Failed loading auctions.", e);
 			return;
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
 		_log.log(Level.INFO, getClass().getSimpleName() + ": Loaded " + _items.size() + " item(s) and registered " + _auctions.size() + " auction(s) for instance " + _instanceId + ".");
 		checkAndSetCurrentAndNextAuction();
@@ -559,10 +551,8 @@ public final class ItemAuctionInstance
 	
 	private final ItemAuction loadAuction(final int auctionId) throws SQLException
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			int auctionItemId = 0;
 			long startingTime = 0;
 			long endingTime = 0;
@@ -638,9 +628,5 @@ public final class ItemAuctionInstance
 			}
 			return new ItemAuction(auctionId, _instanceId, startingTime, endingTime, auctionItem, auctionBids, auctionState);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 }

+ 23 - 31
L2J_Server_BETA/java/com/l2jserver/gameserver/model/itemcontainer/Inventory.java

@@ -1559,52 +1559,44 @@ public abstract class Inventory extends ItemContainer
 	@Override
 	public void restore()
 	{
-		Connection con = null;
-		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("SELECT object_id, item_id, count, enchant_level, loc, loc_data, custom_type1, custom_type2, mana_left, time FROM items WHERE owner_id=? AND (loc=? OR loc=?) ORDER BY loc_data"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("SELECT object_id, item_id, count, enchant_level, loc, loc_data, custom_type1, custom_type2, mana_left, time FROM items WHERE owner_id=? AND (loc=? OR loc=?) ORDER BY loc_data");
 			statement.setInt(1, getOwnerId());
 			statement.setString(2, getBaseLocation().name());
 			statement.setString(3, getEquipLocation().name());
-			ResultSet inv = statement.executeQuery();
-			
-			L2ItemInstance item;
-			while (inv.next())
+			try (ResultSet inv = statement.executeQuery())
 			{
-				item = L2ItemInstance.restoreFromDb(getOwnerId(), inv);
-				if (item == null)
-					continue;
-				
-				if (getOwner() instanceof L2PcInstance)
+				L2ItemInstance item;
+				while (inv.next())
 				{
-					L2PcInstance player = (L2PcInstance)getOwner();
+					item = L2ItemInstance.restoreFromDb(getOwnerId(), inv);
+					if (item == null)
+						continue;
 					
-					if (!player.isGM() && !player.isHero() && item.isHeroItem())
-						item.setLocation(ItemLocation.INVENTORY);
+					if (getOwner() instanceof L2PcInstance)
+					{
+						L2PcInstance player = (L2PcInstance)getOwner();
+						
+						if (!player.isGM() && !player.isHero() && item.isHeroItem())
+							item.setLocation(ItemLocation.INVENTORY);
+					}
+					
+					L2World.getInstance().storeObject(item);
+					
+					// If stackable item is found in inventory just add to current quantity
+					if (item.isStackable() && getItemByItemId(item.getItemId()) != null)
+						addItem("Restore", item, getOwner().getActingPlayer(), null);
+					else
+						addItem(item);
 				}
-				
-				L2World.getInstance().storeObject(item);
-				
-				// If stackable item is found in inventory just add to current quantity
-				if (item.isStackable() && getItemByItemId(item.getItemId()) != null)
-					addItem("Restore", item, getOwner().getActingPlayer(), null);
-				else
-					addItem(item);
 			}
-			inv.close();
-			statement.close();
 			refreshWeight();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Could not restore inventory: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public int getMaxTalismanCount()

+ 20 - 28
L2J_Server_BETA/java/com/l2jserver/gameserver/model/itemcontainer/ItemContainer.java

@@ -573,45 +573,37 @@ public abstract class ItemContainer
 	 */
 	public void restore()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("SELECT object_id, item_id, count, enchant_level, loc, loc_data, custom_type1, custom_type2, mana_left, time FROM items WHERE owner_id=? AND (loc=?)"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("SELECT object_id, item_id, count, enchant_level, loc, loc_data, custom_type1, custom_type2, mana_left, time FROM items WHERE owner_id=? AND (loc=?)");
 			statement.setInt(1, getOwnerId());
 			statement.setString(2, getBaseLocation().name());
-			ResultSet inv = statement.executeQuery();
-			
-			L2ItemInstance item;
-			while (inv.next())
+			try (ResultSet inv = statement.executeQuery())
 			{
-				item = L2ItemInstance.restoreFromDb(getOwnerId(), inv);
-				if (item == null)
-					continue;
-				
-				L2World.getInstance().storeObject(item);
-				
-				L2PcInstance owner = getOwner() == null ? null : getOwner().getActingPlayer();
-				
-				// If stackable item is found in inventory just add to current quantity
-				if (item.isStackable() && getItemByItemId(item.getItemId()) != null)
-					addItem("Restore", item, owner, null);
-				else
-					addItem(item);
+				L2ItemInstance item;
+				while (inv.next())
+				{
+					item = L2ItemInstance.restoreFromDb(getOwnerId(), inv);
+					if (item == null)
+						continue;
+					
+					L2World.getInstance().storeObject(item);
+					
+					L2PcInstance owner = getOwner() == null ? null : getOwner().getActingPlayer();
+					
+					// If stackable item is found in inventory just add to current quantity
+					if (item.isStackable() && getItemByItemId(item.getItemId()) != null)
+						addItem("Restore", item, owner, null);
+					else
+						addItem(item);
+				}
 			}
-			
-			inv.close();
-			statement.close();
 			refreshWeight();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "could not restore container:", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public boolean validateCapacity(long slots)

+ 18 - 27
L2J_Server_BETA/java/com/l2jserver/gameserver/model/itemcontainer/Mail.java

@@ -26,9 +26,7 @@ import com.l2jserver.gameserver.model.items.instance.L2ItemInstance;
 import com.l2jserver.gameserver.model.items.instance.L2ItemInstance.ItemLocation;
 
 /**
- * 
  * @author DS
- *
  */
 public class Mail extends ItemContainer
 {
@@ -116,42 +114,35 @@ public class Mail extends ItemContainer
 	@Override
 	public void restore()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("SELECT object_id, item_id, count, enchant_level, loc, loc_data, custom_type1, custom_type2, mana_left, time FROM items WHERE owner_id=? AND loc=? AND loc_data=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("SELECT object_id, item_id, count, enchant_level, loc, loc_data, custom_type1, custom_type2, mana_left, time FROM items WHERE owner_id=? AND loc=? AND loc_data=?");
 			statement.setInt(1, getOwnerId());
 			statement.setString(2, getBaseLocation().name());
 			statement.setInt(3, getMessageId());
-			ResultSet inv = statement.executeQuery();
-			
-			L2ItemInstance item;
-			while (inv.next())
+			try (ResultSet inv = statement.executeQuery())
 			{
-				item = L2ItemInstance.restoreFromDb(getOwnerId(), inv);
-				if (item == null)
-					continue;
-				
-				L2World.getInstance().storeObject(item);
-				
-				// If stackable item is found just add to current quantity
-				if (item.isStackable() && getItemByItemId(item.getItemId()) != null)
-					addItem("Restore", item, null, null);
-				else
-					addItem(item);
+				L2ItemInstance item;
+				while (inv.next())
+				{
+					item = L2ItemInstance.restoreFromDb(getOwnerId(), inv);
+					if (item == null)
+						continue;
+					
+					L2World.getInstance().storeObject(item);
+					
+					// If stackable item is found just add to current quantity
+					if (item.isStackable() && getItemByItemId(item.getItemId()) != null)
+						addItem("Restore", item, null, null);
+					else
+						addItem(item);
+				}
 			}
-			inv.close();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "could not restore container:", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	@Override

+ 15 - 23
L2J_Server_BETA/java/com/l2jserver/gameserver/model/itemcontainer/PcInventory.java

@@ -741,39 +741,31 @@ public class PcInventory extends Inventory
 	public static int[][] restoreVisibleInventory(int objectId)
 	{
 		int[][] paperdoll = new int[31][3];
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement2 = con.prepareStatement("SELECT object_id,item_id,loc_data,enchant_level FROM items WHERE owner_id=? AND loc='PAPERDOLL'"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement2 = con.prepareStatement("SELECT object_id,item_id,loc_data,enchant_level FROM items WHERE owner_id=? AND loc='PAPERDOLL'");
 			statement2.setInt(1, objectId);
-			ResultSet invdata = statement2.executeQuery();
-			
-			while (invdata.next())
+			try (ResultSet invdata = statement2.executeQuery())
 			{
-				int slot = invdata.getInt("loc_data");
-				paperdoll[slot][0] = invdata.getInt("object_id");
-				paperdoll[slot][1] = invdata.getInt("item_id");
-				paperdoll[slot][2] = invdata.getInt("enchant_level");
-				/*if (slot == Inventory.PAPERDOLL_RHAND)
+				while (invdata.next())
 				{
-					paperdoll[Inventory.PAPERDOLL_RHAND][0] = invdata.getInt("object_id");
-					paperdoll[Inventory.PAPERDOLL_RHAND][1] = invdata.getInt("item_id");
-					paperdoll[Inventory.PAPERDOLL_RHAND][2] = invdata.getInt("enchant_level");
-				}*/
+					int slot = invdata.getInt("loc_data");
+					paperdoll[slot][0] = invdata.getInt("object_id");
+					paperdoll[slot][1] = invdata.getInt("item_id");
+					paperdoll[slot][2] = invdata.getInt("enchant_level");
+					/*if (slot == Inventory.PAPERDOLL_RHAND)
+					{
+						paperdoll[Inventory.PAPERDOLL_RHAND][0] = invdata.getInt("object_id");
+						paperdoll[Inventory.PAPERDOLL_RHAND][1] = invdata.getInt("item_id");
+						paperdoll[Inventory.PAPERDOLL_RHAND][2] = invdata.getInt("enchant_level");
+					}*/
+				}
 			}
-			
-			invdata.close();
-			statement2.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Could not restore inventory: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		return paperdoll;
 	}
 	

+ 51 - 101
L2J_Server_BETA/java/com/l2jserver/gameserver/model/items/instance/L2ItemInstance.java

@@ -897,7 +897,14 @@ public final class L2ItemInstance extends L2Object
 			return false;
 		}
 		_augmentation = augmentation;
-		updateItemAttributes(null);
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
+		{
+			updateItemAttributes(con);
+		}
+		catch (SQLException e)
+		{
+			_log.log(Level.SEVERE, "Could not update atributes for item: " + this + " from DB:", e);
+		}
 		return true;
 	}
 	
@@ -914,77 +921,59 @@ public final class L2ItemInstance extends L2Object
 		}
 		_augmentation = null;
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("DELETE FROM item_attributes WHERE itemId = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
-			PreparedStatement statement = null;
-			// Remove the entry
-			statement = con.prepareStatement("DELETE FROM item_attributes WHERE itemId = ?");
-			
 			statement.setInt(1, getObjectId());
 			statement.executeUpdate();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, "Could not remove augmentation for item: " + this + " from DB:", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public void restoreAttributes()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps1 = con.prepareStatement("SELECT augAttributes,augSkillId,augSkillLevel FROM item_attributes WHERE itemId=?");
+			PreparedStatement ps2 = con.prepareStatement("SELECT elemType,elemValue FROM item_elementals WHERE itemId=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("SELECT augAttributes,augSkillId,augSkillLevel FROM item_attributes WHERE itemId=?");
-			statement.setInt(1, getObjectId());
-			ResultSet rs = statement.executeQuery();
-			if (rs.next())
+			ps1.setInt(1, getObjectId());
+			try (ResultSet rs = ps1.executeQuery())
 			{
-				int aug_attributes = rs.getInt(1);
-				int aug_skillId = rs.getInt(2);
-				int aug_skillLevel = rs.getInt(3);
-				if (aug_attributes != -1 && aug_skillId != -1 && aug_skillLevel != -1)
-					_augmentation = new L2Augmentation(rs.getInt("augAttributes"), rs.getInt("augSkillId"), rs.getInt("augSkillLevel"));
+				if (rs.next())
+				{
+					int aug_attributes = rs.getInt(1);
+					int aug_skillId = rs.getInt(2);
+					int aug_skillLevel = rs.getInt(3);
+					if (aug_attributes != -1 && aug_skillId != -1 && aug_skillLevel != -1)
+						_augmentation = new L2Augmentation(rs.getInt("augAttributes"), rs.getInt("augSkillId"), rs.getInt("augSkillLevel"));
+				}
 			}
-			rs.close();
-			statement.close();
-			statement = con.prepareStatement("SELECT elemType,elemValue FROM item_elementals WHERE itemId=?");
-			statement.setInt(1, getObjectId());
-			rs = statement.executeQuery();
-			while (rs.next())
+			
+			ps2.setInt(1, getObjectId());
+			try (ResultSet rs = ps2.executeQuery())
 			{
-				byte elem_type = rs.getByte(1);
-				int elem_value = rs.getInt(2);
-				if (elem_type != -1 && elem_value != -1)
-					applyAttribute(elem_type, elem_value);
+				while (rs.next())
+				{
+					byte elem_type = rs.getByte(1);
+					int elem_value = rs.getInt(2);
+					if (elem_type != -1 && elem_value != -1)
+						applyAttribute(elem_type, elem_value);
+				}
 			}
-			rs.close();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, "Could not restore augmentation and elemental data for item " + this + " from DB: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
-	private void updateItemAttributes(Connection pooledCon)
+	private void updateItemAttributes(Connection con)
 	{
-		Connection con = null;
 		try
 		{
-			con = pooledCon == null ? L2DatabaseFactory.getInstance().getConnection() : pooledCon;
 			PreparedStatement statement = con.prepareStatement("REPLACE INTO item_attributes VALUES(?,?,?,?)");
 			statement.setInt(1, getObjectId());
 			if (_augmentation == null)
@@ -1013,21 +1002,13 @@ public final class L2ItemInstance extends L2Object
 		catch (SQLException e)
 		{
 			_log.log(Level.SEVERE, "Could not update atributes for item: " + this + " from DB:", e);
-			
-		}
-		finally
-		{
-			if (pooledCon == null)
-				L2DatabaseFactory.close(con);
 		}
 	}
 	
-	private void updateItemElements(Connection pooledCon)
+	private void updateItemElements(Connection con)
 	{
-		Connection con = null;
 		try
 		{
-			con = pooledCon == null ? L2DatabaseFactory.getInstance().getConnection() : pooledCon;
 			PreparedStatement statement = con.prepareStatement("DELETE FROM item_elementals WHERE itemId = ?");
 			statement.setInt(1, getObjectId());
 			statement.executeUpdate();
@@ -1053,11 +1034,6 @@ public final class L2ItemInstance extends L2Object
 		{
 			_log.log(Level.SEVERE, "Could not update elementals for item: " + this + " from DB:", e);
 		}
-		finally
-		{
-			if (pooledCon == null)
-				L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public Elementals[] getElementals()
@@ -1151,7 +1127,14 @@ public final class L2ItemInstance extends L2Object
 	public void setElementAttr(byte element, int value)
 	{
 		applyAttribute(element, value);
-		updateItemElements(null);
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
+		{
+			updateItemElements(con);
+		}
+		catch (SQLException e)
+		{
+			_log.log(Level.SEVERE, "Could not update elementals for item: " + this + " from DB:", e);
+		}
 	}
 	
 	/**
@@ -1180,36 +1163,23 @@ public final class L2ItemInstance extends L2Object
 		}
 		_elementals = array;
 		
-		Connection con = null;
-		try
+		String query = (element != -1) ? "DELETE FROM item_elementals WHERE itemId = ? AND elemType = ?" : "DELETE FROM item_elementals WHERE itemId = ?";
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement(query))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
-			PreparedStatement statement = null;
 			if (element != -1)
 			{
 				// Item can have still others
-				statement = con.prepareStatement("DELETE FROM item_elementals WHERE itemId = ? AND elemType = ?");
 				statement.setInt(2, element);
 			}
-			else
-			{
-				// Remove the entries
-				statement = con.prepareStatement("DELETE FROM item_elementals WHERE itemId = ?");
-			}
 			
 			statement.setInt(1, getObjectId());
 			statement.executeUpdate();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, "Could not remove elemental enchant for item: " + this + " from DB:", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -1643,11 +1613,9 @@ public final class L2ItemInstance extends L2Object
 		if (_storedInDb)
 			return;
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("UPDATE items SET owner_id=?,count=?,loc=?,loc_data=?,enchant_level=?,custom_type1=?,custom_type2=?,mana_left=?,time=? " + "WHERE object_id = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("UPDATE items SET owner_id=?,count=?,loc=?,loc_data=?,enchant_level=?,custom_type1=?,custom_type2=?,mana_left=?,time=? " + "WHERE object_id = ?");
 			statement.setInt(1, _ownerId);
 			statement.setLong(2, getCount());
 			statement.setString(3, _loc.name());
@@ -1661,16 +1629,11 @@ public final class L2ItemInstance extends L2Object
 			statement.executeUpdate();
 			_existsInDb = true;
 			_storedInDb = true;
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, "Could not update item " + this + " in DB: Reason: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -1683,11 +1646,9 @@ public final class L2ItemInstance extends L2Object
 		if (_wear)
 			return;
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("INSERT INTO items (owner_id,item_id,count,loc,loc_data,enchant_level,object_id,custom_type1,custom_type2,mana_left,time) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?)"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("INSERT INTO items (owner_id,item_id,count,loc,loc_data,enchant_level,object_id,custom_type1,custom_type2,mana_left,time) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?)");
 			statement.setInt(1, _ownerId);
 			statement.setInt(2, _itemId);
 			statement.setLong(3, getCount());
@@ -1703,7 +1664,6 @@ public final class L2ItemInstance extends L2Object
 			statement.executeUpdate();
 			_existsInDb = true;
 			_storedInDb = true;
-			statement.close();
 			
 			if (_augmentation != null)
 				updateItemAttributes(con);
@@ -1714,10 +1674,6 @@ public final class L2ItemInstance extends L2Object
 		{
 			_log.log(Level.SEVERE, "Could not insert item " + this + " into DB: Reason: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -1730,10 +1686,8 @@ public final class L2ItemInstance extends L2Object
 		if (_wear)
 			return;
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement("DELETE FROM items WHERE object_id = ?");
 			statement.setInt(1, getObjectId());
 			statement.executeUpdate();
@@ -1755,10 +1709,6 @@ public final class L2ItemInstance extends L2Object
 		{
 			_log.log(Level.SEVERE, "Could not delete item " + this + " in DB: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**

+ 68 - 166
L2J_Server_BETA/java/com/l2jserver/gameserver/model/olympiad/Olympiad.java

@@ -179,14 +179,11 @@ public class Olympiad
 	private void load()
 	{
 		_nobles.clear();
-		Connection con = null;
 		boolean loaded = false;
-		try
-		{
-			con = L2DatabaseFactory.getInstance().getConnection();
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement(OLYMPIAD_LOAD_DATA);
-			ResultSet rset = statement.executeQuery();
-			
+			ResultSet rset = statement.executeQuery())
+		{
 			while (rset.next())
 			{
 				_currentCycle = rset.getInt("current_cycle");
@@ -196,18 +193,11 @@ public class Olympiad
 				_nextWeeklyChange = rset.getLong("next_weekly_change");
 				loaded = true;
 			}
-			
-			rset.close();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Olympiad System: Error loading olympiad data from database: ", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
 		if (!loaded)
 		{
@@ -263,11 +253,10 @@ public class Olympiad
 				return;
 		}
 		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement(OLYMPIAD_LOAD_NOBLES);
+			ResultSet rset = statement.executeQuery())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			final PreparedStatement statement = con.prepareStatement(OLYMPIAD_LOAD_NOBLES);
-			final ResultSet rset = statement.executeQuery();
 			StatsSet statData;
 			while (rset.next())
 			{
@@ -287,18 +276,11 @@ public class Olympiad
 				
 				addNobleStats(rset.getInt(CHAR_ID), statData);
 			}
-			
-			rset.close();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Olympiad System: Error loading noblesse data from database: ", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
 		synchronized (this)
 		{
@@ -340,31 +322,21 @@ public class Olympiad
 	{
 		_noblesRank.clear();
 		TIntIntHashMap tmpPlace = new TIntIntHashMap();
-		
-		Connection con = null;
-		try
-		{
-			con = L2DatabaseFactory.getInstance().getConnection();
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement(GET_ALL_CLASSIFIED_NOBLESS);
-			ResultSet rset = statement.executeQuery();
-			
+			ResultSet rset = statement.executeQuery())
+		{
 			int place = 1;
 			while (rset.next())
 			{
 				tmpPlace.put(rset.getInt(CHAR_ID), place++);
 			}
-			
-			rset.close();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Olympiad System: Error loading noblesse data from database for Ranking: ", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
+		
 		int rank1 = (int) Math.round(tmpPlace.size() * 0.01);
 		int rank2 = (int) Math.round(tmpPlace.size() * 0.10);
 		int rank3 = (int) Math.round(tmpPlace.size() * 0.25);
@@ -756,11 +728,8 @@ public class Olympiad
 			return;
 		}
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement;
 			for (Entry<Integer, StatsSet> entry : _nobles.entrySet())
 			{
 				StatsSet nobleInfo = entry.getValue();
@@ -783,49 +752,45 @@ public class Olympiad
 				int compDoneWeekTeam = nobleInfo.getInteger(COMP_DONE_WEEK_TEAM);
 				boolean toSave = nobleInfo.getBool("to_save");
 				
-				if (toSave)
+				try (PreparedStatement statement = con.prepareStatement(toSave ? OLYMPIAD_SAVE_NOBLES : OLYMPIAD_UPDATE_NOBLES))
 				{
-					statement = con.prepareStatement(OLYMPIAD_SAVE_NOBLES);
-					statement.setInt(1, charId);
-					statement.setInt(2, classId);
-					statement.setInt(3, points);
-					statement.setInt(4, compDone);
-					statement.setInt(5, compWon);
-					statement.setInt(6, compLost);
-					statement.setInt(7, compDrawn);
-					statement.setInt(8, compDoneWeek);
-					statement.setInt(9, compDoneWeekClassed);
-					statement.setInt(10, compDoneWeekNonClassed);
-					statement.setInt(11, compDoneWeekTeam);
-					
-					nobleInfo.set("to_save", false);
-				}
-				else
-				{
-					statement = con.prepareStatement(OLYMPIAD_UPDATE_NOBLES);
-					statement.setInt(1, points);
-					statement.setInt(2, compDone);
-					statement.setInt(3, compWon);
-					statement.setInt(4, compLost);
-					statement.setInt(5, compDrawn);
-					statement.setInt(6, compDoneWeek);
-					statement.setInt(7, compDoneWeekClassed);
-					statement.setInt(8, compDoneWeekNonClassed);
-					statement.setInt(9, compDoneWeekTeam);
-					statement.setInt(10, charId);
+					if (toSave)
+					{
+						statement.setInt(1, charId);
+						statement.setInt(2, classId);
+						statement.setInt(3, points);
+						statement.setInt(4, compDone);
+						statement.setInt(5, compWon);
+						statement.setInt(6, compLost);
+						statement.setInt(7, compDrawn);
+						statement.setInt(8, compDoneWeek);
+						statement.setInt(9, compDoneWeekClassed);
+						statement.setInt(10, compDoneWeekNonClassed);
+						statement.setInt(11, compDoneWeekTeam);
+						
+						nobleInfo.set("to_save", false);
+					}
+					else
+					{
+						statement.setInt(1, points);
+						statement.setInt(2, compDone);
+						statement.setInt(3, compWon);
+						statement.setInt(4, compLost);
+						statement.setInt(5, compDrawn);
+						statement.setInt(6, compDoneWeek);
+						statement.setInt(7, compDoneWeekClassed);
+						statement.setInt(8, compDoneWeekNonClassed);
+						statement.setInt(9, compDoneWeekTeam);
+						statement.setInt(10, charId);
+					}
+					statement.execute();
 				}
-				statement.execute();
-				statement.close();
 			}
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.SEVERE, "Olympiad System: Failed to save noblesse data to database: ", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -835,12 +800,9 @@ public class Olympiad
 	{
 		saveNobleData();
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement(OLYMPIAD_SAVE_DATA))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			final PreparedStatement statement = con.prepareStatement(OLYMPIAD_SAVE_DATA);
-			
 			statement.setInt(1, _currentCycle);
 			statement.setInt(2, _period);
 			statement.setLong(3, _olympiadEnd);
@@ -851,22 +813,16 @@ public class Olympiad
 			statement.setLong(8, _olympiadEnd);
 			statement.setLong(9, _validationEnd);
 			statement.setLong(10, _nextWeeklyChange);
-			
 			statement.execute();
-			statement.close();
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.SEVERE, "Olympiad System: Failed to save olympiad data to database: ", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		//@formatter:off
 		/*
 		Properties OlympiadProperties = new Properties();
-		try (FileOutputStream fos = new FileOutputStream(new File("./" + OLYMPIAD_DATA_FILE));)
+		try (FileOutputStream fos = new FileOutputStream(new File("./" + OLYMPIAD_DATA_FILE)))
 		{
 			OlympiadProperties.setProperty("CurrentCycle", String.valueOf(_currentCycle));
 			OlympiadProperties.setProperty("Period", String.valueOf(_period));
@@ -885,25 +841,17 @@ public class Olympiad
 	
 	protected void updateMonthlyData()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps1 = con.prepareStatement(OLYMPIAD_MONTH_CLEAR);
+			PreparedStatement ps2 = con.prepareStatement(OLYMPIAD_MONTH_CREATE))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement(OLYMPIAD_MONTH_CLEAR);
-			statement.execute();
-			statement.close();
-			statement = con.prepareStatement(OLYMPIAD_MONTH_CREATE);
-			statement.execute();
-			statement.close();
+			ps1.execute();
+			ps2.execute();
 		}
 		catch (SQLException e)
 		{
 			_log.log(Level.SEVERE, "Olympiad System: Failed to update monthly noblese data: ", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	protected void sortHerosToBe()
@@ -946,10 +894,8 @@ public class Olympiad
 		
 		_heroesToBe = new L2FastList<>();
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
 			PreparedStatement statement = con.prepareStatement(OLYMPIAD_GET_HEROS);
 			ResultSet rset;
 			StatsSet hero;
@@ -1077,60 +1023,29 @@ public class Olympiad
 		{
 			_log.warning("Olympiad System: Couldnt load heros from DB");
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public L2FastList<String> getClassLeaderBoard(int classId)
 	{
 		// if (_period != 1) return;
 		final L2FastList<String> names = new L2FastList<>();
-		Connection con = null;
-		try
+		String query = Config.ALT_OLY_SHOW_MONTHLY_WINNERS ? ((classId == 132) ? GET_EACH_CLASS_LEADER_SOULHOUND : GET_EACH_CLASS_LEADER) : ((classId == 132) ? GET_EACH_CLASS_LEADER_CURRENT_SOULHOUND : GET_EACH_CLASS_LEADER_CURRENT);
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement(query))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			final PreparedStatement statement;
-			if (Config.ALT_OLY_SHOW_MONTHLY_WINNERS)
+			ps.setInt(1, classId);
+			try (ResultSet rset = ps.executeQuery())
 			{
-				if (classId == 132)
+				while (rset.next())
 				{
-					statement = con.prepareStatement(GET_EACH_CLASS_LEADER_SOULHOUND);
-				}
-				else
-				{
-					statement = con.prepareStatement(GET_EACH_CLASS_LEADER);
+					names.add(rset.getString(CHAR_NAME));
 				}
 			}
-			else
-			{
-				if (classId == 132)
-				{
-					statement = con.prepareStatement(GET_EACH_CLASS_LEADER_CURRENT_SOULHOUND);
-				}
-				else
-				{
-					statement = con.prepareStatement(GET_EACH_CLASS_LEADER_CURRENT);
-				}
-			}
-			statement.setInt(1, classId);
-			final ResultSet rset = statement.executeQuery();
-			while (rset.next())
-			{
-				names.add(rset.getString(CHAR_NAME));
-			}
-			statement.close();
-			rset.close();
 		}
 		catch (SQLException e)
 		{
 			_log.warning("Olympiad System: Couldn't load olympiad leaders from DB!");
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		return names;
 	}
 	
@@ -1193,28 +1108,22 @@ public class Olympiad
 	public int getLastNobleOlympiadPoints(int objId)
 	{
 		int result = 0;
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement("SELECT olympiad_points FROM olympiad_nobles_eom WHERE charId = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			final PreparedStatement statement = con.prepareStatement("SELECT olympiad_points FROM olympiad_nobles_eom WHERE charId = ?");
-			statement.setInt(1, objId);
-			final ResultSet rs = statement.executeQuery();
-			if (rs.first())
+			ps.setInt(1, objId);
+			try (ResultSet rs = ps.executeQuery())
 			{
-				result = rs.getInt(1);
+				if (rs.first())
+				{
+					result = rs.getInt(1);
+				}
 			}
-			rs.close();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Could not load last olympiad points:", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		return result;
 	}
 	
@@ -1355,22 +1264,15 @@ public class Olympiad
 	
 	protected void deleteNobles()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement(OLYMPIAD_DELETE_ALL))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			final PreparedStatement statement = con.prepareStatement(OLYMPIAD_DELETE_ALL);
 			statement.execute();
-			statement.close();
 		}
 		catch (SQLException e)
 		{
 			_log.warning("Olympiad System: Couldn't delete nobles from DB!");
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		_nobles.clear();
 	}
 	

+ 2 - 9
L2J_Server_BETA/java/com/l2jserver/gameserver/model/olympiad/OlympiadGameNormal.java

@@ -693,11 +693,9 @@ public abstract class OlympiadGameNormal extends AbstractOlympiadGame
 	
 	protected static final void saveResults(Participant one, Participant two, int _winner, long _startTime, long _fightTime, CompetitionType type)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("INSERT INTO olympiad_fights (charOneId, charTwoId, charOneClass, charTwoClass, winner, start, time, classed) values(?,?,?,?,?,?,?,?)"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("INSERT INTO olympiad_fights (charOneId, charTwoId, charOneClass, charTwoClass, winner, start, time, classed) values(?,?,?,?,?,?,?,?)");
 			statement.setInt(1, one.getObjectId());
 			statement.setInt(2, two.getObjectId());
 			statement.setInt(3, one.getBaseClass());
@@ -707,7 +705,6 @@ public abstract class OlympiadGameNormal extends AbstractOlympiadGame
 			statement.setLong(7, _fightTime);
 			statement.setInt(8, (type == CompetitionType.CLASSED ? 1 : 0));
 			statement.execute();
-			statement.close();
 		}
 		catch (SQLException e)
 		{
@@ -716,9 +713,5 @@ public abstract class OlympiadGameNormal extends AbstractOlympiadGame
 				_log.log(Level.SEVERE, "SQL exception while saving olympiad fight.", e);
 			}
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 }

+ 76 - 148
L2J_Server_BETA/java/com/l2jserver/gameserver/model/quest/Quest.java

@@ -1335,85 +1335,78 @@ public class Quest extends ManagedScript
 	 */
 	public static final void playerEnter(L2PcInstance player)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement invalidQuestData = con.prepareStatement("DELETE FROM character_quests WHERE charId = ? AND name = ?");
+			PreparedStatement invalidQuestDataVar = con.prepareStatement("DELETE FROM character_quests WHERE charId = ? AND name = ? AND var = ?");
+			PreparedStatement ps1 = con.prepareStatement("SELECT name, value FROM character_quests WHERE charId = ? AND var = ?"))
 		{
 			// Get list of quests owned by the player from database
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
-			PreparedStatement invalidQuestData = con.prepareStatement("DELETE FROM character_quests WHERE charId=? AND name=?");
-			PreparedStatement invalidQuestDataVar = con.prepareStatement("DELETE FROM character_quests WHERE charId=? AND name=? AND var=?");
 			
-			PreparedStatement statement = con.prepareStatement("SELECT name,value FROM character_quests WHERE charId=? AND var=?");
-			statement.setInt(1, player.getObjectId());
-			statement.setString(2, "<state>");
-			ResultSet rs = statement.executeQuery();
-			while (rs.next())
+			ps1.setInt(1, player.getObjectId());
+			ps1.setString(2, "<state>");
+			try (ResultSet rs = ps1.executeQuery())
 			{
-				// Get ID of the quest and ID of its state
-				String questId = rs.getString("name");
-				String statename = rs.getString("value");
-				
-				// Search quest associated with the ID
-				Quest q = QuestManager.getInstance().getQuest(questId);
-				if (q == null)
+				while (rs.next())
 				{
-					_log.finer("Unknown quest " + questId + " for player " + player.getName());
-					if (Config.AUTODELETE_INVALID_QUEST_DATA)
+					// Get ID of the quest and ID of its state
+					String questId = rs.getString("name");
+					String statename = rs.getString("value");
+					
+					// Search quest associated with the ID
+					Quest q = QuestManager.getInstance().getQuest(questId);
+					if (q == null)
 					{
-						invalidQuestData.setInt(1, player.getObjectId());
-						invalidQuestData.setString(2, questId);
-						invalidQuestData.executeUpdate();
+						_log.finer("Unknown quest " + questId + " for player " + player.getName());
+						if (Config.AUTODELETE_INVALID_QUEST_DATA)
+						{
+							invalidQuestData.setInt(1, player.getObjectId());
+							invalidQuestData.setString(2, questId);
+							invalidQuestData.executeUpdate();
+						}
+						continue;
 					}
-					continue;
+					
+					// Create a new QuestState for the player that will be added to the player's list of quests
+					new QuestState(q, player, State.getStateId(statename));
 				}
-				
-				// Create a new QuestState for the player that will be added to the player's list of quests
-				new QuestState(q, player, State.getStateId(statename));
 			}
-			rs.close();
-			invalidQuestData.close();
-			statement.close();
 			
 			// Get list of quests owned by the player from the DB in order to add variables used in the quest.
-			statement = con.prepareStatement("SELECT name,var,value FROM character_quests WHERE charId=? AND var<>?");
-			statement.setInt(1, player.getObjectId());
-			statement.setString(2, "<state>");
-			rs = statement.executeQuery();
-			while (rs.next())
+			try (PreparedStatement ps2 = con.prepareStatement("SELECT name, var, value FROM character_quests WHERE charId = ? AND var <> ?"))
 			{
-				String questId = rs.getString("name");
-				String var = rs.getString("var");
-				String value = rs.getString("value");
-				// Get the QuestState saved in the loop before
-				QuestState qs = player.getQuestState(questId);
-				if (qs == null)
+				ps2.setInt(1, player.getObjectId());
+				ps2.setString(2, "<state>");
+				try (ResultSet rs = ps2.executeQuery())
 				{
-					_log.finer("Lost variable " + var + " in quest " + questId + " for player " + player.getName());
-					if (Config.AUTODELETE_INVALID_QUEST_DATA)
+					while (rs.next())
 					{
-						invalidQuestDataVar.setInt(1, player.getObjectId());
-						invalidQuestDataVar.setString(2, questId);
-						invalidQuestDataVar.setString(3, var);
-						invalidQuestDataVar.executeUpdate();
+						String questId = rs.getString("name");
+						String var = rs.getString("var");
+						String value = rs.getString("value");
+						// Get the QuestState saved in the loop before
+						QuestState qs = player.getQuestState(questId);
+						if (qs == null)
+						{
+							_log.finer("Lost variable " + var + " in quest " + questId + " for player " + player.getName());
+							if (Config.AUTODELETE_INVALID_QUEST_DATA)
+							{
+								invalidQuestDataVar.setInt(1, player.getObjectId());
+								invalidQuestDataVar.setString(2, questId);
+								invalidQuestDataVar.setString(3, var);
+								invalidQuestDataVar.executeUpdate();
+							}
+							continue;
+						}
+						// Add parameter to the quest
+						qs.setInternal(var, value);
 					}
-					continue;
 				}
-				// Add parameter to the quest
-				qs.setInternal(var, value);
 			}
-			rs.close();
-			invalidQuestDataVar.close();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "could not insert char quest:", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
 		// events
 		for (String name : _allEventsS.keySet())
@@ -1431,25 +1424,18 @@ public class Quest extends ManagedScript
 	 */
 	public final void saveGlobalQuestVar(String var, String value)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("REPLACE INTO quest_global_data (quest_name,var,value) VALUES (?,?,?)"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("REPLACE INTO quest_global_data (quest_name,var,value) VALUES (?,?,?)");
 			statement.setString(1, getName());
 			statement.setString(2, var);
 			statement.setString(3, value);
 			statement.executeUpdate();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "could not insert global quest variable:", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -1464,30 +1450,23 @@ public class Quest extends ManagedScript
 	public final String loadGlobalQuestVar(String var)
 	{
 		String result = "";
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("SELECT value FROM quest_global_data WHERE quest_name = ? AND var = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement;
-			statement = con.prepareStatement("SELECT value FROM quest_global_data WHERE quest_name = ? AND var = ?");
 			statement.setString(1, getName());
 			statement.setString(2, var);
-			ResultSet rs = statement.executeQuery();
-			if (rs.first())
+			try (ResultSet rs = statement.executeQuery())
 			{
-				result = rs.getString(1);
+				if (rs.first())
+				{
+					result = rs.getString(1);
+				}
 			}
-			rs.close();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "could not load global quest variable:", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		return result;
 	}
 	
@@ -1497,24 +1476,17 @@ public class Quest extends ManagedScript
 	 */
 	public final void deleteGlobalQuestVar(String var)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("DELETE FROM quest_global_data WHERE quest_name = ? AND var = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("DELETE FROM quest_global_data WHERE quest_name = ? AND var = ?");
 			statement.setString(1, getName());
 			statement.setString(2, var);
 			statement.executeUpdate();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "could not delete global quest variable:", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -1522,24 +1494,16 @@ public class Quest extends ManagedScript
 	 */
 	public final void deleteAllGlobalQuestVars()
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("DELETE FROM quest_global_data WHERE quest_name = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement;
-			statement = con.prepareStatement("DELETE FROM quest_global_data WHERE quest_name = ?");
 			statement.setString(1, getName());
 			statement.executeUpdate();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "could not delete global quest variables:", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -1550,27 +1514,20 @@ public class Quest extends ManagedScript
 	 */
 	public static void createQuestVarInDb(QuestState qs, String var, String value)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("INSERT INTO character_quests (charId,name,var,value) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE value=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("INSERT INTO character_quests (charId,name,var,value) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE value=?");
 			statement.setInt(1, qs.getPlayer().getObjectId());
 			statement.setString(2, qs.getQuestName());
 			statement.setString(3, var);
 			statement.setString(4, value);
 			statement.setString(5, value);
 			statement.executeUpdate();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "could not insert char quest:", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -1581,26 +1538,19 @@ public class Quest extends ManagedScript
 	 */
 	public static void updateQuestVarInDb(QuestState qs, String var, String value)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("UPDATE character_quests SET value=? WHERE charId=? AND name=? AND var = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("UPDATE character_quests SET value=? WHERE charId=? AND name=? AND var = ?");
 			statement.setString(1, value);
 			statement.setInt(2, qs.getPlayer().getObjectId());
 			statement.setString(3, qs.getQuestName());
 			statement.setString(4, var);
 			statement.executeUpdate();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "could not update char quest:", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -1610,26 +1560,18 @@ public class Quest extends ManagedScript
 	 */
 	public static void deleteQuestVarInDb(QuestState qs, String var)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("DELETE FROM character_quests WHERE charId=? AND name=? AND var=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement;
-			statement = con.prepareStatement("DELETE FROM character_quests WHERE charId=? AND name=? AND var=?");
 			statement.setInt(1, qs.getPlayer().getObjectId());
 			statement.setString(2, qs.getQuestName());
 			statement.setString(3, var);
 			statement.executeUpdate();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "could not delete char quest:", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -1639,35 +1581,21 @@ public class Quest extends ManagedScript
 	 */
 	public static void deleteQuestInDb(QuestState qs, boolean repeatable)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement(repeatable ? QUEST_DELETE_FROM_CHAR_QUERY : QUEST_DELETE_FROM_CHAR_QUERY_NON_REPEATABLE_QUERY))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			final PreparedStatement statement;
-			if (repeatable)
-			{
-				statement = con.prepareStatement(QUEST_DELETE_FROM_CHAR_QUERY);
-				statement.setInt(1, qs.getPlayer().getObjectId());
-				statement.setString(2, qs.getQuestName());
-			}
-			else
+			ps.setInt(1, qs.getPlayer().getObjectId());
+			ps.setString(2, qs.getQuestName());
+			if (!repeatable)
 			{
-				statement = con.prepareStatement(QUEST_DELETE_FROM_CHAR_QUERY_NON_REPEATABLE_QUERY);
-				statement.setInt(1, qs.getPlayer().getObjectId());
-				statement.setString(2, qs.getQuestName());
-				statement.setString(3, "<state>");
+				ps.setString(3, "<state>");
 			}
-			statement.executeUpdate();
-			statement.close();
+			ps.executeUpdate();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "could not delete char quest:", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**

+ 13 - 33
L2J_Server_BETA/java/com/l2jserver/gameserver/model/quest/QuestState.java

@@ -401,25 +401,18 @@ public final class QuestState
 	// TODO: these methods should not be here, they could be used by other classes to save some variables, but they can't because they require to create a QuestState first.
 	public final void saveGlobalQuestVar(String var, String value)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("REPLACE INTO character_quest_global_data (charId, var, value) VALUES (?, ?, ?)"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("REPLACE INTO character_quest_global_data (charId, var, value) VALUES (?, ?, ?)");
 			statement.setInt(1, _player.getObjectId());
 			statement.setString(2, var);
 			statement.setString(3, value);
 			statement.executeUpdate();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Could not insert player's global quest variable: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -435,29 +428,23 @@ public final class QuestState
 	public final String getGlobalQuestVar(String var)
 	{
 		String result = "";
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement ps = con.prepareStatement("SELECT value FROM character_quest_global_data WHERE charId = ? AND var = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("SELECT value FROM character_quest_global_data WHERE charId = ? AND var = ?");
-			statement.setInt(1, _player.getObjectId());
-			statement.setString(2, var);
-			ResultSet rs = statement.executeQuery();
-			if (rs.first())
+			ps.setInt(1, _player.getObjectId());
+			ps.setString(2, var);
+			try (ResultSet rs = ps.executeQuery())
 			{
-				result = rs.getString(1);
+				if (rs.first())
+				{
+					result = rs.getString(1);
+				}
 			}
-			rs.close();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "Could not load player's global quest variable: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		return result;
 	}
 	
@@ -467,24 +454,17 @@ public final class QuestState
 	 */
 	public final void deleteGlobalQuestVar(String var)
 	{
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("DELETE FROM character_quest_global_data WHERE charId = ? AND var = ?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("DELETE FROM character_quest_global_data WHERE charId = ? AND var = ?");
 			statement.setInt(1, _player.getObjectId());
 			statement.setString(2, var);
 			statement.executeUpdate();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.WARNING, "could not delete player's global quest variable; charId = " + _player.getObjectId() + ", variable name = " + var + ". Exception: " + e.getMessage(), e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**

+ 42 - 67
L2J_Server_BETA/java/com/l2jserver/gameserver/network/L2GameClient.java

@@ -301,61 +301,54 @@ public final class L2GameClient extends MMOClient<MMOConnection<L2GameClient>> i
 			return -1;
 		}
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("SELECT clanId FROM characters WHERE charId=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
-			PreparedStatement statement = con.prepareStatement("SELECT clanId FROM characters WHERE charId=?");
 			statement.setInt(1, objid);
-			ResultSet rs = statement.executeQuery();
-			
-			rs.next();
-			
-			int clanId = rs.getInt(1);
 			byte answer = 0;
-			if (clanId != 0)
+			try (ResultSet rs = statement.executeQuery())
 			{
-				L2Clan clan = ClanTable.getInstance().getClan(clanId);
-				
-				if (clan == null)
-				{
-					answer = 0; // jeezes!
-				}
-				else if (clan.getLeaderId() == objid)
-				{
-					answer = 2;
-				}
-				else
+				int clanId = rs.next() ? rs.getInt(1) : 0;
+				if (clanId != 0)
 				{
-					answer = 1;
-				}
-			}
-			
-			rs.close();
-			statement.close();
-			
-			// Setting delete time
-			if (answer == 0)
-			{
-				if (Config.DELETE_DAYS == 0)
-				{
-					deleteCharByObjId(objid);
+					L2Clan clan = ClanTable.getInstance().getClan(clanId);
+					
+					if (clan == null)
+					{
+						answer = 0; // jeezes!
+					}
+					else if (clan.getLeaderId() == objid)
+					{
+						answer = 2;
+					}
+					else
+					{
+						answer = 1;
+					}
 				}
-				else
+				
+				// Setting delete time
+				if (answer == 0)
 				{
-					statement = con.prepareStatement("UPDATE characters SET deletetime=? WHERE charId=?");
-					statement.setLong(1, System.currentTimeMillis() + (Config.DELETE_DAYS * 86400000L)); // 24*60*60*1000 = 86400000
-					statement.setInt(2, objid);
-					statement.execute();
-					statement.close();
+					if (Config.DELETE_DAYS == 0)
+					{
+						deleteCharByObjId(objid);
+					}
+					else
+					{
+						try (PreparedStatement ps2 = con.prepareStatement("UPDATE characters SET deletetime=? WHERE charId=?"))
+						{
+							ps2.setLong(1, System.currentTimeMillis() + (Config.DELETE_DAYS * 86400000L)); // 24*60*60*1000 = 86400000
+							ps2.setInt(2, objid);
+							ps2.execute();
+						}
+					}
+					
+					LogRecord record = new LogRecord(Level.WARNING, "Delete");
+					record.setParameters(new Object[] { objid, this });
+					_logAccounting.log(record);
 				}
-				
-				LogRecord record = new LogRecord(Level.WARNING, "Delete");
-				record.setParameters(new Object[] { objid, this });
-				_logAccounting.log(record);
 			}
-			
 			return answer;
 		}
 		catch (Exception e)
@@ -363,10 +356,6 @@ public final class L2GameClient extends MMOClient<MMOConnection<L2GameClient>> i
 			_log.log(Level.SEVERE, "Error updating delete time of character.", e);
 			return -1;
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	/**
@@ -401,23 +390,16 @@ public final class L2GameClient extends MMOClient<MMOConnection<L2GameClient>> i
 			return;
 		}
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("UPDATE characters SET deletetime=0 WHERE charId=?"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement = con.prepareStatement("UPDATE characters SET deletetime=0 WHERE charId=?");
 			statement.setInt(1, objid);
 			statement.execute();
-			statement.close();
 		}
 		catch (Exception e)
 		{
 			_log.log(Level.SEVERE, "Error restoring character.", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 		
 		final LogRecord record = new LogRecord(Level.WARNING, "Restore");
 		record.setParameters(new Object[] { objid, this });
@@ -433,11 +415,8 @@ public final class L2GameClient extends MMOClient<MMOConnection<L2GameClient>> i
 		
 		CharNameTable.getInstance().removeName(objid);
 		
-		Connection con = null;
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			
 			PreparedStatement statement = con.prepareStatement("DELETE FROM character_contacts WHERE charId=? OR contactId=?");
 			statement.setInt(1, objid);
 			statement.setInt(2, objid);
@@ -563,10 +542,6 @@ public final class L2GameClient extends MMOClient<MMOConnection<L2GameClient>> i
 		{
 			_log.log(Level.SEVERE, "Error deleting character.", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	public L2PcInstance loadCharFromDisk(int charslot)

+ 4 - 11
L2J_Server_BETA/java/com/l2jserver/gameserver/network/clientpackets/RequestAnswerFriendInvite.java

@@ -48,21 +48,18 @@ public final class RequestAnswerFriendInvite extends L2GameClientPacket
 			
 			if (_response == 1)
 			{
-				Connection con = null;
-				try
+				try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+					PreparedStatement statement = con.prepareStatement("INSERT INTO character_friends (charId, friendId) VALUES (?, ?), (?, ?)"))
 				{
-					con = L2DatabaseFactory.getInstance().getConnection();
-					PreparedStatement statement = con.prepareStatement("INSERT INTO character_friends (charId, friendId) VALUES (?, ?), (?, ?)");
 					statement.setInt(1, requestor.getObjectId());
 					statement.setInt(2, player.getObjectId());
 					statement.setInt(3, player.getObjectId());
 					statement.setInt(4, requestor.getObjectId());
 					statement.execute();
-					statement.close();
 					SystemMessage msg = SystemMessage.getSystemMessage(SystemMessageId.YOU_HAVE_SUCCEEDED_INVITING_FRIEND);
 					requestor.sendPacket(msg);
 					
-					//Player added to your friendlist
+					//Player added to your friend list
 					msg = SystemMessage.getSystemMessage(SystemMessageId.S1_ADDED_TO_FRIENDS);
 					msg.addString(player.getName());
 					requestor.sendPacket(msg);
@@ -74,7 +71,7 @@ public final class RequestAnswerFriendInvite extends L2GameClientPacket
 					player.sendPacket(msg);
 					player.getFriendList().add(requestor.getObjectId());
 					
-					//Send notificacions for both player in order to show them online
+					//Send notifications for both player in order to show them online
 					player.sendPacket(new FriendPacket(true, requestor.getObjectId()));
 					requestor.sendPacket(new FriendPacket(true, player.getObjectId()));
 				}
@@ -82,10 +79,6 @@ public final class RequestAnswerFriendInvite extends L2GameClientPacket
 				{
 					_log.log(Level.WARNING, "Could not add friend objectid: "+ e.getMessage(), e);
 				}
-				finally
-				{
-					L2DatabaseFactory.close(con);
-				}
 			}
 			else
 			{

+ 7 - 15
L2J_Server_BETA/java/com/l2jserver/gameserver/network/clientpackets/RequestDestroyItem.java

@@ -145,29 +145,21 @@ public final class RequestDestroyItem extends L2GameClientPacket
 		
 		if (itemToRemove.getItem().isPetItem())
 		{
-			Connection con = null;
-			try
+			if (activeChar.getPet() != null && activeChar.getPet().getControlObjectId() == _objectId)
+			{
+				activeChar.getPet().unSummon(activeChar);
+			}
+			
+			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+				PreparedStatement statement = con.prepareStatement("DELETE FROM pets WHERE item_obj_id=?"))
 			{
-				if (activeChar.getPet() != null && activeChar.getPet().getControlObjectId() == _objectId)
-				{
-					activeChar.getPet().unSummon(activeChar);
-				}
-				
-				// if it's a pet control item, delete the pet
-				con = L2DatabaseFactory.getInstance().getConnection();
-				PreparedStatement statement = con.prepareStatement("DELETE FROM pets WHERE item_obj_id=?");
 				statement.setInt(1, _objectId);
 				statement.execute();
-				statement.close();
 			}
 			catch (Exception e)
 			{
 				_log.log(Level.WARNING, "could not delete pet objectid: ", e);
 			}
-			finally
-			{
-				L2DatabaseFactory.close(con);
-			}
 		}
 		if (itemToRemove.isTimeLimitedItem())
 			itemToRemove.endOfLife();

+ 3 - 12
L2J_Server_BETA/java/com/l2jserver/gameserver/network/clientpackets/RequestFriendDel.java

@@ -70,21 +70,16 @@ public final class RequestFriendDel extends L2GameClientPacket{
 			return;
 		}
 		
-		Connection con = null;
-		
-		try
+		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
+			PreparedStatement statement = con.prepareStatement("DELETE FROM character_friends WHERE (charId=? AND friendId=?) OR (charId=? AND friendId=?)"))
 		{
-			con = L2DatabaseFactory.getInstance().getConnection();
-			PreparedStatement statement;
-			statement = con.prepareStatement("DELETE FROM character_friends WHERE (charId=? AND friendId=?) OR (charId=? AND friendId=?)");
 			statement.setInt(1, activeChar.getObjectId());
 			statement.setInt(2, id);
 			statement.setInt(3, id);
 			statement.setInt(4, activeChar.getObjectId());
 			statement.execute();
-			statement.close();
 			
-			// Player deleted from your friendlist
+			// Player deleted from your friend list
 			sm = SystemMessage.getSystemMessage(SystemMessageId.S1_HAS_BEEN_DELETED_FROM_YOUR_FRIENDS_LIST);
 			sm.addString(_name);
 			activeChar.sendPacket(sm);
@@ -103,10 +98,6 @@ public final class RequestFriendDel extends L2GameClientPacket{
 		{
 			_log.log(Level.WARNING, "could not del friend objectid: ", e);
 		}
-		finally
-		{
-			L2DatabaseFactory.close(con);
-		}
 	}
 	
 	@Override

Alguns arquivos não foram mostrados porque muitos arquivos mudaram nesse diff