/**
	 * Load guards.

	 */
	private void loadSiegeGuard()
	{
		try (Connection 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
				statement.setInt(2, 1);
			else
				statement.setInt(2, 0);
			ResultSet rs = statement.executeQuery();

			L2Spawn spawn1;
			L2NpcTemplate template1;

			while (rs.next())
			{
				template1 = NpcTable.getInstance().getTemplate(rs.getInt("npcId"));
				if (template1 != null)
				{
					spawn1 = new L2Spawn(template1);
					spawn1.setAmount(1);
					spawn1.setLocx(rs.getInt("x"));
					spawn1.setLocy(rs.getInt("y"));
					spawn1.setLocz(rs.getInt("z"));
					spawn1.setHeading(rs.getInt("heading"));
					spawn1.setRespawnDelay(rs.getInt("respawnDelay"));
					spawn1.setLocation(0);

					_siegeGuardSpawn.add(spawn1);
				}
				else
				{
					_log.warning("Missing npc data in npc table for id: " + rs.getInt("npcId"));
				}
			}
			rs.close();
			statement.close();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Error loading siege guard for castle " + getCastle().getName() + ": " + e.getMessage(), e);
		}
	}

/**
	 * Load guards.

	 */
	private void loadSiegeGuard()
	{
		Connection con = null;
		try
		{
			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
				statement.setInt(2, 1);
			else
				statement.setInt(2, 0);
			ResultSet rs = statement.executeQuery();

			L2Spawn spawn1;
			L2NpcTemplate template1;

			while (rs.next())
			{
				template1 = NpcTable.getInstance().getTemplate(rs.getInt("npcId"));
				if (template1 != null)
				{
					spawn1 = new L2Spawn(template1);
					spawn1.setAmount(1);
					spawn1.setLocx(rs.getInt("x"));
					spawn1.setLocy(rs.getInt("y"));
					spawn1.setLocz(rs.getInt("z"));
					spawn1.setHeading(rs.getInt("heading"));
					spawn1.setRespawnDelay(rs.getInt("respawnDelay"));
					spawn1.setLocation(0);

					_siegeGuardSpawn.add(spawn1);
				}
				else
				{
					_log.warning("Missing npc data in npc table for id: " + rs.getInt("npcId"));
				}
			}
			rs.close();
			statement.close();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Error loading siege guard for castle " + getCastle().getName() + ": " + e.getMessage(), e);
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection()) in method private loadSiegeGuard() : void from class com.l2jserver.gameserver.instancemanager.SiegeGuardManager


/**
	 * Save guards.

	 * @param x
	 * @param y
	 * @param z
	 * @param heading
	 * @param npcId
	 * @param isHire
	 */
	private void saveSiegeGuard(int x, int y, int z, int heading, int npcId, int isHire)
	{
		try (Connection 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);
			statement.setInt(3, x);
			statement.setInt(4, y);
			statement.setInt(5, z);
			statement.setInt(6, heading);
			statement.setInt(7, (isHire == 1 ? 0 : 600));
			statement.setInt(8, isHire);
			statement.execute();
			statement.close();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Error adding siege guard for castle " + getCastle().getName() + ": " + e.getMessage(), e);
		}
	}

/**
	 * Save guards.

	 * @param x
	 * @param y
	 * @param z
	 * @param heading
	 * @param npcId
	 * @param isHire
	 */
	private void saveSiegeGuard(int x, int y, int z, int heading, int npcId, int isHire)
	{
		Connection con = null;
		try
		{
			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);
			statement.setInt(3, x);
			statement.setInt(4, y);
			statement.setInt(5, z);
			statement.setInt(6, heading);
			statement.setInt(7, (isHire == 1 ? 0 : 600));
			statement.setInt(8, isHire);
			statement.execute();
			statement.close();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Error adding siege guard for castle " + getCastle().getName() + ": " + e.getMessage(), e);
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection()) in method private saveSiegeGuard(x int, y int, z int, heading int, npcId int, isHire int) : void from class com.l2jserver.gameserver.instancemanager.SiegeGuardManager


	/**
	 * @param clan The L2Clan of the player
	 * @param castleid
	 * @return true if the clan is registered or owner of a castle
	 */
	public final boolean checkIsRegistered(L2Clan clan, int castleid)
	{
		if (clan == null)
			return false;

		if (clan.getCastleId() > 0)
			return true;

		boolean register = false;
		try (Connection 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);
			ResultSet rs = statement.executeQuery();

			while (rs.next())
			{
				register = true;
				break;
			}

			rs.close();
			statement.close();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Exception: checkIsRegistered(): " + e.getMessage() ,e);
		}
		return register;
	}

	/**
	 * @param clan The L2Clan of the player
	 * @param castleid
	 * @return true if the clan is registered or owner of a castle
	 */
	public final boolean checkIsRegistered(L2Clan clan, int castleid)
	{
		if (clan == null)
			return false;

		if (clan.getCastleId() > 0)
			return true;

		Connection con = null;
		boolean register = false;
		try
		{
			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);
			ResultSet rs = statement.executeQuery();

			while (rs.next())
			{
				register = true;
				break;
			}

			rs.close();
			statement.close();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Exception: checkIsRegistered(): " + e.getMessage() ,e);
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
		return register;
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection()) in method public checkIsRegistered(clan L2Clan, castleid int) : boolean from class com.l2jserver.gameserver.instancemanager.SiegeManager


	private void changeRegistration(int castleId, int objId, boolean delete)
	{
		final String query = delete ? DELETE : INSERT;
		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement(query))
		{
			statement.setInt(1, castleId);
			statement.setInt(2, objId);
			statement.execute();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Exception: Territory War registration: " + e.getMessage(), e);
		}
	}

	private void changeRegistration(int castleId, int objId, boolean delete)
	{
		Connection con = null;
		try
		{
			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);
		}
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection(); PreparedStatement statement=con.prepareStatement(query)) in method private changeRegistration(castleId int, objId int, delete boolean) : void from class com.l2jserver.gameserver.instancemanager.TerritoryWarManager


	private void updateTerritoryData(Territory ter)
	{
		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
		{
			PreparedStatement statement = con.prepareStatement("UPDATE territories SET ownedWardIds=? WHERE territoryId=?");
			StringBuilder wardList = new StringBuilder();
			for (int i : ter.getOwnedWardIds())
				wardList.append(i + ";");
			statement.setString(1, wardList.toString());
			statement.setInt(2, ter.getTerritoryId());
			statement.execute();
			statement.close();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Exception: Territory Data update: " + e.getMessage(), e);
		}
	}

	private void updateTerritoryData(Territory ter)
	{
		Connection con = null;
		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("UPDATE territories SET ownedWardIds=? WHERE territoryId=?");
			StringBuilder wardList = new StringBuilder();
			for (int i : ter.getOwnedWardIds())
				wardList.append(i + ";");
			statement.setString(1, wardList.toString());
			statement.setInt(2, ter.getTerritoryId());
			statement.execute();
			statement.close();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Exception: Territory Data update: " + e.getMessage(), e);
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection()) in method private updateTerritoryData(ter Territory) : void from class com.l2jserver.gameserver.instancemanager.TerritoryWarManager


	private final void load()
	{
		try (InputStream is = new FileInputStream(new File(Config.TW_CONFIGURATION_FILE)))
		{
			L2Properties territoryWarSettings = new L2Properties();
			territoryWarSettings.load(is);

			// Siege setting
			DEFENDERMAXCLANS = Integer.decode(territoryWarSettings.getProperty("DefenderMaxClans", "500"));
			DEFENDERMAXPLAYERS = Integer.decode(territoryWarSettings.getProperty("DefenderMaxPlayers", "500"));
			CLANMINLEVEL = Integer.decode(territoryWarSettings.getProperty("ClanMinLevel", "0"));
			PLAYERMINLEVEL = Integer.decode(territoryWarSettings.getProperty("PlayerMinLevel", "40"));
			WARLENGTH = Long.decode(territoryWarSettings.getProperty("WarLength", "120")) * 60000;
			PLAYER_WITH_WARD_CAN_BE_KILLED_IN_PEACEZONE = Boolean.parseBoolean(territoryWarSettings.getProperty("PlayerWithWardCanBeKilledInPeaceZone", "False"));
			SPAWN_WARDS_WHEN_TW_IS_NOT_IN_PROGRESS = Boolean.parseBoolean(territoryWarSettings.getProperty("SpawnWardsWhenTWIsNotInProgress", "False"));
			RETURN_WARDS_WHEN_TW_STARTS = Boolean.parseBoolean(territoryWarSettings.getProperty("ReturnWardsWhenTWStarts", "False"));
			MINTWBADGEFORNOBLESS = Integer.decode(territoryWarSettings.getProperty("MinTerritoryBadgeForNobless", "100"));
			MINTWBADGEFORSTRIDERS = Integer.decode(territoryWarSettings.getProperty("MinTerritoryBadgeForStriders", "50"));
			MINTWBADGEFORBIGSTRIDER = Integer.decode(territoryWarSettings.getProperty("MinTerritoryBadgeForBigStrider", "80"));

			try (Connection con = L2DatabaseFactory.getInstance().getConnection())
			{
				PreparedStatement statement = con.prepareStatement("SELECT * FROM territory_spawnlist");
				ResultSet rs = statement.executeQuery();

				while (rs.next())
				{
					int castleId = rs.getInt("castleId");
					int npcId = rs.getInt("npcId");
					Location loc = new Location(rs.getInt("x"),rs.getInt("y"),rs.getInt("z"),rs.getInt("heading"));
					int spawnType = rs.getInt("spawnType");
					if (!_territoryList.containsKey(castleId))
						_territoryList.put(castleId, new Territory(castleId));
					switch(spawnType)
					{
						case 0: // town npcs
						case 1: // fortress npcs
						case 2: // castle npcs
							_territoryList.get(castleId).getSpawnList().add(new TerritoryNPCSpawn(castleId, loc, npcId, spawnType, null));
							break;
						case 3: // ward spawns
							_territoryList.get(castleId).addWardSpawnPlace(loc);
							break;
						default:
							_log.warning("Territory War Manager: Unknown npc type for " + rs.getInt("id"));
					}
				}

				rs.close();
				statement.close();
			}
			catch (Exception e)
			{
				_log.log(Level.WARNING, "Territory War Manager: SpawnList error: " + e.getMessage(), e);
			}

			try (Connection con = L2DatabaseFactory.getInstance().getConnection())
			{
				PreparedStatement statement = con.prepareStatement("SELECT * FROM territories");
				ResultSet rs = statement.executeQuery();

				while (rs.next())
				{
					int castleId = rs.getInt("castleId");
					int fortId = rs.getInt("fortId");
					String ownedWardIds = rs.getString("OwnedWardIds");

					Territory t = _territoryList.get(castleId);
					if (t != null)
					{
						t._fortId = fortId;
						if (CastleManager.getInstance().getCastleById(castleId).getOwnerId() > 0)
						{
							t.setOwnerClan(ClanTable.getInstance().getClan(CastleManager.getInstance().getCastleById(castleId).getOwnerId()));
							t.changeNPCsSpawn(0, true);
						}

						if (!ownedWardIds.isEmpty())
						{
							for(String wardId:ownedWardIds.split(";"))
								if (Integer.parseInt(wardId) > 0)
									addTerritoryWard(Integer.parseInt(wardId), castleId, 0, false);
						}
					}
				}
				rs.close();
				statement.close();
			}
			catch (Exception e)
			{
				_log.log(Level.WARNING, "Territory War Manager: territory list error(): " + e.getMessage(), e);
			}

			try (Connection con = L2DatabaseFactory.getInstance().getConnection())
			{
				PreparedStatement statement = con.prepareStatement("SELECT * FROM territory_registrations");
				ResultSet rs = statement.executeQuery();

				while (rs.next())
				{
					int castleId = rs.getInt("castleId");
					int registeredId = rs.getInt("registeredId");
					if (ClanTable.getInstance().getClan(registeredId) != null)
					{
						if (_registeredClans.get(castleId) == null)
							_registeredClans.put(castleId, new FastList<L2Clan>());
						_registeredClans.get(castleId).add(ClanTable.getInstance().getClan(registeredId));
					}
					else
					{
						if (_registeredMercenaries.get(castleId) == null)
							_registeredMercenaries.put(castleId, new FastList<Integer>());
						_registeredMercenaries.get(castleId).add(registeredId);
					}
				}
				rs.close();
				statement.close();
			}
			catch (Exception e)
			{
				_log.log(Level.WARNING, "Territory War Manager: registration list error: " + e.getMessage(), e);
			}
		}
		catch (Exception e)
		{
			//_initialized = false;
			_log.log(Level.WARNING, "Error while loading Territory War Manager! " + e.getMessage(), e);
		}
	}

	private final void load()
	{

		try (InputStream is = new FileInputStream(new File(Config.TW_CONFIGURATION_FILE)))
		{
			L2Properties territoryWarSettings = new L2Properties();
			territoryWarSettings.load(is);

			// Siege setting
			DEFENDERMAXCLANS = Integer.decode(territoryWarSettings.getProperty("DefenderMaxClans", "500"));
			DEFENDERMAXPLAYERS = Integer.decode(territoryWarSettings.getProperty("DefenderMaxPlayers", "500"));
			CLANMINLEVEL = Integer.decode(territoryWarSettings.getProperty("ClanMinLevel", "0"));
			PLAYERMINLEVEL = Integer.decode(territoryWarSettings.getProperty("PlayerMinLevel", "40"));
			WARLENGTH = Long.decode(territoryWarSettings.getProperty("WarLength", "120")) * 60000;
			PLAYER_WITH_WARD_CAN_BE_KILLED_IN_PEACEZONE = Boolean.parseBoolean(territoryWarSettings.getProperty("PlayerWithWardCanBeKilledInPeaceZone", "False"));
			SPAWN_WARDS_WHEN_TW_IS_NOT_IN_PROGRESS = Boolean.parseBoolean(territoryWarSettings.getProperty("SpawnWardsWhenTWIsNotInProgress", "False"));
			RETURN_WARDS_WHEN_TW_STARTS = Boolean.parseBoolean(territoryWarSettings.getProperty("ReturnWardsWhenTWStarts", "False"));
			MINTWBADGEFORNOBLESS = Integer.decode(territoryWarSettings.getProperty("MinTerritoryBadgeForNobless", "100"));
			MINTWBADGEFORSTRIDERS = Integer.decode(territoryWarSettings.getProperty("MinTerritoryBadgeForStriders", "50"));
			MINTWBADGEFORBIGSTRIDER = Integer.decode(territoryWarSettings.getProperty("MinTerritoryBadgeForBigStrider", "80"));

			Connection con = null;
			try
			{
				con = L2DatabaseFactory.getInstance().getConnection();
				PreparedStatement statement = con.prepareStatement("SELECT * FROM territory_spawnlist");
				ResultSet rs = statement.executeQuery();

				while (rs.next())
				{
					int castleId = rs.getInt("castleId");
					int npcId = rs.getInt("npcId");
					Location loc = new Location(rs.getInt("x"),rs.getInt("y"),rs.getInt("z"),rs.getInt("heading"));
					int spawnType = rs.getInt("spawnType");
					if (!_territoryList.containsKey(castleId))
						_territoryList.put(castleId, new Territory(castleId));
					switch(spawnType)
					{
						case 0: // town npcs
						case 1: // fortress npcs
						case 2: // castle npcs
							_territoryList.get(castleId).getSpawnList().add(new TerritoryNPCSpawn(castleId, loc, npcId, spawnType, null));
							break;
						case 3: // ward spawns
							_territoryList.get(castleId).addWardSpawnPlace(loc);
							break;
						default:
							_log.warning("Territory War Manager: Unknown npc type for " + rs.getInt("id"));
					}
				}

				rs.close();
				statement.close();
			}
			catch (Exception e)
			{
				_log.log(Level.WARNING, "Territory War Manager: SpawnList error: " + e.getMessage(), e);
			}
			finally
			{
				L2DatabaseFactory.close(con);
			}
			try
			{
				con = L2DatabaseFactory.getInstance().getConnection();
				PreparedStatement statement = con.prepareStatement("SELECT * FROM territories");
				ResultSet rs = statement.executeQuery();

				while (rs.next())
				{
					int castleId = rs.getInt("castleId");
					int fortId = rs.getInt("fortId");
					String ownedWardIds = rs.getString("OwnedWardIds");

					Territory t = _territoryList.get(castleId);
					if (t != null)
					{
						t._fortId = fortId;
						if (CastleManager.getInstance().getCastleById(castleId).getOwnerId() > 0)
						{
							t.setOwnerClan(ClanTable.getInstance().getClan(CastleManager.getInstance().getCastleById(castleId).getOwnerId()));
							t.changeNPCsSpawn(0, true);
						}

						if (!ownedWardIds.isEmpty())
						{
							for(String wardId:ownedWardIds.split(";"))
								if (Integer.parseInt(wardId) > 0)
									addTerritoryWard(Integer.parseInt(wardId), castleId, 0, false);
						}
					}
				}
				rs.close();
				statement.close();
			}
			catch (Exception e)
			{
				_log.log(Level.WARNING, "Territory War Manager: territory list error(): " + e.getMessage(), e);
			}
			finally
			{
				L2DatabaseFactory.close(con);
			}
			try
			{
				con = L2DatabaseFactory.getInstance().getConnection();
				PreparedStatement statement = con.prepareStatement("SELECT * FROM territory_registrations");
				ResultSet rs = statement.executeQuery();

				while (rs.next())
				{
					int castleId = rs.getInt("castleId");
					int registeredId = rs.getInt("registeredId");
					if (ClanTable.getInstance().getClan(registeredId) != null)
					{
						if (_registeredClans.get(castleId) == null)
							_registeredClans.put(castleId, new FastList<L2Clan>());
						_registeredClans.get(castleId).add(ClanTable.getInstance().getClan(registeredId));
					}
					else
					{
						if (_registeredMercenaries.get(castleId) == null)
							_registeredMercenaries.put(castleId, new FastList<Integer>());
						_registeredMercenaries.get(castleId).add(registeredId);
					}
				}
				rs.close();
				statement.close();
			}
			catch (Exception e)
			{
				_log.log(Level.WARNING, "Territory War Manager: registration list error: " + e.getMessage(), e);
			}
			finally
			{
				L2DatabaseFactory.close(con);
			}
		}
		catch (Exception e)
		{
			//_initialized = false;
			_log.log(Level.WARNING, "Error while loading Territory War Manager! " + e.getMessage(), e);
		}
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection()) in method private load() : void from class com.l2jserver.gameserver.instancemanager.TerritoryWarManager


		@Override
		public void run()
		{

			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
				Statement statement = con.createStatement();
				ResultSet rset = statement.executeQuery(SELECT_LAST_LOTTERY))
			{
				if (rset.next())
				{
					_number = rset.getInt("idnr");

					if (rset.getInt("finished") == 1)
					{
						_number++;
						_prize = rset.getLong("newprize");
					}
					else
					{
						_prize = rset.getLong("prize");
						_enddate = rset.getLong("enddate");

						if (_enddate <= System.currentTimeMillis() + 2 * MINUTE)
						{
							(new finishLottery()).run();
							return;
						}

						if (_enddate > System.currentTimeMillis())
						{
							_isStarted = true;
							ThreadPoolManager.getInstance().scheduleGeneral(new finishLottery(), _enddate - System.currentTimeMillis());

							if (_enddate > System.currentTimeMillis() + 12 * MINUTE)
							{
								_isSellingTickets = true;
								ThreadPoolManager.getInstance().scheduleGeneral(new stopSellingTickets(), _enddate - System.currentTimeMillis() - 10 * MINUTE);
							}
							return;
						}
					}
				}
			}
			catch (SQLException e)
			{
				_log.log(Level.WARNING, "Lottery: Could not restore lottery data: " + e.getMessage(), e);
			}

			if (Config.DEBUG)
				_log.info("Lottery: Starting ticket sell for lottery #" + getId() + ".");
			_isSellingTickets = true;
			_isStarted = true;

			Announcements.getInstance().announceToAll("Lottery tickets are now available for Lucky Lottery #" + getId() + ".");
			Calendar finishtime = Calendar.getInstance();
			finishtime.setTimeInMillis(_enddate);
			finishtime.set(Calendar.MINUTE, 0);
			finishtime.set(Calendar.SECOND, 0);

			if (finishtime.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
			{
				finishtime.set(Calendar.HOUR_OF_DAY, 19);
				_enddate = finishtime.getTimeInMillis();
				_enddate += 604800000;
			}
			else
			{
				finishtime.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
				finishtime.set(Calendar.HOUR_OF_DAY, 19);
				_enddate = finishtime.getTimeInMillis();
			}

			ThreadPoolManager.getInstance().scheduleGeneral(new stopSellingTickets(), _enddate - System.currentTimeMillis() - 10 * MINUTE);
			ThreadPoolManager.getInstance().scheduleGeneral(new finishLottery(), _enddate - System.currentTimeMillis());

			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
				PreparedStatement 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();
			}
			catch (SQLException e)
			{
				_log.log(Level.WARNING, "Lottery: Could not store new lottery data: " + e.getMessage(), e);
			}
		}

		@Override
		public void run()
		{
			Connection con = null;
			PreparedStatement statement;
			try
			{
				con = L2DatabaseFactory.getInstance().getConnection();
				statement = con.prepareStatement(SELECT_LAST_LOTTERY);
				ResultSet rset = statement.executeQuery();

				if (rset.next())
				{
					_number = rset.getInt("idnr");

					if (rset.getInt("finished") == 1)
					{
						_number++;
						_prize = rset.getLong("newprize");
					}
					else
					{
						_prize = rset.getLong("prize");
						_enddate = rset.getLong("enddate");

						if (_enddate <= System.currentTimeMillis() + 2 * MINUTE)
						{
							(new finishLottery()).run();
							rset.close();
							statement.close();
							return;
						}

						if (_enddate > System.currentTimeMillis())
						{
							_isStarted = true;
							ThreadPoolManager.getInstance().scheduleGeneral(new finishLottery(), _enddate - System.currentTimeMillis());

							if (_enddate > System.currentTimeMillis() + 12 * MINUTE)
							{
								_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() + ".");
			_isSellingTickets = true;
			_isStarted = true;

			Announcements.getInstance().announceToAll("Lottery tickets are now available for Lucky Lottery #" + getId() + ".");
			Calendar finishtime = Calendar.getInstance();
			finishtime.setTimeInMillis(_enddate);
			finishtime.set(Calendar.MINUTE, 0);
			finishtime.set(Calendar.SECOND, 0);

			if (finishtime.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
			{
				finishtime.set(Calendar.HOUR_OF_DAY, 19);
				_enddate = finishtime.getTimeInMillis();
				_enddate += 604800000;
			}
			else
			{
				finishtime.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
				finishtime.set(Calendar.HOUR_OF_DAY, 19);
				_enddate = finishtime.getTimeInMillis();
			}

			ThreadPoolManager.getInstance().scheduleGeneral(new stopSellingTickets(), _enddate - System.currentTimeMillis() - 10 * MINUTE);
			ThreadPoolManager.getInstance().scheduleGeneral(new finishLottery(), _enddate - System.currentTimeMillis());

			try
			{
				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);
			}
		}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection(); Statement statement=con.createStatement(); ResultSet rset=statement.executeQuery(SELECT_LAST_LOTTERY)) in method public run() : void from class com.l2jserver.gameserver.instancemanager.games.Lottery.startLottery


		@Override
		public void run()
		{
			if (Config.DEBUG)
				_log.info("Lottery: Ending lottery #" + getId() + ".");

			int[] luckynums = new int[5];
			int luckynum = 0;

			for (int i = 0; i < 5; i++)
			{
				boolean found = true;

				while (found)
				{
					luckynum = Rnd.get(20) + 1;
					found = false;

					for (int j = 0; j < i; j++)
						if (luckynums[j] == luckynum)
							found = true;
				}

				luckynums[i] = luckynum;
			}

			if (Config.DEBUG)
				_log.info("Lottery: The lucky numbers are " + luckynums[0] + ", " + luckynums[1] + ", " + luckynums[2] + ", " + luckynums[3] + ", " + luckynums[4] + ".");

			int enchant = 0;
			int type2 = 0;

			for (int i = 0; i < 5; i++)
			{
				if (luckynums[i] < 17)
					enchant += Math.pow(2, luckynums[i] - 1);
				else
					type2 += Math.pow(2, luckynums[i] - 17);
			}

			if (Config.DEBUG)
				_log.info("Lottery: Encoded lucky numbers are " + enchant + ", " + type2);

			int count1 = 0;
			int count2 = 0;
			int count3 = 0;
			int count4 = 0;

			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
				PreparedStatement statement = con.prepareStatement(SELECT_LOTTERY_ITEM))
			{
				statement.setInt(1, getId());
				try (ResultSet rset = statement.executeQuery())
				{
					while (rset.next())
					{
						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++)
						{
							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;
						}

						if (count == 5)
							count1++;
						else if (count == 4)
							count2++;
						else if (count == 3)
							count3++;
						else if (count > 0)
							count4++;
					}
				}
			}
			catch (SQLException e)
			{
				_log.log(Level.WARNING, "Lottery: Could restore lottery data: " + e.getMessage(), e);
			}

			long prize4 = count4 * Config.ALT_LOTTERY_2_AND_1_NUMBER_PRIZE;
			long prize1 = 0;
			long prize2 = 0;
			long prize3 = 0;

			if (count1 > 0)
				prize1 = (long) ((getPrize() - prize4) * Config.ALT_LOTTERY_5_NUMBER_RATE / count1);

			if (count2 > 0)
				prize2 = (long) ((getPrize() - prize4) * Config.ALT_LOTTERY_4_NUMBER_RATE / count2);

			if (count3 > 0)
				prize3 = (long) ((getPrize() - prize4) * Config.ALT_LOTTERY_3_NUMBER_RATE / count3);

			if (Config.DEBUG)
			{
				_log.info("Lottery: " + count1 + " players with all FIVE numbers each win " + prize1 + ".");
				_log.info("Lottery: " + count2 + " players with FOUR numbers each win " + prize2 + ".");
				_log.info("Lottery: " + count3 + " players with THREE numbers each win " + prize3 + ".");
				_log.info("Lottery: " + count4 + " players with ONE or TWO numbers each win " + prize4 + ".");
			}

			long newprize = getPrize() - (prize1 + prize2 + prize3 + prize4);
			if (Config.DEBUG)
				_log.info("Lottery: Jackpot for next lottery is " + newprize + ".");

			SystemMessage sm;
			if (count1 > 0)
			{
				// There are winners.
				sm = SystemMessage.getSystemMessage(SystemMessageId.AMOUNT_FOR_WINNER_S1_IS_S2_ADENA_WE_HAVE_S3_PRIZE_WINNER);
				sm.addNumber(getId());
				sm.addItemNumber(getPrize());
				sm.addItemNumber(count1);
				Announcements.getInstance().announceToAll(sm);
			}
			else
			{
				// There are no winners.
				sm = SystemMessage.getSystemMessage(SystemMessageId.AMOUNT_FOR_LOTTERY_S1_IS_S2_ADENA_NO_WINNER);
				sm.addNumber(getId());
				sm.addItemNumber(getPrize());
				Announcements.getInstance().announceToAll(sm);
			}

			try (Connection con = L2DatabaseFactory.getInstance().getConnection();
				PreparedStatement statement = con.prepareStatement(UPDATE_LOTTERY))
			{
				statement.setLong(1, getPrize());
				statement.setLong(2, newprize);
				statement.setInt(3, enchant);
				statement.setInt(4, type2);
				statement.setLong(5, prize1);
				statement.setLong(6, prize2);
				statement.setLong(7, prize3);
				statement.setInt(8, getId());
				statement.execute();
			}
			catch (SQLException e)
			{
				_log.log(Level.WARNING, "Lottery: Could not store finished lottery data: " + e.getMessage(), e);
			}

			ThreadPoolManager.getInstance().scheduleGeneral(new startLottery(), MINUTE);
			_number++;

			_isStarted = false;
		}

		@Override
		public void run()
		{
			if (Config.DEBUG)
				_log.info("Lottery: Ending lottery #" + getId() + ".");

			int[] luckynums = new int[5];
			int luckynum = 0;

			for (int i = 0; i < 5; i++)
			{
				boolean found = true;

				while (found)
				{
					luckynum = Rnd.get(20) + 1;
					found = false;

					for (int j = 0; j < i; j++)
						if (luckynums[j] == luckynum)
							found = true;
				}

				luckynums[i] = luckynum;
			}

			if (Config.DEBUG)
				_log.info("Lottery: The lucky numbers are " + luckynums[0] + ", " + luckynums[1] + ", " + luckynums[2] + ", " + luckynums[3] + ", " + luckynums[4] + ".");

			int enchant = 0;
			int type2 = 0;

			for (int i = 0; i < 5; i++)
			{
				if (luckynums[i] < 17)
					enchant += Math.pow(2, luckynums[i] - 1);
				else
					type2 += Math.pow(2, luckynums[i] - 17);
			}

			if (Config.DEBUG)
				_log.info("Lottery: Encoded lucky numbers are " + enchant + ", " + type2);

			int count1 = 0;
			int count2 = 0;
			int count3 = 0;
			int count4 = 0;

			Connection con = null;
			PreparedStatement statement;
			try
			{
				con = L2DatabaseFactory.getInstance().getConnection();
				statement = con.prepareStatement(SELECT_LOTTERY_ITEM);
				statement.setInt(1, getId());
				ResultSet rset = statement.executeQuery();

				while (rset.next())
				{
					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++)
					{
						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;
					}

					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;
			long prize2 = 0;
			long prize3 = 0;

			if (count1 > 0)
				prize1 = (long) ((getPrize() - prize4) * Config.ALT_LOTTERY_5_NUMBER_RATE / count1);

			if (count2 > 0)
				prize2 = (long) ((getPrize() - prize4) * Config.ALT_LOTTERY_4_NUMBER_RATE / count2);

			if (count3 > 0)
				prize3 = (long) ((getPrize() - prize4) * Config.ALT_LOTTERY_3_NUMBER_RATE / count3);

			if (Config.DEBUG)
			{
				_log.info("Lottery: " + count1 + " players with all FIVE numbers each win " + prize1 + ".");
				_log.info("Lottery: " + count2 + " players with FOUR numbers each win " + prize2 + ".");
				_log.info("Lottery: " + count3 + " players with THREE numbers each win " + prize3 + ".");
				_log.info("Lottery: " + count4 + " players with ONE or TWO numbers each win " + prize4 + ".");
			}

			long newprize = getPrize() - (prize1 + prize2 + prize3 + prize4);
			if (Config.DEBUG)
				_log.info("Lottery: Jackpot for next lottery is " + newprize + ".");

			SystemMessage sm;
			if (count1 > 0)
			{
				// There are winners.
				sm = SystemMessage.getSystemMessage(SystemMessageId.AMOUNT_FOR_WINNER_S1_IS_S2_ADENA_WE_HAVE_S3_PRIZE_WINNER);
				sm.addNumber(getId());
				sm.addItemNumber(getPrize());
				sm.addItemNumber(count1);
				Announcements.getInstance().announceToAll(sm);
			}
			else
			{
				// There are no winners.
				sm = SystemMessage.getSystemMessage(SystemMessageId.AMOUNT_FOR_LOTTERY_S1_IS_S2_ADENA_NO_WINNER);
				sm.addNumber(getId());
				sm.addItemNumber(getPrize());
				Announcements.getInstance().announceToAll(sm);
			}

			try
			{
				con = L2DatabaseFactory.getInstance().getConnection();
				statement = con.prepareStatement(UPDATE_LOTTERY);
				statement.setLong(1, getPrize());
				statement.setLong(2, newprize);
				statement.setInt(3, enchant);
				statement.setInt(4, type2);
				statement.setLong(5, prize1);
				statement.setLong(6, prize2);
				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++;

			_isStarted = false;
		}

Try With Resources try(ResultSet rset=statement.executeQuery()) in method public run() : void from class com.l2jserver.gameserver.instancemanager.games.Lottery.finishLottery


	public void increasePrize(long count)
	{
		_prize += count;
		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
		{
			PreparedStatement statement = con.prepareStatement(UPDATE_PRICE);
			statement.setLong(1, getPrize());
			statement.setLong(2, getPrize());
			statement.setInt(3, getId());
			statement.execute();
			statement.close();
		}
		catch (SQLException e)
		{
			_log.log(Level.WARNING, "Lottery: Could not increase current lottery prize: " + e.getMessage(), e);
		}
	}

	public void increasePrize(long count)
	{
		_prize += count;
		Connection con = null;
		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement(UPDATE_PRICE);
			statement.setLong(1, getPrize());
			statement.setLong(2, getPrize());
			statement.setInt(3, getId());
			statement.execute();
			statement.close();
		}
		catch (SQLException e)
		{
			_log.log(Level.WARNING, "Lottery: Could not increase current lottery prize: " + e.getMessage(), e);
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection()) in method public increasePrize(count long) : void from class com.l2jserver.gameserver.instancemanager.games.Lottery


	public long[] checkTicket(int id, int enchant, int type2)
	{
		long res[] = { 0, 0 };
		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement(SELECT_LOTTERY_TICKET))
		{
			statement.setInt(1, id);
			try (ResultSet rset = statement.executeQuery())
			{
				if (rset.next())
				{
					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);
				}
			}
		}
		catch (SQLException e)
		{
			_log.log(Level.WARNING, "Lottery: Could not check lottery ticket #" + id + ": " + e.getMessage(), e);
		}
		return res;
	}

	public long[] checkTicket(int id, int enchant, int type2)
	{
		long res[] = { 0, 0 };

		Connection con = null;
		PreparedStatement statement;

		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			statement = con.prepareStatement(SELECT_LOTTERY_TICKET);
			statement.setInt(1, id);
			ResultSet rset = statement.executeQuery();

			if (rset.next())
			{
				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)
				{
					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);
			}

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

Try With Resources try(ResultSet rset=statement.executeQuery()) in method public checkTicket(id int, enchant int, type2 int) : long[] from class com.l2jserver.gameserver.instancemanager.games.Lottery


	private void restoreChatData()
	{
		int numLoaded = 0;
		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
		{
			PreparedStatement statement = con.prepareStatement("SELECT * FROM auto_chat ORDER BY groupId ASC");
			ResultSet rs = statement.executeQuery();

			PreparedStatement statement2 = con.prepareStatement("SELECT * FROM auto_chat_text WHERE groupId=?");
			while (rs.next())
			{
				numLoaded++;

				statement2.setInt(1, rs.getInt("groupId"));
				try (ResultSet rs2 = statement2.executeQuery())
				{
					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"));
				}
			}
			statement2.close();
			rs.close();
			statement.close();

			if (Config.DEBUG)
				_log.info("AutoChatHandler: Loaded " + numLoaded + " chat group(s) from the database.");
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "AutoSpawnHandler: Could not restore chat data: " + e.getMessage(), e);
		}
	}

	private void restoreChatData()
	{
		int numLoaded = 0;
		Connection con = null;
		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();

			PreparedStatement statement = con.prepareStatement("SELECT * FROM auto_chat ORDER BY groupId ASC");
			ResultSet rs = statement.executeQuery();

			PreparedStatement statement2 = con.prepareStatement("SELECT * FROM auto_chat_text WHERE groupId=?");
			while (rs.next())
			{
				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())
				{
					chatTexts[i++] = rs2.getString("chatText");
				}

				registerGlobalChat(rs.getInt("npcId"), chatTexts, rs.getLong("chatDelay"));
			}
			statement2.close();
			rs.close();
			statement.close();

			if (Config.DEBUG)
				_log.info("AutoChatHandler: Loaded " + numLoaded + " chat group(s) from the database.");
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "AutoSpawnHandler: Could not restore chat data: " + e.getMessage(), e);
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection()) in method private restoreChatData() : void from class com.l2jserver.gameserver.model.AutoChatHandler


	private void restoreSpawnData()
	{
		int numLoaded = 0;
		try (Connection 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();
			PreparedStatement statement2 = con.prepareStatement("SELECT * FROM random_spawn_loc WHERE groupId=?");
			while (rs.next())
			{
				// Register random spawn group, set various options on the
				// created spawn instance.
				AutoSpawnInstance spawnInst = registerSpawn(rs.getInt("npcId"), rs.getInt("initialDelay"), rs.getInt("respawnDelay"), rs.getInt("despawnDelay"));

				spawnInst.setSpawnCount(rs.getInt("count"));
				spawnInst.setBroadcast(rs.getBoolean("broadcastSpawn"));
				spawnInst.setRandomSpawn(rs.getBoolean("randomSpawn"));
				numLoaded++;

				// Restore the spawn locations for this spawn group/instance.
				statement2.setInt(1, rs.getInt("groupId"));
				ResultSet rs2 = statement2.executeQuery();
				statement2.clearParameters();

				while (rs2.next())
				{
					// Add each location to the spawn group/instance.
					spawnInst.addSpawnLocation(rs2.getInt("x"), rs2.getInt("y"), rs2.getInt("z"), rs2.getInt("heading"));
				}
				rs2.close();
			}
			statement2.close();
			rs.close();
			statement.close();

			if (Config.DEBUG)
				_log.info("AutoSpawnHandler: Loaded " + numLoaded + " spawn group(s) from the database.");
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "AutoSpawnHandler: Could not restore spawn data: " + e.getMessage(), e);
		}
	}

	private void restoreSpawnData()
	{
		int numLoaded = 0;
		Connection con = null;

		try
		{
			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();
			PreparedStatement statement2 = con.prepareStatement("SELECT * FROM random_spawn_loc WHERE groupId=?");
			while (rs.next())
			{
				// Register random spawn group, set various options on the
				// created spawn instance.
				AutoSpawnInstance spawnInst = registerSpawn(rs.getInt("npcId"), rs.getInt("initialDelay"), rs.getInt("respawnDelay"), rs.getInt("despawnDelay"));

				spawnInst.setSpawnCount(rs.getInt("count"));
				spawnInst.setBroadcast(rs.getBoolean("broadcastSpawn"));
				spawnInst.setRandomSpawn(rs.getBoolean("randomSpawn"));
				numLoaded++;

				// Restore the spawn locations for this spawn group/instance.
				statement2.setInt(1, rs.getInt("groupId"));
				ResultSet rs2 = statement2.executeQuery();
				statement2.clearParameters();

				while (rs2.next())
				{
					// Add each location to the spawn group/instance.
					spawnInst.addSpawnLocation(rs2.getInt("x"), rs2.getInt("y"), rs2.getInt("z"), rs2.getInt("heading"));
				}
				rs2.close();
			}
			statement2.close();
			rs.close();
			statement.close();

			if (Config.DEBUG)
				_log.info("AutoSpawnHandler: Loaded " + numLoaded + " spawn group(s) from the database.");
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "AutoSpawnHandler: Could not restore spawn data: " + e.getMessage(), e);
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection()) in method private restoreSpawnData() : void from class com.l2jserver.gameserver.model.AutoSpawnHandler


	private static List<Integer> loadList(int ObjId)
	{
		List<Integer> list = new FastList<>();

		try (Connection 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();

			int friendId;
			while (rset.next())
			{
				friendId = rset.getInt("friendId");
				if (friendId ==  ObjId)
					continue;
				list.add(friendId);
			}

			rset.close();
			statement.close();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Error found in " + ObjId + " FriendList while loading BlockList: " + e.getMessage(), e);
		}
		return list;
	}

	private static List<Integer> loadList(int ObjId)
	{
		Connection con = null;
		List<Integer> list = new FastList<>();

		try
		{
			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();

			int friendId;
			while (rset.next())
			{
				friendId = rset.getInt("friendId");
				if (friendId ==  ObjId)
					continue;
				list.add(friendId);
			}

			rset.close();
			statement.close();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Error found in " + ObjId + " FriendList while loading BlockList: " + e.getMessage(), e);
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
		return list;
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection()) in method private loadList(ObjId int) : List<Integer> from class com.l2jserver.gameserver.model.BlockList


	private void updateInDB(int targetId, boolean state)
	{
		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
		{
			if (state) //add
			{
				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
			{
				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();
				}
			}
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Could not add block player: " + e.getMessage(), e);
		}
	}

	private void updateInDB(int targetId, boolean state)
	{
		Connection con = null;
		try
		{
			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);
			}
			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);
			}
			statement.execute();
			statement.close();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Could not add block player: " + e.getMessage(), e);
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection()) in method private updateInDB(targetId int, state boolean) : void from class com.l2jserver.gameserver.model.BlockList


	public void endOfLife()
	{
		if (_isActivated)
		{
			if (_player != null && _player.isOnline())
			{
				// Remove from player
				_log.info(_name + " being removed online." );

				_player.abortAttack();

				_player.setKarma(_playerKarma);
				_player.setPkKills(_playerPkKills);
				_player.setCursedWeaponEquippedId(0);
				removeSkill();

				// Remove
				_player.getInventory().unEquipItemInBodySlot(L2Item.SLOT_LR_HAND);
				_player.store();

				// Destroy
				L2ItemInstance removedItem = _player.getInventory().destroyItemByItemId("", _itemId, 1, _player, null);
				if (!Config.FORCE_INVENTORY_UPDATE)
				{
					InventoryUpdate iu = new InventoryUpdate();
					if (removedItem.getCount() == 0) iu.addRemovedItem(removedItem);
					else iu.addModifiedItem(removedItem);

					_player.sendPacket(iu);
				}
				else _player.sendPacket(new ItemList(_player, true));

				_player.broadcastUserInfo();
			} else
			{
				// Remove from Db
				_log.info(_name + " being removed offline." );

				try (Connection con = L2DatabaseFactory.getInstance().getConnection())
				{
					// Delete the item
					PreparedStatement 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 itemId "+ _itemId +" from userId "+ _playerId);
					}
					statement.close();
					/* Yesod: Skill is not stored into database any more.
	    			// Delete the skill
	    			statement = con.prepareStatement("DELETE FROM character_skills WHERE charId=? AND skill_id=?");
	    			statement.setInt(1, _playerId);
	    			statement.setInt(2, _skillId);
	    			if (statement.executeUpdate() != 1)
	    			{
	    				_log.warning("Error while deleting skillId "+ _skillId +" from userId "+_playerId);
	    			}
					 */
					// Restore the karma
					statement = con.prepareStatement("UPDATE characters SET karma=?, pkkills=? WHERE charId=?");
					statement.setInt(1, _playerKarma);
					statement.setInt(2, _playerPkKills);
					statement.setInt(3, _playerId);
					if (statement.executeUpdate() != 1)
					{
						_log.warning("Error while updating karma & pkkills for userId "+_playerId);
					}

					statement.close();
				}
				catch (Exception e)
				{
					_log.log(Level.WARNING, "Could not delete : " + e.getMessage(), e);
				}
			}
		} else
		{
			// either this cursed weapon is in the inventory of someone who has another cursed weapon equipped,
			// OR this cursed weapon is on the ground.
			if ((_player != null) && (_player.getInventory().getItemByItemId(_itemId) != null))
			{
				// Destroy
				L2ItemInstance removedItem = _player.getInventory().destroyItemByItemId("", _itemId, 1, _player, null);
				if (!Config.FORCE_INVENTORY_UPDATE)
				{
					InventoryUpdate iu = new InventoryUpdate();
					if (removedItem.getCount() == 0) iu.addRemovedItem(removedItem);
					else iu.addModifiedItem(removedItem);

					_player.sendPacket(iu);
				}
				else _player.sendPacket(new ItemList(_player, true));

				_player.broadcastUserInfo();
			}
			//  is dropped on the ground
			else if (_item != null)
			{
				_item.decayMe();
				L2World.getInstance().removeObject(_item);
				_log.info(_name+" item has been removed from World.");
			}
		}

		// Delete infos from table if any
		CursedWeaponsManager.removeFromDb(_itemId);

		SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_HAS_DISAPPEARED);
		sm.addItemName(_itemId);
		CursedWeaponsManager.announce(sm);

		// Reset  state
		cancelTask();
		_isActivated = false;
		_isDropped = false;
		_endTime = 0;
		_player = null;
		_playerId = 0;
		_playerKarma = 0;
		_playerPkKills = 0;
		_item = null;
		_nbKills = 0;
	}

	public void endOfLife()
	{
		if (_isActivated)
		{
			if (_player != null && _player.isOnline())
			{
				// Remove from player
				_log.info(_name + " being removed online." );

				_player.abortAttack();

				_player.setKarma(_playerKarma);
				_player.setPkKills(_playerPkKills);
				_player.setCursedWeaponEquippedId(0);
				removeSkill();

				// Remove
				_player.getInventory().unEquipItemInBodySlot(L2Item.SLOT_LR_HAND);
				_player.store();

				// Destroy
				L2ItemInstance removedItem = _player.getInventory().destroyItemByItemId("", _itemId, 1, _player, null);
				if (!Config.FORCE_INVENTORY_UPDATE)
				{
					InventoryUpdate iu = new InventoryUpdate();
					if (removedItem.getCount() == 0) iu.addRemovedItem(removedItem);
					else iu.addModifiedItem(removedItem);

					_player.sendPacket(iu);
				}
				else _player.sendPacket(new ItemList(_player, true));

				_player.broadcastUserInfo();
			} else
			{
				// Remove from Db
				_log.info(_name + " being removed offline." );

				Connection con = null;
				try
				{
					con = L2DatabaseFactory.getInstance().getConnection();

					// Delete the item
					PreparedStatement 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 itemId "+ _itemId +" from userId "+ _playerId);
					}
					statement.close();
					/* Yesod: Skill is not stored into database any more.
	    			// Delete the skill
	    			statement = con.prepareStatement("DELETE FROM character_skills WHERE charId=? AND skill_id=?");
	    			statement.setInt(1, _playerId);
	    			statement.setInt(2, _skillId);
	    			if (statement.executeUpdate() != 1)
	    			{
	    				_log.warning("Error while deleting skillId "+ _skillId +" from userId "+_playerId);
	    			}
					 */
					// Restore the karma
					statement = con.prepareStatement("UPDATE characters SET karma=?, pkkills=? WHERE charId=?");
					statement.setInt(1, _playerKarma);
					statement.setInt(2, _playerPkKills);
					statement.setInt(3, _playerId);
					if (statement.executeUpdate() != 1)
					{
						_log.warning("Error while updating karma & pkkills for userId "+_playerId);
					}

					statement.close();
				}
				catch (Exception e)
				{
					_log.log(Level.WARNING, "Could not delete : " + e.getMessage(), e);
				}
				finally
				{
					L2DatabaseFactory.close(con);
				}
			}
		} else
		{
			// either this cursed weapon is in the inventory of someone who has another cursed weapon equipped,
			// OR this cursed weapon is on the ground.
			if ((_player != null) && (_player.getInventory().getItemByItemId(_itemId) != null))
			{
				// Destroy
				L2ItemInstance removedItem = _player.getInventory().destroyItemByItemId("", _itemId, 1, _player, null);
				if (!Config.FORCE_INVENTORY_UPDATE)
				{
					InventoryUpdate iu = new InventoryUpdate();
					if (removedItem.getCount() == 0) iu.addRemovedItem(removedItem);
					else iu.addModifiedItem(removedItem);

					_player.sendPacket(iu);
				}
				else _player.sendPacket(new ItemList(_player, true));

				_player.broadcastUserInfo();
			}
			//  is dropped on the ground
			else if (_item != null)
			{
				_item.decayMe();
				L2World.getInstance().removeObject(_item);
				_log.info(_name+" item has been removed from World.");
			}
		}

		// Delete infos from table if any
		CursedWeaponsManager.removeFromDb(_itemId);

		SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_HAS_DISAPPEARED);
		sm.addItemName(_itemId);
		CursedWeaponsManager.announce(sm);

		// Reset  state
		cancelTask();
		_isActivated = false;
		_isDropped = false;
		_endTime = 0;
		_player = null;
		_playerId = 0;
		_playerKarma = 0;
		_playerPkKills = 0;
		_item = null;
		_nbKills = 0;
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection()) in method public endOfLife() : void from class com.l2jserver.gameserver.model.CursedWeapon


	public void saveData()
	{
		if (Config.DEBUG)
			_log.info("CursedWeapon: Saving data to disk.");

		try (Connection 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)
			{
				statement = con.prepareStatement("INSERT INTO cursed_weapons (itemId, charId, playerKarma, playerPkKills, nbKills, endTime) VALUES (?, ?, ?, ?, ?, ?)");
				statement.setInt(1, _itemId);
				statement.setInt(2, _playerId);
				statement.setInt(3, _playerKarma);
				statement.setInt(4, _playerPkKills);
				statement.setInt(5, _nbKills);
				statement.setLong(6, _endTime);
				statement.executeUpdate();
				statement.close();
			}
		}
		catch (SQLException e)
		{
			_log.log(Level.SEVERE, "CursedWeapon: Failed to save data.", e);
		}
	}

	public void saveData()
	{
		if (Config.DEBUG)
			_log.info("CursedWeapon: Saving data to disk.");

		Connection con = null;
		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();

			// Delete previous datas
			PreparedStatement statement = con.prepareStatement("DELETE FROM cursed_weapons WHERE itemId = ?");
			statement.setInt(1, _itemId);
			statement.executeUpdate();

			if (_isActivated)
			{
				statement = con.prepareStatement("INSERT INTO cursed_weapons (itemId, charId, playerKarma, playerPkKills, nbKills, endTime) VALUES (?, ?, ?, ?, ?, ?)");
				statement.setInt(1, _itemId);
				statement.setInt(2, _playerId);
				statement.setInt(3, _playerKarma);
				statement.setInt(4, _playerPkKills);
				statement.setInt(5, _nbKills);
				statement.setLong(6, _endTime);
				statement.executeUpdate();
				statement.close();
			}
		}
		catch (SQLException e)
		{
			_log.log(Level.SEVERE, "CursedWeapon: Failed to save data.", e);
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection()) in method public saveData() : void from class com.l2jserver.gameserver.model.CursedWeapon


	/**
	 * Store in database current clan's reputation.
	 */
	public void updateClanScoreInDB()
	{
		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("UPDATE clan_data SET reputation_score=? WHERE clan_id=?"))
		{
			statement.setInt(1, getReputationScore());
			statement.setInt(2, getClanId());
			statement.execute();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Exception on updateClanScoreInDb(): " + e.getMessage(), e);
		}
	}

	/**
	 * Store in database current clan's reputation.
	 */
	public void updateClanScoreInDB()
	{
		Connection con = null;
		try
		{
			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);
		}
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection(); PreparedStatement statement=con.prepareStatement("UPDATE clan_data SET reputation_score=? WHERE clan_id=?")) in method public updateClanScoreInDB() : void from class com.l2jserver.gameserver.model.L2Clan


/**
	 * Updates in database clan information:
	 *

	 *
Clan leader Id

	 *
Alliance Id

	 *
Alliance name

	 *
Clan's reputation

	 *
Alliance's penalty expiration time

	 *
Alliance's penalty type

	 *
Character's penalty expiration time

	 *
Dissolving expiration time

	 *
Clan's id

	 *

	 */
	public void updateClanInDB()
	{
		try (Connection 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());
			statement.setString(3, getAllyName());
			statement.setInt(4, getReputationScore());
			statement.setLong(5, getAllyPenaltyExpiryTime());
			statement.setInt(6, getAllyPenaltyType());
			statement.setLong(7, getCharPenaltyExpiryTime());
			statement.setLong(8, getDissolvingExpiryTime());
			statement.setInt(9, getClanId());
			statement.execute();
			statement.close();
			if (Config.DEBUG)
				_log.fine("New clan leader saved in db: " + getClanId());
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error saving clan: " + e.getMessage(), e);
		}
	}

/**
	 * Updates in database clan information:
	 *

	 *
Clan leader Id

	 *
Alliance Id

	 *
Alliance name

	 *
Clan's reputation

	 *
Alliance's penalty expiration time

	 *
Alliance's penalty type

	 *
Character's penalty expiration time

	 *
Dissolving expiration time

	 *
Clan's id

	 *

	 */
	public void updateClanInDB()
	{
		Connection con = null;
		try
		{
			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());
			statement.setString(3, getAllyName());
			statement.setInt(4, getReputationScore());
			statement.setLong(5, getAllyPenaltyExpiryTime());
			statement.setInt(6, getAllyPenaltyType());
			statement.setLong(7, getCharPenaltyExpiryTime());
			statement.setLong(8, getDissolvingExpiryTime());
			statement.setInt(9, getClanId());
			statement.execute();
			statement.close();
			if (Config.DEBUG)
				_log.fine("New clan leader saved in db: " + getClanId());
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error saving clan: " + e.getMessage(), e);
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection()) in method public updateClanInDB() : void from class com.l2jserver.gameserver.model.L2Clan


