From e35c251827c8c0ba635652d941edb6c512353b44 Mon Sep 17 00:00:00 2001 From: Pim van der Loos Date: Fri, 26 Oct 2018 14:53:58 +0200 Subject: [PATCH] QoL Improvements, bug fixes. - Fixed 1.13 and 1.13.1/1.13.2 bug with armor value retrieval (nbt changed in 1.13). - Added en_US.txt as translation file for easier translation stuff. - Moved more strings to translation file. - Added 1.13.1 and 1.13.2 support. --- pom.xml | 8 +- .../armoredElytra/ArmoredElytra.java | 574 ++++----- .../handlers/CommandHandler.java | 20 +- .../armoredElytra/handlers/EventHandlers.java | 1026 ++++++++--------- .../armoredElytra/handlers/LoginHandler.java | 52 +- .../armoredElytra/handlers/Uninstaller.java | 118 +- .../armoredElytra/nms/NBTEditor_V1_10_R1.java | 195 ++-- .../armoredElytra/nms/NBTEditor_V1_11_R1.java | 195 ++-- .../armoredElytra/nms/NBTEditor_V1_12_R1.java | 197 ++-- .../armoredElytra/nms/NBTEditor_V1_13_R1.java | 201 ++-- .../armoredElytra/nms/NBTEditor_V1_13_R2.java | 121 ++ .../armoredElytra/util/ArmorTier.java | 6 +- .../armoredElytra/util/ConfigLoader.java | 365 +++--- .../armoredElytra/util/ConfigOption.java | 195 ++-- .../armoredElytra/util/Messages.java | 79 ++ .../pim16aap2/armoredElytra/util/Metrics.java | 204 ++-- .../pim16aap2/armoredElytra/util/Update.java | 66 +- src/main/resources/en_US.txt | 12 + src/main/resources/plugin.yml | 2 +- 19 files changed, 1957 insertions(+), 1679 deletions(-) create mode 100644 src/main/java/nl/pim16aap2/armoredElytra/nms/NBTEditor_V1_13_R2.java create mode 100644 src/main/java/nl/pim16aap2/armoredElytra/util/Messages.java create mode 100644 src/main/resources/en_US.txt diff --git a/pom.xml b/pom.xml index 7f33834..68cc2c9 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 nl.pim16aap2 ArmoredElytra - 2.4.2-SNAPSHOT + 2.4.6-SNAPSHOT @@ -40,6 +40,12 @@ 1.13-R0.1-SNAPSHOT provided + + org.spigotmc + spigot-1.13.1 + 1.13.1-R0.1-SNAPSHOT + provided + diff --git a/src/main/java/nl/pim16aap2/armoredElytra/ArmoredElytra.java b/src/main/java/nl/pim16aap2/armoredElytra/ArmoredElytra.java index 556f6ff..0bff5ab 100644 --- a/src/main/java/nl/pim16aap2/armoredElytra/ArmoredElytra.java +++ b/src/main/java/nl/pim16aap2/armoredElytra/ArmoredElytra.java @@ -20,234 +20,243 @@ import nl.pim16aap2.armoredElytra.nms.NBTEditor_V1_10_R1; import nl.pim16aap2.armoredElytra.nms.NBTEditor_V1_11_R1; import nl.pim16aap2.armoredElytra.nms.NBTEditor_V1_12_R1; import nl.pim16aap2.armoredElytra.nms.NBTEditor_V1_13_R1; +import nl.pim16aap2.armoredElytra.nms.NBTEditor_V1_13_R2; import nl.pim16aap2.armoredElytra.util.ArmorTier; import nl.pim16aap2.armoredElytra.util.ConfigLoader; +import nl.pim16aap2.armoredElytra.util.Messages; import nl.pim16aap2.armoredElytra.util.Metrics; import nl.pim16aap2.armoredElytra.util.Update; - + public class ArmoredElytra extends JavaPlugin implements Listener -{ - private NBTEditor nbtEditor; - private ConfigLoader config; +{ + private NBTEditor nbtEditor; + private Messages messages; + private ConfigLoader config; - private String usageDeniedMessage; - private String elytraReceivedMessage; - private String elytraLore; - private boolean upToDate; - private boolean uninstallMode; - private String leatherName, ironName, goldName, chainName, diamondName; - - @Override + private String leatherName, ironName, goldName, chainName, diamondName; + private String elytraReceivedMessage; + private String usageDeniedMessage; + private boolean uninstallMode; + private String elytraLore; + private boolean upToDate; + private String locale; + + @Override public void onEnable() - { - readConfigValues(); - - // Check if the user allows checking for updates. - if (config.getBool("checkForUpdates")) - { - // Check for updates in a new thread, so the server won't hang when it cannot contact the update servers. - Thread thread = new Thread(new Runnable() - { - @Override - public void run() - { - ArmoredElytra plugin = getPlugin(); - Update update = new Update(278437, plugin); - String latestVersion = update.getLatestVersion(); - - if (latestVersion == null) - plugin.myLogger(Level.WARNING, "Encountered problem contacting update servers! Please check manually! The error above does not affect the plugin!"); - else - { - String thisVersion = plugin.getDescription().getVersion(); - // Check if this is the latest version or not. - int updateStatus = update.versionCompare(latestVersion, thisVersion); - - if (updateStatus > 0) - { - // TODO: Insert download link to latest version. - // TODO: Use Spiget as backup? - // TODO: Add auto update option? - - // Load the loginHandler to show messages to the user when they join. - Bukkit.getPluginManager().registerEvents(new LoginHandler(plugin, "The Armored Elytra plugin is out of date!"), plugin); - plugin.myLogger(Level.INFO, "Plugin out of date! You are using version " + thisVersion + " but the latest version is version " + latestVersion + "!"); - plugin.setUpToDate(false); - } - else - { - plugin.setUpToDate(true); - plugin.myLogger(Level.INFO, "You seem to be using the latest version of this plugin!"); - } - } - } - - }); - thread.start(); - } - else - myLogger(Level.INFO, "Plugin update checking not enabled! You will not receive any messages about new updates for this plugin. Please consider turning this on in the config."); - - - - - // Are stats allowed? - if (config.getBool("allowStats")) - { - myLogger(Level.INFO, "Enabling stats! Thanks, it really helps!"); - @SuppressWarnings("unused") - Metrics metrics = new Metrics(this); - } - else - // Y u do dis? :( - myLogger(Level.INFO, "Stats disabled, not laoding stats :(... Please consider enabling it! I am a simple man, seeing higher user numbers helps me stay motivated!"); + { + this.readConfigValues(); + this.messages = new Messages(this); + this.readMessages(); + + // Check if the user allows checking for updates. + if (config.getBool("checkForUpdates")) + { + // Check for updates in a new thread, so the server won't hang when it cannot contact the update servers. + Thread thread = new Thread(new Runnable() + { + @Override + public void run() + { + ArmoredElytra plugin = getPlugin(); + Update update = new Update(278437, plugin); + String latestVersion = update.getLatestVersion(); + + if (latestVersion == null) + plugin.myLogger(Level.WARNING, "Encountered problem contacting update servers! Please check manually! The error above does not affect the plugin!"); + else + { + String thisVersion = plugin.getDescription().getVersion(); + // Check if this is the latest version or not. + int updateStatus = update.versionCompare(latestVersion, thisVersion); + + if (updateStatus > 0) + { + // Load the loginHandler to show messages to the user when they join. + Bukkit.getPluginManager().registerEvents(new LoginHandler(plugin, "The Armored Elytra plugin is out of date!"), plugin); + plugin.myLogger(Level.INFO, "Plugin out of date! You are using version " + thisVersion + " but the latest version is version " + latestVersion + "!"); + plugin.setUpToDate(false); + } + else + { + plugin.setUpToDate(true); + plugin.myLogger(Level.INFO, "You seem to be using the latest version of this plugin!"); + } + } + } + + }); + thread.start(); + } + else + myLogger(Level.INFO, "Plugin update checking not enabled! You will not receive any messages about new updates for this plugin. Please consider turning this on in the config."); + + // Are stats allowed? + if (config.getBool("allowStats")) + { + myLogger(Level.INFO, "Enabling stats! Thanks, it really helps!"); + @SuppressWarnings("unused") + Metrics metrics = new Metrics(this); + } + else + // Y u do dis? :( + myLogger(Level.INFO, "Stats disabled, not laoding stats :(... Please consider enabling it! I am a simple man, seeing higher user numbers helps me stay motivated!"); - - - - // Load the files for the correct version of Minecraft. - if (compatibleMCVer()) - { - Bukkit.getPluginManager().registerEvents(new EventHandlers(this, nbtEditor), this); - getCommand("ArmoredElytra").setExecutor(new CommandHandler(this, nbtEditor)); - } - else - { - myLogger(Level.WARNING, "Trying to load the plugin on an incompatible version of Minecraft! This plugin will NOT be enabled!"); - return; - } - - - - - // Load the plugin normally if not in uninstall mode. - if (!uninstallMode) - { - // Check if the user wants to disable durability penalty for flying with an armored elytra. - if (config.getBool("noFlightDurability")) - { - Bukkit.getPluginManager().registerEvents(new FlyDurabilityHandler(nbtEditor), this); - myLogger(Level.INFO, "Durability penalty for flying disabled!"); - } else - myLogger(Level.INFO, "Durability penalty for flying enabled!"); - - - // Log all allowed enchantments. - myLogger(Level.INFO, ("Allowed enchantments:")); - for (String s : config.getStringList("allowedEnchantments")) - myLogger(Level.INFO, " - " + s); - } - else - { - myLogger(Level.WARNING, "Plugin in uninstall mode!"); - Bukkit.getPluginManager().registerEvents(new Uninstaller(this, nbtEditor), this); - } - } - - public void readConfigValues() - { - // Load the settings from the config file. - this.config = new ConfigLoader(this); + this.locale = config.getString("languageFile"); + + + // Load the files for the correct version of Minecraft. + if (compatibleMCVer()) + { + Bukkit.getPluginManager().registerEvents(new EventHandlers(this, nbtEditor), this); + getCommand("ArmoredElytra").setExecutor(new CommandHandler(this, nbtEditor)); + } + else + { + myLogger(Level.WARNING, "Trying to load the plugin on an incompatible version of Minecraft! This plugin will NOT be enabled!"); + return; + } + + // Load the plugin normally if not in uninstall mode. + if (!uninstallMode) + { + // Check if the user wants to disable durability penalty for flying with an armored elytra. + if (config.getBool("noFlightDurability")) + { + Bukkit.getPluginManager().registerEvents(new FlyDurabilityHandler(nbtEditor), this); + myLogger(Level.INFO, "Durability penalty for flying disabled!"); + } + else + myLogger(Level.INFO, "Durability penalty for flying enabled!"); + + // Log all allowed enchantments. + myLogger(Level.INFO, ("Allowed enchantments:")); + for (String s : config.getStringList("allowedEnchantments")) + myLogger(Level.INFO, " - " + s); + } + else + { + myLogger(Level.WARNING, "Plugin in uninstall mode!"); + Bukkit.getPluginManager().registerEvents(new Uninstaller(this, nbtEditor), this); + } + } + + public void readConfigValues() + { + // Load the settings from the config file. + this.config = new ConfigLoader(this); - // Replace color codes by the corresponding colors. - this.usageDeniedMessage = config.getString("usageDeniedMessage" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1"); - this.elytraReceivedMessage = config.getString("elytraReceivedMessage" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1"); - this.elytraLore = config.getString("elytraLore" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1"); + // Check if the plugin should go into uninstall mode. + this.uninstallMode = config.getBool("uninstallMode"); + } + + public Messages getMyMessages() + { + return this.messages; + } + + private void readMessages() + { + // Replace color codes by the corresponding colors. + this.usageDeniedMessage = this.getMyMessages().getString("MESSAGES.UsageDenied" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1"); + this.elytraReceivedMessage = this.getMyMessages().getString("MESSAGES.ElytraReceived").replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1"); + this.elytraLore = this.getMyMessages().getString("MESSAGES.Lore" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1"); - this.leatherName = config.getString("leatherName" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1"); - this.goldName = config.getString("goldName" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1"); - this.chainName = config.getString("chainName" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1"); - this.ironName = config.getString("ironName" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1"); - this.diamondName = config.getString("diamondName" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1"); - - // Change the string to null if it says "NONE". - this.usageDeniedMessage = (Objects.equals(usageDeniedMessage, new String("NONE")) ? null : usageDeniedMessage ); - this.elytraReceivedMessage = (Objects.equals(elytraReceivedMessage, new String("NONE")) ? null : elytraReceivedMessage); - this.elytraLore = (Objects.equals(elytraLore, new String("NONE")) ? null : elytraLore ); - - // Check if the plugin should go into uninstall mode. - this.uninstallMode = config.getBool("uninstallMode"); - } - - // Returns true if this is the latest version of this plugin. - public boolean isUpToDate() - { - return upToDate; - } - - // Get this. - public ArmoredElytra getPlugin() - { - return this; - } - - // Returns the config handler. - public ConfigLoader getConfigLoader() - { - return config; - } - - // Send a message to a player in a specific color. - public void messagePlayer(Player player, ChatColor color, String s) - { - player.sendMessage(color + s); - } - - // Send a message to a player. - public void messagePlayer(Player player, String s) - { - messagePlayer(player, ChatColor.WHITE, s); - } - - // Send the usageDeniedMessage message to the player. - public void usageDeniedMessage(Player player, ArmorTier armorTier) - { - if (usageDeniedMessage != null) - { - String message = fillInArmorTierInStringNoColor(usageDeniedMessage, armorTier); - messagePlayer(player, ChatColor.RED, message); - } - } - - // Send the elytraReceivedMessage message to the player. - public void elytraReceivedMessage(Player player, ArmorTier armorTier) - { - if (elytraReceivedMessage != null) - { - String message = fillInArmorTierInStringNoColor(elytraReceivedMessage, armorTier); - messagePlayer(player, ChatColor.GREEN, message); - } - } - - // Replace %ARMOR_TIER% by the name of that armor tier in a string, but strip %ARMOR_TIER% of its color. - public String fillInArmorTierInStringNoColor(String string, ArmorTier armorTier) - { - return string.replace("%ARMOR_TIER%", ChatColor.stripColor(getArmoredElytrName(armorTier))); - } - - // Print a string to the log. - public void myLogger(Level level, String str) - { - Bukkit.getLogger().log(level, "[" + this.getName() + "] " + str); - } - - // Log message that only gets printed when debugging is enabled in the config file. - public void debugMsg(Level level, String str) - { - if (config.getBool("enableDebug")) - myLogger(level, str); - } - - // Give the provided player the provided item. - public void giveArmoredElytraToPlayer(Player player, ItemStack item) - { - if (item != null) - player.getInventory().addItem(item); - } - - // Check + initialize for the correct version of Minecraft. - public boolean compatibleMCVer() - { + this.leatherName = this.getMyMessages().getString("TIER.Leather" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1"); + this.goldName = this.getMyMessages().getString("TIER.Gold" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1"); + this.chainName = this.getMyMessages().getString("TIER.Chain" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1"); + this.ironName = this.getMyMessages().getString("TIER.Iron" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1"); + this.diamondName = this.getMyMessages().getString("TIER.Diamond" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1"); + + // Change the string to null if it says "NONE". + this.usageDeniedMessage = (Objects.equals(usageDeniedMessage, new String("NONE")) ? null : usageDeniedMessage ); + this.elytraReceivedMessage = (Objects.equals(elytraReceivedMessage, new String("NONE")) ? null : elytraReceivedMessage); + this.elytraLore = (Objects.equals(elytraLore, new String("NONE")) ? null : elytraLore ); + } + + // Returns true if this is the latest version of this plugin. + public boolean isUpToDate() + { + return upToDate; + } + + // Get this. + public ArmoredElytra getPlugin() + { + return this; + } + + // Returns the config handler. + public ConfigLoader getConfigLoader() + { + return config; + } + + // Send a message to a player in a specific color. + public void messagePlayer(Player player, ChatColor color, String str) + { + player.sendMessage(color + str); + } + + // Send a message to a player. + public void messagePlayer(Player player, String str) + { + messagePlayer(player, ChatColor.WHITE, str); + } + + // Send the usageDeniedMessage message to the player. + public void usageDeniedMessage(Player player, ArmorTier armorTier) + { + if (usageDeniedMessage != null) + { + String message = fillInArmorTierInStringNoColor(usageDeniedMessage, armorTier); + messagePlayer(player, ChatColor.RED, message); + } + } + + // Send the elytraReceivedMessage message to the player. + public void elytraReceivedMessage(Player player, ArmorTier armorTier) + { + if (elytraReceivedMessage != null) + { + String message = fillInArmorTierInStringNoColor(elytraReceivedMessage, armorTier); + messagePlayer(player, ChatColor.GREEN, message); + } + } + + // Replace %ARMOR_TIER% by the name of that armor tier in a string, but strip %ARMOR_TIER% of its color. + public String fillInArmorTierInStringNoColor(String string, ArmorTier armorTier) + { + return string.replace("%ARMOR_TIER%", ChatColor.stripColor(getArmoredElytrName(armorTier))); + } + + public String getLocale() + { + return locale == null ? "en_US" : locale; + } + + // Print a string to the log. + public void myLogger(Level level, String str) + { + Bukkit.getLogger().log(level, "[" + this.getName() + "] " + str); + } + + // Log message that only gets printed when debugging is enabled in the config file. + public void debugMsg(Level level, String str) + { + if (config.getBool("enableDebug")) + myLogger(level, str); + } + + // Give the provided player the provided item. + public void giveArmoredElytraToPlayer(Player player, ItemStack item) + { + if (item != null) + player.getInventory().addItem(item); + } + + // Check + initialize for the correct version of Minecraft. + public boolean compatibleMCVer() + { String version; try @@ -260,75 +269,76 @@ public class ArmoredElytra extends JavaPlugin implements Listener } if (version.equals("v1_10_R1")) - nbtEditor = new NBTEditor_V1_10_R1(this); + nbtEditor = new NBTEditor_V1_10_R1(this); else if (version.equals("v1_11_R1")) - nbtEditor = new NBTEditor_V1_11_R1(this); + nbtEditor = new NBTEditor_V1_11_R1(this); else if (version.equals("v1_12_R1")) - nbtEditor = new NBTEditor_V1_12_R1(this); + nbtEditor = new NBTEditor_V1_12_R1(this); else if (version.equals("v1_13_R1")) - nbtEditor = new NBTEditor_V1_13_R1(this); + nbtEditor = new NBTEditor_V1_13_R1(this); + else if (version.equals("v1_13_R2")) + nbtEditor = new NBTEditor_V1_13_R2(this); // Return true if compatible. return nbtEditor != null; - } - - public String getElytraLore() - { - return this.elytraLore; - } - - public String getArmoredElytrName(ArmorTier tier) - { - String ret; - switch(tier) - { - case LEATHER: - ret = this.leatherName; - break; - case GOLD: - ret = this.goldName; - break; - case CHAIN: - ret = this.chainName; - break; - case IRON: - ret = this.ironName; - break; - case DIAMOND: - ret = this.diamondName; - break; - default: - ret = "NONE"; - } - return ret; - } - - public boolean playerHasCraftPerm(Player player, ArmorTier tier) - { - switch (tier) - { - case LEATHER: - return player.hasPermission("armoredelytra.craft.leather"); - case GOLD: - return player.hasPermission("armoredelytra.craft.gold"); - case CHAIN: - return player.hasPermission("armoredelytra.craft.chain"); - case IRON: - return player.hasPermission("armoredelytra.craft.iron"); - case DIAMOND: - return player.hasPermission("armoredelytra.craft.diamond"); - default: - return false; - } - } + } + + public String getElytraLore() + { + return this.elytraLore; + } + + public String getArmoredElytrName(ArmorTier tier) + { + String ret; + switch(tier) + { + case LEATHER: + ret = this.leatherName; + break; + case GOLD: + ret = this.goldName; + break; + case CHAIN: + ret = this.chainName; + break; + case IRON: + ret = this.ironName; + break; + case DIAMOND: + ret = this.diamondName; + break; + default: + ret = "NONE"; + } + return ret; + } + + public boolean playerHasCraftPerm(Player player, ArmorTier tier) + { + switch (tier) + { + case LEATHER: + return player.hasPermission("armoredelytra.craft.leather"); + case GOLD: + return player.hasPermission("armoredelytra.craft.gold"); + case CHAIN: + return player.hasPermission("armoredelytra.craft.chain"); + case IRON: + return player.hasPermission("armoredelytra.craft.iron"); + case DIAMOND: + return player.hasPermission("armoredelytra.craft.diamond"); + default: + return false; + } + } + public void setUpToDate(boolean upToDate) + { + this.upToDate = upToDate; + } - public void setUpToDate(boolean upToDate) - { - this.upToDate = upToDate; - } - - public boolean getUninstallMode() - { - return uninstallMode; - } + public boolean getUninstallMode() + { + return uninstallMode; + } } \ No newline at end of file diff --git a/src/main/java/nl/pim16aap2/armoredElytra/handlers/CommandHandler.java b/src/main/java/nl/pim16aap2/armoredElytra/handlers/CommandHandler.java index 20bd969..a268a78 100644 --- a/src/main/java/nl/pim16aap2/armoredElytra/handlers/CommandHandler.java +++ b/src/main/java/nl/pim16aap2/armoredElytra/handlers/CommandHandler.java @@ -17,13 +17,13 @@ import nl.pim16aap2.armoredElytra.util.ArmorTier; public class CommandHandler implements CommandExecutor { - ArmoredElytra plugin; - NBTEditor nbtEditor; + ArmoredElytra plugin; + NBTEditor nbtEditor; public CommandHandler(ArmoredElytra plugin, NBTEditor nbtEditor) { - this.plugin = plugin; - this.nbtEditor = nbtEditor; + this.plugin = plugin; + this.nbtEditor = nbtEditor; } @Override @@ -37,7 +37,7 @@ public class CommandHandler implements CommandExecutor if (plugin.getUninstallMode()) { - plugin.messagePlayer(player, "Plugin in uninstall mode! New Armored Elytras are not allowed!"); + plugin.messagePlayer(player, plugin.getMyMessages().getString("MESSAGES.UninstallMode")); return true; } @@ -67,10 +67,6 @@ public class CommandHandler implements CommandExecutor tier = args[1]; } - // TODO: Use armorTier name from ArmorTier struct. - // Also, use AT-name for permission node verification. - - // Leather armor. if (tier.equalsIgnoreCase("leather")) { @@ -111,7 +107,7 @@ public class CommandHandler implements CommandExecutor allowed = true; } else - plugin.messagePlayer(player, "Not a supported armor tier! Try one of these: leather, gold, chain, iron, diamond."); + plugin.messagePlayer(player, plugin.getMyMessages().getString("MESSAGES.UnsupportedTier")); if (allowed) { @@ -120,7 +116,7 @@ public class CommandHandler implements CommandExecutor plugin.giveArmoredElytraToPlayer(receiver, newElytra); } else - plugin.messagePlayer(player, "You do not have the required permission node to give " + plugin.getArmoredElytrName(armorTier)); + plugin.messagePlayer(player, plugin.fillInArmorTierInStringNoColor(plugin.getMyMessages().getString("MESSAGES.UnsupportedTier"), armorTier)); return true; } } @@ -142,8 +138,6 @@ public class CommandHandler implements CommandExecutor player = Bukkit.getPlayer(args[0]); ArmorTier armorTier = ArmorTier.NONE; - // TODO: Again, use the ArmorTier struct for tier retrieval. - if (tier.equalsIgnoreCase("leather")) armorTier = ArmorTier.LEATHER; else if (tier.equalsIgnoreCase("gold")) diff --git a/src/main/java/nl/pim16aap2/armoredElytra/handlers/EventHandlers.java b/src/main/java/nl/pim16aap2/armoredElytra/handlers/EventHandlers.java index 065449c..ecd29fa 100644 --- a/src/main/java/nl/pim16aap2/armoredElytra/handlers/EventHandlers.java +++ b/src/main/java/nl/pim16aap2/armoredElytra/handlers/EventHandlers.java @@ -6,7 +6,6 @@ import java.util.Map; import java.util.Random; import java.util.logging.Level; -import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; @@ -32,533 +31,534 @@ import nl.pim16aap2.armoredElytra.util.Util; public class EventHandlers implements Listener { - private int DIAMONDS_TO_FULL; - private int LEATHER_TO_FULL; - private int GOLD_TO_FULL; - private int IRON_TO_FULL; - private NBTEditor nbtEditor; - private final ArmoredElytra plugin; - private List allowedEnchantments; - - public EventHandlers(ArmoredElytra plugin, NBTEditor nbtEditor) - { - this.plugin = plugin; - this.nbtEditor = nbtEditor; - - // Get the values of the config options. - this.allowedEnchantments = plugin.getConfigLoader().getStringList("allowedEnchantments"); - this.LEATHER_TO_FULL = plugin.getConfigLoader().getInt("leatherRepair"); - this.GOLD_TO_FULL = plugin.getConfigLoader().getInt("goldRepair"); - this.IRON_TO_FULL = plugin.getConfigLoader().getInt("ironRepair"); - this.DIAMONDS_TO_FULL = plugin.getConfigLoader().getInt("diamondsRepair"); - } - - // Clear the anvil's inventory (destroy all the items in all 3 slots (second slot is not emptied, when repairing you can safely give multiple items)). - public void cleanAnvil(AnvilInventory anvilInventory) - { - anvilInventory.getItem(0).setAmount(0); - anvilInventory.getItem(1).setAmount(anvilInventory.getItem(1).getAmount() - 1); - anvilInventory.getItem(2).setAmount(0); - } - - // Check if the enchantment is allowed on elytras. - public boolean isAllowedEnchantment(Enchantment enchant) - { - for (String s : allowedEnchantments) - if (Enchantment.getByName(s) != null) - if (Enchantment.getByName(s).equals(enchant)) - return true; - return false; - } - - // Combine 2 maps of enchantments (and remove any invalid ones). - public Map combineEnchantments(Map enchantments0, Map enchantments1) - { - enchantments0 = fixEnchantments(enchantments0); - Map combined = new HashMap(fixEnchantments(enchantments0)); - - if (enchantments1 != null) - { - enchantments1 = fixEnchantments(enchantments1); - // Loop through the enchantments of item1. - for (Map.Entry entry : enchantments1.entrySet()) - { - Integer enchantLevel = enchantments0.get(entry.getKey()); - if (enchantLevel != null) - { - if (entry.getValue() == enchantLevel && entry.getValue() < entry.getKey().getMaxLevel()) - enchantLevel = entry.getValue() + 1; - else if (entry.getValue() > enchantLevel) - enchantLevel = entry.getValue(); - - // If the enchantment level has changed, - if (enchantLevel != enchantments0.get(entry.getKey())) - { - combined.remove(entry.getKey()); - combined.put(entry.getKey(), enchantLevel); - } - } - else if (enchantLevel == null) - combined.put(entry.getKey(), entry.getValue()); - } - - // Get the protection enchantment rating for both enchantment sets. - int protVal0 = getProtectionEnchantmentsVal(enchantments0); - int protVal1 = getProtectionEnchantmentsVal(enchantments1); - - // If they have different - if (protVal0 != 0 && protVal1 != 0 && protVal0 != protVal1) - { - switch(protVal0) - { - case 1: - combined.remove(Enchantment.PROTECTION_ENVIRONMENTAL); - break; - case 2: - combined.remove(Enchantment.PROTECTION_EXPLOSIONS); - break; - case 4: - combined.remove(Enchantment.PROTECTION_FALL); - break; - case 8: - combined.remove(Enchantment.PROTECTION_FIRE); - break; - case 16: - combined.remove(Enchantment.PROTECTION_PROJECTILE); - break; - } - } - } - return combined; - } - - // Function that returns which/how many protection enchantments there are. - public int getProtectionEnchantmentsVal(Map enchantments) - { - int ret = 0; - if (enchantments.containsKey(Enchantment.PROTECTION_ENVIRONMENTAL)) - ret += 1; - if ( enchantments.containsKey(Enchantment.PROTECTION_EXPLOSIONS)) - ret += 2; - if ( enchantments.containsKey(Enchantment.PROTECTION_FALL)) - ret += 4; - if ( enchantments.containsKey(Enchantment.PROTECTION_FIRE)) - ret += 8; - if ( enchantments.containsKey(Enchantment.PROTECTION_PROJECTILE)) - ret += 16; - return ret; - } - - // Repair an Armored Elytra - public short repairItem(short curDur, ItemStack repairItem) - { - // Get the multiplier for the repair items. - double mult = 0.01; - if (repairItem.getType() == Material.LEATHER) - mult *= (100/LEATHER_TO_FULL); + private int DIAMONDS_TO_FULL; + private int LEATHER_TO_FULL; + private int GOLD_TO_FULL; + private int IRON_TO_FULL; + private NBTEditor nbtEditor; + private final ArmoredElytra plugin; + private List allowedEnchantments; + + public EventHandlers(ArmoredElytra plugin, NBTEditor nbtEditor) + { + this.plugin = plugin; + this.nbtEditor = nbtEditor; + + // Get the values of the config options. + this.allowedEnchantments = plugin.getConfigLoader().getStringList("allowedEnchantments"); + this.LEATHER_TO_FULL = plugin.getConfigLoader().getInt("leatherRepair"); + this.GOLD_TO_FULL = plugin.getConfigLoader().getInt("goldRepair"); + this.IRON_TO_FULL = plugin.getConfigLoader().getInt("ironRepair"); + this.DIAMONDS_TO_FULL = plugin.getConfigLoader().getInt("diamondsRepair"); + } + + // Clear the anvil's inventory (destroy all the items in all 3 slots (second slot is not emptied, when repairing you can safely give multiple items)). + public void cleanAnvil(AnvilInventory anvilInventory) + { + anvilInventory.getItem(0).setAmount(0); + anvilInventory.getItem(1).setAmount(anvilInventory.getItem(1).getAmount() - 1); + anvilInventory.getItem(2).setAmount(0); + } + + // Check if the enchantment is allowed on elytras. + public boolean isAllowedEnchantment(Enchantment enchant) + { + for (String s : allowedEnchantments) + if (Enchantment.getByName(s) != null) + if (Enchantment.getByName(s).equals(enchant)) + return true; + return false; + } + + // Combine 2 maps of enchantments (and remove any invalid ones). + public Map combineEnchantments(Map enchantments0, Map enchantments1) + { + enchantments0 = fixEnchantments(enchantments0); + Map combined = new HashMap(fixEnchantments(enchantments0)); + + if (enchantments1 != null) + { + enchantments1 = fixEnchantments(enchantments1); + // Loop through the enchantments of item1. + for (Map.Entry entry : enchantments1.entrySet()) + { + Integer enchantLevel = enchantments0.get(entry.getKey()); + if (enchantLevel != null) + { + if (entry.getValue() == enchantLevel && entry.getValue() < entry.getKey().getMaxLevel()) + enchantLevel = entry.getValue() + 1; + else if (entry.getValue() > enchantLevel) + enchantLevel = entry.getValue(); + + // If the enchantment level has changed, + if (enchantLevel != enchantments0.get(entry.getKey())) + { + combined.remove(entry.getKey()); + combined.put(entry.getKey(), enchantLevel); + } + } + else if (enchantLevel == null) + combined.put(entry.getKey(), entry.getValue()); + } + + // Get the protection enchantment rating for both enchantment sets. + int protVal0 = getProtectionEnchantmentsVal(enchantments0); + int protVal1 = getProtectionEnchantmentsVal(enchantments1); + + // If they have different protection enchantments, keep enchantment1's enchantments + // And remove the protection enchantment from enchantments0. Yes, this system only works + // If there is 1 protection enchantment on + if (protVal0 != 0 && protVal1 != 0 && protVal0 != protVal1) + { + switch(protVal0) + { + case 1: + combined.remove(Enchantment.PROTECTION_ENVIRONMENTAL); + break; + case 2: + combined.remove(Enchantment.PROTECTION_EXPLOSIONS); + break; + case 4: + combined.remove(Enchantment.PROTECTION_FALL); + break; + case 8: + combined.remove(Enchantment.PROTECTION_FIRE); + break; + case 16: + combined.remove(Enchantment.PROTECTION_PROJECTILE); + break; + } + } + } + return combined; + } + + // Function that returns which/how many protection enchantments there are. + public int getProtectionEnchantmentsVal(Map enchantments) + { + int ret = 0; + if (enchantments.containsKey(Enchantment.PROTECTION_ENVIRONMENTAL)) + ret += 1; + if (enchantments.containsKey(Enchantment.PROTECTION_EXPLOSIONS)) + ret += 2; + if (enchantments.containsKey(Enchantment.PROTECTION_FALL)) + ret += 4; + if (enchantments.containsKey(Enchantment.PROTECTION_FIRE)) + ret += 8; + if (enchantments.containsKey(Enchantment.PROTECTION_PROJECTILE)) + ret += 16; + return ret; + } + + // Repair an Armored Elytra + public short repairItem(short curDur, ItemStack repairItem) + { + // Get the multiplier for the repair items. + double mult = 0.01; + if ( repairItem.getType() == Material.LEATHER) + mult *= (100/LEATHER_TO_FULL); - else if (repairItem.getType() == Material.GOLD_INGOT) - mult *= (100/GOLD_TO_FULL); + else if (repairItem.getType() == Material.GOLD_INGOT) + mult *= (100/GOLD_TO_FULL); - else if (repairItem.getType() == Material.IRON_INGOT) - mult *= (100/IRON_TO_FULL); + else if (repairItem.getType() == Material.IRON_INGOT) + mult *= (100/IRON_TO_FULL); - else if (repairItem.getType() == Material.DIAMOND) - mult *= (100/DIAMONDS_TO_FULL); + else if (repairItem.getType() == Material.DIAMOND) + mult *= (100/DIAMONDS_TO_FULL); - int maxDurability = Material.ELYTRA.getMaxDurability(); - int newDurability = (int) (curDur - (maxDurability * mult)); - return (short) (newDurability <= 0 ? 0 : newDurability); - } + int maxDurability = Material.ELYTRA.getMaxDurability(); + int newDurability = (int) (curDur - (maxDurability * mult)); + return (short) (newDurability <= 0 ? 0 : newDurability); + } - // Remove any disallowed enchantments in the map. - public Map fixEnchantments(Map enchantments) - { - Map ret = new HashMap(enchantments); - for (Map.Entry entry : enchantments.entrySet()) - if (!isAllowedEnchantment(entry.getKey())) - ret.remove(entry.getKey()); - return ret; - } + // Remove any disallowed enchantments in the map. + public Map fixEnchantments(Map enchantments) + { + Map ret = new HashMap(enchantments); + for (Map.Entry entry : enchantments.entrySet()) + if (!isAllowedEnchantment(entry.getKey())) + ret.remove(entry.getKey()); + return ret; + } - // Verify there aren't any disallowed enchantments in the map. - public boolean verifyEnchantments(Map enchantments) - { - for (Map.Entry entry : enchantments.entrySet()) - if (!isAllowedEnchantment(entry.getKey())) - return false; - return true; - } - - // Get the armor tier from a chest plate. - public ArmorTier armorToTier(Material item) - { - ArmorTier ret = ArmorTier.NONE; - - switch (item) - { - case LEATHER_CHESTPLATE: - ret = ArmorTier.LEATHER; - break; - case GOLD_CHESTPLATE: - ret = ArmorTier.GOLD; - break; - case CHAINMAIL_CHESTPLATE: - ret = ArmorTier.CHAIN; - break; - case IRON_CHESTPLATE: - ret = ArmorTier.IRON; - break; - case DIAMOND_CHESTPLATE: - ret = ArmorTier.DIAMOND; - break; - default: - break; - } - return ret; - } - - // Check if mat is a chest plate. - public boolean isChestPlate(Material mat) - { - if (mat == Material.LEATHER_CHESTPLATE || mat == Material.GOLD_CHESTPLATE || - mat == Material.CHAINMAIL_CHESTPLATE || mat == Material.IRON_CHESTPLATE || - mat == Material.DIAMOND_CHESTPLATE) - return true; - return false; - } - - /* - * Valid inputs: - * - Elytra (armored or not) + chestplate -> Create Armored Elytra - * - Elytra (armored) + enchanted book -> Enchant - * - Elytra (armored) + its repair item -> Repair - * - Elytra (armored) + other elytra (armored) -> Combine (Enchant + Repair) - * ! Elytra (armored, !leather) + leather -> Block - * - * Ignoring: - * - Elytra (not armored) + !chestplate -> None - * - * + * -> None - */ - public Action isValidInput(ItemStack itemOne, ItemStack itemTwo) - { - if (itemOne == null || itemTwo == null) - return Action.NONE; - - // If itemTwo is the elytra, while itemOne isn't, switch itemOne and itemTwo. - if (itemTwo.getType() == Material.ELYTRA && itemOne.getType() != Material.ELYTRA) - { - ItemStack tmp = itemOne; - itemOne = itemTwo; - itemTwo = tmp; - } - - if (itemOne.getType() != Material.ELYTRA) - return Action.NONE; - - Material matTwo = itemTwo.getType(); - - // If the elytra is to be combined with chest armor... - if (isChestPlate(matTwo)) - return Action.CREATE; - - ArmorTier tier = nbtEditor.getArmorTier(itemOne); - - if (tier != ArmorTier.NONE) - { - // If the armored elytra is to be enchanted using an enchanted book... - if (matTwo == Material.ENCHANTED_BOOK) - return Action.ENCHANT; - - // If the armored elytra is to be repaired using its repair item... - if (ArmorTier.getRepairItem(tier) == matTwo) - return Action.REPAIR; - - // If the armored elytra is to be combined with another armored elytra of the same tier... - if (nbtEditor.getArmorTier(itemTwo) == tier) - return Action.COMBINE; - - // If the armored elytra is not of the leather tier, but itemTwo is leather, - // Pick the block action, as that would repair the elytra by default (vanilla). - // Also block Armored Elytra + Elytra. - if (tier != ArmorTier.LEATHER && matTwo == Material.LEATHER || matTwo == Material.ELYTRA) - return Action.BLOCK; - } - return Action.NONE; - } - - // Handle all anvil related stuff for this plugin. - @EventHandler - public void onAnvilInventoryOpen(PrepareAnvilEvent event) - { - Player player = (Player) event.getView().getPlayer(); - - ItemStack itemA = event.getInventory().getItem(0); - ItemStack itemB = event.getInventory().getItem(1); - ItemStack result = null; - - if (itemA != null && itemB != null) - { - // If itemB is the elytra, while itemA isn't, switch itemA and itemB. - if (itemB.getType() == Material.ELYTRA && itemA.getType() != Material.ELYTRA) - { - result = itemA; - itemA = itemB; - itemB = result; - result = null; - } - } - - // Check if there are items in both input slots. + // Verify there aren't any disallowed enchantments in the map. + public boolean verifyEnchantments(Map enchantments) + { + for (Map.Entry entry : enchantments.entrySet()) + if (!isAllowedEnchantment(entry.getKey())) + return false; + return true; + } + + // Get the armor tier from a chest plate. + public ArmorTier armorToTier(Material item) + { + ArmorTier ret = ArmorTier.NONE; + + switch (item) + { + case LEATHER_CHESTPLATE: + ret = ArmorTier.LEATHER; + break; + case GOLD_CHESTPLATE: + ret = ArmorTier.GOLD; + break; + case CHAINMAIL_CHESTPLATE: + ret = ArmorTier.CHAIN; + break; + case IRON_CHESTPLATE: + ret = ArmorTier.IRON; + break; + case DIAMOND_CHESTPLATE: + ret = ArmorTier.DIAMOND; + break; + default: + break; + } + return ret; + } + + // Check if mat is a chest plate. + public boolean isChestPlate(Material mat) + { + if (mat == Material.LEATHER_CHESTPLATE || mat == Material.GOLD_CHESTPLATE || + mat == Material.CHAINMAIL_CHESTPLATE || mat == Material.IRON_CHESTPLATE || + mat == Material.DIAMOND_CHESTPLATE) + return true; + return false; + } + + /* + * Valid inputs: + * - Elytra (armored or not) + chestplate -> Create Armored Elytra + * - Elytra (armored) + enchanted book -> Enchant + * - Elytra (armored) + its repair item -> Repair + * - Elytra (armored) + other elytra (armored) -> Combine (Enchant + Repair) + * ! Elytra (armored, !leather) + leather -> Block + * + * Ignoring: + * - Elytra (not armored) + !chestplate -> None + * - * + * -> None + */ + public Action isValidInput(ItemStack itemOne, ItemStack itemTwo) + { + if (itemOne == null || itemTwo == null) + return Action.NONE; + + // If itemTwo is the elytra, while itemOne isn't, switch itemOne and itemTwo. + if (itemTwo.getType() == Material.ELYTRA && itemOne.getType() != Material.ELYTRA) + { + ItemStack tmp = itemOne; + itemOne = itemTwo; + itemTwo = tmp; + } + + if (itemOne.getType() != Material.ELYTRA) + return Action.NONE; + + Material matTwo = itemTwo.getType(); + + // If the elytra is to be combined with chest armor... + if (isChestPlate(matTwo)) + return Action.CREATE; + + ArmorTier tier = nbtEditor.getArmorTier(itemOne); + + if (tier != ArmorTier.NONE) + { + // If the armored elytra is to be enchanted using an enchanted book... + if (matTwo == Material.ENCHANTED_BOOK) + return Action.ENCHANT; + + // If the armored elytra is to be repaired using its repair item... + if (ArmorTier.getRepairItem(tier) == matTwo) + return Action.REPAIR; + + // If the armored elytra is to be combined with another armored elytra of the same tier... + if (nbtEditor.getArmorTier(itemTwo) == tier) + return Action.COMBINE; + + // If the armored elytra is not of the leather tier, but itemTwo is leather, + // Pick the block action, as that would repair the elytra by default (vanilla). + // Also block Armored Elytra + Elytra. + if (tier != ArmorTier.LEATHER && matTwo == Material.LEATHER || matTwo == Material.ELYTRA) + return Action.BLOCK; + } + return Action.NONE; + } + + // Handle all anvil related stuff for this plugin. + @EventHandler + public void onAnvilInventoryOpen(PrepareAnvilEvent event) + { + Player player = (Player) event.getView().getPlayer(); + ItemStack itemA = event.getInventory().getItem(0); + ItemStack itemB = event.getInventory().getItem(1); + ItemStack result = null; + + if (itemA != null && itemB != null) + { + // If itemB is the elytra, while itemA isn't, switch itemA and itemB. + if (itemB.getType() == Material.ELYTRA && itemA.getType() != Material.ELYTRA) + { + result = itemA; + itemA = itemB; + itemB = result; + result = null; + } + } + + // Check if there are items in both input slots. if (itemA != null && itemB != null) { - Action action = isValidInput(itemA, itemB); - ArmorTier newTier = ArmorTier.NONE; - ArmorTier curTier = nbtEditor.getArmorTier(itemA); - short durability = 0; - Map enchantments = itemA.getEnchantments(); - enchantments = fixEnchantments(enchantments); - - switch (action) - { - case REPAIR: - newTier = curTier; - durability = repairItem(itemA.getDurability(), itemB); - break; - case COMBINE: - newTier = curTier; - durability = (short) (- itemA.getType().getMaxDurability() - itemA.getDurability() - itemB.getDurability()); - durability = durability < 0 ? 0 : durability; - enchantments = combineEnchantments(enchantments, itemB.getEnchantments()); - break; - case CREATE: - newTier = armorToTier(itemB.getType()); - durability = 0; - enchantments = combineEnchantments(enchantments, itemB.getEnchantments()); - break; - case ENCHANT: - EnchantmentStorageMeta meta = (EnchantmentStorageMeta) itemB.getItemMeta(); - newTier = curTier; - durability = itemA.getDurability(); - // If there aren't any illegal enchantments on the book, continue as normal. - // Otherwise... Block. - if (verifyEnchantments(meta.getStoredEnchants())) - { - enchantments = combineEnchantments(enchantments, meta.getStoredEnchants()); - break; - } - case BLOCK: - event.setResult(null); - player.updateInventory(); - case NONE: - return; - } - - if (plugin.playerHasCraftPerm(player, newTier)) - { - result = new ItemStack(Material.ELYTRA, 1); - if (enchantments != null) - result.addUnsafeEnchantments(enchantments); - result.setDurability(durability); - - result = nbtEditor.addArmorNBTTags(result, newTier, plugin.getConfigLoader().getBool("unbreakable")); - event.setResult(result); - } + Action action = isValidInput(itemA, itemB); + ArmorTier newTier = ArmorTier.NONE; + ArmorTier curTier = nbtEditor.getArmorTier(itemA); + short durability = 0; + Map enchantments = itemA.getEnchantments(); + enchantments = fixEnchantments(enchantments); + + switch (action) + { + case REPAIR: + newTier = curTier; + durability = repairItem(itemA.getDurability(), itemB); + break; + case COMBINE: + newTier = curTier; + durability = (short) (- itemA.getType().getMaxDurability() - itemA.getDurability() - itemB.getDurability()); + durability = durability < 0 ? 0 : durability; + enchantments = combineEnchantments(enchantments, itemB.getEnchantments()); + break; + case CREATE: + newTier = armorToTier(itemB.getType()); + durability = 0; + enchantments = combineEnchantments(enchantments, itemB.getEnchantments()); + break; + case ENCHANT: + EnchantmentStorageMeta meta = (EnchantmentStorageMeta) itemB.getItemMeta(); + newTier = curTier; + durability = itemA.getDurability(); + // If there aren't any illegal enchantments on the book, continue as normal. + // Otherwise... Block. + if (verifyEnchantments(meta.getStoredEnchants())) + { + enchantments = combineEnchantments(enchantments, meta.getStoredEnchants()); + break; + } + case BLOCK: + event.setResult(null); + player.updateInventory(); + case NONE: + return; + } + + if (plugin.playerHasCraftPerm(player, newTier)) + { + result = new ItemStack(Material.ELYTRA, 1); + if (enchantments != null) + result.addUnsafeEnchantments(enchantments); + result.setDurability(durability); + + result = nbtEditor.addArmorNBTTags(result, newTier, plugin.getConfigLoader().getBool("unbreakable")); + event.setResult(result); + } } // Check if either itemA or itemB is unoccupied. if ((itemA == null || itemB == null) && nbtEditor.getArmorTier(event.getInventory().getItem(2)) != ArmorTier.NONE) - // If Item2 is occupied despite itemA or itemB not being occupied. (only for armored elytra)/ - event.setResult(null); - player.updateInventory(); - } - - // Let the player take items out of the anvil. - @EventHandler - public void onInventoryClick(InventoryClickEvent e) - { - if (e.getWhoClicked() instanceof Player) - { - // Check if the event was a player who interacted with an anvil. - Player player = (Player) e.getWhoClicked(); - if (e.getView().getType() == InventoryType.ANVIL) - { - AnvilInventory anvilInventory; - - // Try to cast inventory being used in the event to an anvil inventory. - // This will throw a ClassCastException when a CraftInventoryCustom is used. - try - { - anvilInventory = (AnvilInventory) e.getInventory(); - } - catch (ClassCastException exception) - { - // Print warning to console and exit onInventoryClick event (no support for custom inventories as they are usually used for GUI's). - plugin.debugMsg(Level.WARNING, "Could not cast inventory to anvilInventory for player " + player.getName() + "! Armored Elytras cannot be crafted!"); - return; - } - - int slot = e.getRawSlot(); - - if (slot == 2 && anvilInventory.getItem(0) != null && anvilInventory.getItem(1) != null && anvilInventory.getItem(2) != null) - { - ArmorTier armortier = nbtEditor.getArmorTier(anvilInventory.getItem(2)); - // If there's an armored elytra in the final slot... - if (armortier != ArmorTier.NONE && plugin.playerHasCraftPerm(player, armortier)) - { - // Create a new armored elytra and give that one to the player instead of the result. - // This is done because after putting item0 in AFTER item1, the first letter of the color code shows up, this gets rid of that problem. - ItemStack result = nbtEditor.addArmorNBTTags(anvilInventory.getItem(2), armortier, plugin.getConfigLoader().getBool("unbreakable")); - // Give the result to the player and clear the anvil's inventory. - if (e.isShiftClick()) - { - // If the player's inventory is full, don't do anything. - if (player.getInventory().firstEmpty() == -1) - return; - player.getInventory().addItem(result); - } - else - player.setItemOnCursor(result); - // Clean the anvil's inventory after transferring the items. - cleanAnvil(anvilInventory); - player.updateInventory(); - return; - } - } - } - } - } - - // Check if the player tries to equip armor by richt clicking it. - @SuppressWarnings("deprecation") - @EventHandler - public void onRightClick(PlayerInteractEvent event) - { - Player player = event.getPlayer(); + // If Item2 is occupied despite itemA or itemB not being occupied. (only for armored elytra)/ + event.setResult(null); + player.updateInventory(); + } - ItemStack item = player.getItemInHand(); - - if (item != null) - if (item.getType() == Material.ELYTRA && (nbtEditor.getArmorTier(item) != ArmorTier.NONE)) - { - ArmorTier armorTier = nbtEditor.getArmorTier(item); - if ((armorTier == ArmorTier.LEATHER && !player.hasPermission("armoredelytra.wear.leather")) || - (armorTier == ArmorTier.GOLD && !player.hasPermission("armoredelytra.wear.gold")) || - (armorTier == ArmorTier.CHAIN && !player.hasPermission("armoredelytra.wear.chain")) || - (armorTier == ArmorTier.IRON && !player.hasPermission("armoredelytra.wear.iron")) || - (armorTier == ArmorTier.DIAMOND && !player.hasPermission("armoredelytra.wear.diamond"))) - { - plugin.usageDeniedMessage(player, armorTier); - event.setCancelled(true); - } + // Let the player take items out of the anvil. + @EventHandler + public void onInventoryClick(InventoryClickEvent e) + { + if (e.getWhoClicked() instanceof Player) + { + // Check if the event was a player who interacted with an anvil. + Player player = (Player) e.getWhoClicked(); + if (e.getView().getType() == InventoryType.ANVIL) + { + AnvilInventory anvilInventory; + + // Try to cast inventory being used in the event to an anvil inventory. + // This will throw a ClassCastException when a CraftInventoryCustom is used. + try + { + anvilInventory = (AnvilInventory) e.getInventory(); + } + catch (ClassCastException exception) + { + // Print warning to console and exit onInventoryClick event (no support for custom inventories as they are usually used for GUI's). + plugin.debugMsg(Level.WARNING, "Could not cast inventory to anvilInventory for player " + player.getName() + "! Armored Elytras cannot be crafted!"); + return; + } + + int slot = e.getRawSlot(); + + if (slot == 2 && anvilInventory.getItem(0) != null && anvilInventory.getItem(1) != null && anvilInventory.getItem(2) != null) + { + ArmorTier armortier = nbtEditor.getArmorTier(anvilInventory.getItem(2)); + // If there's an armored elytra in the final slot... + if (armortier != ArmorTier.NONE && plugin.playerHasCraftPerm(player, armortier)) + { + // Create a new armored elytra and give that one to the player instead of the result. + // This is done because after putting item0 in AFTER item1, the first letter of the color code shows up, this gets rid of that problem. + ItemStack result = nbtEditor.addArmorNBTTags(anvilInventory.getItem(2), armortier, plugin.getConfigLoader().getBool("unbreakable")); + // Give the result to the player and clear the anvil's inventory. + if (e.isShiftClick()) + { + // If the player's inventory is full, don't do anything. + if (player.getInventory().firstEmpty() == -1) + return; + player.getInventory().addItem(result); + } + else + player.setItemOnCursor(result); + // Clean the anvil's inventory after transferring the items. + cleanAnvil(anvilInventory); + player.updateInventory(); + return; + } + } } - } - - // Player closes their inventory. Also checks for whether they are allowed to wear the armored elytra they are wearing. - // This is done again here because there are ways to bypass permission check when equipping. - @EventHandler - public void onInventoryClose(InventoryCloseEvent e) - { - verifyArmorInChestSlot((Player) e.getPlayer()); - } - - // Check if the player is allowed to wear the armored elytra based on their permissions. - public void verifyArmorInChestSlot(Player player) - { - ItemStack chestplate = player.getInventory().getChestplate(); - // If the player equips a new chestplate. - if (player.getInventory().getChestplate() != null) - { - // If that chestplate is an (armored) elytra. - if (nbtEditor.getArmorTier(chestplate) != ArmorTier.NONE) - { - ArmorTier armorTier = nbtEditor.getArmorTier(chestplate); - if ((chestplate.getDurability() >= chestplate.getType().getMaxDurability())) - { - plugin.messagePlayer(player, ChatColor.RED + "You cannot equip this elytra! Please repair it in an anvil first."); - Util.unenquipChestPlayer(player); - } - else if ((armorTier == ArmorTier.LEATHER && !player.hasPermission("armoredelytra.wear.leather")) || - (armorTier == ArmorTier.GOLD && !player.hasPermission("armoredelytra.wear.gold" )) || - (armorTier == ArmorTier.CHAIN && !player.hasPermission("armoredelytra.wear.chain" )) || - (armorTier == ArmorTier.IRON && !player.hasPermission("armoredelytra.wear.iron" )) || - (armorTier == ArmorTier.DIAMOND && !player.hasPermission("armoredelytra.wear.diamond"))) - { - plugin.usageDeniedMessage(player, armorTier); - Util.unenquipChestPlayer(player); - } - player.updateInventory(); - } - } - } - - // Because the armored elytra doesn't actually give any armor, the damage received by players wearing an armored elytra is calculated here. - @EventHandler(ignoreCancelled = true) - public void onPlayerDamage(EntityDamageEvent e) - { - if(e.getEntity() instanceof Player) - { - Player p = (Player) e.getEntity(); - // If the player didn't die from the damage. - if ((p.getHealth() - e.getFinalDamage()) > 0) - { - if (p.getInventory().getChestplate() != null) - { - if (nbtEditor.getArmorTier(p.getInventory().getChestplate()) != ArmorTier.NONE) - { - ItemStack elytra = p.getInventory().getChestplate(); - DamageCause cause = e.getCause(); - - // The elytra doesn't receive any damage for these causes: - if (cause != DamageCause.DROWNING && cause != DamageCause.STARVATION && cause != DamageCause.SUFFOCATION && - cause != DamageCause.SUICIDE && cause != DamageCause.FLY_INTO_WALL && cause != DamageCause.POISON) - { - int durability = p.getInventory().getChestplate().getDurability(); - int maxDurability = p.getInventory().getChestplate().getType().getMaxDurability(); - int newDurability = (int) (durability + ((int) (e.getDamage() / 4) > 1 ? (int) (e.getDamage() / 4) : 1)); - - // If the elytra has the durability enchantment, we calculate the durability loss ourselves. - if (p.getInventory().getChestplate().containsEnchantment(Enchantment.DURABILITY)) { - - // Get a random int between 0 and 100 - Random r = new Random(); - int randomInt = r.nextInt(101); - int enchantLevel = p.getInventory().getChestplate().getEnchantmentLevel(Enchantment.DURABILITY); - int durabilityDelta = (100 / (enchantLevel + 1)) < randomInt ? 0 : 1; - if (durability >= maxDurability) - Util.unenquipChestPlayer(p); - else - newDurability = durability + durabilityDelta; - } - // If the item should be broken, make sure it really is broken and unequip it. - if (newDurability >= maxDurability) - { - newDurability = maxDurability; - Util.unenquipChestPlayer(p); - } - elytra.setDurability((short) (newDurability)); - } - } - } - } - } - } - - // Check if the player is trying to equip a broken elytra (and prevent that). - @EventHandler + } + } + + // Check if the player tries to equip armor by richt clicking it. + @SuppressWarnings("deprecation") + @EventHandler + public void onRightClick(PlayerInteractEvent event) + { + Player player = event.getPlayer(); + ItemStack item = player.getItemInHand(); + + if (item != null) + if (item.getType() == Material.ELYTRA && (nbtEditor.getArmorTier(item) != ArmorTier.NONE)) + { + ArmorTier armorTier = nbtEditor.getArmorTier(item); + if ((armorTier == ArmorTier.LEATHER && !player.hasPermission("armoredelytra.wear.leather")) || + (armorTier == ArmorTier.GOLD && !player.hasPermission("armoredelytra.wear.gold" )) || + (armorTier == ArmorTier.CHAIN && !player.hasPermission("armoredelytra.wear.chain" )) || + (armorTier == ArmorTier.IRON && !player.hasPermission("armoredelytra.wear.iron" )) || + (armorTier == ArmorTier.DIAMOND && !player.hasPermission("armoredelytra.wear.diamond"))) + { + plugin.usageDeniedMessage(player, armorTier); + event.setCancelled(true); + } + } + } + + // Player closes their inventory. Also checks for whether they are allowed to wear the armored elytra they are wearing. + // This is done again here because there are ways to bypass permission check when equipping. + @EventHandler + public void onInventoryClose(InventoryCloseEvent e) + { + verifyArmorInChestSlot((Player) e.getPlayer()); + } + + // Check if the player is allowed to wear the armored elytra based on their permissions. + public void verifyArmorInChestSlot(Player player) + { + ItemStack chestplate = player.getInventory().getChestplate(); + // If the player equips a new chestplate. + if (player.getInventory().getChestplate() != null) + { + // If that chestplate is an (armored) elytra. + if (nbtEditor.getArmorTier(chestplate) != ArmorTier.NONE) + { + ArmorTier armorTier = nbtEditor.getArmorTier(chestplate); + if ((chestplate.getDurability() >= chestplate.getType().getMaxDurability())) + { + plugin.messagePlayer(player, plugin.getMyMessages().getString("MESSAGES.RepairNeeded")); + Util.unenquipChestPlayer(player); + player.updateInventory(); + } + else if ((armorTier == ArmorTier.LEATHER && !player.hasPermission("armoredelytra.wear.leather")) || + (armorTier == ArmorTier.GOLD && !player.hasPermission("armoredelytra.wear.gold" )) || + (armorTier == ArmorTier.CHAIN && !player.hasPermission("armoredelytra.wear.chain" )) || + (armorTier == ArmorTier.IRON && !player.hasPermission("armoredelytra.wear.iron" )) || + (armorTier == ArmorTier.DIAMOND && !player.hasPermission("armoredelytra.wear.diamond"))) + { + plugin.usageDeniedMessage(player, armorTier); + Util.unenquipChestPlayer(player); + player.updateInventory(); + } + } + } + } + + // Because the armored elytra doesn't actually give any armor, the damage received by players wearing an armored elytra is calculated here. + @EventHandler(ignoreCancelled = true) + public void onPlayerDamage(EntityDamageEvent e) + { + if(e.getEntity() instanceof Player) + { + Player p = (Player) e.getEntity(); + // If the player didn't die from the damage. + if ((p.getHealth() - e.getFinalDamage()) > 0) + { + if (p.getInventory().getChestplate() != null) + { + if (nbtEditor.getArmorTier(p.getInventory().getChestplate()) != ArmorTier.NONE) + { + ItemStack elytra = p.getInventory().getChestplate(); + DamageCause cause = e.getCause(); + + // The elytra doesn't receive any damage for these causes: + if (cause != DamageCause.DROWNING && cause != DamageCause.STARVATION && cause != DamageCause.SUFFOCATION && + cause != DamageCause.SUICIDE && cause != DamageCause.FLY_INTO_WALL && cause != DamageCause.POISON) + { + int durability = p.getInventory().getChestplate().getDurability(); + int maxDurability = p.getInventory().getChestplate().getType().getMaxDurability(); + int newDurability = (int) (durability + ((int) (e.getDamage() / 4) > 1 ? (int) (e.getDamage() / 4) : 1)); + + // If the elytra has the durability enchantment, we calculate the durability loss ourselves. + if (p.getInventory().getChestplate().containsEnchantment(Enchantment.DURABILITY)) { + + // Get a random int between 0 and 100 + Random r = new Random(); + int randomInt = r.nextInt(101); + int enchantLevel = p.getInventory().getChestplate().getEnchantmentLevel(Enchantment.DURABILITY); + int durabilityDelta = (100 / (enchantLevel + 1)) < randomInt ? 0 : 1; + if (durability >= maxDurability) + Util.unenquipChestPlayer(p); + else + newDurability = durability + durabilityDelta; + } + // If the item should be broken, make sure it really is broken and unequip it. + if (newDurability >= maxDurability) + { + newDurability = maxDurability; + Util.unenquipChestPlayer(p); + } + elytra.setDurability((short) (newDurability)); + } + } + } + } + } + } + + // Check if the player is trying to equip a broken elytra (and prevent that). + @EventHandler public void playerEquipsArmor(InventoryClickEvent e) - { - if (e.getWhoClicked() instanceof Player) - { - Player player = (Player) e.getWhoClicked(); - new BukkitRunnable() - { - @Override + { + if (e.getWhoClicked() instanceof Player) + { + Player player = (Player) e.getWhoClicked(); + new BukkitRunnable() + { + @Override public void run() - { - verifyArmorInChestSlot(player); - } - }.runTaskLater(this.plugin, 1); - } + { + verifyArmorInChestSlot(player); + } + }.runTaskLater(this.plugin, 1); + } } } \ No newline at end of file diff --git a/src/main/java/nl/pim16aap2/armoredElytra/handlers/LoginHandler.java b/src/main/java/nl/pim16aap2/armoredElytra/handlers/LoginHandler.java index b4d91da..785b13f 100644 --- a/src/main/java/nl/pim16aap2/armoredElytra/handlers/LoginHandler.java +++ b/src/main/java/nl/pim16aap2/armoredElytra/handlers/LoginHandler.java @@ -11,31 +11,31 @@ import nl.pim16aap2.armoredElytra.ArmoredElytra; public class LoginHandler implements Listener { - - ArmoredElytra plugin; - String message; - - public LoginHandler(ArmoredElytra plugin, String message) - { - this.plugin = plugin; - this.message = message; - } - - @EventHandler - public void onLogin(PlayerLoginEvent event) - { - Player player = event.getPlayer(); - if (player.hasPermission("armoredElytra.admin")) - { - // Slight delay so the player actually receives the message; - new BukkitRunnable() - { - @Override + + ArmoredElytra plugin; + String message; + + public LoginHandler(ArmoredElytra plugin, String message) + { + this.plugin = plugin; + this.message = message; + } + + @EventHandler + public void onLogin(PlayerLoginEvent event) + { + Player player = event.getPlayer(); + if (player.hasPermission("armoredElytra.admin")) + { + // Slight delay so the player actually receives the message; + new BukkitRunnable() + { + @Override public void run() - { - plugin.messagePlayer(player, ChatColor.AQUA, message); - } - }.runTaskLater(this.plugin, 10); - } - } + { + plugin.messagePlayer(player, ChatColor.AQUA, message); + } + }.runTaskLater(this.plugin, 10); + } + } } diff --git a/src/main/java/nl/pim16aap2/armoredElytra/handlers/Uninstaller.java b/src/main/java/nl/pim16aap2/armoredElytra/handlers/Uninstaller.java index 0dfd583..2ba62f6 100644 --- a/src/main/java/nl/pim16aap2/armoredElytra/handlers/Uninstaller.java +++ b/src/main/java/nl/pim16aap2/armoredElytra/handlers/Uninstaller.java @@ -1,6 +1,5 @@ package nl.pim16aap2.armoredElytra.handlers; -import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -17,66 +16,65 @@ import nl.pim16aap2.armoredElytra.ArmoredElytra; import nl.pim16aap2.armoredElytra.nms.NBTEditor; import nl.pim16aap2.armoredElytra.util.ArmorTier; -public class Uninstaller implements Listener +public class Uninstaller implements Listener { - ArmoredElytra plugin; - NBTEditor nbtEditor; + ArmoredElytra plugin; + NBTEditor nbtEditor; - public Uninstaller(ArmoredElytra plugin, NBTEditor nbtEditor) - { - this.plugin = plugin; - this.nbtEditor = nbtEditor; - } - - public int removeArmoredElytras(Inventory inv) - { - int count = 0; - for (ItemStack is : inv) - if (is != null) - if (is.getType() == Material.ELYTRA) - if (nbtEditor.getArmorTier(is) != ArmorTier.NONE) - { - Bukkit.broadcastMessage("An armored elytra even! Removing now!"); - inv.remove(is); - ++count; - } - return count; - } + public Uninstaller(ArmoredElytra plugin, NBTEditor nbtEditor) + { + this.plugin = plugin; + this.nbtEditor = nbtEditor; + } - @EventHandler - public void onChestOpen(InventoryOpenEvent event) - { - if (event.getInventory().getType().equals(InventoryType.CHEST)) - { - // Slight delay so the inventory has time to get loaded. - new BukkitRunnable() - { - @Override - public void run() - { - Inventory inv = event.getInventory(); - int removed = removeArmoredElytras(inv); - if (removed != 0) - plugin.messagePlayer((Player) (event.getPlayer()), ChatColor.RED, "Removed " + removed + " armored elytras from your chest!"); - } - }.runTaskLater(this.plugin, 20); - } - } - - @EventHandler - public void onPlayerLogin(PlayerLoginEvent event) - { - // Slight delay so the inventory has time to get loaded. - new BukkitRunnable() - { - @Override - public void run() - { - Inventory inv = event.getPlayer().getInventory(); - int removed = removeArmoredElytras(inv); - if (removed != 0) - plugin.messagePlayer((Player) (event.getPlayer()), ChatColor.RED, "Removed " + removed + " armored elytras from your inventory!"); - } - }.runTaskLater(this.plugin, 20); - } + public int removeArmoredElytras(Inventory inv) + { + int count = 0; + for (ItemStack is : inv) + if (is != null) + if (is.getType() == Material.ELYTRA) + if (nbtEditor.getArmorTier(is) != ArmorTier.NONE) + { + inv.remove(is); + ++count; + } + return count; + } + + @EventHandler + public void onChestOpen(InventoryOpenEvent event) + { + if (event.getInventory().getType().equals(InventoryType.CHEST)) + { + // Slight delay so the inventory has time to get loaded. + new BukkitRunnable() + { + @Override + public void run() + { + Inventory inv = event.getInventory(); + int removed = removeArmoredElytras(inv); + if (removed != 0) + plugin.messagePlayer((Player) (event.getPlayer()), ChatColor.RED, "Removed " + removed + " armored elytras from your chest!"); + } + }.runTaskLater(this.plugin, 20); + } + } + + @EventHandler + public void onPlayerLogin(PlayerLoginEvent event) + { + // Slight delay so the inventory has time to get loaded. + new BukkitRunnable() + { + @Override + public void run() + { + Inventory inv = event.getPlayer().getInventory(); + int removed = removeArmoredElytras(inv); + if (removed != 0) + plugin.messagePlayer((Player) (event.getPlayer()), ChatColor.RED, "Removed " + removed + " armored elytras from your inventory!"); + } + }.runTaskLater(this.plugin, 20); + } } diff --git a/src/main/java/nl/pim16aap2/armoredElytra/nms/NBTEditor_V1_10_R1.java b/src/main/java/nl/pim16aap2/armoredElytra/nms/NBTEditor_V1_10_R1.java index 4ebe471..7cabdee 100644 --- a/src/main/java/nl/pim16aap2/armoredElytra/nms/NBTEditor_V1_10_R1.java +++ b/src/main/java/nl/pim16aap2/armoredElytra/nms/NBTEditor_V1_10_R1.java @@ -15,102 +15,103 @@ import net.minecraft.server.v1_10_R1.NBTTagString; import nl.pim16aap2.armoredElytra.ArmoredElytra; import nl.pim16aap2.armoredElytra.util.ArmorTier; -public class NBTEditor_V1_10_R1 implements NBTEditor +public class NBTEditor_V1_10_R1 implements NBTEditor { - private ArmoredElytra plugin; - - // Get the names and lores for every tier of armor. - public NBTEditor_V1_10_R1(ArmoredElytra plugin) - { - this.plugin = plugin; - } - - // Add armor to the supplied item, based on the armorTier. - @Override - public ItemStack addArmorNBTTags(ItemStack item, ArmorTier armorTier, boolean unbreakable) - { - ItemMeta itemmeta = item.getItemMeta(); - int armorProtection = ArmorTier.getArmor (armorTier); - int armorToughness = ArmorTier.getToughness(armorTier); - - itemmeta.setDisplayName(plugin.getArmoredElytrName(armorTier)); - if (plugin.getElytraLore() != null) - itemmeta.setLore(Arrays.asList(plugin.fillInArmorTierInStringNoColor(plugin.getElytraLore(), armorTier))); - item.setItemMeta(itemmeta); - - net.minecraft.server.v1_10_R1.ItemStack nmsStack = CraftItemStack.asNMSCopy(item); - NBTTagCompound compound = (nmsStack.hasTag()) ? nmsStack.getTag() : new NBTTagCompound(); - NBTTagList modifiers = new NBTTagList(); - NBTTagCompound armor = new NBTTagCompound(); - armor.set("AttributeName", new NBTTagString("generic.armor")); - armor.set("Name", new NBTTagString("generic.armor")); - armor.set("Amount", new NBTTagInt(armorProtection)); - armor.set("Operation", new NBTTagInt(0)); - armor.set("UUIDLeast", new NBTTagInt(894654)); - armor.set("UUIDMost", new NBTTagInt(2872)); - armor.set("Slot", new NBTTagString("chest")); - modifiers.add(armor); - - NBTTagCompound armorTough = new NBTTagCompound(); - armorTough.set("AttributeName", new NBTTagString("generic.armorToughness")); - armorTough.set("Name", new NBTTagString("generic.armorToughness")); - armorTough.set("Amount", new NBTTagInt(armorToughness)); - armorTough.set("Operation", new NBTTagInt(0)); - armorTough.set("UUIDLeast", new NBTTagInt(894654)); - armorTough.set("UUIDMost", new NBTTagInt(2872)); - armorTough.set("Slot", new NBTTagString("chest")); - modifiers.add(armorTough); - - if (unbreakable) - compound.set("Unbreakable", new NBTTagByte((byte) 1)); - - compound.set("AttributeModifiers", modifiers); - item = CraftItemStack.asBukkitCopy(nmsStack); - return item; - } - - // Get the armor tier of the supplied item. - @Override - public ArmorTier getArmorTier(ItemStack item) - { - if (item == null) - return ArmorTier.NONE; - if (item.getType() != Material.ELYTRA) - return ArmorTier.NONE; - - // Get the NBT tags from the item. - NBTTagCompound compound = CraftItemStack.asNMSCopy(item).getTag(); - if (compound == null) - return ArmorTier.NONE; - String nbtTags = compound.toString(); - - // Check if the item has the generic.armor attribute. - // Format = ,Slot:"chest",AttributeName:"generic.armor so get pos of char before - // The start of the string, as that's the value of the generic.armor attribute. - int pos = nbtTags.indexOf(",Slot:\"chest\",AttributeName:\"generic.armor\""); - int armorValue = 0; - if (pos > 0) - { - // If so, get the value of the generic.armor attribute. - pos--; - String stringAtPos = nbtTags.substring(pos, pos+1); - armorValue = Integer.parseInt(stringAtPos); - } else - // Otherwise, the item has no armor, so return 0; - return ArmorTier.NONE; - - switch (armorValue) - { - case 3: - return ArmorTier.LEATHER; - case 5: - return ArmorTier.GOLD; - case 6: - return ArmorTier.IRON; - case 8: - return ArmorTier.DIAMOND; - default: - return ArmorTier.NONE; - } - } + private ArmoredElytra plugin; + + // Get the names and lores for every tier of armor. + public NBTEditor_V1_10_R1(ArmoredElytra plugin) + { + this.plugin = plugin; + } + + // Add armor to the supplied item, based on the armorTier. + @Override + public ItemStack addArmorNBTTags(ItemStack item, ArmorTier armorTier, boolean unbreakable) + { + ItemMeta itemmeta = item.getItemMeta(); + int armorProtection = ArmorTier.getArmor(armorTier); + int armorToughness = ArmorTier.getToughness(armorTier); + + itemmeta.setDisplayName(plugin.getArmoredElytrName(armorTier)); + if (plugin.getElytraLore() != null) + itemmeta.setLore(Arrays.asList(plugin.fillInArmorTierInStringNoColor(plugin.getElytraLore(), armorTier))); + item.setItemMeta(itemmeta); + + net.minecraft.server.v1_10_R1.ItemStack nmsStack = CraftItemStack.asNMSCopy(item); + NBTTagCompound compound = (nmsStack.hasTag()) ? nmsStack.getTag() : new NBTTagCompound(); + NBTTagList modifiers = new NBTTagList(); + NBTTagCompound armor = new NBTTagCompound(); + armor.set("AttributeName", new NBTTagString("generic.armor")); + armor.set("Name", new NBTTagString("generic.armor")); + armor.set("Amount", new NBTTagInt(armorProtection)); + armor.set("Operation", new NBTTagInt(0)); + armor.set("UUIDLeast", new NBTTagInt(894654)); + armor.set("UUIDMost", new NBTTagInt(2872)); + armor.set("Slot", new NBTTagString("chest")); + modifiers.add(armor); + + NBTTagCompound armorTough = new NBTTagCompound(); + armorTough.set("AttributeName", new NBTTagString("generic.armorToughness")); + armorTough.set("Name", new NBTTagString("generic.armorToughness")); + armorTough.set("Amount", new NBTTagInt(armorToughness)); + armorTough.set("Operation", new NBTTagInt(0)); + armorTough.set("UUIDLeast", new NBTTagInt(894654)); + armorTough.set("UUIDMost", new NBTTagInt(2872)); + armorTough.set("Slot", new NBTTagString("chest")); + modifiers.add(armorTough); + + if (unbreakable) + compound.set("Unbreakable", new NBTTagByte((byte) 1)); + + compound.set("AttributeModifiers", modifiers); + item = CraftItemStack.asBukkitCopy(nmsStack); + return item; + } + + // Get the armor tier of the supplied item. + @Override + public ArmorTier getArmorTier(ItemStack item) + { + if (item == null) + return ArmorTier.NONE; + if (item.getType() != Material.ELYTRA) + return ArmorTier.NONE; + + // Get the NBT tags from the item. + NBTTagCompound compound = CraftItemStack.asNMSCopy(item).getTag(); + if (compound == null) + return ArmorTier.NONE; + String nbtTags = compound.toString(); + + // Check if the item has the generic.armor attribute. + // Format = ,Slot:"chest",AttributeName:"generic.armor so get pos of char before + // The start of the string, as that's the value of the generic.armor attribute. + int pos = nbtTags.indexOf(",Slot:\"chest\",AttributeName:\"generic.armor\""); + int armorValue = 0; + if (pos > 0) + { + // If so, get the value of the generic.armor attribute. + pos--; + String stringAtPos = nbtTags.substring(pos, pos + 1); + armorValue = Integer.parseInt(stringAtPos); + } + else + // Otherwise, the item has no armor, so return 0; + return ArmorTier.NONE; + + switch (armorValue) + { + case 3: + return ArmorTier.LEATHER; + case 5: + return ArmorTier.GOLD; + case 6: + return ArmorTier.IRON; + case 8: + return ArmorTier.DIAMOND; + default: + return ArmorTier.NONE; + } + } } diff --git a/src/main/java/nl/pim16aap2/armoredElytra/nms/NBTEditor_V1_11_R1.java b/src/main/java/nl/pim16aap2/armoredElytra/nms/NBTEditor_V1_11_R1.java index 9a6748e..e748c74 100644 --- a/src/main/java/nl/pim16aap2/armoredElytra/nms/NBTEditor_V1_11_R1.java +++ b/src/main/java/nl/pim16aap2/armoredElytra/nms/NBTEditor_V1_11_R1.java @@ -15,102 +15,103 @@ import net.minecraft.server.v1_11_R1.NBTTagString; import nl.pim16aap2.armoredElytra.ArmoredElytra; import nl.pim16aap2.armoredElytra.util.ArmorTier; -public class NBTEditor_V1_11_R1 implements NBTEditor +public class NBTEditor_V1_11_R1 implements NBTEditor { - private ArmoredElytra plugin; - - // Get the names and lores for every tier of armor. - public NBTEditor_V1_11_R1(ArmoredElytra plugin) - { - this.plugin = plugin; - } - - // Add armor to the supplied item, based on the armorTier. - @Override - public ItemStack addArmorNBTTags(ItemStack item, ArmorTier armorTier, boolean unbreakable) - { - ItemMeta itemmeta = item.getItemMeta(); - int armorProtection = ArmorTier.getArmor (armorTier); - int armorToughness = ArmorTier.getToughness(armorTier); - - itemmeta.setDisplayName(plugin.getArmoredElytrName(armorTier)); - if (plugin.getElytraLore() != null) - itemmeta.setLore(Arrays.asList(plugin.fillInArmorTierInStringNoColor(plugin.getElytraLore(), armorTier))); - item.setItemMeta(itemmeta); - - net.minecraft.server.v1_11_R1.ItemStack nmsStack = CraftItemStack.asNMSCopy(item); - NBTTagCompound compound = (nmsStack.hasTag()) ? nmsStack.getTag() : new NBTTagCompound(); - NBTTagList modifiers = new NBTTagList(); - NBTTagCompound armor = new NBTTagCompound(); - armor.set("AttributeName", new NBTTagString("generic.armor")); - armor.set("Name", new NBTTagString("generic.armor")); - armor.set("Amount", new NBTTagInt(armorProtection)); - armor.set("Operation", new NBTTagInt(0)); - armor.set("UUIDLeast", new NBTTagInt(894654)); - armor.set("UUIDMost", new NBTTagInt(2872)); - armor.set("Slot", new NBTTagString("chest")); - modifiers.add(armor); - - NBTTagCompound armorTough = new NBTTagCompound(); - armorTough.set("AttributeName", new NBTTagString("generic.armorToughness")); - armorTough.set("Name", new NBTTagString("generic.armorToughness")); - armorTough.set("Amount", new NBTTagInt(armorToughness)); - armorTough.set("Operation", new NBTTagInt(0)); - armorTough.set("UUIDLeast", new NBTTagInt(894654)); - armorTough.set("UUIDMost", new NBTTagInt(2872)); - armorTough.set("Slot", new NBTTagString("chest")); - modifiers.add(armorTough); - - if (unbreakable) - compound.set("Unbreakable", new NBTTagByte((byte) 1)); - - compound.set("AttributeModifiers", modifiers); - item = CraftItemStack.asBukkitCopy(nmsStack); - return item; - } - - // Get the armor tier of the supplied item. - @Override - public ArmorTier getArmorTier(ItemStack item) - { - if (item == null) - return ArmorTier.NONE; - if (item.getType() != Material.ELYTRA) - return ArmorTier.NONE; - - // Get the NBT tags from the item. - NBTTagCompound compound = CraftItemStack.asNMSCopy(item).getTag(); - if (compound == null) - return ArmorTier.NONE; - String nbtTags = compound.toString(); - - // Check if the item has the generic.armor attribute. - // Format = ,Slot:"chest",AttributeName:"generic.armor so get pos of char before - // The start of the string, as that's the value of the generic.armor attribute. - int pos = nbtTags.indexOf(",Slot:\"chest\",AttributeName:\"generic.armor\""); - int armorValue = 0; - if (pos > 0) - { - // If so, get the value of the generic.armor attribute. - pos--; - String stringAtPos = nbtTags.substring(pos, pos+1); - armorValue = Integer.parseInt(stringAtPos); - } else - // Otherwise, the item has no armor, so return 0; - return ArmorTier.NONE; - - switch (armorValue) - { - case 3: - return ArmorTier.LEATHER; - case 5: - return ArmorTier.GOLD; - case 6: - return ArmorTier.IRON; - case 8: - return ArmorTier.DIAMOND; - default: - return ArmorTier.NONE; - } - } + private ArmoredElytra plugin; + + // Get the names and lores for every tier of armor. + public NBTEditor_V1_11_R1(ArmoredElytra plugin) + { + this.plugin = plugin; + } + + // Add armor to the supplied item, based on the armorTier. + @Override + public ItemStack addArmorNBTTags(ItemStack item, ArmorTier armorTier, boolean unbreakable) + { + ItemMeta itemmeta = item.getItemMeta(); + int armorProtection = ArmorTier.getArmor(armorTier); + int armorToughness = ArmorTier.getToughness(armorTier); + + itemmeta.setDisplayName(plugin.getArmoredElytrName(armorTier)); + if (plugin.getElytraLore() != null) + itemmeta.setLore(Arrays.asList(plugin.fillInArmorTierInStringNoColor(plugin.getElytraLore(), armorTier))); + item.setItemMeta(itemmeta); + + net.minecraft.server.v1_11_R1.ItemStack nmsStack = CraftItemStack.asNMSCopy(item); + NBTTagCompound compound = (nmsStack.hasTag()) ? nmsStack.getTag() : new NBTTagCompound(); + NBTTagList modifiers = new NBTTagList(); + NBTTagCompound armor = new NBTTagCompound(); + armor.set("AttributeName", new NBTTagString("generic.armor")); + armor.set("Name", new NBTTagString("generic.armor")); + armor.set("Amount", new NBTTagInt(armorProtection)); + armor.set("Operation", new NBTTagInt(0)); + armor.set("UUIDLeast", new NBTTagInt(894654)); + armor.set("UUIDMost", new NBTTagInt(2872)); + armor.set("Slot", new NBTTagString("chest")); + modifiers.add(armor); + + NBTTagCompound armorTough = new NBTTagCompound(); + armorTough.set("AttributeName", new NBTTagString("generic.armorToughness")); + armorTough.set("Name", new NBTTagString("generic.armorToughness")); + armorTough.set("Amount", new NBTTagInt(armorToughness)); + armorTough.set("Operation", new NBTTagInt(0)); + armorTough.set("UUIDLeast", new NBTTagInt(894654)); + armorTough.set("UUIDMost", new NBTTagInt(2872)); + armorTough.set("Slot", new NBTTagString("chest")); + modifiers.add(armorTough); + + if (unbreakable) + compound.set("Unbreakable", new NBTTagByte((byte) 1)); + + compound.set("AttributeModifiers", modifiers); + item = CraftItemStack.asBukkitCopy(nmsStack); + return item; + } + + // Get the armor tier of the supplied item. + @Override + public ArmorTier getArmorTier(ItemStack item) + { + if (item == null) + return ArmorTier.NONE; + if (item.getType() != Material.ELYTRA) + return ArmorTier.NONE; + + // Get the NBT tags from the item. + NBTTagCompound compound = CraftItemStack.asNMSCopy(item).getTag(); + if (compound == null) + return ArmorTier.NONE; + String nbtTags = compound.toString(); + + // Check if the item has the generic.armor attribute. + // Format = ,Slot:"chest",AttributeName:"generic.armor so get pos of char before + // The start of the string, as that's the value of the generic.armor attribute. + int pos = nbtTags.indexOf(",Slot:\"chest\",AttributeName:\"generic.armor\""); + int armorValue = 0; + if (pos > 0) + { + // If so, get the value of the generic.armor attribute. + pos--; + String stringAtPos = nbtTags.substring(pos, pos + 1); + armorValue = Integer.parseInt(stringAtPos); + } + else + // Otherwise, the item has no armor, so return 0; + return ArmorTier.NONE; + + switch (armorValue) + { + case 3: + return ArmorTier.LEATHER; + case 5: + return ArmorTier.GOLD; + case 6: + return ArmorTier.IRON; + case 8: + return ArmorTier.DIAMOND; + default: + return ArmorTier.NONE; + } + } } diff --git a/src/main/java/nl/pim16aap2/armoredElytra/nms/NBTEditor_V1_12_R1.java b/src/main/java/nl/pim16aap2/armoredElytra/nms/NBTEditor_V1_12_R1.java index dff456c..e42ef33 100644 --- a/src/main/java/nl/pim16aap2/armoredElytra/nms/NBTEditor_V1_12_R1.java +++ b/src/main/java/nl/pim16aap2/armoredElytra/nms/NBTEditor_V1_12_R1.java @@ -15,102 +15,103 @@ import net.minecraft.server.v1_12_R1.NBTTagString; import nl.pim16aap2.armoredElytra.ArmoredElytra; import nl.pim16aap2.armoredElytra.util.ArmorTier; -public class NBTEditor_V1_12_R1 implements NBTEditor +public class NBTEditor_V1_12_R1 implements NBTEditor { - private ArmoredElytra plugin; - - // Get the names and lores for every tier of armor. - public NBTEditor_V1_12_R1(ArmoredElytra plugin) - { - this.plugin = plugin; - } - - // Add armor to the supplied item, based on the armorTier. - @Override - public ItemStack addArmorNBTTags(ItemStack item, ArmorTier armorTier, boolean unbreakable) - { - ItemMeta itemmeta = item.getItemMeta(); - int armorProtection = ArmorTier.getArmor (armorTier); - int armorToughness = ArmorTier.getToughness(armorTier); - - itemmeta.setDisplayName(plugin.getArmoredElytrName(armorTier)); - if (plugin.getElytraLore() != null) - itemmeta.setLore(Arrays.asList(plugin.fillInArmorTierInStringNoColor(plugin.getElytraLore(), armorTier))); - item.setItemMeta(itemmeta); - - net.minecraft.server.v1_12_R1.ItemStack nmsStack = CraftItemStack.asNMSCopy(item); - NBTTagCompound compound = (nmsStack.hasTag()) ? nmsStack.getTag() : new NBTTagCompound(); - NBTTagList modifiers = new NBTTagList(); - NBTTagCompound armor = new NBTTagCompound(); - armor.set("AttributeName", new NBTTagString("generic.armor")); - armor.set("Name", new NBTTagString("generic.armor")); - armor.set("Amount", new NBTTagInt(armorProtection)); - armor.set("Operation", new NBTTagInt(0)); - armor.set("UUIDLeast", new NBTTagInt(894654)); - armor.set("UUIDMost", new NBTTagInt(2872)); - armor.set("Slot", new NBTTagString("chest")); - modifiers.add(armor); - - NBTTagCompound armorTough = new NBTTagCompound(); - armorTough.set("AttributeName", new NBTTagString("generic.armorToughness")); - armorTough.set("Name", new NBTTagString("generic.armorToughness")); - armorTough.set("Amount", new NBTTagInt(armorToughness)); - armorTough.set("Operation", new NBTTagInt(0)); - armorTough.set("UUIDLeast", new NBTTagInt(894654)); - armorTough.set("UUIDMost", new NBTTagInt(2872)); - armorTough.set("Slot", new NBTTagString("chest")); - modifiers.add(armorTough); - - if (unbreakable) - compound.set("Unbreakable", new NBTTagByte((byte) 1)); - - compound.set("AttributeModifiers", modifiers); - item = CraftItemStack.asBukkitCopy(nmsStack); - return item; - } - - // Get the armor tier of the supplied item. - @Override - public ArmorTier getArmorTier(ItemStack item) - { - if (item == null) - return ArmorTier.NONE; - if (item.getType() != Material.ELYTRA) - return ArmorTier.NONE; - - // Get the NBT tags from the item. - NBTTagCompound compound = CraftItemStack.asNMSCopy(item).getTag(); - if (compound == null) - return ArmorTier.NONE; - String nbtTags = compound.toString(); - - // Check if the item has the generic.armor attribute. - // Format = ,Slot:"chest",AttributeName:"generic.armor so get pos of char before - // The start of the string, as that's the value of the generic.armor attribute. - int pos = nbtTags.indexOf(",Slot:\"chest\",AttributeName:\"generic.armor\""); - int armorValue = 0; - if (pos > 0) - { - // If so, get the value of the generic.armor attribute. - pos--; - String stringAtPos = nbtTags.substring(pos, pos+1); - armorValue = Integer.parseInt(stringAtPos); - } else - // Otherwise, the item has no armor, so return 0; - return ArmorTier.NONE; - - switch (armorValue) - { - case 3: - return ArmorTier.LEATHER; - case 5: - return ArmorTier.GOLD; - case 6: - return ArmorTier.IRON; - case 8: - return ArmorTier.DIAMOND; - default: - return ArmorTier.NONE; - } - } -} \ No newline at end of file + private ArmoredElytra plugin; + + // Get the names and lores for every tier of armor. + public NBTEditor_V1_12_R1(ArmoredElytra plugin) + { + this.plugin = plugin; + } + + // Add armor to the supplied item, based on the armorTier. + @Override + public ItemStack addArmorNBTTags(ItemStack item, ArmorTier armorTier, boolean unbreakable) + { + ItemMeta itemmeta = item.getItemMeta(); + int armorProtection = ArmorTier.getArmor(armorTier); + int armorToughness = ArmorTier.getToughness(armorTier); + + itemmeta.setDisplayName(plugin.getArmoredElytrName(armorTier)); + if (plugin.getElytraLore() != null) + itemmeta.setLore(Arrays.asList(plugin.fillInArmorTierInStringNoColor(plugin.getElytraLore(), armorTier))); + item.setItemMeta(itemmeta); + + net.minecraft.server.v1_12_R1.ItemStack nmsStack = CraftItemStack.asNMSCopy(item); + NBTTagCompound compound = (nmsStack.hasTag()) ? nmsStack.getTag() : new NBTTagCompound(); + NBTTagList modifiers = new NBTTagList(); + NBTTagCompound armor = new NBTTagCompound(); + armor.set("AttributeName", new NBTTagString("generic.armor")); + armor.set("Name", new NBTTagString("generic.armor")); + armor.set("Amount", new NBTTagInt(armorProtection)); + armor.set("Operation", new NBTTagInt(0)); + armor.set("UUIDLeast", new NBTTagInt(894654)); + armor.set("UUIDMost", new NBTTagInt(2872)); + armor.set("Slot", new NBTTagString("chest")); + modifiers.add(armor); + + NBTTagCompound armorTough = new NBTTagCompound(); + armorTough.set("AttributeName", new NBTTagString("generic.armorToughness")); + armorTough.set("Name", new NBTTagString("generic.armorToughness")); + armorTough.set("Amount", new NBTTagInt(armorToughness)); + armorTough.set("Operation", new NBTTagInt(0)); + armorTough.set("UUIDLeast", new NBTTagInt(894654)); + armorTough.set("UUIDMost", new NBTTagInt(2872)); + armorTough.set("Slot", new NBTTagString("chest")); + modifiers.add(armorTough); + + if (unbreakable) + compound.set("Unbreakable", new NBTTagByte((byte) 1)); + + compound.set("AttributeModifiers", modifiers); + item = CraftItemStack.asBukkitCopy(nmsStack); + return item; + } + + // Get the armor tier of the supplied item. + @Override + public ArmorTier getArmorTier(ItemStack item) + { + if (item == null) + return ArmorTier.NONE; + if (item.getType() != Material.ELYTRA) + return ArmorTier.NONE; + + // Get the NBT tags from the item. + NBTTagCompound compound = CraftItemStack.asNMSCopy(item).getTag(); + if (compound == null) + return ArmorTier.NONE; + String nbtTags = compound.toString(); + + // Check if the item has the generic.armor attribute. + // Format = ,Slot:"chest",AttributeName:"generic.armor so get pos of char before + // The start of the string, as that's the value of the generic.armor attribute. + int pos = nbtTags.indexOf(",Slot:\"chest\",AttributeName:\"generic.armor\""); + int armorValue = 0; + if (pos > 0) + { + // If so, get the value of the generic.armor attribute. + pos--; + String stringAtPos = nbtTags.substring(pos, pos + 1); + armorValue = Integer.parseInt(stringAtPos); + } + else + // Otherwise, the item has no armor, so return 0; + return ArmorTier.NONE; + + switch (armorValue) + { + case 3: + return ArmorTier.LEATHER; + case 5: + return ArmorTier.GOLD; + case 6: + return ArmorTier.IRON; + case 8: + return ArmorTier.DIAMOND; + default: + return ArmorTier.NONE; + } + } +} diff --git a/src/main/java/nl/pim16aap2/armoredElytra/nms/NBTEditor_V1_13_R1.java b/src/main/java/nl/pim16aap2/armoredElytra/nms/NBTEditor_V1_13_R1.java index e052e49..6a0cc7d 100644 --- a/src/main/java/nl/pim16aap2/armoredElytra/nms/NBTEditor_V1_13_R1.java +++ b/src/main/java/nl/pim16aap2/armoredElytra/nms/NBTEditor_V1_13_R1.java @@ -15,102 +15,107 @@ import net.minecraft.server.v1_13_R1.NBTTagString; import nl.pim16aap2.armoredElytra.ArmoredElytra; import nl.pim16aap2.armoredElytra.util.ArmorTier; -public class NBTEditor_V1_13_R1 implements NBTEditor +public class NBTEditor_V1_13_R1 implements NBTEditor { - private ArmoredElytra plugin; - - // Get the names and lores for every tier of armor. - public NBTEditor_V1_13_R1(ArmoredElytra plugin) - { - this.plugin = plugin; - } - - // Add armor to the supplied item, based on the armorTier. - @Override - public ItemStack addArmorNBTTags(ItemStack item, ArmorTier armorTier, boolean unbreakable) - { - ItemMeta itemmeta = item.getItemMeta(); - int armorProtection = ArmorTier.getArmor (armorTier); - int armorToughness = ArmorTier.getToughness(armorTier); - - itemmeta.setDisplayName(plugin.getArmoredElytrName(armorTier)); - if (plugin.getElytraLore() != null) - itemmeta.setLore(Arrays.asList(plugin.fillInArmorTierInStringNoColor(plugin.getElytraLore(), armorTier))); - item.setItemMeta(itemmeta); - - net.minecraft.server.v1_13_R1.ItemStack nmsStack = CraftItemStack.asNMSCopy(item); - NBTTagCompound compound = (nmsStack.hasTag()) ? nmsStack.getTag() : new NBTTagCompound(); - NBTTagList modifiers = new NBTTagList(); - NBTTagCompound armor = new NBTTagCompound(); - armor.set("AttributeName", new NBTTagString("generic.armor")); - armor.set("Name", new NBTTagString("generic.armor")); - armor.set("Amount", new NBTTagInt(armorProtection)); - armor.set("Operation", new NBTTagInt(0)); - armor.set("UUIDLeast", new NBTTagInt(894654)); - armor.set("UUIDMost", new NBTTagInt(2872)); - armor.set("Slot", new NBTTagString("chest")); - modifiers.add(armor); - - NBTTagCompound armorTough = new NBTTagCompound(); - armorTough.set("AttributeName", new NBTTagString("generic.armorToughness")); - armorTough.set("Name", new NBTTagString("generic.armorToughness")); - armorTough.set("Amount", new NBTTagInt(armorToughness)); - armorTough.set("Operation", new NBTTagInt(0)); - armorTough.set("UUIDLeast", new NBTTagInt(894654)); - armorTough.set("UUIDMost", new NBTTagInt(2872)); - armorTough.set("Slot", new NBTTagString("chest")); - modifiers.add(armorTough); - - if (unbreakable) - compound.set("Unbreakable", new NBTTagByte((byte) 1)); - - compound.set("AttributeModifiers", modifiers); - item = CraftItemStack.asBukkitCopy(nmsStack); - return item; - } - - // Get the armor tier of the supplied item. - @Override - public ArmorTier getArmorTier(ItemStack item) - { - if (item == null) - return ArmorTier.NONE; - if (item.getType() != Material.ELYTRA) - return ArmorTier.NONE; - - // Get the NBT tags from the item. - NBTTagCompound compound = CraftItemStack.asNMSCopy(item).getTag(); - if (compound == null) - return ArmorTier.NONE; - String nbtTags = compound.toString(); - - // Check if the item has the generic.armor attribute. - // Format = ,Slot:"chest",AttributeName:"generic.armor so get pos of char before - // The start of the string, as that's the value of the generic.armor attribute. - int pos = nbtTags.indexOf(",Slot:\"chest\",AttributeName:\"generic.armor\""); - int armorValue = 0; - if (pos > 0) - { - // If so, get the value of the generic.armor attribute. - pos--; - String stringAtPos = nbtTags.substring(pos, pos+1); - armorValue = Integer.parseInt(stringAtPos); - } else - // Otherwise, the item has no armor, so return 0; - return ArmorTier.NONE; - - switch (armorValue) - { - case 3: - return ArmorTier.LEATHER; - case 5: - return ArmorTier.GOLD; - case 6: - return ArmorTier.IRON; - case 8: - return ArmorTier.DIAMOND; - default: - return ArmorTier.NONE; - } - } -} \ No newline at end of file + private ArmoredElytra plugin; + + // Get the names and lores for every tier of armor. + public NBTEditor_V1_13_R1(ArmoredElytra plugin) + { + this.plugin = plugin; + } + + // Add armor to the supplied item, based on the armorTier. + @Override + public ItemStack addArmorNBTTags(ItemStack item, ArmorTier armorTier, boolean unbreakable) + { + ItemMeta itemmeta = item.getItemMeta(); + int armorProtection = ArmorTier.getArmor(armorTier); + int armorToughness = ArmorTier.getToughness(armorTier); + + itemmeta.setDisplayName(plugin.getArmoredElytrName(armorTier)); + if (plugin.getElytraLore() != null) + itemmeta.setLore(Arrays.asList(plugin.fillInArmorTierInStringNoColor(plugin.getElytraLore(), armorTier))); + item.setItemMeta(itemmeta); + + net.minecraft.server.v1_13_R1.ItemStack nmsStack = CraftItemStack.asNMSCopy(item); + NBTTagCompound compound = (nmsStack.hasTag()) ? nmsStack.getTag() : new NBTTagCompound(); + NBTTagList modifiers = new NBTTagList(); + NBTTagCompound armor = new NBTTagCompound(); + armor.set("AttributeName", new NBTTagString("generic.armor")); + armor.set("Name", new NBTTagString("generic.armor")); + armor.set("Amount", new NBTTagInt(armorProtection)); + armor.set("Operation", new NBTTagInt(0)); + armor.set("UUIDLeast", new NBTTagInt(894654)); + armor.set("UUIDMost", new NBTTagInt(2872)); + armor.set("Slot", new NBTTagString("chest")); + modifiers.add(armor); + + NBTTagCompound armorTough = new NBTTagCompound(); + armorTough.set("AttributeName", new NBTTagString("generic.armorToughness")); + armorTough.set("Name", new NBTTagString("generic.armorToughness")); + armorTough.set("Amount", new NBTTagInt(armorToughness)); + armorTough.set("Operation", new NBTTagInt(0)); + armorTough.set("UUIDLeast", new NBTTagInt(894654)); + armorTough.set("UUIDMost", new NBTTagInt(2872)); + armorTough.set("Slot", new NBTTagString("chest")); + modifiers.add(armorTough); + + if (unbreakable) + compound.set("Unbreakable", new NBTTagByte((byte) 1)); + + compound.set("AttributeModifiers", modifiers); + item = CraftItemStack.asBukkitCopy(nmsStack); + return item; + } + + // Get the armor tier of the supplied item. + @Override + public ArmorTier getArmorTier(ItemStack item) + { + if (item == null) + return ArmorTier.NONE; + if (item.getType() != Material.ELYTRA) + return ArmorTier.NONE; + + // Get the NBT tags from the item. + NBTTagCompound compound = CraftItemStack.asNMSCopy(item).getTag(); + if (compound == null) + return ArmorTier.NONE; + String nbtTags = compound.toString(); + + // Check if the item has the generic.armor attribute. + // Format = ,Slot:"chest",AttributeName:"generic.armor so get pos of char before + // The start of the string, as that's the value of the generic.armor attribute. + // The level is now formatted as x.xd, e.g. 6.0d. + int pos = nbtTags.indexOf(",Slot:\"chest\",AttributeName:\"generic.armor\""); + int armorValue = 0; + + if (pos <= 0) + return ArmorTier.NONE; + + try + { + String stringAtPos = nbtTags.substring(pos - 4, pos - 1); + armorValue = (int) Double.parseDouble(stringAtPos); + } + catch (Exception e) + { + armorValue = 0; + } + + switch (armorValue) + { + case 3: + return ArmorTier.LEATHER; + case 5: + return ArmorTier.GOLD; + case 6: + return ArmorTier.IRON; + case 8: + return ArmorTier.DIAMOND; + default: + return ArmorTier.NONE; + } + } +} diff --git a/src/main/java/nl/pim16aap2/armoredElytra/nms/NBTEditor_V1_13_R2.java b/src/main/java/nl/pim16aap2/armoredElytra/nms/NBTEditor_V1_13_R2.java new file mode 100644 index 0000000..de82164 --- /dev/null +++ b/src/main/java/nl/pim16aap2/armoredElytra/nms/NBTEditor_V1_13_R2.java @@ -0,0 +1,121 @@ +package nl.pim16aap2.armoredElytra.nms; + +import java.util.Arrays; + +import org.bukkit.Material; +import org.bukkit.craftbukkit.v1_13_R2.inventory.CraftItemStack; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import net.minecraft.server.v1_13_R2.NBTTagByte; +import net.minecraft.server.v1_13_R2.NBTTagCompound; +import net.minecraft.server.v1_13_R2.NBTTagInt; +import net.minecraft.server.v1_13_R2.NBTTagList; +import net.minecraft.server.v1_13_R2.NBTTagString; +import nl.pim16aap2.armoredElytra.ArmoredElytra; +import nl.pim16aap2.armoredElytra.util.ArmorTier; + +public class NBTEditor_V1_13_R2 implements NBTEditor +{ + private ArmoredElytra plugin; + + // Get the names and lores for every tier of armor. + public NBTEditor_V1_13_R2(ArmoredElytra plugin) + { + this.plugin = plugin; + } + + // Add armor to the supplied item, based on the armorTier. + @Override + public ItemStack addArmorNBTTags(ItemStack item, ArmorTier armorTier, boolean unbreakable) + { + ItemMeta itemmeta = item.getItemMeta(); + int armorProtection = ArmorTier.getArmor(armorTier); + int armorToughness = ArmorTier.getToughness(armorTier); + + itemmeta.setDisplayName(plugin.getArmoredElytrName(armorTier)); + if (plugin.getElytraLore() != null) + itemmeta.setLore(Arrays.asList(plugin.fillInArmorTierInStringNoColor(plugin.getElytraLore(), armorTier))); + item.setItemMeta(itemmeta); + + net.minecraft.server.v1_13_R2.ItemStack nmsStack = CraftItemStack.asNMSCopy(item); + NBTTagCompound compound = (nmsStack.hasTag()) ? nmsStack.getTag() : new NBTTagCompound(); + NBTTagList modifiers = new NBTTagList(); + NBTTagCompound armor = new NBTTagCompound(); + armor.set("AttributeName", new NBTTagString("generic.armor")); + armor.set("Name", new NBTTagString("generic.armor")); + armor.set("Amount", new NBTTagInt(armorProtection)); + armor.set("Operation", new NBTTagInt(0)); + armor.set("UUIDLeast", new NBTTagInt(894654)); + armor.set("UUIDMost", new NBTTagInt(2872)); + armor.set("Slot", new NBTTagString("chest")); + modifiers.add(armor); + + NBTTagCompound armorTough = new NBTTagCompound(); + armorTough.set("AttributeName", new NBTTagString("generic.armorToughness")); + armorTough.set("Name", new NBTTagString("generic.armorToughness")); + armorTough.set("Amount", new NBTTagInt(armorToughness)); + armorTough.set("Operation", new NBTTagInt(0)); + armorTough.set("UUIDLeast", new NBTTagInt(894654)); + armorTough.set("UUIDMost", new NBTTagInt(2872)); + armorTough.set("Slot", new NBTTagString("chest")); + modifiers.add(armorTough); + + if (unbreakable) + compound.set("Unbreakable", new NBTTagByte((byte) 1)); + + compound.set("AttributeModifiers", modifiers); + item = CraftItemStack.asBukkitCopy(nmsStack); + return item; + } + + // Get the armor tier of the supplied item. + @Override + public ArmorTier getArmorTier(ItemStack item) + { + if (item == null) + return ArmorTier.NONE; + if (item.getType() != Material.ELYTRA) + return ArmorTier.NONE; + + // Get the NBT tags from the item. + NBTTagCompound compound = CraftItemStack.asNMSCopy(item).getTag(); + if (compound == null) + return ArmorTier.NONE; + String nbtTags = compound.toString(); + + // Check if the item has the generic.armor attribute. + // Format = ,Slot:"chest",AttributeName:"generic.armor so get pos of char before + // The start of the string, as that's the value of the generic.armor attribute. + // The level is now formatted as x.xd, e.g. 6.0d. + int pos = nbtTags.indexOf(",Slot:\"chest\",AttributeName:\"generic.armor\""); + int armorValue = 0; + + if (pos <= 0) + return ArmorTier.NONE; + + try + { + String stringAtPos = nbtTags.substring(pos - 4, pos - 1); + armorValue = (int) Double.parseDouble(stringAtPos); + } + catch (Exception e) + { + armorValue = 0; + } + + switch (armorValue) + { + case 3: + return ArmorTier.LEATHER; + case 5: + return ArmorTier.GOLD; + case 6: + return ArmorTier.IRON; + case 8: + return ArmorTier.DIAMOND; + default: + return ArmorTier.NONE; + } + } +} diff --git a/src/main/java/nl/pim16aap2/armoredElytra/util/ArmorTier.java b/src/main/java/nl/pim16aap2/armoredElytra/util/ArmorTier.java index 54a41e9..8bc7af0 100644 --- a/src/main/java/nl/pim16aap2/armoredElytra/util/ArmorTier.java +++ b/src/main/java/nl/pim16aap2/armoredElytra/util/ArmorTier.java @@ -12,9 +12,9 @@ public enum ArmorTier IRON (6 , 0 , Material.IRON_INGOT), DIAMOND (8 , 2 , Material.DIAMOND ); - private int armor; - private int toughness; - private Material repair; + private int armor; + private int toughness; + private Material repair; private ArmorTier (int armor, int toughness, Material repair) { diff --git a/src/main/java/nl/pim16aap2/armoredElytra/util/ConfigLoader.java b/src/main/java/nl/pim16aap2/armoredElytra/util/ConfigLoader.java index e5bdf8c..5013c4c 100644 --- a/src/main/java/nl/pim16aap2/armoredElytra/util/ConfigLoader.java +++ b/src/main/java/nl/pim16aap2/armoredElytra/util/ConfigLoader.java @@ -12,197 +12,186 @@ import org.bukkit.Bukkit; import org.bukkit.configuration.file.FileConfiguration; import nl.pim16aap2.armoredElytra.ArmoredElytra; +import nl.pim16aap2.bigDoors.util.ConfigOption; public class ConfigLoader { - private boolean unbreakable; - private boolean noFlightDurability; - private int LEATHER_TO_FULL; - private int GOLD_TO_FULL; - private int IRON_TO_FULL; - private int DIAMONDS_TO_FULL; - private String leatherName; - private String goldName; - private String chainName; - private String ironName; - private String diamondName; - private String elytraLore; - private List allowedEnchantments; - private String usageDeniedMessage; - private String elytraReceivedMessage; - private boolean checkForUpdates; - private boolean allowStats; - private boolean enableDebug; - private boolean uninstallMode; - - // All the comments for the various config options. - private String[] unbreakableComment = - {"Setting this to true will cause armored elytras to be unbreakable.", - "Changing this to false will NOT make unbreakable elytras breakable again!"}; - private String[] flyDurabilityComment = - {"Setting this to true will cause armored elytras to not lose any durability while flying.", - "This is not a permanent option and will affect ALL elytras."}; - private String[] repairComment = - {"Amount of items it takes to fully repair an armored elytra", - "Repair cost for every tier of armored elytra in number of items to repair 100%."}; - private String[] tierNameComment = - {"Name for every armored elytra tier."}; - private String[] enchantmentsComment = - {"List of enchantments that are allowed to be put on an armored elytra.", - "If you do not want to allow any enchantments at all, remove them all and add \"NONE\"", - "You can find supported enchantments here:", - "https://hub.spigotmc.org/javadocs/spigot/org/bukkit/enchantments/Enchantment.html", - "Note that only 1 protection enchantment (PROTECTION_FIRE, PROTECTION_ENVIRONMENTAL etc) can be active on an elytra."}; - private String[] usageDeniedComment = - {"Message players receive when they lack the required permissions to wear a certain armor tier. \"NONE\" = no message. ", - "%ARMOR_TIER% is replaced by the name of the armor tier."}; - private String[] elytraReceivedComment = - {"Message players receive when they are given an armored elytra using commands. \"NONE\" = no message. ", - "%ARMOR_TIER% is replaced by the name of the armor tier."}; - private String[] elytraLoreComment = - {"The lore of armored elytras. \"NONE\" = no lore. %ARMOR_TIER% is replaced by the name of the armor tier."}; - private String[] updateComment = - {"Allow this plugin to check for updates on startup. It will not download new versions!"}; - private String[] bStatsComment = - {"Allow this plugin to send (anonymised) stats using bStats. Please consider keeping it enabled.", - "It has a negligible impact on performance and more users on stats keeps me more motivated to support this plugin!"}; - private String[] debugComment = - {"Print debug messages to console. You will most likely never need this."}; - private String[] uninstallComment = - {"Setting this to true will disable this plugin and remove any armored elytras it can find.", - "It will check player's inventories and their end chest upon login and any regular chest when it is opened.", - "This means it will take a while for all armored elytras to be removed from your server, but it doesn't take up ", - "a lot of resources, so you can just leave it installed and ignore it.", - "Please do not forget to MAKE A BACKUP before enabling this option!"}; - - private ArrayList configOptionsList; + private boolean allowStats; + private boolean unbreakable; + private boolean enableDebug; + private String languageFile; + private int GOLD_TO_FULL; + private int IRON_TO_FULL; + private boolean uninstallMode; + private boolean checkForUpdates; + private int LEATHER_TO_FULL; + private int DIAMONDS_TO_FULL; + private boolean noFlightDurability; + private List allowedEnchantments; + + private ArrayList configOptionsList; private ArmoredElytra plugin; - - public ConfigLoader(ArmoredElytra plugin) - { - this.plugin = plugin; - configOptionsList = new ArrayList(); - makeConfig(); - } - - // Read the current config, the make a new one based on the old one or default values, whichever is applicable. - public void makeConfig() - { - FileConfiguration config = plugin.getConfig(); - - // Read all the options from the config, then put them in a configOption with their name, value and comment. - // THen put all configOptions into an ArrayList. - unbreakable = config.getBoolean("unbreakable" , false); - configOptionsList.add(new ConfigOption ("unbreakable" , unbreakable , unbreakableComment )); - noFlightDurability = config.getBoolean("noFlightDurability", false); - configOptionsList.add(new ConfigOption ("noFlightDurability", noFlightDurability, flyDurabilityComment)); - - LEATHER_TO_FULL = config.getInt ("leatherRepair" , 6); - configOptionsList.add(new ConfigOption ("leatherRepair" , LEATHER_TO_FULL, repairComment)); - GOLD_TO_FULL = config.getInt ("goldRepair" , 5); - configOptionsList.add(new ConfigOption ("goldRepair" , GOLD_TO_FULL)); - IRON_TO_FULL = config.getInt ("ironRepair" , 4); - configOptionsList.add(new ConfigOption ("ironRepair" , IRON_TO_FULL)); - DIAMONDS_TO_FULL = config.getInt ("diamondsRepair", 3); - configOptionsList.add(new ConfigOption ("diamondsRepair", DIAMONDS_TO_FULL)); - - leatherName = config.getString ("leatherName", "&2Leather Armored Elytra" ); - configOptionsList.add(new ConfigOption ("leatherName", leatherName, tierNameComment)); - goldName = config.getString ("goldName" , "&EGolden Armored Elytra" ); - configOptionsList.add(new ConfigOption ("goldName" , goldName )); - chainName = config.getString ("chainName" , "&8Chain Armored Elytra" ); - configOptionsList.add(new ConfigOption ("chainName" , chainName )); - ironName = config.getString ("ironName" , "&7Iron Armored Elytra" ); - configOptionsList.add(new ConfigOption ("ironName" , ironName )); - diamondName = config.getString ("diamondName", "&BDiamond Armored Elytra" ); - configOptionsList.add(new ConfigOption ("diamondName", diamondName )); - - elytraLore = config.getString ("elytraLore"); - configOptionsList.add(new ConfigOption ("elytraLore", elytraLore, elytraLoreComment)); - - usageDeniedMessage = config.getString ("usageDeniedMessage" ); - configOptionsList.add(new ConfigOption ("usageDeniedMessage" , usageDeniedMessage , usageDeniedComment )); - elytraReceivedMessage = config.getString ("elytraReceivedMessage" ); - configOptionsList.add(new ConfigOption ("elytraReceivedMessage", elytraReceivedMessage, elytraReceivedComment)); - - allowedEnchantments = config.getStringList("allowedEnchantments"); - configOptionsList.add(new ConfigOption ("allowedEnchantments", allowedEnchantments, enchantmentsComment )); - - checkForUpdates = config.getBoolean("checkForUpdates", true ); - configOptionsList.add(new ConfigOption ("checkForUpdates", checkForUpdates, updateComment)); - allowStats = config.getBoolean("allowStats" , true ); - configOptionsList.add(new ConfigOption ("allowStats" , allowStats, bStatsComment)); - enableDebug = config.getBoolean("enableDebug" , false); - configOptionsList.add(new ConfigOption ("enableDebug" , enableDebug, debugComment)); - uninstallMode = config.getBoolean("uninstallMode" , false); - configOptionsList.add(new ConfigOption ("uninstallMode" , uninstallMode, uninstallComment)); - - writeConfig(); - } - - // Write new config file. - public void writeConfig() - { - // Write all the config options to the config.yml. - try - { - File dataFolder = plugin.getDataFolder(); - if (!dataFolder.exists()) - dataFolder.mkdir(); + + public ConfigLoader(ArmoredElytra plugin) + { + this.plugin = plugin; + configOptionsList = new ArrayList(); + makeConfig(); + } + + // Read the current config, the make a new one based on the old one or default values, whichever is applicable. + public void makeConfig() + { + // All the comments for the various config options. + String[] unbreakableComment = + { + "Setting this to true will cause armored elytras to be unbreakable.", + "Changing this to false will NOT make unbreakable elytras breakable again!" + }; + String[] flyDurabilityComment = + { + "Setting this to true will cause armored elytras to not lose any durability while flying.", + "This is not a permanent option and will affect ALL elytras." + }; + String[] repairComment = + { + "Amount of items it takes to fully repair an armored elytra", + "Repair cost for every tier of armored elytra in number of items to repair 100%." + }; + String[] enchantmentsComment = + { + "List of enchantments that are allowed to be put on an armored elytra.", + "If you do not want to allow any enchantments at all, remove them all and add \"NONE\"", + "You can find supported enchantments here:", + "https://hub.spigotmc.org/javadocs/spigot/org/bukkit/enchantments/Enchantment.html", + "Note that only 1 protection enchantment (PROTECTION_FIRE, PROTECTION_ENVIRONMENTAL etc) can be active on an elytra." + }; + String[] updateComment = + { + "Allow this plugin to check for updates on startup. It will not download new versions!" + }; + String[] bStatsComment = + { + "Allow this plugin to send (anonymised) stats using bStats. Please consider keeping it enabled.", + "It has a negligible impact on performance and more users on stats keeps me more motivated to support this plugin!" + }; + String[] debugComment = + { + "Print debug messages to console. You will most likely never need this." + }; + String[] uninstallComment = + { + "Setting this to true will disable this plugin and remove any armored elytras it can find.", + "It will check player's inventories and their end chest upon login and any regular chest when it is opened.", + "This means it will take a while for all armored elytras to be removed from your server, but it doesn't take up ", + "a lot of resources, so you can just leave it installed and ignore it.", + "Please do not forget to MAKE A BACKUP before enabling this option!" + }; + String[] languageFileComment = + { + "Specify a language file to be used. Note that en_US.txt will get regenerated!" + }; + + + + FileConfiguration config = plugin.getConfig(); + + // Read all the options from the config, then put them in a configOption with their name, value and comment. + // THen put all configOptions into an ArrayList. + unbreakable = config.getBoolean ("unbreakable" , false); + configOptionsList.add(new ConfigOption ("unbreakable" , unbreakable , unbreakableComment )); + noFlightDurability = config.getBoolean ("noFlightDurability", false); + configOptionsList.add(new ConfigOption ("noFlightDurability", noFlightDurability, flyDurabilityComment)); + + LEATHER_TO_FULL = config.getInt ("leatherRepair" , 6); + configOptionsList.add(new ConfigOption ("leatherRepair" , LEATHER_TO_FULL, repairComment)); + GOLD_TO_FULL = config.getInt ("goldRepair" , 5); + configOptionsList.add(new ConfigOption ("goldRepair" , GOLD_TO_FULL)); + IRON_TO_FULL = config.getInt ("ironRepair" , 4); + configOptionsList.add(new ConfigOption ("ironRepair" , IRON_TO_FULL)); + DIAMONDS_TO_FULL = config.getInt ("diamondsRepair", 3); + configOptionsList.add(new ConfigOption ("diamondsRepair", DIAMONDS_TO_FULL)); + + allowedEnchantments = config.getStringList("allowedEnchantments"); + configOptionsList.add(new ConfigOption ("allowedEnchantments", allowedEnchantments, enchantmentsComment)); + + checkForUpdates = config.getBoolean ("checkForUpdates", true ); + configOptionsList.add(new ConfigOption ("checkForUpdates", checkForUpdates, updateComment)); + allowStats = config.getBoolean ("allowStats" , true ); + configOptionsList.add(new ConfigOption ("allowStats" , allowStats, bStatsComment)); + enableDebug = config.getBoolean ("enableDebug" , false); + configOptionsList.add(new ConfigOption ("enableDebug" , enableDebug, debugComment)); + uninstallMode = config.getBoolean ("uninstallMode" , false); + configOptionsList.add(new ConfigOption ("uninstallMode" , uninstallMode, uninstallComment)); + languageFile = config.getString ("languageFile" , "en_US"); + configOptionsList.add(new ConfigOption ("languageFile" , languageFile, languageFileComment)); + + writeConfig(); + } + + // Write new config file. + public void writeConfig() + { + // Write all the config options to the config.yml. + try + { + File dataFolder = plugin.getDataFolder(); + if (!dataFolder.exists()) + dataFolder.mkdir(); - File saveTo = new File(plugin.getDataFolder(), "config.yml"); - if (!saveTo.exists()) - saveTo.createNewFile(); - else - { - saveTo.delete(); - saveTo.createNewFile(); - } - FileWriter fw = new FileWriter(saveTo, true); - PrintWriter pw = new PrintWriter(fw); - - for (ConfigOption configOption : configOptionsList) - pw.println(configOption.toString()); - - pw.flush(); - pw.close(); - } - catch (IOException e) - { - Bukkit.getLogger().log(Level.SEVERE, "Could not save config.yml! Please contact pim16aap2 and show him the following code:"); - e.printStackTrace(); - } - } - - public Integer getInt(String path) - { - for (ConfigOption configOption : configOptionsList) - if (configOption.getName().equals(path)) - return configOption.getInt(); - return null; - } - - public Boolean getBool(String path) - { - for (ConfigOption configOption : configOptionsList) - if (configOption.getName().equals(path)) - return configOption.getBool(); - return null; - } - - public String getString(String path) - { - for (ConfigOption configOption : configOptionsList) - if (configOption.getName().equals(path)) - return configOption.getString(); - return null; - } - - public List getStringList(String path) - { - for (ConfigOption configOption : configOptionsList) - if (configOption.getName().equals(path)) - return configOption.getStringList(); - return null; - } + File saveTo = new File(plugin.getDataFolder(), "config.yml"); + if (!saveTo.exists()) + saveTo.createNewFile(); + else + { + saveTo.delete(); + saveTo.createNewFile(); + } + FileWriter fw = new FileWriter(saveTo, true); + PrintWriter pw = new PrintWriter(fw); + + for (ConfigOption configOption : configOptionsList) + pw.println(configOption.toString()); + + pw.flush(); + pw.close(); + } + catch (IOException e) + { + Bukkit.getLogger().log(Level.SEVERE, "Could not save config.yml! Please contact pim16aap2 and show him the following code:"); + e.printStackTrace(); + } + } + + public Integer getInt(String path) + { + for (ConfigOption configOption : configOptionsList) + if (configOption.getName().equals(path)) + return configOption.getInt(); + return null; + } + + public Boolean getBool(String path) + { + for (ConfigOption configOption : configOptionsList) + if (configOption.getName().equals(path)) + return configOption.getBool(); + return null; + } + + public String getString(String path) + { + for (ConfigOption configOption : configOptionsList) + if (configOption.getName().equals(path)) + return configOption.getString(); + return null; + } + + public List getStringList(String path) + { + for (ConfigOption configOption : configOptionsList) + if (configOption.getName().equals(path)) + return configOption.getStringList(); + return null; + } } diff --git a/src/main/java/nl/pim16aap2/armoredElytra/util/ConfigOption.java b/src/main/java/nl/pim16aap2/armoredElytra/util/ConfigOption.java index eef2c31..0ae1c85 100644 --- a/src/main/java/nl/pim16aap2/armoredElytra/util/ConfigOption.java +++ b/src/main/java/nl/pim16aap2/armoredElytra/util/ConfigOption.java @@ -4,103 +4,102 @@ import java.util.List; public class ConfigOption { - private String optionName; - List listVal = null; - private Integer intVal = null; - private Boolean boolVal = null; - private String stringVal = null; - private String[] comment; - - public ConfigOption(String optionName, int value, String[] comment) - { - this.optionName = optionName; - this.intVal = value; - this.comment = comment; - } - - public ConfigOption(String optionName, int value) - { - this.optionName = optionName; - this.intVal = value; - this.comment = null; - } - - public ConfigOption(String optionName, boolean value, String[] comment) - { - this.optionName = optionName; - this.boolVal = value; - this.comment = comment; - } - - public ConfigOption(String optionName, boolean value) - { - this.optionName = optionName; - this.boolVal = value; - this.comment = null; - } - - public ConfigOption(String optionName, String value, String[] comment) - { - this.optionName = optionName; - this.stringVal = value; - this.comment = comment; - } - - public ConfigOption(String optionName, String value) - { - this.optionName = optionName; - this.stringVal = value; - this.comment = null; - } - - public ConfigOption(String optionName, List value, String[] comment) - { - this.optionName = optionName; - this.listVal = value; - this.comment = comment; - } - - public ConfigOption(String optionName, List value) - { - this.optionName = optionName; - this.listVal = value; - this.comment = null; - } - - public String stringListToString() - { - String string = ""; - for (String s : listVal) - string += " - " + s + "\n"; - return string; - } - - public String getName() { return optionName; } - public List getStringList() { return listVal ; } - public int getInt() { return intVal ; } - public boolean getBool() { return boolVal ; } - public String getString() { return stringVal ; } + private String optionName; + List listVal = null; + private Integer intVal = null; + private Boolean boolVal = null; + private String stringVal = null; + private String[] comment; + + public ConfigOption(String optionName, int value, String[] comment) + { + this.optionName = optionName; + this.intVal = value; + this.comment = comment; + } + + public ConfigOption(String optionName, int value) + { + this.optionName = optionName; + this.intVal = value; + this.comment = null; + } + + public ConfigOption(String optionName, boolean value, String[] comment) + { + this.optionName = optionName; + this.boolVal = value; + this.comment = comment; + } + + public ConfigOption(String optionName, boolean value) + { + this.optionName = optionName; + this.boolVal = value; + this.comment = null; + } + + public ConfigOption(String optionName, String value, String[] comment) + { + this.optionName = optionName; + this.stringVal = value; + this.comment = comment; + } + + public ConfigOption(String optionName, String value) + { + this.optionName = optionName; + this.stringVal = value; + this.comment = null; + } + + public ConfigOption(String optionName, List value, String[] comment) + { + this.optionName = optionName; + this.listVal = value; + this.comment = comment; + } + + public ConfigOption(String optionName, List value) + { + this.optionName = optionName; + this.listVal = value; + this.comment = null; + } + + public String stringListToString() + { + String string = ""; + for (String s : listVal) + string += " - " + s + "\n"; + return string; + } + + public String getName() { return optionName; } + public List getStringList() { return listVal ; } + public int getInt() { return intVal ; } + public boolean getBool() { return boolVal ; } + public String getString() { return stringVal ; } - public String toString() - { - String string = ""; - - // Print the comments, if there are any. - if (comment != null) - { - string += "\n"; - for (String comLine : comment) - // Prefix every line by a comment-sign (#). - string += "# " + comLine + "\n"; - } - - // Then add the name of the option followed by its value (if it is an int/bool/String/String[]). - string += optionName + ": " + - (intVal != null ? intVal : - boolVal != null ? boolVal : - stringVal != null ? "\'" + stringVal + "\'" : - listVal != null ? "\n" + stringListToString() : null); - - return string; - } + public String toString() + { + String string = ""; + + // Print the comments, if there are any. + if (comment != null) + { + string += "\n"; + for (String comLine : comment) + // Prefix every line by a comment-sign (#). + string += "# " + comLine + "\n"; + } + + // Then add the name of the option followed by its value (if it is an int/bool/String/String[]). + string += optionName + ": " + + (intVal != null ? intVal : + boolVal != null ? boolVal : + stringVal != null ? "\'" + stringVal + "\'" : + listVal != null ? "\n" + stringListToString() : null); + return string; + } } diff --git a/src/main/java/nl/pim16aap2/armoredElytra/util/Messages.java b/src/main/java/nl/pim16aap2/armoredElytra/util/Messages.java new file mode 100644 index 0000000..bb11e2c --- /dev/null +++ b/src/main/java/nl/pim16aap2/armoredElytra/util/Messages.java @@ -0,0 +1,79 @@ +package nl.pim16aap2.armoredElytra.util; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; + +import nl.pim16aap2.armoredElytra.ArmoredElytra; + +public class Messages +{ + private Map messageMap = new HashMap(); + private ArmoredElytra plugin; + private String locale; + private File textFile; + + public Messages(ArmoredElytra plugin) + { + this.plugin = plugin; + this.locale = plugin.getLocale(); + textFile = new File(plugin.getDataFolder(), locale + ".txt"); + readFile(); + } + + // Read locale file. + private void readFile() + { + // Load the default en_US from the resources. + plugin.saveResource("en_US.txt", true); + + try (BufferedReader br = new BufferedReader(new FileReader(this.textFile))) + { + String sCurrentLine; + + while ((sCurrentLine = br.readLine()) != null) + { + String key, value; + String[] parts = sCurrentLine.split("=", 2); + key = parts[0]; + value = parts[1].replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1"); + String[] newLineSplitter = value.split("\\\\n"); // Wut? Can I haz more backslash? + + String values = newLineSplitter[0]; + + for (int idx = 1; idx < newLineSplitter.length; ++idx) + values += "\n" + newLineSplitter[idx]; + + this.messageMap.put(key, values); + } + br.close(); + } + catch (FileNotFoundException e) + { + plugin.myLogger(Level.SEVERE, "Locale file " + this.locale + ".txt does not exist!"); + } + catch (IOException e) + { + plugin.myLogger(Level.SEVERE, "Could not read locale file! (" + this.locale + ".txt)"); + e.printStackTrace(); + } + } + + // Get a string from a key. Returns "null" if null. + public String getString(String key) + { + String value = null; + value = this.messageMap.get(key); + if (value == null) + { + value = "BigDoors: Translation not found! Contact server admin!"; + plugin.myLogger(Level.WARNING, "Failed to get translation for key " + key); + } + return value; + } +} diff --git a/src/main/java/nl/pim16aap2/armoredElytra/util/Metrics.java b/src/main/java/nl/pim16aap2/armoredElytra/util/Metrics.java index a515abe..fc9ed85 100644 --- a/src/main/java/nl/pim16aap2/armoredElytra/util/Metrics.java +++ b/src/main/java/nl/pim16aap2/armoredElytra/util/Metrics.java @@ -31,17 +31,22 @@ import java.util.zip.GZIPOutputStream; * * Check out https://bStats.org/ to learn more about bStats! */ -public class Metrics { +public class Metrics +{ - static { + static + { // You can use the property to disable the check in your test environment - if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { - // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D - final String defaultPackage = new String( - new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'}); - final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); - // We want to make sure nobody just copy & pastes the example and use the wrong package names - if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) { + if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) + { + // Maven's Relocate is clever and changes strings, too. So we have to use this + // little "trick" ... :D + final String defaultPackage = new String(new byte[] { 'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't' }); + final String examplePackage = new String(new byte[] { 'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e' }); + // We want to make sure nobody just copy & pastes the example and use the wrong + // package names + if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) + { throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); } } @@ -70,8 +75,10 @@ public class Metrics { * * @param plugin The plugin which stats should be submitted. */ - public Metrics(JavaPlugin plugin) { - if (plugin == null) { + public Metrics(JavaPlugin plugin) + { + if (plugin == null) + { throw new IllegalArgumentException("Plugin cannot be null!"); } this.plugin = plugin; @@ -82,7 +89,8 @@ public class Metrics { YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); // Check if the config file exists - if (!config.isSet("serverUuid")) { + if (!config.isSet("serverUuid")) + { // Add default values config.addDefault("enabled", true); @@ -92,15 +100,14 @@ public class Metrics { config.addDefault("logFailedRequests", false); // Inform the server owners about bStats - config.options().header( - "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + - "To honor their work, you should not disable it.\n" + - "This has nearly no effect on the server performance!\n" + - "Check out https://bStats.org/ to learn more :)" - ).copyDefaults(true); - try { + config.options().header("bStats collects some data for plugin authors like how many servers are using their plugins.\n" + "To honor their work, you should not disable it.\n" + "This has nearly no effect on the server performance!\n" + "Check out https://bStats.org/ to learn more :)").copyDefaults(true); + try + { config.save(configFile); - } catch (IOException ignored) { } + } + catch (IOException ignored) + { + } } // Load the data @@ -108,16 +115,22 @@ public class Metrics { logFailedRequests = config.getBoolean("logFailedRequests", false); boolean found = false; // Search for all other bStats Metrics classes to see if we are the first one - for (Class service : Bukkit.getServicesManager().getKnownServices()) { - try { + for (Class service : Bukkit.getServicesManager().getKnownServices()) + { + try + { service.getField("B_STATS_VERSION"); // Our identifier :) found = true; // We aren't the first break; - } catch (NoSuchFieldException ignored) { } + } + catch (NoSuchFieldException ignored) + { + } } // Register our service Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); - if (!found) { + if (!found) + { // We are the first! startSubmitting(); } @@ -126,38 +139,48 @@ public class Metrics { /** * Starts the Scheduler which submits our data every 30 minutes. */ - private void startSubmitting() { + private void startSubmitting() + { final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags - timer.scheduleAtFixedRate(new TimerTask() { + timer.scheduleAtFixedRate(new TimerTask() + { @Override - public void run() { - if (!plugin.isEnabled()) { // Plugin was disabled + public void run() + { + if (!plugin.isEnabled()) + { // Plugin was disabled timer.cancel(); return; } - // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler - // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) - Bukkit.getScheduler().runTask(plugin, new Runnable() { + // Nevertheless we want our code to run in the Bukkit main thread, so we have to + // use the Bukkit scheduler + // Don't be afraid! The connection to the bStats server is still async, only the + // stats collection is sync ;) + Bukkit.getScheduler().runTask(plugin, new Runnable() + { @Override - public void run() { + public void run() + { submitData(); } }); } - }, 1000*60*5, 1000*60*30); - // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start - // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! + }, 1000 * 60 * 5, 1000 * 60 * 30); + // Submit the data every 30 minutes, first time after 5 minutes to give other + // plugins enough time to start + // WARNING: Changing the frequency has no effect but your plugin WILL be + // blocked/deleted! // WARNING: Just don't do it! } /** - * Gets the plugin specific data. - * This method is called using Reflection. + * Gets the plugin specific data. This method is called using Reflection. * * @return The plugin specific data. */ @SuppressWarnings("unchecked") - public JSONObject getPluginData() { + public JSONObject getPluginData() + { JSONObject data = new JSONObject(); String pluginName = plugin.getDescription().getName(); @@ -166,10 +189,12 @@ public class Metrics { data.put("pluginName", pluginName); // Append the name of the plugin data.put("pluginVersion", pluginVersion); // Append the version of the plugin JSONArray customCharts = new JSONArray(); - for (CustomChart customChart : charts) { + for (CustomChart customChart : charts) + { // Add the data of the custom charts JSONObject chart = customChart.getRequestJsonObject(); - if (chart == null) { // If the chart is null, we skip it + if (chart == null) + { // If the chart is null, we skip it continue; } customCharts.add(chart); @@ -185,17 +210,20 @@ public class Metrics { * @return The server specific data. */ @SuppressWarnings("unchecked") - private JSONObject getServerData() { + private JSONObject getServerData() + { // Minecraft specific data int playerAmount; - try { + try + { // Around MC 1.8 the return type was changed to a collection from an array, - // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; + // This fixes java.lang.NoSuchMethodError: + // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); - playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) - ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() - : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; - } catch (Exception e) { + playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; + } + catch (Exception e) + { playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed } int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; @@ -230,35 +258,52 @@ public class Metrics { * Collects the data and sends it afterwards. */ @SuppressWarnings("unchecked") - private void submitData() { + private void submitData() + { final JSONObject data = getServerData(); JSONArray pluginData = new JSONArray(); // Search for all other bStats Metrics classes to get their plugin data - for (Class service : Bukkit.getServicesManager().getKnownServices()) { - try { + for (Class service : Bukkit.getServicesManager().getKnownServices()) + { + try + { service.getField("B_STATS_VERSION"); // Our identifier :) - for (RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { - try { + for (RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) + { + try + { pluginData.add(provider.getService().getMethod("getPluginData").invoke(provider.getProvider())); - } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } + } + catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) + { + } } - } catch (NoSuchFieldException ignored) { } + } + catch (NoSuchFieldException ignored) + { + } } data.put("plugins", pluginData); // Create a new thread for the connection to the bStats server - new Thread(new Runnable() { + new Thread(new Runnable() + { @Override - public void run() { - try { + public void run() + { + try + { // Send the data sendData(data); - } catch (Exception e) { + } + catch (Exception e) + { // Something went wrong! :( - if (logFailedRequests) { + if (logFailedRequests) + { plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); } } @@ -272,11 +317,14 @@ public class Metrics { * @param data The data to send. * @throws Exception If the request failed. */ - private static void sendData(JSONObject data) throws Exception { - if (data == null) { + private static void sendData(JSONObject data) throws Exception + { + if (data == null) + { throw new IllegalArgumentException("Data cannot be null!"); } - if (Bukkit.isPrimaryThread()) { + if (Bukkit.isPrimaryThread()) + { throw new IllegalAccessException("This method must not be called from the main thread!"); } HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); @@ -310,8 +358,10 @@ public class Metrics { * @return The gzipped String. * @throws IOException If the compression failed. */ - private static byte[] compress(final String str) throws IOException { - if (str == null) { + private static byte[] compress(final String str) throws IOException + { + if (str == null) + { return null; } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); @@ -324,7 +374,8 @@ public class Metrics { /** * Represents a custom chart. */ - public static abstract class CustomChart { + public static abstract class CustomChart + { // The id of the chart final String chartId; @@ -334,32 +385,41 @@ public class Metrics { * * @param chartId The id of the chart. */ - CustomChart(String chartId) { - if (chartId == null || chartId.isEmpty()) { + CustomChart(String chartId) + { + if (chartId == null || chartId.isEmpty()) + { throw new IllegalArgumentException("ChartId cannot be null or empty!"); } this.chartId = chartId; } @SuppressWarnings("unchecked") - private JSONObject getRequestJsonObject() { + private JSONObject getRequestJsonObject() + { JSONObject chart = new JSONObject(); chart.put("chartId", chartId); - try { + try + { JSONObject data = getChartData(); - if (data == null) { + if (data == null) + { // If the data is null we don't send the chart. return null; } chart.put("data", data); - } catch (Throwable t) { - if (logFailedRequests) { + } + catch (Throwable t) + { + if (logFailedRequests) + { Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); } return null; } return chart; } + protected abstract JSONObject getChartData() throws Exception; } } diff --git a/src/main/java/nl/pim16aap2/armoredElytra/util/Update.java b/src/main/java/nl/pim16aap2/armoredElytra/util/Update.java index 4eadc73..43f1478 100644 --- a/src/main/java/nl/pim16aap2/armoredElytra/util/Update.java +++ b/src/main/java/nl/pim16aap2/armoredElytra/util/Update.java @@ -13,8 +13,7 @@ import org.json.simple.JSONValue; import nl.pim16aap2.armoredElytra.ArmoredElytra; - -public class Update +public class Update { // The project's unique ID @@ -28,17 +27,18 @@ public class Update // Static information for querying the API private static final String API_QUERY = "/servermods/files?projectIds="; - private static final String API_HOST = "https://api.curseforge.com"; - + private static final String API_HOST = "https://api.curseforge.com"; + private String versionName; ArmoredElytra plugin; /** * Check for updates anonymously (keyless) * - * @param projectID The BukkitDev Project ID, found in the "Facts" panel on the right-side of your project page. + * @param projectID The BukkitDev Project ID, found in the "Facts" panel on the + * right-side of your project page. */ - public Update(int projectID, ArmoredElytra plugin) + public Update(int projectID, ArmoredElytra plugin) { this(projectID, null, plugin); } @@ -46,10 +46,12 @@ public class Update /** * Check for updates using your Curse account (with key) * - * @param projectID The BukkitDev Project ID, found in the "Facts" panel on the right-side of your project page. - * @param apiKey Your ServerMods API key, found at https://dev.bukkit.org/home/servermods-apikey/ + * @param projectID The BukkitDev Project ID, found in the "Facts" panel on the + * right-side of your project page. + * @param apiKey Your ServerMods API key, found at + * https://dev.bukkit.org/home/servermods-apikey/ */ - public Update(int projectID, String apiKey, ArmoredElytra plugin) + public Update(int projectID, String apiKey, ArmoredElytra plugin) { this.projectID = projectID; this.apiKey = apiKey; @@ -57,19 +59,17 @@ public class Update query(); } - - - - public int versionCompare(String str1, String str2) + + public int versionCompare(String str1, String str2) { String[] vals1 = str1.split("\\."); String[] vals2 = str2.split("\\."); int i = 0; // set index to first non-equal ordinal or length of shortest version string - while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) - i++; + while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) + i++; // compare first non-equal ordinal number - if (i < vals1.length && i < vals2.length) + if (i < vals1.length && i < vals2.length) { int diff = Integer.valueOf(vals1[i]).compareTo(Integer.valueOf(vals2[i])); return Integer.signum(diff); @@ -78,29 +78,28 @@ public class Update // e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4" return Integer.signum(vals1.length - vals2.length); } - + // Get the latest version of the plugin. public String getLatestVersion() { - if (versionName == null) - return null; - return versionName.replaceAll("Armored Elytra ", ""); + if (versionName == null) + return null; + return versionName.replaceAll("Armored Elytra ", ""); } - - + /** * Query the API to find the latest approved file's details. */ - public void query() + public void query() { URL url = null; - try + try { // Create the URL to query using the project's ID url = new URL(API_HOST + API_QUERY + projectID); - } - catch (MalformedURLException e) + } + catch (MalformedURLException e) { // There was an error creating the URL @@ -108,7 +107,7 @@ public class Update return; } - try + try { // Open a connection and query the project URLConnection conn = url.openConnection(); @@ -128,7 +127,7 @@ public class Update // Parse the array of files from the query's response JSONArray array = (JSONArray) JSONValue.parse(response); - if (array.size() > 0) + if (array.size() > 0) { // Get the newest file's details JSONObject latest = (JSONObject) array.get(array.size() - 1); @@ -136,12 +135,15 @@ public class Update // Get the version's title this.versionName = (String) latest.get(API_NAME_VALUE); } - } - catch (IOException e) + } + catch (IOException e) { // There was an error reading the query. - // Does not print stacktrace, so people won't see any errors from this plugin when Bukkit Dev's servers are down, - // So people won't think the plugin is broken, while the actualy problem is much, much smaller. latestVersion will be null, though, which will prompt a warning in the log instead. + // Does not print stacktrace, so people won't see any errors from this plugin + // when Bukkit Dev's servers are down, + // So people won't think the plugin is broken, while the actualy problem is + // much, much smaller. latestVersion will be null, though, which will prompt a + // warning in the log instead. // e.printStackTrace(); return; diff --git a/src/main/resources/en_US.txt b/src/main/resources/en_US.txt new file mode 100644 index 0000000..c6ffaec --- /dev/null +++ b/src/main/resources/en_US.txt @@ -0,0 +1,12 @@ +TIER.Leather=&2Leather Armored Elytra +TIER.Gold=&EGolden Armored Elytra +TIER.Chain=&8Chain Armored Elytra +TIER.Iron=&7Iron Armored Elytra +TIER.Diamond=&BDiamond Armored Elytra +MESSAGES.Lore=Elytra with %ARMOR_TIER% level protection +MESSAGES.UsageDenied=You do not have the required permissions to wear %ARMOR_TIER%! +MESSAGES.ElytraReceived=&2A(n) %ARMOR_TIER% has been bestowed upon you! +MESSAGES.UninstallMode=&cPlugin in uninstall mode! New Armored Elytras are not allowed! +MESSAGES.UnsupportedTier=&cNot a supported armor tier! Try one of these: leather, gold, chain, iron, diamond. +MESSAGES.NoGivePermission=&cYou do not have the required permission node to give %ARMOR_TIER%s. +MESSAGES.RepairNeeded=&cYou cannot equip this elytra! Please repair it in an anvil first. \ No newline at end of file diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 669d919..136fc92 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,6 +1,6 @@ name: ArmoredElytra main: nl.pim16aap2.armoredElytra.ArmoredElytra -version: 2.4.2 +version: 2.4.6 author: Pim commands: ArmoredElytra: