diff --git a/src/main/java/com/songoda/epicenchants/CommandCommons.java b/src/main/java/com/songoda/epicenchants/CommandCommons.java index ba21399..14b40fd 100644 --- a/src/main/java/com/songoda/epicenchants/CommandCommons.java +++ b/src/main/java/com/songoda/epicenchants/CommandCommons.java @@ -1,15 +1,15 @@ package com.songoda.epicenchants; -import com.songoda.epicenchants.utils.Methods; +import com.craftaro.core.utils.NumberUtils; import org.bukkit.command.CommandSender; public class CommandCommons { - public static boolean isInt(String number, CommandSender sender) { - if (!Methods.isInt(number)) { - EpicEnchants.getInstance().getLocale().newMessage("Not a number.").sendPrefixedMessage(sender); - return false; + if (NumberUtils.isInt(number)) { + return true; } - return true; + + EpicEnchants.getPlugin(EpicEnchants.class).getLocale().newMessage("Not a number.").sendPrefixedMessage(sender); + return false; } } diff --git a/src/main/java/com/songoda/epicenchants/EpicEnchants.java b/src/main/java/com/songoda/epicenchants/EpicEnchants.java index d6da4ba..b68bc96 100644 --- a/src/main/java/com/songoda/epicenchants/EpicEnchants.java +++ b/src/main/java/com/songoda/epicenchants/EpicEnchants.java @@ -3,7 +3,6 @@ package com.songoda.epicenchants; import com.craftaro.core.SongodaCore; import com.craftaro.core.SongodaPlugin; import com.craftaro.core.commands.CommandManager; -import com.craftaro.core.compatibility.CompatibleMaterial; import com.craftaro.core.configuration.Config; import com.craftaro.core.gui.GuiManager; import com.craftaro.core.hooks.EconomyManager; @@ -44,9 +43,6 @@ import java.util.List; import java.util.stream.Collectors; public class EpicEnchants extends SongodaPlugin { - - private static EpicEnchants INSTANCE; - private final GuiManager guiManager = new GuiManager(this); private EnchantManager enchantManager; private InfoManager infoManager; @@ -58,21 +54,14 @@ public class EpicEnchants extends SongodaPlugin { private EnchantUtils enchantUtils; private ItemGroup itemGroup; - public static EpicEnchants getInstance() { - return INSTANCE; - } - @Override public void onPluginLoad() { - INSTANCE = this; } @Override public void onPluginEnable() { - // Run Songoda Updater SongodaCore.registerPlugin(this, 67, XMaterial.DIAMOND_SWORD); - // setup commands this.commandManager = new com.craftaro.core.commands.CommandManager(this); this.commandManager.addMainCommand("ee") .addSubCommand(new CommandReload(this)) @@ -105,12 +94,12 @@ public class EpicEnchants extends SongodaPlugin { this.commandManager = new CommandManager(this); this.itemGroup = new ItemGroup(); - groupManager.loadGroups(); - enchantManager.loadEnchants(); - infoManager.loadMenus(); + this.groupManager.loadGroups(); + this.enchantManager.loadEnchants(); + this.infoManager.loadMenus(); // Listeners - guiManager.init(); + this.guiManager.init(); PluginManager pluginManager = Bukkit.getPluginManager(); pluginManager.registerEvents(new BookListener(this), this); pluginManager.registerEvents(new ArmorListener(), this); @@ -121,15 +110,15 @@ public class EpicEnchants extends SongodaPlugin { pluginManager.registerEvents(new BlackScrollListener(this), this); pluginManager.registerEvents(new DustListener(this), this); - if (!enchantManager.getValues().isEmpty()) { - getLogger().info("Successfully loaded enchants: " + enchantManager.getValues().stream().map(Enchant::getIdentifier).collect(Collectors.joining(", "))); + if (!this.enchantManager.getValues().isEmpty()) { + getLogger().info("Successfully loaded enchants: " + this.enchantManager.getValues().stream().map(Enchant::getIdentifier).collect(Collectors.joining(", "))); } } private void preload() { FastInv.init(this); this.fileManager = new FileManager(this); - fileManager.loadFiles(); + this.fileManager.loadFiles(); } @Override @@ -142,17 +131,17 @@ public class EpicEnchants extends SongodaPlugin { @Override public void onConfigReload() { - fileManager.clear(); - fileManager.loadFiles(); + this.fileManager.clear(); + this.fileManager.loadFiles(); - groupManager.clear(); - groupManager.loadGroups(); + this.groupManager.clear(); + this.groupManager.loadGroups(); - enchantManager.clear(); - enchantManager.loadEnchants(); + this.enchantManager.clear(); + this.enchantManager.loadEnchants(); - infoManager.clear(); - infoManager.loadMenus(); + this.infoManager.clear(); + this.infoManager.loadMenus(); this.setLocale(getConfig().getString("System.Language Mode"), true); this.locale.reloadMessages(); @@ -192,10 +181,18 @@ public class EpicEnchants extends SongodaPlugin { } public CommandManager getCommandManager() { - return commandManager; + return this.commandManager; } public GuiManager getGuiManager() { - return guiManager; + return this.guiManager; + } + + /** + * @deprecated Use {@link EpicEnchants#getPlugin(Class)} instead + */ + @Deprecated + public static EpicEnchants getInstance() { + return EpicEnchants.getPlugin(EpicEnchants.class); } } diff --git a/src/main/java/com/songoda/epicenchants/commands/CommandAlchemist.java b/src/main/java/com/songoda/epicenchants/commands/CommandAlchemist.java index fa1c554..5cc0440 100644 --- a/src/main/java/com/songoda/epicenchants/commands/CommandAlchemist.java +++ b/src/main/java/com/songoda/epicenchants/commands/CommandAlchemist.java @@ -9,18 +9,17 @@ import org.bukkit.entity.Player; import java.util.List; public class CommandAlchemist extends AbstractCommand { - private final EpicEnchants plugin; public CommandAlchemist(EpicEnchants plugin) { - super(true, "alchemist"); + super(CommandType.PLAYER_ONLY, "alchemist"); this.plugin = plugin; } @Override protected ReturnType runCommand(CommandSender sender, String... args) { Player player = (Player) sender; - new AlchemistMenu(plugin, plugin.getFileManager().getConfiguration("menus/alchemist-menu")).open(player); + new AlchemistMenu(this.plugin, this.plugin.getFileManager().getConfiguration("menus/alchemist-menu")).open(player); return ReturnType.SUCCESS; } diff --git a/src/main/java/com/songoda/epicenchants/commands/CommandApply.java b/src/main/java/com/songoda/epicenchants/commands/CommandApply.java index b3af3c6..779d067 100644 --- a/src/main/java/com/songoda/epicenchants/commands/CommandApply.java +++ b/src/main/java/com/songoda/epicenchants/commands/CommandApply.java @@ -20,42 +20,45 @@ import static com.songoda.epicenchants.enums.EnchantResult.BROKEN_FAILURE; import static com.songoda.epicenchants.utils.single.GeneralUtils.getMessageFromResult; public class CommandApply extends AbstractCommand { - private final EpicEnchants plugin; public CommandApply(EpicEnchants plugin) { - super(true, "apply"); + super(CommandType.PLAYER_ONLY, "apply"); this.plugin = plugin; } //apply [enchant] [level] @Override protected ReturnType runCommand(CommandSender sender, String... args) { - if (args.length < 2 || args.length > 4) + if (args.length < 2 || args.length > 4) { return ReturnType.SYNTAX_ERROR; + } - Optional optionalEnchant = plugin.getEnchantManager().getValue(args[0].replaceAll("_", " ")); + Optional optionalEnchant = this.plugin.getEnchantManager().getValue(args[0].replaceAll("_", " ")); if (!optionalEnchant.isPresent()) { - plugin.getLocale().newMessage("&cNo enchants exist with that name...").sendPrefixedMessage(sender); + this.plugin.getLocale().newMessage("&cNo enchants exist with that name...").sendPrefixedMessage(sender); return ReturnType.FAILURE; } - if (!CommandCommons.isInt(args[1], sender)) + if (!CommandCommons.isInt(args[1], sender)) { return ReturnType.FAILURE; + } int successRate = 100; int destroyRate = 0; if (args.length > 2) { - if (!CommandCommons.isInt(args[2], sender)) + if (!CommandCommons.isInt(args[2], sender)) { return ReturnType.FAILURE; + } successRate = Integer.parseInt(args[2]); } if (args.length > 3) { - if (!CommandCommons.isInt(args[3], sender)) + if (!CommandCommons.isInt(args[3], sender)) { return ReturnType.FAILURE; + } destroyRate = Integer.parseInt(args[3]); } Enchant enchant = optionalEnchant.get(); @@ -64,7 +67,7 @@ public class CommandApply extends AbstractCommand { if (!enchant.getItemWhitelist().contains(CompatibleMaterial.getMaterial(player.getItemInHand().getType()).get())) { System.out.println("List = " + enchant.getItemWhitelist()); - plugin.getLocale().getMessage("command.apply.invaliditem") + this.plugin.getLocale().getMessage("command.apply.invaliditem") .processPlaceholder("enchant", enchant.getIdentifier()) .sendPrefixedMessage(player); return ReturnType.FAILURE; @@ -72,10 +75,9 @@ public class CommandApply extends AbstractCommand { int slot = player.getInventory().getHeldItemSlot(); ItemStack before = player.getItemInHand(); - Tuple result = plugin.getEnchantUtils().apply(before, enchant, level, - successRate, destroyRate); + Tuple result = this.plugin.getEnchantUtils().apply(before, enchant, level, successRate, destroyRate); - plugin.getLocale().getMessage(getMessageFromResult(result.getRight())) + this.plugin.getLocale().getMessage(getMessageFromResult(result.getRight())) .processPlaceholder("enchant", enchant.getIdentifier()) .sendPrefixedMessage(player); @@ -91,21 +93,31 @@ public class CommandApply extends AbstractCommand { @Override protected List onTab(CommandSender sender, String... args) { if (args.length == 1) { - return plugin.getEnchantManager().getValues() - .stream().map(Enchant::getIdentifier).collect(Collectors.toList()); + return this.plugin + .getEnchantManager() + .getValues() + .stream() + .map(Enchant::getIdentifier) + .collect(Collectors.toList()); } else if (args.length == 2) { - Enchant enchant = plugin.getEnchantManager().getValues() - .stream().findFirst().orElse(null); + Enchant enchant = this.plugin + .getEnchantManager() + .getValues() + .stream() + .findFirst() + .orElse(null); List levels = new ArrayList<>(); if (enchant != null) { - for (int i = 1; i <= enchant.getMaxLevel(); i++) + for (int i = 1; i <= enchant.getMaxLevel(); i++) { levels.add(String.valueOf(i)); + } } return levels; } else if (args.length == 3 || args.length == 4) { List rates = new ArrayList<>(); - for (int i = 1; i <= 100; i++) + for (int i = 1; i <= 100; i++) { rates.add(String.valueOf(i)); + } return rates; } return null; diff --git a/src/main/java/com/songoda/epicenchants/commands/CommandEnchanter.java b/src/main/java/com/songoda/epicenchants/commands/CommandEnchanter.java index d214e29..f6abfb0 100644 --- a/src/main/java/com/songoda/epicenchants/commands/CommandEnchanter.java +++ b/src/main/java/com/songoda/epicenchants/commands/CommandEnchanter.java @@ -9,18 +9,17 @@ import org.bukkit.entity.Player; import java.util.List; public class CommandEnchanter extends AbstractCommand { - private final EpicEnchants plugin; public CommandEnchanter(EpicEnchants plugin) { - super(true, "enchanter"); + super(CommandType.PLAYER_ONLY, "enchanter"); this.plugin = plugin; } @Override protected ReturnType runCommand(CommandSender sender, String... args) { Player player = (Player) sender; - new EnchanterMenu(plugin, plugin.getFileManager().getConfiguration("menus/enchanter-menu"), player).open(player); + new EnchanterMenu(this.plugin, this.plugin.getFileManager().getConfiguration("menus/enchanter-menu"), player).open(player); return ReturnType.SUCCESS; } diff --git a/src/main/java/com/songoda/epicenchants/commands/CommandGiveBook.java b/src/main/java/com/songoda/epicenchants/commands/CommandGiveBook.java index fc79d21..6644fa9 100644 --- a/src/main/java/com/songoda/epicenchants/commands/CommandGiveBook.java +++ b/src/main/java/com/songoda/epicenchants/commands/CommandGiveBook.java @@ -15,31 +15,31 @@ import java.util.Optional; import java.util.stream.Collectors; public class CommandGiveBook extends AbstractCommand { - private final EpicEnchants plugin; public CommandGiveBook(EpicEnchants plugin) { - super(false, "givebook"); + super(CommandType.CONSOLE_OK, "givebook"); this.plugin = plugin; } //givebook [level] [success-rate] [destroy-rate] @Override protected ReturnType runCommand(CommandSender sender, String... args) { - if (args.length < 2 || args.length > 5) + if (args.length < 2 || args.length > 5) { return ReturnType.SYNTAX_ERROR; + } OfflinePlayer target = Bukkit.getPlayer(args[0]); if (target == null) { - plugin.getLocale().newMessage("&cThis player does not exist...").sendPrefixedMessage(sender); + this.plugin.getLocale().newMessage("&cThis player does not exist...").sendPrefixedMessage(sender); return ReturnType.FAILURE; } - Optional optionalEnchant = plugin.getEnchantManager().getValue(args[1].replaceAll("_", " ")); + Optional optionalEnchant = this.plugin.getEnchantManager().getValue(args[1].replaceAll("_", " ")); if (!optionalEnchant.isPresent()) { - plugin.getLocale().newMessage("&cNo enchants exist with that name...").sendPrefixedMessage(sender); + this.plugin.getLocale().newMessage("&cNo enchants exist with that name...").sendPrefixedMessage(sender); return ReturnType.FAILURE; } @@ -49,25 +49,28 @@ public class CommandGiveBook extends AbstractCommand { int destroyRate = -1; if (args.length > 2) { - if (!CommandCommons.isInt(args[2], sender)) + if (!CommandCommons.isInt(args[2], sender)) { return ReturnType.FAILURE; + } level = Integer.parseInt(args[2]); } if (args.length > 3) { - if (!CommandCommons.isInt(args[3], sender)) + if (!CommandCommons.isInt(args[3], sender)) { return ReturnType.FAILURE; + } successRate = Integer.parseInt(args[3]); } if (args.length > 4) { - if (!CommandCommons.isInt(args[4], sender)) + if (!CommandCommons.isInt(args[4], sender)) { return ReturnType.FAILURE; + } destroyRate = Integer.parseInt(args[4]); } if (level != -0 && (level > enchant.getMaxLevel() || level < 0)) { - plugin.getLocale().getMessage("command.book." + (level > enchant.getMaxLevel() ? "maxlevel" : "minlevel")) + this.plugin.getLocale().getMessage("command.book." + (level > enchant.getMaxLevel() ? "maxlevel" : "minlevel")) .processPlaceholder("enchant", enchant.getIdentifier()) .processPlaceholder("max_level", enchant.getMaxLevel()) .sendPrefixedMessage(sender); @@ -75,10 +78,10 @@ public class CommandGiveBook extends AbstractCommand { } target.getPlayer().getInventory().addItem(enchant.getBook().get(enchant, level, successRate, destroyRate)); - plugin.getLocale().getMessage("command.book.received") + this.plugin.getLocale().getMessage("command.book.received") .processPlaceholder("enchant", enchant.getIdentifier()) .sendPrefixedMessage(target.getPlayer()); - plugin.getLocale().getMessage("command.book.gave") + this.plugin.getLocale().getMessage("command.book.gave") .processPlaceholder("player", target.getPlayer().getName()) .processPlaceholder("enchant", enchant.getIdentifier()) .sendPrefixedMessage(sender); @@ -90,21 +93,27 @@ public class CommandGiveBook extends AbstractCommand { if (args.length == 1) { return Bukkit.getOnlinePlayers().stream().map(Player::getName).collect(Collectors.toList()); } else if (args.length == 2) { - return plugin.getEnchantManager().getValues() + return this.plugin.getEnchantManager().getValues() .stream().map(Enchant::getIdentifier).collect(Collectors.toList()); } else if (args.length == 3) { - Enchant enchant = plugin.getEnchantManager().getValues() - .stream().findFirst().orElse(null); + Enchant enchant = this.plugin + .getEnchantManager() + .getValues() + .stream() + .findFirst() + .orElse(null); List levels = new ArrayList<>(); if (enchant != null) { - for (int i = 1; i <= enchant.getMaxLevel(); i++) + for (int i = 1; i <= enchant.getMaxLevel(); i++) { levels.add(String.valueOf(i)); + } } return levels; } else if (args.length == 4 || args.length == 5) { List rates = new ArrayList<>(); - for (int i = 1; i <= 100; i++) + for (int i = 1; i <= 100; i++) { rates.add(String.valueOf(i)); + } return rates; } return null; diff --git a/src/main/java/com/songoda/epicenchants/commands/CommandGiveItemDust.java b/src/main/java/com/songoda/epicenchants/commands/CommandGiveItemDust.java index 5ec9b50..b1d3cbb 100644 --- a/src/main/java/com/songoda/epicenchants/commands/CommandGiveItemDust.java +++ b/src/main/java/com/songoda/epicenchants/commands/CommandGiveItemDust.java @@ -15,32 +15,32 @@ import java.util.List; import java.util.stream.Collectors; public class CommandGiveItemDust extends AbstractCommand { - private final EpicEnchants plugin; public CommandGiveItemDust(EpicEnchants plugin) { - super(false, "giveitemdust"); + super(CommandType.CONSOLE_OK, "giveitemdust"); this.plugin = plugin; } //giveitemdust [type] [percentage] @Override protected ReturnType runCommand(CommandSender sender, String... args) { - if (args.length < 2 || args.length > 5) + if (args.length < 2 || args.length > 5) { return ReturnType.SYNTAX_ERROR; + } OfflinePlayer target = Bukkit.getPlayer(args[0]); if (target == null) { - plugin.getLocale().newMessage("&cThis player does not exist...").sendPrefixedMessage(sender); + this.plugin.getLocale().newMessage("&cThis player does not exist...").sendPrefixedMessage(sender); return ReturnType.FAILURE; } - List groups = plugin.getGroupManager().getValues().stream() + List groups = this.plugin.getGroupManager().getValues().stream() .filter(group -> group.getIdentifier().equalsIgnoreCase(args[1])).collect(Collectors.toList()); if (groups.isEmpty()) { - plugin.getLocale().newMessage("&cThe group you entered was no found...").sendPrefixedMessage(sender); + this.plugin.getLocale().newMessage("&cThe group you entered was no found...").sendPrefixedMessage(sender); return ReturnType.FAILURE; } @@ -54,16 +54,17 @@ public class CommandGiveItemDust extends AbstractCommand { } if (args.length > 3) { - if (!CommandCommons.isInt(args[3], sender)) + if (!CommandCommons.isInt(args[3], sender)) { return ReturnType.FAILURE; + } percentage = Integer.parseInt(args[3]); } - target.getPlayer().getInventory().addItem(plugin.getSpecialItems().getDust(group, dustType, percentage, true)); - plugin.getLocale().getMessage("command.dust.received") + target.getPlayer().getInventory().addItem(this.plugin.getSpecialItems().getDust(group, dustType, percentage, true)); + this.plugin.getLocale().getMessage("command.dust.received") .processPlaceholder("group", group.getIdentifier()) .sendPrefixedMessage(target.getPlayer()); - plugin.getLocale().getMessage("command.dust.gave") + this.plugin.getLocale().getMessage("command.dust.gave") .processPlaceholder("player", target.getPlayer().getName()) .processPlaceholder("group", group.getIdentifier()) .sendPrefixedMessage(sender); @@ -75,18 +76,22 @@ public class CommandGiveItemDust extends AbstractCommand { if (args.length == 1) { return Bukkit.getOnlinePlayers().stream().map(Player::getName).collect(Collectors.toList()); } else if (args.length == 2) { - return plugin.getGroupManager().getValues().stream() - .map(Group::getIdentifier).collect(Collectors.toList()); + return this.plugin.getGroupManager() + .getValues() + .stream() + .map(Group::getIdentifier) + .collect(Collectors.toList()); } else if (args.length == 3) { List dusts = new ArrayList<>(); - FileConfiguration dustConfig = plugin.getFileManager().getConfiguration("items/dusts"); + FileConfiguration dustConfig = this.plugin.getFileManager().getConfiguration("items/dusts"); dusts.addAll(dustConfig.getConfigurationSection("dusts").getKeys(false)); return dusts; } else if (args.length == 4) { List rates = new ArrayList<>(); - for (int i = 1; i <= 100; i++) + for (int i = 1; i <= 100; i++) { rates.add(String.valueOf(i)); + } return rates; } return null; diff --git a/src/main/java/com/songoda/epicenchants/commands/CommandGiveRandomBook.java b/src/main/java/com/songoda/epicenchants/commands/CommandGiveRandomBook.java index 6d8f4bf..3b92324 100644 --- a/src/main/java/com/songoda/epicenchants/commands/CommandGiveRandomBook.java +++ b/src/main/java/com/songoda/epicenchants/commands/CommandGiveRandomBook.java @@ -16,37 +16,38 @@ public class CommandGiveRandomBook extends AbstractCommand { private final EpicEnchants plugin; public CommandGiveRandomBook(EpicEnchants plugin) { - super(false, "giverandombook"); + super(CommandType.CONSOLE_OK, "giverandombook"); this.plugin = plugin; } //giverandombook @Override protected ReturnType runCommand(CommandSender sender, String... args) { - if (args.length < 2 || args.length > 6) + if (args.length < 2 || args.length > 6) { return ReturnType.SYNTAX_ERROR; + } OfflinePlayer target = Bukkit.getPlayer(args[0]); if (target == null) { - plugin.getLocale().newMessage("&cThis player does not exist...").sendPrefixedMessage(sender); + this.plugin.getLocale().newMessage("&cThis player does not exist...").sendPrefixedMessage(sender); return ReturnType.FAILURE; } - List groups = plugin.getGroupManager().getValues().stream() + List groups = this.plugin.getGroupManager().getValues().stream() .filter(group -> group.getIdentifier().equalsIgnoreCase(args[1])).collect(Collectors.toList()); if (groups.isEmpty()) { - plugin.getLocale().newMessage("&cThe group you entered was no found...").sendPrefixedMessage(sender); + this.plugin.getLocale().newMessage("&cThe group you entered was no found...").sendPrefixedMessage(sender); return ReturnType.FAILURE; } Group group = groups.get(0); - target.getPlayer().getInventory().addItem(plugin.getSpecialItems().getMysteryBook(group)); - plugin.getLocale().getMessage("command.randombook.received") + target.getPlayer().getInventory().addItem(this.plugin.getSpecialItems().getMysteryBook(group)); + this.plugin.getLocale().getMessage("command.randombook.received") .sendPrefixedMessage(target.getPlayer()); - plugin.getLocale().getMessage("command.randombook.gave") + this.plugin.getLocale().getMessage("command.randombook.gave") .processPlaceholder("player", target.getPlayer().getName()) .sendPrefixedMessage(sender); return ReturnType.SUCCESS; @@ -55,10 +56,16 @@ public class CommandGiveRandomBook extends AbstractCommand { @Override protected List onTab(CommandSender sender, String... args) { if (args.length == 1) { - return Bukkit.getOnlinePlayers().stream().map(Player::getName).collect(Collectors.toList()); + return Bukkit.getOnlinePlayers() + .stream() + .map(Player::getName) + .collect(Collectors.toList()); } else if (args.length == 2) { - return plugin.getGroupManager().getValues().stream() - .map(Group::getIdentifier).collect(Collectors.toList()); + return this.plugin.getGroupManager() + .getValues() + .stream() + .map(Group::getIdentifier) + .collect(Collectors.toList()); } return null; } diff --git a/src/main/java/com/songoda/epicenchants/commands/CommandGiveScroll.java b/src/main/java/com/songoda/epicenchants/commands/CommandGiveScroll.java index 6999df2..e9abe38 100644 --- a/src/main/java/com/songoda/epicenchants/commands/CommandGiveScroll.java +++ b/src/main/java/com/songoda/epicenchants/commands/CommandGiveScroll.java @@ -14,25 +14,25 @@ import java.util.List; import java.util.stream.Collectors; public class CommandGiveScroll extends AbstractCommand { - private final EpicEnchants plugin; public CommandGiveScroll(EpicEnchants plugin) { - super(false, "givescroll"); + super(CommandType.CONSOLE_OK, "givescroll"); this.plugin = plugin; } //givescroll [amount] [success-rate] @Override protected ReturnType runCommand(CommandSender sender, String... args) { - if (args.length < 2 || args.length > 5) + if (args.length < 2 || args.length > 5) { return ReturnType.SYNTAX_ERROR; + } String giveType = args[0]; OfflinePlayer target = Bukkit.getPlayer(args[1]); if (target == null) { - plugin.getLocale().newMessage("&cThis player does not exist...").sendPrefixedMessage(sender); + this.plugin.getLocale().newMessage("&cThis player does not exist...").sendPrefixedMessage(sender); return ReturnType.FAILURE; } @@ -40,37 +40,39 @@ public class CommandGiveScroll extends AbstractCommand { int successRate = -1; if (args.length > 2) { - if (!CommandCommons.isInt(args[2], sender)) + if (!CommandCommons.isInt(args[2], sender)) { return ReturnType.FAILURE; + } amount = Integer.parseInt(args[2]); } if (args.length > 3) { - if (!CommandCommons.isInt(args[3], sender)) + if (!CommandCommons.isInt(args[3], sender)) { return ReturnType.FAILURE; + } successRate = Integer.parseInt(args[3]); } String messageKey; switch (giveType.toLowerCase()) { case "whitescroll": - target.getPlayer().getInventory().addItem(plugin.getSpecialItems().getWhiteScroll(amount)); + target.getPlayer().getInventory().addItem(this.plugin.getSpecialItems().getWhiteScroll(amount)); messageKey = "whitescroll"; break; case "blackscroll": messageKey = "blackscroll"; - target.getPlayer().getInventory().addItem(plugin.getSpecialItems().getBlackScroll(amount, successRate)); + target.getPlayer().getInventory().addItem(this.plugin.getSpecialItems().getBlackScroll(amount, successRate)); break; default: - plugin.getLocale().getMessage("command.giveunknown") + this.plugin.getLocale().getMessage("command.giveunknown") .processPlaceholder("unknown", giveType) .sendPrefixedMessage(sender); return ReturnType.FAILURE; } - plugin.getLocale().getMessage("command." + messageKey + ".received") + this.plugin.getLocale().getMessage("command." + messageKey + ".received") .sendPrefixedMessage(target.getPlayer()); - plugin.getLocale().getMessage("command." + messageKey + ".gave") + this.plugin.getLocale().getMessage("command." + messageKey + ".gave") .processPlaceholder("player", target.getName()) .sendPrefixedMessage(sender); return ReturnType.SUCCESS; @@ -81,11 +83,15 @@ public class CommandGiveScroll extends AbstractCommand { if (args.length == 1) { return Arrays.asList("whitescroll", "blackscroll"); } else if (args.length == 2) { - return Bukkit.getOnlinePlayers().stream().map(Player::getName).collect(Collectors.toList()); + return Bukkit.getOnlinePlayers() + .stream() + .map(Player::getName) + .collect(Collectors.toList()); } else if (args.length == 3 || args.length == 4) { List rates = new ArrayList<>(); - for (int i = 1; i <= (args.length == 3 ? 10 : 100); i++) + for (int i = 1; i <= (args.length == 3 ? 10 : 100); i++) { rates.add(String.valueOf(i)); + } return rates; } return null; diff --git a/src/main/java/com/songoda/epicenchants/commands/CommandList.java b/src/main/java/com/songoda/epicenchants/commands/CommandList.java index 80d1d96..5418915 100644 --- a/src/main/java/com/songoda/epicenchants/commands/CommandList.java +++ b/src/main/java/com/songoda/epicenchants/commands/CommandList.java @@ -10,24 +10,23 @@ import java.util.List; import java.util.stream.Collectors; public class CommandList extends AbstractCommand { - private final EpicEnchants plugin; public CommandList(EpicEnchants plugin) { - super(true, "list"); + super(CommandType.PLAYER_ONLY, "list"); this.plugin = plugin; } @Override protected ReturnType runCommand(CommandSender sender, String... args) { if (args.length > 1 && args[1].equalsIgnoreCase("chat")) { - plugin.getLocale().newMessage(plugin.getEnchantManager().getValues().stream() + this.plugin.getLocale().newMessage(this.plugin.getEnchantManager().getValues().stream() .sorted(Comparator.comparing(enchant -> enchant.getGroup().getOrder())) .map(enchant -> enchant.getColoredIdentifier(true)).collect(Collectors.joining("&7, "))) .sendPrefixedMessage(sender); return ReturnType.SUCCESS; } - plugin.getInfoManager().getMainInfoMenu().open((Player) sender); + this.plugin.getInfoManager().getMainInfoMenu().open((Player) sender); return ReturnType.SUCCESS; } diff --git a/src/main/java/com/songoda/epicenchants/commands/CommandReload.java b/src/main/java/com/songoda/epicenchants/commands/CommandReload.java index 2be4542..3b9c02e 100644 --- a/src/main/java/com/songoda/epicenchants/commands/CommandReload.java +++ b/src/main/java/com/songoda/epicenchants/commands/CommandReload.java @@ -7,18 +7,17 @@ import org.bukkit.command.CommandSender; import java.util.List; public class CommandReload extends AbstractCommand { - private final EpicEnchants plugin; public CommandReload(EpicEnchants plugin) { - super(false, "reload"); + super(CommandType.CONSOLE_OK, "reload"); this.plugin = plugin; } @Override protected ReturnType runCommand(CommandSender sender, String... args) { - plugin.reloadConfig(); - plugin.getLocale().getMessage("command.reload").sendPrefixedMessage(sender); + this.plugin.reloadConfig(); + this.plugin.getLocale().getMessage("command.reload").sendPrefixedMessage(sender); return ReturnType.SUCCESS; } diff --git a/src/main/java/com/songoda/epicenchants/commands/CommandSettings.java b/src/main/java/com/songoda/epicenchants/commands/CommandSettings.java index c78c530..df4cacc 100644 --- a/src/main/java/com/songoda/epicenchants/commands/CommandSettings.java +++ b/src/main/java/com/songoda/epicenchants/commands/CommandSettings.java @@ -9,17 +9,16 @@ import org.bukkit.entity.Player; import java.util.List; public class CommandSettings extends AbstractCommand { - private final EpicEnchants plugin; public CommandSettings(EpicEnchants plugin) { - super(true, "Settings"); + super(CommandType.PLAYER_ONLY, "Settings"); this.plugin = plugin; } @Override protected ReturnType runCommand(CommandSender sender, String... args) { - plugin.getGuiManager().showGUI((Player) sender, new PluginConfigGui(plugin)); + this.plugin.getGuiManager().showGUI((Player) sender, new PluginConfigGui(this.plugin)); return ReturnType.SUCCESS; } diff --git a/src/main/java/com/songoda/epicenchants/commands/CommandTinkerer.java b/src/main/java/com/songoda/epicenchants/commands/CommandTinkerer.java index 8ba6a56..e313f87 100644 --- a/src/main/java/com/songoda/epicenchants/commands/CommandTinkerer.java +++ b/src/main/java/com/songoda/epicenchants/commands/CommandTinkerer.java @@ -9,18 +9,17 @@ import org.bukkit.entity.Player; import java.util.List; public class CommandTinkerer extends AbstractCommand { - private final EpicEnchants plugin; public CommandTinkerer(EpicEnchants plugin) { - super(true, "tinkerer"); + super(CommandType.PLAYER_ONLY, "tinkerer"); this.plugin = plugin; } @Override protected ReturnType runCommand(CommandSender sender, String... args) { Player player = (Player) sender; - new TinkererMenu(plugin, plugin.getFileManager().getConfiguration("menus/tinkerer-menu")).open(player); + new TinkererMenu(this.plugin, this.plugin.getFileManager().getConfiguration("menus/tinkerer-menu")).open(player); return ReturnType.SUCCESS; } diff --git a/src/main/java/com/songoda/epicenchants/effect/EffectExecutor.java b/src/main/java/com/songoda/epicenchants/effect/EffectExecutor.java index 2a7fe48..91a040b 100644 --- a/src/main/java/com/songoda/epicenchants/effect/EffectExecutor.java +++ b/src/main/java/com/songoda/epicenchants/effect/EffectExecutor.java @@ -45,15 +45,15 @@ public abstract class EffectExecutor { } public void testAndRun(@NotNull Player user, @Nullable LivingEntity opponent, int level, TriggerType type, Event event, EventType eventType, boolean simul) { - if (!simul && !triggerTypes.contains(type)) { + if (!simul && !this.triggerTypes.contains(type)) { return; } - if (section.isString("chance") && !GeneralUtils.chance(LeveledModifier.of(section.getString("chance")).get(level, 100, user, opponent))) { + if (this.section.isString("chance") && !GeneralUtils.chance(LeveledModifier.of(this.section.getString("chance")).get(level, 100, user, opponent))) { return; } - if (!condition.get(user, opponent, level, event, false)) { + if (!this.condition.get(user, opponent, level, event, false)) { return; } @@ -63,25 +63,31 @@ public abstract class EffectExecutor { execute(user, opponent, level, eventType); } - simultaneous.forEach(e -> e.testAndRun(user, opponent, level, type, event, eventType, true)); + this.simultaneous.forEach(e -> e.testAndRun(user, opponent, level, type, event, eventType, true)); } public abstract void execute(@NotNull Player user, @Nullable LivingEntity opponent, int level, EventType eventType); protected Who who() { - if (section.isString("who")) { - if (section.getString("who").equalsIgnoreCase("user")) return USER; - else if (section.getString("who").equalsIgnoreCase("opponent")) return OPPONENT; + if (this.section.isString("who")) { + if (this.section.getString("who").equalsIgnoreCase("user")) { + return USER; + } + + if (this.section.getString("who").equalsIgnoreCase("opponent")) { + return OPPONENT; + } } + return USER; } public LeveledModifier getAmount() { - return LeveledModifier.of(section.getString("amount")); + return LeveledModifier.of(this.section.getString("amount")); } public void consume(Consumer playerConsumer, Player user, @Nullable LivingEntity opponent) { - if (triggerTypes.contains(TriggerType.HELD_ITEM) || triggerTypes.contains(TriggerType.STATIC_EFFECT)) { + if (this.triggerTypes.contains(TriggerType.HELD_ITEM) || this.triggerTypes.contains(TriggerType.STATIC_EFFECT)) { playerConsumer.accept(user); return; } @@ -91,8 +97,9 @@ public abstract class EffectExecutor { playerConsumer.accept(user); break; case OPPONENT: - if (opponent != null) + if (opponent != null) { playerConsumer.accept(opponent); + } } } diff --git a/src/main/java/com/songoda/epicenchants/effect/EffectManager.java b/src/main/java/com/songoda/epicenchants/effect/EffectManager.java index 875105f..afc312a 100644 --- a/src/main/java/com/songoda/epicenchants/effect/EffectManager.java +++ b/src/main/java/com/songoda/epicenchants/effect/EffectManager.java @@ -4,14 +4,12 @@ import org.bukkit.Bukkit; import org.bukkit.configuration.ConfigurationSection; import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; import java.util.Optional; import static com.google.common.base.CaseFormat.UPPER_CAMEL; import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE; public class EffectManager { - public static Optional getEffect(ConfigurationSection section) { if (section == null) { return Optional.empty(); @@ -23,8 +21,8 @@ public class EffectManager { Constructor constructor = clazz.getConstructor(ConfigurationSection.class); Object object = constructor.newInstance(section); return Optional.of((EffectExecutor) object); - } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException | ClassCastException e) { - e.printStackTrace(); + } catch (ReflectiveOperationException | ClassCastException ex) { + ex.printStackTrace(); Bukkit.getLogger().severe("Invalid effect: " + section.getName()); } diff --git a/src/main/java/com/songoda/epicenchants/effect/effects/CancelEvent.java b/src/main/java/com/songoda/epicenchants/effect/effects/CancelEvent.java index a1dee92..d78d729 100644 --- a/src/main/java/com/songoda/epicenchants/effect/effects/CancelEvent.java +++ b/src/main/java/com/songoda/epicenchants/effect/effects/CancelEvent.java @@ -14,7 +14,7 @@ public class CancelEvent extends EffectEventExecutor { } @Override - public void execute(Player player, LivingEntity opponent, int level, Event event, EventType eventType) { + public void execute(Player user, LivingEntity opponent, int level, Event event, EventType eventType) { if (event instanceof Cancellable) { ((Cancellable) event).setCancelled(true); } diff --git a/src/main/java/com/songoda/epicenchants/effect/effects/ConsoleCommand.java b/src/main/java/com/songoda/epicenchants/effect/effects/ConsoleCommand.java index cd2e6a1..7980703 100644 --- a/src/main/java/com/songoda/epicenchants/effect/effects/ConsoleCommand.java +++ b/src/main/java/com/songoda/epicenchants/effect/effects/ConsoleCommand.java @@ -17,7 +17,8 @@ public class ConsoleCommand extends EffectExecutor { @Override public void execute(@NotNull Player user, LivingEntity opponent, int level, EventType eventType) { - GeneralUtils.getString(getSection(), "command").stream() + GeneralUtils.getString(getSection(), "command") + .stream() .map(s -> Placeholders.setPlaceholders(s, user, opponent, level)) .forEach(s -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), s)); } diff --git a/src/main/java/com/songoda/epicenchants/effect/effects/DropHeld.java b/src/main/java/com/songoda/epicenchants/effect/effects/DropHeld.java index 8144ca3..6c5d3aa 100644 --- a/src/main/java/com/songoda/epicenchants/effect/effects/DropHeld.java +++ b/src/main/java/com/songoda/epicenchants/effect/effects/DropHeld.java @@ -20,8 +20,7 @@ public class DropHeld extends EffectExecutor { consume(entity -> { Player player = ((Player) entity); if (player.getItemInHand().getType() != Material.AIR) { - entity.getLocation().getWorld().dropItemNaturally(entity.getLocation(), new ItemBuilder(player - .getItemInHand()).build()); + entity.getLocation().getWorld().dropItemNaturally(entity.getLocation(), new ItemBuilder(player.getItemInHand()).build()); player.setItemInHand(null); } }, user, opponent); diff --git a/src/main/java/com/songoda/epicenchants/effect/effects/DropItem.java b/src/main/java/com/songoda/epicenchants/effect/effects/DropItem.java index 1de7e31..f087337 100644 --- a/src/main/java/com/songoda/epicenchants/effect/effects/DropItem.java +++ b/src/main/java/com/songoda/epicenchants/effect/effects/DropItem.java @@ -16,7 +16,6 @@ public class DropItem extends EffectExecutor { @Override public void execute(@NotNull Player user, @Nullable LivingEntity opponent, int level, EventType eventType) { - consume(entity -> entity.getLocation().getWorld().dropItemNaturally(entity.getLocation(), - new ItemBuilder(getSection(), ((Player) entity)).build()), user, opponent); + consume(entity -> entity.getLocation().getWorld().dropItemNaturally(entity.getLocation(), new ItemBuilder(getSection(), ((Player) entity)).build()), user, opponent); } } diff --git a/src/main/java/com/songoda/epicenchants/effect/effects/Message.java b/src/main/java/com/songoda/epicenchants/effect/effects/Message.java index 42122bf..38467d4 100644 --- a/src/main/java/com/songoda/epicenchants/effect/effects/Message.java +++ b/src/main/java/com/songoda/epicenchants/effect/effects/Message.java @@ -17,7 +17,8 @@ public class Message extends EffectExecutor { @Override public void execute(@NotNull Player user, LivingEntity opponent, int level, EventType eventType) { if (eventType == EventType.ON || eventType == EventType.NONE) { - consume(entity -> GeneralUtils.getString(getSection(), "message").stream() + consume(entity -> GeneralUtils.getString(getSection(), "message") + .stream() .map(s -> Placeholders.setPlaceholders(s, user, opponent, level)) .forEach(entity::sendMessage), user, opponent); } diff --git a/src/main/java/com/songoda/epicenchants/effect/effects/ModifyBlock.java b/src/main/java/com/songoda/epicenchants/effect/effects/ModifyBlock.java index 7e0f31c..695536f 100644 --- a/src/main/java/com/songoda/epicenchants/effect/effects/ModifyBlock.java +++ b/src/main/java/com/songoda/epicenchants/effect/effects/ModifyBlock.java @@ -28,7 +28,6 @@ public class ModifyBlock extends EffectEventExecutor { block.breakNaturally(); return; } - block.setType(Material.getMaterial(getSection().getString("material"))); } } diff --git a/src/main/java/com/songoda/epicenchants/effect/effects/MoreDrops.java b/src/main/java/com/songoda/epicenchants/effect/effects/MoreDrops.java index f8e6a00..6ab29c7 100644 --- a/src/main/java/com/songoda/epicenchants/effect/effects/MoreDrops.java +++ b/src/main/java/com/songoda/epicenchants/effect/effects/MoreDrops.java @@ -26,7 +26,8 @@ public class MoreDrops extends EffectEventExecutor { EntityDeathEvent deathEvent = (EntityDeathEvent) event; LeveledModifier modifier = getAmount(); - List newDrops = deathEvent.getDrops().stream() + List newDrops = deathEvent.getDrops() + .stream() .peek(itemStack -> itemStack.setAmount(((int) (itemStack.getAmount() * modifier.get(level, 1, user, opponent))))) .collect(Collectors.toList()); diff --git a/src/main/java/com/songoda/epicenchants/effect/effects/PlayerCommand.java b/src/main/java/com/songoda/epicenchants/effect/effects/PlayerCommand.java index 219ec0b..6d6de1f 100644 --- a/src/main/java/com/songoda/epicenchants/effect/effects/PlayerCommand.java +++ b/src/main/java/com/songoda/epicenchants/effect/effects/PlayerCommand.java @@ -28,7 +28,8 @@ public class PlayerCommand extends EffectExecutor { return; } - consume(entity -> GeneralUtils.getString(getSection(), "message").stream() + consume(entity -> GeneralUtils.getString(getSection(), "message") + .stream() .map(s -> Placeholders.setPlaceholders(s, user, opponent, level)) .forEach(((Player) entity)::performCommand), user, opponent); } diff --git a/src/main/java/com/songoda/epicenchants/effect/effects/Potion.java b/src/main/java/com/songoda/epicenchants/effect/effects/Potion.java index ffe7d5e..cccc78f 100644 --- a/src/main/java/com/songoda/epicenchants/effect/effects/Potion.java +++ b/src/main/java/com/songoda/epicenchants/effect/effects/Potion.java @@ -31,17 +31,24 @@ public class Potion extends EffectExecutor { if (getTriggerTypes().contains(TriggerType.STATIC_EFFECT) || getTriggerTypes().contains(TriggerType.HELD_ITEM)) { if (eventType == EventType.ON) { - consume(entity -> entity.addPotionEffect(new PotionEffect(effectType, Integer.MAX_VALUE, (int) amplifier.get(level - 1, 0, user, opponent), - false, false)), user, opponent); + consume(entity -> entity.addPotionEffect(new PotionEffect(effectType, Integer.MAX_VALUE, (int) amplifier.get(level - 1, 0, user, opponent), false, false)), user, opponent); } else if (eventType == EventType.OFF) { consume(entity -> entity.removePotionEffect(effectType), user, opponent); } + return; } LeveledModifier duration = LeveledModifier.of(getSection().getString("duration")); - consume(entity -> entity.addPotionEffect(new PotionEffect(effectType, (int) duration.get(level, 60, user, opponent) * 20, - (int) amplifier.get(level - 1, 0, user, opponent), false, false)), user, opponent); + consume( + entity -> entity.addPotionEffect(new PotionEffect(effectType, + (int) duration.get(level, 60, user, opponent) * 20, + (int) amplifier.get(level - 1, 0, user, opponent), + false, + false)), + user, + opponent + ); } } diff --git a/src/main/java/com/songoda/epicenchants/effect/effects/Repair.java b/src/main/java/com/songoda/epicenchants/effect/effects/Repair.java index cbd9de0..f87d287 100644 --- a/src/main/java/com/songoda/epicenchants/effect/effects/Repair.java +++ b/src/main/java/com/songoda/epicenchants/effect/effects/Repair.java @@ -15,8 +15,9 @@ public class Repair extends EffectExecutor { @Override public void execute(@NotNull Player user, LivingEntity opponent, int level, EventType eventType) { consume(livingEntity -> { - if (livingEntity instanceof Player) + if (livingEntity instanceof Player) { ((Player) livingEntity).getItemInHand().setDurability((short) 0); + } }, user, opponent); } } diff --git a/src/main/java/com/songoda/epicenchants/effect/effects/SpawnMob.java b/src/main/java/com/songoda/epicenchants/effect/effects/SpawnMob.java index 1d973ff..35b8157 100644 --- a/src/main/java/com/songoda/epicenchants/effect/effects/SpawnMob.java +++ b/src/main/java/com/songoda/epicenchants/effect/effects/SpawnMob.java @@ -19,37 +19,41 @@ import static com.songoda.epicenchants.utils.single.GeneralUtils.color; import static java.util.concurrent.ThreadLocalRandom.current; public class SpawnMob extends EffectExecutor { - private LeveledModifier attackDamage; - private String displayName; - private EntityType entityType; - private LeveledModifier equipmentDropChance; - private LeveledModifier health; - private ItemBuilder helmet, chestPlate, leggings, boots, handItem; - private boolean hostile; - private LeveledModifier amount; + private final LeveledModifier attackDamage; + private final String displayName; + private final EntityType entityType; + private final LeveledModifier equipmentDropChance; + private final LeveledModifier health; + private final ItemBuilder helmet; + private final ItemBuilder chestPlate; + private final ItemBuilder leggings; + private final ItemBuilder boots; + private final ItemBuilder handItem; + private final boolean hostile; + private final LeveledModifier amount; public SpawnMob(ConfigurationSection section) { super(section); - entityType = EntityType.valueOf(section.getString("mob-type")); - amount = of(section.getString("amount")); - health = of(section.getString("health")); - attackDamage = of(section.getString("attack-damage")); - equipmentDropChance = LeveledModifier.of(section.getString("equipment-drop-chance")); - hostile = section.getBoolean("hostile", false); - displayName = section.isString("display-name") ? color(section.getString("display-name")) : ""; - helmet = section.isConfigurationSection("equipment.helmet") ? new ItemBuilder(section.getConfigurationSection("equipment.helmet")) : null; - chestPlate = section.isConfigurationSection("equipment.chestplate") ? new ItemBuilder(section.getConfigurationSection("equipment.chestplate")) : null; - leggings = section.isConfigurationSection("equipment.leggings") ? new ItemBuilder(section.getConfigurationSection("equipment.leggings")) : null; - boots = section.isConfigurationSection("equipment.boots") ? new ItemBuilder(section.getConfigurationSection("equipment.boots")) : null; - handItem = section.isConfigurationSection("equipment.hand-item") ? new ItemBuilder(section.getConfigurationSection("equipment.hand-item")) : null; + this.entityType = EntityType.valueOf(section.getString("mob-type")); + this.amount = of(section.getString("amount")); + this.health = of(section.getString("health")); + this.attackDamage = of(section.getString("attack-damage")); + this.equipmentDropChance = LeveledModifier.of(section.getString("equipment-drop-chance")); + this.hostile = section.getBoolean("hostile", false); + this.displayName = section.isString("display-name") ? color(section.getString("display-name")) : ""; + this.helmet = section.isConfigurationSection("equipment.helmet") ? new ItemBuilder(section.getConfigurationSection("equipment.helmet")) : null; + this.chestPlate = section.isConfigurationSection("equipment.chestplate") ? new ItemBuilder(section.getConfigurationSection("equipment.chestplate")) : null; + this.leggings = section.isConfigurationSection("equipment.leggings") ? new ItemBuilder(section.getConfigurationSection("equipment.leggings")) : null; + this.boots = section.isConfigurationSection("equipment.boots") ? new ItemBuilder(section.getConfigurationSection("equipment.boots")) : null; + this.handItem = section.isConfigurationSection("equipment.hand-item") ? new ItemBuilder(section.getConfigurationSection("equipment.hand-item")) : null; } @Override public void execute(@NotNull Player user, @Nullable LivingEntity opponent, int level, EventType eventType) { Location location = user.getLocation(); - for (int i = 0; i < amount.get(level, 1, user, opponent); i++) { + for (int i = 0; i < this.amount.get(level, 1, user, opponent); i++) { Location spawnLocation = location.clone().add(current().nextInt(-3, 3), 0, current().nextInt(-3, 3)); int y = location.getWorld().getHighestBlockAt(spawnLocation).getY(); @@ -57,34 +61,40 @@ public class SpawnMob extends EffectExecutor { continue; } - Entity entity = location.getWorld().spawnEntity(spawnLocation, entityType); + Entity entity = location.getWorld().spawnEntity(spawnLocation, this.entityType); - entity.setCustomName(displayName.replace("{level}", "" + level)); + entity.setCustomName(this.displayName.replace("{level}", "" + level)); entity.setCustomNameVisible(true); if (entity instanceof LivingEntity) { LivingEntity livingEntity = (LivingEntity) entity; livingEntity.setRemoveWhenFarAway(true); - int dropChance = (int) equipmentDropChance.get(level, 0, user, opponent); + int dropChance = (int) this.equipmentDropChance.get(level, 0, user, opponent); - if (helmet != null) - livingEntity.getEquipment().setHelmet(helmet.buildWithWrappers(level, user, opponent)); - if (chestPlate != null) - livingEntity.getEquipment().setChestplate(chestPlate.buildWithWrappers(level, user, opponent)); - if (leggings != null) - livingEntity.getEquipment().setLeggings(leggings.buildWithWrappers(level, user, opponent)); - if (boots != null) livingEntity.getEquipment().setBoots(boots.buildWithWrappers(level, user, opponent)); + if (this.helmet != null) { + livingEntity.getEquipment().setHelmet(this.helmet.buildWithWrappers(level, user, opponent)); + } + if (this.chestPlate != null) { + livingEntity.getEquipment().setChestplate(this.chestPlate.buildWithWrappers(level, user, opponent)); + } + if (this.leggings != null) { + livingEntity.getEquipment().setLeggings(this.leggings.buildWithWrappers(level, user, opponent)); + } + if (this.boots != null) { + livingEntity.getEquipment().setBoots(this.boots.buildWithWrappers(level, user, opponent)); + } livingEntity.getEquipment().setHelmetDropChance(dropChance); livingEntity.getEquipment().setLeggingsDropChance(dropChance); livingEntity.getEquipment().setHelmetDropChance(dropChance); livingEntity.getEquipment().setChestplateDropChance(dropChance); - if (handItem != null) - livingEntity.getEquipment().setItemInHand(handItem.buildWithWrappers(level, user, opponent)); + if (this.handItem != null) { + livingEntity.getEquipment().setItemInHand(this.handItem.buildWithWrappers(level, user, opponent)); + } livingEntity.getEquipment().setItemInHandDropChance(dropChance); } - if (hostile && entity instanceof Monster && opponent != null) { + if (this.hostile && entity instanceof Monster && opponent != null) { ((Monster) entity).setTarget(opponent); } @@ -95,7 +105,7 @@ public class SpawnMob extends EffectExecutor { // attack.setBaseValue(attackDamage.get(level, (int) Math.round(attack.getBaseValue()), user, opponent)); double maxHealth = livingEntity.getMaxHealth(); - livingEntity.setMaxHealth(health.get(level, (int) Math.round(maxHealth), user, opponent)); + livingEntity.setMaxHealth(this.health.get(level, (int) Math.round(maxHealth), user, opponent)); } } } diff --git a/src/main/java/com/songoda/epicenchants/effect/effects/StealFood.java b/src/main/java/com/songoda/epicenchants/effect/effects/StealFood.java index 1fa08cf..a3b590f 100644 --- a/src/main/java/com/songoda/epicenchants/effect/effects/StealFood.java +++ b/src/main/java/com/songoda/epicenchants/effect/effects/StealFood.java @@ -27,10 +27,14 @@ public class StealFood extends EffectExecutor { if (opponentFood <= 0) { opponentPlayer.setFoodLevel(0); - } else opponentPlayer.setFoodLevel(Math.min(opponentFood, 20)); + } else { + opponentPlayer.setFoodLevel(Math.min(opponentFood, 20)); + } if (userFood <= 0) { user.setFoodLevel(0); - } else user.setFoodLevel(Math.min(userFood, 20)); + } else { + user.setFoodLevel(Math.min(userFood, 20)); + } } } diff --git a/src/main/java/com/songoda/epicenchants/events/ArmorEquipEvent.java b/src/main/java/com/songoda/epicenchants/events/ArmorEquipEvent.java index bf5d9fb..3aa585e 100644 --- a/src/main/java/com/songoda/epicenchants/events/ArmorEquipEvent.java +++ b/src/main/java/com/songoda/epicenchants/events/ArmorEquipEvent.java @@ -8,8 +8,8 @@ import org.bukkit.event.player.PlayerEvent; import org.bukkit.inventory.ItemStack; public final class ArmorEquipEvent extends PlayerEvent implements Cancellable { + private static final HandlerList HANDLERS = new HandlerList(); - private static final HandlerList handlers = new HandlerList(); private boolean cancel = false; private final EquipMethod equipType; private final ArmorType type; @@ -18,36 +18,27 @@ public final class ArmorEquipEvent extends PlayerEvent implements Cancellable { /** * Constructor for the ArmorEquipEvent. * - * @param player The player who put on / removed the armor. + * @param who The player who put on / removed the armor. * @param type The ArmorType of the armor added * @param oldArmorPiece The ItemStack of the armor removed. * @param newArmorPiece The ItemStack of the armor added. */ - public ArmorEquipEvent(final Player player, final EquipMethod equipType, final ArmorType type, final ItemStack oldArmorPiece, final ItemStack newArmorPiece) { - super(player); + public ArmorEquipEvent(final Player who, final EquipMethod equipType, final ArmorType type, final ItemStack oldArmorPiece, final ItemStack newArmorPiece) { + super(who); this.equipType = equipType; this.type = type; this.oldArmorPiece = oldArmorPiece; this.newArmorPiece = newArmorPiece; } - /** - * Gets a list of handlers handling this event. - * - * @return A list of handlers handling this event. - */ - public static HandlerList getHandlerList() { - return handlers; - } - /** * Gets a list of handlers handling this event. * * @return A list of handlers handling this event. */ @Override - public final HandlerList getHandlers() { - return handlers; + public HandlerList getHandlers() { + return HANDLERS; } /** @@ -55,7 +46,7 @@ public final class ArmorEquipEvent extends PlayerEvent implements Cancellable { * * @param cancel If this event should be cancelled. */ - public final void setCancelled(final boolean cancel) { + public void setCancelled(final boolean cancel) { this.cancel = cancel; } @@ -64,33 +55,33 @@ public final class ArmorEquipEvent extends PlayerEvent implements Cancellable { * * @return If this event is cancelled */ - public final boolean isCancelled() { - return cancel; + public boolean isCancelled() { + return this.cancel; } - public final ArmorType getType() { - return type; + public ArmorType getType() { + return this.type; } /** * Returns the last equipped armor piece, could be a piece of armor, {@link Material#AIR}, or null. */ - public final ItemStack getOldArmorPiece() { - return oldArmorPiece; + public ItemStack getOldArmorPiece() { + return this.oldArmorPiece; } - public final void setOldArmorPiece(final ItemStack oldArmorPiece) { + public void setOldArmorPiece(final ItemStack oldArmorPiece) { this.oldArmorPiece = oldArmorPiece; } /** * Returns the newly equipped armor, could be a piece of armor, {@link Material#AIR}, or null. */ - public final ItemStack getNewArmorPiece() { - return newArmorPiece; + public ItemStack getNewArmorPiece() { + return this.newArmorPiece; } - public final void setNewArmorPiece(final ItemStack newArmorPiece) { + public void setNewArmorPiece(final ItemStack newArmorPiece) { this.newArmorPiece = newArmorPiece; } @@ -98,12 +89,21 @@ public final class ArmorEquipEvent extends PlayerEvent implements Cancellable { * Gets the method used to either equip or unequip an armor piece. */ public EquipMethod getMethod() { - return equipType; + return this.equipType; + } + + /** + * Gets a list of handlers handling this event. + * + * @return A list of handlers handling this event. + */ + public static HandlerList getHandlerList() { + return HANDLERS; } public enum EquipMethod {// These have got to be the worst documentations ever. /** - * When you shift click an armor piece to equip or unequip + * When you shift-click an armor piece to equip or unequip */ SHIFT_CLICK, /** @@ -115,7 +115,7 @@ public final class ArmorEquipEvent extends PlayerEvent implements Cancellable { */ PICK_DROP, /** - * When you right click an armor piece in the hotbar without the inventory open to equip. + * When you right-click an armor piece in the hotbar without the inventory open to equip. */ HOTBAR, /** @@ -123,18 +123,17 @@ public final class ArmorEquipEvent extends PlayerEvent implements Cancellable { */ HOTBAR_SWAP, /** - * When in range of a dispenser that shoots an armor piece to equip. + * When in range of a dispenser that shoots an armor piece to equip */ DISPENSER, /** - * When an armor piece is removed due to it losing all durability. + * When an armor piece is removed due to it losing all durability */ BROKE, /** * When you die causing all armor to unequip */ DEATH, - ; } public enum ArmorType { @@ -154,17 +153,26 @@ public final class ArmorEquipEvent extends PlayerEvent implements Cancellable { * @return The parsed ArmorType. (null if none were found.) */ public static ArmorType matchType(final ItemStack itemStack) { - if (itemStack == null || itemStack.getType().equals(Material.AIR)) return null; + if (itemStack == null || itemStack.getType() == Material.AIR) { + return null; + } + String type = itemStack.getType().name(); - if (type.endsWith("_HELMET") || type.endsWith("_SKULL")) return HELMET; - else if (type.endsWith("_CHESTPLATE") || type.equals("ELYTRA")) return CHESTPLATE; - else if (type.endsWith("_LEGGINGS")) return LEGGINGS; - else if (type.endsWith("_BOOTS")) return BOOTS; - else return null; + if (type.endsWith("_HELMET") || type.endsWith("_SKULL")) { + return HELMET; + } else if (type.endsWith("_CHESTPLATE") || type.equals("ELYTRA")) { + return CHESTPLATE; + } else if (type.endsWith("_LEGGINGS")) { + return LEGGINGS; + } else if (type.endsWith("_BOOTS")) { + return BOOTS; + } else { + return null; + } } public int getSlot() { - return slot; + return this.slot; } } } diff --git a/src/main/java/com/songoda/epicenchants/events/EnchantApplyEvent.java b/src/main/java/com/songoda/epicenchants/events/EnchantApplyEvent.java index 94ffe3a..469ecfc 100644 --- a/src/main/java/com/songoda/epicenchants/events/EnchantApplyEvent.java +++ b/src/main/java/com/songoda/epicenchants/events/EnchantApplyEvent.java @@ -7,7 +7,8 @@ import org.bukkit.event.HandlerList; import org.bukkit.inventory.ItemStack; public class EnchantApplyEvent extends Event implements Cancellable { - private static final HandlerList handlers = new HandlerList(); + private static final HandlerList HANDLERS = new HandlerList(); + private final ItemStack toEnchant; private final Enchant enchant; private final int level; @@ -23,23 +24,19 @@ public class EnchantApplyEvent extends Event implements Cancellable { this.destroyRate = destroyRate; } - public static HandlerList getHandlerList() { - return handlers; - } - @Override public boolean isCancelled() { - return cancelled; + return this.cancelled; } @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; + public void setCancelled(boolean cancel) { + this.cancelled = cancel; } @Override public HandlerList getHandlers() { - return handlers; + return HANDLERS; } public ItemStack getToEnchant() { @@ -61,4 +58,8 @@ public class EnchantApplyEvent extends Event implements Cancellable { public int getDestroyRate() { return this.destroyRate; } + + public static HandlerList getHandlerList() { + return HANDLERS; + } } diff --git a/src/main/java/com/songoda/epicenchants/events/HeldItemChangedEvent.java b/src/main/java/com/songoda/epicenchants/events/HeldItemChangedEvent.java index 3b48809..cb43011 100644 --- a/src/main/java/com/songoda/epicenchants/events/HeldItemChangedEvent.java +++ b/src/main/java/com/songoda/epicenchants/events/HeldItemChangedEvent.java @@ -8,8 +8,8 @@ import org.bukkit.event.player.PlayerEvent; import org.bukkit.inventory.ItemStack; public final class HeldItemChangedEvent extends PlayerEvent implements Cancellable { + private static final HandlerList HANDLERS = new HandlerList(); - private static final HandlerList handlers = new HandlerList(); private boolean cancel = false; private final EquipMethod equipType; private final ItemStack oldItem, newItem; @@ -17,47 +17,38 @@ public final class HeldItemChangedEvent extends PlayerEvent implements Cancellab /** * Constructor for the HeldItemChangedEvent. * - * @param player The player who put (un)equipped an item. + * @param who The player who put (un)equipped an item. * @param oldItem The ItemStack removed. * @param newItem The ItemStack added. */ - public HeldItemChangedEvent(final Player player, final EquipMethod equipType, final ItemStack oldItem, final ItemStack newItem) { - super(player); + public HeldItemChangedEvent(final Player who, final EquipMethod equipType, final ItemStack oldItem, final ItemStack newItem) { + super(who); this.equipType = equipType; this.oldItem = oldItem; this.newItem = newItem; } /** - * Gets a list of handlers handling this event. + * Gets a list of handlers handling this event * - * @return A list of handlers handling this event. - */ - public static HandlerList getHandlerList() { - return handlers; - } - - /** - * Gets a list of handlers handling this event. - * - * @return A list of handlers handling this event. + * @return A list of handlers handling this event */ @Override public final HandlerList getHandlers() { - return handlers; + return HANDLERS; } /** - * Sets if this event should be cancelled. + * Sets if this event should be cancelled * - * @param cancel If this event should be cancelled. + * @param cancel If this event should be cancelled */ public final void setCancelled(final boolean cancel) { this.cancel = cancel; } /** - * Gets if this event is cancelled. + * Gets if this event is cancelled * * @return If this event is cancelled */ @@ -86,9 +77,18 @@ public final class HeldItemChangedEvent extends PlayerEvent implements Cancellab return equipType; } + /** + * Gets a list of handlers handling this event. + * + * @return A list of handlers handling this event. + */ + public static HandlerList getHandlerList() { + return HANDLERS; + } + public enum EquipMethod {// These have got to be the worst documentations ever. /** - * When you shift click an armor piece to equip or unequip + * When you shift-click an armor piece to equip or unequip */ SHIFT_CLICK, /** @@ -108,7 +108,7 @@ public final class HeldItemChangedEvent extends PlayerEvent implements Cancellab */ OFFHAND_SWAP, /** - * When an item, e.g. tool, is removed due to it losing all durability. + * When an item, e.g., tool, is removed due to it losing all durability */ BROKE, /** diff --git a/src/main/java/com/songoda/epicenchants/listeners/ArmorListener.java b/src/main/java/com/songoda/epicenchants/listeners/ArmorListener.java index 9d9faef..b21875b 100644 --- a/src/main/java/com/songoda/epicenchants/listeners/ArmorListener.java +++ b/src/main/java/com/songoda/epicenchants/listeners/ArmorListener.java @@ -24,7 +24,6 @@ import org.bukkit.inventory.ItemStack; import static org.bukkit.event.EventPriority.HIGHEST; public class ArmorListener implements Listener { - @EventHandler(ignoreCancelled = true) public final void onInventoryClick(final InventoryClickEvent e) { boolean shift = false, numberKey = false; @@ -194,9 +193,9 @@ public class ArmorListener implements Listener { @EventHandler public void playerDeathEvent(PlayerDeathEvent event) { - for (ItemStack i : event.getEntity().getInventory().getArmorContents()) { - if (!isAirOrNull(i)) { - Bukkit.getServer().getPluginManager().callEvent(new ArmorEquipEvent(event.getEntity(), EquipMethod.DEATH, ArmorType.matchType(i), i, null)); + for (ItemStack item : event.getEntity().getInventory().getArmorContents()) { + if (!isAirOrNull(item)) { + Bukkit.getServer().getPluginManager().callEvent(new ArmorEquipEvent(event.getEntity(), EquipMethod.DEATH, ArmorType.matchType(item), item, null)); // No way to cancel a death event. } } diff --git a/src/main/java/com/songoda/epicenchants/listeners/EntityListener.java b/src/main/java/com/songoda/epicenchants/listeners/EntityListener.java index 6734ec9..1d70460 100644 --- a/src/main/java/com/songoda/epicenchants/listeners/EntityListener.java +++ b/src/main/java/com/songoda/epicenchants/listeners/EntityListener.java @@ -1,6 +1,6 @@ package com.songoda.epicenchants.listeners; -import com.craftaro.core.nms.NmsManager; +import com.craftaro.core.nms.Nms; import com.songoda.epicenchants.EpicEnchants; import com.songoda.epicenchants.enums.TriggerType; import org.bukkit.entity.LivingEntity; @@ -17,20 +17,7 @@ import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityTargetLivingEntityEvent; import org.bukkit.projectiles.ProjectileSource; -import static com.songoda.epicenchants.enums.TriggerType.ATTACK_MOB_MELEE; -import static com.songoda.epicenchants.enums.TriggerType.ATTACK_MOB_RANGE; -import static com.songoda.epicenchants.enums.TriggerType.ATTACK_PLAYER_MELEE; -import static com.songoda.epicenchants.enums.TriggerType.ATTACK_PLAYER_RANGE; -import static com.songoda.epicenchants.enums.TriggerType.DEFENSE_MOB_MELEE; -import static com.songoda.epicenchants.enums.TriggerType.DEFENSE_MOB_RANGE; -import static com.songoda.epicenchants.enums.TriggerType.DEFENSE_PLAYER_MELEE; -import static com.songoda.epicenchants.enums.TriggerType.DEFENSE_PLAYER_RANGE; -import static com.songoda.epicenchants.enums.TriggerType.EXPLOSION_DAMAGE; -import static com.songoda.epicenchants.enums.TriggerType.FALL_DAMAGE; -import static com.songoda.epicenchants.enums.TriggerType.FIRE_DAMAGE; -import static com.songoda.epicenchants.enums.TriggerType.KILLED_MOB; -import static com.songoda.epicenchants.enums.TriggerType.LAVA_DAMAGE; -import static com.songoda.epicenchants.enums.TriggerType.POISON_DAMAGE; +import static com.songoda.epicenchants.enums.TriggerType.*; public class EntityListener implements Listener { private final EpicEnchants instance; @@ -42,7 +29,7 @@ public class EntityListener implements Listener { @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) public void onEntityDeath(EntityDeathEvent event) { if (event.getEntity() instanceof Monster && event.getEntity().getKiller() != null) { - instance.getEnchantUtils().handlePlayer(event.getEntity().getKiller(), event.getEntity(), event, KILLED_MOB); + this.instance.getEnchantUtils().handlePlayer(event.getEntity().getKiller(), event.getEntity(), event, KILLED_MOB); } } @@ -61,12 +48,12 @@ public class EntityListener implements Listener { if (hitEntity instanceof Player) { LivingEntity opponent = source instanceof LivingEntity ? ((LivingEntity) source) : null; TriggerType type = source instanceof Player ? DEFENSE_PLAYER_RANGE : DEFENSE_MOB_RANGE; - instance.getEnchantUtils().handlePlayer(((Player) hitEntity), opponent, event, type); + this.instance.getEnchantUtils().handlePlayer(((Player) hitEntity), opponent, event, type); } if (source instanceof Player) { TriggerType type = event.getEntity() instanceof Player ? ATTACK_PLAYER_RANGE : ATTACK_MOB_RANGE; - instance.getEnchantUtils().handlePlayer(((Player) source), hitEntity, event, type); + this.instance.getEnchantUtils().handlePlayer(((Player) source), hitEntity, event, type); } } @@ -85,7 +72,7 @@ public class EntityListener implements Listener { } if (triggerType != null) { - instance.getEnchantUtils().handlePlayer(defender, opponent, event, triggerType); + this.instance.getEnchantUtils().handlePlayer(defender, opponent, event, triggerType); } } @@ -101,7 +88,7 @@ public class EntityListener implements Listener { } if (triggerType != null) { - instance.getEnchantUtils().handlePlayer(attacker, ((LivingEntity) event.getEntity()), event, triggerType); + this.instance.getEnchantUtils().handlePlayer(attacker, ((LivingEntity) event.getEntity()), event, triggerType); } } } @@ -113,31 +100,32 @@ public class EntityListener implements Listener { } switch (event.getCause()) { case FALL: - instance.getEnchantUtils().handlePlayer(((Player) event.getEntity()), null, event, FALL_DAMAGE); + this.instance.getEnchantUtils().handlePlayer(((Player) event.getEntity()), null, event, FALL_DAMAGE); break; case FIRE: case FIRE_TICK: - instance.getEnchantUtils().handlePlayer(((Player) event.getEntity()), null, event, FIRE_DAMAGE); + this.instance.getEnchantUtils().handlePlayer(((Player) event.getEntity()), null, event, FIRE_DAMAGE); break; case LAVA: - instance.getEnchantUtils().handlePlayer(((Player) event.getEntity()), null, event, LAVA_DAMAGE); + this.instance.getEnchantUtils().handlePlayer(((Player) event.getEntity()), null, event, LAVA_DAMAGE); break; case BLOCK_EXPLOSION: case ENTITY_EXPLOSION: - instance.getEnchantUtils().handlePlayer(((Player) event.getEntity()), null, event, EXPLOSION_DAMAGE); + this.instance.getEnchantUtils().handlePlayer(((Player) event.getEntity()), null, event, EXPLOSION_DAMAGE); break; case POISON: - instance.getEnchantUtils().handlePlayer(((Player) event.getEntity()), null, event, POISON_DAMAGE); + this.instance.getEnchantUtils().handlePlayer(((Player) event.getEntity()), null, event, POISON_DAMAGE); break; } } @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) public void onEntityTargetLivingEntity(EntityTargetLivingEntityEvent event) { - if (event.getTarget() == null) + if (event.getTarget() == null) { return; + } - if (NmsManager.getNbt().of(event.getEntity()).has(event.getTarget().getUniqueId().toString())) { + if (Nms.getImplementations().getNbt().of(event.getEntity()).has(event.getTarget().getUniqueId().toString())) { //TODO: Add team support. event.setCancelled(true); } diff --git a/src/main/java/com/songoda/epicenchants/listeners/HeldItemListener.java b/src/main/java/com/songoda/epicenchants/listeners/HeldItemListener.java index 834d61b..facbce8 100644 --- a/src/main/java/com/songoda/epicenchants/listeners/HeldItemListener.java +++ b/src/main/java/com/songoda/epicenchants/listeners/HeldItemListener.java @@ -28,7 +28,6 @@ import java.util.OptionalInt; import java.util.stream.IntStream; public class HeldItemListener implements Listener { - private static final boolean SWAP_OFFHAND_SUPPORTED = Arrays.stream(ClickType.values()).anyMatch(e -> e.name().equals("SWAP_OFFHAND")); @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) @@ -190,8 +189,9 @@ public class HeldItemListener implements Listener { @EventHandler public void playerDeathEvent(PlayerDeathEvent event) { ItemStack i = event.getEntity().getInventory().getItem(event.getEntity().getInventory().getHeldItemSlot()); - if (!isAirOrNull(i)) + if (!isAirOrNull(i)) { Bukkit.getServer().getPluginManager().callEvent(new HeldItemChangedEvent(event.getEntity(), EquipMethod.DEATH, i, null)); + } // No way to cancel a death event. } diff --git a/src/main/java/com/songoda/epicenchants/listeners/PlayerListener.java b/src/main/java/com/songoda/epicenchants/listeners/PlayerListener.java index 4bab2c2..893acd5 100644 --- a/src/main/java/com/songoda/epicenchants/listeners/PlayerListener.java +++ b/src/main/java/com/songoda/epicenchants/listeners/PlayerListener.java @@ -32,8 +32,8 @@ public class PlayerListener implements Listener { @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) public void onArmorEquip(ArmorEquipEvent event) { - Map oldArmorMap = instance.getEnchantUtils().getEnchants(event.getOldArmorPiece()); - Map newArmorMap = instance.getEnchantUtils().getEnchants(event.getNewArmorPiece()); + Map oldArmorMap = this.instance.getEnchantUtils().getEnchants(event.getOldArmorPiece()); + Map newArmorMap = this.instance.getEnchantUtils().getEnchants(event.getNewArmorPiece()); oldArmorMap.forEach((enchant, level) -> enchant.onAction(event.getPlayer(), null, event, level, STATIC_EFFECT, OFF)); newArmorMap.forEach((enchant, level) -> enchant.onAction(event.getPlayer(), null, event, level, STATIC_EFFECT, ON)); @@ -41,8 +41,8 @@ public class PlayerListener implements Listener { @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) public void onHeldItemChanged(HeldItemChangedEvent event) { - Map oldItemMap = instance.getEnchantUtils().getEnchants(event.getOldItem()); - Map newItemMap = instance.getEnchantUtils().getEnchants(event.getNewItem()); + Map oldItemMap = this.instance.getEnchantUtils().getEnchants(event.getOldItem()); + Map newItemMap = this.instance.getEnchantUtils().getEnchants(event.getNewItem()); oldItemMap.forEach((enchant, level) -> enchant.onAction(event.getPlayer(), null, event, level, HELD_ITEM, OFF)); newItemMap.forEach((enchant, level) -> enchant.onAction(event.getPlayer(), null, event, level, HELD_ITEM, ON)); @@ -50,56 +50,64 @@ public class PlayerListener implements Listener { @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) public void onPlayerItemHeld(PlayerItemHeldEvent event) { - instance.getEnchantUtils().getEnchants(event.getPlayer().getInventory().getItem(event.getPreviousSlot())) + this.instance.getEnchantUtils().getEnchants(event.getPlayer().getInventory().getItem(event.getPreviousSlot())) .forEach((enchant, level) -> enchant.onAction(event.getPlayer(), null, event, level, HELD_ITEM, OFF)); - instance.getEnchantUtils().getEnchants(event.getPlayer().getInventory().getItem(event.getNewSlot())) + this.instance.getEnchantUtils().getEnchants(event.getPlayer().getInventory().getItem(event.getNewSlot())) .forEach((enchant, level) -> enchant.onAction(event.getPlayer(), null, event, level, HELD_ITEM, ON)); } @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) public void onPlayerDeath(PlayerDeathEvent event) { - instance.getEnchantUtils().handlePlayer(event.getEntity(), event.getEntity().getKiller(), event, DEATH); + this.instance.getEnchantUtils().handlePlayer(event.getEntity(), event.getEntity().getKiller(), event, DEATH); if (event.getEntity().getKiller() != null) { - instance.getEnchantUtils().handlePlayer(event.getEntity().getKiller(), event.getEntity(), event, KILLED_PLAYER); + this.instance.getEnchantUtils().handlePlayer(event.getEntity().getKiller(), event.getEntity(), event, KILLED_PLAYER); } } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerInteract(PlayerInteractEvent event) { if (event.getAction() == Action.RIGHT_CLICK_AIR) { - instance.getEnchantUtils().handlePlayer(event.getPlayer(), null, event, RIGHT_CLICK); + this.instance.getEnchantUtils().handlePlayer(event.getPlayer(), null, event, RIGHT_CLICK); } else if (event.getAction() == Action.LEFT_CLICK_AIR) { - instance.getEnchantUtils().handlePlayer(event.getPlayer(), null, event, LEFT_CLICK); + this.instance.getEnchantUtils().handlePlayer(event.getPlayer(), null, event, LEFT_CLICK); } if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { - instance.getEnchantUtils().handlePlayer(event.getPlayer(), null, event, RIGHT_CLICK_BLOCK); + this.instance.getEnchantUtils().handlePlayer(event.getPlayer(), null, event, RIGHT_CLICK_BLOCK); } else if (event.getAction() == Action.LEFT_CLICK_BLOCK) { - instance.getEnchantUtils().handlePlayer(event.getPlayer(), null, event, LEFT_CLICK_BLOCK); + this.instance.getEnchantUtils().handlePlayer(event.getPlayer(), null, event, LEFT_CLICK_BLOCK); } } @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) public void onBlockBreak(BlockBreakEvent event) { - instance.getEnchantUtils().handlePlayer(event.getPlayer(), null, event, BLOCK_BREAK); - if (event.getExpToDrop() != 0) - instance.getEnchantUtils().handlePlayer(event.getPlayer(), null, event, EXPERIENCE_BLOCK_BREAK); + this.instance.getEnchantUtils().handlePlayer(event.getPlayer(), null, event, BLOCK_BREAK); + if (event.getExpToDrop() != 0) { + this.instance.getEnchantUtils().handlePlayer(event.getPlayer(), null, event, EXPERIENCE_BLOCK_BREAK); + } } @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) public void onPlayerJoin(PlayerJoinEvent event) { - event.getPlayer().getActivePotionEffects().stream().filter(potion -> potion.getDuration() >= 32760) + event.getPlayer() + .getActivePotionEffects() + .stream() + .filter(potion -> potion.getDuration() >= 32760) .forEach(potionEffect -> event.getPlayer().removePotionEffect(potionEffect.getType())); - Arrays.stream(event.getPlayer().getInventory().getArmorContents()).forEach(itemStack -> { - instance.getEnchantUtils().getEnchants(itemStack).forEach((enchant, level) - -> enchant.onAction(event.getPlayer(), null, event, level, STATIC_EFFECT, ON)); - }); - ItemStack mainhand = event.getPlayer().getInventory().getItem(event.getPlayer().getInventory().getHeldItemSlot()); - if (isItem(mainhand)) - instance.getEnchantUtils().getEnchants(mainhand).forEach((enchant, level) - -> enchant.onAction(event.getPlayer(), null, event, level, HELD_ITEM, ON)); + Arrays.stream(event.getPlayer().getInventory().getArmorContents()) + .forEach(itemStack -> this.instance + .getEnchantUtils() + .getEnchants(itemStack) + .forEach((enchant, level) -> enchant.onAction(event.getPlayer(), null, event, level, STATIC_EFFECT, ON))); + ItemStack mainHand = event.getPlayer().getInventory().getItem(event.getPlayer().getInventory().getHeldItemSlot()); + if (isItem(mainHand)) { + this.instance + .getEnchantUtils() + .getEnchants(mainHand) + .forEach((enchant, level) -> enchant.onAction(event.getPlayer(), null, event, level, HELD_ITEM, ON)); + } } private boolean isItem(ItemStack is) { diff --git a/src/main/java/com/songoda/epicenchants/listeners/item/BlackScrollListener.java b/src/main/java/com/songoda/epicenchants/listeners/item/BlackScrollListener.java index 9d067f5..b2f3f25 100644 --- a/src/main/java/com/songoda/epicenchants/listeners/item/BlackScrollListener.java +++ b/src/main/java/com/songoda/epicenchants/listeners/item/BlackScrollListener.java @@ -17,7 +17,7 @@ public class BlackScrollListener extends ItemListener { @Override void onApply(InventoryClickEvent event, NBTItem cursor, NBTItem current) { - if (!cursor.hasKey("black-scroll") || !cursor.getBoolean("black-scroll")) { + if (!cursor.hasTag("black-scroll") || !cursor.getBoolean("black-scroll")) { return; } @@ -25,20 +25,20 @@ public class BlackScrollListener extends ItemListener { NBTCompound compound = current.getCompound("enchants"); if (compound == null || compound.getKeys().isEmpty()) { - instance.getLocale().getMessage("blackscroll.noenchants") + this.instance.getLocale().getMessage("blackscroll.noenchants") .sendPrefixedMessage(event.getWhoClicked()); return; } String id = getRandomElement(compound.getKeys()); int level = compound.getInteger(id); - Enchant enchant = instance.getEnchantManager().getValueUnsafe(id); - ItemStack toSet = instance.getEnchantUtils().removeEnchant(event.getCurrentItem(), enchant); + Enchant enchant = this.instance.getEnchantManager().getValueUnsafe(id); + ItemStack toSet = this.instance.getEnchantUtils().removeEnchant(event.getCurrentItem(), enchant); event.getWhoClicked().getInventory().addItem(enchant.getBook().get(enchant, level, cursor.getInteger("success-rate"), 100)); event.setCurrentItem(toSet); - instance.getLocale().getMessage("blackscroll.success") + this.instance.getLocale().getMessage("blackscroll.success") .processPlaceholder("enchant", enchant.getIdentifier()) .processPlaceholder("group_color", enchant.getGroup().getColor()) .processPlaceholder("group_name", enchant.getGroup().getName()) diff --git a/src/main/java/com/songoda/epicenchants/listeners/item/BookListener.java b/src/main/java/com/songoda/epicenchants/listeners/item/BookListener.java index 3dfc17a..0e1be2f 100644 --- a/src/main/java/com/songoda/epicenchants/listeners/item/BookListener.java +++ b/src/main/java/com/songoda/epicenchants/listeners/item/BookListener.java @@ -30,26 +30,26 @@ public class BookListener extends ItemListener { @Override void onApply(InventoryClickEvent event, NBTItem cursor, NBTItem current) { - if (!cursor.hasKey("book-item") || !cursor.getBoolean("book-item")) { + if (!cursor.hasTag("book-item") || !cursor.getBoolean("book-item")) { return; } event.setCancelled(true); ItemStack toApply = event.getCurrentItem(); - Enchant enchant = instance.getEnchantManager().getValue(cursor.getString("enchant")).orElseThrow(() -> new IllegalStateException("Book without enchant!")); + Enchant enchant = this.instance.getEnchantManager().getValue(cursor.getString("enchant")).orElseThrow(() -> new IllegalStateException("Book without enchant!")); if (!enchant.getItemWhitelist().contains(CompatibleMaterial.getMaterial(current.getItem().getType()).get())) { return; } // get total amount of enchantments on item - int currentEnchantmentTotal = instance.getEnchantUtils().getEnchants(toApply).size(); - int maxAllowedOverride = instance.getEnchantUtils().getMaximumEnchantsCanApply((Player) event.getWhoClicked()); - int maxAllowedApply = instance.getEnchantUtils().getMaximumEnchantsCanApplyItem(toApply, (Player) event.getWhoClicked()); + int currentEnchantmentTotal = this.instance.getEnchantUtils().getEnchants(toApply).size(); + int maxAllowedOverride = this.instance.getEnchantUtils().getMaximumEnchantsCanApply((Player) event.getWhoClicked()); + int maxAllowedApply = this.instance.getEnchantUtils().getMaximumEnchantsCanApplyItem(toApply, (Player) event.getWhoClicked()); maxAllowedApply = Math.min(maxAllowedApply, maxAllowedOverride); // item is at max enchantments if (currentEnchantmentTotal >= maxAllowedApply) { - instance.getLocale().getMessage("enchants.maxallowed").processPlaceholder("max_enchants", maxAllowedApply).sendPrefixedMessage(event.getWhoClicked()); + this.instance.getLocale().getMessage("enchants.maxallowed").processPlaceholder("max_enchants", maxAllowedApply).sendPrefixedMessage(event.getWhoClicked()); return; } @@ -64,9 +64,9 @@ public class BookListener extends ItemListener { return; } - Tuple result = instance.getEnchantUtils().apply(toApply, enchant, enchantEvent.getLevel(), enchantEvent.getSuccessRate(), enchantEvent.getDestroyRate()); + Tuple result = this.instance.getEnchantUtils().apply(toApply, enchant, enchantEvent.getLevel(), enchantEvent.getSuccessRate(), enchantEvent.getDestroyRate()); - instance.getLocale().getMessage(GeneralUtils.getMessageFromResult(result.getRight())) + this.instance.getLocale().getMessage(GeneralUtils.getMessageFromResult(result.getRight())) .processPlaceholder("enchant", enchant.getIdentifier()) .sendPrefixedMessage(event.getWhoClicked()); @@ -83,7 +83,7 @@ public class BookListener extends ItemListener { @Override void onClick(PlayerInteractEvent event, NBTItem clicked) { - if (!clicked.hasKey("mystery-book") || !clicked.getBoolean("mystery-book")) { + if (!clicked.hasTag("mystery-book") || !clicked.getBoolean("mystery-book")) { return; } @@ -93,9 +93,9 @@ public class BookListener extends ItemListener { return; } - Group group = instance.getGroupManager().getValue(clicked.getString("group")).orElseThrow(() -> new IllegalStateException("Book without group!")); + Group group = this.instance.getGroupManager().getValue(clicked.getString("group")).orElseThrow(() -> new IllegalStateException("Book without group!")); - Optional enchant = instance.getEnchantManager().getRandomEnchant(group); + Optional enchant = this.instance.getEnchantManager().getRandomEnchant(group); if (!enchant.isPresent()) { throw new IllegalStateException("The " + group.getName() + " group does not have any enchants."); @@ -106,7 +106,7 @@ public class BookListener extends ItemListener { useItem(event); event.getPlayer().getInventory().addItem(enchant.get().getBook().get(enchant.get(), level)); - event.getPlayer().sendMessage(instance.getLocale().getMessage("book.discover") + event.getPlayer().sendMessage(this.instance.getLocale().getMessage("book.discover") .processPlaceholder("group_name", group.getName()) .processPlaceholder("group_color", group.getColor()) .processPlaceholder("enchant_format", enchant.get().getFormat()) diff --git a/src/main/java/com/songoda/epicenchants/listeners/item/DustListener.java b/src/main/java/com/songoda/epicenchants/listeners/item/DustListener.java index f7df27d..eaab724 100644 --- a/src/main/java/com/songoda/epicenchants/listeners/item/DustListener.java +++ b/src/main/java/com/songoda/epicenchants/listeners/item/DustListener.java @@ -16,17 +16,17 @@ public class DustListener extends ItemListener { @Override void onApply(InventoryClickEvent event, NBTItem cursor, NBTItem current) { - if (!cursor.hasKey("dust") || !cursor.getBoolean("dust")) { + if (!cursor.hasTag("dust") || !cursor.getBoolean("dust")) { return; } - if (!current.hasKey("book-item") || !current.getBoolean("book-item")) { + if (!current.hasTag("book-item") || !current.getBoolean("book-item")) { return; } - Enchant enchant = instance.getEnchantManager().getValue(current.getString("enchant")).orElseThrow(() -> new IllegalStateException("Book without enchant!")); + Enchant enchant = this.instance.getEnchantManager().getValue(current.getString("enchant")).orElseThrow(() -> new IllegalStateException("Book without enchant!")); - if (!enchant.getGroup().equals(instance.getGroupManager().getValue(cursor.getString("group")).orElseThrow(() -> new IllegalStateException("Dust without group!")))) { + if (!enchant.getGroup().equals(this.instance.getGroupManager().getValue(cursor.getString("group")).orElseThrow(() -> new IllegalStateException("Dust without group!")))) { return; } @@ -45,7 +45,7 @@ public class DustListener extends ItemListener { @Override void onClick(PlayerInteractEvent event, NBTItem clicked) { - if (!clicked.hasKey("secret-dust") || !clicked.getBoolean("secret-dust")) { + if (!clicked.hasTag("secret-dust") || !clicked.getBoolean("secret-dust")) { return; } @@ -55,10 +55,10 @@ public class DustListener extends ItemListener { return; } - Group group = instance.getGroupManager().getValueUnsafe(clicked.getString("group")); + Group group = this.instance.getGroupManager().getValueUnsafe(clicked.getString("group")); int rate = ThreadLocalRandom.current().nextInt(clicked.getInteger("min-rate"), clicked.getInteger("max-rate")); useItem(event); - event.getPlayer().getInventory().addItem(instance.getSpecialItems().getDust(group, null, rate, false)); + event.getPlayer().getInventory().addItem(this.instance.getSpecialItems().getDust(group, null, rate, false)); } } diff --git a/src/main/java/com/songoda/epicenchants/listeners/item/WhiteScrollListener.java b/src/main/java/com/songoda/epicenchants/listeners/item/WhiteScrollListener.java index df7f3e7..89173e7 100644 --- a/src/main/java/com/songoda/epicenchants/listeners/item/WhiteScrollListener.java +++ b/src/main/java/com/songoda/epicenchants/listeners/item/WhiteScrollListener.java @@ -8,32 +8,32 @@ import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.ItemStack; public class WhiteScrollListener extends ItemListener { - public WhiteScrollListener(EpicEnchants instance) { super(instance); } @Override void onApply(InventoryClickEvent event, NBTItem cursor, NBTItem current) { - if (!cursor.hasKey("white-scroll") || !cursor.getBoolean("white-scroll")) { + if (!cursor.hasTag("white-scroll") || !cursor.getBoolean("white-scroll")) { return; } event.setCancelled(true); - if (current.hasKey("protected")) { - instance.getLocale().getMessage("whitescroll.alreadyapplied") + if (current.hasTag("protected")) { + this.instance.getLocale().getMessage("whitescroll.alreadyapplied") .sendPrefixedMessage(event.getWhoClicked()); return; } - if (!instance.getItemGroup().isValid(CompatibleMaterial.getMaterial(event.getCurrentItem().getType()).get())) + if (!this.instance.getItemGroup().isValid(CompatibleMaterial.getMaterial(event.getCurrentItem().getType()).get())) { return; + } current.setBoolean("protected", true); - instance.getLocale().getMessage("whitescrollapplied").sendPrefixedMessage(event.getWhoClicked()); + this.instance.getLocale().getMessage("whitescrollapplied").sendPrefixedMessage(event.getWhoClicked()); - ItemStack toSet = new ItemBuilder(current.getItem()).addLore(instance.getSpecialItems().getWhiteScrollLore()).build(); + ItemStack toSet = new ItemBuilder(current.getItem()).addLore(this.instance.getSpecialItems().getWhiteScrollLore()).build(); event.getClickedInventory().setItem(event.getSlot(), toSet); useItem(event); diff --git a/src/main/java/com/songoda/epicenchants/managers/EnchantManager.java b/src/main/java/com/songoda/epicenchants/managers/EnchantManager.java index bfd5aeb..2939930 100644 --- a/src/main/java/com/songoda/epicenchants/managers/EnchantManager.java +++ b/src/main/java/com/songoda/epicenchants/managers/EnchantManager.java @@ -15,7 +15,6 @@ import java.util.stream.Collectors; import static com.songoda.epicenchants.utils.single.ConfigParser.parseEnchant; public class EnchantManager extends Manager { - public EnchantManager(EpicEnchants instance) { super(instance); } @@ -30,7 +29,7 @@ public class EnchantManager extends Manager { } public void loadEnchants() { - instance.getFileManager().getYmlFiles("enchants").forEach(file -> { + this.instance.getFileManager().getYmlFiles("enchants").forEach(file -> { try { loadEnchant(file); } catch (Exception e) { @@ -41,10 +40,8 @@ public class EnchantManager extends Manager { }); } - public void loadEnchant(File file) throws Exception { - Enchant enchant = parseEnchant(instance, YamlConfiguration.loadConfiguration(file)); + public void loadEnchant(File file) { + Enchant enchant = parseEnchant(this.instance, YamlConfiguration.loadConfiguration(file)); add(enchant.getIdentifier(), enchant); } } - - diff --git a/src/main/java/com/songoda/epicenchants/managers/FileManager.java b/src/main/java/com/songoda/epicenchants/managers/FileManager.java index 04e6ec5..e3428e7 100644 --- a/src/main/java/com/songoda/epicenchants/managers/FileManager.java +++ b/src/main/java/com/songoda/epicenchants/managers/FileManager.java @@ -25,7 +25,6 @@ import static java.io.File.separator; import static java.util.Arrays.asList; public class FileManager extends Manager { - private final String directory; private final LinkedHashSet files = new LinkedHashSet<>(asList( of("menus/main-info-menu.yml", true, true), @@ -89,13 +88,13 @@ public class FileManager extends Manager { public FileManager(EpicEnchants instance) { super(instance); - directory = ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13) ? "master" : "legacy"; - Bukkit.getConsoleSender().sendMessage("Using the " + directory + " configurations because version is " + ServerVersion.getServerVersion().name()); + this.directory = ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13) ? "master" : "legacy"; + Bukkit.getConsoleSender().sendMessage("Using the " + this.directory + " configurations because version is " + ServerVersion.getServerVersion().name()); } public void loadFiles() { - files.forEach(fileLocation -> { - File file = new File(instance.getDataFolder() + separator + fileLocation.getPath()); + this.files.forEach(fileLocation -> { + File file = new File(this.instance.getDataFolder() + separator + fileLocation.getPath()); if (!file.exists() && (fileLocation.isRequired() || Settings.FIRST_LOAD.getBoolean())) { Bukkit.getConsoleSender().sendMessage("Creating file: " + fileLocation.getPath()); @@ -103,7 +102,7 @@ public class FileManager extends Manager { try { // System.out.println(fileLocation.getResourcePath(directory) + " : " + file.toPath()); - copy(instance.getResource(fileLocation.getResourcePath(directory)), Files.newOutputStream(file.toPath())); + copy(this.instance.getResource(fileLocation.getResourcePath(this.directory)), Files.newOutputStream(file.toPath())); } catch (IOException e) { e.printStackTrace(); } @@ -120,8 +119,8 @@ public class FileManager extends Manager { } }); - instance.getConfig().set("System.First Load", false); - instance.saveConfig(); + this.instance.getConfig().set("System.First Load", false); + this.instance.saveConfig(); } public FileConfiguration getConfiguration(String key) { @@ -129,7 +128,7 @@ public class FileManager extends Manager { } public List getYmlFiles(String directory) { - File dir = new File(instance.getDataFolder() + separator + directory + separator); + File dir = new File(this.instance.getDataFolder() + separator + directory + separator); File[] allFiles = dir.listFiles(); List output = new ArrayList<>(); @@ -143,8 +142,8 @@ public class FileManager extends Manager { Arrays.stream(allFiles) .filter(File::isDirectory) - .filter(s -> !s.getName().equalsIgnoreCase("old")) - .forEach(f -> output.addAll(getYmlFiles(directory + separator + f.getName()))); + .filter(file -> !file.getName().equalsIgnoreCase("old")) + .forEach(file -> output.addAll(getYmlFiles(directory + separator + file.getName()))); return output; } diff --git a/src/main/java/com/songoda/epicenchants/managers/GroupManager.java b/src/main/java/com/songoda/epicenchants/managers/GroupManager.java index fdeb7e5..96cbcf1 100644 --- a/src/main/java/com/songoda/epicenchants/managers/GroupManager.java +++ b/src/main/java/com/songoda/epicenchants/managers/GroupManager.java @@ -11,10 +11,10 @@ public class GroupManager extends Manager { } public void loadGroups() { - ConfigurationSection config = instance.getFileManager().getConfiguration("groups").getConfigurationSection("groups"); + ConfigurationSection config = this.instance.getFileManager().getConfiguration("groups").getConfigurationSection("groups"); config.getKeys(false).forEach(key -> { - Group group = ConfigParser.parseGroup(instance, config.getConfigurationSection(key)); + Group group = ConfigParser.parseGroup(this.instance, config.getConfigurationSection(key)); add(group.getIdentifier().toUpperCase(), group); }); } -} \ No newline at end of file +} diff --git a/src/main/java/com/songoda/epicenchants/managers/InfoManager.java b/src/main/java/com/songoda/epicenchants/managers/InfoManager.java index 09a67c1..951149b 100644 --- a/src/main/java/com/songoda/epicenchants/managers/InfoManager.java +++ b/src/main/java/com/songoda/epicenchants/managers/InfoManager.java @@ -23,12 +23,15 @@ public class InfoManager extends Manager { } public void loadMenus() { - mainInfoMenu = new MainInfoMenu(instance, instance.getFileManager().getConfiguration("menus/main-info-menu")); - instance.getFileManager().getYmlFiles("menus/groups").forEach(file -> { + this.mainInfoMenu = new MainInfoMenu(this.instance, this.instance.getFileManager().getConfiguration("menus/main-info-menu")); + this.instance.getFileManager().getYmlFiles("menus/groups").forEach(file -> { try { YamlConfiguration config = YamlConfiguration.loadConfiguration(file); - add(instance.getGroupManager().getValue(config.getString("group")) - .orElseThrow(() -> new IllegalArgumentException("Invalid group: " + config.getString("group"))), new InfoMenu(instance, config)); + add(this.instance + .getGroupManager() + .getValue(config.getString("group")) + .orElseThrow(() -> new IllegalArgumentException("Invalid group: " + config.getString("group"))), + new InfoMenu(this.instance, config)); } catch (Exception e) { Bukkit.getConsoleSender().sendMessage("Something went wrong loading the menu from file " + file.getName()); Bukkit.getConsoleSender().sendMessage("Please check to make sure there are no errors in the file."); diff --git a/src/main/java/com/songoda/epicenchants/managers/Manager.java b/src/main/java/com/songoda/epicenchants/managers/Manager.java index 040c0b7..dbdde62 100644 --- a/src/main/java/com/songoda/epicenchants/managers/Manager.java +++ b/src/main/java/com/songoda/epicenchants/managers/Manager.java @@ -9,7 +9,6 @@ import java.util.Map; import java.util.Optional; public abstract class Manager { - final EpicEnchants instance; private final Map map; @@ -19,15 +18,16 @@ public abstract class Manager { } public Optional getValue(K key) { - for (Object k : map.keySet()) { - if (k.toString().equalsIgnoreCase(key.toString())) - return Optional.ofNullable(map.get(k)); + for (Object k : this.map.keySet()) { + if (k.toString().equalsIgnoreCase(key.toString())) { + return Optional.ofNullable(this.map.get(k)); + } } return Optional.empty(); } public void add(K key, V value) { - map.put(key, value); + this.map.put(key, value); } public V getValueUnsafe(K key) { @@ -35,14 +35,14 @@ public abstract class Manager { } public Collection getValues() { - return Collections.unmodifiableCollection(map.values()); + return Collections.unmodifiableCollection(this.map.values()); } public Collection getKeys() { - return Collections.unmodifiableCollection(map.keySet()); + return Collections.unmodifiableCollection(this.map.keySet()); } public void clear() { - map.clear(); + this.map.clear(); } } diff --git a/src/main/java/com/songoda/epicenchants/menus/AlchemistMenu.java b/src/main/java/com/songoda/epicenchants/menus/AlchemistMenu.java index 215d401..144663e 100644 --- a/src/main/java/com/songoda/epicenchants/menus/AlchemistMenu.java +++ b/src/main/java/com/songoda/epicenchants/menus/AlchemistMenu.java @@ -36,13 +36,13 @@ public class AlchemistMenu extends FastInv { this.instance = instance; this.config = config; - LEFT_SLOT = config.getInt("left-slot"); - RIGHT_SLOT = config.getInt("right-slot"); - PREVIEW_SLOT = config.getInt("preview-slot"); - ACCEPT_SLOT = config.getInt("accept-slot"); + this.LEFT_SLOT = config.getInt("left-slot"); + this.RIGHT_SLOT = config.getInt("right-slot"); + this.PREVIEW_SLOT = config.getInt("preview-slot"); + this.ACCEPT_SLOT = config.getInt("accept-slot"); - PREVIEW_ITEM = new ItemBuilder(config.getConfigurationSection("contents.preview")).build(); - ACCEPT_ITEM = new ItemBuilder(config.getConfigurationSection("contents.accept-before")).build(); + this.PREVIEW_ITEM = new ItemBuilder(config.getConfigurationSection("contents.preview")).build(); + this.ACCEPT_ITEM = new ItemBuilder(config.getConfigurationSection("contents.accept-before")).build(); if (config.isConfigurationSection("fill")) { fill(new ItemBuilder(config.getConfigurationSection("fill")).build()); @@ -61,8 +61,8 @@ public class AlchemistMenu extends FastInv { .map(config::getConfigurationSection) .forEach(section -> addItem(getSlots(section.getString("slot")), new ItemBuilder(section).build())); - clear(RIGHT_SLOT); - clear(LEFT_SLOT); + clear(this.RIGHT_SLOT); + clear(this.LEFT_SLOT); updateSlots(); @@ -74,7 +74,7 @@ public class AlchemistMenu extends FastInv { int slot = event.getSlot(); - if (slot != RIGHT_SLOT && slot != LEFT_SLOT) { + if (slot != this.RIGHT_SLOT && slot != this.LEFT_SLOT) { return; } @@ -107,10 +107,10 @@ public class AlchemistMenu extends FastInv { // Player closed inventory onClose(event -> { - if (getInventory().getItem(RIGHT_SLOT) != null) - event.getPlayer().getInventory().addItem(getInventory().getItem(RIGHT_SLOT)); - if (getInventory().getItem(LEFT_SLOT) != null) - event.getPlayer().getInventory().addItem(getInventory().getItem(LEFT_SLOT)); + if (getInventory().getItem(this.RIGHT_SLOT) != null) + event.getPlayer().getInventory().addItem(getInventory().getItem(this.RIGHT_SLOT)); + if (getInventory().getItem(this.LEFT_SLOT) != null) + event.getPlayer().getInventory().addItem(getInventory().getItem(this.LEFT_SLOT)); }); } @@ -124,65 +124,65 @@ public class AlchemistMenu extends FastInv { NBTItem nbtItem = new NBTItem(toHandle); - if (!nbtItem.hasKey("book-item") && !nbtItem.hasKey("dust")) { - instance.getLocale().getMessage("alchemist.notinterested").sendPrefixedMessage(player); + if (!nbtItem.hasTag("book-item") && !nbtItem.hasTag("dust")) { + this.instance.getLocale().getMessage("alchemist.notinterested").sendPrefixedMessage(player); return false; } // Both slots occupied - if (getInventory().getItem(LEFT_SLOT) != null && getInventory().getItem(RIGHT_SLOT) != null) { - instance.getLocale().getMessage("alchemist.maxtwoitems").sendPrefixedMessage(player); + if (getInventory().getItem(this.LEFT_SLOT) != null && getInventory().getItem(this.RIGHT_SLOT) != null) { + this.instance.getLocale().getMessage("alchemist.maxtwoitems").sendPrefixedMessage(player); return false; } int successRate = nbtItem.getInteger("success-rate"); // Both slots empty - if (getInventory().getItem(LEFT_SLOT) == null && getInventory().getItem(RIGHT_SLOT) == null) { - if (nbtItem.hasKey("book-item")) { - Enchant enchant = instance.getEnchantManager().getValue(nbtItem.getString("enchant")).orElseThrow(() -> new IllegalStateException("Book without enchant!")); + if (getInventory().getItem(this.LEFT_SLOT) == null && getInventory().getItem(this.RIGHT_SLOT) == null) { + if (nbtItem.hasTag("book-item")) { + Enchant enchant = this.instance.getEnchantManager().getValue(nbtItem.getString("enchant")).orElseThrow(() -> new IllegalStateException("Book without enchant!")); int level = nbtItem.getInteger("level"); if (enchant.getMaxLevel() == level) { - instance.getLocale().getMessage("alchemist.maxlevelbook") + this.instance.getLocale().getMessage("alchemist.maxlevelbook") .sendPrefixedMessage(player); return false; } } else { - Group group = instance.getGroupManager().getValue(nbtItem.getString("group")).orElseThrow(() -> new IllegalStateException("Dust without group!")); + Group group = this.instance.getGroupManager().getValue(nbtItem.getString("group")).orElseThrow(() -> new IllegalStateException("Dust without group!")); - if (group.getOrder() == instance.getGroupManager().getValues().stream().mapToInt(Group::getOrder).max().orElse(0) || successRate == 100) { - instance.getLocale().getMessage("alchemist." + (successRate == 100 ? "maxpercentagedust" : "highestgroupdust")) + if (group.getOrder() == this.instance.getGroupManager().getValues().stream().mapToInt(Group::getOrder).max().orElse(0) || successRate == 100) { + this.instance.getLocale().getMessage("alchemist." + (successRate == 100 ? "maxpercentagedust" : "highestgroupdust")) .sendPrefixedMessage(player); return false; } } - getInventory().setItem(LEFT_SLOT, toHandle); + getInventory().setItem(this.LEFT_SLOT, toHandle); return true; } - NBTItem other = new NBTItem(getInventory().getItem(getInventory().getItem(LEFT_SLOT) == null ? RIGHT_SLOT : LEFT_SLOT)); - int emptySlot = getInventory().getItem(LEFT_SLOT) == null ? LEFT_SLOT : RIGHT_SLOT; + NBTItem other = new NBTItem(getInventory().getItem(getInventory().getItem(this.LEFT_SLOT) == null ? this.RIGHT_SLOT : this.LEFT_SLOT)); + int emptySlot = getInventory().getItem(this.LEFT_SLOT) == null ? this.LEFT_SLOT : this.RIGHT_SLOT; - if (other.hasKey("book-item")) { + if (other.hasTag("book-item")) { if (!nbtItem.getString("enchant").equals(other.getString("enchant"))) { - instance.getLocale().getMessage("alchemist.differentenchantment").sendPrefixedMessage(player); + this.instance.getLocale().getMessage("alchemist.differentenchantment").sendPrefixedMessage(player); return false; } if (nbtItem.getInteger("level") != other.getInteger("level")) { - instance.getLocale().getMessage("alchemist.differentlevels").sendPrefixedMessage(player); + this.instance.getLocale().getMessage("alchemist.differentlevels").sendPrefixedMessage(player); return false; } } else { if (!nbtItem.getString("group").equals(other.getString("group"))) { - instance.getLocale().getMessage("alchemist.differentgroups").sendPrefixedMessage(player); + this.instance.getLocale().getMessage("alchemist.differentgroups").sendPrefixedMessage(player); return false; } if (successRate >= 100) { - instance.getLocale().getMessage("alchemist.maxpercentagedust").sendPrefixedMessage(player); + this.instance.getLocale().getMessage("alchemist.maxpercentagedust").sendPrefixedMessage(player); return false; } } @@ -193,20 +193,20 @@ public class AlchemistMenu extends FastInv { } private void updateSlots() { - if (getInventory().getItem(LEFT_SLOT) == null || getInventory().getItem(RIGHT_SLOT) == null) { - addItem(ACCEPT_SLOT, ACCEPT_ITEM); - addItem(PREVIEW_SLOT, PREVIEW_ITEM); + if (getInventory().getItem(this.LEFT_SLOT) == null || getInventory().getItem(this.RIGHT_SLOT) == null) { + addItem(this.ACCEPT_SLOT, this.ACCEPT_ITEM); + addItem(this.PREVIEW_SLOT, this.PREVIEW_ITEM); return; } - NBTItem leftItem = new NBTItem(getInventory().getItem(LEFT_SLOT)); - NBTItem rightItem = new NBTItem(getInventory().getItem(RIGHT_SLOT)); + NBTItem leftItem = new NBTItem(getInventory().getItem(this.LEFT_SLOT)); + NBTItem rightItem = new NBTItem(getInventory().getItem(this.RIGHT_SLOT)); int ecoCost; int expCost; - if (leftItem.hasKey("book-item")) { + if (leftItem.hasTag("book-item")) { int level = leftItem.getInteger("level"); - Enchant enchant = instance.getEnchantManager().getValue(leftItem.getString("enchant")).orElseThrow(() -> new IllegalStateException("Book without enchant!")); + Enchant enchant = this.instance.getEnchantManager().getValue(leftItem.getString("enchant")).orElseThrow(() -> new IllegalStateException("Book without enchant!")); int leftSuccess = leftItem.getInteger("success-rate"); int rightSuccess = rightItem.getInteger("success-rate"); int leftDestroy = leftItem.getInteger("destroy-rate"); @@ -235,9 +235,9 @@ public class AlchemistMenu extends FastInv { ecoCost = getFromFormula("book.eco-cost-formula", costPlaceholders); expCost = getFromFormula("book.exp-cost-formula", costPlaceholders); - getInventory().setItem(PREVIEW_SLOT, enchant.getBook().get(enchant, level + 1, successRate, destroyRate)); + getInventory().setItem(this.PREVIEW_SLOT, enchant.getBook().get(enchant, level + 1, successRate, destroyRate)); } else { - Group group = instance.getGroupManager().getValue(leftItem.getString("group")).orElseThrow(() -> new IllegalStateException("Dust without group!")); + Group group = this.instance.getGroupManager().getValue(leftItem.getString("group")).orElseThrow(() -> new IllegalStateException("Dust without group!")); Placeholder[] placeholders = new Placeholder[] { of("left_percentage", leftItem.getInteger("percentage")), @@ -254,39 +254,42 @@ public class AlchemistMenu extends FastInv { ecoCost = getFromFormula("dust.eco-cost-formula", costPlaceholders); expCost = getFromFormula("dust.exp-cost-formula", costPlaceholders); - Group newGroup = instance.getGroupManager().getValues().stream() + Group newGroup = this.instance + .getGroupManager() + .getValues() + .stream() .filter(s -> s.getOrder() == group.getOrder() + 1) .findFirst() .orElseThrow(() -> new IllegalStateException("No group higher than: " + group.getIdentifier())); - getInventory().setItem(PREVIEW_SLOT, instance.getSpecialItems().getDust(newGroup, "magic", successRate, true)); + getInventory().setItem(this.PREVIEW_SLOT, this.instance.getSpecialItems().getDust(newGroup, "magic", successRate, true)); } - addItem(ACCEPT_SLOT, new ItemBuilder(config.getConfigurationSection("contents.accept-after"), + addItem(this.ACCEPT_SLOT, new ItemBuilder(this.config.getConfigurationSection("contents.accept-after"), of("eco_cost", ecoCost), of("exp_cost", expCost) ).build(), event -> { if (!EconomyManager.hasBalance(event.getPlayer(), ecoCost) || getExp(event.getPlayer()) < expCost) { - instance.getLocale().getMessage("alchemist.cannotafford").sendPrefixedMessage(event.getPlayer()); + this.instance.getLocale().getMessage("alchemist.cannotafford").sendPrefixedMessage(event.getPlayer()); return; } EconomyManager.withdrawBalance(event.getPlayer(), ecoCost); changeExp(event.getPlayer(), -expCost); - instance.getLocale().getMessage("alchemist.success") + this.instance.getLocale().getMessage("alchemist.success") .processPlaceholder("eco_cost", ecoCost) .processPlaceholder("exp_cost", expCost) .sendPrefixedMessage(event.getPlayer()); - event.getPlayer().getInventory().addItem(getInventory().getItem(PREVIEW_SLOT)); - clear(RIGHT_SLOT); - clear(LEFT_SLOT); + event.getPlayer().getInventory().addItem(getInventory().getItem(this.PREVIEW_SLOT)); + clear(this.RIGHT_SLOT); + clear(this.LEFT_SLOT); event.getPlayer().closeInventory(); }); } private int getFromFormula(String path, Placeholder... placeholders) { - String toTest = config.getString(path); + String toTest = this.config.getString(path); for (Placeholder placeholder : placeholders) toTest = toTest.replace(placeholder.getPlaceholder(), placeholder.getToReplace().toString()); diff --git a/src/main/java/com/songoda/epicenchants/menus/EnchanterMenu.java b/src/main/java/com/songoda/epicenchants/menus/EnchanterMenu.java index b5c63e3..9e5ee34 100644 --- a/src/main/java/com/songoda/epicenchants/menus/EnchanterMenu.java +++ b/src/main/java/com/songoda/epicenchants/menus/EnchanterMenu.java @@ -20,7 +20,7 @@ import static com.songoda.epicenchants.utils.single.GeneralUtils.color; import static com.songoda.epicenchants.utils.single.GeneralUtils.getSlots; public class EnchanterMenu extends FastInv { - private final Map DELAY = new HashMap<>(); + private final Map delay = new HashMap<>(); public EnchanterMenu(EpicEnchants instance, FileConfiguration config, Player player) { super(config.getInt("rows") * 9, color(config.getString("title"))); @@ -33,7 +33,7 @@ public class EnchanterMenu extends FastInv { .stream() .map(s -> "contents." + s) .map(config::getConfigurationSection) - .filter(s -> s.get("group") != null) + .filter(section -> section.get("group") != null) .forEach(section -> { int expCost = section.getInt("exp-cost"); int ecoCost = section.getInt("eco-cost"); @@ -51,7 +51,7 @@ public class EnchanterMenu extends FastInv { addItem(getSlots(section.getString("slot")), itemStack, event -> { // Todo: wanna change this - if (DELAY.getOrDefault(player.getUniqueId(), 0L) > System.currentTimeMillis()) { + if (this.delay.getOrDefault(player.getUniqueId(), 0L) > System.currentTimeMillis()) { return; } @@ -72,7 +72,7 @@ public class EnchanterMenu extends FastInv { changeExp(player, -expCost); player.getInventory().addItem(instance.getSpecialItems().getMysteryBook(group)); - DELAY.put(event.getPlayer().getUniqueId(), System.currentTimeMillis() + 120); + this.delay.put(event.getPlayer().getUniqueId(), System.currentTimeMillis() + 120); }); }); @@ -80,7 +80,7 @@ public class EnchanterMenu extends FastInv { .stream() .map(s -> "contents." + s) .map(config::getConfigurationSection) - .filter(s -> s.get("group") == null) + .filter(section -> section.get("group") == null) .forEach(section -> addItem(getSlots(section.getString("slot")), new ItemBuilder(section).build())); } } diff --git a/src/main/java/com/songoda/epicenchants/menus/InfoMenu.java b/src/main/java/com/songoda/epicenchants/menus/InfoMenu.java index 70c53b6..6e08720 100644 --- a/src/main/java/com/songoda/epicenchants/menus/InfoMenu.java +++ b/src/main/java/com/songoda/epicenchants/menus/InfoMenu.java @@ -59,7 +59,12 @@ public class InfoMenu extends FastInv { of("max_level", enchant.getMaxLevel()), of("applicable_to", whitelist), of("enchant", enchant.getIdentifier()), - of("description", enchant.getDescription().stream().map(s -> config.getString("enchant-item.description-color") + s).collect(Collectors.toList()))).build()); + of("description", enchant + .getDescription() + .stream() + .map(s -> config.getString("enchant-item.description-color") + s) + .collect(Collectors.toList()))) + .build()); }); } } diff --git a/src/main/java/com/songoda/epicenchants/menus/MainInfoMenu.java b/src/main/java/com/songoda/epicenchants/menus/MainInfoMenu.java index 7fda7c1..fb18d7d 100644 --- a/src/main/java/com/songoda/epicenchants/menus/MainInfoMenu.java +++ b/src/main/java/com/songoda/epicenchants/menus/MainInfoMenu.java @@ -11,7 +11,6 @@ import static com.songoda.epicenchants.utils.single.GeneralUtils.color; import static com.songoda.epicenchants.utils.single.GeneralUtils.getSlots; public class MainInfoMenu extends FastInv implements Listener { - public MainInfoMenu(EpicEnchants instance, FileConfiguration config) { super(config.getInt("rows") * 9, color(config.getString("title"))); config.getConfigurationSection("contents").getKeys(false) @@ -19,10 +18,18 @@ public class MainInfoMenu extends FastInv implements Listener { .map(s -> "contents." + s) .map(config::getConfigurationSection) .forEach(section -> addItem(getSlots(section.getString("slot")), new ItemBuilder(section).build(), event -> { - if (section.getString("group") == null) return; - Group group = instance.getGroupManager().getValue(section.getString("group")) + if (section.getString("group") == null) { + return; + } + + Group group = instance + .getGroupManager() + .getValue(section.getString("group")) .orElseThrow(() -> new IllegalArgumentException("Invalid group: " + section.getString("group"))); - instance.getInfoManager().getMenu(group).ifPresent(menu -> menu.open(event.getPlayer())); + + instance.getInfoManager() + .getMenu(group) + .ifPresent(menu -> menu.open(event.getPlayer())); })); } } diff --git a/src/main/java/com/songoda/epicenchants/menus/TinkererMenu.java b/src/main/java/com/songoda/epicenchants/menus/TinkererMenu.java index bdd85b6..dff2914 100644 --- a/src/main/java/com/songoda/epicenchants/menus/TinkererMenu.java +++ b/src/main/java/com/songoda/epicenchants/menus/TinkererMenu.java @@ -54,8 +54,8 @@ public class TinkererMenu extends FastInv { .forEach(section -> { addItem(getSlots(section.getString("slot")), new ItemBuilder(section).build(), event -> { if (section.getName().equalsIgnoreCase("accept-left") || section.getName().equalsIgnoreCase("accept-right")) { - slotMap.values().stream().map(slot -> getInventory().getItem(slot)).filter(Objects::nonNull).forEach(event.getPlayer().getInventory()::addItem); - slotMap.keySet().forEach(slot -> getInventory().clear(slot)); + this.slotMap.values().stream().map(slot -> getInventory().getItem(slot)).filter(Objects::nonNull).forEach(event.getPlayer().getInventory()::addItem); + this.slotMap.keySet().forEach(slot -> getInventory().clear(slot)); accepted.set(true); event.getPlayer().closeInventory(); instance.getLocale().getMessage("tinkerer.accepted").sendPrefixedMessage(event.getPlayer()); @@ -118,14 +118,14 @@ public class TinkererMenu extends FastInv { int slot = event.getSlot(); - if (!slotMap.keySet().contains(slot)) { + if (!this.slotMap.keySet().contains(slot)) { return; } if (getInventory().getItem(slot) != null && getInventory().getItem(slot).getType() != Material.AIR) { event.getPlayer().getInventory().addItem(getInventory().getItem(slot)); getInventory().clear(slot); - getInventory().clear(slotMap.get(slot)); + getInventory().clear(this.slotMap.get(slot)); } }); @@ -154,7 +154,7 @@ public class TinkererMenu extends FastInv { // Player closed inventory onClose(event -> { - slotMap.keySet().stream().filter(s -> getInventory().getItem(s) != null).forEach(s -> { + this.slotMap.keySet().stream().filter(s -> getInventory().getItem(s) != null).forEach(s -> { event.getPlayer().getInventory().addItem(getInventory().getItem(s)); }); @@ -186,7 +186,7 @@ public class TinkererMenu extends FastInv { } private boolean handleItem(ItemStack itemStack, ItemType itemType) { - Optional> emptySlot = slotMap.entrySet().stream() + Optional> emptySlot = this.slotMap.entrySet().stream() .filter(slot -> getInventory().getItem(slot.getKey()) == null || getInventory().getItem(slot.getKey()).getType() == Material.AIR) .findFirst(); @@ -200,7 +200,7 @@ public class TinkererMenu extends FastInv { addItem(emptySlot.get().getKey(), finalItemStack); if (itemType == BOOK) { - getInventory().setItem(emptySlot.get().getValue(), instance.getSpecialItems().getSecretDust(new NBTItem(finalItemStack))); + getInventory().setItem(emptySlot.get().getValue(), this.instance.getSpecialItems().getSecretDust(new NBTItem(finalItemStack))); } return true; @@ -220,7 +220,7 @@ public class TinkererMenu extends FastInv { private int getExpAmount(ItemStack itemStack) { AtomicInteger total = new AtomicInteger(); - ConfigurationSection section = config.getConfigurationSection("exp-table-per-level"); + ConfigurationSection section = this.config.getConfigurationSection("exp-table-per-level"); itemStack.getEnchantments().forEach((enchantment, level) -> { total.addAndGet(section.getInt(enchantment.getName(), section.getInt("DEFAULT")) * level); @@ -239,7 +239,7 @@ public class TinkererMenu extends FastInv { } enchantments.getKeys().forEach(key -> { - Enchant enchant = instance.getEnchantManager().getValueUnsafe(key); + Enchant enchant = this.instance.getEnchantManager().getValueUnsafe(key); total.addAndGet(section.getInt(enchant.getIdentifier(), enchant.getGroup().getTinkererExp()) * enchantments.getInteger(key)); }); diff --git a/src/main/java/com/songoda/epicenchants/objects/BookItem.java b/src/main/java/com/songoda/epicenchants/objects/BookItem.java index 7bd0093..c6e3e86 100644 --- a/src/main/java/com/songoda/epicenchants/objects/BookItem.java +++ b/src/main/java/com/songoda/epicenchants/objects/BookItem.java @@ -18,10 +18,10 @@ import static com.songoda.epicenchants.utils.single.GeneralUtils.color; import static java.util.concurrent.ThreadLocalRandom.current; public class BookItem { - private EpicEnchants instance; - private Material material; - private String displayName; - private List lore; + private final EpicEnchants instance; + private final Material material; + private final String displayName; + private final List lore; BookItem(EpicEnchants instance, Material material, String displayName, List lore) { this.instance = instance; @@ -52,7 +52,7 @@ public class BookItem { int finalSuccessRate = successRate; int finalDestroyRate = destroyRate; - List toSet = new ArrayList<>(lore); + List toSet = new ArrayList<>(this.lore); for (int i = toSet.size() - 1; i >= 0; i--) { String string = toSet.get(i); @@ -64,17 +64,17 @@ public class BookItem { } string = string - .replace("{item_group}", "" + instance.getItemGroup().getGroup(enchant.getItemWhitelist()).map(ItemGroup.Group::getName).orElse("N/A")) - .replace("{success_rate}", "" + finalSuccessRate) - .replace("{destroy_rate}", "" + finalDestroyRate); + .replace("{item_group}", this.instance.getItemGroup().getGroup(enchant.getItemWhitelist()).map(ItemGroup.Group::getName).orElse("N/A")) + .replace("{success_rate}", String.valueOf(finalSuccessRate)) + .replace("{destroy_rate}", String.valueOf(finalDestroyRate)); toSet.set(i, string); } - ItemBuilder itemBuilder = new ItemBuilder(material) - .name(color(displayName - .replace("{level}", "" + (Settings.ROMAN.getBoolean() ? RomanNumber.toRoman(level) : level)) - .replace("{enchant}", "" + enchant.getIdentifier()) + ItemBuilder itemBuilder = new ItemBuilder(this.material) + .name(color(this.displayName + .replace("{level}", String.valueOf(Settings.ROMAN.getBoolean() ? RomanNumber.toRoman(level) : level)) + .replace("{enchant}", enchant.getIdentifier()) .replace("{group_color}", enchant.getGroup().getColor()) .replace("{group_name}", enchant.getGroup().getName()) )) @@ -120,7 +120,7 @@ public class BookItem { } public BookItem build() { - return new BookItem(instance, material, displayName, lore); + return new BookItem(this.instance, this.material, this.displayName, this.lore); } public String toString() { diff --git a/src/main/java/com/songoda/epicenchants/objects/Condition.java b/src/main/java/com/songoda/epicenchants/objects/Condition.java index a99a5a5..2b6e0eb 100644 --- a/src/main/java/com/songoda/epicenchants/objects/Condition.java +++ b/src/main/java/com/songoda/epicenchants/objects/Condition.java @@ -20,11 +20,11 @@ public class Condition { } public boolean get(Player user, @Nullable LivingEntity attacker, int level, @Nullable Event event, boolean def) { - if (string == null || string.isEmpty()) { + if (this.string == null || this.string.isEmpty()) { return true; } - String toValidate = ChatColor.stripColor(Placeholders.setPlaceholders(string, user, attacker, level, event)); + String toValidate = ChatColor.stripColor(Placeholders.setPlaceholders(this.string, user, attacker, level, event)); return (boolean) GeneralUtils.parseJS(toValidate, "condition", def); } diff --git a/src/main/java/com/songoda/epicenchants/objects/Enchant.java b/src/main/java/com/songoda/epicenchants/objects/Enchant.java index ad831a0..171e276 100644 --- a/src/main/java/com/songoda/epicenchants/objects/Enchant.java +++ b/src/main/java/com/songoda/epicenchants/objects/Enchant.java @@ -1,6 +1,5 @@ package com.songoda.epicenchants.objects; -import com.craftaro.core.compatibility.CompatibleMaterial; import com.craftaro.core.third_party.com.cryptomorin.xseries.XMaterial; import com.songoda.epicenchants.effect.EffectExecutor; import com.songoda.epicenchants.enums.EventType; @@ -19,19 +18,18 @@ import java.util.Set; import static com.songoda.epicenchants.utils.single.GeneralUtils.color; public class Enchant { - private String author; - private String identifier; - private Group group; - private int maxLevel; - private Set conflict; - private Set itemWhitelist; - private Set effectExecutors; - private List description; - private String format; - @Nullable - private BookItem bookItem; + private final String author; + private final String identifier; + private final Group group; + private final int maxLevel; + private final Set conflict; + private final Set itemWhitelist; + private final Set effectExecutors; + private final List description; + private final String format; + private final @Nullable BookItem bookItem; - Enchant(String author, String identifier, Group group, int maxLevel, Set conflict, Set itemWhitelist, Set effectExecutors, List description, String format, BookItem bookItem) { + Enchant(String author, String identifier, Group group, int maxLevel, Set conflict, Set itemWhitelist, Set effectExecutors, List description, String format, @Nullable BookItem bookItem) { this.author = author; this.identifier = identifier; this.group = group; @@ -49,26 +47,26 @@ public class Enchant { } public void onAction(@NotNull Player user, @Nullable LivingEntity opponent, Event event, int level, TriggerType triggerType, EventType eventType) { - effectExecutors.forEach(effect -> effect.testAndRun(user, opponent, level, triggerType, event, eventType)); + this.effectExecutors.forEach(effect -> effect.testAndRun(user, opponent, level, triggerType, event, eventType)); } public BookItem getBook() { - return bookItem != null ? bookItem : group.getBookItem(); + return this.bookItem != null ? this.bookItem : this.group.getBookItem(); } public String getFormat(int level, boolean roman) { - String output = format.isEmpty() ? group.getFormat() : format; + String output = this.format.isEmpty() ? this.group.getFormat() : this.format; output = output - .replace("{level}", "" + (roman ? RomanNumber.toRoman(level) : level)) - .replace("{enchant}", "" + identifier) - .replace("{group_color}", "" + group.getColor()); + .replace("{level}", String.valueOf(roman ? RomanNumber.toRoman(level) : level)) + .replace("{enchant}", this.identifier) + .replace("{group_color}", this.group.getColor()); return color(output); } public String getAuthor() { - return author; + return this.author; } public String getIdentifier() { @@ -184,7 +182,7 @@ public class Enchant { } public Enchant build() { - return new Enchant(author, identifier, group, maxLevel, conflict, itemWhitelist, effectExecutors, description, format, bookItem); + return new Enchant(this.author, this.identifier, this.group, this.maxLevel, this.conflict, this.itemWhitelist, this.effectExecutors, this.description, this.format, this.bookItem); } public String toString() { diff --git a/src/main/java/com/songoda/epicenchants/objects/Group.java b/src/main/java/com/songoda/epicenchants/objects/Group.java index bde2453..c7b7771 100644 --- a/src/main/java/com/songoda/epicenchants/objects/Group.java +++ b/src/main/java/com/songoda/epicenchants/objects/Group.java @@ -1,16 +1,19 @@ package com.songoda.epicenchants.objects; public class Group { - private String identifier; - private String name; - private String format; - private String color; - private String descriptionColor; - private int slotsUsed; - private BookItem bookItem; - private int destroyRateMin, destroyRateMax, successRateMin, successRateMax; - private int tinkererExp; - private int order; + private final String identifier; + private final String name; + private final String format; + private final String color; + private final String descriptionColor; + private final int slotsUsed; + private final BookItem bookItem; + private final int destroyRateMin; + private final int destroyRateMax; + private final int successRateMin; + private final int successRateMax; + private final int tinkererExp; + private final int order; Group(String identifier, String name, String format, String color, String descriptionColor, int slotsUsed, BookItem bookItem, int destroyRateMin, int destroyRateMax, int successRateMin, int successRateMax, int tinkererExp, int order) { this.identifier = identifier; @@ -168,7 +171,7 @@ public class Group { } public Group build() { - return new Group(identifier, name, format, color, descriptionColor, slotsUsed, bookItem, destroyRateMin, destroyRateMax, successRateMin, successRateMax, tinkererExp, order); + return new Group(this.identifier, this.name, this.format, this.color, this.descriptionColor, this.slotsUsed, this.bookItem, this.destroyRateMin, this.destroyRateMax, this.successRateMin, this.successRateMax, this.tinkererExp, this.order); } public String toString() { diff --git a/src/main/java/com/songoda/epicenchants/objects/LeveledModifier.java b/src/main/java/com/songoda/epicenchants/objects/LeveledModifier.java index 6d1609e..f8d4d4f 100644 --- a/src/main/java/com/songoda/epicenchants/objects/LeveledModifier.java +++ b/src/main/java/com/songoda/epicenchants/objects/LeveledModifier.java @@ -17,15 +17,15 @@ public class LeveledModifier { } public double get(int level, double def, Player user, LivingEntity opponent) { - if (string == null || string.isEmpty()) { + if (this.string == null || this.string.isEmpty()) { return def; } - if (string.equalsIgnoreCase("MAX")) { + if (this.string.equalsIgnoreCase("MAX")) { return Integer.MAX_VALUE; } - String toTest = Placeholders.setPlaceholders(string, user, opponent, level); + String toTest = Placeholders.setPlaceholders(this.string, user, opponent, level); Object value = GeneralUtils.parseJS(toTest, "LeveledModifier", def); return value instanceof Double ? (double) value : (int) value; diff --git a/src/main/java/com/songoda/epicenchants/objects/Placeholder.java b/src/main/java/com/songoda/epicenchants/objects/Placeholder.java index 1b6fb76..7e4a326 100644 --- a/src/main/java/com/songoda/epicenchants/objects/Placeholder.java +++ b/src/main/java/com/songoda/epicenchants/objects/Placeholder.java @@ -1,8 +1,8 @@ package com.songoda.epicenchants.objects; public class Placeholder { - private String placeholder; - private Object toReplace; + private final String placeholder; + private final Object toReplace; private Placeholder(String placeholder, Object toReplace) { this.placeholder = "{" + placeholder + "}"; @@ -14,10 +14,10 @@ public class Placeholder { } public String getPlaceholder() { - return placeholder; + return this.placeholder; } public Object getToReplace() { - return toReplace; + return this.toReplace; } } diff --git a/src/main/java/com/songoda/epicenchants/utils/EnchantUtils.java b/src/main/java/com/songoda/epicenchants/utils/EnchantUtils.java index 2579dad..74714b6 100644 --- a/src/main/java/com/songoda/epicenchants/utils/EnchantUtils.java +++ b/src/main/java/com/songoda/epicenchants/utils/EnchantUtils.java @@ -2,6 +2,7 @@ package com.songoda.epicenchants.utils; import com.craftaro.core.third_party.de.tr7zw.nbtapi.NBTCompound; import com.craftaro.core.third_party.de.tr7zw.nbtapi.NBTItem; +import com.craftaro.core.utils.NumberUtils; import com.craftaro.core.utils.TextUtils; import com.songoda.epicenchants.EpicEnchants; import com.songoda.epicenchants.enums.EnchantResult; @@ -48,7 +49,7 @@ public class EnchantUtils { } public Tuple apply(ItemStack itemStack, Enchant enchant, int level, int successRate, int destroyRate) { - boolean hasProtection = new NBTItem(itemStack).hasKey("protected"); + boolean hasProtection = new NBTItem(itemStack).hasTag("protected"); Map currentEnchantMap = getEnchants(itemStack); Set currentIds = currentEnchantMap.keySet().stream().map(Enchant::getIdentifier).collect(Collectors.toSet()); @@ -69,7 +70,7 @@ public class EnchantUtils { if (!GeneralUtils.chance(successRate)) { if (GeneralUtils.chance(destroyRate)) { if (hasProtection) { - NBTItem nbtItem = new ItemBuilder(itemStack).removeLore(instance.getSpecialItems().getWhiteScrollLore()).nbt(); + NBTItem nbtItem = new ItemBuilder(itemStack).removeLore(this.instance.getSpecialItems().getWhiteScrollLore()).nbt(); nbtItem.removeKey("protected"); return Tuple.of(nbtItem.getItem(), PROTECTED); } @@ -81,14 +82,14 @@ public class EnchantUtils { ItemBuilder itemBuilder = new ItemBuilder(itemStack); if (hasProtection) { - itemBuilder.removeLore(instance.getSpecialItems().getWhiteScrollLore()); + itemBuilder.removeLore(this.instance.getSpecialItems().getWhiteScrollLore()); } itemBuilder.removeLore(enchant.getFormat(-1, Settings.ROMAN.getBoolean()).replace("-1", "").trim()); itemBuilder.addLore(enchant.getFormat(level, Settings.ROMAN.getBoolean())); if (hasProtection) { - itemBuilder.addLore(instance.getSpecialItems().getWhiteScrollLore()); + itemBuilder.addLore(this.instance.getSpecialItems().getWhiteScrollLore()); } NBTItem nbtItem = itemBuilder.nbt(); @@ -105,7 +106,7 @@ public class EnchantUtils { } NBTItem nbtItem = new NBTItem(itemStack); - if (!nbtItem.hasKey("enchants")) { + if (!nbtItem.hasTag("enchants")) { return Collections.emptyMap(); } @@ -115,8 +116,8 @@ public class EnchantUtils { return Collections.emptyMap(); } - return compound.getKeys().stream().filter(key -> instance.getEnchantManager().getValueUnsafe(key) != null) - .collect(Collectors.toMap(key -> instance.getEnchantManager().getValueUnsafe(key), compound::getInteger)); + return compound.getKeys().stream().filter(key -> this.instance.getEnchantManager().getValueUnsafe(key) != null) + .collect(Collectors.toMap(key -> this.instance.getEnchantManager().getValueUnsafe(key), compound::getInteger)); } public void handlePlayer(@NotNull Player player, @Nullable LivingEntity opponent, Event event, TriggerType triggerType) { @@ -155,26 +156,34 @@ public class EnchantUtils { public int getMaximumEnchantsCanApplyItem(ItemStack itemStack, Player p) { int max; - if (p.isOp()) return 100; // in theory no single item will have 100 enchantments at a time. - if (instance.getFileManager().getConfiguration("items/item-limits").contains("limits." + itemStack.getType().toString())) { - max = instance.getFileManager().getConfiguration("items/item-limits").getInt("limits." + itemStack.getType().toString()); + if (p.isOp()) { + return 100; // in theory, no single item will have 100 enchantments at a time. + } + if (this.instance.getFileManager().getConfiguration("items/item-limits").contains("limits." + itemStack.getType().toString())) { + max = this.instance.getFileManager().getConfiguration("items/item-limits").getInt("limits." + itemStack.getType().toString()); } else { - max = instance.getFileManager().getConfiguration("items/item-limits").getInt("default"); + max = this.instance.getFileManager().getConfiguration("items/item-limits").getInt("default"); } return max; } public int getMaximumEnchantsCanApply(Player p) { int max = 0; - if (p.isOp()) return 100; // in theory no single item will have 100 enchantments at a time. + if (p.isOp()) { + return 100; // in theory, no single item will have 100 enchantments at a time. + } for (PermissionAttachmentInfo effectivePermission : p.getEffectivePermissions()) { - if (!effectivePermission.getPermission().startsWith("epicenchants.maxapply.")) continue; + if (!effectivePermission.getPermission().startsWith("epicenchants.maxapply.")) { + continue; + } - String node[] = effectivePermission.getPermission().split("\\."); + String[] node = effectivePermission.getPermission().split("\\."); - if (Methods.isInt(node[node.length - 1])) { + if (NumberUtils.isInt(node[node.length - 1])) { int num = Integer.parseInt(node[node.length - 1]); - if (num > max) max = num; + if (num > max) { + max = num; + } } } return max; diff --git a/src/main/java/com/songoda/epicenchants/utils/Methods.java b/src/main/java/com/songoda/epicenchants/utils/Methods.java deleted file mode 100644 index 530525b..0000000 --- a/src/main/java/com/songoda/epicenchants/utils/Methods.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.songoda.epicenchants.utils; - -import org.bukkit.ChatColor; - -public class Methods { - public static boolean isInt(String number) { - if (number == null || number.equals("")) - return false; - try { - Integer.parseInt(number); - } catch (NumberFormatException e) { - return false; - } - return true; - } - - public static String formatText(String text) { - if (text == null || text.equals("")) - return ""; - return formatText(text, false); - } - - public static String formatText(String text, boolean cap) { - if (text == null || text.equals("")) - return ""; - if (cap) - text = text.substring(0, 1).toUpperCase() + text.substring(1); - return ChatColor.translateAlternateColorCodes('&', text); - } -} diff --git a/src/main/java/com/songoda/epicenchants/utils/SpecialItems.java b/src/main/java/com/songoda/epicenchants/utils/SpecialItems.java index cd7659b..94ec5dd 100644 --- a/src/main/java/com/songoda/epicenchants/utils/SpecialItems.java +++ b/src/main/java/com/songoda/epicenchants/utils/SpecialItems.java @@ -23,7 +23,7 @@ public class SpecialItems { } public ItemStack getWhiteScroll(int amount) { - NBTItem nbtItem = new ItemBuilder(instance.getFileManager().getConfiguration("items/special-items").getConfigurationSection("white-scroll")).nbt(); + NBTItem nbtItem = new ItemBuilder(this.instance.getFileManager().getConfiguration("items/special-items").getConfigurationSection("white-scroll")).nbt(); nbtItem.setBoolean("white-scroll", true); ItemStack itemStack = nbtItem.getItem(); @@ -34,7 +34,7 @@ public class SpecialItems { public ItemStack getBlackScroll(int amount, int chance) { int successRate = chance == -1 ? ThreadLocalRandom.current().nextInt(Settings.BLACK_MIN.getInt(), Settings.BLACK_MAX.getInt() + 1) : chance; - NBTItem nbtItem = new ItemBuilder(instance.getFileManager().getConfiguration("items/special-items").getConfigurationSection("black-scroll"), of("success-rate", successRate)).nbt(); + NBTItem nbtItem = new ItemBuilder(this.instance.getFileManager().getConfiguration("items/special-items").getConfigurationSection("black-scroll"), of("success-rate", successRate)).nbt(); nbtItem.setBoolean("black-scroll", true); nbtItem.setInteger("success-rate", successRate); @@ -47,7 +47,7 @@ public class SpecialItems { } public ItemStack getMysteryBook(Group group) { - NBTItem nbtItem = new ItemBuilder(instance.getFileManager().getConfiguration("items/special-items").getConfigurationSection("mystery-book"), + NBTItem nbtItem = new ItemBuilder(this.instance.getFileManager().getConfiguration("items/special-items").getConfigurationSection("mystery-book"), of("group-color", group.getColor()), of("group-name", group.getName())).nbt(); @@ -57,12 +57,12 @@ public class SpecialItems { } public ItemStack getSecretDust(NBTItem book) { - Group group = instance.getEnchantManager().getValueUnsafe(book.getString("enchant")).getGroup(); + Group group = this.instance.getEnchantManager().getValueUnsafe(book.getString("enchant")).getGroup(); return getSecretDust(group, (int) Math.floor(book.getInteger("success-rate") / 10.0)); } public ItemStack getSecretDust(Group group, int max) { - NBTItem nbtItem = new ItemBuilder(instance.getFileManager().getConfiguration("items/dusts").getConfigurationSection("secret-dust"), + NBTItem nbtItem = new ItemBuilder(this.instance.getFileManager().getConfiguration("items/dusts").getConfigurationSection("secret-dust"), of("group-color", group.getColor()), of("group-name", group.getName()), of("max-rate", max), @@ -76,7 +76,7 @@ public class SpecialItems { } public ItemStack getDust(Group group, @Nullable String type, int percentage, boolean command) { - FileConfiguration dustConfig = instance.getFileManager().getConfiguration("items/dusts"); + FileConfiguration dustConfig = this.instance.getFileManager().getConfiguration("items/dusts"); int random = ThreadLocalRandom.current().nextInt(101); int counter = 0; @@ -119,6 +119,6 @@ public class SpecialItems { } public String getWhiteScrollLore() { - return color(instance.getFileManager().getConfiguration("items/special-items").getString("white-scroll.format")); + return color(this.instance.getFileManager().getConfiguration("items/special-items").getString("white-scroll.format")); } } diff --git a/src/main/java/com/songoda/epicenchants/utils/Tuple.java b/src/main/java/com/songoda/epicenchants/utils/Tuple.java index a8e5185..fba3ff3 100644 --- a/src/main/java/com/songoda/epicenchants/utils/Tuple.java +++ b/src/main/java/com/songoda/epicenchants/utils/Tuple.java @@ -1,8 +1,8 @@ package com.songoda.epicenchants.utils; public class Tuple { - private key x; - private value y; + private final key x; + private final value y; public Tuple(key x, value y) { this.x = x; @@ -18,6 +18,6 @@ public class Tuple { } public static Tuple of(key x, value y) { - return new Tuple(x, y); + return new Tuple<>(x, y); } } diff --git a/src/main/java/com/songoda/epicenchants/utils/objects/FastInv.java b/src/main/java/com/songoda/epicenchants/utils/objects/FastInv.java index 6176048..b375872 100644 --- a/src/main/java/com/songoda/epicenchants/utils/objects/FastInv.java +++ b/src/main/java/com/songoda/epicenchants/utils/objects/FastInv.java @@ -55,9 +55,9 @@ public class FastInv implements InventoryHolder { runSync(() -> { if (type == InventoryType.CHEST && size > 0) { - inventory = Bukkit.createInventory(this, size, title); + this.inventory = Bukkit.createInventory(this, size, title); } else { - inventory = Bukkit.createInventory(this, type, title); + this.inventory = Bukkit.createInventory(this, type, title); } }); } @@ -124,7 +124,7 @@ public class FastInv implements InventoryHolder { } public InventoryClickEvent getEvent() { - return event; + return this.event; } } @@ -149,7 +149,7 @@ public class FastInv implements InventoryHolder { */ public FastInv addItem(ItemStack item, FastInvClickListener listener) { runSync(() -> { - int slot = inventory.firstEmpty(); + int slot = this.inventory.firstEmpty(); if (slot >= 0) { addItem(slot, item, listener); } @@ -180,12 +180,12 @@ public class FastInv implements InventoryHolder { */ public FastInv addItem(int slot, ItemStack item, FastInvClickListener listener) { runSync(() -> { - inventory.setItem(slot, item); + this.inventory.setItem(slot, item); if (listener != null) { - itemListeners.put(slot, listener); + this.itemListeners.put(slot, listener); } else { - itemListeners.remove(slot); + this.itemListeners.remove(slot); } }); @@ -253,10 +253,10 @@ public class FastInv implements InventoryHolder { * @return This FastInv instance, for chaining. */ public FastInv edge(ItemStack item) { - int height = inventory.getSize() / 9; + int height = this.inventory.getSize() / 9; addItem(0, 9, item); - addItem(inventory.getSize() - 9, inventory.getSize() - 1, item); + addItem(this.inventory.getSize() - 9, this.inventory.getSize() - 1, item); for (int i = 0; i < height; i++) { addItem(i * 9, item); @@ -284,8 +284,8 @@ public class FastInv implements InventoryHolder { public FastInv fill(ItemStack itemStack) { runSync(() -> { - for (int i = 0; i < inventory.getSize(); i++) { - if (inventory.getItem(i) == null) { + for (int i = 0; i < this.inventory.getSize(); i++) { + if (this.inventory.getItem(i) == null) { addItem(i, itemStack); } } @@ -301,7 +301,7 @@ public class FastInv implements InventoryHolder { * @return This FastInv instance, for chaining. */ public FastInv onClose(FastInvCloseListener listener) { - closeListeners.add(listener); + this.closeListeners.add(listener); return this; } @@ -313,7 +313,7 @@ public class FastInv implements InventoryHolder { * @return This FastInv instance, for chaining. */ public FastInv onClick(FastInvClickListener listener) { - clickListeners.add(listener); + this.clickListeners.add(listener); return this; } @@ -339,7 +339,7 @@ public class FastInv implements InventoryHolder { * @return This FastInv instance, for chaining */ public FastInv onUpdate(long delay, long period, Runnable runnable) { - tasks.add(Bukkit.getScheduler().runTaskTimer(plugin, runnable, delay, period)); + this.tasks.add(Bukkit.getScheduler().runTaskTimer(plugin, runnable, delay, period)); return this; } @@ -349,15 +349,15 @@ public class FastInv implements InventoryHolder { * @param player The player to open the menu. */ public void open(Player player) { - Bukkit.getScheduler().runTask(plugin, () -> player.openInventory(inventory)); + Bukkit.getScheduler().runTask(plugin, () -> player.openInventory(this.inventory)); } /** * Cancel all tasks. */ public void cancelTasks() { - tasks.forEach(BukkitTask::cancel); - tasks.clear(); + this.tasks.forEach(BukkitTask::cancel); + this.tasks.clear(); } /** @@ -380,13 +380,13 @@ public class FastInv implements InventoryHolder { */ @Override public Inventory getInventory() { - return inventory; + return this.inventory; } /** - * Set if the tasks will be cancel on menus close. + * Set if the tasks will be canceled on menus close. * - * @param cancelTasksOnClose Set if the tasks will be cancel + * @param cancelTasksOnClose Set if the tasks will be canceled * * @return This FastInv instance, for chaining. */ @@ -420,7 +420,7 @@ public class FastInv implements InventoryHolder { * @return This associated FastInv instance. */ public FastInv getInventory() { - return inventory; + return this.inventory; } /** @@ -429,7 +429,7 @@ public class FastInv implements InventoryHolder { * @return the player who clicked. */ public Player getPlayer() { - return player; + return this.player; } /** @@ -438,11 +438,11 @@ public class FastInv implements InventoryHolder { * @return Whether the event was cancelled. */ public boolean isCancelled() { - return cancelled; + return this.cancelled; } /** - * Set if the event will be cancel or not. + * Set if the event will be canceled or not. * * @param cancel Whether the event should be cancelled. */ diff --git a/src/main/java/com/songoda/epicenchants/utils/objects/FileLocation.java b/src/main/java/com/songoda/epicenchants/utils/objects/FileLocation.java index d0da630..6435613 100644 --- a/src/main/java/com/songoda/epicenchants/utils/objects/FileLocation.java +++ b/src/main/java/com/songoda/epicenchants/utils/objects/FileLocation.java @@ -19,22 +19,22 @@ public class FileLocation { } public String getResourcePath(String dir) { - return (versionDependent ? "version-dependent/" + dir + "/" : "") + path; + return (this.versionDependent ? "version-dependent/" + dir + "/" : "") + this.path; } public boolean isDirectory() { - return path.endsWith("/"); + return this.path.endsWith("/"); } public boolean isRequired() { - return required; + return this.required; } public boolean isVersionDependent() { - return versionDependent; + return this.versionDependent; } public String getPath() { - return path; + return this.path; } } diff --git a/src/main/java/com/songoda/epicenchants/utils/objects/ItemBuilder.java b/src/main/java/com/songoda/epicenchants/utils/objects/ItemBuilder.java index 94d0e8f..67cf786 100644 --- a/src/main/java/com/songoda/epicenchants/utils/objects/ItemBuilder.java +++ b/src/main/java/com/songoda/epicenchants/utils/objects/ItemBuilder.java @@ -27,7 +27,6 @@ import java.util.stream.Collectors; import static com.songoda.epicenchants.utils.single.GeneralUtils.color; public class ItemBuilder { - private final ItemStack item; private ItemMeta meta; private final Set enchantmentWrappers; @@ -54,8 +53,8 @@ public class ItemBuilder { public ItemBuilder(ConfigurationSection section, Player player, Placeholder... placeholders) { this(section, placeholders); - if (XMaterial.PLAYER_HEAD.isSimilar(item)) { - ((SkullMeta) item.getItemMeta()).setOwner(player.getName()); + if (XMaterial.PLAYER_HEAD.isSimilar(this.item)) { + ((SkullMeta) this.item.getItemMeta()).setOwner(player.getName()); } } @@ -120,11 +119,11 @@ public class ItemBuilder { * Name: */ public boolean hasName() { - return meta.hasDisplayName(); + return this.meta.hasDisplayName(); } public ItemBuilder name(String name) { - meta.setDisplayName(name); + this.meta.setDisplayName(name); return this; } @@ -132,7 +131,7 @@ public class ItemBuilder { * Lore: */ public boolean hasLore() { - return meta.hasLore(); + return this.meta.hasLore(); } public ItemBuilder lore(String... lore) { @@ -140,37 +139,37 @@ public class ItemBuilder { } public ItemBuilder lore(List lore) { - meta.setLore(lore); + this.meta.setLore(lore); return this; } public ItemBuilder addLore(List lore) { - if (!meta.hasLore()) { - meta.setLore(lore); + if (!this.meta.hasLore()) { + this.meta.setLore(lore); return this; } - List toAdd = meta.getLore(); + List toAdd = this.meta.getLore(); toAdd.addAll(lore); - meta.setLore(toAdd); + this.meta.setLore(toAdd); return this; } public ItemBuilder removeLore(String string) { - if (meta == null || !meta.hasLore()) { + if (this.meta == null || !this.meta.hasLore()) { return this; } - meta.setLore(meta.getLore().stream().filter(s -> !s.startsWith(string)).collect(Collectors.toList())); + this.meta.setLore(this.meta.getLore().stream().filter(s -> !s.startsWith(string)).collect(Collectors.toList())); return this; } public ItemBuilder removeLore(int index) { - if (!meta.hasLore()) { + if (!this.meta.hasLore()) { return this; } - List lore = meta.getLore(); + List lore = this.meta.getLore(); if (index >= lore.size()) { return this; @@ -178,7 +177,7 @@ public class ItemBuilder { lore.remove(index); - meta.setLore(lore); + this.meta.setLore(lore); return this; } @@ -190,29 +189,29 @@ public class ItemBuilder { * Enchantments: */ public boolean hasEnchants() { - return meta.hasEnchants(); + return this.meta.hasEnchants(); } public boolean hasEnchant(Enchantment enchantment) { - return meta.hasEnchant(enchantment); + return this.meta.hasEnchant(enchantment); } public boolean hasConflictingEnchant(Enchantment enchantment) { - return meta.hasConflictingEnchant(enchantment); + return this.meta.hasConflictingEnchant(enchantment); } public ItemBuilder addEnchant(Enchantment enchantment, int level) { - meta.addEnchant(enchantment, level, true); + this.meta.addEnchant(enchantment, level, true); return this; } public ItemBuilder removeEnchant(Enchantment enchantment) { - meta.removeEnchant(enchantment); + this.meta.removeEnchant(enchantment); return this; } public ItemBuilder addEnchantWrapper(EnchantmentWrapper enchantmentWrapper) { - enchantmentWrappers.add(enchantmentWrapper); + this.enchantmentWrappers.add(enchantmentWrapper); return this; } @@ -220,21 +219,21 @@ public class ItemBuilder { * Skulls: */ public boolean hasSkullOwner() { - return ((SkullMeta) meta).hasOwner(); + return ((SkullMeta) this.meta).hasOwner(); } public String getSkullOwner() { - return ((SkullMeta) meta).getOwner(); + return ((SkullMeta) this.meta).getOwner(); } public ItemBuilder skullOwner(String owner) { - item.setDurability((short) 3); - ((SkullMeta) meta).setOwner(owner); + this.item.setDurability((short) 3); + ((SkullMeta) this.meta).setOwner(owner); return this; } public ItemBuilder durability(int durability) { - item.setDurability((short) durability); + this.item.setDurability((short) durability); return this; } @@ -242,16 +241,16 @@ public class ItemBuilder { * Flags: */ public boolean hasFlag(ItemFlag flag) { - return meta.hasItemFlag(flag); + return this.meta.hasItemFlag(flag); } public ItemBuilder addFlags(ItemFlag... flags) { - meta.addItemFlags(flags); + this.meta.addItemFlags(flags); return this; } public ItemBuilder removeFlags(ItemFlag... flags) { - meta.removeItemFlags(flags); + this.meta.removeItemFlags(flags); return this; } @@ -263,30 +262,30 @@ public class ItemBuilder { * Build the ItemStack. */ public ItemStack build() { - item.setItemMeta(meta); - return item; + this.item.setItemMeta(this.meta); + return this.item; } public ItemStack buildWithWrappers(int level, Player user, LivingEntity opponent) { - item.setItemMeta(meta); - enchantmentWrappers.forEach(enchant -> item.addUnsafeEnchantment(enchant.getEnchantment(), enchant.getAmplifier(level, user, opponent))); - return item; + this.item.setItemMeta(this.meta); + this.enchantmentWrappers.forEach(enchant -> this.item.addUnsafeEnchantment(enchant.getEnchantment(), enchant.getAmplifier(level, user, opponent))); + return this.item; } public Map getEnchants() { - return meta.getEnchants(); + return this.meta.getEnchants(); } public Set getFlags() { - return meta.getItemFlags(); + return this.meta.getItemFlags(); } public List getLore() { - return meta.getLore(); + return this.meta.getLore(); } public ItemMeta getMeta() { - return meta; + return this.meta; } /* @@ -294,6 +293,6 @@ public class ItemBuilder { */ public String getName() { - return meta.getDisplayName(); + return this.meta.getDisplayName(); } } diff --git a/src/main/java/com/songoda/epicenchants/utils/settings/Settings.java b/src/main/java/com/songoda/epicenchants/utils/settings/Settings.java index 652f26e..5f3d025 100644 --- a/src/main/java/com/songoda/epicenchants/utils/settings/Settings.java +++ b/src/main/java/com/songoda/epicenchants/utils/settings/Settings.java @@ -8,25 +8,24 @@ import com.songoda.epicenchants.EpicEnchants; import java.util.stream.Collectors; public class Settings { + static final Config CONFIG = EpicEnchants.getPlugin(EpicEnchants.class).getCoreConfig(); - static final Config config = EpicEnchants.getInstance().getCoreConfig(); + public static final ConfigSetting ROMAN = new ConfigSetting(CONFIG, "Main.Roman Numerals", true); - public static final ConfigSetting ROMAN = new ConfigSetting(config, "Main.Roman Numerals", true); + public static final ConfigSetting BLACK_MIN = new ConfigSetting(CONFIG, "Main.Black Scroll Min", 20); + public static final ConfigSetting BLACK_MAX = new ConfigSetting(CONFIG, "Main.Black Scroll Max", 100); - public static final ConfigSetting BLACK_MIN = new ConfigSetting(config, "Main.Black Scroll Min", 20); - public static final ConfigSetting BLACK_MAX = new ConfigSetting(config, "Main.Black Scroll Max", 100); - - public static final ConfigSetting ECONOMY_PLUGIN = new ConfigSetting(config, "Main.Economy", EconomyManager.getEconomy() == null ? "Vault" : EconomyManager.getEconomy().getName(), + public static final ConfigSetting ECONOMY_PLUGIN = new ConfigSetting(CONFIG, "Main.Economy", EconomyManager.getEconomy() == null ? "Vault" : EconomyManager.getEconomy().getName(), "Which economy plugin should be used?", "Supported plugins you have installed: \"" + EconomyManager.getManager().getRegisteredPlugins().stream().collect(Collectors.joining("\", \"")) + "\"."); - public static final ConfigSetting GLASS_TYPE_1 = new ConfigSetting(config, "Interfaces.Glass Type 1", 7); - public static final ConfigSetting GLASS_TYPE_2 = new ConfigSetting(config, "Interfaces.Glass Type 2", 11); - public static final ConfigSetting GLASS_TYPE_3 = new ConfigSetting(config, "Interfaces.Glass Type 3", 3); + public static final ConfigSetting GLASS_TYPE_1 = new ConfigSetting(CONFIG, "Interfaces.Glass Type 1", 7); + public static final ConfigSetting GLASS_TYPE_2 = new ConfigSetting(CONFIG, "Interfaces.Glass Type 2", 11); + public static final ConfigSetting GLASS_TYPE_3 = new ConfigSetting(CONFIG, "Interfaces.Glass Type 3", 3); - public static final ConfigSetting FIRST_LOAD = new ConfigSetting(config, "System.First Load", true); + public static final ConfigSetting FIRST_LOAD = new ConfigSetting(CONFIG, "System.First Load", true); - public static final ConfigSetting LANGUGE_MODE = new ConfigSetting(config, "System.Language Mode", "en_US", + public static final ConfigSetting LANGUGE_MODE = new ConfigSetting(CONFIG, "System.Language Mode", "en_US", "The enabled language file.", "More language files (if available) can be found in the plugins data folder."); @@ -35,18 +34,18 @@ public class Settings { * called after EconomyManager load */ public static void setupConfig() { - config.load(); - config.setAutoremove(true).setAutosave(true); + CONFIG.load(); + CONFIG.setAutoremove(true).setAutosave(true); // convert economy settings - if (config.getBoolean("Economy.Use Vault Economy") && EconomyManager.getManager().isEnabled("Vault")) { - config.set("Main.Economy", "Vault"); - } else if (config.getBoolean("Economy.Use Reserve Economy") && EconomyManager.getManager().isEnabled("Reserve")) { - config.set("Main.Economy", "Reserve"); - } else if (config.getBoolean("Economy.Use Player Points Economy") && EconomyManager.getManager().isEnabled("PlayerPoints")) { - config.set("Main.Economy", "PlayerPoints"); + if (CONFIG.getBoolean("Economy.Use Vault Economy") && EconomyManager.getManager().isEnabled("Vault")) { + CONFIG.set("Main.Economy", "Vault"); + } else if (CONFIG.getBoolean("Economy.Use Reserve Economy") && EconomyManager.getManager().isEnabled("Reserve")) { + CONFIG.set("Main.Economy", "Reserve"); + } else if (CONFIG.getBoolean("Economy.Use Player Points Economy") && EconomyManager.getManager().isEnabled("PlayerPoints")) { + CONFIG.set("Main.Economy", "PlayerPoints"); } - config.saveChanges(); + CONFIG.saveChanges(); } } diff --git a/src/main/java/com/songoda/epicenchants/utils/single/ConfigParser.java b/src/main/java/com/songoda/epicenchants/utils/single/ConfigParser.java index 5a9ff7a..f9eb97f 100644 --- a/src/main/java/com/songoda/epicenchants/utils/single/ConfigParser.java +++ b/src/main/java/com/songoda/epicenchants/utils/single/ConfigParser.java @@ -21,7 +21,7 @@ import java.util.stream.Collectors; import static com.songoda.epicenchants.utils.single.GeneralUtils.color; public class ConfigParser { - public static Enchant parseEnchant(EpicEnchants instance, FileConfiguration config) throws Exception { + public static Enchant parseEnchant(EpicEnchants instance, FileConfiguration config) { return Enchant.builder() .author("author") .identifier(config.getString("identifier")) diff --git a/src/main/java/com/songoda/epicenchants/utils/single/ItemGroup.java b/src/main/java/com/songoda/epicenchants/utils/single/ItemGroup.java index f9bd2a7..e860f86 100644 --- a/src/main/java/com/songoda/epicenchants/utils/single/ItemGroup.java +++ b/src/main/java/com/songoda/epicenchants/utils/single/ItemGroup.java @@ -1,13 +1,15 @@ package com.songoda.epicenchants.utils.single; +import com.craftaro.core.compatibility.CompatibleMaterial; import com.craftaro.core.third_party.com.cryptomorin.xseries.XMaterial; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; -import com.craftaro.core.compatibility.CompatibleMaterial; import org.apache.commons.lang.StringUtils; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; +import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Optional; @@ -15,36 +17,35 @@ import java.util.Set; import java.util.stream.Collectors; import static com.craftaro.core.third_party.com.cryptomorin.xseries.XMaterial.*; -import static com.songoda.epicenchants.utils.single.ItemGroup.Group.*; public class ItemGroup { private final Multimap groupMap; public ItemGroup() { - groupMap = HashMultimap.create(); + this.groupMap = HashMultimap.create(); - groupMap.putAll(AXES, Arrays.asList(NETHERITE_AXE, DIAMOND_AXE, GOLDEN_AXE, IRON_AXE, STONE_AXE, WOODEN_AXE)); + this.groupMap.putAll(ItemGroup.Group.AXES, Arrays.asList(NETHERITE_AXE, DIAMOND_AXE, GOLDEN_AXE, IRON_AXE, STONE_AXE, WOODEN_AXE)); - groupMap.putAll(PICKAXES, Arrays.asList(NETHERITE_PICKAXE, DIAMOND_PICKAXE, GOLDEN_PICKAXE, IRON_PICKAXE, STONE_PICKAXE, WOODEN_PICKAXE)); + this.groupMap.putAll(ItemGroup.Group.PICKAXES, Arrays.asList(NETHERITE_PICKAXE, DIAMOND_PICKAXE, GOLDEN_PICKAXE, IRON_PICKAXE, STONE_PICKAXE, WOODEN_PICKAXE)); - groupMap.putAll(HOES, Arrays.asList(NETHERITE_HOE, DIAMOND_HOE, GOLDEN_HOE, IRON_HOE, STONE_HOE, WOODEN_HOE)); + this.groupMap.putAll(ItemGroup.Group.HOES, Arrays.asList(NETHERITE_HOE, DIAMOND_HOE, GOLDEN_HOE, IRON_HOE, STONE_HOE, WOODEN_HOE)); - groupMap.putAll(SHOVELS, Arrays.asList(NETHERITE_SHOVEL, DIAMOND_SHOVEL, GOLDEN_SHOVEL, IRON_SHOVEL, STONE_SHOVEL, WOODEN_SHOVEL)); + this.groupMap.putAll(ItemGroup.Group.SHOVELS, Arrays.asList(NETHERITE_SHOVEL, DIAMOND_SHOVEL, GOLDEN_SHOVEL, IRON_SHOVEL, STONE_SHOVEL, WOODEN_SHOVEL)); - groupMap.putAll(SWORDS, Arrays.asList(NETHERITE_SWORD, DIAMOND_SWORD, GOLDEN_SWORD, IRON_SWORD, STONE_SWORD, WOODEN_SWORD)); + this.groupMap.putAll(ItemGroup.Group.SWORDS, Arrays.asList(NETHERITE_SWORD, DIAMOND_SWORD, GOLDEN_SWORD, IRON_SWORD, STONE_SWORD, WOODEN_SWORD)); - groupMap.put(BOWS, BOW); + this.groupMap.put(ItemGroup.Group.BOWS, BOW); - groupMap.putAll(BOOTS, Arrays.asList(NETHERITE_BOOTS, DIAMOND_BOOTS, GOLDEN_BOOTS, IRON_BOOTS, LEATHER_BOOTS)); + this.groupMap.putAll(ItemGroup.Group.BOOTS, Arrays.asList(NETHERITE_BOOTS, DIAMOND_BOOTS, GOLDEN_BOOTS, IRON_BOOTS, LEATHER_BOOTS)); - groupMap.putAll(LEGGINGS, Arrays.asList(NETHERITE_LEGGINGS, DIAMOND_LEGGINGS, GOLDEN_LEGGINGS, IRON_LEGGINGS, LEATHER_LEGGINGS)); + this.groupMap.putAll(ItemGroup.Group.LEGGINGS, Arrays.asList(NETHERITE_LEGGINGS, DIAMOND_LEGGINGS, GOLDEN_LEGGINGS, IRON_LEGGINGS, LEATHER_LEGGINGS)); - groupMap.putAll(CHESTPLATES, Arrays.asList(NETHERITE_CHESTPLATE, DIAMOND_CHESTPLATE, GOLDEN_CHESTPLATE, IRON_CHESTPLATE, LEATHER_CHESTPLATE)); + this.groupMap.putAll(ItemGroup.Group.CHESTPLATES, Arrays.asList(NETHERITE_CHESTPLATE, DIAMOND_CHESTPLATE, GOLDEN_CHESTPLATE, IRON_CHESTPLATE, LEATHER_CHESTPLATE)); - groupMap.putAll(HELMETS, Arrays.asList(NETHERITE_HELMET, DIAMOND_HELMET, GOLDEN_HELMET, IRON_HELMET, LEATHER_HELMET)); + this.groupMap.putAll(ItemGroup.Group.HELMETS, Arrays.asList(NETHERITE_HELMET, DIAMOND_HELMET, GOLDEN_HELMET, IRON_HELMET, LEATHER_HELMET)); - groupMap.put(TRIDENTS, TRIDENT); + this.groupMap.put(ItemGroup.Group.TRIDENTS, TRIDENT); } public Set get(String key) { @@ -60,9 +61,11 @@ public class ItemGroup { } public boolean isValid(XMaterial material) { - for (Group group : groupMap.keys()) - if (getMaterials(group).contains(material)) + for (Group group : this.groupMap.keys()) { + if (getMaterials(group).contains(material)) { return true; + } + } return false; } @@ -72,7 +75,7 @@ public class ItemGroup { for (int i = 0; i < 5; i++) { getGroup(materials).ifPresent(group -> { groups.add(group.getName()); - materials.removeAll(getMaterials(group).stream().collect(Collectors.toList())); + new ArrayList<>(getMaterials(group)).forEach(materials::remove); }); } @@ -81,25 +84,29 @@ public class ItemGroup { } public Optional getGroup(Set materials) { - Optional group = Arrays.stream(Group.values()) - .filter(s -> !s.getChildren().isEmpty() && s.getChildren().stream().allMatch(child -> materials.containsAll(groupMap.get(child)))) - .findFirst(); - - if (group.isPresent()) { - return group; + for (Group group : Group.values()) { + if (!group.getChildren().isEmpty() && group.getChildren().stream().allMatch(child -> materials.containsAll(this.groupMap.get(child)))) { + return Optional.of(group); + } } - return groupMap.asMap().entrySet().stream().filter(s -> materials.containsAll(s.getValue())).map(Map.Entry::getKey).findFirst(); + for (Map.Entry> entry : this.groupMap.asMap().entrySet()) { + if (materials.containsAll(entry.getValue())) { + return Optional.of(entry.getKey()); + } + } + return Optional.empty(); } public Set getMaterials(Group group) { Set out = new HashSet<>(); for (int i = 0; i < 5; i++) { - if (group.getChildren().isEmpty()) - out.addAll(groupMap.get(group)); - else + if (group.getChildren().isEmpty()) { + out.addAll(this.groupMap.get(group)); + } else { out.addAll(group.getChildren().stream().map(this::getMaterials).flatMap(Collection::stream).collect(Collectors.toSet())); + } } return out; @@ -126,11 +133,16 @@ public class ItemGroup { private final Set children; Group(Group... child) { - children = child == null ? new HashSet<>() : new HashSet<>(Arrays.asList(child)); + this.children = child == null ? Collections.emptySet() : new HashSet<>(Arrays.asList(child)); } public static Optional from(String key) { - return Arrays.stream(values()).filter(s -> s.toString().equalsIgnoreCase(key)).findFirst(); + for (Group group : values()) { + if (group.toString().equalsIgnoreCase(key)) { + return Optional.of(group); + } + } + return Optional.empty(); } public String getName() { diff --git a/src/main/java/com/songoda/epicenchants/utils/single/Placeholders.java b/src/main/java/com/songoda/epicenchants/utils/single/Placeholders.java index d692579..ad3b822 100644 --- a/src/main/java/com/songoda/epicenchants/utils/single/Placeholders.java +++ b/src/main/java/com/songoda/epicenchants/utils/single/Placeholders.java @@ -30,7 +30,6 @@ import java.util.stream.Collectors; import static com.songoda.epicenchants.utils.single.GeneralUtils.getHeldItem; public class Placeholders { - private static final Map> EVENT_FUNCTIONS = new HashMap>() {{ put("{block_type}", event -> { if (event instanceof BlockBreakEvent) { diff --git a/src/main/java/com/songoda/epicenchants/utils/single/RomanNumber.java b/src/main/java/com/songoda/epicenchants/utils/single/RomanNumber.java index 58a04e9..3fdf8ae 100644 --- a/src/main/java/com/songoda/epicenchants/utils/single/RomanNumber.java +++ b/src/main/java/com/songoda/epicenchants/utils/single/RomanNumber.java @@ -3,7 +3,7 @@ package com.songoda.epicenchants.utils.single; import java.util.TreeMap; public class RomanNumber { - private final static TreeMap TREE_MAP = new TreeMap() {{ + private static final TreeMap TREE_MAP = new TreeMap() {{ put(1000, "M"); put(900, "CM"); put(500, "D"); diff --git a/src/main/java/com/songoda/epicenchants/wrappers/EnchantmentWrapper.java b/src/main/java/com/songoda/epicenchants/wrappers/EnchantmentWrapper.java index e54f636..6eebc93 100644 --- a/src/main/java/com/songoda/epicenchants/wrappers/EnchantmentWrapper.java +++ b/src/main/java/com/songoda/epicenchants/wrappers/EnchantmentWrapper.java @@ -8,8 +8,8 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class EnchantmentWrapper { - private LeveledModifier amplifier; - private Enchantment enchantment; + private final LeveledModifier amplifier; + private final Enchantment enchantment; EnchantmentWrapper(LeveledModifier amplifier, Enchantment enchantment) { this.amplifier = amplifier; @@ -21,11 +21,11 @@ public class EnchantmentWrapper { } public int getAmplifier(int level, @NotNull Player user, @Nullable LivingEntity opponent) { - return (int) amplifier.get(level, 0, user, opponent); + return (int) this.amplifier.get(level, 0, user, opponent); } public Enchantment getEnchantment() { - return enchantment; + return this.enchantment; } public static class EnchantmentWrapperBuilder { @@ -46,7 +46,7 @@ public class EnchantmentWrapper { } public EnchantmentWrapper build() { - return new EnchantmentWrapper(amplifier, enchantment); + return new EnchantmentWrapper(this.amplifier, this.enchantment); } public String toString() { diff --git a/src/main/resources/version-dependent/legacy/items/item-limits.yml b/src/main/resources/version-dependent/legacy/items/item-limits.yml index df91196..5acaa27 100644 --- a/src/main/resources/version-dependent/legacy/items/item-limits.yml +++ b/src/main/resources/version-dependent/legacy/items/item-limits.yml @@ -1,4 +1,4 @@ -# each item that's not specified in limits category will use default value +# each item that's not specified in the 'limits' category will use default value default: 5 # Example of some of the items @@ -6,4 +6,3 @@ limits: DIAMOND_SWORD: 5 IRON_SWORD: 2 STONE_SWORD: 1 -