/**
	 * Stores in database clan information:
	 *

	 *
Clan Id

	 *
Clan name

	 *
Clan level

	 *
Has castle

	 *
Alliance Id

	 *
Alliance name

	 *
Clan leader Id

	 *
Clan crest Id

	 *
Clan large crest Id

	 *
Alliance crest Id

	 *

	 */
	public void store()
	{
		try (Connection 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());
			statement.setInt(3, getLevel());
			statement.setInt(4, getCastleId());
			statement.setInt(5, getAllyId());
			statement.setString(6, getAllyName());
			statement.setInt(7, getLeaderId());
			statement.setInt(8, getCrestId());
			statement.setInt(9, getCrestLargeId());
			statement.setInt(10, getAllyCrestId());
			statement.execute();
			statement.close();
			if (Config.DEBUG)
				_log.fine("New clan saved in db: " + getClanId());
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error saving new clan: " + e.getMessage(), e);
		}
	}

/**
	 * Stores in database clan information:
	 *

	 *
Clan Id

	 *
Clan name

	 *
Clan level

	 *
Has castle

	 *
Alliance Id

	 *
Alliance name

	 *
Clan leader Id

	 *
Clan crest Id

	 *
Clan large crest Id

	 *
Alliance crest Id

	 *

	 */
	public void store()
	{
		Connection con = null;
		try
		{
			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());
			statement.setInt(3, getLevel());
			statement.setInt(4, getCastleId());
			statement.setInt(5, getAllyId());
			statement.setString(6, getAllyName());
			statement.setInt(7, getLeaderId());
			statement.setInt(8, getCrestId());
			statement.setInt(9, getCrestLargeId());
			statement.setInt(10, getAllyCrestId());
			statement.execute();
			statement.close();
			if (Config.DEBUG)
				_log.fine("New clan saved in db: " + getClanId());
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error saving new clan: " + e.getMessage(), e);
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection()) in method public store() : void from class com.l2jserver.gameserver.model.L2Clan


	/**
	 * @param member the clan member to be removed.
	 * @param clanJoinExpiryTime
	 * @param clanCreateExpiryTime
	 */
	private void removeMemberInDatabase(L2ClanMember member, long clanJoinExpiryTime, long clanCreateExpiryTime)
	{
		try (Connection 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);
			statement.setLong(3, clanCreateExpiryTime);
			statement.setInt(4, member.getObjectId());
			statement.execute();
			statement.close();
			if (Config.DEBUG)
				_log.fine("clan member removed in db: " + getClanId());

			statement = con.prepareStatement("UPDATE characters SET apprentice=0 WHERE apprentice=?");
			statement.setInt(1, member.getObjectId());
			statement.execute();
			statement.close();

			statement = con.prepareStatement("UPDATE characters SET sponsor=0 WHERE sponsor=?");
			statement.setInt(1, member.getObjectId());
			statement.execute();
			statement.close();
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error removing clan member: " + e.getMessage(), e);
		}
	}

	/**
	 * @param member the clan member to be removed.
	 * @param clanJoinExpiryTime
	 * @param clanCreateExpiryTime
	 */
	private void removeMemberInDatabase(L2ClanMember member, long clanJoinExpiryTime, long clanCreateExpiryTime)
	{
		Connection con = null;
		try
		{
			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);
			statement.setLong(3, clanCreateExpiryTime);
			statement.setInt(4, member.getObjectId());
			statement.execute();
			statement.close();
			if (Config.DEBUG)
				_log.fine("clan member removed in db: " + getClanId());

			statement = con.prepareStatement("UPDATE characters SET apprentice=0 WHERE apprentice=?");
			statement.setInt(1, member.getObjectId());
			statement.execute();
			statement.close();

			statement = con.prepareStatement("UPDATE characters SET sponsor=0 WHERE sponsor=?");
			statement.setInt(1, member.getObjectId());
			statement.execute();
			statement.close();
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error removing clan member: " + e.getMessage(), e);
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection()) in method private removeMemberInDatabase(member L2ClanMember, clanJoinExpiryTime long, clanCreateExpiryTime long) : void from class com.l2jserver.gameserver.model.L2Clan


	@SuppressWarnings("unused")
	private void updateWarsInDB()
	{
		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
		{
			final PreparedStatement statement = con.prepareStatement("UPDATE clan_wars SET wantspeace1=? WHERE clan1=?");
			statement.setInt(1, 0);
			statement.setInt(2, 0);
			statement.close();
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error updating clan wars data: " + e.getMessage(), e);
		}
	}

	@SuppressWarnings("unused")
	private void updateWarsInDB()
	{
		Connection con = null;
		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			final PreparedStatement statement = con.prepareStatement("UPDATE clan_wars SET wantspeace1=? WHERE clan1=?");
			statement.setInt(1, 0);
			statement.setInt(2, 0);
			statement.close();
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error updating clan wars data: " + e.getMessage(), e);
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection()) in method private updateWarsInDB() : void from class com.l2jserver.gameserver.model.L2Clan


	private void restore()
	{
		//restorewars();
		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=?"))
		{
			statement.setInt(1, getClanId());
			try (ResultSet clanData = statement.executeQuery())
			{
				if (clanData.next())
				{
					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"));
							}
						}
					}
				}
			}

			if (Config.DEBUG && getName() != null)
				_log.info("Restored clan data for \"" + getName() + "\" from database.");

			restoreSubPledges();
			restoreRankPrivs();
			restoreSkills();
			restoreNotice();
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error restoring clan data: " + e.getMessage(), e);
		}
	}

	private void restore()
	{
		//restorewars();
		Connection con = null;
		try
		{
			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())
			{
				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();
				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"));
				}
				clanMembers.close();
			}
			clanData.close();
			statement.close();

			if (Config.DEBUG && getName() != null)
				_log.info("Restored clan data for \"" + getName() + "\" from database.");

			restoreSubPledges();
			restoreRankPrivs();
			restoreSkills();
			restoreNotice();
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error restoring clan data: " + e.getMessage(), e);
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
	}

Try With Resources try(ResultSet clanData=statement.executeQuery()) in method private restore() : void from class com.l2jserver.gameserver.model.L2Clan


	private void restoreNotice()
	{
		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("SELECT enabled,notice FROM clan_notices WHERE clan_id=?"))
		{
			statement.setInt(1, getClanId());
			try (ResultSet noticeData = statement.executeQuery())
			{
				while (noticeData.next())
				{
					_noticeEnabled = noticeData.getBoolean("enabled");
					_notice = noticeData.getString("notice");
				}
			}
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error restoring clan notice: " + e.getMessage(), e);
		}
	}

	private void restoreNotice()
	{
		Connection con = null;
		try
		{
			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())
			{
				_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);
		}
	}

Try With Resources try(ResultSet noticeData=statement.executeQuery()) in method private restoreNotice() : void from class com.l2jserver.gameserver.model.L2Clan


	private void storeNotice(String notice, boolean enabled)
	{
		if (notice == null)
			notice = "";

		if (notice.length() > MAX_NOTICE_LENGTH)
			notice = notice.substring(0, MAX_NOTICE_LENGTH - 1);

		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=?"))
		{
			statement.setInt(1, getClanId());
			statement.setString(2, notice);
			if (enabled)
				statement.setString(3, "true");
			else
				statement.setString(3, "false");
			statement.setString(4, notice);
			if (enabled)
				statement.setString(5, "true");
			else
				statement.setString(5, "false");
			statement.execute();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Error could not store clan notice: " + e.getMessage(), e);
		}

		_notice = notice;
		_noticeEnabled = enabled;
	}

	private void storeNotice(String notice, boolean enabled)
	{
		if (notice == null)
			notice = "";

		if (notice.length() > MAX_NOTICE_LENGTH)
			notice = notice.substring(0, MAX_NOTICE_LENGTH - 1);

		Connection con = null;
		try
		{
			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)
				statement.setString(3, "true");
			else
				statement.setString(3, "false");
			statement.setString(4, notice);
			if (enabled)
				statement.setString(5, "true");
			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;
	}

