	private void readFromDisk(String path, List<String> list)
	{
		final File file = new File(Config.DATAPACK_ROOT, path);
		if (file.exists())
		{

			try (LineNumberReader lnr = new LineNumberReader(new FileReader(file)))
			{
				String line = null;
				while ((line = lnr.readLine()) != null)
				{
					StringTokenizer st = new StringTokenizer(line, "\n\r");
					if (st.hasMoreTokens())
					{
						list.add(st.nextToken());
					}
				}
			}
			catch (IOException e1)
			{
				_log.log(Level.SEVERE, "Error reading announcements: ", e1);
			}
		}
		else
			_log.warning(file.getAbsolutePath() + " doesn't exist");
	}

	private void readFromDisk(String path, List<String> list)
	{
		File file = new File(Config.DATAPACK_ROOT, path);

		if (file.exists())
		{
			LineNumberReader lnr = null;
			try
			{
				String line = null;
				lnr = new LineNumberReader(new FileReader(file));
				while ((line = lnr.readLine()) != null)
				{
					StringTokenizer st = new StringTokenizer(line, "\n\r");
					if (st.hasMoreTokens())
					{
						String announcement = st.nextToken();
						list.add(announcement);
					}
				}
			}
			catch (IOException e1)
			{
				_log.log(Level.SEVERE, "Error reading announcements: ", e1);
			}
			finally
			{
				try
				{
					lnr.close();
				}
				catch (Exception e2)
				{
					// nothing
				}
			}
		}
		else
			_log.warning(file.getAbsolutePath() + " doesn't exist");
	}

Try With Resources try(LineNumberReader lnr=new LineNumberReader(new FileReader(file))) in method private readFromDisk(path String, list List<String>) : void from class com.l2jserver.gameserver.Announcements


	public void reload()
	{
		final FileFilter filter = new BMPFilter();
		final File dir = new File(Config.DATAPACK_ROOT, "data/crests/");
		final File[] files = dir.listFiles(filter);
		byte[] content;
		synchronized (this)
		{
			_loadedFiles = 0;
			_bytesBuffLen = 0;

			_cachePledge.clear();
			_cachePledgeLarge.clear();
			_cacheAlly.clear();
		}

		FastMap<Integer, byte[]> _mapPledge = _cachePledge.getContentMap();
		FastMap<Integer, byte[]> _mapPledgeLarge = _cachePledgeLarge.getContentMap();
		FastMap<Integer, byte[]> _mapAlly = _cacheAlly.getContentMap();

		final L2Clan[] clans = ClanTable.getInstance().getClans();
		for (File file : files)
		{
			synchronized (this)
			{
				try (RandomAccessFile rfa = new RandomAccessFile(file, "r"))
				{
					content = new byte[(int) rfa.length()];
					rfa.readFully(content);

					boolean erase = true;
					int crestId = 0;

					if (file.getName().startsWith("Crest_Large_"))
					{
						crestId = Integer.parseInt(file.getName().substring(12, file.getName().length() - 4));
						if (Config.CLEAR_CREST_CACHE)
						{
							for (final L2Clan clan : clans)
							{
								if (clan.getCrestLargeId() == crestId)
								{
									erase = false;
									break;
								}
							}
							if (erase)
							{
								file.delete();
								continue;
							}
						}
						_mapPledgeLarge.put(crestId, content);
					}
					else if (file.getName().startsWith("Crest_"))
					{
						crestId = Integer.parseInt(file.getName().substring(6, file.getName().length() - 4));
						if (Config.CLEAR_CREST_CACHE)
						{
							for (final L2Clan clan : clans)
							{
								if (clan.getCrestId() == crestId)
								{
									erase = false;
									break;
								}
							}
							if (erase)
							{
								file.delete();
								continue;
							}
						}
						_mapPledge.put(crestId, content);
					}
					else if (file.getName().startsWith("AllyCrest_"))
					{
						crestId = Integer.parseInt(file.getName().substring(10, file.getName().length() - 4));
						if (Config.CLEAR_CREST_CACHE)
						{
							for (final L2Clan clan : clans)
							{
								if (clan.getAllyCrestId() == crestId)
								{
									erase = false;
									break;
								}
							}
							if (erase)
							{
								file.delete();
								continue;
							}
						}
						_mapAlly.put(crestId, content);
					}
					_loadedFiles++;
					_bytesBuffLen += content.length;
				}
				catch (Exception e)
				{
					_log.log(Level.WARNING, "Problem with crest bmp file " + e.getMessage(), e);
				}
			}
		}

		for (L2Clan clan : clans)
		{
			if (clan.getCrestId() != 0)
			{
				if (getPledgeCrest(clan.getCrestId()) == null)
				{
					_log.log(Level.INFO, "Removing non-existent crest for clan " + clan.getName() + " [" + clan.getClanId() + "], crestId:" + clan.getCrestId());
					clan.setCrestId(0);
					clan.changeClanCrest(0);
				}
			}
			if (clan.getCrestLargeId() != 0)
			{
				if (getPledgeCrestLarge(clan.getCrestLargeId()) == null)
				{
					_log.log(Level.INFO, "Removing non-existent large crest for clan " + clan.getName() + " [" + clan.getClanId() + "], crestLargeId:" + clan.getCrestLargeId());
					clan.setCrestLargeId(0);
					clan.changeLargeCrest(0);
				}
			}
			if (clan.getAllyCrestId() != 0)
			{
				if (getAllyCrest(clan.getAllyCrestId()) == null)
				{
					_log.log(Level.INFO, "Removing non-existent ally crest for clan " + clan.getName() + " [" + clan.getClanId() + "], allyCrestId:" + clan.getAllyCrestId());
					clan.setAllyCrestId(0);
					clan.changeAllyCrest(0, true);
				}
			}
		}

		_log.info("Cache[Crest]: " + String.format("%.3f", getMemoryUsage()) + "MB on " + getLoadedFiles() + " files loaded. (Forget Time: " + (_cachePledge.getForgetTime() / 1000) + "s , Capacity: " + _cachePledge.capacity() + ")");
	}

	public void reload()
	{
		FileFilter filter = new BmpFilter();

		File dir = new File(Config.DATAPACK_ROOT, "data/crests/");

		File[] files = dir.listFiles(filter);
		byte[] content;
		synchronized (this)
		{
			_loadedFiles = 0;
			_bytesBuffLen = 0;

			_cachePledge.clear();
			_cachePledgeLarge.clear();
			_cacheAlly.clear();
		}

		FastMap<Integer, byte[]> _mapPledge = _cachePledge.getContentMap();
		FastMap<Integer, byte[]> _mapPledgeLarge = _cachePledgeLarge.getContentMap();
		FastMap<Integer, byte[]> _mapAlly = _cacheAlly.getContentMap();

		final L2Clan[] clans = ClanTable.getInstance().getClans();

		for (File file : files)
		{
			RandomAccessFile f = null;
			synchronized (this)
			{
				try
				{
					f = new RandomAccessFile(file, "r");
					content = new byte[(int) f.length()];
					f.readFully(content);

					boolean erase = true;
					int crestId = 0;

					if (file.getName().startsWith("Crest_Large_"))
					{
						crestId = Integer.parseInt(file.getName().substring(12, file.getName().length() - 4));
						if(Config.CLEAR_CREST_CACHE)
						{
							for(final L2Clan clan : clans)
								if(clan.getCrestLargeId() == crestId)
								{
									erase = false;
									break;
								}
							if(erase)
							{
								file.delete();
								continue;
							}
						}
						_mapPledgeLarge.put(crestId, content);
					}
					else if (file.getName().startsWith("Crest_"))
					{
						crestId = Integer.parseInt(file.getName().substring(6, file.getName().length() - 4));
						if(Config.CLEAR_CREST_CACHE)
						{
							for(final L2Clan clan : clans)
								if(clan.getCrestId() == crestId)
								{
									erase = false;
									break;
								}
							if(erase)
							{
								file.delete();
								continue;
							}
						}
						_mapPledge.put(crestId, content);
					}
					else if (file.getName().startsWith("AllyCrest_"))
					{
						crestId = Integer.parseInt(file.getName().substring(10, file.getName().length() - 4));
						if(Config.CLEAR_CREST_CACHE)
						{
							for(final L2Clan clan : clans)
								if(clan.getAllyCrestId() == crestId)
								{
									erase = false;
									break;
								}
							if(erase)
							{
								file.delete();
								continue;
							}
						}
						_mapAlly.put(crestId, content);
					}
					_loadedFiles++;
					_bytesBuffLen += content.length;
				}
				catch (Exception e)
				{
					_log.log(Level.WARNING, "Problem with crest bmp file " + e.getMessage(), e);
				}
				finally
				{
					try
					{
						f.close();
					}
					catch (Exception e1)
					{
					}
				}
			}
		}

		for (L2Clan clan : clans)
		{
			if (clan.getCrestId() != 0)
			{
				if (getPledgeCrest(clan.getCrestId()) == null)
				{
					_log.log(Level.INFO, "Removing non-existent crest for clan " + clan.getName() + " [" + clan.getClanId() + "], crestId:" + clan.getCrestId());
					clan.setCrestId(0);
					clan.changeClanCrest(0);
				}
			}
			if (clan.getCrestLargeId() != 0)
			{
				if (getPledgeCrestLarge(clan.getCrestLargeId()) == null)
				{
					_log.log(Level.INFO, "Removing non-existent large crest for clan " + clan.getName() + " [" + clan.getClanId() + "], crestLargeId:" + clan.getCrestLargeId());
					clan.setCrestLargeId(0);
					clan.changeLargeCrest(0);
				}
			}
			if (clan.getAllyCrestId() != 0)
			{
				if (getAllyCrest(clan.getAllyCrestId()) == null)
				{
					_log.log(Level.INFO, "Removing non-existent ally crest for clan " + clan.getName() + " [" + clan.getClanId() + "], allyCrestId:" + clan.getAllyCrestId());
					clan.setAllyCrestId(0);
					clan.changeAllyCrest(0, true);
				}
			}
		}

		_log.info("Cache[Crest]: " + String.format("%.3f", getMemoryUsage()) + "MB on " + getLoadedFiles()
				+ " files loaded. (Forget Time: " + (_cachePledge.getForgetTime() / 1000) + "s , Capacity: " + _cachePledge.capacity()
				+ ")");
	}

Try With Resources try(RandomAccessFile rfa=new RandomAccessFile(file,"r")) in method public reload() : void from class com.l2jserver.gameserver.cache.CrestCache


	public void parseData()
	{
		final File doorData = new File(Config.DATAPACK_ROOT, "data/door.csv");
		try (FileReader fr = new FileReader(doorData);
			BufferedReader br = new BufferedReader (fr);
			LineNumberReader lnr = new LineNumberReader(br))
		{
			String line = null;
			_log.info("Searching clan halls doors:");

			while ((line = lnr.readLine()) != null)
			{
				if (line.trim().length() == 0 || line.startsWith("#"))
					continue;

				L2DoorInstance door = parseList(line, false);
				putDoor(door);
				door.spawnMe(door.getX(), door.getY(), door.getZ());
			}

			_log.info("DoorTable: Loaded " + _staticItems.size() + " Door Templates for " + _regions.size() + " regions.");
		}
		catch (FileNotFoundException e)
		{
			_log.warning("door.csv is missing in data folder");
		}
		catch (IOException e)
		{
			_log.log(Level.WARNING, "Error while creating door table " + e.getMessage(), e);
		}
	}

	public void parseData()
	{
		LineNumberReader lnr = null;
		try
		{
			File doorData = new File(Config.DATAPACK_ROOT, "data/door.csv");
			lnr = new LineNumberReader(new BufferedReader(new FileReader(doorData)));

			String line = null;
			_log.info("Searching clan halls doors:");

			while ((line = lnr.readLine()) != null)
			{
				if (line.trim().length() == 0 || line.startsWith("#"))
					continue;

				L2DoorInstance door = parseList(line, false);
				putDoor(door);
				door.spawnMe(door.getX(), door.getY(), door.getZ());
			}

			_log.info("DoorTable: Loaded " + _staticItems.size() + " Door Templates for " + _regions.size() + " regions.");
		}
		catch (FileNotFoundException e)
		{
			_log.warning("door.csv is missing in data folder");
		}
		catch (IOException e)
		{
			_log.log(Level.WARNING, "Error while creating door table " + e.getMessage(), e);
		}
		finally
		{
			try
			{
				lnr.close();
			}
			catch (Exception e1)
			{ /* ignore problems */
			}
		}
	}

Try With Resources try(FileReader fr=new FileReader(doorData); BufferedReader br=new BufferedReader(fr); LineNumberReader lnr=new LineNumberReader(br)) in method public parseData() : void from class com.l2jserver.gameserver.datatables.DoorTable


	private final void load()
	{
		final File file = new File(Config.FORTSIEGE_CONFIGURATION_FILE);
		try (InputStream is = new FileInputStream(file))
		{
			Properties siegeSettings = new Properties();
			siegeSettings.load(is);

			// Siege setting
			_attackerMaxClans = Integer.decode(siegeSettings.getProperty("AttackerMaxClans", "500"));
			_flagMaxCount = Integer.decode(siegeSettings.getProperty("MaxFlags", "1"));
			_siegeClanMinLevel = Integer.decode(siegeSettings.getProperty("SiegeClanMinLevel", "4"));
			_siegeLength = Integer.decode(siegeSettings.getProperty("SiegeLength", "60"));
			_countDownLength = Integer.decode(siegeSettings.getProperty("CountDownLength", "10"));
			_suspiciousMerchantRespawnDelay = Integer.decode(siegeSettings.getProperty("SuspiciousMerchantRespawnDelay", "180"));

			// Siege spawns settings
			_commanderSpawnList = new FastMap<Integer, FastList<SiegeSpawn>>();
			_flagList = new FastMap<Integer, FastList<CombatFlag>>();

			for (Fort fort : FortManager.getInstance().getForts())
			{
				FastList<SiegeSpawn> _commanderSpawns = new FastList<SiegeSpawn>();
				FastList<CombatFlag> _flagSpawns = new FastList<CombatFlag>();
				for (int i = 1; i < 5; i++)
				{
					String _spawnParams = siegeSettings.getProperty(fort.getName().replace(" ", "") + "Commander" + i, "");
					if (_spawnParams.length() == 0)
						break;
					StringTokenizer st = new StringTokenizer(_spawnParams.trim(), ",");

					try
					{
						int x = Integer.parseInt(st.nextToken());
						int y = Integer.parseInt(st.nextToken());
						int z = Integer.parseInt(st.nextToken());
						int heading = Integer.parseInt(st.nextToken());
						int npc_id = Integer.parseInt(st.nextToken());

						_commanderSpawns.add(new SiegeSpawn(fort.getFortId(), x, y, z, heading, npc_id, i));
					}
					catch (Exception e)
					{
						_log.warning("Error while loading commander(s) for " + fort.getName() + " fort.");
					}
				}

				_commanderSpawnList.put(fort.getFortId(), _commanderSpawns);

				for (int i = 1; i < 4; i++)
				{
					String _spawnParams = siegeSettings.getProperty(fort.getName().replace(" ", "") + "Flag" + i, "");
					if (_spawnParams.length() == 0)
						break;
					StringTokenizer st = new StringTokenizer(_spawnParams.trim(), ",");

					try
					{
						int x = Integer.parseInt(st.nextToken());
						int y = Integer.parseInt(st.nextToken());
						int z = Integer.parseInt(st.nextToken());
						int flag_id = Integer.parseInt(st.nextToken());

						_flagSpawns.add(new CombatFlag(fort.getFortId(), x, y, z, 0, flag_id));
					}
					catch (Exception e)
					{
						_log.warning("Error while loading flag(s) for " + fort.getName() + " fort.");
					}
				}
				_flagList.put(fort.getFortId(), _flagSpawns);
			}

		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Error while loading fortsiege data." + e.getMessage(), e);
		}
	}

	private final void load()
	{
		InputStream is = null;
		try
		{
			is = new FileInputStream(new File(Config.FORTSIEGE_CONFIGURATION_FILE));
			Properties siegeSettings = new Properties();
			siegeSettings.load(is);

			// Siege setting
			_attackerMaxClans = Integer.decode(siegeSettings.getProperty("AttackerMaxClans", "500"));
			_flagMaxCount = Integer.decode(siegeSettings.getProperty("MaxFlags", "1"));
			_siegeClanMinLevel = Integer.decode(siegeSettings.getProperty("SiegeClanMinLevel", "4"));
			_siegeLength = Integer.decode(siegeSettings.getProperty("SiegeLength", "60"));
			_countDownLength = Integer.decode(siegeSettings.getProperty("CountDownLength", "10"));
			_suspiciousMerchantRespawnDelay = Integer.decode(siegeSettings.getProperty("SuspiciousMerchantRespawnDelay", "180"));

			// Siege spawns settings
			_commanderSpawnList = new FastMap<Integer, FastList<SiegeSpawn>>();
			_flagList = new FastMap<Integer, FastList<CombatFlag>>();

			for (Fort fort : FortManager.getInstance().getForts())
			{
				FastList<SiegeSpawn> _commanderSpawns = new FastList<SiegeSpawn>();
				FastList<CombatFlag> _flagSpawns = new FastList<CombatFlag>();
				for (int i = 1; i < 5; i++)
				{
					String _spawnParams = siegeSettings.getProperty(fort.getName().replace(" ", "") + "Commander" + i, "");
					if (_spawnParams.length() == 0)
						break;
					StringTokenizer st = new StringTokenizer(_spawnParams.trim(), ",");

					try
					{
						int x = Integer.parseInt(st.nextToken());
						int y = Integer.parseInt(st.nextToken());
						int z = Integer.parseInt(st.nextToken());
						int heading = Integer.parseInt(st.nextToken());
						int npc_id = Integer.parseInt(st.nextToken());

						_commanderSpawns.add(new SiegeSpawn(fort.getFortId(), x, y, z, heading, npc_id, i));
					}
					catch (Exception e)
					{
						_log.warning("Error while loading commander(s) for " + fort.getName() + " fort.");
					}
				}

				_commanderSpawnList.put(fort.getFortId(), _commanderSpawns);

				for (int i = 1; i < 4; i++)
				{
					String _spawnParams = siegeSettings.getProperty(fort.getName().replace(" ", "") + "Flag" + i, "");
					if (_spawnParams.length() == 0)
						break;
					StringTokenizer st = new StringTokenizer(_spawnParams.trim(), ",");

					try
					{
						int x = Integer.parseInt(st.nextToken());
						int y = Integer.parseInt(st.nextToken());
						int z = Integer.parseInt(st.nextToken());
						int flag_id = Integer.parseInt(st.nextToken());

						_flagSpawns.add(new CombatFlag(fort.getFortId(), x, y, z, 0, flag_id));
					}
					catch (Exception e)
					{
						_log.warning("Error while loading flag(s) for " + fort.getName() + " fort.");
					}
				}
				_flagList.put(fort.getFortId(), _flagSpawns);
			}

		}
		catch (Exception e)
		{
			//_initialized = false;
			_log.log(Level.WARNING, "Error while loading fortsiege data." + e.getMessage(), e);
		}
		finally
		{
			try
			{
				is.close();
			}
			catch (Exception e)
			{
			}
		}
	}

Try With Resources try(InputStream is=new FileInputStream(file)) in method private load() : void from class com.l2jserver.gameserver.instancemanager.FortSiegeManager


	private final void load()
	{
		final File file = new File(Config.SIEGE_CONFIGURATION_FILE);
		try (InputStream is = new FileInputStream(file))
		{
			Properties siegeSettings = new Properties();
			siegeSettings.load(is);

			// Siege setting
			_attackerMaxClans = Integer.decode(siegeSettings.getProperty("AttackerMaxClans", "500"));
			_attackerRespawnDelay = Integer.decode(siegeSettings.getProperty("AttackerRespawn", "0"));
			_defenderMaxClans = Integer.decode(siegeSettings.getProperty("DefenderMaxClans", "500"));
			_flagMaxCount = Integer.decode(siegeSettings.getProperty("MaxFlags", "1"));
			_siegeClanMinLevel = Integer.decode(siegeSettings.getProperty("SiegeClanMinLevel", "5"));
			_siegeLength = Integer.decode(siegeSettings.getProperty("SiegeLength", "120"));
			_bloodAllianceReward = Integer.decode(siegeSettings.getProperty("BloodAllianceReward", "0"));

			// Siege spawns settings
			_controlTowerSpawnList = new TIntObjectHashMap<FastList<SiegeSpawn>>();
			_artefactSpawnList = new TIntObjectHashMap<FastList<SiegeSpawn>>();
			_flameTowerSpawnList = new TIntObjectHashMap<FastList<SiegeSpawn>>();

			for (Castle castle : CastleManager.getInstance().getCastles())
			{
				FastList<SiegeSpawn> _controlTowersSpawns = new FastList<SiegeSpawn>();

				for (int i = 1; i < 0xFF; i++)
				{
					String _spawnParams = siegeSettings.getProperty(castle.getName() + "ControlTower" + i, "");

					if (_spawnParams.isEmpty())
						break;

					StringTokenizer st = new StringTokenizer(_spawnParams.trim(), ",");

					try
					{
						int x = Integer.parseInt(st.nextToken());
						int y = Integer.parseInt(st.nextToken());
						int z = Integer.parseInt(st.nextToken());
						int npc_id = Integer.parseInt(st.nextToken());
						int hp = Integer.parseInt(st.nextToken());

						_controlTowersSpawns.add(new SiegeSpawn(castle.getCastleId(), x, y, z, 0, npc_id, hp));
					}
					catch (Exception e)
					{
						_log.warning("Error while loading control tower(s) for " + castle.getName() + " castle.");
					}
				}

				FastList<SiegeSpawn> _flameTowersSpawns = new FastList<SiegeSpawn>();

				for (int i = 1; i < 0xFF; i++)
				{
					String _spawnParams = siegeSettings.getProperty(castle.getName() + "FlameTower" + i, "");

					if (_spawnParams.isEmpty())
						break;

					StringTokenizer st = new StringTokenizer(_spawnParams.trim(), ",");

					try
					{
						int x = Integer.parseInt(st.nextToken());
						int y = Integer.parseInt(st.nextToken());
						int z = Integer.parseInt(st.nextToken());
						int npc_id = Integer.parseInt(st.nextToken());
						int hp = Integer.parseInt(st.nextToken());

						_flameTowersSpawns.add(new SiegeSpawn(castle.getCastleId(), x, y, z, 0, npc_id, hp));
					}
					catch (Exception e)
					{
						_log.warning("Error while loading artefact(s) for " + castle.getName() + " castle.");
					}
				}

				FastList<SiegeSpawn> _artefactSpawns = new FastList<SiegeSpawn>();

				for (int i = 1; i < 0xFF; i++)
				{
					String _spawnParams = siegeSettings.getProperty(castle.getName() + "Artefact" + i, "");

					if (_spawnParams.isEmpty())
						break;

					StringTokenizer st = new StringTokenizer(_spawnParams.trim(), ",");

					try
					{
						int x = Integer.parseInt(st.nextToken());
						int y = Integer.parseInt(st.nextToken());
						int z = Integer.parseInt(st.nextToken());
						int heading = Integer.parseInt(st.nextToken());
						int npc_id = Integer.parseInt(st.nextToken());

						_artefactSpawns.add(new SiegeSpawn(castle.getCastleId(), x, y, z, heading, npc_id));
					}
					catch (Exception e)
					{
						_log.warning("Error while loading artefact(s) for " + castle.getName() + " castle.");
					}
				}

				MercTicketManager.MERCS_MAX_PER_CASTLE[castle.getCastleId()-1] = Integer.parseInt(siegeSettings.getProperty(castle.getName() + "MaxMercenaries",
						Integer.toString(MercTicketManager.MERCS_MAX_PER_CASTLE[castle.getCastleId()-1])).trim());

				_controlTowerSpawnList.put(castle.getCastleId(), _controlTowersSpawns);
				_artefactSpawnList.put(castle.getCastleId(), _artefactSpawns);
				_flameTowerSpawnList.put(castle.getCastleId(), _flameTowersSpawns);
			}

		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Error while loading siege data: " + e.getMessage(), e);
		}
	}

	private final void load()
	{
		InputStream is = null;
		try
		{
			is = new FileInputStream(new File(Config.SIEGE_CONFIGURATION_FILE));
			Properties siegeSettings = new Properties();
			siegeSettings.load(is);

			// Siege setting
			_attackerMaxClans = Integer.decode(siegeSettings.getProperty("AttackerMaxClans", "500"));
			_attackerRespawnDelay = Integer.decode(siegeSettings.getProperty("AttackerRespawn", "0"));
			_defenderMaxClans = Integer.decode(siegeSettings.getProperty("DefenderMaxClans", "500"));
			_flagMaxCount = Integer.decode(siegeSettings.getProperty("MaxFlags", "1"));
			_siegeClanMinLevel = Integer.decode(siegeSettings.getProperty("SiegeClanMinLevel", "5"));
			_siegeLength = Integer.decode(siegeSettings.getProperty("SiegeLength", "120"));
			_bloodAllianceReward = Integer.decode(siegeSettings.getProperty("BloodAllianceReward", "0"));

			// Siege spawns settings
			_controlTowerSpawnList = new TIntObjectHashMap<FastList<SiegeSpawn>>();
			_artefactSpawnList = new TIntObjectHashMap<FastList<SiegeSpawn>>();
			_flameTowerSpawnList = new TIntObjectHashMap<FastList<SiegeSpawn>>();

			for (Castle castle : CastleManager.getInstance().getCastles())
			{
				FastList<SiegeSpawn> _controlTowersSpawns = new FastList<SiegeSpawn>();

				for (int i = 1; i < 0xFF; i++)
				{
					String _spawnParams = siegeSettings.getProperty(castle.getName() + "ControlTower" + i, "");

					if (_spawnParams.isEmpty())
						break;

					StringTokenizer st = new StringTokenizer(_spawnParams.trim(), ",");

					try
					{
						int x = Integer.parseInt(st.nextToken());
						int y = Integer.parseInt(st.nextToken());
						int z = Integer.parseInt(st.nextToken());
						int npc_id = Integer.parseInt(st.nextToken());
						int hp = Integer.parseInt(st.nextToken());

						_controlTowersSpawns.add(new SiegeSpawn(castle.getCastleId(), x, y, z, 0, npc_id, hp));
					}
					catch (Exception e)
					{
						_log.warning("Error while loading control tower(s) for " + castle.getName() + " castle.");
					}
				}

				FastList<SiegeSpawn> _flameTowersSpawns = new FastList<SiegeSpawn>();

				for (int i = 1; i < 0xFF; i++)
				{
					String _spawnParams = siegeSettings.getProperty(castle.getName() + "FlameTower" + i, "");

					if (_spawnParams.isEmpty())
						break;

					StringTokenizer st = new StringTokenizer(_spawnParams.trim(), ",");

					try
					{
						int x = Integer.parseInt(st.nextToken());
						int y = Integer.parseInt(st.nextToken());
						int z = Integer.parseInt(st.nextToken());
						int npc_id = Integer.parseInt(st.nextToken());
						int hp = Integer.parseInt(st.nextToken());

						_flameTowersSpawns.add(new SiegeSpawn(castle.getCastleId(), x, y, z, 0, npc_id, hp));
					}
					catch (Exception e)
					{
						_log.warning("Error while loading artefact(s) for " + castle.getName() + " castle.");
					}
				}

				FastList<SiegeSpawn> _artefactSpawns = new FastList<SiegeSpawn>();

				for (int i = 1; i < 0xFF; i++)
				{
					String _spawnParams = siegeSettings.getProperty(castle.getName() + "Artefact" + i, "");

					if (_spawnParams.isEmpty())
						break;

					StringTokenizer st = new StringTokenizer(_spawnParams.trim(), ",");

					try
					{
						int x = Integer.parseInt(st.nextToken());
						int y = Integer.parseInt(st.nextToken());
						int z = Integer.parseInt(st.nextToken());
						int heading = Integer.parseInt(st.nextToken());
						int npc_id = Integer.parseInt(st.nextToken());

						_artefactSpawns.add(new SiegeSpawn(castle.getCastleId(), x, y, z, heading, npc_id));
					}
					catch (Exception e)
					{
						_log.warning("Error while loading artefact(s) for " + castle.getName() + " castle.");
					}
				}

				MercTicketManager.MERCS_MAX_PER_CASTLE[castle.getCastleId()-1] = Integer.parseInt(siegeSettings.getProperty(castle.getName() + "MaxMercenaries",
						Integer.toString(MercTicketManager.MERCS_MAX_PER_CASTLE[castle.getCastleId()-1])).trim());

				_controlTowerSpawnList.put(castle.getCastleId(), _controlTowersSpawns);
				_artefactSpawnList.put(castle.getCastleId(), _artefactSpawns);
				_flameTowerSpawnList.put(castle.getCastleId(), _flameTowersSpawns);
			}

		}
		catch (Exception e)
		{
			//_initialized = false;
			_log.log(Level.WARNING, "Error while loading siege data: " + e.getMessage(), e);
		}
		finally
		{
			try
			{
				is.close();
			}
			catch (Exception e)
			{
			}
		}
	}

Try With Resources try(InputStream is=new FileInputStream(file)) in method private load() : void from class com.l2jserver.gameserver.instancemanager.SiegeManager


	private void LoadPathNodeFile(byte rx, byte ry)
	{
		if (rx < Config.WORLD_X_MIN || rx > Config.WORLD_X_MAX || ry < Config.WORLD_Y_MIN || ry > Config.WORLD_Y_MAX)
		{
			_log.warning("Failed to Load PathNode File: invalid region " + rx +","+ ry + "\n");
			return;
		}
		String fname = "./data/pathnode/" + rx + "_" + ry + ".pn";
		short regionoffset = getRegionOffset(rx, ry);
		_log.info("PathFinding Engine: - Loading: " + fname + " -> region offset: " + regionoffset + "X: " + rx + " Y: " + ry);
		File Pn = new File(fname);
		int node = 0, size, index = 0;

		// Create a read-only memory-mapped file
		try (RandomAccessFile raf = new RandomAccessFile(Pn, "r");
			FileChannel roChannel = raf.getChannel())
		{
			size = (int) roChannel.size();
			MappedByteBuffer nodes;
			if (Config.FORCE_GEODATA) //Force O/S to Loads this buffer's content into physical memory.
				//it is not guarantee, because the underlying operating system may have paged out some of the buffer's data
				nodes = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, size).load();
			else
				nodes = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, size);

			// Indexing pathnode files, so we will know where each block starts
			IntBuffer indexs = IntBuffer.allocate(65536);

			while (node < 65536)
			{
				byte layer = nodes.get(index);
				indexs.put(node++, index);
				index += layer * 10 + 1;
			}
			_pathNodesIndex.put(regionoffset, indexs);
			_pathNodes.put(regionoffset, nodes);
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Failed to Load PathNode File: " + fname + " : " + e.getMessage(), e);
		}
	}

	private void LoadPathNodeFile(byte rx, byte ry)
	{
		if (rx < Config.WORLD_X_MIN || rx > Config.WORLD_X_MAX || ry < Config.WORLD_Y_MIN || ry > Config.WORLD_Y_MAX)
		{
			_log.warning("Failed to Load PathNode File: invalid region " + rx +","+ ry + "\n");
			return;
		}
		String fname = "./data/pathnode/" + rx + "_" + ry + ".pn";
		short regionoffset = getRegionOffset(rx, ry);
		_log.info("PathFinding Engine: - Loading: " + fname + " -> region offset: " + regionoffset + "X: " + rx + " Y: " + ry);
		File Pn = new File(fname);
		int node = 0, size, index = 0;
		FileChannel roChannel = null;
		try
		{
			// Create a read-only memory-mapped file
			roChannel = new RandomAccessFile(Pn, "r").getChannel();
			size = (int) roChannel.size();
			MappedByteBuffer nodes;
			if (Config.FORCE_GEODATA) //Force O/S to Loads this buffer's content into physical memory.
				//it is not guarantee, because the underlying operating system may have paged out some of the buffer's data
				nodes = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, size).load();
			else
				nodes = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, size);

			// Indexing pathnode files, so we will know where each block starts
			IntBuffer indexs = IntBuffer.allocate(65536);

			while (node < 65536)
			{
				byte layer = nodes.get(index);
				indexs.put(node++, index);
				index += layer * 10 + 1;
			}
			_pathNodesIndex.put(regionoffset, indexs);
			_pathNodes.put(regionoffset, nodes);
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Failed to Load PathNode File: " + fname + " : " + e.getMessage(), e);
		}
		finally
		{
			try
			{
				roChannel.close();
			}
			catch (Exception e)
			{
			}
		}

	}

Try With Resources try(RandomAccessFile raf=new RandomAccessFile(Pn,"r"); FileChannel roChannel=raf.getChannel()) in method private LoadPathNodeFile(rx byte, ry byte) : void from class com.l2jserver.gameserver.pathfinding.geonodes.GeoPathFinding


	public void reportScriptFileError(File script, ScriptException e)
	{
		String dir = script.getParent();
		String name = script.getName() + ".error.log";
		if (dir != null)
		{
			final File file = new File(dir + "/" + name);
			try (FileOutputStream fos = new FileOutputStream(file))
			{
				String errorHeader = "Error on: " + file.getCanonicalPath() + "\r\nLine: " + e.getLineNumber() + " - Column: "
				+ e.getColumnNumber() + "\r\n\r\n";
				fos.write(errorHeader.getBytes());
				fos.write(e.getMessage().getBytes());
				_log.warning("Failed executing script: " + script.getAbsolutePath() + ". See " + file.getName() + " for details.");
			}
			catch (IOException ioe)
			{
				_log.log(Level.WARNING, "Failed executing script: " + script.getAbsolutePath() + "\r\n" + e.getMessage()
						+ "Additionally failed when trying to write an error report on script directory. Reason: " + ioe.getMessage(), ioe);
			}
		}
		else
		{
			_log.log(Level.WARNING, "Failed executing script: " + script.getAbsolutePath() + "\r\n" + e.getMessage()
					+ "Additionally failed when trying to write an error report on script directory.", e);
		}
	}

	public void reportScriptFileError(File script, ScriptException e)
	{
		String dir = script.getParent();
		String name = script.getName() + ".error.log";
		if (dir != null)
		{
			File file = new File(dir + "/" + name);
			FileOutputStream fos = null;
			try
			{
				if (!file.exists())
				{
					file.createNewFile();
				}

				fos = new FileOutputStream(file);
				String errorHeader = "Error on: " + file.getCanonicalPath() + "\r\nLine: " + e.getLineNumber() + " - Column: "
				+ e.getColumnNumber() + "\r\n\r\n";
				fos.write(errorHeader.getBytes());
				fos.write(e.getMessage().getBytes());
				_log.warning("Failed executing script: " + script.getAbsolutePath() + ". See " + file.getName() + " for details.");
			}
			catch (IOException ioe)
			{
				_log.log(Level.WARNING, "Failed executing script: " + script.getAbsolutePath() + "\r\n" + e.getMessage()
						+ "Additionally failed when trying to write an error report on script directory. Reason: " + ioe.getMessage(), ioe);
			}
			finally
			{
				try
				{
					fos.close();
				}
				catch (Exception e1)
				{
				}
			}
		}
		else
		{
			_log.log(Level.WARNING, "Failed executing script: " + script.getAbsolutePath() + "\r\n" + e.getMessage()
					+ "Additionally failed when trying to write an error report on script directory.", e);
		}
	}

