From 52aea1cf909d03075a83c4c68d82b95c62cf4bff Mon Sep 17 00:00:00 2001 From: jascotty2 Date: Tue, 10 Sep 2019 09:52:40 -0500 Subject: [PATCH] code cleanup --- .../songoda/epicfurnaces/EpicFurnaces.java | 37 +- .../epicfurnaces/commands/CommandRemote.java | 3 +- .../commands/CommandSettings.java | 7 +- .../songoda/epicfurnaces/furnace/Furnace.java | 17 +- .../songoda/epicfurnaces/gui/GUIOverview.java | 396 ++++------ .../handlers/BlacklistHandler.java | 30 +- .../listeners/BlockListeners.java | 4 +- .../listeners/FurnaceListeners.java | 1 - .../listeners/InteractListeners.java | 25 +- .../listeners/InventoryListeners.java | 1 - .../epicfurnaces/storage/StorageItem.java | 14 - .../types}/MySQLDatabase.java | 2 +- .../storage/types/StorageMysql.java | 7 +- .../storage/types/StorageYaml.java | 4 +- .../epicfurnaces/tasks/FurnaceTask.java | 71 +- .../songoda/epicfurnaces/utils/Methods.java | 7 +- .../songoda/epicfurnaces/utils/Metrics.java | 695 ------------------ .../epicfurnaces/utils/Serializers.java | 156 ---- 18 files changed, 246 insertions(+), 1231 deletions(-) rename src/main/java/com/songoda/epicfurnaces/{utils => storage/types}/MySQLDatabase.java (97%) delete mode 100644 src/main/java/com/songoda/epicfurnaces/utils/Metrics.java delete mode 100644 src/main/java/com/songoda/epicfurnaces/utils/Serializers.java diff --git a/src/main/java/com/songoda/epicfurnaces/EpicFurnaces.java b/src/main/java/com/songoda/epicfurnaces/EpicFurnaces.java index 597d8f1..70f115e 100644 --- a/src/main/java/com/songoda/epicfurnaces/EpicFurnaces.java +++ b/src/main/java/com/songoda/epicfurnaces/EpicFurnaces.java @@ -40,6 +40,7 @@ import org.bukkit.plugin.PluginManager; import java.io.File; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.UUID; @@ -47,9 +48,9 @@ public class EpicFurnaces extends SongodaPlugin { private static EpicFurnaces INSTANCE; - private Config dataConfig = new Config(this, "data.yml"); - private Config furnaceRecipeFile = new Config(this, "Furnace Recipes.yml"); - private Config levelsFile = new Config(this, "levels.yml"); + private final Config dataConfig = new Config(this, "data.yml"); + private final Config furnaceRecipeFile = new Config(this, "Furnace Recipes.yml"); + private final Config levelsFile = new Config(this, "levels.yml"); private final GuiManager guiManager = new GuiManager(this); private LevelManager levelManager; @@ -84,6 +85,8 @@ public class EpicFurnaces extends SongodaPlugin { // Load Economy EconomyManager.load(); + // Register Hologram Plugin + HologramManager.load(this); // Setup Config Settings.setupConfig(); @@ -100,7 +103,7 @@ public class EpicFurnaces extends SongodaPlugin { new CommandGive(this), new CommandReload(this), new CommandRemote(this), - new CommandSettings(this) + new CommandSettings(this, guiManager) ); dataConfig.load(); @@ -123,15 +126,12 @@ public class EpicFurnaces extends SongodaPlugin { FurnaceTask.startTask(this); HologramTask.startTask(this); - // Register Hologram Plugin - HologramManager.load(this); - // Register Listeners guiManager.init(); PluginManager pluginManager = Bukkit.getPluginManager(); pluginManager.registerEvents(new BlockListeners(this), this); pluginManager.registerEvents(new FurnaceListeners(this), this); - pluginManager.registerEvents(new InteractListeners(this), this); + pluginManager.registerEvents(new InteractListeners(this, guiManager), this); pluginManager.registerEvents(new InventoryListeners(this), this); // Start auto save @@ -142,13 +142,13 @@ public class EpicFurnaces extends SongodaPlugin { @Override public void onConfigReload() { this.setLocale(getConfig().getString("System.Language Mode"), true); - this.locale.reloadMessages(); this.blacklistHandler.reload(); + loadLevelManager(); } @Override public List getExtraConfig() { - return null; + return Arrays.asList(levelsFile); } public void clearHologram(Furnace furnace) { @@ -158,6 +158,8 @@ public class EpicFurnaces extends SongodaPlugin { public void updateHologram(Furnace furnace) { // are holograms enabled? if (!Settings.HOLOGRAMS.getBoolean() || !HologramManager.getManager().isEnabled()) return; + // don't try to load furnaces in chunks that aren't loaded + if (!furnace.isInLoadedChunk()) return; BlockState state = furnace.getLocation().getBlock().getState(); @@ -265,7 +267,7 @@ public class EpicFurnaces extends SongodaPlugin { } private void loadLevelManager() { - if (!new File(this.getDataFolder(), "levels.yml").exists()) + if (!levelsFile.getFile().exists()) this.saveResource("levels.yml", false); levelsFile.load(); @@ -322,7 +324,7 @@ public class EpicFurnaces extends SongodaPlugin { } furnaceRecipeFile.load(); - if (getConfig().getBoolean("Main.Use Custom Recipes")) { + if (Settings.CUSTOM_RECIPES.getBoolean()) { ConfigurationSection cs = furnaceRecipeFile.getConfigurationSection("Recipes"); for (String key : cs.getKeys(false)) { Material item = Material.valueOf(key.toUpperCase()); @@ -336,12 +338,13 @@ public class EpicFurnaces extends SongodaPlugin { public ItemStack createLeveledFurnace(Material material, int level, int uses) { ItemStack item = new ItemStack(material, 1); - ItemMeta itemmeta = item.getItemMeta(); - if (getConfig().getBoolean("Main.Remember Furnace Item Levels")) + if (Settings.FURNACE_ITEM.getBoolean()) { + ItemMeta itemmeta = item.getItemMeta(); itemmeta.setDisplayName(Methods.formatText(Methods.formatName(level, uses, true))); + item.setItemMeta(itemmeta); + } - item.setItemMeta(itemmeta); return item; } @@ -386,8 +389,4 @@ public class EpicFurnaces extends SongodaPlugin { public LevelManager getLevelManager() { return levelManager; } - - public GuiManager getGuiManager() { - return guiManager; - } } \ No newline at end of file diff --git a/src/main/java/com/songoda/epicfurnaces/commands/CommandRemote.java b/src/main/java/com/songoda/epicfurnaces/commands/CommandRemote.java index 2c24cb1..89f47cd 100644 --- a/src/main/java/com/songoda/epicfurnaces/commands/CommandRemote.java +++ b/src/main/java/com/songoda/epicfurnaces/commands/CommandRemote.java @@ -3,6 +3,7 @@ package com.songoda.epicfurnaces.commands; import com.songoda.core.commands.AbstractCommand; import com.songoda.epicfurnaces.EpicFurnaces; import com.songoda.epicfurnaces.furnace.Furnace; +import com.songoda.epicfurnaces.settings.Settings; import org.bukkit.block.Block; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -22,7 +23,7 @@ public class CommandRemote extends AbstractCommand { @Override protected ReturnType runCommand(CommandSender sender, String... args) { - if (!plugin.getConfig().getBoolean("Main.Access Furnaces Remotely") || !sender.hasPermission("EpicFurnaces.Remote")) { + if (!Settings.REMOTE.getBoolean() || !sender.hasPermission("EpicFurnaces.Remote")) { plugin.getLocale().getMessage("event.general.nopermission").sendPrefixedMessage(sender); return ReturnType.FAILURE; } diff --git a/src/main/java/com/songoda/epicfurnaces/commands/CommandSettings.java b/src/main/java/com/songoda/epicfurnaces/commands/CommandSettings.java index 2fe2319..3863967 100644 --- a/src/main/java/com/songoda/epicfurnaces/commands/CommandSettings.java +++ b/src/main/java/com/songoda/epicfurnaces/commands/CommandSettings.java @@ -2,6 +2,7 @@ package com.songoda.epicfurnaces.commands; import com.songoda.core.commands.AbstractCommand; import com.songoda.core.configuration.editor.PluginConfigGui; +import com.songoda.core.gui.GuiManager; import com.songoda.epicfurnaces.EpicFurnaces; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -11,15 +12,17 @@ import java.util.List; public class CommandSettings extends AbstractCommand { final EpicFurnaces plugin; + final GuiManager guiManager; - public CommandSettings(EpicFurnaces plugin) { + public CommandSettings(EpicFurnaces plugin, GuiManager guiManager) { super(true, "settings"); this.plugin = plugin; + this.guiManager = guiManager; } @Override protected ReturnType runCommand(CommandSender sender, String... args) { - plugin.getGuiManager().showGUI((Player) sender, new PluginConfigGui(plugin)); + guiManager.showGUI((Player) sender, new PluginConfigGui(plugin)); return ReturnType.SUCCESS; } diff --git a/src/main/java/com/songoda/epicfurnaces/furnace/Furnace.java b/src/main/java/com/songoda/epicfurnaces/furnace/Furnace.java index 961e3b6..0e46e73 100644 --- a/src/main/java/com/songoda/epicfurnaces/furnace/Furnace.java +++ b/src/main/java/com/songoda/epicfurnaces/furnace/Furnace.java @@ -1,6 +1,7 @@ package com.songoda.epicfurnaces.furnace; import com.songoda.core.compatibility.ServerVersion; +import com.songoda.core.gui.GuiManager; import com.songoda.core.hooks.EconomyManager; import com.songoda.epicfurnaces.EpicFurnaces; import com.songoda.epicfurnaces.boost.BoostData; @@ -34,20 +35,20 @@ public class Furnace { private String nickname = null; private UUID placedBy = null; private int uses, tolevel, radiusOverheatLast, radiusFuelshareLast = 0; - private List radiusOverheat = new ArrayList<>(); - private List radiusFuelshare = new ArrayList<>(); - private List accessList = new ArrayList<>(); - private Map cache = new HashMap<>(); + private final List radiusOverheat = new ArrayList<>(); + private final List radiusFuelshare = new ArrayList<>(); + private final List accessList = new ArrayList<>(); + private final Map cache = new HashMap<>(); public Furnace(Location location) { this.location = location; } - public void overview(Player player) { + public void overview(GuiManager guiManager, Player player) { if (placedBy == null) placedBy = player.getUniqueId(); if (!player.hasPermission("epicfurnaces.overview")) return; - plugin.getGuiManager().showGUI(player, new GUIOverview(plugin, this, player)); + guiManager.showGUI(player, new GUIOverview(plugin, this, player)); } public void plus(FurnaceSmeltEvent e) { @@ -307,6 +308,10 @@ public class Furnace { return location.clone(); } + public boolean isInLoadedChunk() { + return location != null && location.getWorld() != null && location.getWorld().isChunkLoaded(((int) location.getX()) >> 4, ((int) location.getZ()) >> 4); + } + public void setLevel(Level level) { this.level = level; } diff --git a/src/main/java/com/songoda/epicfurnaces/gui/GUIOverview.java b/src/main/java/com/songoda/epicfurnaces/gui/GUIOverview.java index d7ff813..dddb1d8 100644 --- a/src/main/java/com/songoda/epicfurnaces/gui/GUIOverview.java +++ b/src/main/java/com/songoda/epicfurnaces/gui/GUIOverview.java @@ -1,5 +1,6 @@ package com.songoda.epicfurnaces.gui; +import com.songoda.core.compatibility.CompatibleMaterial; import com.songoda.core.gui.Gui; import com.songoda.core.gui.GuiUtils; import com.songoda.core.input.ChatPrompt; @@ -11,21 +12,20 @@ import com.songoda.epicfurnaces.settings.Settings; import com.songoda.epicfurnaces.utils.CostType; import com.songoda.epicfurnaces.utils.Methods; import org.bukkit.Bukkit; -import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; +import java.util.Arrays; +import java.util.List; public class GUIOverview extends Gui { private final EpicFurnaces plugin; private final Furnace furnace; private final Player player; + static int[][] infoIconOrder = new int[][]{{22}, {21, 23}, {21, 22, 23}, {20, 21, 23, 24}, {20, 21, 22, 23, 24}}; private int task; @@ -57,166 +57,14 @@ public class GUIOverview extends Gui { Level level = furnace.getLevel(); Level nextLevel = plugin.getLevelManager().getHighestLevel().getLevel() > level.getLevel() ? plugin.getLevelManager().getLevel(level.getLevel() + 1) : null; - int multi = plugin.getConfig().getInt("Main.Level Cost Multiplier"); - - int needed = (multi * level.getLevel()) - furnace.getTolevel(); - - ItemStack item = new ItemStack(Material.FURNACE, 1); - - ItemMeta itemmeta = item.getItemMeta(); - itemmeta.setDisplayName(plugin.getLocale().getMessage("interface.furnace.currentlevel") - .processPlaceholder("level", level.getLevel()).getMessage()); - ArrayList lore = new ArrayList<>(); - lore.add(plugin.getLocale().getMessage("interface.furnace.smeltedx") - .processPlaceholder("amount", furnace.getUses()).getMessage()); - lore.addAll(level.getDescription()); - lore.add(""); - if (nextLevel == null) - lore.add(plugin.getLocale().getMessage("interface.furnace.alreadymaxed").getMessage()); - else { - lore.add(plugin.getLocale().getMessage("interface.furnace.level") - .processPlaceholder("level", nextLevel.getLevel()).getMessage()); - lore.addAll(nextLevel.getDescription()); - - if (plugin.getConfig().getBoolean("Main.Upgrade By Smelting Materials")) { - lore.add(plugin.getLocale().getMessage("interface.furnace.tolevel") - .processPlaceholder("amount", needed) - .processPlaceholder("type", - Methods.cleanString(plugin.getConfig().getString("Main.Furnace Upgrade Cost"))) - .getMessage()); - } - } - - BoostData boostData = plugin.getBoostManager().getBoost(furnace.getPlacedBy()); - if (boostData != null) { - String[] parts = plugin.getLocale().getMessage("interface.button.boostedstats") - .processPlaceholder("amount", Integer.toString(boostData.getMultiplier())) - .processPlaceholder("time", Methods.makeReadable(boostData.getEndTime() - - System.currentTimeMillis())).getMessage().split("\\|"); - lore.add(""); - for (String line : parts) - lore.add(Methods.formatText(line)); - } - - itemmeta.setLore(lore); - item.setItemMeta(itemmeta); - - - ItemStack item2 = new ItemStack(Material.valueOf(plugin.getConfig().getString("Interfaces.Performance Icon")), 1); - ItemMeta itemmeta2 = item2.getItemMeta(); - itemmeta2.setDisplayName(plugin.getLocale().getMessage("interface.furnace.performancetitle").getMessage()); //greyed out until available - ArrayList lore2 = new ArrayList<>(); - - String[] parts = plugin.getLocale().getMessage("interface.furnace.performanceinfo") - .processPlaceholder("amount", level.getPerformance()).getMessage().split("\\|"); - lore.add(""); - for (String line : parts) { - lore2.add(Methods.formatText(line)); - } - itemmeta2.setLore(lore2); - item2.setItemMeta(itemmeta2); - - ItemStack item3 = new ItemStack(Material.valueOf(plugin.getConfig().getString("Interfaces.Reward Icon")), 1); - ItemMeta itemmeta3 = item3.getItemMeta(); - itemmeta3.setDisplayName(plugin.getLocale().getMessage("interface.furnace.rewardtitle").getMessage()); - ArrayList lore3 = new ArrayList<>(); - - parts = plugin.getLocale().getMessage("interface.furnace.rewardinfo") - .processPlaceholder("amount", level.getReward().split(":")[0].replace("%", "")) - .getMessage().split("\\|"); - lore.add(""); - for (String line : parts) { - lore3.add(Methods.formatText(line)); - } - itemmeta3.setLore(lore3); - item3.setItemMeta(itemmeta3); - - - ItemStack item4 = new ItemStack(Material.valueOf(plugin.getConfig().getString("Interfaces.FuelDuration Icon")), 1); - ItemMeta itemmeta4 = item4.getItemMeta(); - itemmeta4.setDisplayName(plugin.getLocale().getMessage("interface.furnace.fueldurationtitle").getMessage()); - ArrayList lore4 = new ArrayList<>(); - - parts = plugin.getLocale().getMessage("interface.furnace.fueldurationinfo") - .processPlaceholder("amount", level.getFuelDuration()).getMessage().split("\\|"); - lore.add(""); - for (String line : parts) { - lore4.add(Methods.formatText(line)); - } - itemmeta4.setLore(lore4); - item4.setItemMeta(itemmeta4); - - ItemStack item5 = new ItemStack(Material.valueOf(plugin.getConfig().getString("Interfaces.Overheat Icon")), 1); - ItemMeta itemmeta5 = item4.getItemMeta(); - itemmeta5.setDisplayName(plugin.getLocale().getMessage("interface.furnace.overheattitle").getMessage()); - ArrayList lore5 = new ArrayList<>(); - - parts = plugin.getLocale().getMessage("interface.furnace.overheatinfo") - .processPlaceholder("amount", level.getOverheat() * 3) - .getMessage().split("\\|"); - - lore.add(""); - for (String line : parts) { - lore5.add(Methods.formatText(line)); - } - itemmeta5.setLore(lore5); - item5.setItemMeta(itemmeta5); - - ItemStack item6 = new ItemStack(Material.valueOf(plugin.getConfig().getString("Interfaces.FuelShare Icon")), 1); - ItemMeta itemmeta6 = item4.getItemMeta(); - itemmeta6.setDisplayName(plugin.getLocale().getMessage("interface.furnace.fuelsharetitle").getMessage()); - ArrayList lore6 = new ArrayList<>(); - - parts = plugin.getLocale().getMessage("interface.furnace.fuelshareinfo") - .processPlaceholder("amount", level.getOverheat() * 3).getMessage().split("\\|"); - lore.add(""); - for (String line : parts) { - lore6.add(Methods.formatText(line)); - } - itemmeta6.setLore(lore6); - item6.setItemMeta(itemmeta6); - - ItemStack itemXP = new ItemStack(Material.valueOf(plugin.getConfig().getString("Interfaces.XP Icon")), 1); - ItemMeta itemmetaXP = itemXP.getItemMeta(); - itemmetaXP.setDisplayName(plugin.getLocale().getMessage("interface.furnace.upgradewithxp").getMessage()); - ArrayList loreXP = new ArrayList<>(); - if (nextLevel != null) - loreXP.add(plugin.getLocale().getMessage("interface.furnace.upgradewithxplore") - .processPlaceholder("cost", nextLevel.getCostExperience()).getMessage()); - else - loreXP.add(plugin.getLocale().getMessage("interface.furnace.alreadymaxed").getMessage()); - itemmetaXP.setLore(loreXP); - itemXP.setItemMeta(itemmetaXP); - - ItemStack itemECO = new ItemStack(Material.valueOf(plugin.getConfig().getString("Interfaces.Economy Icon")), 1); - ItemMeta itemmetaECO = itemECO.getItemMeta(); - itemmetaECO.setDisplayName(plugin.getLocale().getMessage("interface.furnace.upgradewitheconomy").getMessage()); - ArrayList loreECO = new ArrayList<>(); - if (nextLevel != null) - loreECO.add(plugin.getLocale().getMessage("interface.furnace.upgradewitheconomylore") - .processPlaceholder("cost", Methods.formatEconomy(nextLevel.getCostEconomy())) - .getMessage()); - else - loreECO.add(plugin.getLocale().getMessage("interface.furnace.alreadymaxed").getMessage()); - itemmetaECO.setLore(loreECO); - itemECO.setItemMeta(itemmetaECO); - - setItem(13, item); + // main furnace information icon + setItem(1, 4, GuiUtils.createButtonItem(CompatibleMaterial.FURNACE, + plugin.getLocale().getMessage("interface.furnace.currentlevel") + .processPlaceholder("level", level.getLevel()).getMessage(), + getFurnaceDescription(furnace, level, nextLevel))); + // check how many info icons we have to show int num = -1; - Map spots = new HashMap(); - - int[] s1 = {22}; - spots.put(0, s1); - int[] s2 = {21, 23}; - spots.put(1, s2); - int[] s3 = {21, 22, 23}; - spots.put(2, s3); - int[] s4 = {20, 21, 23, 24}; - spots.put(3, s4); - int[] s5 = {20, 21, 22, 23, 24}; - spots.put(4, s5); - if (level.getPerformance() != 0) { num++; } @@ -233,116 +81,108 @@ public class GUIOverview extends Gui { num++; } - int[] order = spots.get(num); - int current = 0; if (level.getPerformance() != 0) { - setItem(order[current], item2); - current++; + setItem(infoIconOrder[num][current++], GuiUtils.createButtonItem( + Settings.PERFORMANCE_ICON.getMaterial(CompatibleMaterial.REDSTONE), + plugin.getLocale().getMessage("interface.furnace.performancetitle").getMessage(), + plugin.getLocale().getMessage("interface.furnace.performanceinfo") + .processPlaceholder("amount", level.getPerformance()).getMessage().split("\\|"))); } if (level.getReward() != null) { - setItem(order[current], item3); - current++; + setItem(infoIconOrder[num][current++], GuiUtils.createButtonItem( + Settings.REWARD_ICON.getMaterial(CompatibleMaterial.GOLDEN_APPLE), + plugin.getLocale().getMessage("interface.furnace.rewardtitle").getMessage(), + plugin.getLocale().getMessage("interface.furnace.rewardinfo") + .processPlaceholder("amount", level.getReward().split(":")[0].replace("%", "")) + .getMessage().split("\\|"))); } if (level.getFuelDuration() != 0) { - setItem(order[current], item4); - current++; + setItem(infoIconOrder[num][current++], GuiUtils.createButtonItem( + Settings.FUEL_DURATION_ICON.getMaterial(CompatibleMaterial.COAL), + plugin.getLocale().getMessage("interface.furnace.fueldurationtitle").getMessage(), + plugin.getLocale().getMessage("interface.furnace.fueldurationinfo") + .processPlaceholder("amount", level.getFuelDuration()) + .getMessage().split("\\|"))); } if (level.getFuelShare() != 0) { - setItem(order[current], item6); - current++; + setItem(infoIconOrder[num][current++], GuiUtils.createButtonItem( + Settings.FUEL_SHARE_ICON.getMaterial(CompatibleMaterial.COAL_BLOCK), + plugin.getLocale().getMessage("interface.furnace.fuelsharetitle").getMessage(), + plugin.getLocale().getMessage("interface.furnace.fuelshareinfo") + .processPlaceholder("amount", level.getOverheat() * 3) + .getMessage().split("\\|"))); } if (level.getOverheat() != 0) { - setItem(order[current], item5); + setItem(infoIconOrder[num][current++], GuiUtils.createButtonItem( + Settings.OVERHEAT_ICON.getMaterial(CompatibleMaterial.FIRE_CHARGE), + plugin.getLocale().getMessage("interface.furnace.overheattitle").getMessage(), + plugin.getLocale().getMessage("interface.furnace.overheatinfo") + .processPlaceholder("amount", level.getOverheat() * 3) + .getMessage().split("\\|"))); } + + // remote control + if (Settings.REMOTE.getBoolean() && player.hasPermission("EpicFurnaces.Remote")) { + setButton(4, GuiUtils.createButtonItem( + CompatibleMaterial.TRIPWIRE_HOOK, + plugin.getLocale().getMessage("interface.furnace.remotefurnace").getMessage(), + getFurnaceRemoteLore(furnace)), + ClickType.LEFT, (event) -> { - ItemStack hook = new ItemStack(Material.TRIPWIRE_HOOK, 1); - ItemMeta hookmeta = hook.getItemMeta(); - hookmeta.setDisplayName(plugin.getLocale().getMessage("interface.furnace.remotefurnace").getMessage()); - ArrayList lorehook = new ArrayList<>(); + player.sendMessage(furnace.getNickname() == null ? "Enter a nickname" : furnace.getNickname()); + ChatPrompt.showPrompt(plugin, event.player, plugin.getLocale().getMessage("event.remote.enter").getMessage(), + promptEvent -> { + for (Furnace other : plugin.getFurnaceManager().getFurnaces().values()) { + if (other.getNickname() == null) { + continue; + } - String nickname = furnace.getNickname(); + if (other.getNickname().equalsIgnoreCase(promptEvent.getMessage())) { + plugin.getLocale().getMessage("event.remote.nicknameinuse").sendPrefixedMessage(player); + return; + } + } - parts = plugin.getLocale().getMessage("interface.furnace.remotefurnacelore") - .processPlaceholder("nickname", nickname == null ? "Unset" : nickname).getMessage().split("\\|"); + furnace.setNickname(promptEvent.getMessage()); + plugin.getLocale().getMessage("event.remote.nicknamesuccess").sendPrefixedMessage(player); + }).setOnClose(this::constructGUI); - for (String line : parts) { - lorehook.add(Methods.formatText(line)); - } - if (nickname != null) { - parts = plugin.getLocale().getMessage("interface.furnace.utilize") - .processPlaceholder("nickname", nickname).getMessage().split("\\|"); - for (String line : parts) { - lorehook.add(Methods.formatText(line)); - } - } - - lorehook.add(""); - lorehook.add(plugin.getLocale().getMessage("interface.furnace.remotelist").getMessage()); - for (String line : furnace.getRawAccessList()) { - String[] halfs = line.split(":"); - String name = halfs[1]; - Player player = Bukkit.getPlayer(halfs[0]); - if (player != null) { - name = player.getDisplayName(); - } - lorehook.add(Methods.formatText("&6" + name)); - } - hookmeta.setLore(lorehook); - hook.setItemMeta(hookmeta); - - if (plugin.getConfig().getBoolean("Main.Access Furnaces Remotely") - && player.hasPermission("EpicFurnaces.Remote")) { - setButton(4, hook, (event) -> { - if (event.clickType == ClickType.LEFT) { - - ChatPrompt chatPrompt = ChatPrompt.showPrompt(plugin, event.player, promptEvent -> { - for (Furnace other : plugin.getFurnaceManager().getFurnaces().values()) { - if (other.getNickname() == null) { - continue; - } - - if (other.getNickname().equalsIgnoreCase(promptEvent.getMessage())) { - plugin.getLocale().getMessage("event.remote.nicknameinuse").sendPrefixedMessage(player); - return; - } - } - - furnace.setNickname(promptEvent.getMessage()); - plugin.getLocale().getMessage("event.remote.nicknamesuccess").sendPrefixedMessage(player); + }).setAction(4, ClickType.RIGHT, (event) -> { + furnace.addToAccessList(player); + constructGUI(); }); - - chatPrompt.setOnClose(this::constructGUI); - - player.sendMessage(furnace.getNickname() == null ? "Enter a nickname" : furnace.getNickname()); - - plugin.getLocale().getMessage("event.remote.enter").sendPrefixedMessage(player); - - - } else if (event.clickType == ClickType.RIGHT) { - furnace.addToAccessList(player); - constructGUI(); - } - }); } - setItem(13, item); - - if (plugin.getConfig().getBoolean("Main.Upgrade With XP") - && player.hasPermission("EpicFurnaces.Upgrade.XP") - && level.getCostExperience() != -1) { - setButton(11, itemXP, (event) -> { - furnace.upgrade(player, CostType.EXPERIENCE); - furnace.overview(player); - }); + if (Settings.UPGRADE_WITH_XP.getBoolean() + && level.getCostExperience() != -1 + && player.hasPermission("EpicFurnaces.Upgrade.XP")) { + setButton(1, 2, GuiUtils.createButtonItem( + Settings.XP_ICON.getMaterial(CompatibleMaterial.EXPERIENCE_BOTTLE), + plugin.getLocale().getMessage("interface.furnace.upgradewithxp").getMessage(), + nextLevel != null + ? plugin.getLocale().getMessage("interface.furnace.upgradewithxplore") + .processPlaceholder("cost", nextLevel.getCostExperience()).getMessage() + : plugin.getLocale().getMessage("interface.furnace.alreadymaxed").getMessage()), + (event) -> { + furnace.upgrade(player, CostType.EXPERIENCE); + furnace.overview(guiManager, player); + }); } - if (plugin.getConfig().getBoolean("Main.Upgrade With Economy") - && player.hasPermission("EpicFurnaces.Upgrade.ECO") - && level.getCostEconomy() != -1) { - setButton(15, itemECO, (event) -> { + if (Settings.UPGRADE_WITH_ECONOMY.getBoolean() + && level.getCostEconomy() != -1 + && player.hasPermission("EpicFurnaces.Upgrade.ECO")) { + setButton(1, 6, GuiUtils.createButtonItem( + Settings.ECO_ICON.getMaterial(CompatibleMaterial.SUNFLOWER), + plugin.getLocale().getMessage("interface.furnace.upgradewitheconomy").getMessage(), + nextLevel != null + ? plugin.getLocale().getMessage("interface.furnace.upgradewitheconomylore") + .processPlaceholder("cost", nextLevel.getCostExperience()).getMessage() + : plugin.getLocale().getMessage("interface.furnace.alreadymaxed").getMessage()), + (event) -> { furnace.upgrade(player, CostType.ECONOMY); - furnace.overview(player); + furnace.overview(guiManager, player); }); } } @@ -351,4 +191,58 @@ public class GUIOverview extends Gui { task = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, this::constructGUI, 5L, 5L); } + List getFurnaceDescription(Furnace furnace, Level level, Level nextLevel) { + ArrayList lore = new ArrayList<>(); + lore.add(plugin.getLocale().getMessage("interface.furnace.smeltedx") + .processPlaceholder("amount", furnace.getUses()).getMessage()); + lore.addAll(level.getDescription()); + lore.add(""); + if (nextLevel == null) { + lore.add(plugin.getLocale().getMessage("interface.furnace.alreadymaxed").getMessage()); + } else { + lore.add(plugin.getLocale().getMessage("interface.furnace.level") + .processPlaceholder("level", nextLevel.getLevel()).getMessage()); + lore.addAll(nextLevel.getDescription()); + + if (Settings.UPGRADE_BY_SMELTING.getBoolean()) { + lore.add(plugin.getLocale().getMessage("interface.furnace.tolevel") + .processPlaceholder("amount", (Settings.LEVEL_MULTIPLIER.getInt() * level.getLevel()) - furnace.getTolevel()) + .processPlaceholder("type", Methods.cleanString(Settings.UPGRADE_COST.getString())) + .getMessage()); + } + } + + BoostData boostData = plugin.getBoostManager().getBoost(furnace.getPlacedBy()); + if (boostData != null) { + lore.addAll(Arrays.asList(plugin.getLocale().getMessage("interface.button.boostedstats") + .processPlaceholder("amount", Integer.toString(boostData.getMultiplier())) + .processPlaceholder("time", Methods.makeReadable(boostData.getEndTime() - System.currentTimeMillis())) + .getMessage().split("\\|"))); + } + return lore; + } + + List getFurnaceRemoteLore(Furnace furnace) { + String nickname = furnace.getNickname(); + ArrayList lorehook = new ArrayList<>(Arrays.asList(plugin.getLocale().getMessage("interface.furnace.remotefurnacelore") + .processPlaceholder("nickname", nickname == null ? "Unset" : nickname).getMessage().split("\\|"))); + + if (nickname != null) { + lorehook.addAll(Arrays.asList(plugin.getLocale().getMessage("interface.furnace.utilize") + .processPlaceholder("nickname", nickname).getMessage().split("\\|"))); + } + + lorehook.add(""); + lorehook.add(plugin.getLocale().getMessage("interface.furnace.remotelist").getMessage()); + for (String line : furnace.getRawAccessList()) { + String[] halfs = line.split(":"); + String name = halfs[1]; + Player remotePlayer = Bukkit.getPlayer(halfs[0]); + if (remotePlayer != null) { + name = remotePlayer.getDisplayName(); + } + lorehook.add(Methods.formatText("&6" + name)); + } + return lorehook; + } } diff --git a/src/main/java/com/songoda/epicfurnaces/handlers/BlacklistHandler.java b/src/main/java/com/songoda/epicfurnaces/handlers/BlacklistHandler.java index ce5c5f3..9598ed9 100644 --- a/src/main/java/com/songoda/epicfurnaces/handlers/BlacklistHandler.java +++ b/src/main/java/com/songoda/epicfurnaces/handlers/BlacklistHandler.java @@ -2,9 +2,9 @@ package com.songoda.epicfurnaces.handlers; import com.songoda.core.configuration.Config; import com.songoda.epicfurnaces.EpicFurnaces; -import org.bukkit.entity.Player; +import org.bukkit.World; -import java.util.ArrayList; +import java.util.Arrays; import java.util.List; /** @@ -12,38 +12,26 @@ import java.util.List; */ public class BlacklistHandler { - private Config blackConfig = new Config(EpicFurnaces.getInstance(), "blacklist.yml"); + private final Config blackConfig = new Config(EpicFurnaces.getInstance(), "blacklist.yml"); public BlacklistHandler() { - blackConfig.load(); loadBlacklistFile(); } - public boolean isBlacklisted(Player player) { + public boolean isBlacklisted(World world) { List list = blackConfig.getStringList("settings.blacklist"); - String cWorld = player.getWorld().getName(); - for (String world : list) { - if (cWorld.equalsIgnoreCase(world)) { - return true; - } - } - return false; + final String checkWorld = world.getName(); + return list.stream().anyMatch(w -> w.equalsIgnoreCase(checkWorld)); } private void loadBlacklistFile() { - List list = new ArrayList<>(); - list.add("world2"); - list.add("world3"); - list.add("world4"); - list.add("world5"); - blackConfig.addDefault("settings.blacklist", list); + blackConfig.addDefault("settings.blacklist", Arrays.asList("world2", "world3", "world4", "world5")); + blackConfig.load(); - blackConfig.options().copyDefaults(true); - blackConfig.save(); + blackConfig.saveChanges(); } public void reload() { - blackConfig.load(); loadBlacklistFile(); } } \ No newline at end of file diff --git a/src/main/java/com/songoda/epicfurnaces/listeners/BlockListeners.java b/src/main/java/com/songoda/epicfurnaces/listeners/BlockListeners.java index 67995b1..5f50203 100644 --- a/src/main/java/com/songoda/epicfurnaces/listeners/BlockListeners.java +++ b/src/main/java/com/songoda/epicfurnaces/listeners/BlockListeners.java @@ -47,7 +47,7 @@ public class BlockListeners implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockPlace(BlockPlaceEvent event) { - if (plugin.getBlacklistHandler().isBlacklisted(event.getPlayer()) + if (plugin.getBlacklistHandler().isBlacklisted(event.getPlayer().getWorld()) || !event.getBlock().getType().name().contains("FURNACE")) return; @@ -74,7 +74,7 @@ public class BlockListeners implements Listener { } Block block = event.getBlock(); if (!block.getType().name().contains("FURNACE") - || plugin.getBlacklistHandler().isBlacklisted(event.getPlayer())) + || plugin.getBlacklistHandler().isBlacklisted(event.getPlayer().getWorld())) return; Furnace furnace = plugin.getFurnaceManager().getFurnace(block); diff --git a/src/main/java/com/songoda/epicfurnaces/listeners/FurnaceListeners.java b/src/main/java/com/songoda/epicfurnaces/listeners/FurnaceListeners.java index d397689..fb9969e 100644 --- a/src/main/java/com/songoda/epicfurnaces/listeners/FurnaceListeners.java +++ b/src/main/java/com/songoda/epicfurnaces/listeners/FurnaceListeners.java @@ -3,7 +3,6 @@ package com.songoda.epicfurnaces.listeners; import com.songoda.epicfurnaces.EpicFurnaces; import com.songoda.epicfurnaces.furnace.Furnace; import com.songoda.epicfurnaces.furnace.levels.Level; -import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; diff --git a/src/main/java/com/songoda/epicfurnaces/listeners/InteractListeners.java b/src/main/java/com/songoda/epicfurnaces/listeners/InteractListeners.java index 7f18806..503ca6d 100644 --- a/src/main/java/com/songoda/epicfurnaces/listeners/InteractListeners.java +++ b/src/main/java/com/songoda/epicfurnaces/listeners/InteractListeners.java @@ -1,8 +1,7 @@ package com.songoda.epicfurnaces.listeners; +import com.songoda.core.gui.GuiManager; import com.songoda.epicfurnaces.EpicFurnaces; -import com.songoda.epicfurnaces.furnace.Furnace; -import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -17,30 +16,32 @@ import org.bukkit.event.player.PlayerInteractEvent; public class InteractListeners implements Listener { private final EpicFurnaces plugin; + private final GuiManager guiManager; - public InteractListeners(EpicFurnaces plugin) { + public InteractListeners(EpicFurnaces plugin, GuiManager guiManager) { this.plugin = plugin; + this.guiManager = guiManager; } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onClick(PlayerInteractEvent event) { - if (event.getClickedBlock() == null) return; + final Block block = event.getClickedBlock(); + if (block == null) return; - if (plugin.getBlacklistHandler().isBlacklisted(event.getPlayer())) { + if (plugin.getBlacklistHandler().isBlacklisted(block.getWorld())) { return; } Player player = event.getPlayer(); - Block block = event.getClickedBlock(); - if (!player.hasPermission("EpicFurnaces.overview") - || event.getAction() != Action.LEFT_CLICK_BLOCK - || player.isSneaking() + if (event.getAction() != Action.LEFT_CLICK_BLOCK || (!block.getType().name().contains("FURNACE")) - || player.getInventory().getItemInHand().getType().name().contains("PICKAXE")) { + || player.isSneaking() + || player.getInventory().getItemInHand().getType().name().contains("PICKAXE") + || !player.hasPermission("EpicFurnaces.overview")) { return; } event.setCancelled(true); - plugin.getFurnaceManager().getFurnace(block.getLocation()).overview(player); + plugin.getFurnaceManager().getFurnace(block.getLocation()).overview(guiManager, player); } } \ No newline at end of file diff --git a/src/main/java/com/songoda/epicfurnaces/listeners/InventoryListeners.java b/src/main/java/com/songoda/epicfurnaces/listeners/InventoryListeners.java index 6c9bc6c..16537d6 100644 --- a/src/main/java/com/songoda/epicfurnaces/listeners/InventoryListeners.java +++ b/src/main/java/com/songoda/epicfurnaces/listeners/InventoryListeners.java @@ -2,7 +2,6 @@ package com.songoda.epicfurnaces.listeners; import com.songoda.epicfurnaces.EpicFurnaces; import org.bukkit.Material; -import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.*; diff --git a/src/main/java/com/songoda/epicfurnaces/storage/StorageItem.java b/src/main/java/com/songoda/epicfurnaces/storage/StorageItem.java index 07dc72e..7fb9dc4 100644 --- a/src/main/java/com/songoda/epicfurnaces/storage/StorageItem.java +++ b/src/main/java/com/songoda/epicfurnaces/storage/StorageItem.java @@ -1,12 +1,9 @@ package com.songoda.epicfurnaces.storage; import com.songoda.epicfurnaces.utils.Methods; -import com.songoda.epicfurnaces.utils.Serializers; import org.bukkit.Location; -import org.bukkit.inventory.ItemStack; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; public class StorageItem { @@ -68,17 +65,6 @@ public class StorageItem { return object; } - public List asItemStackList() { - List list = new ArrayList<>(); - if (object == null) return list; - String obj = (String) object; - if (obj.equals("[]")) return list; - List sers = new ArrayList<>(Arrays.asList(obj.split(";;"))); - for (String ser : sers) { - list.add(Serializers.deserialize(ser)); - } - return list; - } public List asStringList() { if (object instanceof ArrayList) return new ArrayList<>(); List list = new ArrayList<>(); diff --git a/src/main/java/com/songoda/epicfurnaces/utils/MySQLDatabase.java b/src/main/java/com/songoda/epicfurnaces/storage/types/MySQLDatabase.java similarity index 97% rename from src/main/java/com/songoda/epicfurnaces/utils/MySQLDatabase.java rename to src/main/java/com/songoda/epicfurnaces/storage/types/MySQLDatabase.java index 2d40a86..e72b139 100644 --- a/src/main/java/com/songoda/epicfurnaces/utils/MySQLDatabase.java +++ b/src/main/java/com/songoda/epicfurnaces/storage/types/MySQLDatabase.java @@ -1,4 +1,4 @@ -package com.songoda.epicfurnaces.utils; +package com.songoda.epicfurnaces.storage.types; import com.songoda.epicfurnaces.EpicFurnaces; diff --git a/src/main/java/com/songoda/epicfurnaces/storage/types/StorageMysql.java b/src/main/java/com/songoda/epicfurnaces/storage/types/StorageMysql.java index 138bc11..db3328b 100644 --- a/src/main/java/com/songoda/epicfurnaces/storage/types/StorageMysql.java +++ b/src/main/java/com/songoda/epicfurnaces/storage/types/StorageMysql.java @@ -4,7 +4,6 @@ import com.songoda.epicfurnaces.EpicFurnaces; import com.songoda.epicfurnaces.storage.Storage; import com.songoda.epicfurnaces.storage.StorageItem; import com.songoda.epicfurnaces.storage.StorageRow; -import com.songoda.epicfurnaces.utils.MySQLDatabase; import java.sql.DatabaseMetaData; import java.sql.ResultSet; @@ -17,9 +16,9 @@ import java.util.Map; public class StorageMysql extends Storage { - private static Map toSave = new HashMap<>(); - private static Map lastSave = null; - private MySQLDatabase database; + private Map toSave = new HashMap<>(); + private Map lastSave = null; + private final MySQLDatabase database; public StorageMysql(EpicFurnaces plugin) { super(plugin); diff --git a/src/main/java/com/songoda/epicfurnaces/storage/types/StorageYaml.java b/src/main/java/com/songoda/epicfurnaces/storage/types/StorageYaml.java index 8045e26..9519bed 100644 --- a/src/main/java/com/songoda/epicfurnaces/storage/types/StorageYaml.java +++ b/src/main/java/com/songoda/epicfurnaces/storage/types/StorageYaml.java @@ -12,8 +12,8 @@ import java.util.*; public class StorageYaml extends Storage { - private static final Map toSave = new HashMap<>(); - private static Map lastSave = null; + private final Map toSave = new HashMap<>(); + private Map lastSave = null; public StorageYaml(EpicFurnaces plugin) { super(plugin); diff --git a/src/main/java/com/songoda/epicfurnaces/tasks/FurnaceTask.java b/src/main/java/com/songoda/epicfurnaces/tasks/FurnaceTask.java index 5612abc..6561225 100644 --- a/src/main/java/com/songoda/epicfurnaces/tasks/FurnaceTask.java +++ b/src/main/java/com/songoda/epicfurnaces/tasks/FurnaceTask.java @@ -1,17 +1,17 @@ package com.songoda.epicfurnaces.tasks; -import com.songoda.core.compatibility.ServerVersion; +import com.songoda.core.compatibility.CompatibleParticleHandler; import com.songoda.epicfurnaces.EpicFurnaces; import com.songoda.epicfurnaces.furnace.Furnace; +import com.songoda.epicfurnaces.settings.Settings; +import java.util.HashSet; import org.bukkit.Location; import org.bukkit.Material; -import org.bukkit.Particle; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.scheduler.BukkitRunnable; -import java.util.ArrayList; import java.util.concurrent.ThreadLocalRandom; public class FurnaceTask extends BukkitRunnable { @@ -19,6 +19,8 @@ public class FurnaceTask extends BukkitRunnable { private static FurnaceTask instance; private final EpicFurnaces plugin; + final HashSet toRemove = new HashSet(); + boolean doParticles; private FurnaceTask(EpicFurnaces plugin) { this.plugin = plugin; @@ -27,7 +29,7 @@ public class FurnaceTask extends BukkitRunnable { public static FurnaceTask startTask(EpicFurnaces plugin) { if (instance == null) { instance = new FurnaceTask(plugin); - instance.runTaskTimer(plugin, 0, plugin.getConfig().getInt("Main.Furnace Tick Speed")); + instance.runTaskTimer(plugin, 0, Settings.TICK_SPEED.getInt()); } return instance; @@ -35,36 +37,27 @@ public class FurnaceTask extends BukkitRunnable { @Override public void run() { - for (Furnace furnace : new ArrayList<>(plugin.getFurnaceManager().getFurnaces().values())) { - Location furnaceLocation = furnace.getLocation(); + doParticles = Settings.OVERHEAT_PARTICLES.getBoolean(); + plugin.getFurnaceManager().getFurnaces().values().stream() + .filter(Furnace::isInLoadedChunk) + .forEach(furnace -> { + Location location = furnace.getLocation(); + BlockState state = location.getBlock().getState(); - if (furnaceLocation == null) continue; - - if (furnaceLocation.getWorld() == null) { - plugin.getFurnaceManager().removeFurnace(furnaceLocation); - continue; - } - - int x = furnaceLocation.getBlockX() >> 4; - int z = furnaceLocation.getBlockZ() >> 4; - - if (!furnaceLocation.getWorld().isChunkLoaded(x, z)) { - continue; - } - - BlockState state = furnace.getLocation().getBlock().getState(); - - if (!(state instanceof org.bukkit.block.Furnace)) return; - - if (((org.bukkit.block.Furnace) state).getBurnTime() == 0) continue; - - if (furnace.getLevel().getOverheat() != 0) { - overheat(furnace); - } - - if (furnace.getLevel().getFuelShare() != 0) { - fuelshare(furnace); - } + if (!(state instanceof org.bukkit.block.Furnace)) { + toRemove.add(location); + } else if (((org.bukkit.block.Furnace) state).getBurnTime() != 0) { + if (furnace.getLevel().getOverheat() != 0) { + overheat(furnace); + } + if (furnace.getLevel().getFuelShare() != 0) { + fuelshare(furnace); + } + } + }); + if (!toRemove.isEmpty()) { + toRemove.stream().forEach(l -> plugin.getFurnaceManager().removeFurnace(l)); + toRemove.clear(); } } @@ -84,14 +77,13 @@ public class FurnaceTask extends BukkitRunnable { if (block.getType() == Material.AIR || block.getRelative(BlockFace.UP).getType() != Material.AIR) continue; - if (plugin.getConfig().getBoolean("Main.Overheat Particles")) { + if (doParticles) { float xx = (float) (0 + (Math.random() * .75)); float yy = (float) (0 + (Math.random() * 1)); float zz = (float) (0 + (Math.random() * .75)); - - if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_9)) - location.getWorld().spawnParticle(Particle.SMOKE_NORMAL, location, 25, xx, yy, zz, 0); + + CompatibleParticleHandler.spawnParticles(CompatibleParticleHandler.ParticleType.SMOKE_NORMAL, location, 25, xx, yy, zz); } if (block.getType() == Material.SNOW) { block.setType(Material.AIR); @@ -122,14 +114,13 @@ public class FurnaceTask extends BukkitRunnable { furnaceBlock.setBurnTime((short) 100); furnaceBlock.update(); - if (plugin.getConfig().getBoolean("Main.Overheat Particles")) { + if (doParticles) { float xx = (float) (0 + (Math.random() * .75)); float yy = (float) (0 + (Math.random() * 1)); float zz = (float) (0 + (Math.random() * .75)); - if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_9)) - location.getWorld().spawnParticle(Particle.SMOKE_NORMAL, location, 25, xx, yy, zz, 0); + CompatibleParticleHandler.spawnParticles(CompatibleParticleHandler.ParticleType.SMOKE_NORMAL, location, 25, xx, yy, zz); } } } diff --git a/src/main/java/com/songoda/epicfurnaces/utils/Methods.java b/src/main/java/com/songoda/epicfurnaces/utils/Methods.java index ca70cdc..d67b6c7 100644 --- a/src/main/java/com/songoda/epicfurnaces/utils/Methods.java +++ b/src/main/java/com/songoda/epicfurnaces/utils/Methods.java @@ -2,10 +2,11 @@ package com.songoda.epicfurnaces.utils; import com.songoda.core.compatibility.ServerVersion; import com.songoda.epicfurnaces.EpicFurnaces; -import org.bukkit.*; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.World; import org.bukkit.block.Block; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; import java.text.DecimalFormat; import java.util.Arrays; diff --git a/src/main/java/com/songoda/epicfurnaces/utils/Metrics.java b/src/main/java/com/songoda/epicfurnaces/utils/Metrics.java deleted file mode 100644 index 6ad2263..0000000 --- a/src/main/java/com/songoda/epicfurnaces/utils/Metrics.java +++ /dev/null @@ -1,695 +0,0 @@ -package com.songoda.epicfurnaces.utils; - -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.RegisteredServiceProvider; -import org.bukkit.plugin.ServicePriority; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - -import javax.net.ssl.HttpsURLConnection; -import java.io.*; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.*; -import java.util.concurrent.Callable; -import java.util.logging.Level; -import java.util.zip.GZIPOutputStream; - -/** - * bStats collects some data for plugin authors. - *

- * Check out https://bStats.org/ to learn more about bStats! - */ -@SuppressWarnings({"WeakerAccess", "unused"}) -public class Metrics { - - static { - // You can use the property to disable the check in your test environment - if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { - // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D - final String defaultPackage = new String( - new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'}); - final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); - // We want to make sure nobody just copy & pastes the example and use the wrong package names - if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) { - throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); - } - } - } - - // The version of this bStats class - public static final int B_STATS_VERSION = 1; - - // The url to which the data is sent - private static final String URL = "https://bStats.org/submitData/bukkit"; - - // Is bStats enabled on this server? - private boolean enabled; - - // Should failed requests be logged? - private static boolean logFailedRequests; - - // Should the sent data be logged? - private static boolean logSentData; - - // Should the response text be logged? - private static boolean logResponseStatusText; - - // The uuid of the server - private static String serverUUID; - - // The plugin - private final Plugin plugin; - - // A list with all custom charts - private final List charts = new ArrayList<>(); - - /** - * Class constructor. - * - * @param plugin The plugin which stats should be submitted. - */ - public Metrics(Plugin plugin) { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null!"); - } - this.plugin = plugin; - - // Get the config file - File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); - File configFile = new File(bStatsFolder, "config.yml"); - YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); - - // Check if the config file exists - if (!config.isSet("serverUuid")) { - - // Add default values - config.addDefault("enabled", true); - // Every server gets it's unique random id. - config.addDefault("serverUuid", UUID.randomUUID().toString()); - // Should failed request be logged? - config.addDefault("logFailedRequests", false); - // Should the sent data be logged? - config.addDefault("logSentData", false); - // Should the response text be logged? - config.addDefault("logResponseStatusText", false); - - // Inform the server owners about bStats - config.options().header( - "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + - "To honor their work, you should not disable it.\n" + - "This has nearly blacklist effect on the server performance!\n" + - "Check out https://bStats.org/ to learn more :)" - ).copyDefaults(true); - try { - config.save(configFile); - } catch (IOException ignored) { } - } - - // Load the data - enabled = config.getBoolean("enabled", true); - serverUUID = config.getString("serverUuid"); - logFailedRequests = config.getBoolean("logFailedRequests", false); - logSentData = config.getBoolean("logSentData", false); - logResponseStatusText = config.getBoolean("logResponseStatusText", false); - - if (enabled) { - boolean found = false; - // Search for all other bStats Metrics classes to see if we are the first one - for (Class service : Bukkit.getServicesManager().getKnownServices()) { - try { - service.getField("B_STATS_VERSION"); // Our identifier :) - found = true; // We aren't the first - break; - } catch (NoSuchFieldException ignored) { } - } - // Register our service - Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); - if (!found) { - // We are the first! - startSubmitting(); - } - } - } - - /** - * Checks if bStats is enabled. - * - * @return Whether bStats is enabled or not. - */ - public boolean isEnabled() { - return enabled; - } - - /** - * Adds a custom chart. - * - * @param chart The chart to add. - */ - public void addCustomChart(CustomChart chart) { - if (chart == null) { - throw new IllegalArgumentException("Chart cannot be null!"); - } - charts.add(chart); - } - - /** - * Starts the Scheduler which submits our data every 30 minutes. - */ - private void startSubmitting() { - final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags - timer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - if (!plugin.isEnabled()) { // Plugin was disabled - timer.cancel(); - return; - } - // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler - // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) - Bukkit.getScheduler().runTask(plugin, () -> submitData()); - } - }, 1000 * 60 * 5, 1000 * 60 * 30); - // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start - // WARNING: Changing the frequency has blacklist effect but your plugin WILL be blocked/deleted! - // WARNING: Just don't do it! - } - - /** - * Gets the plugin specific data. - * This method is called using Reflection. - * - * @return The plugin specific data. - */ - public JSONObject getPluginData() { - JSONObject data = new JSONObject(); - - String pluginName = plugin.getDescription().getName(); - String pluginVersion = plugin.getDescription().getVersion(); - - data.put("pluginName", pluginName); // Append the name of the plugin - data.put("pluginVersion", pluginVersion); // Append the version of the plugin - JSONArray customCharts = new JSONArray(); - for (CustomChart customChart : charts) { - // Add the data of the custom charts - JSONObject chart = customChart.getRequestJsonObject(); - if (chart == null) { // If the chart is null, we skip it - continue; - } - customCharts.add(chart); - } - data.put("customCharts", customCharts); - - return data; - } - - /** - * Gets the server specific data. - * - * @return The server specific data. - */ - private JSONObject getServerData() { - // Minecraft specific data - int playerAmount; - try { - // Around MC 1.8 the return type was changed to a collection from an array, - // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; - Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); - playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) - ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() - : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; - } catch (Exception e) { - playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed - } - int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; - String bukkitVersion = Bukkit.getVersion(); - - // OS/Java specific data - String javaVersion = System.getProperty("java.version"); - String osName = System.getProperty("os.name"); - String osArch = System.getProperty("os.arch"); - String osVersion = System.getProperty("os.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - - JSONObject data = new JSONObject(); - - data.put("serverUUID", serverUUID); - - data.put("playerAmount", playerAmount); - data.put("onlineMode", onlineMode); - data.put("bukkitVersion", bukkitVersion); - - data.put("javaVersion", javaVersion); - data.put("osName", osName); - data.put("osArch", osArch); - data.put("osVersion", osVersion); - data.put("coreCount", coreCount); - - return data; - } - - /** - * Collects the data and sends it afterwards. - */ - private void submitData() { - final JSONObject data = getServerData(); - - JSONArray pluginData = new JSONArray(); - // Search for all other bStats Metrics classes to get their plugin data - for (Class service : Bukkit.getServicesManager().getKnownServices()) { - try { - service.getField("B_STATS_VERSION"); // Our identifier :) - - for (RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { - try { - pluginData.add(provider.getService().getMethod("getPluginData").invoke(provider.getProvider())); - } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } - } - } catch (NoSuchFieldException ignored) { } - } - - data.put("plugins", pluginData); - - // Create a new thread for the connection to the bStats server - new Thread(new Runnable() { - @Override - public void run() { - try { - // Send the data - sendData(plugin, data); - } catch (Exception e) { - // Something went wrong! :( - if (logFailedRequests) { - plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); - } - } - } - }).start(); - } - - /** - * Sends the data to the bStats server. - * - * @param plugin Any plugin. It's just used to get a logger plugin. - * @param data The data to send. - * @throws Exception If the request failed. - */ - private static void sendData(Plugin plugin, JSONObject data) throws Exception { - if (data == null) { - throw new IllegalArgumentException("Data cannot be null!"); - } - if (Bukkit.isPrimaryThread()) { - throw new IllegalAccessException("This method must not be called from the main thread!"); - } - if (logSentData) { - plugin.getLogger().info("Sending data to bStats: " + data.toString()); - } - HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); - - // Compress the data to save bandwidth - byte[] compressedData = compress(data.toString()); - - // Add headers - connection.setRequestMethod("POST"); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request - connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); - connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format - connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); - - // Send data - connection.setDoOutput(true); - DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); - outputStream.write(compressedData); - outputStream.flush(); - outputStream.close(); - - InputStream inputStream = connection.getInputStream(); - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); - - StringBuilder builder = new StringBuilder(); - String line; - while ((line = bufferedReader.readLine()) != null) { - builder.append(line); - } - bufferedReader.close(); - if (logResponseStatusText) { - plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString()); - } - } - - /** - * Gzips the given String. - * - * @param str The string to gzip. - * @return The gzipped String. - * @throws IOException If the compression failed. - */ - private static byte[] compress(final String str) throws IOException { - if (str == null) { - return null; - } - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - GZIPOutputStream gzip = new GZIPOutputStream(outputStream); - gzip.write(str.getBytes(StandardCharsets.UTF_8)); - gzip.close(); - return outputStream.toByteArray(); - } - - /** - * Represents a custom chart. - */ - public static abstract class CustomChart { - - // The id of the chart - final String chartId; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - CustomChart(String chartId) { - if (chartId == null || chartId.isEmpty()) { - throw new IllegalArgumentException("ChartId cannot be null or empty!"); - } - this.chartId = chartId; - } - - private JSONObject getRequestJsonObject() { - JSONObject chart = new JSONObject(); - chart.put("chartId", chartId); - try { - JSONObject data = getChartData(); - if (data == null) { - // If the data is null we don't send the chart. - return null; - } - chart.put("data", data); - } catch (Throwable t) { - if (logFailedRequests) { - Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); - } - return null; - } - return chart; - } - - protected abstract JSONObject getChartData() throws Exception; - - } - - /** - * Represents a custom simple pie. - */ - public static class SimplePie extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimplePie(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JSONObject getChartData() throws Exception { - JSONObject data = new JSONObject(); - String value = callable.call(); - if (value == null || value.isEmpty()) { - // Null = skip the chart - return null; - } - data.put("value", value); - return data; - } - } - - /** - * Represents a custom advanced pie. - */ - public static class AdvancedPie extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedPie(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JSONObject getChartData() throws Exception { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - values.put(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.put("values", values); - return data; - } - } - - /** - * Represents a custom drilldown pie. - */ - public static class DrilldownPie extends CustomChart { - - private final Callable>> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public DrilldownPie(String chartId, Callable>> callable) { - super(chartId); - this.callable = callable; - } - - @Override - public JSONObject getChartData() throws Exception { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - Map> map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean reallyAllSkipped = true; - for (Map.Entry> entryValues : map.entrySet()) { - JSONObject value = new JSONObject(); - boolean allSkipped = true; - for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { - value.put(valueEntry.getKey(), valueEntry.getValue()); - allSkipped = false; - } - if (!allSkipped) { - reallyAllSkipped = false; - values.put(entryValues.getKey(), value); - } - } - if (reallyAllSkipped) { - // Null = skip the chart - return null; - } - data.put("values", values); - return data; - } - } - - /** - * Represents a custom single line chart. - */ - public static class SingleLineChart extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SingleLineChart(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JSONObject getChartData() throws Exception { - JSONObject data = new JSONObject(); - int value = callable.call(); - if (value == 0) { - // Null = skip the chart - return null; - } - data.put("value", value); - return data; - } - - } - - /** - * Represents a custom multi line chart. - */ - public static class MultiLineChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public MultiLineChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JSONObject getChartData() throws Exception { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - values.put(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.put("values", values); - return data; - } - - } - - /** - * Represents a custom simple bar chart. - */ - public static class SimpleBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimpleBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JSONObject getChartData() throws Exception { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - for (Map.Entry entry : map.entrySet()) { - JSONArray categoryValues = new JSONArray(); - categoryValues.add(entry.getValue()); - values.put(entry.getKey(), categoryValues); - } - data.put("values", values); - return data; - } - - } - - /** - * Represents a custom advanced bar chart. - */ - public static class AdvancedBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JSONObject getChartData() throws Exception { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue().length == 0) { - continue; // Skip this invalid - } - allSkipped = false; - JSONArray categoryValues = new JSONArray(); - for (int categoryValue : entry.getValue()) { - categoryValues.add(categoryValue); - } - values.put(entry.getKey(), categoryValues); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.put("values", values); - return data; - } - } - -} \ No newline at end of file diff --git a/src/main/java/com/songoda/epicfurnaces/utils/Serializers.java b/src/main/java/com/songoda/epicfurnaces/utils/Serializers.java deleted file mode 100644 index 6c13dbb..0000000 --- a/src/main/java/com/songoda/epicfurnaces/utils/Serializers.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.songoda.epicfurnaces.utils; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Color; -import org.bukkit.Material; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.inventory.meta.LeatherArmorMeta; -import org.bukkit.inventory.meta.SkullMeta; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class Serializers { - public static String serialize(ItemStack item) { - StringBuilder builder = new StringBuilder(); - builder.append(item.getType().toString()); - if (item.getDurability() != 0) builder.append(":" + item.getDurability()); - builder.append(" " + item.getAmount()); - for (Enchantment enchant : item.getEnchantments().keySet()) - builder.append(" " + enchant.getName() + ":" + item.getEnchantments().get(enchant)); - String name = getName(item); - if (name != null) builder.append(" name:" + name); - String lore = getLore(item); - if (lore != null) builder.append(" lore:" + lore); - Color color = getArmorColor(item); - if (color != null) builder.append(" rgb:" + color.getRed() + "|" + color.getGreen() + "|" + color.getBlue()); - String owner = getOwner(item); - if (owner != null) builder.append(" owner:" + owner); - return builder.toString(); - } - - public static ItemStack deserialize(String serializedItem) { - String[] strings = serializedItem.split(" "); - Map enchants = new HashMap<>(); - String[] args; - ItemStack item = new ItemStack(Material.AIR); - for (String str : strings) { - args = str.split(":"); - if (Material.matchMaterial(args[0]) != null && item.getType() == Material.AIR) { - item.setType(Material.matchMaterial(args[0])); - if (args.length == 2) item.setDurability(Short.parseShort(args[1])); - break; - } - } - if (item.getType() == Material.AIR) { - Bukkit.getLogger().info("Could not find a valid material for the item in \"" + serializedItem + "\""); - return null; - } - for (String str : strings) { - args = str.split(":", 2); - if (isNumber(args[0])) item.setAmount(Integer.parseInt(args[0])); - if (args.length == 1) continue; - if (args[0].equalsIgnoreCase("name")) { - setName(item, ChatColor.translateAlternateColorCodes('&', args[1])); - continue; - } - if (args[0].equalsIgnoreCase("lore")) { - setLore(item, ChatColor.translateAlternateColorCodes('&', args[1])); - continue; - } - if (args[0].equalsIgnoreCase("rgb")) { - setArmorColor(item, args[1]); - continue; - } - if (args[0].equalsIgnoreCase("owner")) { - setOwner(item, args[1]); - continue; - } - if (Enchantment.getByName(args[0].toUpperCase()) != null) { - enchants.put(Enchantment.getByName(args[0].toUpperCase()), Integer.parseInt(args[1])); - continue; - } - } - item.addUnsafeEnchantments(enchants); - return item.getType().equals(Material.AIR) ? null : item; - } - - private static String getOwner(ItemStack item) { - if (!(item.getItemMeta() instanceof SkullMeta)) return null; - return ((SkullMeta) item.getItemMeta()).getOwner(); - } - - private static void setOwner(ItemStack item, String owner) { - try { - SkullMeta meta = (SkullMeta) item.getItemMeta(); - meta.setOwner(owner); - item.setItemMeta(meta); - } catch (Exception exception) { - return; - } - } - - private static String getName(ItemStack item) { - if (!item.hasItemMeta()) return null; - if (!item.getItemMeta().hasDisplayName()) return null; - return item.getItemMeta().getDisplayName().replace(" ", "_").replace(ChatColor.COLOR_CHAR, '&'); - } - - private static void setName(ItemStack item, String name) { - name = name.replace("_", " ").replace('&', ChatColor.COLOR_CHAR); - ItemMeta meta = item.getItemMeta(); - meta.setDisplayName(name); - item.setItemMeta(meta); - } - - private static String getLore(ItemStack item) { - if (!item.hasItemMeta()) return null; - if (!item.getItemMeta().hasLore()) return null; - StringBuilder builder = new StringBuilder(); - List lore = item.getItemMeta().getLore(); - for (int ind = 0; ind < lore.size(); ind++) { - builder.append((ind > 0 ? "|" : "") + lore.get(ind).replace(" ", "_").replace(ChatColor.COLOR_CHAR, '&')); - } - return builder.toString(); - } - - private static void setLore(ItemStack item, String lore) { - lore = lore.replace("_", " ").replace('&', ChatColor.COLOR_CHAR); - ItemMeta meta = item.getItemMeta(); - meta.setLore(Arrays.asList(lore.split("\\|"))); - item.setItemMeta(meta); - } - - private static Color getArmorColor(ItemStack item) { - if (!(item.getItemMeta() instanceof LeatherArmorMeta)) return null; - return ((LeatherArmorMeta) item.getItemMeta()).getColor(); - } - - private static void setArmorColor(ItemStack item, String str) { - try { - String[] colors = str.split("\\|"); - int red = Integer.parseInt(colors[0]); - int green = Integer.parseInt(colors[1]); - int blue = Integer.parseInt(colors[2]); - LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta(); - meta.setColor(Color.fromRGB(red, green, blue)); - item.setItemMeta(meta); - } catch (Exception exception) { - return; - } - } - - private static boolean isNumber(String str) { - try { - Integer.parseInt(str); - } catch (NumberFormatException exception) { - return false; - } - return true; - } -}