Try With Resources 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=?")) in method private storeNotice(notice String, enabled boolean) : void from class com.l2jserver.gameserver.model.L2Clan


	private void restoreSkills()
	{
		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
			statement.setInt(1, getClanId());
			try (ResultSet rset = statement.executeQuery())
			{
				// Go though the recordset of this SQL query
				while (rset.next())
				{
					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
					{
						SubPledge subunit = _subPledges.get(subType);
						if (subunit != null)
							subunit.addNewSkill(skill);
						else
							_log.info("Missing subpledge "+subType+" for clan "+this+", skill skipped.");
					}
				}
			}
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error restoring clan skills: " + e.getMessage(), e);
		}
	}

	private void restoreSkills()
	{
		Connection con = null;

		try
		{
			// 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())
			{
				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
				{
					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);
		}
	}

Try With Resources try(ResultSet rset=statement.executeQuery()) in method private restoreSkills() : void from class com.l2jserver.gameserver.model.L2Clan


	/**
	 * Used to add a new skill to the list, send a packet to all online clan members, update their stats and store it in db
	 * @param newSkill
	 * @param subType
	 * @return
	 */
	public L2Skill addNewSkill(L2Skill newSkill, int subType)
	{
		L2Skill oldSkill = null;
		if (newSkill != null)
		{

			if (subType == -2) // regular clan skill
				oldSkill = _skills.put(newSkill.getId(), newSkill);
			else if (subType == 0) // main clan sub skill
				oldSkill = _subPledgeSkills.put(newSkill.getId(), newSkill);
			else
			{
				SubPledge subunit = getSubPledge(subType);
				if (subunit != null)
					oldSkill = subunit.addNewSkill(newSkill);
				else
				{
					_log.log(Level.WARNING, "Subpledge "+subType +" does not exist for clan "+this);
					return oldSkill;
				}
			}

			try (Connection con = L2DatabaseFactory.getInstance().getConnection())
			{
				if (oldSkill != null)
				{
					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
				{
					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();
					}
				}
			}
			catch (Exception e)
			{
				_log.log(Level.WARNING, "Error could not store clan skills: " + e.getMessage(), e);
			}

			SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.CLAN_SKILL_S1_ADDED);
			sm.addSkillName(newSkill.getId());

			for (L2ClanMember temp : _members.values())
			{
				if (temp != null && temp.getPlayerInstance() != null && temp.isOnline())
				{
					if (subType == -2)
					{
						if (newSkill.getMinPledgeClass() <= temp.getPlayerInstance().getPledgeClass())
						{
							temp.getPlayerInstance().addSkill(newSkill, false); // Skill is not saved to player DB
							temp.getPlayerInstance().sendPacket(new PledgeSkillListAdd(newSkill.getId(), newSkill.getLevel()));
							temp.getPlayerInstance().sendPacket(sm);
							temp.getPlayerInstance().sendSkillList();
						}
					}
					else
					{
						if (temp.getPledgeType() == subType)
						{
							temp.getPlayerInstance().addSkill(newSkill, false); // Skill is not saved to player DB
							temp.getPlayerInstance().sendPacket(new ExSubPledgeSkillAdd(subType, newSkill.getId(), newSkill.getLevel()));
							temp.getPlayerInstance().sendPacket(sm);
							temp.getPlayerInstance().sendSkillList();
						}
					}
				}
			}
		}

		return oldSkill;
	}

	/**
	 * Used to add a new skill to the list, send a packet to all online clan members, update their stats and store it in db
	 * @param newSkill
	 * @param subType
	 * @return
	 */
	public L2Skill addNewSkill(L2Skill newSkill, int subType)
	{
		L2Skill oldSkill = null;
		Connection con = null;

		if (newSkill != null)
		{

			if (subType == -2) // regular clan skill
				oldSkill = _skills.put(newSkill.getId(), newSkill);
			else if (subType == 0) // main clan sub skill
				oldSkill = _subPledgeSkills.put(newSkill.getId(), newSkill);
			else
			{
				SubPledge subunit = getSubPledge(subType);
				if (subunit != null)
					oldSkill = subunit.addNewSkill(newSkill);
				else
				{
					_log.log(Level.WARNING, "Subpledge "+subType +" does not exist for clan "+this);
					return oldSkill;
				}
			}

			try
			{
				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());
				}
				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);
				}
				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());

			for (L2ClanMember temp : _members.values())
			{
				if (temp != null && temp.getPlayerInstance() != null && temp.isOnline())
				{
					if (subType == -2)
					{
						if (newSkill.getMinPledgeClass() <= temp.getPlayerInstance().getPledgeClass())
						{
							temp.getPlayerInstance().addSkill(newSkill, false); // Skill is not saved to player DB
							temp.getPlayerInstance().sendPacket(new PledgeSkillListAdd(newSkill.getId(), newSkill.getLevel()));
							temp.getPlayerInstance().sendPacket(sm);
							temp.getPlayerInstance().sendSkillList();
						}
					}
					else
					{
						if (temp.getPledgeType() == subType)
						{
							temp.getPlayerInstance().addSkill(newSkill, false); // Skill is not saved to player DB
							temp.getPlayerInstance().sendPacket(new ExSubPledgeSkillAdd(subType, newSkill.getId(), newSkill.getLevel()));
							temp.getPlayerInstance().sendPacket(sm);
							temp.getPlayerInstance().sendSkillList();
						}
					}
				}
			}
		}

		return oldSkill;
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection()) in method public addNewSkill(newSkill L2Skill, subType int) : L2Skill from class com.l2jserver.gameserver.model.L2Clan


	private void restoreSubPledges()
	{
		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
			statement.setInt(1, getClanId());
			try (ResultSet rset = statement.executeQuery())
			{
				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);
				}
			}
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Could not restore clan sub-units: " + e.getMessage(), e);
		}
	}

	private void restoreSubPledges()
	{
		Connection con = null;
		try
		{
			// 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())
			{
				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);
		}
	}