Try With Resources try(FileOutputStream fos=new FileOutputStream(file)) in method public reportScriptFileError(script File, e ScriptException) : void from class com.l2jserver.gameserver.scripting.L2ScriptEngineManager


	private void loadBanFile()
	{
		final File bannedFile = new File("./banned_ip.cfg");
		if (bannedFile.exists() && bannedFile.isFile())
		{
			String line;
			String[] parts;
			try (FileInputStream fis = new FileInputStream(bannedFile);
				InputStreamReader is = new InputStreamReader(fis);
				LineNumberReader reader = new LineNumberReader(is))
			{
				while ((line = reader.readLine()) != null)
				{
					line = line.trim();
					// check if this line isn't a comment line
					if (line.length() > 0 && line.charAt(0) != '#')
					{
						// split comments if any
						parts = line.split("#", 2);

						// discard comments in the line, if any
						line = parts[0];

						parts = line.split(" ");

						String address = parts[0];

						long duration = 0;

						if (parts.length > 1)
						{
							try
							{
								duration = Long.parseLong(parts[1]);
							}
							catch (NumberFormatException e)
							{
								_log.warning("Skipped: Incorrect ban duration (" + parts[1] + ") on (" + bannedFile.getName() + "). Line: " + reader.getLineNumber());
								continue;
							}
						}

						try
						{
							LoginController.getInstance().addBanForAddress(address, duration);
						}
						catch (UnknownHostException e)
						{
							_log.warning("Skipped: Invalid address (" + parts[0] + ") on (" + bannedFile.getName() + "). Line: " + reader.getLineNumber());
						}
					}
				}
			}
			catch (IOException e)
			{
				_log.log(Level.WARNING, "Error while reading the bans file (" + bannedFile.getName() + "). Details: " + e.getMessage(), e);
			}
			_log.info("Loaded " + LoginController.getInstance().getBannedIps().size() + " IP Bans.");
		}
		else
		{
			_log.warning("IP Bans file (" + bannedFile.getName() + ") is missing or is a directory, skipped.");
		}

		if (Config.LOGIN_SERVER_SCHEDULE_RESTART)
		{
			_log.info("Scheduled LS restart after " + Config.LOGIN_SERVER_SCHEDULE_RESTART_TIME + " hours");
			_restartLoginServer = new LoginServerRestart();
			_restartLoginServer.setDaemon(true);
			_restartLoginServer.start();
		}
	}

	private void loadBanFile()
	{
		File bannedFile = new File("./banned_ip.cfg");
		if (bannedFile.exists() && bannedFile.isFile())
		{
			FileInputStream fis = null;
			try
			{
				fis = new FileInputStream(bannedFile);
			}
			catch (FileNotFoundException e)
			{
				_log.log(Level.WARNING, "Failed to load banned IPs file (" + bannedFile.getName() + ") for reading. Reason: " + e.getMessage(), e);
				return;
			}

			LineNumberReader reader = null;
			String line;
			String[] parts;
			try
			{
				reader = new LineNumberReader(new InputStreamReader(fis));

				while ((line = reader.readLine()) != null)
				{
					line = line.trim();
					// check if this line isnt a comment line
					if (line.length() > 0 && line.charAt(0) != '#')
					{
						// split comments if any
						parts = line.split("#", 2);

						// discard comments in the line, if any
						line = parts[0];

						parts = line.split(" ");

						String address = parts[0];

						long duration = 0;

						if (parts.length > 1)
						{
							try
							{
								duration = Long.parseLong(parts[1]);
							}
							catch (NumberFormatException e)
							{
								_log.warning("Skipped: Incorrect ban duration (" + parts[1] + ") on (" + bannedFile.getName() + "). Line: " + reader.getLineNumber());
								continue;
							}
						}

						try
						{
							LoginController.getInstance().addBanForAddress(address, duration);
						}
						catch (UnknownHostException e)
						{
							_log.warning("Skipped: Invalid address (" + parts[0] + ") on (" + bannedFile.getName() + "). Line: " + reader.getLineNumber());
						}
					}
				}
			}
			catch (IOException e)
			{
				_log.log(Level.WARNING, "Error while reading the bans file (" + bannedFile.getName() + "). Details: " + e.getMessage(), e);
			}
			finally
			{
				try
				{
					reader.close();
				}
				catch (Exception e)
				{
				}

				try
				{
					fis.close();
				}
				catch (Exception e)
				{
				}
			}
			_log.info("Loaded " + LoginController.getInstance().getBannedIps().size() + " IP Bans.");
		}
		else
		{
			_log.warning("IP Bans file (" + bannedFile.getName() + ") is missing or is a directory, skipped.");
		}

		if (Config.LOGIN_SERVER_SCHEDULE_RESTART)
		{
			_log.info("Scheduled LS restart after " + Config.LOGIN_SERVER_SCHEDULE_RESTART_TIME + " hours");
			_restartLoginServer = new LoginServerRestart();
			_restartLoginServer.setDaemon(true);
			_restartLoginServer.start();
		}
	}

Try With Resources try(FileInputStream fis=new FileInputStream(bannedFile); InputStreamReader is=new InputStreamReader(fis); LineNumberReader reader=new LineNumberReader(is)) in method private loadBanFile() : void from class com.l2jserver.loginserver.L2LoginServer


	private boolean isValidIP(Socket client)
	{
		boolean result = false;
		InetAddress ClientIP = client.getInetAddress();

		// convert IP to String, and compare with list
		String clientStringIP = ClientIP.getHostAddress();

		telnetOutput(1, "Connection from: " + clientStringIP);

		// read and loop thru list of IPs, compare with newIP
		if (Config.DEVELOPER)
			telnetOutput(2, "");

		final File file = new File(Config.TELNET_FILE);
		try (InputStream telnetIS = new FileInputStream(file);)
		{
			Properties telnetSettings = new Properties();
			telnetSettings.load(telnetIS);

			String HostList = telnetSettings.getProperty("ListOfHosts", "127.0.0.1,localhost,::1");

			if (Config.DEVELOPER)
				telnetOutput(3, "Comparing ip to list...");

			// compare
			String ipToCompare = null;
			for (String ip : HostList.split(","))
			{
				if (!result)
				{
					ipToCompare = InetAddress.getByName(ip).getHostAddress();
					if (clientStringIP.equals(ipToCompare))
						result = true;
					if (Config.DEVELOPER)
						telnetOutput(3, clientStringIP + " = " + ipToCompare + "(" + ip + ") = " + result);
				}
			}
		}
		catch (IOException e)
		{
			if (Config.DEVELOPER)
				telnetOutput(4, "");
			telnetOutput(1, "Error: " + e);
		}

		if (Config.DEVELOPER)
			telnetOutput(4, "Allow IP: " + result);
		return result;
	}

	private boolean isValidIP(Socket client)
	{
		boolean result = false;
		InetAddress ClientIP = client.getInetAddress();

		// convert IP to String, and compare with list
		String clientStringIP = ClientIP.getHostAddress();

		telnetOutput(1, "Connection from: " + clientStringIP);

		// read and loop thru list of IPs, compare with newIP
		if (Config.DEVELOPER)
			telnetOutput(2, "");

		InputStream telnetIS = null;
		try
		{
			Properties telnetSettings = new Properties();
			telnetIS = new FileInputStream(new File(Config.TELNET_FILE));
			telnetSettings.load(telnetIS);

			String HostList = telnetSettings.getProperty("ListOfHosts", "127.0.0.1,localhost,::1");

			if (Config.DEVELOPER)
				telnetOutput(3, "Comparing ip to list...");

			// compare
			String ipToCompare = null;
			for (String ip : HostList.split(","))
			{
				if (!result)
				{
					ipToCompare = InetAddress.getByName(ip).getHostAddress();
					if (clientStringIP.equals(ipToCompare))
						result = true;
					if (Config.DEVELOPER)
						telnetOutput(3, clientStringIP + " = " + ipToCompare + "(" + ip + ") = " + result);
				}
			}
		}
		catch (IOException e)
		{
			if (Config.DEVELOPER)
				telnetOutput(4, "");
			telnetOutput(1, "Error: " + e);
		}
		finally
		{
			try
			{
				telnetIS.close();
			}
			catch (Exception e)
			{
			}
		}

		if (Config.DEVELOPER)
			telnetOutput(4, "Allow IP: " + result);
		return result;
	}

Try With Resources try(InputStream telnetIS=new FileInputStream(file)) in method private isValidIP(client Socket) : boolean from class com.l2jserver.status.GameStatusThread


	private boolean isValidIP(Socket client)
	{
		boolean result = false;
		InetAddress ClientIP = client.getInetAddress();

		// convert IP to String, and compare with list
		String clientStringIP = ClientIP.getHostAddress();

		telnetOutput(1, "Connection from: " + clientStringIP);

		// read and loop thru list of IPs, compare with newIP
		if (Config.DEVELOPER)
			telnetOutput(2, "");

		final File file = new File(Config.TELNET_FILE);
		try (InputStream telnetIS = new FileInputStream(file))
		{
			Properties telnetSettings = new Properties();
			telnetSettings.load(telnetIS);

			String HostList = telnetSettings.getProperty("ListOfHosts", "127.0.0.1,localhost,::1");

			if (Config.DEVELOPER)
				telnetOutput(3, "Comparing ip to list...");

			// compare
			String ipToCompare = null;
			for (String ip : HostList.split(","))
			{
				if (!result)
				{
					ipToCompare = InetAddress.getByName(ip).getHostAddress();
					if (clientStringIP.equals(ipToCompare))
						result = true;
					if (Config.DEVELOPER)
						telnetOutput(3, clientStringIP + " = " + ipToCompare + "(" + ip + ") = " + result);
				}
			}
		}
		catch (IOException e)
		{
			if (Config.DEVELOPER)
				telnetOutput(4, "");
			telnetOutput(1, "Error: " + e);
		}

		if (Config.DEVELOPER)
			telnetOutput(4, "Allow IP: " + result);
		return result;
	}

Try With Resources try(InputStream telnetIS=new FileInputStream(file)) in method private isValidIP(client Socket) : boolean from class com.l2jserver.status.LoginStatusThread


	/**
	 * Attempts to decode Base64 data and deserialize a Java Object within.
	 * Returns <tt>null</tt> if there was an error.
	 *
	 * @param encodedObject
	 *            The Base64 data to decode
	 * @return The decoded and deserialized object
	 * @since 1.5
	 */
	public static Object decodeToObject(String encodedObject)
	{
		// Decode and gunzip if necessary
		byte[] objBytes = decode(encodedObject);
		Object obj = null;
		try (ByteArrayInputStream bais = new ByteArrayInputStream(objBytes);
			ObjectInputStream ois = new ObjectInputStream(bais))
		{
			obj = ois.readObject();
		}
		catch (IOException e)
		{
			_log.warning("Base64: " + e.getMessage());
		}
		catch (ClassNotFoundException e)
		{
			_log.warning("Base64: " + e.getMessage());
		}
		return obj;
	}

	/**
	 * Attempts to decode Base64 data and deserialize a Java Object within.
	 * Returns <tt>null</tt> if there was an error.
	 *
	 * @param encodedObject
	 *            The Base64 data to decode
	 * @return The decoded and deserialized object
	 * @since 1.5
	 */
	public static Object decodeToObject(String encodedObject)
	{
		// Decode and gunzip if necessary
		byte[] objBytes = decode(encodedObject);

		java.io.ByteArrayInputStream bais = null;
		java.io.ObjectInputStream ois = null;
		Object obj = null;

		try
		{
			bais = new java.io.ByteArrayInputStream(objBytes);
			ois = new java.io.ObjectInputStream(bais);

			obj = ois.readObject();
		}
		catch (java.io.IOException e)
		{
			_log.warning("Base64: " + e.getMessage());
		}
		catch (java.lang.ClassNotFoundException e)
		{
			_log.warning("Base64: " + e.getMessage());
		}
		finally
		{
			try
			{
				bais.close();
			}
			catch (Exception e)
			{
			}
			try
			{
				ois.close();
			}
			catch (Exception e)
			{
			}
		} // end finally

		return obj;
	} // end decodeObject

Try With Resources try(ByteArrayInputStream bais=new ByteArrayInputStream(objBytes); ObjectInputStream ois=new ObjectInputStream(bais)) in method public decodeToObject(encodedObject String) : Object from class com.l2jserver.util.Base64


	@Override
	public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IOException
	{
		if (baseName == null || locale == null || format == null || loader == null)
		{
			throw new NullPointerException();
		}
		ResourceBundle bundle = null;
		if (format.equals("java.properties"))
		{
			format = "properties";
			String bundleName = toBundleName(baseName, locale);
			String resourceName = LANGUAGES_DIRECTORY + toResourceName(bundleName, format);

			try (FileInputStream fis = new FileInputStream(resourceName);
				BufferedInputStream bis = new BufferedInputStream(fis))
			{
				bundle = new PropertyResourceBundle(bis);
			}
		}
		return bundle;
	}

	@Override
	public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IOException
	{
		if (baseName == null || locale == null || format == null || loader == null)
		{
			throw new NullPointerException();
		}
		ResourceBundle bundle = null;
		if (format.equals("java.properties"))
		{
			format = "properties";
			String bundleName = toBundleName(baseName, locale);
			String resourceName = LANGUAGES_DIRECTORY + toResourceName(bundleName, format);
			BufferedInputStream bis = null;
			try
			{
				bis = new BufferedInputStream(new FileInputStream(resourceName));
				bundle = new PropertyResourceBundle(bis);
			}
			finally
			{
				bis.close();
			}
		}
		return bundle;
	}