Try With Resources try(ResultSet rset=statement.executeQuery()) in method private restoreSubPledges() : void from class com.l2jserver.gameserver.model.L2Clan


	public SubPledge createSubPledge(L2PcInstance player, int pledgeType, int leaderId, String subPledgeName)
	{
		SubPledge subPledge = null;
		pledgeType = getAvailablePledgeTypes(pledgeType);
		if (pledgeType == 0)
		{
			if (pledgeType == L2Clan.SUBUNIT_ACADEMY)
				player.sendPacket(SystemMessageId.CLAN_HAS_ALREADY_ESTABLISHED_A_CLAN_ACADEMY);
			else
				player.sendMessage("You can't create any more sub-units of this type");
			return null;
		}
		if (_leader.getObjectId() == leaderId)
		{
			player.sendMessage("Leader is not correct");
			return null;
		}

		// Royal Guard 5000 points per each
		// Order of Knights 10000 points per each
		if (pledgeType != -1 && ((getReputationScore() < 5000 && pledgeType < L2Clan.SUBUNIT_KNIGHT1) || (getReputationScore() < 10000 && pledgeType > L2Clan.SUBUNIT_ROYAL2)))
		{
			player.sendPacket(SystemMessageId.THE_CLAN_REPUTATION_SCORE_IS_TOO_LOW);
			return null;
		}

		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);
			if (pledgeType != -1)
				statement.setInt(4, leaderId);
			else
				statement.setInt(4, 0);
			statement.execute();

			subPledge = new SubPledge(pledgeType, subPledgeName, leaderId);
			_subPledges.put(pledgeType, subPledge);

			if (pledgeType != -1)
			{
				// Royal Guard 5000 points per each
				// Order of Knights 10000 points per each
				if (pledgeType < L2Clan.SUBUNIT_KNIGHT1)
					setReputationScore(getReputationScore() - Config.ROYAL_GUARD_COST, true);
				else
					setReputationScore(getReputationScore() - Config.KNIGHT_UNIT_COST, true);
				//TODO: clan lvl9 or more can reinforce knights cheaper if first knight unit already created, use Config.KNIGHT_REINFORCE_COST
			}

			if (Config.DEBUG)
				_log.fine("New sub_clan saved in db: " + getClanId() + "; " + pledgeType);
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error saving sub clan data: " + e.getMessage(), e);
		}

		broadcastToOnlineMembers(new PledgeShowInfoUpdate(_leader.getClan()));
		broadcastToOnlineMembers(new PledgeReceiveSubPledgeCreated(subPledge, _leader.getClan()));
		return subPledge;
	}

	public SubPledge createSubPledge(L2PcInstance player, int pledgeType, int leaderId, String subPledgeName)
	{
		SubPledge subPledge = null;
		pledgeType = getAvailablePledgeTypes(pledgeType);
		if (pledgeType == 0)
		{
			if (pledgeType == L2Clan.SUBUNIT_ACADEMY)
				player.sendPacket(SystemMessageId.CLAN_HAS_ALREADY_ESTABLISHED_A_CLAN_ACADEMY);
			else
				player.sendMessage("You can't create any more sub-units of this type");
			return null;
		}
		if (_leader.getObjectId() == leaderId)
		{
			player.sendMessage("Leader is not correct");
			return null;
		}

		// Royal Guard 5000 points per each
		// Order of Knights 10000 points per each
		if (pledgeType != -1 && ((getReputationScore() < 5000 && pledgeType < L2Clan.SUBUNIT_KNIGHT1) || (getReputationScore() < 10000 && pledgeType > L2Clan.SUBUNIT_ROYAL2)))
		{
			player.sendPacket(SystemMessageId.THE_CLAN_REPUTATION_SCORE_IS_TOO_LOW);
			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 (?,?,?,?)");
			statement.setInt(1, getClanId());
			statement.setInt(2, pledgeType);
			statement.setString(3, subPledgeName);
			if (pledgeType != -1)
				statement.setInt(4, leaderId);
			else
				statement.setInt(4, 0);
			statement.execute();
			statement.close();

			subPledge = new SubPledge(pledgeType, subPledgeName, leaderId);
			_subPledges.put(pledgeType, subPledge);

			if (pledgeType != -1)
			{
				// Royal Guard 5000 points per each
				// Order of Knights 10000 points per each
				if (pledgeType < L2Clan.SUBUNIT_KNIGHT1)
					setReputationScore(getReputationScore() - Config.ROYAL_GUARD_COST, true);
				else
					setReputationScore(getReputationScore() - Config.KNIGHT_UNIT_COST, true);
				//TODO: clan lvl9 or more can reinforce knights cheaper if first knight unit already created, use Config.KNIGHT_REINFORCE_COST
			}

			if (Config.DEBUG)
				_log.fine("New sub_clan saved in db: " + getClanId() + "; " + pledgeType);
		}
		catch (Exception e)
		{
			_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;
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection(); PreparedStatement statement=con.prepareStatement("INSERT INTO clan_subpledges (clan_id,sub_pledge_id,name,leader_id) values (?,?,?,?)")) in method public createSubPledge(player L2PcInstance, pledgeType int, leaderId int, subPledgeName String) : SubPledge from class com.l2jserver.gameserver.model.L2Clan


	public void updateSubPledgeInDB(int pledgeType)
	{
		try (Connection con = L2DatabaseFactory.getInstance().getConnection();
			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();
			if (Config.DEBUG)
				_log.fine("Subpledge updated in db: " + getClanId());
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error updating subpledge: " + e.getMessage(), e);
		}
	}

	public void updateSubPledgeInDB(int pledgeType)
	{
		Connection con = null;
		try
		{
			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());
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, "Error updating subpledge: " + e.getMessage(), e);
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection(); PreparedStatement statement=con.prepareStatement("UPDATE clan_subpledges SET leader_id=?, name=? WHERE clan_id=? AND sub_pledge_id=?")) in method public updateSubPledgeInDB(pledgeType int) : void from class com.l2jserver.gameserver.model.L2Clan