Try With Resources try(FileInputStream fis=new FileInputStream(resourceName); BufferedInputStream bis=new BufferedInputStream(fis)) in method public newBundle(baseName String, locale Locale, format String, loader ClassLoader, reload boolean) : ResourceBundle from class com.l2jserver.tools.i18n.LanguageControl


	/**
	 * Load game server names.
	 */
	private void loadGameServerNames()
	{
		final File xml = new File(Config.DATAPACK_ROOT, "data/servername.xml");
		try (InputStream in = new FileInputStream(xml);)
		{
			final XMLStreamReaderImpl xpp = new XMLStreamReaderImpl();
			xpp.setInput(new UTF8StreamReader().setInput(in));
			for (int e = xpp.getEventType(); e != XMLStreamConstants.END_DOCUMENT; e = xpp.next())
			{
				if (e == XMLStreamConstants.START_ELEMENT)
				{
					if (xpp.getLocalName().toString().equals("server"))
					{
						Integer id = Integer.valueOf(xpp.getAttributeValue(null, "id").toString());
						String name = xpp.getAttributeValue(null, "name").toString();
						_serverNames.put(id, name);
					}
				}
			}
			xpp.close();
		}
		catch (Exception e)
		{
			_log.info(getClass().getSimpleName() + ": Cannot load " + xml.getAbsolutePath() + "!");
		}
	}

	private void loadServerNames()
	{
		InputStream in = null;
		try
		{
			in = new FileInputStream(new File(Config.DATAPACK_ROOT, "data/servername.xml"));
			XMLStreamReaderImpl xpp = new XMLStreamReaderImpl();
			xpp.setInput(new UTF8StreamReader().setInput(in));
			for (int e = xpp.getEventType(); e != XMLStreamConstants.END_DOCUMENT; e = xpp.next())
			{
				if (e == XMLStreamConstants.START_ELEMENT)
				{
					if (xpp.getLocalName().toString().equals("server"))
					{
						Integer id = Integer.valueOf(xpp.getAttributeValue(null, "id").toString());
						String name = xpp.getAttributeValue(null, "name").toString();
						_serverNames.put(id, name);
					}
				}
			}
		}
		catch (FileNotFoundException e)
		{
			_log.warning("servername.xml could not be loaded: file not found");
		}
		catch (XMLStreamException xppe)
		{
			_log.warning(getClass().getSimpleName() + ": " + xppe.getMessage());
		}
		finally
		{
			try
			{
				in.close();
			}
			catch (Exception e)
			{
				_log.warning(getClass().getSimpleName() + ": " + e.getMessage());
			}
		}
	}

Try With Resources try(InputStream in=new FileInputStream(xml)) in method private loadGameServerNames() : void from class com.l2jserver.loginserver.GameServerTable


	private void load()
	{
		_nobles.clear();
		Connection con = null;
		boolean loaded = false;
		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement(OLYMPIAD_LOAD_DATA);
			ResultSet rset = statement.executeQuery();

			while (rset.next())
			{
				_currentCycle = rset.getInt("current_cycle");
				_period = rset.getInt("period");
				_olympiadEnd = rset.getLong("olympiad_end");
				_validationEnd = rset.getLong("validation_end");
				_nextWeeklyChange = rset.getLong("next_weekly_change");
				loaded = true;
			}

			rset.close();
			statement.close();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Olympiad System: Error loading olympiad data from database: ", e);
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}

		if (!loaded)
		{
			_log.log(Level.INFO, "Olympiad System: failed to load data from database, trying to load from file.");

			Properties OlympiadProperties = new Properties();
			try (InputStream is = new FileInputStream(new File("./" + OLYMPIAD_DATA_FILE)))
			{

				OlympiadProperties.load(is);
			}
			catch (Exception e)
			{
				_log.log(Level.SEVERE, "Olympiad System: Error loading olympiad properties: ", e);
				return;
			}

			_currentCycle = Integer.parseInt(OlympiadProperties.getProperty("CurrentCycle", "1"));
			_period = Integer.parseInt(OlympiadProperties.getProperty("Period", "0"));
			_olympiadEnd = Long.parseLong(OlympiadProperties.getProperty("OlympiadEnd", "0"));
			_validationEnd = Long.parseLong(OlympiadProperties.getProperty("ValidationEnd", "0"));
			_nextWeeklyChange = Long.parseLong(OlympiadProperties.getProperty("NextWeeklyChange", "0"));
		}

		switch (_period)
		{
			case 0:
				if ((_olympiadEnd == 0) || (_olympiadEnd < Calendar.getInstance().getTimeInMillis()))
				{
					setNewOlympiadEnd();
				}
				else
				{
					scheduleWeeklyChange();
				}
				break;
			case 1:
				if (_validationEnd > Calendar.getInstance().getTimeInMillis())
				{
					loadNoblesRank();
					_scheduledValdationTask = ThreadPoolManager.getInstance().scheduleGeneral(new ValidationEndTask(), getMillisToValidationEnd());
				}
				else
				{
					_currentCycle++;
					_period = 0;
					deleteNobles();
					setNewOlympiadEnd();
				}
				break;
			default:
				_log.warning("Olympiad System: Omg something went wrong in loading!! Period = " + _period);
				return;
		}

		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			final PreparedStatement statement = con.prepareStatement(OLYMPIAD_LOAD_NOBLES);
			final ResultSet rset = statement.executeQuery();
			StatsSet statData;
			while (rset.next())
			{
				statData = new StatsSet();
				statData.set(CLASS_ID, rset.getInt(CLASS_ID));
				statData.set(CHAR_NAME, rset.getString(CHAR_NAME));
				statData.set(POINTS, rset.getInt(POINTS));
				statData.set(COMP_DONE, rset.getInt(COMP_DONE));
				statData.set(COMP_WON, rset.getInt(COMP_WON));
				statData.set(COMP_LOST, rset.getInt(COMP_LOST));
				statData.set(COMP_DRAWN, rset.getInt(COMP_DRAWN));
				statData.set(COMP_DONE_WEEK, rset.getInt(COMP_DONE_WEEK));
				statData.set(COMP_DONE_WEEK_CLASSED, rset.getInt(COMP_DONE_WEEK_CLASSED));
				statData.set(COMP_DONE_WEEK_NON_CLASSED, rset.getInt(COMP_DONE_WEEK_NON_CLASSED));
				statData.set(COMP_DONE_WEEK_TEAM, rset.getInt(COMP_DONE_WEEK_TEAM));
				statData.set("to_save", false);

				addNobleStats(rset.getInt(CHAR_ID), statData);
			}

			rset.close();
			statement.close();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Olympiad System: Error loading noblesse data from database: ", e);
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}

		synchronized (this)
		{
			_log.info("Olympiad System: Loading Olympiad System....");
			if (_period == 0)
			{
				_log.info("Olympiad System: Currently in Olympiad Period");
			}
			else
			{
				_log.info("Olympiad System: Currently in Validation Period");
			}

			long milliToEnd;
			if (_period == 0)
			{
				milliToEnd = getMillisToOlympiadEnd();
			}
			else
			{
				milliToEnd = getMillisToValidationEnd();
			}

			_log.info("Olympiad System: " + (milliToEnd / 60000) + " minutes until period ends");

			if (_period == 0)
			{
				milliToEnd = getMillisToWeekChange();

				_log.info("Olympiad System: Next weekly change is in " + (milliToEnd / 60000) + " minutes");
			}
		}

		_log.info("Olympiad System: Loaded " + _nobles.size() + " Nobles");

	}

	private void load()
	{
		_nobles.clear();
		Connection con = null;
		boolean loaded = false;
		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement(OLYMPIAD_LOAD_DATA);
			ResultSet rset = statement.executeQuery();

			while (rset.next())
			{
				_currentCycle = rset.getInt("current_cycle");
				_period = rset.getInt("period");
				_olympiadEnd = rset.getLong("olympiad_end");
				_validationEnd = rset.getLong("validation_end");
				_nextWeeklyChange = rset.getLong("next_weekly_change");
				loaded = true;
			}

			rset.close();
			statement.close();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Olympiad System: Error loading olympiad data from database: ", e);
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}

		if (!loaded)
		{
			_log.log(Level.INFO, "Olympiad System: failed to load data from database, trying to load from file.");

			Properties OlympiadProperties = new Properties();
			InputStream is = null;
			try
			{
				is = new FileInputStream(new File("./" + OLYMPIAD_DATA_FILE));
				OlympiadProperties.load(is);
			}
			catch (Exception e)
			{
				_log.log(Level.SEVERE, "Olympiad System: Error loading olympiad properties: ", e);
				return;
			}
			finally
			{
				try
				{
					is.close();
				}
				catch (Exception e)
				{
					_log.log(Level.WARNING, "", e);
				}
			}

			_currentCycle = Integer.parseInt(OlympiadProperties.getProperty("CurrentCycle", "1"));
			_period = Integer.parseInt(OlympiadProperties.getProperty("Period", "0"));
			_olympiadEnd = Long.parseLong(OlympiadProperties.getProperty("OlympiadEnd", "0"));
			_validationEnd = Long.parseLong(OlympiadProperties.getProperty("ValidationEnd", "0"));
			_nextWeeklyChange = Long.parseLong(OlympiadProperties.getProperty("NextWeeklyChange", "0"));
		}

		switch (_period)
		{
			case 0:
				if ((_olympiadEnd == 0) || (_olympiadEnd < Calendar.getInstance().getTimeInMillis()))
				{
					setNewOlympiadEnd();
				}
				else
				{
					scheduleWeeklyChange();
				}
				break;
			case 1:
				if (_validationEnd > Calendar.getInstance().getTimeInMillis())
				{
					loadNoblesRank();
					_scheduledValdationTask = ThreadPoolManager.getInstance().scheduleGeneral(new ValidationEndTask(), getMillisToValidationEnd());
				}
				else
				{
					_currentCycle++;
					_period = 0;
					deleteNobles();
					setNewOlympiadEnd();
				}
				break;
			default:
				_log.warning("Olympiad System: Omg something went wrong in loading!! Period = " + _period);
				return;
		}

		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			final PreparedStatement statement = con.prepareStatement(OLYMPIAD_LOAD_NOBLES);
			final ResultSet rset = statement.executeQuery();
			StatsSet statData;
			while (rset.next())
			{
				statData = new StatsSet();
				statData.set(CLASS_ID, rset.getInt(CLASS_ID));
				statData.set(CHAR_NAME, rset.getString(CHAR_NAME));
				statData.set(POINTS, rset.getInt(POINTS));
				statData.set(COMP_DONE, rset.getInt(COMP_DONE));
				statData.set(COMP_WON, rset.getInt(COMP_WON));
				statData.set(COMP_LOST, rset.getInt(COMP_LOST));
				statData.set(COMP_DRAWN, rset.getInt(COMP_DRAWN));
				statData.set(COMP_DONE_WEEK, rset.getInt(COMP_DONE_WEEK));
				statData.set(COMP_DONE_WEEK_CLASSED, rset.getInt(COMP_DONE_WEEK_CLASSED));
				statData.set(COMP_DONE_WEEK_NON_CLASSED, rset.getInt(COMP_DONE_WEEK_NON_CLASSED));
				statData.set(COMP_DONE_WEEK_TEAM, rset.getInt(COMP_DONE_WEEK_TEAM));
				statData.set("to_save", false);

				addNobleStats(rset.getInt(CHAR_ID), statData);
			}

			rset.close();
			statement.close();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Olympiad System: Error loading noblesse data from database: ", e);
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}

		synchronized (this)
		{
			_log.info("Olympiad System: Loading Olympiad System....");
			if (_period == 0)
			{
				_log.info("Olympiad System: Currently in Olympiad Period");
			}
			else
			{
				_log.info("Olympiad System: Currently in Validation Period");
			}

			long milliToEnd;
			if (_period == 0)
			{
				milliToEnd = getMillisToOlympiadEnd();
			}
			else
			{
				milliToEnd = getMillisToValidationEnd();
			}

			_log.info("Olympiad System: " + (milliToEnd / 60000) + " minutes until period ends");

			if (_period == 0)
			{
				milliToEnd = getMillisToWeekChange();

				_log.info("Olympiad System: Next weekly change is in " + (milliToEnd / 60000) + " minutes");
			}
		}

		_log.info("Olympiad System: Loaded " + _nobles.size() + " Nobles");

	}

Try With Resources try(InputStream is=new FileInputStream(new File("./" + OLYMPIAD_DATA_FILE))) in method private load() : void from class com.l2jserver.gameserver.model.olympiad.Olympiad


	private ArmorSetsTable()
	{
		_armorSets = new FastList<>();
		loadData();
	}

	private ArmorSetsTable()
	{
		_armorSets = new TIntObjectHashMap<L2ArmorSet>();
		loadData();
	}

Replace Generic With Diamond TIntObjectHashMap<L2ArmorSet> with FastList<> in method private ArmorSetsTable() from class com.l2jserver.gameserver.datatables.ArmorSetsTable


	public String loadFile(File file)
	{
		final String relpath = Util.getRelativePath(Config.DATAPACK_ROOT, file);
		final int hashcode = relpath.hashCode();
		String content = null;
		if (htmlFilter.accept(file))
		{
			try (FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis);)
			{
				final int bytes = bis.available();
				byte[] raw = new byte[bytes];

				bis.read(raw);
				content = new String(raw, "UTF-8");
				content = content.replaceAll("\r\n", "\n");

				String oldContent = _cache.get(hashcode);
				if (oldContent == null)
				{
					_bytesBuffLen += bytes;
					_loadedFiles++;
				}
				else
				{
					_bytesBuffLen = (_bytesBuffLen - oldContent.length()) + bytes;
				}
				_cache.put(hashcode, content);
			}
			catch (Exception e)
			{
				_log.log(Level.WARNING, "Problem with htm file " + e.getMessage(), e);
			}
		}
		return content;
	}

	public String loadFile(File file)
	{
		final String relpath = Util.getRelativePath(Config.DATAPACK_ROOT, file);
		final int hashcode = relpath.hashCode();

		final HtmFilter filter = new HtmFilter();

		if (file.exists() && filter.accept(file) && !file.isDirectory())
		{
			String content;
			FileInputStream fis = null;

			try
			{
				fis = new FileInputStream(file);
				BufferedInputStream bis = new BufferedInputStream(fis);
				int bytes = bis.available();
				byte[] raw = new byte[bytes];

				bis.read(raw);
				content = new String(raw, "UTF-8");
				content = content.replaceAll("\r\n", "\n");

				String oldContent = _cache.get(hashcode);

				if (oldContent == null)
				{
					_bytesBuffLen += bytes;
					_loadedFiles++;
				}
				else
				{
					_bytesBuffLen = _bytesBuffLen - oldContent.length() + bytes;
				}

				_cache.put(hashcode, content);

				return content;
			}
			catch (Exception e)
			{
				_log.log(Level.WARNING, "Problem with htm file " + e.getMessage(), e);
			}
			finally
			{
				try
				{
					fis.close();
				}
				catch (Exception e1)
				{
				}
			}
		}

		return null;
	}

Try With Resources try(FileInputStream fis=new FileInputStream(file); BufferedInputStream bis=new BufferedInputStream(fis)) in method public loadFile(file File) : String from class com.l2jserver.gameserver.cache.HtmCache


	private void loadMails()
	{
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setValidating(false);
		factory.setIgnoringComments(true);
		File file = new File(Config.DATAPACK_ROOT, "data/mail/MailList.xml");
		Document doc = null;
		if (file.exists())
		{
			try
			{
				doc = factory.newDocumentBuilder().parse(file);
			}
			catch (Exception e)
			{
				_log.log(Level.WARNING, "Could not parse MailList.xml file: " + e.getMessage(), e);
				return;
			}

			Node n = doc.getFirstChild();
			File mailFile;
			for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling())
			{
				if (d.getNodeName().equals("mail"))
				{
					String mailId = d.getAttributes().getNamedItem("id").getNodeValue();
					String subject = d.getAttributes().getNamedItem("subject").getNodeValue();
					String maFile = d.getAttributes().getNamedItem("file").getNodeValue();

					mailFile = new File(Config.DATAPACK_ROOT, "data/mail/" + maFile);
					try (FileInputStream fis = new FileInputStream(mailFile);
						BufferedInputStream bis = new BufferedInputStream(fis);)
					{
						int bytes = bis.available();
						byte[] raw = new byte[bytes];

						bis.read(raw);
						String html = new String(raw, "UTF-8");
						html = html.replaceAll("\r\n", "\n");
						html = html.replace("%servermail%", Config.EMAIL_SERVERINFO_ADDRESS);
						html = html.replace("%servername%", Config.EMAIL_SERVERINFO_NAME);

						_mailData.put(mailId, new MailContent(subject, html));
					}
					catch (IOException e)
					{
						_log.warning("IOException while reading " + maFile);
					}
				}
			}
			_log.info("eMail System Loaded");
		}
		else
		{
			_log.warning("Cannot load eMail System - Missing file MailList.xml");
		}
	}

	private void loadMails()
	{
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setValidating(false);
		factory.setIgnoringComments(true);
		File file = new File(Config.DATAPACK_ROOT, "data/mail/MailList.xml");
		Document doc = null;
		if (file.exists())
		{
			try
			{
				doc = factory.newDocumentBuilder().parse(file);
			}
			catch (Exception e)
			{
				_log.log(Level.WARNING, "Could not parse MailList.xml file: " + e.getMessage(), e);
				return;
			}

			Node n = doc.getFirstChild();
			for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling())
			{
				if (d.getNodeName().equals("mail"))
				{
					String mailId = d.getAttributes().getNamedItem("id").getNodeValue();
					String subject = d.getAttributes().getNamedItem("subject").getNodeValue();
					String maFile = d.getAttributes().getNamedItem("file").getNodeValue();

					try
					{
						FileInputStream fis = new FileInputStream(new File(Config.DATAPACK_ROOT, "data/mail/" + maFile));
						BufferedInputStream bis = new BufferedInputStream(fis);
						int bytes = bis.available();
						byte[] raw = new byte[bytes];

						bis.read(raw);
						String html = new String(raw, "UTF-8");
						html = html.replaceAll("\r\n", "\n");
						html = html.replace("%servermail%", Config.EMAIL_SERVERINFO_ADDRESS);
						html = html.replace("%servername%", Config.EMAIL_SERVERINFO_NAME);

						_mailData.put(mailId, new MailContent(subject, html));
					}
					catch (IOException e)
					{
						_log.warning("IOException while reading " + maFile);
					}
				}
			}
			_log.info("eMail System Loaded");
		}
		else
		{
			_log.warning("Cannot load eMail System - Missing file MailList.xml");
		}
	}

Try With Resources try(FileInputStream fis=new FileInputStream(mailFile); BufferedInputStream bis=new BufferedInputStream(fis)) in method private loadMails() : void from class com.l2jserver.loginserver.mail.MailSystem


    @NonNull
    private String getContentAsString(@NonNull final HttpEntity entity, @NonNull final Charset charset) {
        String result = "";
        try (final BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent(), charset))) {
            var line = "";
            final var sb = new StringBuilder();
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }

            result = sb.toString();
        } catch (final IllegalStateException | IOException e) {
            LOGGER.logp(Level.SEVERE, "HTTPManager", "getContent", e.getMessage(), e);
        }

        return result;
    }

    @NonNull
    private String getContentAsString(@NonNull final HttpEntity entity, @NonNull final Charset charset) {
        String result = "";
        try (final BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent(), charset))) {
            var line = "";
            final var sb = new StringBuilder();
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }

            result = sb.toString();
        } catch (final IllegalStateException e) {
            LOGGER.logp(Level.SEVERE, "HTTPManager", "getContent", e.getMessage(), e);
        } catch (final IOException e) {
            LOGGER.logp(Level.SEVERE, "HTTPManager", "getContent", e.getMessage(), e);
        }

        return result;
    }

Merge Catch [catch(final IllegalStateException e), catch(final IOException e)] to catch(final IllegalStateException|IOException e) in method private getContentAsString(entity HttpEntity, charset Charset) : String from class aka.jhttprequest.main.HTTPManager


    @NonNull
    private DefaultHttpClient getHttpClient(@NonNull final HTTPRequestData httpRequestData) {
        final var httpclient = new DefaultHttpClient();

        if (httpRequestData.isSSl() && httpRequestData.isAllowSelfSignedCertificate()) {
            // this code is to allow self-signed certificates
            try {
                // add ssl if necessary
                // Now put the trust manager into an SSLContext.
                // Supported: SSL, SSLv2, SSLv3, TLS, TLSv1, TLSv1.1
                final var sslContext = SSLContext.getInstance("SSL");
                sslContext.init(null, this.trustAllCerts, new SecureRandom());
                final var sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

                // Register our new socket factory with the typical SSL port and the
                // correct protocol name.
                final var httpsScheme = new Scheme("https", 443, sf);
                httpclient.getConnectionManager().getSchemeRegistry().register(httpsScheme);

            } catch (final KeyManagementException | NoSuchAlgorithmException e) {
                LOGGER.logp(Level.SEVERE, "HTTPManager", "getHttpClient", e.getMessage(), e);
            }
        }

        return httpclient;
    }

    @NonNull
    private DefaultHttpClient getHttpClient(@NonNull final HTTPRequestData httpRequestData) {
        final var httpclient = new DefaultHttpClient();

        if (httpRequestData.isSSl() && httpRequestData.isAllowSelfSignedCertificate()) {
            // this code is to allow self-signed certificates
            try {
                // add ssl if necessary
                // Now put the trust manager into an SSLContext.
                // Supported: SSL, SSLv2, SSLv3, TLS, TLSv1, TLSv1.1
                final var sslContext = SSLContext.getInstance("SSL");
                sslContext.init(null, this.trustAllCerts, new SecureRandom());
                final var sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

                // Register our new socket factory with the typical SSL port and the
                // correct protocol name.
                final var httpsScheme = new Scheme("https", 443, sf);
                httpclient.getConnectionManager().getSchemeRegistry().register(httpsScheme);

            } catch (final KeyManagementException e) {
                LOGGER.logp(Level.SEVERE, "HTTPManager", "getHttpClient", e.getMessage(), e);
            } catch (final NoSuchAlgorithmException e) {
                LOGGER.logp(Level.SEVERE, "HTTPManager", "getHttpClient", e.getMessage(), e);
            }
        }

        return httpclient;
    }

Merge Catch [catch(final KeyManagementException e), catch(final NoSuchAlgorithmException e)] to catch(final KeyManagementException|NoSuchAlgorithmException e) in method private getHttpClient(httpRequestData HTTPRequestData) : DefaultHttpClient from class aka.jhttprequest.main.HTTPManager


    public static void main(String[] args)
    {
        try(FileInputStream propFile = new FileInputStream("config.properties"))
        {
            Properties prop = new Properties();
            prop.load(propFile);

            String spClientId = prop.getProperty("spotify_client_id");
            String spClientSecret = prop.getProperty("spotify_client_secret");
            String redirectUrl = prop.getProperty("redirect_url");

            spotifyApi = new SpotifyApi.Builder()
                .setClientId(spClientId)
                .setClientSecret(spClientSecret)
                .setRedirectUri(SpotifyHttpManager.makeUri(redirectUrl))
                .build();

            AuthorizationCodeCredentials authorizationCodeCredentials = getAuthCredentials();
            spotifyApi.setAccessToken(authorizationCodeCredentials.getAccessToken());
            spotifyApi.setRefreshToken(authorizationCodeCredentials.getRefreshToken());
            System.out.println("Set access/refresh token.");

            ScheduledTasks.init();
        }

        catch(Exception e)
        {
            System.out.println("Error occurred: " + e.getMessage());
        }
    }

    public static void main(String[] args)
    {
        try
        {
            Properties prop = new Properties();
            FileInputStream propFile = new FileInputStream("config.properties");
            prop.load(propFile);

            String spClientId = prop.getProperty("spotify_client_id");
            String spClientSecret = prop.getProperty("spotify_client_secret");

            spotifyApi = new SpotifyApi.Builder()
                .setClientId(spClientId)
                .setClientSecret(spClientSecret)
                .setRedirectUri(SpotifyHttpManager.makeUri("https://angelolz.one"))
                .build();

            AuthorizationCodeCredentials authorizationCodeCredentials = getAuthCredentials();
            spotifyApi.setAccessToken(authorizationCodeCredentials.getAccessToken());
            spotifyApi.setRefreshToken(authorizationCodeCredentials.getRefreshToken());
            System.out.println("Set access/refresh token.");

            ScheduledTasks.init();
        }

        catch(Exception e)
        {
            System.out.println("oopsies something went wrong");
            e.printStackTrace();
        }
    }

Try With Resources try(FileInputStream propFile=new FileInputStream("config.properties")) in method public main(args String[]) : void from class DaylistSaver


	@Override
	public byte[] readNextChunk(final InputStream stream, final long size, final long currentOffset) {
		try (final ByteArrayOutputStream dataBuffer = new ByteArrayOutputStream()) {
			int normalSize = expectedSize;
			//noinspection StandardVariableNames
			long n = size - currentOffset;
			if (n <= 0) {
				throw new IllegalArgumentException(
						"Attempting to read the next chunk but out of available bytes, as indicated by size");
			}
			if (n <= FastCdcChunkerCore.MIN_SIZE) {
				return stream.readNBytes((int) n);
			}
			if (n >= FastCdcChunkerCore.MAX_SIZE) {
				n = FastCdcChunkerCore.MAX_SIZE;
			} else if (n <= normalSize) {
				normalSize = (int) n;
			}

			long fingerprint = 0;
			int i = FastCdcChunkerCore.MIN_SIZE;
			dataBuffer.write(stream.readNBytes(i));

			//noinspection ForLoopWithMissingComponent
			for (; i < normalSize; i++) {
				final int data = stream.read();
				if (data == -1) {
					throw new IllegalStateException(
							"Attempting to read a byte from the stream but the stream has ended");
				}
				dataBuffer.write(data);
				fingerprint = (fingerprint << 1) + gear[data];
				if ((fingerprint & FastCdcChunkerCore.MASK_S) == 0) {
					return dataBuffer.toByteArray();
				}
			}
			//noinspection ForLoopWithMissingComponent
			for (; i < n; i++) {
				final int data = stream.read();
				if (data == -1) {
					throw new IllegalStateException(
							"Attempting to read a byte from the stream but the stream has ended");
				}
				dataBuffer.write(data);
				fingerprint = (fingerprint << 1) + gear[data];
				if ((fingerprint & FastCdcChunkerCore.MASK_L) == 0) {
					return dataBuffer.toByteArray();
				}
			}

			return dataBuffer.toByteArray();

		} catch (final IOException e) {
			throw new UncheckedIOException(e);
		}
	}

	@Override
	public byte[] readNextChunk(final InputStream stream, final long size, final long currentOffset) {
		try {
			int normalSize = expectedSize;
			long n = size - currentOffset;
			if (n <= 0) {
				throw new IllegalArgumentException();
			}
			if (n <= MIN_SIZE) {
				return stream.readNBytes((int) n);
			}
			if (n >= MAX_SIZE) {
				n = MAX_SIZE;
			} else if (n <= normalSize) {
				normalSize = (int) n;
			}

			ByteArrayOutputStream dataBuffer = new ByteArrayOutputStream();
			long fingerprint = 0;
			int i = MIN_SIZE;
			dataBuffer.write(stream.readNBytes(i));

			for (; i < normalSize; i++) {
				int data = stream.read();
				if (data == -1) {
					throw new IllegalStateException();
				}
				dataBuffer.write(data);
				fingerprint = (fingerprint << 1) + gear[data];
				if ((fingerprint & MASK_S) == 0) {
					return dataBuffer.toByteArray();
				}
			}
			for (; i < n; i++) {
				int data = stream.read();
				if (data == -1) {
					throw new IllegalStateException();
				}
				dataBuffer.write(data);
				fingerprint = (fingerprint << 1) + gear[data];
				if ((fingerprint & MASK_L) == 0) {
					return dataBuffer.toByteArray();
				}
			}

			return dataBuffer.toByteArray();
		} catch (IOException e) {
			throw new UncheckedIOException(e);
		}
	}

Try With Resources try(final ByteArrayOutputStream dataBuffer=new ByteArrayOutputStream()) in method public readNextChunk(stream InputStream, size long, currentOffset long) : byte[] from class de.zabuza.fastcdc4j.internal.chunking.FastCdcChunkerCore


	@Override
	public byte[] readNextChunk(final InputStream stream, final long size, final long currentOffset) {
		try (final ByteArrayOutputStream dataBuffer = new ByteArrayOutputStream()) {
			int normalSize = expectedSize;
			//noinspection StandardVariableNames
			long n = size - currentOffset;
			if (n <= 0) {
				throw new IllegalArgumentException(
						"Attempting to read the next chunk but out of available bytes, as indicated by size");
			}
			if (n <= NlfiedlerRustChunkerCore.MIN_SIZE) {
				return stream.readNBytes((int) n);
			}
			if (n >= NlfiedlerRustChunkerCore.MAX_SIZE) {
				n = NlfiedlerRustChunkerCore.MAX_SIZE;
			} else if (n <= normalSize) {
				normalSize = (int) n;
			}

			long fingerprint = 0;
			int i = NlfiedlerRustChunkerCore.MIN_SIZE;
			dataBuffer.write(stream.readNBytes(i));

			//noinspection ForLoopWithMissingComponent
			for (; i < normalSize; i++) {
				final int data = stream.read();
				if (data == -1) {
					throw new IllegalStateException(
							"Attempting to read a byte from the stream but the stream has ended");
				}
				dataBuffer.write(data);
				fingerprint = (fingerprint >> 1) + gear[data];
				if ((fingerprint & NlfiedlerRustChunkerCore.MASK_S) == 0) {
					return dataBuffer.toByteArray();
				}
			}
			//noinspection ForLoopWithMissingComponent
			for (; i < n; i++) {
				final int data = stream.read();
				if (data == -1) {
					throw new IllegalStateException(
							"Attempting to read a byte from the stream but the stream has ended");
				}
				dataBuffer.write(data);
				fingerprint = (fingerprint >> 1) + gear[data];
				if ((fingerprint & NlfiedlerRustChunkerCore.MASK_L) == 0) {
					return dataBuffer.toByteArray();
				}
			}

			return dataBuffer.toByteArray();
		} catch (final IOException e) {
			throw new UncheckedIOException(e);
		}
	}

	@Override
	public byte[] readNextChunk(final InputStream stream, final long size, final long currentOffset) {
		try {
			int normalSize = expectedSize;
			long n = size - currentOffset;
			if (n <= 0) {
				throw new IllegalArgumentException();
			}
			if (n <= MIN_SIZE) {
				return stream.readNBytes((int) n);
			}
			if (n >= MAX_SIZE) {
				n = MAX_SIZE;
			} else if (n <= normalSize) {
				normalSize = (int) n;
			}

			ByteArrayOutputStream dataBuffer = new ByteArrayOutputStream();
			long fingerprint = 0;
			int i = MIN_SIZE;
			dataBuffer.write(stream.readNBytes(i));

			for (; i < normalSize; i++) {
				int data = stream.read();
				if (data == -1) {
					throw new IllegalStateException();
				}
				dataBuffer.write(data);
				fingerprint = (fingerprint >> 1) + gear[data];
				if ((fingerprint & MASK_S) == 0) {
					return dataBuffer.toByteArray();
				}
			}
			for (; i < n; i++) {
				int data = stream.read();
				if (data == -1) {
					throw new IllegalStateException();
				}
				dataBuffer.write(data);
				fingerprint = (fingerprint >> 1) + gear[data];
				if ((fingerprint & MASK_L) == 0) {
					return dataBuffer.toByteArray();
				}
			}

			return dataBuffer.toByteArray();
		} catch (IOException e) {
			throw new UncheckedIOException(e);
		}
	}

Try With Resources try(final ByteArrayOutputStream dataBuffer=new ByteArrayOutputStream()) in method public readNextChunk(stream InputStream, size long, currentOffset long) : byte[] from class de.zabuza.fastcdc4j.internal.chunking.NlfiedlerRustChunkerCore


    public EstudoBiblicoCongregacao buscarEstudoBiblicoCongregacaoSemDataMaisAntigaParaPessoas(List<Integer> idsPessoasIgnorar) {
        try (EntityManager em = FabricaJPA.getEntityManager()) {
            String queryString = "SELECT e FROM EstudoBiblicoCongregacao e WHERE e.pessoa.id NOT IN (:idsPessoasIgnorar) ORDER BY e.data ASC NULLS FIRST";
            TypedQuery<EstudoBiblicoCongregacao> query = em.createQuery(queryString, EstudoBiblicoCongregacao.class)
                    .setParameter("idsPessoasIgnorar", idsPessoasIgnorar)
                    .setMaxResults(1);
            List<EstudoBiblicoCongregacao> estudos = query.getResultList();
            if (!estudos.isEmpty()) {
                return estudos.get(0);
            }
            return null;
        }
    }

    public EstudoBiblicoCongregacao buscarEstudoBiblicoCongregacaoSemDataMaisAntigaParaPessoas(List<Integer> idsPessoasIgnorar) {
        EntityManager em = FabricaJPA.getEntityManager();
        try {
            String queryString = "SELECT e FROM EstudoBiblicoCongregacao e WHERE e.pessoa.id NOT IN (:idsPessoasIgnorar) ORDER BY e.data ASC NULLS FIRST";
            TypedQuery<EstudoBiblicoCongregacao> query = em.createQuery(queryString, EstudoBiblicoCongregacao.class)
                    .setParameter("idsPessoasIgnorar", idsPessoasIgnorar)
                    .setMaxResults(1);
            List<EstudoBiblicoCongregacao> estudos = query.getResultList();
            if (!estudos.isEmpty()) {
                return estudos.get(0);
            }
            return null;
        } finally {
            em.close();
        }
    }

Try With Resources try(EntityManager em=FabricaJPA.getEntityManager()) in method public buscarEstudoBiblicoCongregacaoSemDataMaisAntigaParaPessoas(idsPessoasIgnorar List<Integer>) : EstudoBiblicoCongregacao from class br.com.alexlopes.designacoes.dao.EstudoBiblicoCongregacaoDAO


    public EstudoBiblicoCongregacao buscarEstudoBiblicoCongregacaoSemDataMaisAntigaParaPessoas2() {
        try (EntityManager em = FabricaJPA.getEntityManager()) {
            String queryString = "SELECT e FROM EstudoBiblicoCongregacao e WHERE e.data IS NULL OR e.data = (SELECT MIN(eb.data) FROM EstudoBiblicoCongregacao eb WHERE eb.data IS NOT NULL)";
            TypedQuery<EstudoBiblicoCongregacao> query = em.createQuery(queryString, EstudoBiblicoCongregacao.class);

            List<EstudoBiblicoCongregacao> estudos = query.getResultList();
            if (!estudos.isEmpty()) {
                // Gerar um índice aleatório dentro do intervalo da lista
                Random random = new Random();
                int indiceAleatorio = random.nextInt(estudos.size());
                return estudos.get(indiceAleatorio);
            }
            return null;
        }
    }

    public EstudoBiblicoCongregacao buscarEstudoBiblicoCongregacaoSemDataMaisAntigaParaPessoas2() {
        EntityManager em = FabricaJPA.getEntityManager();
        try {
            String queryString = "SELECT e FROM EstudoBiblicoCongregacao e WHERE e.data IS NULL OR e.data = (SELECT MIN(eb.data) FROM EstudoBiblicoCongregacao eb WHERE eb.data IS NOT NULL)";
            TypedQuery<EstudoBiblicoCongregacao> query = em.createQuery(queryString, EstudoBiblicoCongregacao.class);

            List<EstudoBiblicoCongregacao> estudos = query.getResultList();
            if (!estudos.isEmpty()) {
                // Gerar um índice aleatório dentro do intervalo da lista
                Random random = new Random();
                int indiceAleatorio = random.nextInt(estudos.size());
                return estudos.get(indiceAleatorio);
            }
            return null;
        } finally {
            em.close();
        }
    }

Try With Resources try(EntityManager em=FabricaJPA.getEntityManager()) in method public buscarEstudoBiblicoCongregacaoSemDataMaisAntigaParaPessoas2() : EstudoBiblicoCongregacao from class br.com.alexlopes.designacoes.dao.EstudoBiblicoCongregacaoDAO


    public void alterarDataEstudoBiblicoCongregacao(int estudoId, LocalDate novaData) {
        try (EntityManager em = FabricaJPA.getEntityManager()) {
            em.getTransaction().begin();
            EstudoBiblicoCongregacao estudo = em.find(EstudoBiblicoCongregacao.class, estudoId);
            if (estudo != null) {
                estudo.setData(novaData);
                em.merge(estudo);
            }
            em.getTransaction().commit();
        } catch (Exception e) {
        }
    }

    public void alterarDataEstudoBiblicoCongregacao(int estudoId, LocalDate novaData) {
        EntityManager em = FabricaJPA.getEntityManager();
        try {
            em.getTransaction().begin();
            EstudoBiblicoCongregacao estudo = em.find(EstudoBiblicoCongregacao.class, estudoId);
            if (estudo != null) {
                estudo.setData(novaData);
                em.merge(estudo);
            }
            em.getTransaction().commit();
        } catch (Exception e) {
        } finally {
            em.close();
        }
    }

Try With Resources try(EntityManager em=FabricaJPA.getEntityManager()) in method public alterarDataEstudoBiblicoCongregacao(estudoId int, novaData LocalDate) : void from class br.com.alexlopes.designacoes.dao.EstudoBiblicoCongregacaoDAO


    public EstudoBiblicoCongregacao buscarPorIdPessoa(int idPessoa) {
        try (EntityManager em = FabricaJPA.getEntityManager()) {
            String jpql = "SELECT p FROM EstudoBiblicoCongregacao p WHERE p.pessoa.id = :idPessoa";
            TypedQuery<EstudoBiblicoCongregacao> query = em.createQuery(jpql, EstudoBiblicoCongregacao.class);
            query.setParameter("idPessoa", idPessoa);
            List<EstudoBiblicoCongregacao> resultados = query.getResultList();
            if (!resultados.isEmpty()) {
                return resultados.get(0);
            }
            return null; // Retorna nulo se não encontrar um presidente com o ID da pessoa
        }
    }

    public EstudoBiblicoCongregacao buscarPorIdPessoa(int idPessoa) {
        EntityManager em = FabricaJPA.getEntityManager();
        try {
            String jpql = "SELECT p FROM EstudoBiblicoCongregacao p WHERE p.pessoa.id = :idPessoa";
            TypedQuery<EstudoBiblicoCongregacao> query = em.createQuery(jpql, EstudoBiblicoCongregacao.class);
            query.setParameter("idPessoa", idPessoa);
            List<EstudoBiblicoCongregacao> resultados = query.getResultList();
            if (!resultados.isEmpty()) {
                return resultados.get(0);
            }
            return null; // Retorna nulo se não encontrar um presidente com o ID da pessoa
        } finally {
            em.close();
        }
    }

Try With Resources try(EntityManager em=FabricaJPA.getEntityManager()) in method public buscarPorIdPessoa(idPessoa int) : EstudoBiblicoCongregacao from class br.com.alexlopes.designacoes.dao.EstudoBiblicoCongregacaoDAO


    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;

                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Tela1.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);

        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Tela1.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);

        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Tela1.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);

        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Tela1.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(() -> {
            new Tela1().setVisible(true);
        });
    }

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;

                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Tela1.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);

        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Tela1.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);

        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Tela1.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);

        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Tela1.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Tela1().setVisible(true);
            }
        });
    }

Replace Anonymous With Lambda br.com.alexlopes.designacoes.views.Tela1.main.invokeLater.new Runnable with () -> {new Tela1().setVisible(true); in method public main(args String[]) : void from class br.com.alexlopes.designacoes.views.Tela1


    private void botaoSalvarSemanaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoSalvarSemanaActionPerformed
        try {
            Janela.ag = null;
            Janela.irAguarde();
            Janela.ag.botao.setText("Aguarde");
            Janela.ag.botao.setEnabled(false);

            Thread thread = new Thread(() -> {
                try {
                    // Cadastrar na tabela do banco de dados: SEMANA
                    cadastrarSemana();

                    // Cadastrar cada parte no BD
                    salvarAlterar();

                    // SALVAR NA CLASSE TODAS AS PARTES
                    salvarTodasPartes();

                    // Salvar em arquivo .pdf
                    salvarPdf();

                    // Enviar ZAP
                    enviarZap();

                    // Limpar Tela e Listas
                    limparTelaListas();

                    // Verificar se há mais segundas-feiras a processar
                    verificarSegundas();

                    // Deixar todas variaveis null
                    limparVariaveis();

                    //Atualizar tabela do menu principal
                    Janela.menu.mostrarTabela();

                    // Atualizar a interface do usuário na thread de interface do usuário
                    SwingUtilities.invokeLater(() -> {
                        Janela.ag.botao.setEnabled(true);
                        Janela.ag.botao.setText("OK");
                    });
                } catch (Exception e) {
                    SwingUtilities.invokeLater(() -> {
                        Janela.ag.botao.setEnabled(true);
                        Janela.ag.botao.setText("OK");
                    });
                }
            });

            // Iniciar a thread
            thread.start();

        } catch (Exception e) {
            Janela.ag.botao.setEnabled(true);
            Janela.ag.botao.setText("OK");
        }
    }//GEN-LAST:event_botaoSalvarSemanaActionPerformed

    private void botaoSalvarSemanaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoSalvarSemanaActionPerformed
        try {
            Janela.ag = null;
            Janela.irAguarde();
            Janela.ag.botao.setText("Aguarde");
            Janela.ag.botao.setEnabled(false);

            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // Cadastrar na tabela do banco de dados: SEMANA
                        cadastrarSemana();

                        // Cadastrar cada parte no BD
                        salvarAlterar();

                        // SALVAR NA CLASSE TODAS AS PARTES
                        salvarTodasPartes();

                        // Salvar em arquivo .pdf
                        salvarPdf();

                        // Enviar ZAP
                        enviarZap();

                        // Limpar Tela e Listas
                        limparTelaListas();

                        // Verificar se há mais segundas-feiras a processar
                        verificarSegundas();

                        // Deixar todas variaveis null
                        limparVariaveis();

                        //Atualizar tabela do menu principal
                        Janela.menu.mostrarTabela();

                        // Atualizar a interface do usuário na thread de interface do usuário
                        SwingUtilities.invokeLater(new Runnable() {
                            @Override
                            public void run() {
                                Janela.ag.botao.setEnabled(true);
                                Janela.ag.botao.setText("OK");
                            }
                        });
                    } catch (Exception e) {
                        SwingUtilities.invokeLater(new Runnable() {
                            @Override
                            public void run() {
                                Janela.ag.botao.setEnabled(true);
                                Janela.ag.botao.setText("OK");
                            }
                        });
                        e.printStackTrace();
                    }
                }
            });

            // Iniciar a thread
            thread.start();

        } catch (Exception e) {
            Janela.ag.botao.setEnabled(true);
            Janela.ag.botao.setText("OK");
            e.printStackTrace();
        }
    }//GEN-LAST:event_botaoSalvarSemanaActionPerformed

Replace Anonymous With Lambda br.com.alexlopes.designacoes.views.Tela1.botaoSalvarSemanaActionPerformed.thread.new Thread.new Runnable with () -> {trycadastrarSemana(); in method private botaoSalvarSemanaActionPerformed(evt ActionEvent) : void from class br.com.alexlopes.designacoes.views.Tela1


    /**
     * Command Handler that receives host selected gods
     * If selection is done right the game proceed to next phase according to the gamestate struct
     * If cardIDs is not correct this phase is requested again to the external event handler
     * @param sender player who issues this command
     * @param filter allowed cards selected by the host
     * @throws NotAllowedOperationException if the sender is not in this game or it's not the host or the operation is not allowed at the current game state
     */
    public boolean applyGodFilter(Player sender, int[] filter) throws NotAllowedOperationException
    {
        if(!isPlayerInThisMatch(sender) || !isPlayerHost(sender) || filter == null)
            throw new NotAllowedOperationException("Only the host can chose allowed gods");

        try
        {
            if(filter.length != playerCount() || hasDuplicates(filter)) // 20 cards should be fine for base gods ids
                return false;

            allowed_cards = new ArrayList<>(Arrays.asList(cardCollection.getCards(filter))); // force a mutable list generation
            current_player = 1;
            state_progress = 1;
            gameState = GameState.GOD_PICK;
            return true;

        } catch (CardNotExistsException e)
        {
            return false;
        }

    }

    /**
     * Command Handler that receives host selected gods
     * If selection is done right the game proceed to next phase according to the gamestate struct
     * If cardIDs is not correct this phase is requested again to the external event handler
     * @param sender player who issues this command
     * @param filter allowed cards selected by the host
     * @throws NotAllowedOperationException if the sender is not in this game or it's not the host or the operation is not allowed at the current game state
     */
    public boolean applyGodFilter(Player sender, int[] filter) throws NotAllowedOperationException
    {
        if(!isPlayerInThisMatch(sender) || !isPlayerHost(sender) || filter == null)
            throw new NotAllowedOperationException("Only the host can chose allowed gods");

        try
        {
            if(filter.length != playerCount() || hasDuplicates(filter)) // 20 cards should be fine for base gods ids
                return false;

            allowed_cards = new ArrayList<Card>(Arrays.asList(cardCollection.getCards(filter)));
            current_player = 1;
            state_progress = 1;
            gameState = GameState.GOD_PICK;
            return true;

        } catch (CardNotExistsException e)
        {
            return false;
        }

    }

Replace Generic With Diamond ArrayList<Card> with ArrayList<> in method public applyGodFilter(sender Player, filter int[]) : boolean from class it.polimi.ingsw.game.Game


	private static void createDefaultSettings() {
		settings = new Settings();

		String filename = System.getProperty("dapnet.core.settings", "config/Settings.json");
		try (FileWriter writer = new FileWriter(filename)) {
			Gson gson = new GsonBuilder().setPrettyPrinting().create();
			writer.write(gson.toJson(settings));
		} catch (IOException e) {
			logger.error("Failed to create settings file.", e);
		}
	}

	private static Settings createDefaultSettings() {
		settings = new Settings();
		try {
			File file = new File("config/Settings.json");
			FileWriter writer = new FileWriter(file);
			Gson gson = new GsonBuilder().setPrettyPrinting().create();
			writer.write(gson.toJson(settings));
			writer.flush();
			writer.close();
		} catch (IOException e) {
			logger.error("Failed to create settings file. Using default values", e);
		}
		return settings;
	}

Try With Resources try(FileWriter writer=new FileWriter(filename)) in method private createDefaultSettings() : void from class org.dapnet.core.Settings


	private void reloadDraftTable() {
		if (LogInEvent.getWorker() != null) {
			List<Object> parameters = new ArrayList<>();
			parameters.add(LogInEvent.getWorker().getLogin());
			((DraftTableModel) emailForm.getPanelDraftPage().getDraftTable().getModel()) //
					.reloadData(Query.TabOutboxPageEventQuery.DRAFT_MESSAGE_BY_SENDER_LOGIN.getValue(), parameters);
		} else {
			((DraftTableModel) emailForm.getPanelDraftPage().getDraftTable().getModel()) //
					.reloadData();
		}
	}

	private void reloadDraftTable() {
		if (LogInEvent.getWorker() != null) {
			List<Object> parameters = new ArrayList<Object>();
			parameters.add(LogInEvent.getWorker().getLogin());
			((DraftTableModel) emailForm.getPanelDraftPage().getDraftTable().getModel()) //
					.reloadData(Query.TabOutboxPageEventQuery.DRAFT_MESSAGE_BY_SENDER_LOGIN.getValue(), parameters);
		} else {
			((DraftTableModel) emailForm.getPanelDraftPage().getDraftTable().getModel()) //
					.reloadData();
		}
	}

Replace Generic With Diamond ArrayList<Object> with ArrayList<> in method private reloadDraftTable() : void from class com.javafee.elibrary.core.emailform.TabDraftPageEvent


	private void onChangeChckShowOnlySystemCorrespondence() {
		if (emailForm.getPanelDraftPage().getCheckShowOnlySystemCorrespondence().isSelected()) {
			List<Object> parameters = new ArrayList<>();
			MessageType messageType = Common
					.findMessageTypeByName(Constants.DATA_BASE_MESSAGE_TYPE_SYS_MESSAGE).get();
			parameters.add(messageType);
			((DraftTableModel) emailForm.getPanelDraftPage().getDraftTable().getModel()) //
					.reloadData(Query.TabOutboxPageEventQuery.DRAFT_MESSAGE_BY_MESSAGE_TYPE.getValue(), parameters);
		} else {
			onChangeComboBoxRecipient();
		}
	}

	private void onChangeChckShowOnlySystemCorrespondence() {
		if (emailForm.getPanelDraftPage().getCheckShowOnlySystemCorrespondence().isSelected()) {
			List<Object> parameters = new ArrayList<Object>();
			MessageType messageType = Common
					.findMessageTypeByName(Constants.DATA_BASE_MESSAGE_TYPE_SYS_MESSAGE).get();
			parameters.add(messageType);
			((DraftTableModel) emailForm.getPanelDraftPage().getDraftTable().getModel()) //
					.reloadData(Query.TabOutboxPageEventQuery.DRAFT_MESSAGE_BY_MESSAGE_TYPE.getValue(), parameters);
		} else {
			onChangeComboBoxRecipient();
		}
	}

Replace Generic With Diamond ArrayList<Object> with ArrayList<> in method private onChangeChckShowOnlySystemCorrespondence() : void from class com.javafee.elibrary.core.emailform.TabDraftPageEvent