diff --git a/src/main/java/com/gmail/nossr50/api/AbilityAPI.java b/src/main/java/com/gmail/nossr50/api/AbilityAPI.java index 5922ecbe6..6772df1ca 100644 --- a/src/main/java/com/gmail/nossr50/api/AbilityAPI.java +++ b/src/main/java/com/gmail/nossr50/api/AbilityAPI.java @@ -8,7 +8,8 @@ import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; public final class AbilityAPI { - private AbilityAPI() {} + private AbilityAPI() { + } public static boolean berserkEnabled(Player player) { return UserManager.getPlayer(player).getAbilityMode(SuperAbilityType.BERSERK); diff --git a/src/main/java/com/gmail/nossr50/api/ChatAPI.java b/src/main/java/com/gmail/nossr50/api/ChatAPI.java index 7e4434316..eb37c05e7 100644 --- a/src/main/java/com/gmail/nossr50/api/ChatAPI.java +++ b/src/main/java/com/gmail/nossr50/api/ChatAPI.java @@ -10,18 +10,19 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; public final class ChatAPI { - private ChatAPI() {} + private ChatAPI() { + } /** * Send a message to all members of a party *
* This function is designed for API usage. * - * @param plugin The plugin sending the message - * @param sender The name of the sender + * @param plugin The plugin sending the message + * @param sender The name of the sender * @param displayName The display name of the sender - * @param party The name of the party to send to - * @param message The message to send + * @param party The name of the party to send to + * @param message The message to send */ public static void sendPartyChat(Plugin plugin, String sender, String displayName, String party, String message) { getPartyChatManager(plugin, party).handleChat(sender, displayName, message); @@ -32,9 +33,9 @@ public final class ChatAPI { *
* This function is designed for API usage. * - * @param plugin The plugin sending the message - * @param sender The name of the sender to display in the chat - * @param party The name of the party to send to + * @param plugin The plugin sending the message + * @param sender The name of the sender to display in the chat + * @param party The name of the party to send to * @param message The message to send */ public static void sendPartyChat(Plugin plugin, String sender, String party, String message) { @@ -46,10 +47,10 @@ public final class ChatAPI { *
* This function is designed for API usage. * - * @param plugin The plugin sending the message - * @param sender The name of the sender + * @param plugin The plugin sending the message + * @param sender The name of the sender * @param displayName The display name of the sender - * @param message The message to send + * @param message The message to send */ public static void sendAdminChat(Plugin plugin, String sender, String displayName, String message) { ChatManagerFactory.getChatManager(plugin, ChatMode.ADMIN).handleChat(sender, displayName, message); @@ -60,8 +61,8 @@ public final class ChatAPI { *
* This function is designed for API usage. * - * @param plugin The plugin sending the message - * @param sender The name of the sender to display in the chat + * @param plugin The plugin sending the message + * @param sender The name of the sender to display in the chat * @param message The message to send */ public static void sendAdminChat(Plugin plugin, String sender, String message) { diff --git a/src/main/java/com/gmail/nossr50/api/ExperienceAPI.java b/src/main/java/com/gmail/nossr50/api/ExperienceAPI.java index b091ccfe9..5baff2727 100644 --- a/src/main/java/com/gmail/nossr50/api/ExperienceAPI.java +++ b/src/main/java/com/gmail/nossr50/api/ExperienceAPI.java @@ -19,7 +19,8 @@ import java.util.Set; import java.util.UUID; public final class ExperienceAPI { - private ExperienceAPI() {} + private ExperienceAPI() { + } /** * Returns whether given string is a valid type of skill suitable for the @@ -60,10 +61,9 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param player The player to add XP to + * @param player The player to add XP to * @param skillType The skill to add XP to - * @param XP The amount of XP to add - * + * @param XP The amount of XP to add * @throws InvalidSkillException if the given skill is not valid */ @Deprecated @@ -76,12 +76,11 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param player The player to add XP to - * @param skillType The skill to add XP to - * @param XP The amount of XP to add + * @param player The player to add XP to + * @param skillType The skill to add XP to + * @param XP The amount of XP to add * @param xpGainReason The reason to gain XP - * - * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidSkillException if the given skill is not valid * @throws InvalidXPGainReasonException if the given xpGainReason is not valid */ public static void addRawXP(Player player, String skillType, float XP, String xpGainReason) { @@ -93,13 +92,12 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param player The player to add XP to - * @param skillType The skill to add XP to - * @param XP The amount of XP to add + * @param player The player to add XP to + * @param skillType The skill to add XP to + * @param XP The amount of XP to add * @param xpGainReason The reason to gain XP - * @param isUnshared true if the XP cannot be shared with party members - * - * @throws InvalidSkillException if the given skill is not valid + * @param isUnshared true if the XP cannot be shared with party members + * @throws InvalidSkillException if the given skill is not valid * @throws InvalidXPGainReasonException if the given xpGainReason is not valid */ public static void addRawXP(Player player, String skillType, float XP, String xpGainReason, boolean isUnshared) { @@ -129,15 +127,13 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * + * @param playerName The player to add XP to + * @param skillType The skill to add XP to + * @param XP The amount of XP to add + * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidPlayerException if the given player does not exist in the database * @deprecated We're using uuids to get an offline player * replaced by {@link #addRawXPOffline(UUID uuid, String skillType, float XP)} - * - * @param playerName The player to add XP to - * @param skillType The skill to add XP to - * @param XP The amount of XP to add - * - * @throws InvalidSkillException if the given skill is not valid - * @throws InvalidPlayerException if the given player does not exist in the database */ @Deprecated public static void addRawXPOffline(String playerName, String skillType, float XP) { @@ -149,11 +145,10 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param uuid The UUID of player to add XP to + * @param uuid The UUID of player to add XP to * @param skillType The skill to add XP to - * @param XP The amount of XP to add - * - * @throws InvalidSkillException if the given skill is not valid + * @param XP The amount of XP to add + * @throws InvalidSkillException if the given skill is not valid * @throws InvalidPlayerException if the given player does not exist in the database */ public static void addRawXPOffline(UUID uuid, String skillType, float XP) { @@ -165,10 +160,9 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param player The player to add XP to + * @param player The player to add XP to * @param skillType The skill to add XP to - * @param XP The amount of XP to add - * + * @param XP The amount of XP to add * @throws InvalidSkillException if the given skill is not valid */ @Deprecated @@ -181,12 +175,11 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param player The player to add XP to - * @param skillType The skill to add XP to - * @param XP The amount of XP to add + * @param player The player to add XP to + * @param skillType The skill to add XP to + * @param XP The amount of XP to add * @param xpGainReason The reason to gain XP - * - * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidSkillException if the given skill is not valid * @throws InvalidXPGainReasonException if the given xpGainReason is not valid */ public static void addMultipliedXP(Player player, String skillType, int XP, String xpGainReason) { @@ -199,10 +192,9 @@ public final class ExperienceAPI { * This function is designed for API usage. * * @param playerName The player to add XP to - * @param skillType The skill to add XP to - * @param XP The amount of XP to add - * - * @throws InvalidSkillException if the given skill is not valid + * @param skillType The skill to add XP to + * @param XP The amount of XP to add + * @throws InvalidSkillException if the given skill is not valid * @throws InvalidPlayerException if the given player does not exist in the database */ @Deprecated @@ -215,10 +207,9 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param player The player to add XP to + * @param player The player to add XP to * @param skillType The skill to add XP to - * @param XP The amount of XP to add - * + * @param XP The amount of XP to add * @throws InvalidSkillException if the given skill is not valid */ @Deprecated @@ -231,12 +222,11 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param player The player to add XP to - * @param skillType The skill to add XP to - * @param XP The amount of XP to add + * @param player The player to add XP to + * @param skillType The skill to add XP to + * @param XP The amount of XP to add * @param xpGainReason The reason to gain XP - * - * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidSkillException if the given skill is not valid * @throws InvalidXPGainReasonException if the given xpGainReason is not valid */ public static void addModifiedXP(Player player, String skillType, int XP, String xpGainReason) { @@ -248,13 +238,12 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param player The player to add XP to - * @param skillType The skill to add XP to - * @param XP The amount of XP to add + * @param player The player to add XP to + * @param skillType The skill to add XP to + * @param XP The amount of XP to add * @param xpGainReason The reason to gain XP - * @param isUnshared true if the XP cannot be shared with party members - * - * @throws InvalidSkillException if the given skill is not valid + * @param isUnshared true if the XP cannot be shared with party members + * @throws InvalidSkillException if the given skill is not valid * @throws InvalidXPGainReasonException if the given xpGainReason is not valid */ public static void addModifiedXP(Player player, String skillType, int XP, String xpGainReason, boolean isUnshared) { @@ -274,10 +263,9 @@ public final class ExperienceAPI { * This function is designed for API usage. * * @param playerName The player to add XP to - * @param skillType The skill to add XP to - * @param XP The amount of XP to add - * - * @throws InvalidSkillException if the given skill is not valid + * @param skillType The skill to add XP to + * @param XP The amount of XP to add + * @throws InvalidSkillException if the given skill is not valid * @throws InvalidPlayerException if the given player does not exist in the database */ @Deprecated @@ -293,10 +281,9 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param player The player to add XP to + * @param player The player to add XP to * @param skillType The skill to add XP to - * @param XP The amount of XP to add - * + * @param XP The amount of XP to add * @throws InvalidSkillException if the given skill is not valid */ @Deprecated @@ -310,12 +297,11 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param player The player to add XP to - * @param skillType The skill to add XP to - * @param XP The amount of XP to add + * @param player The player to add XP to + * @param skillType The skill to add XP to + * @param XP The amount of XP to add * @param xpGainReason The reason to gain XP - * - * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidSkillException if the given skill is not valid * @throws InvalidXPGainReasonException if the given xpGainReason is not valid */ public static void addXP(Player player, String skillType, int XP, String xpGainReason) { @@ -328,13 +314,12 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param player The player to add XP to - * @param skillType The skill to add XP to - * @param XP The amount of XP to add + * @param player The player to add XP to + * @param skillType The skill to add XP to + * @param XP The amount of XP to add * @param xpGainReason The reason to gain XP - * @param isUnshared true if the XP cannot be shared with party members - * - * @throws InvalidSkillException if the given skill is not valid + * @param isUnshared true if the XP cannot be shared with party members + * @throws InvalidSkillException if the given skill is not valid * @throws InvalidXPGainReasonException if the given xpGainReason is not valid */ public static void addXP(Player player, String skillType, int XP, String xpGainReason, boolean isUnshared) { @@ -351,11 +336,10 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param player The player to get XP for + * @param player The player to get XP for * @param skillType The skill to get XP for * @return the amount of XP in a given skill - * - * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidSkillException if the given skill is not valid * @throws UnsupportedOperationException if the given skill is a child skill */ public static int getXP(Player player, String skillType) { @@ -368,11 +352,10 @@ public final class ExperienceAPI { * This function is designed for API usage. * * @param playerName The player to get XP for - * @param skillType The skill to get XP for + * @param skillType The skill to get XP for * @return the amount of XP in a given skill - * - * @throws InvalidSkillException if the given skill is not valid - * @throws InvalidPlayerException if the given player does not exist in the database + * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidPlayerException if the given player does not exist in the database * @throws UnsupportedOperationException if the given skill is a child skill */ @Deprecated @@ -385,12 +368,11 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param uuid The player to get XP for + * @param uuid The player to get XP for * @param skillType The skill to get XP for * @return the amount of XP in a given skill - * - * @throws InvalidSkillException if the given skill is not valid - * @throws InvalidPlayerException if the given player does not exist in the database + * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidPlayerException if the given player does not exist in the database * @throws UnsupportedOperationException if the given skill is a child skill */ public static int getOfflineXP(UUID uuid, String skillType) { @@ -402,11 +384,10 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param player The player to get XP for + * @param player The player to get XP for * @param skillType The skill to get XP for * @return the amount of XP in a given skill - * - * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidSkillException if the given skill is not valid * @throws UnsupportedOperationException if the given skill is a child skill */ public static float getXPRaw(Player player, String skillType) { @@ -419,11 +400,10 @@ public final class ExperienceAPI { * This function is designed for API usage. * * @param playerName The player to get XP for - * @param skillType The skill to get XP for + * @param skillType The skill to get XP for * @return the amount of XP in a given skill - * - * @throws InvalidSkillException if the given skill is not valid - * @throws InvalidPlayerException if the given player does not exist in the database + * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidPlayerException if the given player does not exist in the database * @throws UnsupportedOperationException if the given skill is a child skill */ @Deprecated @@ -436,12 +416,11 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param uuid The player to get XP for + * @param uuid The player to get XP for * @param skillType The skill to get XP for * @return the amount of XP in a given skill - * - * @throws InvalidSkillException if the given skill is not valid - * @throws InvalidPlayerException if the given player does not exist in the database + * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidPlayerException if the given player does not exist in the database * @throws UnsupportedOperationException if the given skill is a child skill */ public static float getOfflineXPRaw(UUID uuid, String skillType) { @@ -453,11 +432,10 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param player The player to get the XP amount for + * @param player The player to get the XP amount for * @param skillType The skill to get the XP amount for * @return the total amount of XP needed to reach the next level - * - * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidSkillException if the given skill is not valid * @throws UnsupportedOperationException if the given skill is a child skill */ public static int getXPToNextLevel(Player player, String skillType) { @@ -470,11 +448,10 @@ public final class ExperienceAPI { * This function is designed for API usage. * * @param playerName The player to get XP for - * @param skillType The skill to get XP for + * @param skillType The skill to get XP for * @return the total amount of XP needed to reach the next level - * - * @throws InvalidSkillException if the given skill is not valid - * @throws InvalidPlayerException if the given player does not exist in the database + * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidPlayerException if the given player does not exist in the database * @throws UnsupportedOperationException if the given skill is a child skill */ @Deprecated @@ -487,12 +464,11 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param uuid The player to get XP for + * @param uuid The player to get XP for * @param skillType The skill to get XP for * @return the total amount of XP needed to reach the next level - * - * @throws InvalidSkillException if the given skill is not valid - * @throws InvalidPlayerException if the given player does not exist in the database + * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidPlayerException if the given player does not exist in the database * @throws UnsupportedOperationException if the given skill is a child skill */ public static int getOfflineXPToNextLevel(UUID uuid, String skillType) { @@ -504,11 +480,10 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param player The player to get the XP amount for + * @param player The player to get the XP amount for * @param skillType The skill to get the XP amount for * @return the amount of XP remaining until the next level - * - * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidSkillException if the given skill is not valid * @throws UnsupportedOperationException if the given skill is a child skill */ public static int getXPRemaining(Player player, String skillType) { @@ -525,11 +500,10 @@ public final class ExperienceAPI { * This function is designed for API usage. * * @param playerName The player to get XP for - * @param skillType The skill to get XP for + * @param skillType The skill to get XP for * @return the amount of XP needed to reach the next level - * - * @throws InvalidSkillException if the given skill is not valid - * @throws InvalidPlayerException if the given player does not exist in the database + * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidPlayerException if the given player does not exist in the database * @throws UnsupportedOperationException if the given skill is a child skill */ @Deprecated @@ -545,12 +519,11 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param uuid The player to get XP for + * @param uuid The player to get XP for * @param skillType The skill to get XP for * @return the amount of XP needed to reach the next level - * - * @throws InvalidSkillException if the given skill is not valid - * @throws InvalidPlayerException if the given player does not exist in the database + * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidPlayerException if the given player does not exist in the database * @throws UnsupportedOperationException if the given skill is a child skill */ public static float getOfflineXPRemaining(UUID uuid, String skillType) { @@ -565,10 +538,9 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param player The player to add levels to + * @param player The player to add levels to * @param skillType Type of skill to add levels to - * @param levels Number of levels to add - * + * @param levels Number of levels to add * @throws InvalidSkillException if the given skill is not valid */ public static void addLevel(Player player, String skillType, int levels) { @@ -581,10 +553,9 @@ public final class ExperienceAPI { * This function is designed for API usage. * * @param playerName The player to add levels to - * @param skillType Type of skill to add levels to - * @param levels Number of levels to add - * - * @throws InvalidSkillException if the given skill is not valid + * @param skillType Type of skill to add levels to + * @param levels Number of levels to add + * @throws InvalidSkillException if the given skill is not valid * @throws InvalidPlayerException if the given player does not exist in the database */ @Deprecated @@ -612,11 +583,10 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param uuid The player to add levels to + * @param uuid The player to add levels to * @param skillType Type of skill to add levels to - * @param levels Number of levels to add - * - * @throws InvalidSkillException if the given skill is not valid + * @param levels Number of levels to add + * @throws InvalidSkillException if the given skill is not valid * @throws InvalidPlayerException if the given player does not exist in the database */ public static void addLevelOffline(UUID uuid, String skillType, int levels) { @@ -643,10 +613,9 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param player The player to get the level for + * @param player The player to get the level for * @param skillType The skill to get the level for * @return the level of a given skill - * * @throws InvalidSkillException if the given skill is not valid */ public static int getLevel(Player player, String skillType) { @@ -659,10 +628,9 @@ public final class ExperienceAPI { * This function is designed for API usage. * * @param playerName The player to get the level for - * @param skillType The skill to get the level for + * @param skillType The skill to get the level for * @return the level of a given skill - * - * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidSkillException if the given skill is not valid * @throws InvalidPlayerException if the given player does not exist in the database */ @Deprecated @@ -675,11 +643,10 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param uuid The player to get the level for + * @param uuid The player to get the level for * @param skillType The skill to get the level for * @return the level of a given skill - * - * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidSkillException if the given skill is not valid * @throws InvalidPlayerException if the given player does not exist in the database */ public static int getLevelOffline(UUID uuid, String skillType) { @@ -705,7 +672,6 @@ public final class ExperienceAPI { * * @param playerName The player to get the power level for * @return the power level of the player - * * @throws InvalidPlayerException if the given player does not exist in the database */ @Deprecated @@ -727,7 +693,6 @@ public final class ExperienceAPI { * * @param uuid The player to get the power level for * @return the power level of the player - * * @throws InvalidPlayerException if the given player does not exist in the database */ public static int getPowerLevelOffline(UUID uuid) { @@ -748,7 +713,6 @@ public final class ExperienceAPI { * * @param skillType The skill to get the level cap for * @return the level cap of a given skill - * * @throws InvalidSkillException if the given skill is not valid */ public static int getLevelCap(String skillType) { @@ -762,7 +726,6 @@ public final class ExperienceAPI { * * @param skillType The skill to get the level cap for * @return the level cap of a given skill - * * @throws InvalidSkillException if the given skill is not valid */ public static int getLevelCap(PrimarySkillType skillType) { @@ -771,11 +734,11 @@ public final class ExperienceAPI { /** * Checks whether or not a specific skill is level capped + * * @param skillType target skill * @return true if the skill has a level cap */ - public static boolean isSkillLevelCapped(PrimarySkillType skillType) - { + public static boolean isSkillLevelCapped(PrimarySkillType skillType) { return mcMMO.getPlayerLevelingSettings().isLevelCapEnabled(skillType); } @@ -796,13 +759,11 @@ public final class ExperienceAPI { * This function is designed for API usage. * * @param playerName The name of the player to check - * @param skillType The skill to check - * - * @throws InvalidSkillException if the given skill is not valid - * @throws InvalidPlayerException if the given player does not exist in the database - * @throws UnsupportedOperationException if the given skill is a child skill - * + * @param skillType The skill to check * @return the position on the leaderboard + * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidPlayerException if the given player does not exist in the database + * @throws UnsupportedOperationException if the given skill is a child skill */ @Deprecated public static int getPlayerRankSkill(String playerName, String skillType) { @@ -814,14 +775,12 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param uuid The name of the player to check + * @param uuid The name of the player to check * @param skillType The skill to check - * - * @throws InvalidSkillException if the given skill is not valid - * @throws InvalidPlayerException if the given player does not exist in the database - * @throws UnsupportedOperationException if the given skill is a child skill - * * @return the position on the leaderboard + * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidPlayerException if the given player does not exist in the database + * @throws UnsupportedOperationException if the given skill is a child skill */ public static int getPlayerRankSkill(UUID uuid, String skillType) { return mcMMO.getDatabaseManager().readRank(mcMMO.p.getServer().getOfflinePlayer(uuid).getName()).get(getNonChildSkillType(skillType)); @@ -833,10 +792,8 @@ public final class ExperienceAPI { * This function is designed for API usage. * * @param playerName The name of the player to check - * - * @throws InvalidPlayerException if the given player does not exist in the database - * * @return the position on the power level leaderboard + * @throws InvalidPlayerException if the given player does not exist in the database */ @Deprecated public static int getPlayerRankOverall(String playerName) { @@ -849,10 +806,8 @@ public final class ExperienceAPI { * This function is designed for API usage. * * @param uuid The name of the player to check - * - * @throws InvalidPlayerException if the given player does not exist in the database - * * @return the position on the power level leaderboard + * @throws InvalidPlayerException if the given player does not exist in the database */ public static int getPlayerRankOverall(UUID uuid) { return mcMMO.getDatabaseManager().readRank(mcMMO.p.getServer().getOfflinePlayer(uuid).getName()).get(null); @@ -863,10 +818,9 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param player The player to set the level of - * @param skillType The skill to set the level for + * @param player The player to set the level of + * @param skillType The skill to set the level for * @param skillLevel The value to set the level to - * * @throws InvalidSkillException if the given skill is not valid */ public static void setLevel(Player player, String skillType, int skillLevel) { @@ -879,10 +833,9 @@ public final class ExperienceAPI { * This function is designed for API usage. * * @param playerName The player to set the level of - * @param skillType The skill to set the level for + * @param skillType The skill to set the level for * @param skillLevel The value to set the level to - * - * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidSkillException if the given skill is not valid * @throws InvalidPlayerException if the given player does not exist in the database */ @Deprecated @@ -895,11 +848,10 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param uuid The player to set the level of - * @param skillType The skill to set the level for + * @param uuid The player to set the level of + * @param skillType The skill to set the level for * @param skillLevel The value to set the level to - * - * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidSkillException if the given skill is not valid * @throws InvalidPlayerException if the given player does not exist in the database */ public static void setLevelOffline(UUID uuid, String skillType, int skillLevel) { @@ -911,11 +863,10 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param player The player to set the XP of + * @param player The player to set the XP of * @param skillType The skill to set the XP for - * @param newValue The value to set the XP to - * - * @throws InvalidSkillException if the given skill is not valid + * @param newValue The value to set the XP to + * @throws InvalidSkillException if the given skill is not valid * @throws UnsupportedOperationException if the given skill is a child skill */ public static void setXP(Player player, String skillType, int newValue) { @@ -928,11 +879,10 @@ public final class ExperienceAPI { * This function is designed for API usage. * * @param playerName The player to set the XP of - * @param skillType The skill to set the XP for - * @param newValue The value to set the XP to - * - * @throws InvalidSkillException if the given skill is not valid - * @throws InvalidPlayerException if the given player does not exist in the database + * @param skillType The skill to set the XP for + * @param newValue The value to set the XP to + * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidPlayerException if the given player does not exist in the database * @throws UnsupportedOperationException if the given skill is a child skill */ @Deprecated @@ -945,12 +895,11 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param uuid The player to set the XP of + * @param uuid The player to set the XP of * @param skillType The skill to set the XP for - * @param newValue The value to set the XP to - * - * @throws InvalidSkillException if the given skill is not valid - * @throws InvalidPlayerException if the given player does not exist in the database + * @param newValue The value to set the XP to + * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidPlayerException if the given player does not exist in the database * @throws UnsupportedOperationException if the given skill is a child skill */ public static void setXPOffline(UUID uuid, String skillType, int newValue) { @@ -962,11 +911,10 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param player The player to change the XP of + * @param player The player to change the XP of * @param skillType The skill to change the XP for - * @param xp The amount of XP to remove - * - * @throws InvalidSkillException if the given skill is not valid + * @param xp The amount of XP to remove + * @throws InvalidSkillException if the given skill is not valid * @throws UnsupportedOperationException if the given skill is a child skill */ public static void removeXP(Player player, String skillType, int xp) { @@ -979,11 +927,10 @@ public final class ExperienceAPI { * This function is designed for API usage. * * @param playerName The player to change the XP of - * @param skillType The skill to change the XP for - * @param xp The amount of XP to remove - * - * @throws InvalidSkillException if the given skill is not valid - * @throws InvalidPlayerException if the given player does not exist in the database + * @param skillType The skill to change the XP for + * @param xp The amount of XP to remove + * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidPlayerException if the given player does not exist in the database * @throws UnsupportedOperationException if the given skill is a child skill */ @Deprecated @@ -996,12 +943,11 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param uuid The player to change the XP of + * @param uuid The player to change the XP of * @param skillType The skill to change the XP for - * @param xp The amount of XP to remove - * - * @throws InvalidSkillException if the given skill is not valid - * @throws InvalidPlayerException if the given player does not exist in the database + * @param xp The amount of XP to remove + * @throws InvalidSkillException if the given skill is not valid + * @throws InvalidPlayerException if the given player does not exist in the database * @throws UnsupportedOperationException if the given skill is a child skill */ public static void removeXPOffline(UUID uuid, String skillType, int xp) { @@ -1014,7 +960,6 @@ public final class ExperienceAPI { * This function is designed for API usage. * * @param level The level to get the amount of XP for - * * @throws InvalidFormulaTypeException if the given formulaType is not valid */ public static int getXpNeededToLevel(int level) { @@ -1026,9 +971,8 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @param level The level to get the amount of XP for + * @param level The level to get the amount of XP for * @param formulaType The formula type to get the amount of XP for - * * @throws InvalidFormulaTypeException if the given formulaType is not valid */ public static int getXpNeededToLevel(int level, String formulaType) { @@ -1037,17 +981,14 @@ public final class ExperienceAPI { /** * Will add the appropriate type of XP from the block to the player based on the material of the blocks given + * * @param blockStates the blocks to reward XP for * @param mcMMOPlayer the target player */ - public static void addXpFromBlocks(ArrayList blockStates, McMMOPlayer mcMMOPlayer) - { - for(BlockState bs : blockStates) - { - for(PrimarySkillType skillType : PrimarySkillType.values()) - { - if(ExperienceConfig.getInstance().getXp(skillType, bs.getType()) > 0) - { + public static void addXpFromBlocks(ArrayList blockStates, McMMOPlayer mcMMOPlayer) { + for (BlockState bs : blockStates) { + for (PrimarySkillType skillType : PrimarySkillType.values()) { + if (ExperienceConfig.getInstance().getXp(skillType, bs.getType()) > 0) { mcMMOPlayer.applyXpGain(skillType, ExperienceConfig.getInstance().getXp(skillType, bs.getType()), XPGainReason.PVE, XPGainSource.SELF); } } @@ -1056,16 +997,14 @@ public final class ExperienceAPI { /** * Will add the appropriate type of XP from the block to the player based on the material of the blocks given if it matches the given skillType + * * @param blockStates the blocks to reward XP for * @param mcMMOPlayer the target player - * @param skillType target primary skill + * @param skillType target primary skill */ - public static void addXpFromBlocksBySkill(ArrayList blockStates, McMMOPlayer mcMMOPlayer, PrimarySkillType skillType) - { - for(BlockState bs : blockStates) - { - if(ExperienceConfig.getInstance().getXp(skillType, bs.getType()) > 0) - { + public static void addXpFromBlocksBySkill(ArrayList blockStates, McMMOPlayer mcMMOPlayer, PrimarySkillType skillType) { + for (BlockState bs : blockStates) { + if (ExperienceConfig.getInstance().getXp(skillType, bs.getType()) > 0) { mcMMOPlayer.applyXpGain(skillType, ExperienceConfig.getInstance().getXp(skillType, bs.getType()), XPGainReason.PVE, XPGainSource.SELF); } } @@ -1073,15 +1012,13 @@ public final class ExperienceAPI { /** * Will add the appropriate type of XP from the block to the player based on the material of the blocks given - * @param blockState The target blockstate + * + * @param blockState The target blockstate * @param mcMMOPlayer The target player */ - public static void addXpFromBlock(BlockState blockState, McMMOPlayer mcMMOPlayer) - { - for(PrimarySkillType skillType : PrimarySkillType.values()) - { - if(ExperienceConfig.getInstance().getXp(skillType, blockState.getType()) > 0) - { + public static void addXpFromBlock(BlockState blockState, McMMOPlayer mcMMOPlayer) { + for (PrimarySkillType skillType : PrimarySkillType.values()) { + if (ExperienceConfig.getInstance().getXp(skillType, blockState.getType()) > 0) { mcMMOPlayer.applyXpGain(skillType, ExperienceConfig.getInstance().getXp(skillType, blockState.getType()), XPGainReason.PVE, XPGainSource.SELF); } } @@ -1089,20 +1026,18 @@ public final class ExperienceAPI { /** * Will add the appropriate type of XP from the block to the player based on the material of the blocks given if it matches the given skillType - * @param blockState The target blockstate + * + * @param blockState The target blockstate * @param mcMMOPlayer The target player - * @param skillType target primary skill + * @param skillType target primary skill */ - public static void addXpFromBlockBySkill(BlockState blockState, McMMOPlayer mcMMOPlayer, PrimarySkillType skillType) - { - if(ExperienceConfig.getInstance().getXp(skillType, blockState.getType()) > 0) - { + public static void addXpFromBlockBySkill(BlockState blockState, McMMOPlayer mcMMOPlayer, PrimarySkillType skillType) { + if (ExperienceConfig.getInstance().getXp(skillType, blockState.getType()) > 0) { mcMMOPlayer.applyXpGain(skillType, ExperienceConfig.getInstance().getXp(skillType, blockState.getType()), XPGainReason.PVE, XPGainSource.SELF); } } - // Utility methods follow. private static void addOfflineXP(UUID playerUniqueId, PrimarySkillType skill, int XP) { PlayerProfile profile = getOfflineProfile(playerUniqueId); @@ -1182,10 +1117,10 @@ public final class ExperienceAPI { } /** - * @deprecated Use UserManager::getPlayer(Player player) instead * @param player target player * @return McMMOPlayer for that player if the profile is loaded, otherwise null * @throws McMMOPlayerNotFoundException + * @deprecated Use UserManager::getPlayer(Player player) instead */ @Deprecated private static McMMOPlayer getPlayer(Player player) throws McMMOPlayerNotFoundException { diff --git a/src/main/java/com/gmail/nossr50/api/PartyAPI.java b/src/main/java/com/gmail/nossr50/api/PartyAPI.java index 0c668ea2a..17c4f7b26 100644 --- a/src/main/java/com/gmail/nossr50/api/PartyAPI.java +++ b/src/main/java/com/gmail/nossr50/api/PartyAPI.java @@ -13,7 +13,8 @@ import org.bukkit.entity.Player; import java.util.*; public final class PartyAPI { - private PartyAPI() {} + private PartyAPI() { + } /** * Get the name of the party a player is in. @@ -40,7 +41,7 @@ public final class PartyAPI { * @return true if the player is in a party, false otherwise */ public static boolean inParty(Player player) { - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) return false; return UserManager.getPlayer(player).inParty(); @@ -75,23 +76,22 @@ public final class PartyAPI { *
* This function is designed for API usage. * - * @param player The player to add to the party + * @param player The player to add to the party * @param partyName The party to add the player to * @deprecated parties can have limits, use the other method */ @Deprecated public static void addToParty(Player player, String partyName) { //Check if player profile is loaded - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) return; Party party = PartyManager.getParty(partyName); if (party == null) { party = new Party(new PartyLeader(player.getUniqueId(), player.getName()), partyName); - } else if(mcMMO.getConfigManager().getConfigParty().getPartyGeneral().isPartySizeCapped()) { - if(PartyManager.isPartyFull(player, party)) - { + } else if (mcMMO.getConfigManager().getConfigParty().getPartyGeneral().isPartySizeCapped()) { + if (PartyManager.isPartyFull(player, party)) { NotificationManager.sendPlayerInformation(player, NotificationType.PARTY_MESSAGE, "Commands.Party.PartyFull", party.toString()); return; } @@ -103,15 +103,16 @@ public final class PartyAPI { /** * The max party size of the server * Limits are only enforced if the enforcement setting is on + * * @return the max party size on this server */ - public static int getMaxPartySize() - { + public static int getMaxPartySize() { return mcMMO.getConfigManager().getConfigParty().getPartySizeLimit(); } /** * Checks if parties are currently size capped which is determined by the user config + * * @return true if parties are size capped */ public static boolean isPartySizeCapped() { @@ -123,14 +124,14 @@ public final class PartyAPI { *
* This function is designed for API usage. * - * @param player The player to add to the party - * @param partyName The party to add the player to + * @param player The player to add to the party + * @param partyName The party to add the player to * @param bypassLimit if true bypasses party size limits */ //TODO: bypasslimit not used? public static void addToParty(Player player, String partyName, boolean bypassLimit) { //Check if player profile is loaded - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) return; Party party = PartyManager.getParty(partyName); @@ -151,7 +152,7 @@ public final class PartyAPI { */ public static void removeFromParty(Player player) { //Check if player profile is loaded - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) return; PartyManager.removeFromParty(UserManager.getPlayer(player)); @@ -174,7 +175,7 @@ public final class PartyAPI { *
* This function is designed for API usage. * - * @param partyName The name of the party to set the leader of + * @param partyName The name of the party to set the leader of * @param playerName The playerName to set as leader */ @Deprecated diff --git a/src/main/java/com/gmail/nossr50/api/SkillAPI.java b/src/main/java/com/gmail/nossr50/api/SkillAPI.java index cdb686af8..4f6ec998c 100644 --- a/src/main/java/com/gmail/nossr50/api/SkillAPI.java +++ b/src/main/java/com/gmail/nossr50/api/SkillAPI.java @@ -7,7 +7,8 @@ import java.util.Arrays; import java.util.List; public final class SkillAPI { - private SkillAPI() {} + private SkillAPI() { + } /** * Returns a list of strings with mcMMO's skills diff --git a/src/main/java/com/gmail/nossr50/chat/ChatManager.java b/src/main/java/com/gmail/nossr50/chat/ChatManager.java index d91d5885e..f4d8d03a6 100644 --- a/src/main/java/com/gmail/nossr50/chat/ChatManager.java +++ b/src/main/java/com/gmail/nossr50/chat/ChatManager.java @@ -41,26 +41,22 @@ public abstract class ChatManager { * Party Chat Spying * Party messages will be copied to people with the mcmmo.admin.chatspy permission node */ - if(event instanceof McMMOPartyChatEvent) - { + if (event instanceof McMMOPartyChatEvent) { //We need to grab the party chat name McMMOPartyChatEvent partyChatEvent = (McMMOPartyChatEvent) event; //Find the people with permissions - for(McMMOPlayer mcMMOPlayer : UserManager.getPlayers()) - { + for (McMMOPlayer mcMMOPlayer : UserManager.getPlayers()) { Player player = mcMMOPlayer.getPlayer(); //Check for toggled players - if(mcMMOPlayer.isPartyChatSpying()) - { + if (mcMMOPlayer.isPartyChatSpying()) { Party adminParty = mcMMOPlayer.getParty(); //Only message admins not part of this party - if(adminParty != null) - { + if (adminParty != null) { //TODO: Incorporate JSON - if(!adminParty.getName().equalsIgnoreCase(partyChatEvent.getParty())) + if (!adminParty.getName().equalsIgnoreCase(partyChatEvent.getParty())) player.sendMessage(LocaleLoader.getString("Commands.AdminChatSpy.Chat", partyChatEvent.getParty(), message)); } else { player.sendMessage(LocaleLoader.getString("Commands.AdminChatSpy.Chat", partyChatEvent.getParty(), message)); diff --git a/src/main/java/com/gmail/nossr50/commands/McImportCommand.java b/src/main/java/com/gmail/nossr50/commands/McImportCommand.java index 37fa0e7c0..5e08491fd 100644 --- a/src/main/java/com/gmail/nossr50/commands/McImportCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/McImportCommand.java @@ -70,17 +70,14 @@ public class McImportCommand implements CommandExecutor { materialNames.get(type).add(materialName); } - } - catch (FileNotFoundException e) { + } catch (FileNotFoundException e) { mcMMO.p.getLogger().warning("Could not find " + importFile.getAbsolutePath() + " ! (No such file or directory)"); mcMMO.p.getLogger().warning("Copy and paste latest.log to " + importFile.getParentFile().getAbsolutePath() + " and rename it to import.log"); return; - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); return; - } - finally { + } finally { tryClose(in); } @@ -114,8 +111,7 @@ public class McImportCommand implements CommandExecutor { } try { c.close(); - } - catch (IOException e) { + } catch (IOException e) { e.printStackTrace(); } } @@ -200,14 +196,11 @@ public class McImportCommand implements CommandExecutor { String skillName = "UNIDENTIFIED"; if (materialName.contains("ORE")) { skillName = "Mining"; - } - else if (materialName.contains("LOG") || materialName.contains("LEAVES")) { + } else if (materialName.contains("LOG") || materialName.contains("LEAVES")) { skillName = "Woodcutting"; - } - else if (materialName.contains("GRASS") || materialName.contains("FLOWER") || materialName.contains("CROP")) { + } else if (materialName.contains("GRASS") || materialName.contains("FLOWER") || materialName.contains("CROP")) { skillName = "Herbalism"; - } - else if (materialName.contains("DIRT") || materialName.contains("SAND")) { + } else if (materialName.contains("DIRT") || materialName.contains("SAND")) { skillName = "Excavation"; } @@ -222,8 +215,7 @@ public class McImportCommand implements CommandExecutor { if (skillName.equals("Mining")) { skillContents.add(" " + " " + "Smelting_XP_Gain: 9"); - } - else if (skillName.equals("Woodcutting")) { + } else if (skillName.equals("Woodcutting")) { skillContents.add(" " + " " + "Is_Log: " + materialName.contains("LOG")); } } @@ -239,20 +231,15 @@ public class McImportCommand implements CommandExecutor { String toolType = "UNIDENTIFIED"; if (materialName.contains("PICKAXE")) { toolType = "Pickaxes"; - } - else if (materialName.contains("AXE")) { + } else if (materialName.contains("AXE")) { toolType = "Axes"; - } - else if (materialName.contains("BOW")) { + } else if (materialName.contains("BOW")) { toolType = "Bows"; - } - else if (materialName.contains("HOE")) { + } else if (materialName.contains("HOE")) { toolType = "Hoes"; - } - else if (materialName.contains("SHOVEL") || materialName.contains("SPADE")) { + } else if (materialName.contains("SHOVEL") || materialName.contains("SPADE")) { toolType = "Shovels"; - } - else if (materialName.contains("SWORD")) { + } else if (materialName.contains("SWORD")) { toolType = "Swords"; } @@ -279,14 +266,11 @@ public class McImportCommand implements CommandExecutor { String toolType = "UNIDENTIFIED"; if (materialName.contains("BOOT") || materialName.contains("SHOE")) { toolType = "Boots"; - } - else if (materialName.contains("CHESTPLATE") || materialName.contains("CHEST")) { + } else if (materialName.contains("CHESTPLATE") || materialName.contains("CHEST")) { toolType = "Chestplates"; - } - else if (materialName.contains("HELM") || materialName.contains("HAT")) { + } else if (materialName.contains("HELM") || materialName.contains("HAT")) { toolType = "Helmets"; - } - else if (materialName.contains("LEGGINGS") || materialName.contains("LEGS") || materialName.contains("PANTS")) { + } else if (materialName.contains("LEGGINGS") || materialName.contains("LEGS") || materialName.contains("PANTS")) { toolType = "Leggings"; } diff --git a/src/main/java/com/gmail/nossr50/commands/McconvertCommand.java b/src/main/java/com/gmail/nossr50/commands/McconvertCommand.java index 4202fda4c..3c100003f 100644 --- a/src/main/java/com/gmail/nossr50/commands/McconvertCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/McconvertCommand.java @@ -22,9 +22,6 @@ public class McconvertCommand implements TabExecutor { private static final List DATABASE_TYPES; private static final List SUBCOMMANDS = ImmutableList.of("database", "experience"); - private CommandExecutor databaseConvertCommand = new ConvertDatabaseCommand(); - private CommandExecutor experienceConvertCommand = new ConvertExperienceCommand(); - static { ArrayList formulaTypes = new ArrayList<>(); ArrayList databaseTypes = new ArrayList<>(); @@ -52,14 +49,16 @@ public class McconvertCommand implements TabExecutor { } + private CommandExecutor databaseConvertCommand = new ConvertDatabaseCommand(); + private CommandExecutor experienceConvertCommand = new ConvertExperienceCommand(); + @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { switch (args.length) { case 2: if (args[0].equalsIgnoreCase("database") || args[0].equalsIgnoreCase("db")) { return databaseConvertCommand.onCommand(sender, command, label, args); - } - else if (args[0].equalsIgnoreCase("experience") || args[0].equalsIgnoreCase("xp") || args[1].equalsIgnoreCase("exp")) { + } else if (args[0].equalsIgnoreCase("experience") || args[0].equalsIgnoreCase("xp") || args[1].equalsIgnoreCase("exp")) { return experienceConvertCommand.onCommand(sender, command, label, args); } diff --git a/src/main/java/com/gmail/nossr50/commands/McmmoCommand.java b/src/main/java/com/gmail/nossr50/commands/McmmoCommand.java index e655b75ac..f7b6fb4a8 100644 --- a/src/main/java/com/gmail/nossr50/commands/McmmoCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/McmmoCommand.java @@ -68,7 +68,7 @@ public class McmmoCommand implements CommandExecutor { private void displayOtherCommands(CommandSender sender) { //Don't show them this category if they have none of the permissions - if(!Permissions.skillreset(sender) && !Permissions.mmoedit(sender) && !Permissions.adminChat(sender) && !Permissions.mcgod(sender)) + if (!Permissions.skillreset(sender) && !Permissions.mmoedit(sender) && !Permissions.adminChat(sender) && !Permissions.mcgod(sender)) return; sender.sendMessage(LocaleLoader.getString("Commands.Other")); diff --git a/src/main/java/com/gmail/nossr50/commands/McnotifyCommand.java b/src/main/java/com/gmail/nossr50/commands/McnotifyCommand.java index 08b4e59f2..b26e980fd 100644 --- a/src/main/java/com/gmail/nossr50/commands/McnotifyCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/McnotifyCommand.java @@ -19,7 +19,7 @@ public class McnotifyCommand implements TabExecutor { McMMOPlayer mcMMOPlayer = UserManager.getPlayer((Player) sender); //Not Loaded yet - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); sender.sendMessage(LocaleLoader.getString("Commands.Notifications." + (mcMMOPlayer.useChatNotifications() ? "Off" : "On"))); diff --git a/src/main/java/com/gmail/nossr50/commands/ToggleCommand.java b/src/main/java/com/gmail/nossr50/commands/ToggleCommand.java index 802fb4021..5e71618a9 100644 --- a/src/main/java/com/gmail/nossr50/commands/ToggleCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/ToggleCommand.java @@ -71,7 +71,10 @@ public abstract class ToggleCommand implements TabExecutor { } protected abstract boolean hasOtherPermission(CommandSender sender); + protected abstract boolean hasSelfPermission(CommandSender sender); + protected abstract void applyCommandAction(McMMOPlayer mcMMOPlayer); + protected abstract void sendSuccessMessage(CommandSender sender, String playerName); } diff --git a/src/main/java/com/gmail/nossr50/commands/XprateCommand.java b/src/main/java/com/gmail/nossr50/commands/XprateCommand.java index f3e714644..b2bc3bfc1 100644 --- a/src/main/java/com/gmail/nossr50/commands/XprateCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/XprateCommand.java @@ -25,7 +25,7 @@ public class XprateCommand implements TabExecutor { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { switch (args.length) { case 1: - if (!args[0].equalsIgnoreCase("reset") && !args[0].equalsIgnoreCase("clear")) { + if (!args[0].equalsIgnoreCase("reset") && !args[0].equalsIgnoreCase("clear")) { return false; } @@ -36,12 +36,11 @@ public class XprateCommand implements TabExecutor { if (mcMMO.p.isXPEventEnabled()) { - if(AdvancedConfig.getInstance().useTitlesForXPEvent()) - { + if (AdvancedConfig.getInstance().useTitlesForXPEvent()) { NotificationManager.broadcastTitle(mcMMO.p.getServer(), LocaleLoader.getString("Commands.Event.Stop"), LocaleLoader.getString("Commands.Event.Stop.Subtitle"), - 10, 10*20, 20); + 10, 10 * 20, 20); } mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.Stop")); @@ -65,36 +64,31 @@ public class XprateCommand implements TabExecutor { if (CommandUtils.shouldDisableToggle(args[1])) { mcMMO.p.setXPEventEnabled(false); - } - else if (CommandUtils.shouldEnableToggle(args[1])) { + } else if (CommandUtils.shouldEnableToggle(args[1])) { mcMMO.p.setXPEventEnabled(true); - } - else { + } else { return false; } int newXpRate = Integer.parseInt(args[0]); - if(newXpRate < 0) - { - sender.sendMessage(ChatColor.RED+LocaleLoader.getString("Commands.NegativeNumberWarn")); + if (newXpRate < 0) { + sender.sendMessage(ChatColor.RED + LocaleLoader.getString("Commands.NegativeNumberWarn")); return true; } ExperienceConfig.getInstance().setGlobalXPMultiplier(newXpRate); if (mcMMO.p.isXPEventEnabled()) { - if(AdvancedConfig.getInstance().useTitlesForXPEvent()) - { + if (AdvancedConfig.getInstance().useTitlesForXPEvent()) { NotificationManager.broadcastTitle(mcMMO.p.getServer(), LocaleLoader.getString("Commands.Event.Start"), LocaleLoader.getString("Commands.Event.XP", newXpRate), - 10, 10*20, 20); + 10, 10 * 20, 20); } mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.Start")); mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.XP", newXpRate)); - } - else { + } else { sender.sendMessage(LocaleLoader.getString("Commands.xprate.modified", newXpRate)); } diff --git a/src/main/java/com/gmail/nossr50/commands/chat/ChatCommand.java b/src/main/java/com/gmail/nossr50/commands/chat/ChatCommand.java index 2f7ade1ea..27ab659be 100644 --- a/src/main/java/com/gmail/nossr50/commands/chat/ChatCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/chat/ChatCommand.java @@ -21,8 +21,8 @@ import java.util.ArrayList; import java.util.List; public abstract class ChatCommand implements TabExecutor { - private ChatMode chatMode; protected ChatManager chatManager; + private ChatMode chatMode; public ChatCommand(ChatMode chatMode) { this.chatMode = chatMode; @@ -47,8 +47,7 @@ public abstract class ChatCommand implements TabExecutor { if (mcMMOPlayer.isChatEnabled(chatMode)) { disableChatMode(mcMMOPlayer, sender); - } - else { + } else { enableChatMode(mcMMOPlayer, sender); } diff --git a/src/main/java/com/gmail/nossr50/commands/chat/PartyChatCommand.java b/src/main/java/com/gmail/nossr50/commands/chat/PartyChatCommand.java index 2e2866e6b..d9dfb35c5 100644 --- a/src/main/java/com/gmail/nossr50/commands/chat/PartyChatCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/chat/PartyChatCommand.java @@ -22,7 +22,7 @@ public class PartyChatCommand extends ChatCommand { if (sender instanceof Player) { //Check if player profile is loaded - if(UserManager.getPlayer((Player) sender) == null) + if (UserManager.getPlayer((Player) sender) == null) return; party = UserManager.getPlayer((Player) sender).getParty(); @@ -38,8 +38,7 @@ public class PartyChatCommand extends ChatCommand { } message = buildChatMessage(args, 0); - } - else { + } else { if (args.length < 2) { sender.sendMessage(LocaleLoader.getString("Party.Specify")); return; diff --git a/src/main/java/com/gmail/nossr50/commands/database/ConvertDatabaseCommand.java b/src/main/java/com/gmail/nossr50/commands/database/ConvertDatabaseCommand.java index a7834ee03..cd7f5770d 100644 --- a/src/main/java/com/gmail/nossr50/commands/database/ConvertDatabaseCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/database/ConvertDatabaseCommand.java @@ -41,8 +41,7 @@ public class ConvertDatabaseCommand implements CommandExecutor { } oldDatabase = DatabaseManagerFactory.createCustomDatabaseManager((Class) clazz); - } - catch (Throwable e) { + } catch (Throwable e) { e.printStackTrace(); sender.sendMessage(LocaleLoader.getString("Commands.mcconvert.Database.InvalidType", args[1])); return true; diff --git a/src/main/java/com/gmail/nossr50/commands/database/McremoveCommand.java b/src/main/java/com/gmail/nossr50/commands/database/McremoveCommand.java index 957cbbc99..062b72a8c 100644 --- a/src/main/java/com/gmail/nossr50/commands/database/McremoveCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/database/McremoveCommand.java @@ -26,8 +26,7 @@ public class McremoveCommand implements TabExecutor { if (mcMMO.getDatabaseManager().removeUser(playerName)) { sender.sendMessage(LocaleLoader.getString("Commands.mcremove.Success", playerName)); - } - else { + } else { sender.sendMessage(playerName + " could not be removed from the database."); // Pretty sure this should NEVER happen. } diff --git a/src/main/java/com/gmail/nossr50/commands/experience/AddxpCommand.java b/src/main/java/com/gmail/nossr50/commands/experience/AddxpCommand.java index f2f3a5370..560cb943b 100644 --- a/src/main/java/com/gmail/nossr50/commands/experience/AddxpCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/experience/AddxpCommand.java @@ -25,12 +25,11 @@ public class AddxpCommand extends ExperienceCommand { protected void handleCommand(Player player, PlayerProfile profile, PrimarySkillType skill, int value) { if (player != null) { //Check if player profile is loaded - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) return; UserManager.getPlayer(player).applyXpGain(skill, value, XPGainReason.COMMAND, XPGainSource.COMMAND); - } - else { + } else { profile.addXp(skill, value); profile.scheduleAsyncSave(); } diff --git a/src/main/java/com/gmail/nossr50/commands/experience/ExperienceCommand.java b/src/main/java/com/gmail/nossr50/commands/experience/ExperienceCommand.java index c320c621b..9bec99bfc 100644 --- a/src/main/java/com/gmail/nossr50/commands/experience/ExperienceCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/experience/ExperienceCommand.java @@ -20,6 +20,14 @@ import java.util.List; import java.util.UUID; public abstract class ExperienceCommand implements TabExecutor { + protected static void handleSenderMessage(CommandSender sender, String playerName, PrimarySkillType skill) { + if (skill == null) { + sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.2", playerName)); + } else { + sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.2", skill.getName(), playerName)); + } + } + @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { PrimarySkillType skill; @@ -45,15 +53,13 @@ public abstract class ExperienceCommand implements TabExecutor { skill = null; } - if (skill != null && skill.isChildSkill()) - { + if (skill != null && skill.isChildSkill()) { sender.sendMessage(LocaleLoader.getString("Commands.Skill.ChildSkill")); return true; } //Profile not loaded - if(UserManager.getPlayer(sender.getName()) == null) - { + if (UserManager.getPlayer(sender.getName()) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -78,8 +84,7 @@ public abstract class ExperienceCommand implements TabExecutor { skill = null; } - if (skill != null && skill.isChildSkill()) - { + if (skill != null && skill.isChildSkill()) { sender.sendMessage(LocaleLoader.getString("Commands.Skill.ChildSkill")); return true; } @@ -103,8 +108,7 @@ public abstract class ExperienceCommand implements TabExecutor { } editValues(null, profile, skill, value); - } - else { + } else { editValues(mcMMOPlayer.getPlayer(), mcMMOPlayer.getProfile(), skill, value); } @@ -130,24 +134,19 @@ public abstract class ExperienceCommand implements TabExecutor { } protected abstract boolean permissionsCheckSelf(CommandSender sender); + protected abstract boolean permissionsCheckOthers(CommandSender sender); + protected abstract void handleCommand(Player player, PlayerProfile profile, PrimarySkillType skill, int value); + protected abstract void handlePlayerMessageAll(Player player, int value); + protected abstract void handlePlayerMessageSkill(Player player, int value, PrimarySkillType skill); private boolean validateArguments(CommandSender sender, String skillName, String value) { return !(CommandUtils.isInvalidInteger(sender, value) || (!skillName.equalsIgnoreCase("all") && CommandUtils.isInvalidSkill(sender, skillName))); } - protected static void handleSenderMessage(CommandSender sender, String playerName, PrimarySkillType skill) { - if (skill == null) { - sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.2", playerName)); - } - else { - sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.2", skill.getName(), playerName)); - } - } - protected void editValues(Player player, PlayerProfile profile, PrimarySkillType skill, int value) { if (skill == null) { for (PrimarySkillType primarySkillType : PrimarySkillType.NON_CHILD_SKILLS) { @@ -157,8 +156,7 @@ public abstract class ExperienceCommand implements TabExecutor { if (player != null) { handlePlayerMessageAll(player, value); } - } - else { + } else { handleCommand(player, profile, skill, value); if (player != null) { diff --git a/src/main/java/com/gmail/nossr50/commands/experience/SkillresetCommand.java b/src/main/java/com/gmail/nossr50/commands/experience/SkillresetCommand.java index 4e8a0bcfc..915806510 100644 --- a/src/main/java/com/gmail/nossr50/commands/experience/SkillresetCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/experience/SkillresetCommand.java @@ -27,6 +27,14 @@ import java.util.UUID; * value/quantity argument is removed. */ public class SkillresetCommand implements TabExecutor { + protected static void handleSenderMessage(CommandSender sender, String playerName, PrimarySkillType skill) { + if (skill == null) { + sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.2", playerName)); + } else { + sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.2", skill.getName(), playerName)); + } + } + @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { PrimarySkillType skill; @@ -47,8 +55,7 @@ public class SkillresetCommand implements TabExecutor { if (args[0].equalsIgnoreCase("all")) { skill = null; - } - else { + } else { skill = PrimarySkillType.getSkill(args[1]); } @@ -67,8 +74,7 @@ public class SkillresetCommand implements TabExecutor { if (args[1].equalsIgnoreCase("all")) { skill = null; - } - else { + } else { skill = PrimarySkillType.getSkill(args[1]); } @@ -89,8 +95,7 @@ public class SkillresetCommand implements TabExecutor { } editValues(null, profile, skill); - } - else { + } else { editValues(mcMMOPlayer.getPlayer(), mcMMOPlayer.getProfile(), skill); } @@ -149,15 +154,6 @@ public class SkillresetCommand implements TabExecutor { return skillName.equalsIgnoreCase("all") || !CommandUtils.isInvalidSkill(sender, skillName); } - protected static void handleSenderMessage(CommandSender sender, String playerName, PrimarySkillType skill) { - if (skill == null) { - sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.2", playerName)); - } - else { - sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.2", skill.getName(), playerName)); - } - } - protected void editValues(Player player, PlayerProfile profile, PrimarySkillType skill) { if (skill == null) { for (PrimarySkillType primarySkillType : PrimarySkillType.NON_CHILD_SKILLS) { @@ -167,8 +163,7 @@ public class SkillresetCommand implements TabExecutor { if (player != null) { handlePlayerMessageAll(player); } - } - else { + } else { handleCommand(player, profile, skill); if (player != null) { diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyAcceptCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyAcceptCommand.java index d60868dd9..af4f1bc46 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyAcceptCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyAcceptCommand.java @@ -17,8 +17,7 @@ public class PartyAcceptCommand implements CommandExecutor { Player player = (Player) sender; //Check if player profile is loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyChangeOwnerCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyChangeOwnerCommand.java index ef711fbef..36d855107 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyChangeOwnerCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyChangeOwnerCommand.java @@ -18,8 +18,7 @@ public class PartyChangeOwnerCommand implements CommandExecutor { switch (args.length) { case 2: //Check if player profile is loaded - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyChangePasswordCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyChangePasswordCommand.java index dc641789b..607e03fed 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyChangePasswordCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyChangePasswordCommand.java @@ -11,8 +11,7 @@ import org.bukkit.entity.Player; public class PartyChangePasswordCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyCommand.java index 7b87ff6d8..fb0fa75af 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyCommand.java @@ -39,29 +39,29 @@ public class PartyCommand implements TabExecutor { PARTY_SUBCOMMANDS = ImmutableList.copyOf(subcommands); } - private CommandExecutor partyJoinCommand = new PartyJoinCommand(); - private CommandExecutor partyAcceptCommand = new PartyAcceptCommand(); - private CommandExecutor partyCreateCommand = new PartyCreateCommand(); - private CommandExecutor partyQuitCommand = new PartyQuitCommand(); - private CommandExecutor partyXpShareCommand = new PartyXpShareCommand(); - private CommandExecutor partyItemShareCommand = new PartyItemShareCommand(); - private CommandExecutor partyInviteCommand = new PartyInviteCommand(); - private CommandExecutor partyKickCommand = new PartyKickCommand(); - private CommandExecutor partyDisbandCommand = new PartyDisbandCommand(); - private CommandExecutor partyChangeOwnerCommand = new PartyChangeOwnerCommand(); - private CommandExecutor partyLockCommand = new PartyLockCommand(); + private CommandExecutor partyJoinCommand = new PartyJoinCommand(); + private CommandExecutor partyAcceptCommand = new PartyAcceptCommand(); + private CommandExecutor partyCreateCommand = new PartyCreateCommand(); + private CommandExecutor partyQuitCommand = new PartyQuitCommand(); + private CommandExecutor partyXpShareCommand = new PartyXpShareCommand(); + private CommandExecutor partyItemShareCommand = new PartyItemShareCommand(); + private CommandExecutor partyInviteCommand = new PartyInviteCommand(); + private CommandExecutor partyKickCommand = new PartyKickCommand(); + private CommandExecutor partyDisbandCommand = new PartyDisbandCommand(); + private CommandExecutor partyChangeOwnerCommand = new PartyChangeOwnerCommand(); + private CommandExecutor partyLockCommand = new PartyLockCommand(); private CommandExecutor partyChangePasswordCommand = new PartyChangePasswordCommand(); - private CommandExecutor partyRenameCommand = new PartyRenameCommand(); - private CommandExecutor partyInfoCommand = new PartyInfoCommand(); - private CommandExecutor partyHelpCommand = new PartyHelpCommand(); - private CommandExecutor partyTeleportCommand = new PtpCommand(); - private CommandExecutor partyChatCommand = new PartyChatCommand(); - private CommandExecutor partyAllianceCommand = new PartyAllianceCommand(); + private CommandExecutor partyRenameCommand = new PartyRenameCommand(); + private CommandExecutor partyInfoCommand = new PartyInfoCommand(); + private CommandExecutor partyHelpCommand = new PartyHelpCommand(); + private CommandExecutor partyTeleportCommand = new PtpCommand(); + private CommandExecutor partyChatCommand = new PartyChatCommand(); + private CommandExecutor partyAllianceCommand = new PartyAllianceCommand(); @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { //If the party system is disabled, don't fire this command - if(!mcMMO.getConfigManager().getConfigParty().isPartySystemEnabled()) + if (!mcMMO.getConfigManager().getConfigParty().isPartySystemEnabled()) return true; if (CommandUtils.noConsoleUsage(sender)) { @@ -79,8 +79,7 @@ public class PartyCommand implements TabExecutor { return true; } - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { player.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -210,8 +209,7 @@ public class PartyCommand implements TabExecutor { Player player = (Player) sender; //Not Loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return ImmutableList.of(); } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyCreateCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyCreateCommand.java index ed5b95b72..386b10adb 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyCreateCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyCreateCommand.java @@ -18,8 +18,7 @@ public class PartyCreateCommand implements CommandExecutor { Player player = (Player) sender; McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { player.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyDisbandCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyDisbandCommand.java index 8e10e1719..315fa96b7 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyDisbandCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyDisbandCommand.java @@ -15,8 +15,7 @@ public class PartyDisbandCommand implements CommandExecutor { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { switch (args.length) { case 1: - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyInfoCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyInfoCommand.java index 550950aa2..d5054b0d8 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyInfoCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyInfoCommand.java @@ -22,8 +22,7 @@ public class PartyInfoCommand implements CommandExecutor { switch (args.length) { case 0: case 1: - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -69,8 +68,7 @@ public class PartyInfoCommand implements CommandExecutor { if (isUnlockedFeature(party, partyFeature)) { unlockedPartyFeatures.add(partyFeature.getLocaleString()); - } - else { + } else { lockedPartyFeatures.add(partyFeature.getFeatureLockedLocaleString()); } } @@ -127,7 +125,7 @@ public class PartyInfoCommand implements CommandExecutor { int membersOnline = party.getVisibleMembers(player).size(); player.sendMessage(LocaleLoader.getString("Commands.Party.Members.Header")); - player.sendMessage(LocaleLoader.getString("Commands.Party.MembersNear", nearMembers.size()+1, membersOnline)); + player.sendMessage(LocaleLoader.getString("Commands.Party.MembersNear", nearMembers.size() + 1, membersOnline)); player.sendMessage(party.createMembersList(player)); } } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyInviteCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyInviteCommand.java index 2d79c4fff..15be8037e 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyInviteCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyInviteCommand.java @@ -26,8 +26,7 @@ public class PartyInviteCommand implements CommandExecutor { Player target = mcMMOTarget.getPlayer(); - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -53,12 +52,11 @@ public class PartyInviteCommand implements CommandExecutor { Party playerParty = mcMMOPlayer.getParty(); - if(mcMMO.getConfigManager().getConfigParty().getPartyGeneral().isPartySizeCapped()) - if(PartyManager.isPartyFull(target, playerParty)) - { + if (mcMMO.getConfigManager().getConfigParty().getPartyGeneral().isPartySizeCapped()) + if (PartyManager.isPartyFull(target, playerParty)) { player.sendMessage(LocaleLoader.getString("Commands.Party.PartyFull.Invite", target.getName(), playerParty.toString(), - mcMMO.getConfigManager().getConfigParty().getPartySizeLimit())); + mcMMO.getConfigManager().getConfigParty().getPartySizeLimit())); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyItemShareCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyItemShareCommand.java index 412a18f99..cf7d4e3a5 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyItemShareCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyItemShareCommand.java @@ -17,8 +17,7 @@ import org.bukkit.entity.Player; public class PartyItemShareCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -47,19 +46,16 @@ public class PartyItemShareCommand implements CommandExecutor { if (CommandUtils.shouldEnableToggle(args[2])) { toggle = true; - } - else if (CommandUtils.shouldDisableToggle(args[2])) { + } else if (CommandUtils.shouldDisableToggle(args[2])) { toggle = false; - } - else { + } else { sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", " ")); return true; } try { handleToggleItemShareCategory(party, ItemShareType.valueOf(args[1].toUpperCase()), toggle); - } - catch (IllegalArgumentException ex) { + } catch (IllegalArgumentException ex) { sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", " ")); } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyJoinCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyJoinCommand.java index dd2e87517..f5b2939bd 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyJoinCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyJoinCommand.java @@ -34,8 +34,7 @@ public class PartyJoinCommand implements CommandExecutor { Player player = (Player) sender; - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -62,9 +61,8 @@ public class PartyJoinCommand implements CommandExecutor { return true; } - if(mcMMO.getConfigManager().getConfigParty().getPartyGeneral().isPartySizeCapped()) - if(PartyManager.isPartyFull(player, targetParty)) - { + if (mcMMO.getConfigManager().getConfigParty().getPartyGeneral().isPartySizeCapped()) + if (PartyManager.isPartyFull(player, targetParty)) { player.sendMessage(LocaleLoader.getString("Commands.Party.PartyFull", targetParty.toString())); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyKickCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyKickCommand.java index ed0adde76..b2c9e63a8 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyKickCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyKickCommand.java @@ -18,8 +18,7 @@ public class PartyKickCommand implements CommandExecutor { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { switch (args.length) { case 2: - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyLockCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyLockCommand.java index fdf02ee23..3583afd25 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyLockCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyLockCommand.java @@ -17,8 +17,7 @@ public class PartyLockCommand implements CommandExecutor { case 1: if (args[0].equalsIgnoreCase("lock")) { togglePartyLock(sender, true); - } - else if (args[0].equalsIgnoreCase("unlock")) { + } else if (args[0].equalsIgnoreCase("unlock")) { togglePartyLock(sender, false); } @@ -32,11 +31,9 @@ public class PartyLockCommand implements CommandExecutor { if (CommandUtils.shouldEnableToggle(args[1])) { togglePartyLock(sender, true); - } - else if (CommandUtils.shouldDisableToggle(args[1])) { + } else if (CommandUtils.shouldDisableToggle(args[1])) { togglePartyLock(sender, false); - } - else { + } else { sendUsageStrings(sender); } @@ -54,8 +51,7 @@ public class PartyLockCommand implements CommandExecutor { } private void togglePartyLock(CommandSender sender, boolean lock) { - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyQuitCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyQuitCommand.java index c8cd07fbf..1c10c0d99 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyQuitCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyQuitCommand.java @@ -18,8 +18,7 @@ public class PartyQuitCommand implements CommandExecutor { case 1: Player player = (Player) sender; - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyRenameCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyRenameCommand.java index 592ac4ca7..adebc23c3 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyRenameCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyRenameCommand.java @@ -16,8 +16,7 @@ public class PartyRenameCommand implements CommandExecutor { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { switch (args.length) { case 2: - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartySubcommandType.java b/src/main/java/com/gmail/nossr50/commands/party/PartySubcommandType.java index f4ebdb510..c9c45453d 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartySubcommandType.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartySubcommandType.java @@ -30,20 +30,15 @@ public enum PartySubcommandType { if (commandName.equalsIgnoreCase("?")) { return HELP; - } - else if (commandName.equalsIgnoreCase("q") || commandName.equalsIgnoreCase("leave")) { + } else if (commandName.equalsIgnoreCase("q") || commandName.equalsIgnoreCase("leave")) { return QUIT; - } - else if (commandName.equalsIgnoreCase("leader")) { + } else if (commandName.equalsIgnoreCase("leader")) { return OWNER; - } - else if (commandName.equalsIgnoreCase("xpshare") || commandName.equalsIgnoreCase("shareexp") || commandName.equalsIgnoreCase("sharexp")) { + } else if (commandName.equalsIgnoreCase("xpshare") || commandName.equalsIgnoreCase("shareexp") || commandName.equalsIgnoreCase("sharexp")) { return XPSHARE; - } - else if (commandName.equalsIgnoreCase("shareitem") || commandName.equalsIgnoreCase("shareitems")) { + } else if (commandName.equalsIgnoreCase("shareitem") || commandName.equalsIgnoreCase("shareitems")) { return ITEMSHARE; - } - else if (commandName.equalsIgnoreCase("ally")) { + } else if (commandName.equalsIgnoreCase("ally")) { return ALLIANCE; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyXpShareCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyXpShareCommand.java index cd8d832bd..222fc81c0 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyXpShareCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyXpShareCommand.java @@ -16,8 +16,7 @@ import org.bukkit.entity.Player; public class PartyXpShareCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -33,11 +32,9 @@ public class PartyXpShareCommand implements CommandExecutor { case 2: if (args[1].equalsIgnoreCase("none") || CommandUtils.shouldDisableToggle(args[1])) { handleChangingShareMode(party, ShareMode.NONE); - } - else if (args[1].equalsIgnoreCase("equal") || args[1].equalsIgnoreCase("even") || CommandUtils.shouldEnableToggle(args[1])) { + } else if (args[1].equalsIgnoreCase("equal") || args[1].equalsIgnoreCase("even") || CommandUtils.shouldEnableToggle(args[1])) { handleChangingShareMode(party, ShareMode.EQUAL); - } - else { + } else { sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "xpshare", "")); } diff --git a/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceAcceptCommand.java b/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceAcceptCommand.java index e4854a0cc..33415bc33 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceAcceptCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceAcceptCommand.java @@ -14,8 +14,7 @@ public class PartyAllianceAcceptCommand implements CommandExecutor { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { switch (args.length) { case 2: - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceCommand.java b/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceCommand.java index be4fa911b..03798e2f5 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceCommand.java @@ -20,12 +20,10 @@ import java.util.ArrayList; import java.util.List; public class PartyAllianceCommand implements TabExecutor { + public static final List ALLIANCE_SUBCOMMANDS = ImmutableList.of("invite", "accept", "disband"); private Player player; private Party playerParty; private Party targetParty; - - public static final List ALLIANCE_SUBCOMMANDS = ImmutableList.of("invite", "accept", "disband"); - private CommandExecutor partyAllianceInviteCommand = new PartyAllianceInviteCommand(); private CommandExecutor partyAllianceAcceptCommand = new PartyAllianceAcceptCommand(); private CommandExecutor partyAllianceDisbandCommand = new PartyAllianceDisbandCommand(); @@ -36,8 +34,7 @@ public class PartyAllianceCommand implements TabExecutor { return true; } - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceDisbandCommand.java b/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceDisbandCommand.java index 44829d4c8..b8c31af11 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceDisbandCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceDisbandCommand.java @@ -15,8 +15,7 @@ public class PartyAllianceDisbandCommand implements CommandExecutor { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { switch (args.length) { case 2: - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceInviteCommand.java b/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceInviteCommand.java index 97461021a..1f6f5137b 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceInviteCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceInviteCommand.java @@ -25,8 +25,7 @@ public class PartyAllianceInviteCommand implements CommandExecutor { Player target = mcMMOTarget.getPlayer(); - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptAnyCommand.java b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptAnyCommand.java index a58044f26..e2b784aa1 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptAnyCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptAnyCommand.java @@ -20,8 +20,7 @@ public class PtpAcceptAnyCommand implements CommandExecutor { if (ptpRecord.isConfirmRequired()) { sender.sendMessage(LocaleLoader.getString("Commands.ptp.AcceptAny.Disabled")); - } - else { + } else { sender.sendMessage(LocaleLoader.getString("Commands.ptp.AcceptAny.Enabled")); } diff --git a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptCommand.java b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptCommand.java index 4cd0b2c08..71b2c60bb 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptCommand.java @@ -20,8 +20,7 @@ public class PtpAcceptCommand implements CommandExecutor { return true; } - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -55,8 +54,7 @@ public class PtpAcceptCommand implements CommandExecutor { if (!Permissions.partyTeleportWorld(target, targetWorld)) { target.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", targetWorld.getName())); return true; - } - else if (targetWorld != playerWorld && !Permissions.partyTeleportWorld(target, playerWorld)) { + } else if (targetWorld != playerWorld && !Permissions.partyTeleportWorld(target, playerWorld)) { target.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", playerWorld.getName())); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpCommand.java b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpCommand.java index 654f04f29..6bf0c182c 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpCommand.java @@ -35,6 +35,64 @@ public class PtpCommand implements TabExecutor { private CommandExecutor ptpAcceptAnyCommand = new PtpAcceptAnyCommand(); private CommandExecutor ptpAcceptCommand = new PtpAcceptCommand(); + protected static boolean canTeleport(CommandSender sender, Player player, String targetName) { + McMMOPlayer mcMMOTarget = UserManager.getPlayer(targetName); + + if (!CommandUtils.checkPlayerExistence(sender, targetName, mcMMOTarget)) { + return false; + } + + Player target = mcMMOTarget.getPlayer(); + + if (player.equals(target)) { + player.sendMessage(LocaleLoader.getString("Party.Teleport.Self")); + return false; + } + + if (!PartyManager.inSameParty(player, target)) { + player.sendMessage(LocaleLoader.getString("Party.NotInYourParty", targetName)); + return false; + } + + if (!mcMMOTarget.getPartyTeleportRecord().isEnabled()) { + player.sendMessage(LocaleLoader.getString("Party.Teleport.Disabled", targetName)); + return false; + } + + if (!target.isValid()) { + player.sendMessage(LocaleLoader.getString("Party.Teleport.Dead")); + return false; + } + + return true; + } + + protected static void handleTeleportWarmup(Player teleportingPlayer, Player targetPlayer) { + if (UserManager.getPlayer(targetPlayer) == null) { + targetPlayer.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); + return; + } + + if (UserManager.getPlayer(teleportingPlayer) == null) { + teleportingPlayer.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); + return; + } + + McMMOPlayer mcMMOPlayer = UserManager.getPlayer(teleportingPlayer); + McMMOPlayer mcMMOTarget = UserManager.getPlayer(targetPlayer); + + long warmup = mcMMO.getConfigManager().getConfigParty().getPTP().getPtpWarmup(); + + mcMMOPlayer.actualizeTeleportCommenceLocation(teleportingPlayer); + + if (warmup > 0) { + teleportingPlayer.sendMessage(LocaleLoader.getString("Teleport.Commencing", warmup)); + new TeleportationWarmup(mcMMOPlayer, mcMMOTarget).runTaskLater(mcMMO.p, 20 * warmup); + } else { + EventUtils.handlePartyTeleportEvent(teleportingPlayer, targetPlayer); + } + } + @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (CommandUtils.noConsoleUsage(sender)) { @@ -44,22 +102,20 @@ public class PtpCommand implements TabExecutor { Player player = (Player) sender; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return true; } /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(player.getWorld())) + if (WorldBlacklist.isWorldBlacklisted(player.getWorld())) return true; if (!UserManager.hasPlayerDataKey(player)) { return true; } - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -136,8 +192,7 @@ public class PtpCommand implements TabExecutor { List matches = StringUtil.copyPartialMatches(args[0], TELEPORT_SUBCOMMANDS, new ArrayList<>(TELEPORT_SUBCOMMANDS.size())); if (matches.size() == 0) { - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return ImmutableList.of(); } @@ -182,65 +237,4 @@ public class PtpCommand implements TabExecutor { target.sendMessage(LocaleLoader.getString("Commands.ptp.Request1", player.getName())); target.sendMessage(LocaleLoader.getString("Commands.ptp.Request2", mcMMO.getConfigManager().getConfigParty().getPTP().getPtpRequestTimeout())); } - - protected static boolean canTeleport(CommandSender sender, Player player, String targetName) { - McMMOPlayer mcMMOTarget = UserManager.getPlayer(targetName); - - if (!CommandUtils.checkPlayerExistence(sender, targetName, mcMMOTarget)) { - return false; - } - - Player target = mcMMOTarget.getPlayer(); - - if (player.equals(target)) { - player.sendMessage(LocaleLoader.getString("Party.Teleport.Self")); - return false; - } - - if (!PartyManager.inSameParty(player, target)) { - player.sendMessage(LocaleLoader.getString("Party.NotInYourParty", targetName)); - return false; - } - - if (!mcMMOTarget.getPartyTeleportRecord().isEnabled()) { - player.sendMessage(LocaleLoader.getString("Party.Teleport.Disabled", targetName)); - return false; - } - - if (!target.isValid()) { - player.sendMessage(LocaleLoader.getString("Party.Teleport.Dead")); - return false; - } - - return true; - } - - protected static void handleTeleportWarmup(Player teleportingPlayer, Player targetPlayer) { - if(UserManager.getPlayer(targetPlayer) == null) - { - targetPlayer.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); - return; - } - - if(UserManager.getPlayer(teleportingPlayer) == null) - { - teleportingPlayer.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); - return; - } - - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(teleportingPlayer); - McMMOPlayer mcMMOTarget = UserManager.getPlayer(targetPlayer); - - long warmup = mcMMO.getConfigManager().getConfigParty().getPTP().getPtpWarmup(); - - mcMMOPlayer.actualizeTeleportCommenceLocation(teleportingPlayer); - - if (warmup > 0) { - teleportingPlayer.sendMessage(LocaleLoader.getString("Teleport.Commencing", warmup)); - new TeleportationWarmup(mcMMOPlayer, mcMMOTarget).runTaskLater(mcMMO.p, 20 * warmup); - } - else { - EventUtils.handlePartyTeleportEvent(teleportingPlayer, targetPlayer); - } - } } diff --git a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpToggleCommand.java b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpToggleCommand.java index 1a669cb5c..34c261349 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpToggleCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpToggleCommand.java @@ -20,8 +20,7 @@ public class PtpToggleCommand implements CommandExecutor { if (ptpRecord.isEnabled()) { sender.sendMessage(LocaleLoader.getString("Commands.ptp.Disabled")); - } - else { + } else { sender.sendMessage(LocaleLoader.getString("Commands.ptp.Enabled")); } diff --git a/src/main/java/com/gmail/nossr50/commands/player/InspectCommand.java b/src/main/java/com/gmail/nossr50/commands/player/InspectCommand.java index b1d47ed7e..a215e213f 100644 --- a/src/main/java/com/gmail/nossr50/commands/player/InspectCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/player/InspectCommand.java @@ -65,8 +65,7 @@ public class InspectCommand implements TabExecutor { sender.sendMessage(CommandUtils.displaySkill(profile, skill)); } - } - else { + } else { Player target = mcMMOPlayer.getPlayer(); if (CommandUtils.hidden(sender, target, Permissions.inspectHidden(sender))) { @@ -74,8 +73,7 @@ public class InspectCommand implements TabExecutor { sender.sendMessage(LocaleLoader.getString("Inspect.Offline")); return true; } - } - else if (CommandUtils.tooFar(sender, target, Permissions.inspectFar(sender))) { + } else if (CommandUtils.tooFar(sender, target, Permissions.inspectFar(sender))) { return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/player/MccooldownCommand.java b/src/main/java/com/gmail/nossr50/commands/player/MccooldownCommand.java index 4f290bdb4..eea7ff30f 100644 --- a/src/main/java/com/gmail/nossr50/commands/player/MccooldownCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/player/MccooldownCommand.java @@ -38,8 +38,7 @@ public class MccooldownCommand implements TabExecutor { } } - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { player.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -58,8 +57,7 @@ public class MccooldownCommand implements TabExecutor { if (seconds <= 0) { player.sendMessage(LocaleLoader.getString("Commands.Cooldowns.Row.Y", ability.getName())); - } - else { + } else { player.sendMessage(LocaleLoader.getString("Commands.Cooldowns.Row.N", ability.getName(), seconds)); } } diff --git a/src/main/java/com/gmail/nossr50/commands/player/McrankCommand.java b/src/main/java/com/gmail/nossr50/commands/player/McrankCommand.java index f7fad60d0..36470fcb3 100644 --- a/src/main/java/com/gmail/nossr50/commands/player/McrankCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/player/McrankCommand.java @@ -62,8 +62,7 @@ public class McrankCommand implements TabExecutor { if (CommandUtils.tooFar(sender, player, Permissions.mcrankFar(sender))) { return true; } - } - else if (CommandUtils.inspectOffline(sender, mcMMO.getDatabaseManager().loadPlayerProfile(playerName, false), Permissions.mcrankOffline(sender))) { + } else if (CommandUtils.inspectOffline(sender, mcMMO.getDatabaseManager().loadPlayerProfile(playerName, false), Permissions.mcrankOffline(sender))) { return true; } @@ -91,8 +90,7 @@ public class McrankCommand implements TabExecutor { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName()); - if(mcMMOPlayer == null) - { + if (mcMMOPlayer == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return; } diff --git a/src/main/java/com/gmail/nossr50/commands/player/McstatsCommand.java b/src/main/java/com/gmail/nossr50/commands/player/McstatsCommand.java index 440e54f29..d17a70fbc 100644 --- a/src/main/java/com/gmail/nossr50/commands/player/McstatsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/player/McstatsCommand.java @@ -26,8 +26,7 @@ public class McstatsCommand implements TabExecutor { switch (args.length) { case 0: - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -53,8 +52,7 @@ public class McstatsCommand implements TabExecutor { if (mcMMO.getPlayerLevelingSettings().getConfigSectionLevelCaps().getPowerLevel().isLevelCapEnabled()) { player.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Capped", UserManager.getPlayer(player).getPowerLevel(), powerLevelCap)); - } - else { + } else { player.sendMessage(LocaleLoader.getString("Commands.PowerLevel", UserManager.getPlayer(player).getPowerLevel())); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/AcrobaticsCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/AcrobaticsCommand.java index 1003ecfd3..22efda139 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/AcrobaticsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/AcrobaticsCommand.java @@ -49,31 +49,30 @@ public class AcrobaticsCommand extends SkillCommand { messages.add(getStatMessage(SubSkillType.ACROBATICS_DODGE, dodgeChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", dodgeChanceLucky) : "")); } - + if (canRoll) { AbstractSubSkill abstractSubSkill = InteractionManager.getAbstractByName("Roll"); - if(abstractSubSkill != null) - { + if (abstractSubSkill != null) { double rollChance, graceChance; //Chance to roll at half - RandomChanceSkill roll_rcs = new RandomChanceSkill(player, SubSkillType.ACROBATICS_ROLL); + RandomChanceSkill roll_rcs = new RandomChanceSkill(player, SubSkillType.ACROBATICS_ROLL); //Chance to graceful roll RandomChanceSkill grace_rcs = new RandomChanceSkill(player, SubSkillType.ACROBATICS_ROLL); grace_rcs.setSkillLevel(grace_rcs.getSkillLevel() * 2); //Double Odds //Chance Stat Calculations - rollChance = RandomChanceUtil.getRandomChanceExecutionChance(roll_rcs); - graceChance = RandomChanceUtil.getRandomChanceExecutionChance(grace_rcs); + rollChance = RandomChanceUtil.getRandomChanceExecutionChance(roll_rcs); + graceChance = RandomChanceUtil.getRandomChanceExecutionChance(grace_rcs); //damageThreshold = AdvancedConfig.getInstance().getRollDamageThreshold(); String[] rollStrings = getAbilityDisplayValues(player, SubSkillType.ACROBATICS_ROLL); //Format - double rollChanceLucky = rollChance * 1.333D; + double rollChanceLucky = rollChance * 1.333D; double graceChanceLucky = graceChance * 1.333D; messages.add(getStatMessage(SubSkillType.ACROBATICS_ROLL, rollStrings[0]) diff --git a/src/main/java/com/gmail/nossr50/commands/skills/AlchemyCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/AlchemyCommand.java index b8df20ad4..bda8113a1 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/AlchemyCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/AlchemyCommand.java @@ -18,8 +18,8 @@ public class AlchemyCommand extends SkillCommand { private String brewSpeed; private String brewSpeedLucky; - private int tier; - private int ingredientCount; + private int tier; + private int ingredientCount; private String ingredientList; private boolean canCatalysis; @@ -31,10 +31,9 @@ public class AlchemyCommand extends SkillCommand { protected String[] calculateAbilityDisplayValues(Player player) { //TODO: Needed? - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { player.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); - return new String[] {"DATA NOT LOADED", "DATA NOT LOADED"}; + return new String[]{"DATA NOT LOADED", "DATA NOT LOADED"}; } AlchemyManager alchemyManager = UserManager.getPlayer(player).getAlchemyManager(); diff --git a/src/main/java/com/gmail/nossr50/commands/skills/ArcheryCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/ArcheryCommand.java index 70d3466da..423a56fe9 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/ArcheryCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/ArcheryCommand.java @@ -35,14 +35,14 @@ public class ArcheryCommand extends SkillCommand { retrieveChance = retrieveStrings[0]; retrieveChanceLucky = retrieveStrings[1]; } - + // ARCHERY_DAZE if (canDaze) { String[] dazeStrings = getAbilityDisplayValues(player, SubSkillType.ARCHERY_DAZE); dazeChance = dazeStrings[0]; dazeChanceLucky = dazeStrings[1]; } - + // SKILL SHOT if (canSkillShot) { skillShotBonus = percent.format(Archery.getDamageBonusPercent(player)); @@ -64,17 +64,17 @@ public class ArcheryCommand extends SkillCommand { messages.add(getStatMessage(SubSkillType.ARCHERY_ARROW_RETRIEVAL, retrieveChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", retrieveChanceLucky) : "")); } - + if (canDaze) { messages.add(getStatMessage(SubSkillType.ARCHERY_DAZE, dazeChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", dazeChanceLucky) : "")); } - + if (canSkillShot) { messages.add(getStatMessage(SubSkillType.ARCHERY_SKILL_SHOT, skillShotBonus)); } - if(canUseSubskill(player, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK)) { + if (canUseSubskill(player, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK)) { messages.add(getStatMessage(SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK, String.valueOf(CombatUtils.getLimitBreakDamage(player, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK)))); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/AxesCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/AxesCommand.java index 8b56fc9a9..70ea0a988 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/AxesCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/AxesCommand.java @@ -44,14 +44,14 @@ public class AxesCommand extends SkillCommand { if (canAxeMastery) { axeMasteryDamage = Axes.getAxeMasteryBonusDamage(player); } - + // CRITICAL HIT if (canCritical) { String[] criticalHitStrings = getAbilityDisplayValues(player, SubSkillType.AXES_CRITICAL_STRIKES); critChance = criticalHitStrings[0]; critChanceLucky = criticalHitStrings[1]; } - + // SKULL SPLITTER if (canSkullSplitter) { String[] skullSplitterStrings = calculateLengthDisplayValues(player, skillValue); @@ -76,7 +76,7 @@ public class AxesCommand extends SkillCommand { if (canImpact) { messages.add(LocaleLoader.getString("Ability.Generic.Template", LocaleLoader.getString("Axes.Ability.Bonus.2"), LocaleLoader.getString("Axes.Ability.Bonus.3", impactDamage))); } - + if (canAxeMastery) { messages.add(LocaleLoader.getString("Ability.Generic.Template", LocaleLoader.getString("Axes.Ability.Bonus.0"), LocaleLoader.getString("Axes.Ability.Bonus.1", axeMasteryDamage))); } @@ -85,7 +85,7 @@ public class AxesCommand extends SkillCommand { messages.add(getStatMessage(SubSkillType.AXES_CRITICAL_STRIKES, critChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", critChanceLucky) : "")); } - + if (canGreaterImpact) { messages.add(LocaleLoader.getString("Ability.Generic.Template", LocaleLoader.getString("Axes.Ability.Bonus.4"), LocaleLoader.getString("Axes.Ability.Bonus.5", Axes.greaterImpactBonusDamage))); } @@ -95,7 +95,7 @@ public class AxesCommand extends SkillCommand { + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", skullSplitterLengthEndurance) : "")); } - if(canUseSubskill(player, SubSkillType.AXES_AXES_LIMIT_BREAK)) { + if (canUseSubskill(player, SubSkillType.AXES_AXES_LIMIT_BREAK)) { messages.add(getStatMessage(SubSkillType.AXES_AXES_LIMIT_BREAK, String.valueOf(CombatUtils.getLimitBreakDamage(player, SubSkillType.AXES_AXES_LIMIT_BREAK)))); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/FishingCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/FishingCommand.java index e49e871a4..730066154 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/FishingCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/FishingCommand.java @@ -75,7 +75,7 @@ public class FishingCommand extends SkillCommand { } } - if(totalEnchantChance >= 1) + if (totalEnchantChance >= 1) magicChance = percent.format(totalEnchantChance / 100.0); else magicChance = percent.format(0); @@ -116,8 +116,7 @@ public class FishingCommand extends SkillCommand { biteChance = percent.format((rawBiteChance * 100.0D) * luckyModifier); } - if(canInnerPeace) - { + if (canInnerPeace) { innerPeaceMult = String.valueOf(fishingManager.getInnerPeaceMultiplier()); } } @@ -136,15 +135,15 @@ public class FishingCommand extends SkillCommand { @Override protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { List messages = new ArrayList<>(); - + if (canFishermansDiet) { messages.add(getStatMessage(false, true, SubSkillType.FISHING_FISHERMANS_DIET, String.valueOf(fishermansDietRank))); } - + if (canIceFish) { messages.add(getStatMessage(SubSkillType.FISHING_ICE_FISHING, SubSkillType.FISHING_ICE_FISHING.getLocaleStatDescription())); } - + if (canMagicHunt) { messages.add(getStatMessage(SubSkillType.FISHING_MAGIC_HUNTER, magicChance)); } @@ -153,12 +152,12 @@ public class FishingCommand extends SkillCommand { //TODO: Update this with more details messages.add(getStatMessage(false, true, SubSkillType.FISHING_MASTER_ANGLER, biteChance)); } - + if (canShake) { messages.add(getStatMessage(SubSkillType.FISHING_SHAKE, shakeChance) - + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", shakeChanceLucky) : "")); + + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", shakeChanceLucky) : "")); } - + if (canTreasureHunt) { messages.add(getStatMessage(false, true, SubSkillType.FISHING_TREASURE_HUNTER, String.valueOf(lootTier), String.valueOf(RankUtils.getHighestRank(SubSkillType.FISHING_TREASURE_HUNTER)))); messages.add(getStatMessage(true, true, SubSkillType.FISHING_TREASURE_HUNTER, @@ -170,8 +169,7 @@ public class FishingCommand extends SkillCommand { String.valueOf(recordTreasure))); } - if(canInnerPeace) - { + if (canInnerPeace) { messages.add(getStatMessage(SubSkillType.FISHING_INNER_PEACE, innerPeaceMult)); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/HerbalismCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/HerbalismCommand.java index 3d60f17e2..3519c8e34 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/HerbalismCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/HerbalismCommand.java @@ -41,19 +41,19 @@ public class HerbalismCommand extends SkillCommand { @Override protected void dataCalculations(Player player, float skillValue) { - + // DOUBLE DROPS if (canDoubleDrop) { String[] doubleDropStrings = getAbilityDisplayValues(player, SubSkillType.HERBALISM_DOUBLE_DROPS); doubleDropChance = doubleDropStrings[0]; doubleDropChanceLucky = doubleDropStrings[1]; } - + // FARMERS DIET if (canFarmersDiet) { farmersDietRank = RankUtils.getRank(player, SubSkillType.HERBALISM_FARMERS_DIET); } - + // GREEN TERRA if (canGreenTerra) { String[] greenTerraStrings = calculateLengthDisplayValues(player, skillValue); @@ -104,11 +104,11 @@ public class HerbalismCommand extends SkillCommand { messages.add(getStatMessage(SubSkillType.HERBALISM_DOUBLE_DROPS, doubleDropChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", doubleDropChanceLucky) : "")); } - + if (canFarmersDiet) { messages.add(getStatMessage(false, true, SubSkillType.HERBALISM_FARMERS_DIET, String.valueOf(farmersDietRank))); } - + if (canGreenTerra) { messages.add(getStatMessage(SubSkillType.HERBALISM_GREEN_TERRA, greenTerraLength) + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", greenTerraLengthEndurance) : "")); @@ -123,7 +123,7 @@ public class HerbalismCommand extends SkillCommand { } if (canGreenThumbPlants) { - messages.add(getStatMessage(true, true,SubSkillType.HERBALISM_GREEN_THUMB, String.valueOf(greenThumbStage))); + messages.add(getStatMessage(true, true, SubSkillType.HERBALISM_GREEN_THUMB, String.valueOf(greenThumbStage))); } if (hasHylianLuck) { diff --git a/src/main/java/com/gmail/nossr50/commands/skills/MiningCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/MiningCommand.java index e2ee79d63..d541df3f8 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/MiningCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/MiningCommand.java @@ -50,14 +50,14 @@ public class MiningCommand extends SkillCommand { blastDamageDecrease = percent.format(miningManager.getBlastDamageModifier() / 100.0D); blastRadiusIncrease = miningManager.getBlastRadiusModifier(); } - + // DOUBLE DROPS if (canDoubleDrop) { String[] doubleDropStrings = getAbilityDisplayValues(player, SubSkillType.MINING_DOUBLE_DROPS); doubleDropChance = doubleDropStrings[0]; doubleDropChanceLucky = doubleDropStrings[1]; } - + // SUPER BREAKER if (canSuperBreaker) { String[] superBreakerStrings = calculateLengthDisplayValues(player, skillValue); @@ -83,17 +83,17 @@ public class MiningCommand extends SkillCommand { messages.add(getStatMessage(true, true, SubSkillType.MINING_BLAST_MINING, String.valueOf(blastRadiusIncrease))); //messages.add(LocaleLoader.getString("Mining.Blast.Radius.Increase", blastRadiusIncrease)); } - + if (canBlast) { messages.add(getStatMessage(false, true, SubSkillType.MINING_BLAST_MINING, String.valueOf(blastMiningRank), String.valueOf(RankUtils.getHighestRank(SubSkillType.MINING_BLAST_MINING)), LocaleLoader.getString("Mining.Blast.Effect", oreBonus, debrisReduction, bonusTNTDrops))); //messages.add(LocaleLoader.getString("Mining.Blast.Rank", blastMiningRank, RankUtils.getHighestRank(SubSkillType.MINING_BLAST_MINING), LocaleLoader.getString("Mining.Blast.Effect", oreBonus, debrisReduction, bonusTNTDrops))); } - - if (canDemoExpert) { + + if (canDemoExpert) { messages.add(getStatMessage(SubSkillType.MINING_DEMOLITIONS_EXPERTISE, blastDamageDecrease)); //messages.add(LocaleLoader.getString("Mining.Effect.Decrease", blastDamageDecrease)); } - + if (canDoubleDrop) { messages.add(getStatMessage(SubSkillType.HERBALISM_DOUBLE_DROPS, doubleDropChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", doubleDropChanceLucky) : "")); diff --git a/src/main/java/com/gmail/nossr50/commands/skills/MmoInfoCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/MmoInfoCommand.java index d8ae0aa89..f6582ab93 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/MmoInfoCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/MmoInfoCommand.java @@ -27,26 +27,22 @@ public class MmoInfoCommand implements TabExecutor { /* * Only allow players to use this command */ - if(commandSender instanceof Player) - { - if(args.length < 1) + if (commandSender instanceof Player) { + if (args.length < 1) return false; Player player = (Player) commandSender; - if(Permissions.mmoinfo(player)) - { - if(args == null || args[0] == null) + if (Permissions.mmoinfo(player)) { + if (args == null || args[0] == null) return false; - if(args[0].equalsIgnoreCase( "???")) - { + if (args[0].equalsIgnoreCase("???")) { player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.Header")); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.SubSkillHeader", "???")); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.DetailsHeader")); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.Mystery")); return true; - } else if(InteractionManager.getAbstractByName(args[0]) != null || PrimarySkillType.SUBSKILL_NAMES.contains(args[0])) - { + } else if (InteractionManager.getAbstractByName(args[0]) != null || PrimarySkillType.SUBSKILL_NAMES.contains(args[0])) { displayInfo(player, args[0]); return true; } @@ -70,12 +66,10 @@ public class MmoInfoCommand implements TabExecutor { } } - private void displayInfo(Player player, String subSkillName) - { + private void displayInfo(Player player, String subSkillName) { //Check to see if the skill exists in the new system AbstractSubSkill abstractSubSkill = InteractionManager.getAbstractByName(subSkillName); - if(abstractSubSkill != null) - { + if (abstractSubSkill != null) { /* New System Skills are programmable */ abstractSubSkill.printInfo(player); //TextComponentFactory.sendPlayerUrlHeader(player); @@ -89,9 +83,8 @@ public class MmoInfoCommand implements TabExecutor { player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.OldSkill")); } - for(SubSkillType subSkillType : SubSkillType.values()) - { - if(subSkillType.getNiceNameNoSpaces(subSkillType).equalsIgnoreCase(subSkillName)) + for (SubSkillType subSkillType : SubSkillType.values()) { + if (subSkillType.getNiceNameNoSpaces(subSkillType).equalsIgnoreCase(subSkillName)) subSkillName = subSkillType.getWikiName(subSkillType.toString()); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/RepairCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/RepairCommand.java index fdfbe56e0..cd860ec76 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/RepairCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/RepairCommand.java @@ -105,7 +105,7 @@ public class RepairCommand extends SkillCommand { String.valueOf(arcaneBypass ? 0 : repairManager.getDowngradeEnchantChance()))); //Jesus those parentheses } } - + if (canMasterRepair) { messages.add(getStatMessage(false, true, SubSkillType.REPAIR_REPAIR_MASTERY, repairMasteryBonus)); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/SkillCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/SkillCommand.java index 8547ab771..09299ca3e 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/SkillCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/SkillCommand.java @@ -33,11 +33,9 @@ import java.util.Set; public abstract class SkillCommand implements TabExecutor { protected PrimarySkillType skill; - private String skillName; - protected DecimalFormat percent = new DecimalFormat("##0.00%"); protected DecimalFormat decimal = new DecimalFormat("##0.00"); - + private String skillName; private CommandExecutor skillGuideCommand; public SkillCommand(PrimarySkillType skill) { @@ -46,6 +44,15 @@ public abstract class SkillCommand implements TabExecutor { skillGuideCommand = new SkillGuideCommand(skill); } + public static String[] addItemToFirstPositionOfArray(String itemToAdd, String... existingArray) { + String[] newArray = new String[existingArray.length + 1]; + newArray[0] = itemToAdd; + + System.arraycopy(existingArray, 0, newArray, 1, existingArray.length); + + return newArray; + } + @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (CommandUtils.noConsoleUsage(sender)) { @@ -56,8 +63,7 @@ public abstract class SkillCommand implements TabExecutor { return true; } - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -72,9 +78,8 @@ public abstract class SkillCommand implements TabExecutor { float skillValue = mcMMOPlayer.getSkillLevel(skill); //Send the players a few blank lines to make finding the top of the skill command easier - if(AdvancedConfig.getInstance().doesSkillCommandSendBlankLines()) - for(int i = 0; i < 2; i++) - { + if (AdvancedConfig.getInstance().doesSkillCommandSendBlankLines()) + for (int i = 0; i < 2; i++) { player.sendMessage(""); } @@ -105,8 +110,7 @@ public abstract class SkillCommand implements TabExecutor { //Link Header - if(mcMMO.getConfigManager().getConfigAds().isShowWebsiteLinks()) - { + if (mcMMO.getConfigManager().getConfigAds().isShowWebsiteLinks()) { player.sendMessage(LocaleLoader.getString("Overhaul.mcMMO.Header")); TextComponentFactory.sendPlayerUrlHeader(player); } @@ -114,7 +118,7 @@ public abstract class SkillCommand implements TabExecutor { if (mcMMO.getScoreboardSettings().getScoreboardsEnabled() && mcMMO.getScoreboardSettings().getConfigSectionScoreboardTypes() - .getConfigSectionSkillBoard().isUseThisBoard()) { + .getConfigSectionSkillBoard().isUseThisBoard()) { ScoreboardManager.enablePlayerSkillScoreboard(player, skill); } @@ -146,8 +150,7 @@ public abstract class SkillCommand implements TabExecutor { player.sendMessage(LocaleLoader.getString("Skills.Overhaul.Header", skillName)); - if(!skill.isChildSkill()) - { + if (!skill.isChildSkill()) { /* * NON-CHILD SKILLS */ @@ -173,10 +176,8 @@ public abstract class SkillCommand implements TabExecutor { StringBuilder parentMessage = new StringBuilder(); - for(int i = 0; i < parentList.size(); i++) - { - if(i+1 < parentList.size()) - { + for (int i = 0; i < parentList.size(); i++) { + if (i + 1 < parentList.size()) { parentMessage.append(LocaleLoader.getString("Effects.Child.ParentList", parentList.get(i).getName(), mcMMOPlayer.getSkillLevel(parentList.get(i)))); parentMessage.append(ChatColor.GRAY + ", "); } else { @@ -237,11 +238,9 @@ public abstract class SkillCommand implements TabExecutor { int length; - if(abilityLengthCap <= 0) - { + if (abilityLengthCap <= 0) { length = 2 + (int) (skillValue / abilityLengthVar); - } - else { + } else { length = 2 + (int) (Math.min(abilityLengthCap, skillValue) / abilityLengthVar); } @@ -251,38 +250,25 @@ public abstract class SkillCommand implements TabExecutor { length = Math.min(length, maxLength); } - return new String[] { String.valueOf(length), String.valueOf(enduranceLength) }; + return new String[]{String.valueOf(length), String.valueOf(enduranceLength)}; } - protected String getStatMessage(SubSkillType subSkillType, String... vars) - { + protected String getStatMessage(SubSkillType subSkillType, String... vars) { return getStatMessage(false, false, subSkillType, vars); } - protected String getStatMessage(boolean isExtra, boolean isCustom, SubSkillType subSkillType, String... vars) - { + protected String getStatMessage(boolean isExtra, boolean isCustom, SubSkillType subSkillType, String... vars) { String templateKey = isCustom ? "Ability.Generic.Template.Custom" : "Ability.Generic.Template"; String statDescriptionKey = !isExtra ? subSkillType.getLocaleKeyStatDescription() : subSkillType.getLocaleKeyStatExtraDescription(); - if(isCustom) + if (isCustom) return LocaleLoader.getString(templateKey, LocaleLoader.getString(statDescriptionKey, vars)); - else - { + else { String[] mergedList = addItemToFirstPositionOfArray(LocaleLoader.getString(statDescriptionKey), vars); return LocaleLoader.getString(templateKey, mergedList); } } - - public static String[] addItemToFirstPositionOfArray(String itemToAdd, String... existingArray) { - String[] newArray = new String[existingArray.length + 1]; - newArray[0] = itemToAdd; - - System.arraycopy(existingArray, 0, newArray, 1, existingArray.length); - - return newArray; - } - protected abstract void dataCalculations(Player player, float skillValue); protected abstract void permissionsCheck(Player player); @@ -295,12 +281,12 @@ public abstract class SkillCommand implements TabExecutor { /** * Checks if a player can use a skill - * @param player target player + * + * @param player target player * @param subSkillType target subskill * @return true if the player has permission and has the skill unlocked */ - protected boolean canUseSubskill(Player player, SubSkillType subSkillType) - { + protected boolean canUseSubskill(Player player, SubSkillType subSkillType) { return Permissions.isSubSkillEnabled(player, subSkillType) && RankUtils.hasUnlockedSubskill(player, subSkillType); } } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/SkillGuideCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/SkillGuideCommand.java index 9d9af016a..e85846e6f 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/SkillGuideCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/SkillGuideCommand.java @@ -75,8 +75,7 @@ public class SkillGuideCommand implements CommandExecutor { while (allStrings.size() < 9) { if (pageIndexStart + allStrings.size() > guide.size()) { allStrings.add(""); - } - else { + } else { allStrings.add(guide.get(pageIndexStart + (allStrings.size() - 1))); } } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/SmeltingCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/SmeltingCommand.java index 06b530392..de9742ea2 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/SmeltingCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/SmeltingCommand.java @@ -42,7 +42,7 @@ public class SmeltingCommand extends SkillCommand { str_fluxMiningChance = fluxMiningStrings[0]; str_fluxMiningChanceLucky = fluxMiningStrings[1]; }*/ - + // SECOND SMELT if (canSecondSmelt) { String[] secondSmeltStrings = getAbilityDisplayValues(player, SubSkillType.SMELTING_SECOND_SMELT); @@ -68,7 +68,7 @@ public class SmeltingCommand extends SkillCommand { + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", str_fluxMiningChanceLucky) : "")); //messages.add(LocaleLoader.getString("Smelting.Ability.FluxMining", str_fluxMiningChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", str_fluxMiningChanceLucky) : "")); }*/ - + if (canFuelEfficiency) { messages.add(getStatMessage(false, true, SubSkillType.SMELTING_FUEL_EFFICIENCY, burnTimeModifier)); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/SwordsCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/SwordsCommand.java index 4d7b7d88c..813ce4e31 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/SwordsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/SwordsCommand.java @@ -49,7 +49,7 @@ public class SwordsCommand extends SkillCommand { bleedChance = bleedStrings[0]; bleedChanceLucky = bleedStrings[1]; } - + // SERRATED STRIKES if (canSerratedStrike) { String[] serratedStrikesStrings = calculateLengthDisplayValues(player, skillValue); @@ -70,8 +70,8 @@ public class SwordsCommand extends SkillCommand { List messages = new ArrayList<>(); int ruptureTicks = UserManager.getPlayer(player).getSwordsManager().getRuptureBleedTicks(); - double ruptureDamagePlayers = RankUtils.getRank(player, SubSkillType.SWORDS_RUPTURE) >= 3 ? AdvancedConfig.getInstance().getRuptureDamagePlayer() * 1.5D : AdvancedConfig.getInstance().getRuptureDamagePlayer(); - double ruptureDamageMobs = RankUtils.getRank(player, SubSkillType.SWORDS_RUPTURE) >= 3 ? AdvancedConfig.getInstance().getRuptureDamageMobs() * 1.5D : AdvancedConfig.getInstance().getRuptureDamageMobs(); + double ruptureDamagePlayers = RankUtils.getRank(player, SubSkillType.SWORDS_RUPTURE) >= 3 ? AdvancedConfig.getInstance().getRuptureDamagePlayer() * 1.5D : AdvancedConfig.getInstance().getRuptureDamagePlayer(); + double ruptureDamageMobs = RankUtils.getRank(player, SubSkillType.SWORDS_RUPTURE) >= 3 ? AdvancedConfig.getInstance().getRuptureDamageMobs() * 1.5D : AdvancedConfig.getInstance().getRuptureDamageMobs(); if (canCounter) { messages.add(getStatMessage(SubSkillType.SWORDS_COUNTER_ATTACK, counterChance) @@ -94,13 +94,12 @@ public class SwordsCommand extends SkillCommand { + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", serratedStrikesLengthEndurance) : "")); } - if(canUseSubskill(player, SubSkillType.SWORDS_STAB)) - { + if (canUseSubskill(player, SubSkillType.SWORDS_STAB)) { messages.add(getStatMessage(SubSkillType.SWORDS_STAB, String.valueOf(UserManager.getPlayer(player).getSwordsManager().getStabDamage()))); } - if(canUseSubskill(player, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK)) { + if (canUseSubskill(player, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK)) { messages.add(getStatMessage(SubSkillType.SWORDS_SWORDS_LIMIT_BREAK, String.valueOf(CombatUtils.getLimitBreakDamage(player, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK)))); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/UnarmedCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/UnarmedCommand.java index f479369cf..9062e6a1b 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/UnarmedCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/UnarmedCommand.java @@ -43,7 +43,7 @@ public class UnarmedCommand extends SkillCommand { deflectChance = deflectStrings[0]; deflectChanceLucky = deflectStrings[1]; } - + // BERSERK if (canBerserk) { String[] berserkStrings = calculateLengthDisplayValues(player, skillValue); @@ -90,19 +90,19 @@ public class UnarmedCommand extends SkillCommand { + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", deflectChanceLucky) : "")); //messages.add(LocaleLoader.getString("Unarmed.Ability.Chance.ArrowDeflect", deflectChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", deflectChanceLucky) : "")); } - + if (canBerserk) { messages.add(getStatMessage(SubSkillType.UNARMED_BERSERK, berserkLength) + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", berserkLengthEndurance) : "")); //messages.add(LocaleLoader.getString("Unarmed.Ability.Berserk.Length", berserkLength) + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", berserkLengthEndurance) : "")); } - + if (canDisarm) { messages.add(getStatMessage(SubSkillType.UNARMED_DISARM, disarmChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", disarmChanceLucky) : "")); //messages.add(LocaleLoader.getString("Unarmed.Ability.Chance.Disarm", disarmChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", disarmChanceLucky) : "")); } - + if (canIronArm) { messages.add(LocaleLoader.getString("Ability.Generic.Template", LocaleLoader.getString("Unarmed.Ability.Bonus.0"), LocaleLoader.getString("Unarmed.Ability.Bonus.1", ironArmBonus))); } @@ -113,7 +113,7 @@ public class UnarmedCommand extends SkillCommand { //messages.add(LocaleLoader.getString("Unarmed.Ability.Chance.IronGrip", ironGripChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", ironGripChanceLucky) : "")); } - if(canUseSubskill(player, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK)) { + if (canUseSubskill(player, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK)) { messages.add(getStatMessage(SubSkillType.UNARMED_UNARMED_LIMIT_BREAK, String.valueOf(CombatUtils.getLimitBreakDamage(player, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK)))); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/WoodcuttingCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/WoodcuttingCommand.java index bb97a3ad2..c9d9478b6 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/WoodcuttingCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/WoodcuttingCommand.java @@ -35,7 +35,7 @@ public class WoodcuttingCommand extends SkillCommand { if (canDoubleDrop) { setDoubleDropClassicChanceStrings(player); } - + // TREE FELLER if (canTreeFell) { String[] treeFellerStrings = calculateLengthDisplayValues(player, skillValue); @@ -68,7 +68,7 @@ public class WoodcuttingCommand extends SkillCommand { messages.add(getStatMessage(SubSkillType.WOODCUTTING_HARVEST_LUMBER, doubleDropChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", doubleDropChanceLucky) : "")); } - + if (canLeafBlow) { messages.add(LocaleLoader.getString("Ability.Generic.Template", LocaleLoader.getString("Woodcutting.Ability.0"), LocaleLoader.getString("Woodcutting.Ability.1"))); } diff --git a/src/main/java/com/gmail/nossr50/config/AdvancedConfig.java b/src/main/java/com/gmail/nossr50/config/AdvancedConfig.java index 3e74c5bda..cc40aaa51 100644 --- a/src/main/java/com/gmail/nossr50/config/AdvancedConfig.java +++ b/src/main/java/com/gmail/nossr50/config/AdvancedConfig.java @@ -130,16 +130,12 @@ public class AdvancedConfig extends ConfigValidated { super("advanced", mcMMO.p.getDataFolder().getAbsoluteFile(), ConfigConstants.RELATIVE_PATH_CONFIG_DIR, true, true, true, true); } - @Override - public void unload() { - //do nothing - } - /** * This grabs an instance of this config class from the Config Manager * This method is deprecated and will be removed in the future - * @see mcMMO#getConfigManager() + * * @return the instance of this config + * @see mcMMO#getConfigManager() * @deprecated Please use mcMMO.getConfigManager() to grab a specific config instead */ @Deprecated @@ -147,6 +143,11 @@ public class AdvancedConfig extends ConfigValidated { return mcMMO.getConfigManager().getAdvancedConfig(); } + @Override + public void unload() { + //do nothing + } + /** * The version of this config * @@ -239,8 +240,7 @@ public class AdvancedConfig extends ConfigValidated { } /* AXES */ - if(getAxeMasteryRankDamageMultiplier() < 0) - { + if (getAxeMasteryRankDamageMultiplier() < 0) { reason.add(SKILLS + "." + AXES + "." + AXE_MASTERY + "." + RANK_DAMAGE_MULTIPLIER + " should be at least 0!"); } @@ -499,10 +499,11 @@ public class AdvancedConfig extends ConfigValidated { /** * This returns the maximum level at which superabilities will stop lengthening from scaling alongside skill level. * It returns a different value depending on whether or not the server is in retro mode + * * @return the level at which abilities stop increasing in length */ public int getAbilityLengthCap() { - if(!mcMMO.isRetroModeEnabled()) + if (!mcMMO.isRetroModeEnabled()) return getIntValue(SKILLS, GENERAL, ABILITY, LENGTH, STANDARD, CAP_LEVEL); else return getIntValue(SKILLS, GENERAL, ABILITY, LENGTH, RETRO_MODE, CAP_LEVEL); @@ -511,28 +512,32 @@ public class AdvancedConfig extends ConfigValidated { /** * This returns the frequency at which abilities will increase in length * It returns a different value depending on whether or not the server is in retro mode + * * @return the number of levels required per ability length increase */ public int getAbilityLength() { - if(!mcMMO.isRetroModeEnabled()) + if (!mcMMO.isRetroModeEnabled()) return getIntValue(SKILLS, GENERAL, ABILITY, LENGTH, STANDARD, INCREASE_LEVEL); else return getIntValue(SKILLS, GENERAL, ABILITY, LENGTH, RETRO_MODE, INCREASE_LEVEL); } - public int getEnchantBuff() { return getIntValue(SKILLS, GENERAL, ABILITY, ENCHANT_BUFF); } + public int getEnchantBuff() { + return getIntValue(SKILLS, GENERAL, ABILITY, ENCHANT_BUFF); + } /** * Grabs the max bonus level for a skill used in RNG calculations * All max level values in the config are multiplied by 10 if the server is in retro mode as the values in the config are based around the new 1-100 skill system scaling * A value of 10 in the file will be returned as 100 for retro mode servers to accommodate the change in scaling + * * @param subSkillType target subskill * @return the level at which this skills max benefits will be reached on the curve */ public int getMaxBonusLevel(SubSkillType subSkillType) { String[] category = subSkillType.getAdvConfigAddress(); - - if(!mcMMO.isRetroModeEnabled()) + + if (!mcMMO.isRetroModeEnabled()) return getIntValue(category[0], category[1], category[2], MAX_BONUS_LEVEL, STANDARD); else return getIntValue(category[0], category[1], category[2], MAX_BONUS_LEVEL, RETRO_MODE); @@ -544,37 +549,32 @@ public class AdvancedConfig extends ConfigValidated { public double getMaximumProbability(SubSkillType subSkillType) { String[] category = subSkillType.getAdvConfigAddress(); - + double maximumProbability = getDoubleValue(category[0], category[1], category[2], CHANCE_MAX); return maximumProbability; } - public double getMaximumProbability(AbstractSubSkill abstractSubSkill) - { + public double getMaximumProbability(AbstractSubSkill abstractSubSkill) { return getMaximumProbability(abstractSubSkill.getSubSkillType()); } /* Notification Settings */ - public boolean doesSkillCommandSendBlankLines() - { - return getBooleanValue(FEEDBACK, SKILL_COMMAND, BLANK_LINES_ABOVE_HEADER); + public boolean doesSkillCommandSendBlankLines() { + return getBooleanValue(FEEDBACK, SKILL_COMMAND, BLANK_LINES_ABOVE_HEADER); } - public boolean doesNotificationUseActionBar(NotificationType notificationType) - { - return getBooleanValue(FEEDBACK, ACTION_BAR_NOTIFICATIONS, notificationType.toString(), ENABLED); + public boolean doesNotificationUseActionBar(NotificationType notificationType) { + return getBooleanValue(FEEDBACK, ACTION_BAR_NOTIFICATIONS, notificationType.toString(), ENABLED); } - public boolean doesNotificationSendCopyToChat(NotificationType notificationType) - { - return getBooleanValue(FEEDBACK, ACTION_BAR_NOTIFICATIONS, notificationType.toString(), SEND_COPY_OF_MESSAGE_TO_CHAT); + public boolean doesNotificationSendCopyToChat(NotificationType notificationType) { + return getBooleanValue(FEEDBACK, ACTION_BAR_NOTIFICATIONS, notificationType.toString(), SEND_COPY_OF_MESSAGE_TO_CHAT); } - public boolean useTitlesForXPEvent() - { - return getBooleanValue(FEEDBACK, EVENTS, XP, SEND_TITLES); + public boolean useTitlesForXPEvent() { + return getBooleanValue(FEEDBACK, EVENTS, XP, SEND_TITLES); } private ChatColor getChatColorFromKey(String keyLocation) { @@ -595,57 +595,109 @@ public class AdvancedConfig extends ConfigValidated { } /* ACROBATICS */ - public double getDodgeDamageModifier() { return getDoubleValue(SKILLS, ACROBATICS, DODGE, DAMAGE_MODIFIER); } + public double getDodgeDamageModifier() { + return getDoubleValue(SKILLS, ACROBATICS, DODGE, DAMAGE_MODIFIER); + } - public double getRollDamageThreshold() { return getDoubleValue(SKILLS, ACROBATICS, ROLL, DAMAGE_THRESHOLD); } + public double getRollDamageThreshold() { + return getDoubleValue(SKILLS, ACROBATICS, ROLL, DAMAGE_THRESHOLD); + } - public double getGracefulRollDamageThreshold() { return getDoubleValue(SKILLS, ACROBATICS, GRACEFUL_ROLL, DAMAGE_THRESHOLD); } + public double getGracefulRollDamageThreshold() { + return getDoubleValue(SKILLS, ACROBATICS, GRACEFUL_ROLL, DAMAGE_THRESHOLD); + } /* ALCHEMY */ - public int getCatalysisMaxBonusLevel() { return getIntValue(SKILLS, ALCHEMY, CATALYSIS, MAX_BONUS_LEVEL); } + public int getCatalysisMaxBonusLevel() { + return getIntValue(SKILLS, ALCHEMY, CATALYSIS, MAX_BONUS_LEVEL); + } - public double getCatalysisMinSpeed() { return getDoubleValue(SKILLS, ALCHEMY, CATALYSIS, MIN_SPEED); } - public double getCatalysisMaxSpeed() { return getDoubleValue(SKILLS, ALCHEMY, CATALYSIS, MAX_SPEED); } + public double getCatalysisMinSpeed() { + return getDoubleValue(SKILLS, ALCHEMY, CATALYSIS, MIN_SPEED); + } + + public double getCatalysisMaxSpeed() { + return getDoubleValue(SKILLS, ALCHEMY, CATALYSIS, MAX_SPEED); + } /* ARCHERY */ - public double getSkillShotRankDamageMultiplier() { return getDoubleValue(SKILLS, ARCHERY, SKILL_SHOT, RANK_DAMAGE_MULTIPLIER); } - public double getSkillShotDamageMax() { return getDoubleValue(SKILLS, ARCHERY, SKILL_SHOT, MAX_DAMAGE); } + public double getSkillShotRankDamageMultiplier() { + return getDoubleValue(SKILLS, ARCHERY, SKILL_SHOT, RANK_DAMAGE_MULTIPLIER); + } - public double getDazeBonusDamage() { return getDoubleValue(SKILLS, ARCHERY, DAZE, BONUS_DAMAGE); } + public double getSkillShotDamageMax() { + return getDoubleValue(SKILLS, ARCHERY, SKILL_SHOT, MAX_DAMAGE); + } - public double getForceMultiplier() { return getDoubleValue(SKILLS, ARCHERY, FORCE_MULTIPLIER); } + public double getDazeBonusDamage() { + return getDoubleValue(SKILLS, ARCHERY, DAZE, BONUS_DAMAGE); + } + + public double getForceMultiplier() { + return getDoubleValue(SKILLS, ARCHERY, FORCE_MULTIPLIER); + } /* AXES */ - public double getAxeMasteryRankDamageMultiplier() { return getDoubleValue(SKILLS, AXES, AXE_MASTERY, RANK_DAMAGE_MULTIPLIER); } + public double getAxeMasteryRankDamageMultiplier() { + return getDoubleValue(SKILLS, AXES, AXE_MASTERY, RANK_DAMAGE_MULTIPLIER); + } - public double getCriticalStrikesPVPModifier() { return getDoubleValue(SKILLS, AXES, CRITICAL_STRIKES, PVP_MODIFIER); } - public double getCriticalStrikesPVEModifier() { return getDoubleValue(SKILLS, AXES, CRITICAL_STRIKES, PVE_MODIFIER); } + public double getCriticalStrikesPVPModifier() { + return getDoubleValue(SKILLS, AXES, CRITICAL_STRIKES, PVP_MODIFIER); + } - public double getGreaterImpactChance() { return getDoubleValue(SKILLS, AXES, GREATER_IMPACT, CHANCE); } - public double getGreaterImpactModifier() { return getDoubleValue(SKILLS, AXES, GREATER_IMPACT, KNOCKBACK_MODIFIER); } - public double getGreaterImpactBonusDamage() { return getDoubleValue(SKILLS, AXES, GREATER_IMPACT, BONUS_DAMAGE); } + public double getCriticalStrikesPVEModifier() { + return getDoubleValue(SKILLS, AXES, CRITICAL_STRIKES, PVE_MODIFIER); + } + + public double getGreaterImpactChance() { + return getDoubleValue(SKILLS, AXES, GREATER_IMPACT, CHANCE); + } + + public double getGreaterImpactModifier() { + return getDoubleValue(SKILLS, AXES, GREATER_IMPACT, KNOCKBACK_MODIFIER); + } + + public double getGreaterImpactBonusDamage() { + return getDoubleValue(SKILLS, AXES, GREATER_IMPACT, BONUS_DAMAGE); + } public int getArmorImpactIncreaseLevel() { int increaseLevel = getIntValue(SKILLS, AXES, ARMOR_IMPACT, INCREASE_LEVEL); - if(mcMMO.isRetroModeEnabled()) + if (mcMMO.isRetroModeEnabled()) return increaseLevel * 10; return increaseLevel; } - public double getImpactChance() { return getDoubleValue(SKILLS, AXES, ARMOR_IMPACT, CHANCE); } - public double getArmorImpactMaxDurabilityDamage() { return getDoubleValue(SKILLS, AXES, ARMOR_IMPACT, MAX_PERCENTAGE_DURABILITY_DAMAGE); } + public double getImpactChance() { + return getDoubleValue(SKILLS, AXES, ARMOR_IMPACT, CHANCE); + } - public double getSkullSplitterModifier() { return getDoubleValue(SKILLS, AXES, SKULL_SPLITTER, DAMAGE_MODIFIER); } + public double getArmorImpactMaxDurabilityDamage() { + return getDoubleValue(SKILLS, AXES, ARMOR_IMPACT, MAX_PERCENTAGE_DURABILITY_DAMAGE); + } + + public double getSkullSplitterModifier() { + return getDoubleValue(SKILLS, AXES, SKULL_SPLITTER, DAMAGE_MODIFIER); + } /* EXCAVATION */ //Nothing to configure, everything is already configurable in config.yml /* FISHING */ - public double getShakeChance(int rank) { return getDoubleValue(SKILLS, FISHING, SHAKE, CHANCE, RANK, String.valueOf(rank)); } - public double getMasterAnglerBoatModifier() {return getDoubleValue(SKILLS, FISHING, MASTER_ANGLER, BOAT_MODIFIER); } - public double getMasterAnglerBiomeModifier() {return getDoubleValue(SKILLS, FISHING, MASTER_ANGLER, BIOME_MODIFIER); } + public double getShakeChance(int rank) { + return getDoubleValue(SKILLS, FISHING, SHAKE, CHANCE, RANK, String.valueOf(rank)); + } + + public double getMasterAnglerBoatModifier() { + return getDoubleValue(SKILLS, FISHING, MASTER_ANGLER, BOAT_MODIFIER); + } + + public double getMasterAnglerBiomeModifier() { + return getDoubleValue(SKILLS, FISHING, MASTER_ANGLER, BIOME_MODIFIER); + } /* HERBALISM */ //public int getFarmerDietRankChange() { return getIntValue(SKILLS, ".Herbalism.FarmersDiet.RankChange"); } @@ -653,67 +705,152 @@ public class AdvancedConfig extends ConfigValidated { //public int getGreenThumbStageChange() { return getIntValue(SKILLS, ".Herbalism.GreenThumb.StageChange"); } /* MINING */ - public boolean getDoubleDropSilkTouchEnabled() { return getBooleanValue(SKILLS, MINING, "DoubleDrops", "SilkTouch"); } - public int getBlastMiningRankLevel(int rank) { return getIntValue(SKILLS, MINING, BLAST_MINING, RANK, LEVELS, RANK, String.valueOf(rank)); } - public double getBlastDamageDecrease(int rank) { return getDoubleValue(SKILLS, MINING, BLAST_MINING, BLAST_DAMAGE_DECREASE, RANK, String.valueOf(rank)); } - public double getOreBonus(int rank) { return getDoubleValue(SKILLS, MINING, BLAST_MINING, ORE_BONUS, RANK, String.valueOf(rank)); } - public double getDebrisReduction(int rank) { return getDoubleValue(SKILLS, MINING, BLAST_MINING, DEBRIS_REDUCTION, RANK, String.valueOf(rank)); } - public int getDropMultiplier(int rank) { return getIntValue(SKILLS, MINING, BLAST_MINING, DROP_MULTIPLIER, RANK, String.valueOf(rank)); } - public double getBlastRadiusModifier(int rank) { return getDoubleValue(SKILLS, MINING, BLAST_MINING, BLAST_RADIUS, MODIFIER, RANK, String.valueOf(rank)); } + public boolean getDoubleDropSilkTouchEnabled() { + return getBooleanValue(SKILLS, MINING, "DoubleDrops", "SilkTouch"); + } + + public int getBlastMiningRankLevel(int rank) { + return getIntValue(SKILLS, MINING, BLAST_MINING, RANK, LEVELS, RANK, String.valueOf(rank)); + } + + public double getBlastDamageDecrease(int rank) { + return getDoubleValue(SKILLS, MINING, BLAST_MINING, BLAST_DAMAGE_DECREASE, RANK, String.valueOf(rank)); + } + + public double getOreBonus(int rank) { + return getDoubleValue(SKILLS, MINING, BLAST_MINING, ORE_BONUS, RANK, String.valueOf(rank)); + } + + public double getDebrisReduction(int rank) { + return getDoubleValue(SKILLS, MINING, BLAST_MINING, DEBRIS_REDUCTION, RANK, String.valueOf(rank)); + } + + public int getDropMultiplier(int rank) { + return getIntValue(SKILLS, MINING, BLAST_MINING, DROP_MULTIPLIER, RANK, String.valueOf(rank)); + } + + public double getBlastRadiusModifier(int rank) { + return getDoubleValue(SKILLS, MINING, BLAST_MINING, BLAST_RADIUS, MODIFIER, RANK, String.valueOf(rank)); + } /* REPAIR */ - public double getRepairMasteryMaxBonus() { return getDoubleValue(SKILLS, REPAIR, REPAIR_MASTERY, MAX_BONUS_PERCENTAGE); } + public double getRepairMasteryMaxBonus() { + return getDoubleValue(SKILLS, REPAIR, REPAIR_MASTERY, MAX_BONUS_PERCENTAGE); + } //public int getRepairMasteryMaxLevel() { return getIntValue(SKILLS, REPAIR, REPAIR_MASTERY, MAX_BONUS_LEVEL); } /* Arcane Forging */ - public boolean getArcaneForgingEnchantLossEnabled() { return getBooleanValue(SKILLS, REPAIR, ARCANE_FORGING, MAY_LOSE_ENCHANTS); } - public double getArcaneForgingKeepEnchantsChance(int rank) { return getDoubleValue(SKILLS, REPAIR, ARCANE_FORGING, KEEP_ENCHANTS, CHANCE, RANK, String.valueOf(rank)); } + public boolean getArcaneForgingEnchantLossEnabled() { + return getBooleanValue(SKILLS, REPAIR, ARCANE_FORGING, MAY_LOSE_ENCHANTS); + } - public boolean getArcaneForgingDowngradeEnabled() { return getBooleanValue(SKILLS, REPAIR, ARCANE_FORGING, DOWNGRADES_ENABLED); } - public double getArcaneForgingDowngradeChance(int rank) { return getDoubleValue(SKILLS, REPAIR, ARCANE_FORGING, DOWNGRADES, CHANCE, RANK, String.valueOf(rank)); } + public double getArcaneForgingKeepEnchantsChance(int rank) { + return getDoubleValue(SKILLS, REPAIR, ARCANE_FORGING, KEEP_ENCHANTS, CHANCE, RANK, String.valueOf(rank)); + } + + public boolean getArcaneForgingDowngradeEnabled() { + return getBooleanValue(SKILLS, REPAIR, ARCANE_FORGING, DOWNGRADES_ENABLED); + } + + public double getArcaneForgingDowngradeChance(int rank) { + return getDoubleValue(SKILLS, REPAIR, ARCANE_FORGING, DOWNGRADES, CHANCE, RANK, String.valueOf(rank)); + } /* SALVAGE */ - public boolean getArcaneSalvageEnchantDowngradeEnabled() { return getBooleanValue(SKILLS, SALVAGE, ARCANE_SALVAGE, ENCHANT_DOWNGRADE_ENABLED); } - public boolean getArcaneSalvageEnchantLossEnabled() { return getBooleanValue(SKILLS, SALVAGE, ARCANE_SALVAGE, ENCHANT_LOSS_ENABLED); } + public boolean getArcaneSalvageEnchantDowngradeEnabled() { + return getBooleanValue(SKILLS, SALVAGE, ARCANE_SALVAGE, ENCHANT_DOWNGRADE_ENABLED); + } - public double getArcaneSalvageExtractFullEnchantsChance(int rank) { return getDoubleValue(SKILLS, SALVAGE, ARCANE_SALVAGE, EXTRACT_FULL_ENCHANT, RANK, String.valueOf(rank)); } - public double getArcaneSalvageExtractPartialEnchantsChance(int rank) { return getDoubleValue(SKILLS, SALVAGE, ARCANE_SALVAGE, EXTRACT_PARTIAL_ENCHANT, RANK, String.valueOf(rank)); } + public boolean getArcaneSalvageEnchantLossEnabled() { + return getBooleanValue(SKILLS, SALVAGE, ARCANE_SALVAGE, ENCHANT_LOSS_ENABLED); + } + + public double getArcaneSalvageExtractFullEnchantsChance(int rank) { + return getDoubleValue(SKILLS, SALVAGE, ARCANE_SALVAGE, EXTRACT_FULL_ENCHANT, RANK, String.valueOf(rank)); + } + + public double getArcaneSalvageExtractPartialEnchantsChance(int rank) { + return getDoubleValue(SKILLS, SALVAGE, ARCANE_SALVAGE, EXTRACT_PARTIAL_ENCHANT, RANK, String.valueOf(rank)); + } /* SMELTING */ //public int getBurnModifierMaxLevel() { return getIntValue(SKILLS, SMELTING, FUEL_EFFICIENCY, MAX_BONUS_LEVEL); } - public double getBurnTimeMultiplier() { return getDoubleValue(SKILLS, SMELTING, FUEL_EFFICIENCY, MULTIPLIER); } + public double getBurnTimeMultiplier() { + return getDoubleValue(SKILLS, SMELTING, FUEL_EFFICIENCY, MULTIPLIER); + } - public int getSmeltingRankLevel(int rank) { return getIntValue(SKILLS, SMELTING, RANK, LEVELS, RANK, String.valueOf(rank)); } + public int getSmeltingRankLevel(int rank) { + return getIntValue(SKILLS, SMELTING, RANK, LEVELS, RANK, String.valueOf(rank)); + } - public int getSmeltingVanillaXPBoostMultiplier(int rank) { return getIntValue(SKILLS, SMELTING, VANILLA_XPMULTIPLIER, RANK, String.valueOf(rank)); } + public int getSmeltingVanillaXPBoostMultiplier(int rank) { + return getIntValue(SKILLS, SMELTING, VANILLA_XPMULTIPLIER, RANK, String.valueOf(rank)); + } /* SWORDS */ - public double getRuptureDamagePlayer() { return getDoubleValue(SKILLS, SWORDS, RUPTURE, DAMAGE_PLAYER); } - public double getRuptureDamageMobs() { return getDoubleValue(SKILLS, SWORDS, RUPTURE, DAMAGE_MOBS); } + public double getRuptureDamagePlayer() { + return getDoubleValue(SKILLS, SWORDS, RUPTURE, DAMAGE_PLAYER); + } - public int getRuptureMaxTicks() { return getIntValue(SKILLS, SWORDS, RUPTURE, MAX_TICKS); } - public int getRuptureBaseTicks() { return getIntValue(SKILLS, SWORDS, RUPTURE, BASE_TICKS); } + public double getRuptureDamageMobs() { + return getDoubleValue(SKILLS, SWORDS, RUPTURE, DAMAGE_MOBS); + } - public double getCounterAttackModifier() { return getDoubleValue(SKILLS, SWORDS, COUNTER_ATTACK, DAMAGE_MODIFIER); } + public int getRuptureMaxTicks() { + return getIntValue(SKILLS, SWORDS, RUPTURE, MAX_TICKS); + } - public double getSerratedStrikesModifier() { return getDoubleValue(SKILLS, SWORDS, SERRATED_STRIKES, DAMAGE_MODIFIER); } + public int getRuptureBaseTicks() { + return getIntValue(SKILLS, SWORDS, RUPTURE, BASE_TICKS); + } + + public double getCounterAttackModifier() { + return getDoubleValue(SKILLS, SWORDS, COUNTER_ATTACK, DAMAGE_MODIFIER); + } + + public double getSerratedStrikesModifier() { + return getDoubleValue(SKILLS, SWORDS, SERRATED_STRIKES, DAMAGE_MODIFIER); + } //public int getSerratedStrikesTicks() { return getIntValue(SKILLS, SWORDS, SERRATED_STRIKES, RUPTURE, TICKS); } /* TAMING */ - public double getGoreModifier() { return getDoubleValue(SKILLS, TAMING, GORE, MODIFIER); } - public double getFastFoodChance() { return getDoubleValue(SKILLS, TAMING, FAST_FOOD_SERVICE, CHANCE); } - public double getPummelChance() { return getDoubleValue(SKILLS, TAMING, PUMMEL, CHANCE); } - public double getThickFurModifier() { return getDoubleValue(SKILLS, TAMING, THICK_FUR, MODIFIER); } - public double getShockProofModifier() { return getDoubleValue(SKILLS, TAMING, SHOCK_PROOF, MODIFIER); } + public double getGoreModifier() { + return getDoubleValue(SKILLS, TAMING, GORE, MODIFIER); + } - public double getSharpenedClawsBonus() { return getDoubleValue(SKILLS, TAMING, SHARPENED_CLAWS, BONUS); } + public double getFastFoodChance() { + return getDoubleValue(SKILLS, TAMING, FAST_FOOD_SERVICE, CHANCE); + } - public double getMinHorseJumpStrength() { return getDoubleValue(SKILLS, TAMING, CALL_OF_THE_WILD, MIN_HORSE_JUMP_STRENGTH); } - public double getMaxHorseJumpStrength() { return getDoubleValue(SKILLS, TAMING, CALL_OF_THE_WILD, MAX_HORSE_JUMP_STRENGTH); } + public double getPummelChance() { + return getDoubleValue(SKILLS, TAMING, PUMMEL, CHANCE); + } + + public double getThickFurModifier() { + return getDoubleValue(SKILLS, TAMING, THICK_FUR, MODIFIER); + } + + public double getShockProofModifier() { + return getDoubleValue(SKILLS, TAMING, SHOCK_PROOF, MODIFIER); + } + + public double getSharpenedClawsBonus() { + return getDoubleValue(SKILLS, TAMING, SHARPENED_CLAWS, BONUS); + } + + public double getMinHorseJumpStrength() { + return getDoubleValue(SKILLS, TAMING, CALL_OF_THE_WILD, MIN_HORSE_JUMP_STRENGTH); + } + + public double getMaxHorseJumpStrength() { + return getDoubleValue(SKILLS, TAMING, CALL_OF_THE_WILD, MAX_HORSE_JUMP_STRENGTH); + } /* UNARMED */ - public boolean getDisarmProtected() { return getBooleanValue(SKILLS, UNARMED, DISARM, ANTI_THEFT); } + public boolean getDisarmProtected() { + return getBooleanValue(SKILLS, UNARMED, DISARM, ANTI_THEFT); + } /* WOODCUTTING */ } diff --git a/src/main/java/com/gmail/nossr50/config/BonusDropManager.java b/src/main/java/com/gmail/nossr50/config/BonusDropManager.java index f63bac50a..e25931d32 100644 --- a/src/main/java/com/gmail/nossr50/config/BonusDropManager.java +++ b/src/main/java/com/gmail/nossr50/config/BonusDropManager.java @@ -13,13 +13,11 @@ public class BonusDropManager implements Unload { private HashMap bonusDropWhitelist; - public BonusDropManager() - { + public BonusDropManager() { bonusDropWhitelist = new HashMap<>(); //Start by setting all Materials to false to avoid null checks - for(Material material : Material.values()) - { + for (Material material : Material.values()) { registerMaterial(material, false); } } @@ -31,28 +29,25 @@ public class BonusDropManager implements Unload { /** * Adds materials to the bonus drop whitelist + * * @param materials target material list */ - public void addToWhitelistByMaterial(List materials) - { - for(Material material : materials) - { + public void addToWhitelistByMaterial(List materials) { + for (Material material : materials) { registerMaterial(material, true); } } /** * Adds materials to the bonus drop whitelist + * * @param materials target material list */ - public void addToWhitelistByNameID(List materials) - { - for(String material : materials) - { + public void addToWhitelistByNameID(List materials) { + for (String material : materials) { Material m = Material.matchMaterial(material); - if(m == null) - { - mcMMO.p.getLogger().severe("Error registering Bonus Drop -- Invalid Minecraft Name ID: "+material); + if (m == null) { + mcMMO.p.getLogger().severe("Error registering Bonus Drop -- Invalid Minecraft Name ID: " + material); continue; } @@ -62,6 +57,7 @@ public class BonusDropManager implements Unload { /** * Adds a material to the bonus drop whitelist + * * @param material target material */ private void registerMaterial(Material material, boolean isWhitelisted) { @@ -70,11 +66,11 @@ public class BonusDropManager implements Unload { /** * Check if a material can provide bonus drops + * * @param material target material * @return true if the material can provide bonus drops */ - public boolean isBonusDropWhitelisted(Material material) - { + public boolean isBonusDropWhitelisted(Material material) { return bonusDropWhitelist.get(material); } } diff --git a/src/main/java/com/gmail/nossr50/config/Config.java b/src/main/java/com/gmail/nossr50/config/Config.java index dea9e155d..955dc6d34 100644 --- a/src/main/java/com/gmail/nossr50/config/Config.java +++ b/src/main/java/com/gmail/nossr50/config/Config.java @@ -21,22 +21,20 @@ import java.util.List; public abstract class Config implements VersionedConfig, Unload { public static final String HOCON_FILE_EXTENSION = ".conf"; + public final File DIRECTORY_DATA_FOLDER; //Directory that the file is in + public final String FILE_RELATIVE_PATH; //Relative Path to the file + protected final String DIRECTORY_DEFAULTS = "defaults"; /* SETTINGS */ //private static final String FILE_EXTENSION = ".conf"; //HOCON private boolean mergeNewKeys; //Whether or not to merge keys found in the default config private boolean removeOldKeys; //Whether or not to remove unused keys form the config + + /* PATH VARS */ private boolean copyDefaults; //Whether or not to copy the default config when first creating the file private boolean generateDefaults; //Whether or not we use Configurate to generate a default file, if this is false we copy the file from the JAR private String fileName; //The file name of the config - /* PATH VARS */ - - public final File DIRECTORY_DATA_FOLDER; //Directory that the file is in - public final String FILE_RELATIVE_PATH; //Relative Path to the file - protected final String DIRECTORY_DEFAULTS = "defaults"; - /* LOADERS */ - private HoconConfigurationLoader defaultCopyLoader; private HoconConfigurationLoader userCopyLoader; @@ -78,8 +76,7 @@ public abstract class Config implements VersionedConfig, Unload { FILE_RELATIVE_PATH = relativePath + fileName + HOCON_FILE_EXTENSION; //Relative path to config from a parent folder } - public void initFullConfig() - { + public void initFullConfig() { //Attempt IO Operations try { //Makes sure we have valid Files corresponding to this config @@ -106,8 +103,7 @@ public abstract class Config implements VersionedConfig, Unload { * Registers with the config managers unloader * The unloader runs when the plugin gets disabled which cleans up registries to make reloading safe */ - private void registerUnload() - { + private void registerUnload() { mcMMO.getConfigManager().registerUnloadable(this); } @@ -115,13 +111,13 @@ public abstract class Config implements VersionedConfig, Unload { * Registers with the config managers file list * Used for backing up configs with our zip library */ - private void registerFileBackup() - { + private void registerFileBackup() { mcMMO.getConfigManager().registerUserFile(getUserConfigFile()); } /** * Initializes the default copy File and the user config File + * * @throws IOException */ private void initConfigFiles() throws IOException { @@ -135,8 +131,7 @@ public abstract class Config implements VersionedConfig, Unload { /** * Loads the root node for the default config File and user config File */ - private void loadConfig() - { + private void loadConfig() { try { final CommentedConfigurationNode defaultConfig = this.defaultCopyLoader.load(); defaultRootNode = defaultConfig; @@ -152,20 +147,19 @@ public abstract class Config implements VersionedConfig, Unload { /** * Initializes the Configuration Loaders for this config */ - private void initConfigLoaders() - { + private void initConfigLoaders() { this.defaultCopyLoader = HoconConfigurationLoader.builder().setPath(resourceConfigCopy.toPath()).build(); this.userCopyLoader = HoconConfigurationLoader.builder().setPath(resourceUserCopy.toPath()).build(); } /** * Copies a new file from the JAR to the defaults directory and uses that new file to initialize our resourceConfigCopy - * @see Config#resourceConfigCopy + * * @throws IOException + * @see Config#resourceConfigCopy */ private File initDefaultConfig() throws IOException { - if(generateDefaults) - { + if (generateDefaults) { return generateDefaultFile(); } else return copyDefaultFromJar(getDefaultConfigCopyRelativePath(), true); @@ -174,11 +168,11 @@ public abstract class Config implements VersionedConfig, Unload { /** * Generates a default config file using the Configurate library, makes use of @Setting and @ConfigSerializable annotations in the config file * Assigns the default root node to the newly loaded default config if successful + * * @return the File for the newly created config */ - private File generateDefaultFile() - { - mcMMO.p.getLogger().info("Attempting to create a default config for "+fileName); + private File generateDefaultFile() { + mcMMO.p.getLogger().info("Attempting to create a default config for " + fileName); //Not sure if this will work properly... Path potentialFile = Paths.get(getDefaultConfigCopyRelativePath()); @@ -186,9 +180,9 @@ public abstract class Config implements VersionedConfig, Unload { = HoconConfigurationLoader.builder().setPath(potentialFile).build(); try { - mcMMO.p.getLogger().info("Config File Full Path: "+getDefaultConfigFile().getAbsolutePath()); + mcMMO.p.getLogger().info("Config File Full Path: " + getDefaultConfigFile().getAbsolutePath()); //Delete any existing default config - if(getDefaultConfigFile().exists()) + if (getDefaultConfigFile().exists()) getDefaultConfigFile().delete(); //Make new file @@ -200,8 +194,8 @@ public abstract class Config implements VersionedConfig, Unload { //Save to a new file generation_loader.save(defaultRootNode); - mcMMO.p.getLogger().info("Generated a default file for "+fileName); - } catch(IOException e) { + mcMMO.p.getLogger().info("Generated a default file for " + fileName); + } catch (IOException e) { mcMMO.p.getLogger().severe("Error when trying to generate a default configuration file for " + getDefaultConfigCopyRelativePath()); e.printStackTrace(); } @@ -212,26 +206,23 @@ public abstract class Config implements VersionedConfig, Unload { /** * Attemps to load the config file if it exists, if it doesn't it copies a new one from within the JAR + * * @return user config File - * @see Config#resourceUserCopy * @throws IOException + * @see Config#resourceUserCopy */ private File initUserConfig() throws IOException { File userCopy = new File(DIRECTORY_DATA_FOLDER, FILE_RELATIVE_PATH); //Load the user file; - if(userCopy.exists()) - { + if (userCopy.exists()) { // Yay return userCopy; - } - else - { + } else { //If it's gone we copy default files //Note that we don't copy the values from the default copy put in /defaults/ that file exists only as a reference to admins and is unreliable - if(copyDefaults) + if (copyDefaults) return copyDefaultFromJar(FILE_RELATIVE_PATH, false); - else - { + else { //Make a new empty file userCopy.createNewFile(); return userCopy; @@ -241,6 +232,7 @@ public abstract class Config implements VersionedConfig, Unload { /** * Gets the File representation of the this users config + * * @return the users config File */ public File getUserConfigFile() { @@ -249,17 +241,17 @@ public abstract class Config implements VersionedConfig, Unload { /** * Used to make a new config file at a specified relative output path inside the data directory by copying the matching file found in that same relative path within the JAR + * * @param relativeOutputPath the path to the output file - * @param deleteOld whether or not to delete the existing output file on disk + * @param deleteOld whether or not to delete the existing output file on disk * @return a copy of the default config within the JAR * @throws IOException */ - private File copyDefaultFromJar(String relativeOutputPath, boolean deleteOld) throws IOException - { + private File copyDefaultFromJar(String relativeOutputPath, boolean deleteOld) throws IOException { /* * Gen a Default config from inside the JAR */ - mcMMO.p.getLogger().info("Preparing to copy internal resource file (in JAR) - "+FILE_RELATIVE_PATH); + mcMMO.p.getLogger().info("Preparing to copy internal resource file (in JAR) - " + FILE_RELATIVE_PATH); //InputStream inputStream = McmmoCore.getResource(FILE_RELATIVE_PATH); InputStream inputStream = mcMMO.p.getResource(FILE_RELATIVE_PATH); @@ -270,14 +262,12 @@ public abstract class Config implements VersionedConfig, Unload { File targetFile = new File(DIRECTORY_DATA_FOLDER, relativeOutputPath); //Wipe old default file on disk - if (targetFile.exists() && deleteOld) - { + if (targetFile.exists() && deleteOld) { mcMMO.p.getLogger().info("Updating file " + relativeOutputPath); targetFile.delete(); //Necessary? } - if(!targetFile.exists()) - { + if (!targetFile.exists()) { targetFile.getParentFile().mkdirs(); targetFile.createNewFile(); //New File Boys } @@ -292,6 +282,7 @@ public abstract class Config implements VersionedConfig, Unload { /** * The path to the defaults directory + * * @return the path to the defaults directory */ private String getDefaultConfigCopyRelativePath() { @@ -301,6 +292,7 @@ public abstract class Config implements VersionedConfig, Unload { /** * Grabs the File representation of the default config, which is stored on disk in a defaults folder * this file will be overwritten every time mcMMO starts to keep it up to date. + * * @return the copy of the default config file, stored in the defaults directory */ private File getDefaultConfigFile() { @@ -316,11 +308,11 @@ public abstract class Config implements VersionedConfig, Unload { /** * Configs are versioned based on when they had significant changes to keys + * * @return current MainConfig Version String */ - public String getVersion() - { - return String.valueOf(getConfigVersion()); + public String getVersion() { + return String.valueOf(getConfigVersion()); } /** @@ -342,13 +334,12 @@ public abstract class Config implements VersionedConfig, Unload { /** * Compares the users config file to the default and adds any missing nodes and applies any necessary updates */ - private void updateConfig() - { - mcMMO.p.getLogger().info(defaultRootNode.getChildrenMap().size() +" items in default children map"); - mcMMO.p.getLogger().info(userRootNode.getChildrenMap().size() +" items in default root map"); + private void updateConfig() { + mcMMO.p.getLogger().info(defaultRootNode.getChildrenMap().size() + " items in default children map"); + mcMMO.p.getLogger().info(userRootNode.getChildrenMap().size() + " items in default root map"); // Merge Values from default - if(mergeNewKeys) + if (mergeNewKeys) userRootNode = userRootNode.mergeValuesFrom(defaultRootNode); removeOldKeys(); @@ -368,23 +359,21 @@ public abstract class Config implements VersionedConfig, Unload { * Finds any keys in the users config that are not present in the default config and removes them */ //TODO: Finish this - private void removeOldKeys() - { - if(!removeOldKeys) + private void removeOldKeys() { + if (!removeOldKeys) return; - for(CommentedConfigurationNode CommentedConfigurationNode : defaultRootNode.getChildrenList()) - { + for (CommentedConfigurationNode CommentedConfigurationNode : defaultRootNode.getChildrenList()) { } } /** * Saves the current state information of the config to the users copy (which they may edit) + * * @throws IOException */ - private void saveUserCopy() throws IOException - { + private void saveUserCopy() throws IOException { mcMMO.p.getLogger().info("Saving new node"); userCopyLoader.save(userRootNode); } @@ -395,11 +384,12 @@ public abstract class Config implements VersionedConfig, Unload { private void updateConfigVersion() { // Set a version for our config this.userRootNode.getNode("ConfigVersion").setValue(getConfigVersion()); - mcMMO.p.getLogger().info("Updated config to ["+getConfigVersion()+"] - " + FILE_RELATIVE_PATH); + mcMMO.p.getLogger().info("Updated config to [" + getConfigVersion() + "] - " + FILE_RELATIVE_PATH); } /** * Returns the root node of this config + * * @return the root node of this config */ protected CommentedConfigurationNode getUserRootNode() { @@ -408,62 +398,67 @@ public abstract class Config implements VersionedConfig, Unload { /** * Gets an int from the config and casts it to short before returning + * * @param path the path to the int * @return the value of the int after being cast to short at the node, null references will zero initialize */ - public short getShortValue(String... path) { return (short) userRootNode.getNode(path).getInt();} + public short getShortValue(String... path) { + return (short) userRootNode.getNode(path).getInt(); + } /** * Grabs an int from the specified node + * * @param path * @return the int from the node, null references will zero initialize */ - public int getIntValue(String... path) - { + public int getIntValue(String... path) { return userRootNode.getNode(path).getInt(); } + /** * Grabs a double from the specified node + * * @param path * @return the double from the node, null references will zero initialize */ - public double getDoubleValue(String... path) - { + public double getDoubleValue(String... path) { return userRootNode.getNode(path).getDouble(); } /** * Grabs a long from the specified node + * * @param path * @return the long from the node, null references will zero initialize */ - public long getLongValue(String... path) - { + public long getLongValue(String... path) { return userRootNode.getNode(path).getLong(); } /** * Grabs a boolean from the specified node + * * @param path * @return the boolean from the node, null references will zero initialize */ - public boolean getBooleanValue(String... path) - { + public boolean getBooleanValue(String... path) { return userRootNode.getNode(path).getBoolean(); } /** * Grabs a string from the specified node + * * @param path * @return the string from the node, null references will zero initialize */ - public String getStringValue(String... path) - { + public String getStringValue(String... path) { return userRootNode.getNode(path).getString(); } /** * Checks to see if a node exists in the user's config file + * * @param path path to the node * @return true if the node exists */ @@ -473,6 +468,7 @@ public abstract class Config implements VersionedConfig, Unload { /** * Returns the children of a specific node + * * @param path the path to the parent node * @return the list of children for the target parent node */ @@ -480,8 +476,7 @@ public abstract class Config implements VersionedConfig, Unload { return userRootNode.getNode(path).getChildrenList(); } - public List getListFromNode(String... path) throws ObjectMappingException - { + public List getListFromNode(String... path) throws ObjectMappingException { return userRootNode.getNode(path).getList(TypeToken.of(String.class)); } } diff --git a/src/main/java/com/gmail/nossr50/config/ConfigCollection.java b/src/main/java/com/gmail/nossr50/config/ConfigCollection.java index 7bc5be308..2bfa42147 100644 --- a/src/main/java/com/gmail/nossr50/config/ConfigCollection.java +++ b/src/main/java/com/gmail/nossr50/config/ConfigCollection.java @@ -14,10 +14,10 @@ public abstract class ConfigCollection extends Config implements Registers, G /** * @param pathToParentFolder Path to the "parent" folder on disk - * @param relativePath Path to the config relative to the "parent" folder, this should mirror internal structure of resource files - * @param mergeNewKeys if true, the users config will add keys found in the internal file that are missing from the users file during load - * @param copyDefaults if true, the users config file when it is first made will be a copy of an internal resource file of the same name and path - * @param removeOldKeys if true, the users config file will have keys not found in the internal default resource file of the same name and path removed + * @param relativePath Path to the config relative to the "parent" folder, this should mirror internal structure of resource files + * @param mergeNewKeys if true, the users config will add keys found in the internal file that are missing from the users file during load + * @param copyDefaults if true, the users config file when it is first made will be a copy of an internal resource file of the same name and path + * @param removeOldKeys if true, the users config file will have keys not found in the internal default resource file of the same name and path removed */ public ConfigCollection(String fileName, File pathToParentFolder, String relativePath, boolean generateDefaults, boolean mergeNewKeys, boolean copyDefaults, boolean removeOldKeys) { super(fileName, pathToParentFolder, relativePath, generateDefaults, mergeNewKeys, copyDefaults, removeOldKeys); diff --git a/src/main/java/com/gmail/nossr50/config/ConfigConstants.java b/src/main/java/com/gmail/nossr50/config/ConfigConstants.java index d2275cf44..fb691d06e 100644 --- a/src/main/java/com/gmail/nossr50/config/ConfigConstants.java +++ b/src/main/java/com/gmail/nossr50/config/ConfigConstants.java @@ -9,11 +9,19 @@ import java.util.ArrayList; * Constants relating to config folders and paths */ public class ConfigConstants { - private final static String[] EXAMPLE_BLACKLIST_WORLDS = {"Example_15434453", "Example_2324423", "Example_323423465"}; public final static ArrayList EXAMPLE_BLACKLIST_WORLDS_LIST_DEFAULT; - public final static String SKILL_SCALING_BENEFIT_EXPLANATION = "\nSub-Skills dynamically adjust their rewards to match the max bonus level, you can think of it as a curve that calculates what bonuses " + "\n a player should have based on how far they are from the max bonus level value, and the other parameters used for the scaling of that sub-skill."; + /* FOLDER NAMES */ + public static final String FOLDER_NAME_CONFIG = "config"; + public static final String FOLDER_NAME_SKILLS = "skills"; + public static final String FOLDER_NAME_EXPERIENCE = "Experience Settings"; + public static final String FOLDER_NAME_DEFAULTS = "defaults"; + /* RELATIVE PATHS */ + public final static String RELATIVE_PATH_CONFIG_DIR = File.separator + FOLDER_NAME_CONFIG + File.separator; + public final static String RELATIVE_PATH_SKILLS_DIR = RELATIVE_PATH_CONFIG_DIR + FOLDER_NAME_SKILLS + File.separator; + public final static String RELATIVE_PATH_XP_DIR = RELATIVE_PATH_CONFIG_DIR + FOLDER_NAME_EXPERIENCE + File.separator; + private final static String[] EXAMPLE_BLACKLIST_WORLDS = {"Example_15434453", "Example_2324423", "Example_323423465"}; //Add the worlds to the list static { @@ -23,23 +31,12 @@ public class ConfigConstants { EXAMPLE_BLACKLIST_WORLDS_LIST_DEFAULT.add(EXAMPLE_BLACKLIST_WORLDS[2]); } - /* FOLDER NAMES */ - public static final String FOLDER_NAME_CONFIG = "config"; - public static final String FOLDER_NAME_SKILLS = "skills"; - public static final String FOLDER_NAME_EXPERIENCE = "Experience Settings"; - public static final String FOLDER_NAME_DEFAULTS = "defaults"; - - /* RELATIVE PATHS */ - public final static String RELATIVE_PATH_CONFIG_DIR = File.separator + FOLDER_NAME_CONFIG + File.separator; - public final static String RELATIVE_PATH_SKILLS_DIR = RELATIVE_PATH_CONFIG_DIR + FOLDER_NAME_SKILLS + File.separator; - public final static String RELATIVE_PATH_XP_DIR = RELATIVE_PATH_CONFIG_DIR + FOLDER_NAME_EXPERIENCE + File.separator; - /** * Return the data folder for mcMMO + * * @return the File for the data folder used by mcMMO */ - public static File getDataFolder() - { + public static File getDataFolder() { return mcMMO.p.getDataFolder(); } @@ -74,33 +71,32 @@ public class ConfigConstants { /** * Creates all directories used by mcMMO config files */ - public static void makeAllConfigDirectories() - { + public static void makeAllConfigDirectories() { /* CONFIG DIRECTORY */ - if(!getConfigFolder().exists()) + if (!getConfigFolder().exists()) getConfigFolder().mkdirs(); /* DEFAULT DIRECTORIES */ - if(!getDefaultsFolder().exists()) + if (!getDefaultsFolder().exists()) getDefaultsFolder().mkdirs(); - if(!getDefaultsConfigFolder().exists()) + if (!getDefaultsConfigFolder().exists()) getDefaultsConfigFolder().mkdirs(); - if(!getDefaultsSkillFolder().exists()) + if (!getDefaultsSkillFolder().exists()) getDefaultsSkillFolder().mkdirs(); - if(!getDefaultsXPFolder().exists()) + if (!getDefaultsXPFolder().exists()) getDefaultsXPFolder().mkdirs(); /* CONFIG SUBDIRECTORIES */ - if(!getConfigSkillFolder().exists()) + if (!getConfigSkillFolder().exists()) getConfigSkillFolder().mkdirs(); - if(!getConfigXPFolder().exists()) + if (!getConfigXPFolder().exists()) getConfigXPFolder().mkdirs(); } } diff --git a/src/main/java/com/gmail/nossr50/config/ConfigManager.java b/src/main/java/com/gmail/nossr50/config/ConfigManager.java index e79012b27..428a38841 100644 --- a/src/main/java/com/gmail/nossr50/config/ConfigManager.java +++ b/src/main/java/com/gmail/nossr50/config/ConfigManager.java @@ -65,37 +65,32 @@ import java.util.ArrayList; import java.util.HashMap; /** - * * The Config Manager handles initializing, loading, and unloading registers for all configs that mcMMO uses * This makes sure that mcMMO properly loads and unloads its values on reload - * + *

* Config Manager also holds all of our MultiConfigContainers */ public final class ConfigManager { /* UNLOAD REGISTER */ + SkillPropertiesManager skillPropertiesManager; private ArrayList unloadables; - private ArrayList userFiles; /* COLLECTION MANAGERS */ - + private ArrayList userFiles; private RepairableManager repairableManager; private SalvageableManager salvageableManager; - private BonusDropManager bonusDropManager; /* CUSTOM SERIALIZERS */ - - private TypeSerializerCollection customSerializers; + private BonusDropManager bonusDropManager; /* MOD MANAGERS */ //TODO: Add these back when modded servers become a thing again /* MISC MANAGERS */ - - SkillPropertiesManager skillPropertiesManager; - + private TypeSerializerCollection customSerializers; private ExperienceMapManager experienceMapManager; /* CONFIG INSTANCES */ @@ -163,14 +158,12 @@ public final class ConfigManager { private ArrayList configErrors; //Collect errors to whine about to server admins - public ConfigManager() - { + public ConfigManager() { unloadables = new ArrayList<>(); userFiles = new ArrayList<>(); } - public void loadConfigs() - { + public void loadConfigs() { //Register Custom Serializers registerCustomTypeSerializers(); @@ -314,9 +307,12 @@ public final class ConfigManager { customSerializers = TypeSerializers.getDefaultSerializers().newChild(); mcMMO.p.getLogger().info("Registering custom type serializers for Configurate..."); - customSerializers.registerType(new TypeToken() {}, new CustomEnumValueSerializer()); - customSerializers.registerType(new TypeToken() {}, new CustomEnumValueSerializer()); - customSerializers.registerType(new TypeToken() {}, new CustomEnumValueSerializer()); + customSerializers.registerType(new TypeToken() { + }, new CustomEnumValueSerializer()); + customSerializers.registerType(new TypeToken() { + }, new CustomEnumValueSerializer()); + customSerializers.registerType(new TypeToken() { + }, new CustomEnumValueSerializer()); customSerializers.registerType(TypeToken.of(Repairable.class), new RepairableSerializer()); customSerializers.registerType(TypeToken.of(Salvageable.class), new SalvageableSerializer()); customSerializers.registerType(TypeToken.of(MinecraftMaterialWrapper.class), new MinecraftMaterialWrapperSerializer()); @@ -325,22 +321,21 @@ public final class ConfigManager { /** * Gets the serializers registered and used by mcMMO * This includes all default serializers + * * @return our custom serializers */ public TypeSerializerCollection getCustomSerializers() { return customSerializers; } - private void registerSkillConfig(PrimarySkillType primarySkillType, Class clazz) - { + private void registerSkillConfig(PrimarySkillType primarySkillType, Class clazz) { skillConfigLoaders.put(primarySkillType, SkillConfigFactory.initSkillConfig(primarySkillType, clazz)); } /** * Misc managers */ - private void initMiscManagers() - { + private void initMiscManagers() { experienceMapManager = new ExperienceMapManager(); } @@ -361,8 +356,7 @@ public final class ConfigManager { /** * Initializes any managers related to config collections */ - private void initCollectionManagers() - { + private void initCollectionManagers() { // Handles registration of repairables repairableManager = new RepairableManager(getRepairables()); unloadables.add(repairableManager); @@ -378,30 +372,28 @@ public final class ConfigManager { /** * Get all loaded repairables (loaded from all repairable configs) + * * @return the currently loaded repairables */ - public ArrayList getRepairables() - { + public ArrayList getRepairables() { return getConfigRepair().getConfigRepairablesList(); } /** * Get all loaded salvageables (loaded from all salvageable configs) + * * @return the currently loaded salvageables */ - public ArrayList getSalvageables() - { + public ArrayList getSalvageables() { return getConfigSalvage().getConfigSalvageablesList(); } /** * Unloads all config options (prepares for reload) */ - public void unloadAllConfigsAndRegisters() - { + public void unloadAllConfigsAndRegisters() { //Unload - for(Unload unloadable : unloadables) - { + for (Unload unloadable : unloadables) { unloadable.unload(); } @@ -414,9 +406,8 @@ public final class ConfigManager { * Registers an unloadable * Unloadables call unload() on plugin disable to cleanup registries */ - public void registerUnloadable(Unload unload) - { - if(!unloadables.contains(unload)) + public void registerUnloadable(Unload unload) { + if (!unloadables.contains(unload)) unloadables.add(unload); } @@ -424,24 +415,21 @@ public final class ConfigManager { * Registers an unloadable * Unloadables call unload() on plugin disable to cleanup registries */ - public void registerUserFile(File userFile) - { - if(!userFiles.contains(userFile)) + public void registerUserFile(File userFile) { + if (!userFiles.contains(userFile)) userFiles.add(userFile); } /** * Registers bonus drops from several skill configs */ - public void registerBonusDrops() - { + public void registerBonusDrops() { bonusDropManager.addToWhitelistByNameID(getConfigMining().getBonusDrops()); // bonusDropManager.addToWhitelistByNameID(configHerbalism.getBonusDrops()); // bonusDropManager.addToWhitelistByNameID(configWoodcutting.getBonusDrops()); } - public void validateConfigs() - { + public void validateConfigs() { } @@ -451,10 +439,10 @@ public final class ConfigManager { /** * Used to back up our zip files real easily + * * @return */ - public ArrayList getConfigFiles() - { + public ArrayList getConfigFiles() { return userFiles; } @@ -510,9 +498,13 @@ public final class ConfigManager { return experienceMapManager; } - public ConfigDatabase getConfigDatabase() { return configDatabase.getConfig(); } + public ConfigDatabase getConfigDatabase() { + return configDatabase.getConfig(); + } - public ConfigScoreboard getConfigScoreboard() { return configScoreboard.getConfig(); } + public ConfigScoreboard getConfigScoreboard() { + return configScoreboard.getConfig(); + } public ConfigLeveling getConfigLeveling() { return configLeveling.getConfig(); @@ -658,25 +650,22 @@ public final class ConfigManager { * Checks if this plugin is using retro mode * Retro mode is a 0-1000 skill system * Standard mode is scaled for 1-100 + * * @return true if retro mode is enabled */ - public boolean isRetroMode() - { + public boolean isRetroMode() { return getConfigLeveling().getConfigSectionLevelingGeneral().getConfigSectionLevelScaling().isRetroModeEnabled(); } - public boolean isBonusDropsEnabled(Material material) - { + public boolean isBonusDropsEnabled(Material material) { return getBonusDropManager().isBonusDropWhitelisted(material); } - public double getSkillMaxBonusLevel(SubSkillType subSkillType) - { + public double getSkillMaxBonusLevel(SubSkillType subSkillType) { return skillPropertiesManager.getMaxBonusLevel(subSkillType); } - public double getSkillMaxChance(SubSkillType subSkillType) - { + public double getSkillMaxChance(SubSkillType subSkillType) { return skillPropertiesManager.getMaxChance(subSkillType); } diff --git a/src/main/java/com/gmail/nossr50/config/ConfigValidated.java b/src/main/java/com/gmail/nossr50/config/ConfigValidated.java index e0a506c83..41de8af72 100644 --- a/src/main/java/com/gmail/nossr50/config/ConfigValidated.java +++ b/src/main/java/com/gmail/nossr50/config/ConfigValidated.java @@ -9,12 +9,11 @@ import java.io.File; public abstract class ConfigValidated extends Config implements UnsafeValueValidation { /** * @param pathToParentFolder File for the "parent" folder on disk - * @param relativePath Path to the config relative to the "parent" folder, this should mirror internal structure of resource files - * @param mergeNewKeys if true, the users config will add keys found in the internal file that are missing from the users file during load - * @param copyDefaults if true, the users config file when it is first made will be a copy of an internal resource file of the same name and path + * @param relativePath Path to the config relative to the "parent" folder, this should mirror internal structure of resource files + * @param mergeNewKeys if true, the users config will add keys found in the internal file that are missing from the users file during load + * @param copyDefaults if true, the users config file when it is first made will be a copy of an internal resource file of the same name and path */ - public ConfigValidated(String fileName, File pathToParentFolder, String relativePath, boolean generateDefaults, boolean mergeNewKeys, boolean copyDefaults, boolean removeOldKeys) - { + public ConfigValidated(String fileName, File pathToParentFolder, String relativePath, boolean generateDefaults, boolean mergeNewKeys, boolean copyDefaults, boolean removeOldKeys) { super(fileName, pathToParentFolder, relativePath, generateDefaults, mergeNewKeys, copyDefaults, removeOldKeys); validateEntries(); } diff --git a/src/main/java/com/gmail/nossr50/config/CoreSkillsConfig.java b/src/main/java/com/gmail/nossr50/config/CoreSkillsConfig.java index 013474570..bbdbad36c 100644 --- a/src/main/java/com/gmail/nossr50/config/CoreSkillsConfig.java +++ b/src/main/java/com/gmail/nossr50/config/CoreSkillsConfig.java @@ -19,8 +19,9 @@ public class CoreSkillsConfig extends Config { /** * This grabs an instance of the class from the Config Manager * This method is deprecated and will be removed in the future - * @see mcMMO#getConfigManager() + * * @return the instance of this config + * @see mcMMO#getConfigManager() * @deprecated Please use mcMMO.getConfigManager() to grab a specific config instead */ @Deprecated @@ -55,7 +56,7 @@ public class CoreSkillsConfig extends Config { * @return true if subskill is enabled */ public boolean isSkillEnabled(AbstractSubSkill abstractSubSkill) { - return getBooleanValue(StringUtils.getCapitalized(abstractSubSkill.getPrimarySkill().toString()), abstractSubSkill.getConfigKeyName(), ENABLED); + return getBooleanValue(StringUtils.getCapitalized(abstractSubSkill.getPrimarySkill().toString()), abstractSubSkill.getConfigKeyName(), ENABLED); } /** @@ -65,6 +66,6 @@ public class CoreSkillsConfig extends Config { * @return true if enabled */ public boolean isPrimarySkillEnabled(PrimarySkillType primarySkillType) { - return getBooleanValue(StringUtils.getCapitalized(primarySkillType.toString()), ENABLED); + return getBooleanValue(StringUtils.getCapitalized(primarySkillType.toString()), ENABLED); } } diff --git a/src/main/java/com/gmail/nossr50/config/GenericCollectionContainer.java b/src/main/java/com/gmail/nossr50/config/GenericCollectionContainer.java index 973ea5795..3176b6fd6 100644 --- a/src/main/java/com/gmail/nossr50/config/GenericCollectionContainer.java +++ b/src/main/java/com/gmail/nossr50/config/GenericCollectionContainer.java @@ -4,11 +4,13 @@ import java.util.Collection; /** * Represents a class that contains a generic collection + * * @param */ public interface GenericCollectionContainer { /** * Grab the collection held by this class + * * @return the collection held by this class */ Collection getLoadedCollection(); diff --git a/src/main/java/com/gmail/nossr50/config/MainConfig.java b/src/main/java/com/gmail/nossr50/config/MainConfig.java index 90143a73e..b192b24ea 100644 --- a/src/main/java/com/gmail/nossr50/config/MainConfig.java +++ b/src/main/java/com/gmail/nossr50/config/MainConfig.java @@ -208,8 +208,9 @@ public class MainConfig extends ConfigValidated { /** * This grabs an instance of this config class from the Config Manager * This method is deprecated and will be removed in the future - * @see mcMMO#getConfigManager() + * * @return the instance of this config + * @see mcMMO#getConfigManager() * @deprecated Please use mcMMO.getConfigManager() to grab a specific config instead */ @Deprecated diff --git a/src/main/java/com/gmail/nossr50/config/RankConfig.java b/src/main/java/com/gmail/nossr50/config/RankConfig.java index 3dc4a302d..4fa10671c 100644 --- a/src/main/java/com/gmail/nossr50/config/RankConfig.java +++ b/src/main/java/com/gmail/nossr50/config/RankConfig.java @@ -23,8 +23,9 @@ public class RankConfig extends ConfigValidated { /** * This grabs an instance of this config class from the Config Manager * This method is deprecated and will be removed in the future - * @see mcMMO#getConfigManager() + * * @return the instance of this config + * @see mcMMO#getConfigManager() * @deprecated Please use mcMMO.getConfigManager() to grab a specific config instead */ @Deprecated diff --git a/src/main/java/com/gmail/nossr50/config/SkillConfigFactory.java b/src/main/java/com/gmail/nossr50/config/SkillConfigFactory.java index ef08fd441..a5f6a2b78 100644 --- a/src/main/java/com/gmail/nossr50/config/SkillConfigFactory.java +++ b/src/main/java/com/gmail/nossr50/config/SkillConfigFactory.java @@ -6,11 +6,10 @@ import com.gmail.nossr50.util.StringUtils; public class SkillConfigFactory { - protected static SerializedConfigLoader initSkillConfig(PrimarySkillType primarySkillType, Class clazz) - { + protected static SerializedConfigLoader initSkillConfig(PrimarySkillType primarySkillType, Class clazz) { return new SerializedConfigLoader(clazz, - primarySkillType.toString().toLowerCase() + ".conf", - StringUtils.getCapitalized(primarySkillType.toString()), - null); + primarySkillType.toString().toLowerCase() + ".conf", + StringUtils.getCapitalized(primarySkillType.toString()), + null); } } diff --git a/src/main/java/com/gmail/nossr50/config/SkillPropertiesManager.java b/src/main/java/com/gmail/nossr50/config/SkillPropertiesManager.java index e1d254e33..18e0e73f0 100644 --- a/src/main/java/com/gmail/nossr50/config/SkillPropertiesManager.java +++ b/src/main/java/com/gmail/nossr50/config/SkillPropertiesManager.java @@ -14,37 +14,31 @@ public class SkillPropertiesManager { private HashMap maxBonusLevelMap; private HashMap maxBonusPercentage; - public SkillPropertiesManager() - { + public SkillPropertiesManager() { maxChanceMap = new HashMap<>(); maxBonusLevelMap = new HashMap<>(); maxBonusPercentage = new HashMap<>(); } - public void registerRNG(SubSkillType subSkillType, ConfigSubSkillScalingRNG config) - { + public void registerRNG(SubSkillType subSkillType, ConfigSubSkillScalingRNG config) { maxChanceMap.put(subSkillType, config.getMaxChance()); maxBonusLevelMap.put(subSkillType, config.getMaxBonusLevel()); } - public double getMaxChance(SubSkillType subSkillType) - { + public double getMaxChance(SubSkillType subSkillType) { return maxChanceMap.get(subSkillType); } - public double getMaxBonusLevel(SubSkillType subSkillType) - { + public double getMaxBonusLevel(SubSkillType subSkillType) { return maxBonusLevelMap.get(subSkillType); } - public void fillRegisters() - { + public void fillRegisters() { fillRNGRegisters(); } - private void fillRNGRegisters() - { + private void fillRNGRegisters() { //Acrobatics registerRNG(SubSkillType.ACROBATICS_DODGE, mcMMO.getConfigManager().getConfigAcrobatics().getDodge().getRNGSettings()); registerRNG(SubSkillType.ACROBATICS_DODGE, mcMMO.getConfigManager().getConfigAcrobatics().getRoll().getRNGSettings()); diff --git a/src/main/java/com/gmail/nossr50/config/SoundConfig.java b/src/main/java/com/gmail/nossr50/config/SoundConfig.java index 563a94220..415fad85a 100644 --- a/src/main/java/com/gmail/nossr50/config/SoundConfig.java +++ b/src/main/java/com/gmail/nossr50/config/SoundConfig.java @@ -24,8 +24,9 @@ public class SoundConfig extends ConfigValidated { /** * This grabs an instance of this config class from the Config Manager * This method is deprecated and will be removed in the future - * @see mcMMO#getConfigManager() + * * @return the instance of this config + * @see mcMMO#getConfigManager() * @deprecated Please use mcMMO.getConfigManager() to grab a specific config instead */ @Deprecated diff --git a/src/main/java/com/gmail/nossr50/config/UnsafeValueValidation.java b/src/main/java/com/gmail/nossr50/config/UnsafeValueValidation.java index a6f18a2d4..175a19834 100644 --- a/src/main/java/com/gmail/nossr50/config/UnsafeValueValidation.java +++ b/src/main/java/com/gmail/nossr50/config/UnsafeValueValidation.java @@ -13,18 +13,15 @@ public interface UnsafeValueValidation { /** * Prints all errors found when validating the config */ - default void validateEntries() - { + default void validateEntries() { /* * Print Errors about Keys */ List validKeyErrors = validateKeys(); // Validate Keys - if(validKeyErrors != null && validKeyErrors.size() > 0) - { - for(String error : validKeyErrors) - { + if (validKeyErrors != null && validKeyErrors.size() > 0) { + for (String error : validKeyErrors) { mcMMO.p.getLogger().severe(error); } } diff --git a/src/main/java/com/gmail/nossr50/config/VersionedConfig.java b/src/main/java/com/gmail/nossr50/config/VersionedConfig.java index 00c29dfb7..a3799bea9 100644 --- a/src/main/java/com/gmail/nossr50/config/VersionedConfig.java +++ b/src/main/java/com/gmail/nossr50/config/VersionedConfig.java @@ -6,6 +6,7 @@ package com.gmail.nossr50.config; public interface VersionedConfig { /** * The version of this config + * * @return */ double getConfigVersion(); diff --git a/src/main/java/com/gmail/nossr50/config/experience/ExperienceConfig.java b/src/main/java/com/gmail/nossr50/config/experience/ExperienceConfig.java index 9309a97ac..b9e32ef72 100644 --- a/src/main/java/com/gmail/nossr50/config/experience/ExperienceConfig.java +++ b/src/main/java/com/gmail/nossr50/config/experience/ExperienceConfig.java @@ -86,8 +86,9 @@ public class ExperienceConfig extends ConfigValidated { /** * This grabs an instance of this config class from the Config Manager * This method is deprecated and will be removed in the future - * @see mcMMO#getConfigManager() + * * @return the instance of this config + * @see mcMMO#getConfigManager() * @deprecated Please use mcMMO.getConfigManager() to grab a specific config instead */ @Deprecated @@ -168,9 +169,6 @@ public class ExperienceConfig extends ConfigValidated { return reason; } - - - /* * FORMULA SETTINGS */ @@ -185,8 +183,7 @@ public class ExperienceConfig extends ConfigValidated { return getDoubleValue(EXPERIENCE_FORMULA, MULTIPLIER, GLOBAL); } - public void setGlobalXPMultiplier(double newXpMultiplier) - { + public void setGlobalXPMultiplier(double newXpMultiplier) { getUserRootNode().getNode(EXPERIENCE_FORMULA, MULTIPLIER, GLOBAL).setValue(newXpMultiplier); } @@ -266,14 +263,15 @@ public class ExperienceConfig extends ConfigValidated { /** * Gets the raw XP given for breaking this block, this does not include modifiers - * @param skill The skill to give XP for + * + * @param skill The skill to give XP for * @param blockType the type of block * @return the raw amount of XP for this block before modifiers */ //public int getXp(PrimarySkillType skill, BlockType blockType) { public int getXp(PrimarySkillType skill, Material blockType) { //TODO: This is going to need to be changed, this code here is only placeholder - String[] path = new String[]{ EXPERIENCE, StringUtils.getCapitalized(skill.toString()), blockType.toString()}; + String[] path = new String[]{EXPERIENCE, StringUtils.getCapitalized(skill.toString()), blockType.toString()}; return getIntValue(path); } diff --git a/src/main/java/com/gmail/nossr50/config/hocon/HOCONUtil.java b/src/main/java/com/gmail/nossr50/config/hocon/HOCONUtil.java index 6e9d3780f..0a3160c9c 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/HOCONUtil.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/HOCONUtil.java @@ -4,14 +4,12 @@ import com.gmail.nossr50.util.StringUtils; public final class HOCONUtil { - public static String serializeENUMName(String hyphenedString) - { + public static String serializeENUMName(String hyphenedString) { String[] split = hyphenedString.split("_"); StringBuilder formattedString = new StringBuilder(); - for(int x = 0; x < split.length; x++) - { - if(x + 1 >= split.length) + for (int x = 0; x < split.length; x++) { + if (x + 1 >= split.length) formattedString.append(StringUtils.getCapitalized(split[x])); else formattedString.append(StringUtils.getCapitalized(split[x])).append('-'); @@ -20,14 +18,12 @@ public final class HOCONUtil { return formattedString.toString(); } - public static String deserializeENUMName(String serializedName) - { + public static String deserializeENUMName(String serializedName) { String[] split = serializedName.split("-"); StringBuilder formattedString = new StringBuilder(); - for(int x = 0; x < split.length; x++) - { - if(x + 1 >= split.length) + for (int x = 0; x < split.length; x++) { + if (x + 1 >= split.length) formattedString.append(split[x].toUpperCase()); else formattedString.append(split[x]).append('_'); diff --git a/src/main/java/com/gmail/nossr50/config/hocon/RepairableSerializer.java b/src/main/java/com/gmail/nossr50/config/hocon/RepairableSerializer.java index 999289ccd..68c0988a5 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/RepairableSerializer.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/RepairableSerializer.java @@ -46,7 +46,8 @@ public class RepairableSerializer implements TypeSerializer { /* Repairable(Material itemMaterial, Material repairMaterial, int minimumQuantity, int minimumLevel, double xpMultiplier) */ String item = value.getNode(ITEM).getValue(TypeToken.of(String.class)); - List repairItems = value.getNode(ITEMS_USED_TO_REPAIR).getValue(new TypeToken>() {}); + List repairItems = value.getNode(ITEMS_USED_TO_REPAIR).getValue(new TypeToken>() { + }); /*String itemConstant = HOCONUtil.deserializeENUMName(value.getNode("Item").getString()); @@ -74,8 +75,7 @@ public class RepairableSerializer implements TypeSerializer { value.getNode(XP_MULTIPLIER).setValue(obj.getXpMultiplier()); } - private Enum getEnum(String enumConstant, TypeToken type) throws ObjectMappingException - { + private Enum getEnum(String enumConstant, TypeToken type) throws ObjectMappingException { //noinspection RedundantCast Optional ret = (Optional) EnumLookup.lookupEnum(type.getRawType().asSubclass(Enum.class), enumConstant); // XXX: intellij says this cast is optional but it isnt diff --git a/src/main/java/com/gmail/nossr50/config/hocon/SalvageableSerializer.java b/src/main/java/com/gmail/nossr50/config/hocon/SalvageableSerializer.java index 4e9d28bbb..a6ebf94d2 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/SalvageableSerializer.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/SalvageableSerializer.java @@ -61,8 +61,7 @@ public class SalvageableSerializer implements TypeSerializer { value.getNode(OVERRIDE_LEVEL_REQUIREMENT).setValue(obj.getMinimumLevel()); } - private Enum getEnum(String enumConstant, TypeToken type) throws ObjectMappingException - { + private Enum getEnum(String enumConstant, TypeToken type) throws ObjectMappingException { //noinspection RedundantCast Optional ret = (Optional) EnumLookup.lookupEnum(type.getRawType().asSubclass(Enum.class), enumConstant); // XXX: intellij says this cast is optional but it isnt diff --git a/src/main/java/com/gmail/nossr50/config/hocon/SerializedConfigLoader.java b/src/main/java/com/gmail/nossr50/config/hocon/SerializedConfigLoader.java index 2ada0563e..7408421b3 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/SerializedConfigLoader.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/SerializedConfigLoader.java @@ -49,6 +49,7 @@ import java.util.Objects; /** * Handles loading serialized configs with configurate + * * @param the class type of the config */ public class SerializedConfigLoader { @@ -61,20 +62,15 @@ public class SerializedConfigLoader { "\nOfficial mcMMO Discord - https://discord.gg/bJ7pFS9\n" + "\nYou can also consult the new official wiki" + "\nhttps://mcmmo.org/wiki - Keep in mind the wiki is a WIP and may not have information about everything in mcMMO!"; - - private ConfigurationOptions configurationOptions; - private CommentedConfigurationNode data; - private CommentedConfigurationNode fileData; - private final String ROOT_NODE_ADDRESS; - private final Path path; - /** * The parent configuration - values are inherited from this */ private final SerializedConfigLoader parent; - + private ConfigurationOptions configurationOptions; + private CommentedConfigurationNode data; + private CommentedConfigurationNode fileData; /** * The loader (mapped to a file) used to read/write the config to disk */ @@ -110,13 +106,12 @@ public class SerializedConfigLoader { reload(); save(); } catch (Exception e) { - mcMMO.p.getLogger().severe("Failed to initialize config - "+path.toString()); + mcMMO.p.getLogger().severe("Failed to initialize config - " + path.toString()); e.printStackTrace(); } } - private Path getPathFromFileName(String fileName) - { + private Path getPathFromFileName(String fileName) { File configFile = new File(ConfigConstants.getConfigFolder(), fileName); return configFile.toPath(); } @@ -143,7 +138,7 @@ public class SerializedConfigLoader { this.loader.save(saveNode); return true; } catch (IOException | ObjectMappingException e) { - mcMMO.p.getLogger().severe("Failed to save configuration - "+path.toString()); + mcMMO.p.getLogger().severe("Failed to save configuration - " + path.toString()); e.printStackTrace(); return false; } @@ -169,7 +164,7 @@ public class SerializedConfigLoader { // populate the config object populateInstance(); } catch (Exception e) { - mcMMO.p.getLogger().severe("Failed to load configuration - "+path.toString()); + mcMMO.p.getLogger().severe("Failed to load configuration - " + path.toString()); e.printStackTrace(); } } diff --git a/src/main/java/com/gmail/nossr50/config/hocon/antiexploit/AntiExploit.java b/src/main/java/com/gmail/nossr50/config/hocon/antiexploit/AntiExploit.java index 9ea19c2a9..33e021f8a 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/antiexploit/AntiExploit.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/antiexploit/AntiExploit.java @@ -5,18 +5,17 @@ import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; @ConfigSerializable public class AntiExploit { + public static final boolean SPAWNED_MOBS_DEFAULT = true; private static final boolean ENDERMEN_ENDERMITE_DEFAULT = true; private static final boolean PISTONS_MARK_BLOCKS_DEFAULT = true; - public static final boolean SPAWNED_MOBS_DEFAULT = true; /* * CONFIG NODES */ - @Setting(value = "Endermen-Endermite-Fix", comment = "Removes XP from Endermen that target endermite, this is a common exploit in The End because of how rapidly they can spawn." + "\nIt is recommended that you leave this on as it allows players to easily gain massive amounts of combat XP" + - "\nDefault value: "+ENDERMEN_ENDERMITE_DEFAULT) + "\nDefault value: " + ENDERMEN_ENDERMITE_DEFAULT) private boolean endermenEndermiteFix = ENDERMEN_ENDERMITE_DEFAULT; @Setting(value = "Pistons-Mark-Blocks-As-Unnatural", @@ -26,7 +25,7 @@ public class AntiExploit { @Setting(value = "Spawned-Mobs-Give-No-XP", comment = "Spawned mobs will not give players combat XP." + - "\nThis includes mobs spawned from a nether portal, mob spawner, or eggs." + - "\nThis will not include mobs spawned from commands, typically.") + "\nThis includes mobs spawned from a nether portal, mob spawner, or eggs." + + "\nThis will not include mobs spawned from commands, typically.") private boolean spawnedMobsGiveNoXP = SPAWNED_MOBS_DEFAULT; } diff --git a/src/main/java/com/gmail/nossr50/config/hocon/antiexploit/ConfigSectionExploitAcrobatics.java b/src/main/java/com/gmail/nossr50/config/hocon/antiexploit/ConfigSectionExploitAcrobatics.java index 4a08eff34..a223cb176 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/antiexploit/ConfigSectionExploitAcrobatics.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/antiexploit/ConfigSectionExploitAcrobatics.java @@ -18,7 +18,7 @@ public class ConfigSectionExploitAcrobatics { "\nPlayers cannot gain XP from falling in the same location twice." + "\nIt's best you do not raise this number unless you have some kind of god computer," + "\n mcMMO processes the entire tracked location list anytime a player takes fall damage so the bigger this is the more expensive that calculation is." + - "\nDefault value: "+ACROBATIC_LOCATION_LIMIT_DEFAULT) + "\nDefault value: " + ACROBATIC_LOCATION_LIMIT_DEFAULT) private int acrobaticLocationLimit = ACROBATIC_LOCATION_LIMIT_DEFAULT; @Setting(value = "Prevent-Acrobatics-Farming", @@ -26,16 +26,16 @@ public class ConfigSectionExploitAcrobatics { "\nEnabled tracking player fall locations" + "\nEnables tracking when a player last teleported" + "\nEnables tracking when a player last respawned" + - "\nDefault value: "+PREVENT_ACROBATICS_ABUSE_DEFAULT) + "\nDefault value: " + PREVENT_ACROBATICS_ABUSE_DEFAULT) private boolean preventAcrobaticsAbuse = PREVENT_ACROBATICS_ABUSE_DEFAULT; @Setting(value = "No-XP-After-Teleporting-Cooldown-In-Seconds", comment = "Prevents XP gains for Acrobatics for a set period of time after teleporting." + - "\nDefault value: "+TELEPORT_COOLDOWN_DEFAULT) + "\nDefault value: " + TELEPORT_COOLDOWN_DEFAULT) private int teleportCooldownSeconds = TELEPORT_COOLDOWN_DEFAULT; @Setting(value = "Fall-Damage-XP-Gain-Cooldown-In-Seconds", comment = "Prevent players from gaining XP from fall damage if they had gained XP recently." + "\nWhen players take fall damage again within this cooldown period the length of the cooldown is increased to discourage automated Roll XP farming." + - "\nDefault value: "+ROLL_XP_GAIN_CD_DEFAULT) + "\nDefault value: " + ROLL_XP_GAIN_CD_DEFAULT) private int rollXPGainCooldownSeconds = ROLL_XP_GAIN_CD_DEFAULT; public int getRollXPGainCooldownSeconds() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/antiexploit/ConfigSectionExploitFishing.java b/src/main/java/com/gmail/nossr50/config/hocon/antiexploit/ConfigSectionExploitFishing.java index bdb06bcbd..413d21182 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/antiexploit/ConfigSectionExploitFishing.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/antiexploit/ConfigSectionExploitFishing.java @@ -6,24 +6,23 @@ import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; @ConfigSerializable public class ConfigSectionExploitFishing { - private static final boolean PREVENT_FISHING_EXPLOITS_DEFAULT = true; public static final int OVER_FISHING_LIMIT_DEFAULT = 3; public static final boolean ADMINS_OVER_FISHING_DEFAULT = true; public static final float OVER_FISHING_SIZE = 1.0F; public static final int FISHING_ROD_SPAM_THRESHOLD_MILLISECONDS_DEFAULT = 200; - + private static final boolean PREVENT_FISHING_EXPLOITS_DEFAULT = true; @Setting(value = "Prevent-Fishing-AFK-Farming", comment = "Prevents many methods for automatically farming Fishing XP." + "\nSuch as farming in the same spot more than once." + "\nSpam-click fishing." + - "\nDefault value: "+PREVENT_FISHING_EXPLOITS_DEFAULT) + "\nDefault value: " + PREVENT_FISHING_EXPLOITS_DEFAULT) private boolean preventFishingExploits = PREVENT_FISHING_EXPLOITS_DEFAULT; @Setting(value = "Overfishing-Limit", comment = "How many times a player can fish in the same spot before it becomes over-fished" + "\nOver fishing is in place to prevent 99% of AFK fishing from working." + "\nFishing in a new spot is all it takes to remove over-fishing from your previous location." + "\nOver-fishing is based on where your fishing bobber actually lands and catches fish, it has nothing to do with where you are standing." + - "\nDefault value: "+OVER_FISHING_LIMIT_DEFAULT) + "\nDefault value: " + OVER_FISHING_LIMIT_DEFAULT) private int overfishingLimit = OVER_FISHING_LIMIT_DEFAULT; @Setting(value = "Overfishing-Area-Size-Radius", comment = "Over-Fishing tracks where you've caught fish from by making a bounding box around where your fishing rod's bobber lands." + @@ -32,18 +31,18 @@ public class ConfigSectionExploitFishing { "\nA value of 1.0 would result in a bounding box that is 2.0 units (blocks) in size" + "\nWhen you catch a new fish it makes a new bounding box at that location and checks to see if it overlaps with the bounding box of the last place you caught a fish," + "\n if they intersect then that increases your fish counter, if you are at your fishing limit then you get nothing." + - "\nDefault value: "+OVER_FISHING_SIZE) + "\nDefault value: " + OVER_FISHING_SIZE) private float overFishingAreaSize = OVER_FISHING_SIZE; @Setting(value = "Alert-Admins-To-Overfishing-Abuse", comment = "If someone is triggering over-fishing exploit detection too often, alert admins." + "\nThis will send a message to ops in game and to the console, and to anyone with the admin chat permission node." + - "\nDefault value: "+ADMINS_OVER_FISHING_DEFAULT) + "\nDefault value: " + ADMINS_OVER_FISHING_DEFAULT) private boolean alertAdminsOnOverFishing = ADMINS_OVER_FISHING_DEFAULT; @Setting(value = "Fishing-Rod-Spam-Threshold-In-Milliseconds", comment = "How many milliseconds in between casting the fishing rod before a player suffers from fatigue." + "\nFatigue causes a loss of 1 hunger and 5 durability damage to the currently held fishing rod." + "\nThis is to prevent exploits for fishing that involve rapid fire auto clickers." + - "\nDefault value: "+FISHING_ROD_SPAM_THRESHOLD_MILLISECONDS_DEFAULT) + "\nDefault value: " + FISHING_ROD_SPAM_THRESHOLD_MILLISECONDS_DEFAULT) private long fishingRodSpamMilliseconds = FISHING_ROD_SPAM_THRESHOLD_MILLISECONDS_DEFAULT; public long getFishingRodSpamMilliseconds() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/antiexploit/ConfigSectionGeneral.java b/src/main/java/com/gmail/nossr50/config/hocon/antiexploit/ConfigSectionGeneral.java index 35d8f0848..83347f9fc 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/antiexploit/ConfigSectionGeneral.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/antiexploit/ConfigSectionGeneral.java @@ -6,39 +6,38 @@ import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; @ConfigSerializable public class ConfigSectionGeneral { - private static final boolean ENDERMEN_ENDERMITE_DEFAULT = true; - private static final boolean PISTONS_MARK_BLOCKS_DEFAULT = true; public static final boolean SPAWNED_MOBS_DEFAULT = true; public static final boolean TAMED_MOB_DEFAULT = true; - + private static final boolean ENDERMEN_ENDERMITE_DEFAULT = true; + private static final boolean PISTONS_MARK_BLOCKS_DEFAULT = true; @Setting(value = "Endermen-Endermite-Fix", comment = "Removes XP from Endermen that target endermite, this is a common exploit in The End because of how rapidly they can spawn." + "\nIt is recommended that you leave this on as it allows players to easily gain massive amounts of combat XP" + - "\nDefault value: "+ENDERMEN_ENDERMITE_DEFAULT) + "\nDefault value: " + ENDERMEN_ENDERMITE_DEFAULT) private boolean endermenEndermiteFix = ENDERMEN_ENDERMITE_DEFAULT; @Setting(value = "Pistons-Mark-Blocks-As-Unnatural", comment = "Unnatural blocks give no XP." + "This helps prevent complex automated stone farms that enable auto clickers to gain XP passively." + - "\nDefault value: "+PISTONS_MARK_BLOCKS_DEFAULT) + "\nDefault value: " + PISTONS_MARK_BLOCKS_DEFAULT) private boolean pistonsMarkBlocksUnnatural = PISTONS_MARK_BLOCKS_DEFAULT; @Setting(value = "Spawned-Mobs-Have-Modified-XP-Values", comment = "Spawned mobs will give different XP values than their naturally spawning counterparts" + - "\nBy default, spawned mob XP is reduced to zero, but you could change it in the experience config to whatever you want." + - "\nSpawned mobs include mobs spawned from a nether portal, mob spawner, or eggs." + - "\nThis will not include mobs spawned from commands, typically." + - "\nDefault value: "+SPAWNED_MOBS_DEFAULT) + "\nBy default, spawned mob XP is reduced to zero, but you could change it in the experience config to whatever you want." + + "\nSpawned mobs include mobs spawned from a nether portal, mob spawner, or eggs." + + "\nThis will not include mobs spawned from commands, typically." + + "\nDefault value: " + SPAWNED_MOBS_DEFAULT) private boolean markSpawnedMobs = SPAWNED_MOBS_DEFAULT; @Setting(value = "Tamed-Entities-Have-Modified-XP-Values", comment = "Prevents tamed entities from giving normal combat XP when struck by players" + - "\nBy default, combat XP from tamed mobs is reduced to zero, but you could change it in the experience config to whatever you want." + - "\nIt's hard to imagine this being abused, but we disable it anyways." + - "\nTamed entities get marked in the same way that spawned mobs do, so they are affected by the same XP modifiers." + - "\nDefault value: "+TAMED_MOB_DEFAULT) + "\nBy default, combat XP from tamed mobs is reduced to zero, but you could change it in the experience config to whatever you want." + + "\nIt's hard to imagine this being abused, but we disable it anyways." + + "\nTamed entities get marked in the same way that spawned mobs do, so they are affected by the same XP modifiers." + + "\nDefault value: " + TAMED_MOB_DEFAULT) private boolean preventTamedMobXp = TAMED_MOB_DEFAULT; public boolean getEndermenEndermiteFix() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/backup/ConfigAutomatedBackups.java b/src/main/java/com/gmail/nossr50/config/hocon/backup/ConfigAutomatedBackups.java index 878322a04..48a41b25f 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/backup/ConfigAutomatedBackups.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/backup/ConfigAutomatedBackups.java @@ -14,12 +14,12 @@ public class ConfigAutomatedBackups { "\nYou can find the backups in the following directory inside your mcMMO folder - \\mcMMO\\backup" + "\nAutomated backups are deleted regularly once they reach a certain age, see the other options in this config to change this." + "\nBackups are made whenever you start your server for the first time and on each reload of the mcMMO plugin" + - "\nDefault value: "+ZIP_BACKUPS_ENABLED_DEFAULT) + "\nDefault value: " + ZIP_BACKUPS_ENABLED_DEFAULT) private boolean zipBackupsEnabled = ZIP_BACKUPS_ENABLED_DEFAULT; @Setting(value = "Old-File-Age-Limit-In-Days", comment = "How many days should backups be kept in days?" + "\nBackups older than this are removed if the number of file backups is greater than \"Minimum-Backups\"." + - "\nDefault value: "+ BACKUP_DAY_LIMIT_DEFAULT) + "\nDefault value: " + BACKUP_DAY_LIMIT_DEFAULT) private int backupDayLimit = BACKUP_DAY_LIMIT_DEFAULT; public boolean isZipBackupsEnabled() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/commands/ConfigCommandsAdminChat.java b/src/main/java/com/gmail/nossr50/config/hocon/commands/ConfigCommandsAdminChat.java index 79cb7f584..f0aabd7c8 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/commands/ConfigCommandsAdminChat.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/commands/ConfigCommandsAdminChat.java @@ -8,18 +8,16 @@ public class ConfigCommandsAdminChat { private static final String ADMIN_CHAT_PREFIX_DEFAULT = "&b[&f{0}&b]"; private static final boolean USE_DISPLAY_NAMES_DEFAULT = true; - - @Setting(value = "Admin-Chat-Prefix", comment = "Formatting use at the beginning of an admin chat message." + - "\nYou can use & color codes here or type stuff like [[RED]]." + - "\nDefault value: "+ADMIN_CHAT_PREFIX_DEFAULT) - private String adminChatPrefix = ADMIN_CHAT_PREFIX_DEFAULT; - @Setting(value = "Whether or not to use Display Names for admin chat." + "\nDisplay names are the current visible name of a player in the scoreboard, chat, and so on." + "\nThese names are modified by mods and are not necessarily the same nickname that a player has associated with their account." + "\nIf you turn this off, mcMMO will use a players registered nickname with their Minecraft account instead." + - "\nDefault value: "+USE_DISPLAY_NAMES_DEFAULT) + "\nDefault value: " + USE_DISPLAY_NAMES_DEFAULT) public boolean useDisplayNames = USE_DISPLAY_NAMES_DEFAULT; + @Setting(value = "Admin-Chat-Prefix", comment = "Formatting use at the beginning of an admin chat message." + + "\nYou can use & color codes here or type stuff like [[RED]]." + + "\nDefault value: " + ADMIN_CHAT_PREFIX_DEFAULT) + private String adminChatPrefix = ADMIN_CHAT_PREFIX_DEFAULT; public String getAdminChatPrefix() { return adminChatPrefix; diff --git a/src/main/java/com/gmail/nossr50/config/hocon/commands/ConfigCommandsInspect.java b/src/main/java/com/gmail/nossr50/config/hocon/commands/ConfigCommandsInspect.java index c7effc7ab..8b2409675 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/commands/ConfigCommandsInspect.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/commands/ConfigCommandsInspect.java @@ -13,17 +13,17 @@ public class ConfigCommandsInspect { @Setting(value = "Inspect-Max-Distance", comment = "The maximum range at which players can inspect one another." + "\nIs only used if limit inspect range is turned on." + - "\nDefault value: "+INSPECT_MAX_DISTANCE_DEFAULT) + "\nDefault value: " + INSPECT_MAX_DISTANCE_DEFAULT) private double inspectCommandMaxDistance = INSPECT_MAX_DISTANCE_DEFAULT; @Setting(value = "Limit-Inspect-Range", comment = "Inspection is limited by the distance between players instead of always being usable." + "Permission to bypass this limit - " + BYPASS_PERMISSION - +"\nDefault value: "+LIMIT_INSPECT_RANGE_DEFAULT) + + "\nDefault value: " + LIMIT_INSPECT_RANGE_DEFAULT) private boolean limitInspectRange = LIMIT_INSPECT_RANGE_DEFAULT; @Setting(value = "Allow-Offline-Inspection", comment = "If set to true players will be able to look at the profiles of anyone on the server whether they are connected or not." + "\nAdmins and the console can always check the profiles of offline players." + - "\nDefault value: "+ALLOW_OFFLINE_INSPECTION_DEFAULT) + "\nDefault value: " + ALLOW_OFFLINE_INSPECTION_DEFAULT) private boolean allowInspectOnOfflinePlayers = ALLOW_OFFLINE_INSPECTION_DEFAULT; public double getInspectCommandMaxDistance() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigDatabaseFlatFile.java b/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigDatabaseFlatFile.java index bc915391b..6598006db 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigDatabaseFlatFile.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigDatabaseFlatFile.java @@ -10,7 +10,7 @@ public class ConfigDatabaseFlatFile { @Setting(value = "Scoreboard-Leaderboard-Update-Interval", comment = "How often the scoreboard leaderboards will update." + "\nThis is an expensive operation, it is highly recommended to avoid doing this often." + - "\nDefault value: "+LEADERBOARD_SCOREBOARD_UPDATE_INTERVAL_MINUTES_DEFAULT) + "\nDefault value: " + LEADERBOARD_SCOREBOARD_UPDATE_INTERVAL_MINUTES_DEFAULT) private int leaderboardUpdateIntervalMinutes = LEADERBOARD_SCOREBOARD_UPDATE_INTERVAL_MINUTES_DEFAULT; public int getLeaderboardUpdateIntervalMinutes() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigSectionCleaning.java b/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigSectionCleaning.java index a5d729ee3..517dfe66e 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigSectionCleaning.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigSectionCleaning.java @@ -19,26 +19,26 @@ public class ConfigSectionCleaning { @Setting(value = "Purge-Old-Users", comment = "Turn this on to enable automatic database pruning of old users." + - "\nDefault value: "+PURGE_OLD_USERS) + "\nDefault value: " + PURGE_OLD_USERS) private boolean purgeOldUsers = PURGE_OLD_USERS; @Setting(value = "Purge-Powerless-Users", comment = "Powerless users are players who have not" + " leveled up in a single skill." + - "\nDefault value: "+PURGE_POWERLESS_USERS) + "\nDefault value: " + PURGE_POWERLESS_USERS) private boolean purgePowerlessUsers = PURGE_POWERLESS_USERS; @Setting(value = "Only-Purge-At-Plugin-Startup", comment = "If set to true, then purging will only happen when the plugin first loads." + "\nKeep in mind, this will trigger on reload as well." + "\nThis purge is on a 2 second delay from plugin start-up and runs in an ASYNC thread." + - "\nDefault value: "+ONLY_PURGE_AT_STARTUP) + "\nDefault value: " + ONLY_PURGE_AT_STARTUP) private boolean onlyPurgeAtStartup = ONLY_PURGE_AT_STARTUP; @Setting(value = "Purge-Interval-In-Hours", comment = "How many hours between automatic purging?") private int purgeInterval = PURGE_INTERVAL_DEFAULT; @Setting(value = "Old-User-Cutoff-In-Months", comment = "Users who haven't connected in this many months will be purged" + - "\nDefault value: "+OLD_USER_CUTOFF_IN_MONTHS) + "\nDefault value: " + OLD_USER_CUTOFF_IN_MONTHS) private int oldUserCutoffMonths = OLD_USER_CUTOFF_IN_MONTHS; /* diff --git a/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigSectionDatabaseGeneral.java b/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigSectionDatabaseGeneral.java index 658ca88d1..64c80f1e8 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigSectionDatabaseGeneral.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigSectionDatabaseGeneral.java @@ -12,7 +12,7 @@ public class ConfigSectionDatabaseGeneral { "\nSaving the database is an expensive operation although it is done in an ASYNC thread." + "\nI wouldn't recommend setting this value lower than 10 minutes" + "\nKeep in mind if you properly shut down your server with a stop command mcMMO saves before your server shuts down." + - "\nDefault value: "+SAVE_INTERVAL_MINUTES_DEFAULT) + "\nDefault value: " + SAVE_INTERVAL_MINUTES_DEFAULT) private int saveIntervalMinutes = SAVE_INTERVAL_MINUTES_DEFAULT; public int getSaveIntervalMinutes() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigSectionMaxConnections.java b/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigSectionMaxConnections.java index e24b98a99..3dbe441ea 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigSectionMaxConnections.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigSectionMaxConnections.java @@ -15,13 +15,13 @@ public class ConfigSectionMaxConnections { * CONFIG NODES */ - @Setting(value = "Misc-Connection-Limit", comment = "Default value: "+MISC_DEFAULT) + @Setting(value = "Misc-Connection-Limit", comment = "Default value: " + MISC_DEFAULT) private int misc = 30; - @Setting(value = "Load-Connection-Limit", comment = "Default value: "+LOAD_DEFAULT) + @Setting(value = "Load-Connection-Limit", comment = "Default value: " + LOAD_DEFAULT) private int load = 30; - @Setting(value = "Save-Connection-Limit", comment = "Default value: "+SAVE_DEFAULT) + @Setting(value = "Save-Connection-Limit", comment = "Default value: " + SAVE_DEFAULT) private int save = 30; /* diff --git a/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigSectionMaxPoolSize.java b/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigSectionMaxPoolSize.java index 487f4b5b6..9696d7b2b 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigSectionMaxPoolSize.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigSectionMaxPoolSize.java @@ -15,13 +15,13 @@ public class ConfigSectionMaxPoolSize { * CONFIG NODES */ - @Setting(value = "Misc-Pool", comment = "Default value: "+MISC_DEFAULT) + @Setting(value = "Misc-Pool", comment = "Default value: " + MISC_DEFAULT) private int misc = 10; - @Setting(value = "Load-Pool", comment = "Default value: "+LOAD_DEFAULT) + @Setting(value = "Load-Pool", comment = "Default value: " + LOAD_DEFAULT) private int load = 20; - @Setting(value = "Save-Pool", comment = "Default value: "+SAVE_DEFAULT) + @Setting(value = "Save-Pool", comment = "Default value: " + SAVE_DEFAULT) private int save = 20; /* diff --git a/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigSectionMySQL.java b/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigSectionMySQL.java index 7179548c1..9c2212392 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigSectionMySQL.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/database/ConfigSectionMySQL.java @@ -17,7 +17,7 @@ public class ConfigSectionMySQL { @Setting(value = "Use-MySQL", comment = "If set to true, mcMMO will use MySQL/MariaDB instead of FlatFile storage" + "\nIt is highly recommended to use a MySQL/MariaDB server over FlatFile," + " especially if the number of players on your Minecraft server is fairly high." + - "\nDefault value: "+USE_MYSQL_DEFAULT) + "\nDefault value: " + USE_MYSQL_DEFAULT) private boolean useMySQL = USE_MYSQL_DEFAULT; @Setting(value = "User", comment = "Your MySQL User Settings") @@ -53,10 +53,8 @@ public class ConfigSectionMySQL { * HELPER METHODS */ - public int getMaxPoolSize(PoolIdentifier poolIdentifier) - { - switch (poolIdentifier) - { + public int getMaxPoolSize(PoolIdentifier poolIdentifier) { + switch (poolIdentifier) { case LOAD: return userConfigSectionServer.getConfigSectionMaxPoolSize().getLoad(); case SAVE: @@ -68,10 +66,8 @@ public class ConfigSectionMySQL { } } - public int getMaxConnections(PoolIdentifier poolIdentifier) - { - switch (poolIdentifier) - { + public int getMaxConnections(PoolIdentifier poolIdentifier) { + switch (poolIdentifier) { case LOAD: return userConfigSectionServer.getConfigSectionMaxConnections().getLoad(); case SAVE: diff --git a/src/main/java/com/gmail/nossr50/config/hocon/database/UserConfigSectionServer.java b/src/main/java/com/gmail/nossr50/config/hocon/database/UserConfigSectionServer.java index 3be9e3284..a45fb842d 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/database/UserConfigSectionServer.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/database/UserConfigSectionServer.java @@ -15,20 +15,20 @@ public class UserConfigSectionServer { * CONFIG NODES */ - @Setting(value = "Use-SSL", comment = "Enables SSL for MySQL/MariaDB connections." + - "\nIf your SQL server supports SSL, it is recommended to have it on but not necessary." + - "\nIf you run into any issues involving SSL, its best to just turn this off." + - "\nDefault value: "+USE_SSL_DEFAULT) + @Setting(value = "Use-SSL", comment = "Enables SSL for MySQL/MariaDB connections." + + "\nIf your SQL server supports SSL, it is recommended to have it on but not necessary." + + "\nIf you run into any issues involving SSL, its best to just turn this off." + + "\nDefault value: " + USE_SSL_DEFAULT) private boolean useSSL = USE_SSL_DEFAULT; @Setting(value = "Server-Port", comment = "Your MySQL/MariaDB server port" + "\nThe default port is typically 3306 for MySQL, but every server configuration is different!" + - "\nDefault value: "+SERVER_PORT_DEFAULT) + "\nDefault value: " + SERVER_PORT_DEFAULT) private int serverPort = SERVER_PORT_DEFAULT; @Setting(value = "Server-Address", comment = "The address for your MySQL/MariaDB server" + "If the MySQL server is hosted on the same machine, you can use the localhost alias" + - "\nDefault value: "+SERVER_ADDRESS_DEFAULT) + "\nDefault value: " + SERVER_ADDRESS_DEFAULT) private String serverAddress = SERVER_ADDRESS_DEFAULT; @Setting(value = "Max-Connections", comment = "This setting is the max simultaneous MySQL/MariaDB connections allowed at a time." + diff --git a/src/main/java/com/gmail/nossr50/config/hocon/donation/ConfigAuthorAdvertisements.java b/src/main/java/com/gmail/nossr50/config/hocon/donation/ConfigAuthorAdvertisements.java index 38366c2f4..c73d3424a 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/donation/ConfigAuthorAdvertisements.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/donation/ConfigAuthorAdvertisements.java @@ -14,13 +14,13 @@ public class ConfigAuthorAdvertisements { comment = "Shows donation info in various mcMMO commands." + "\nSuch as a paypal link for the author on the /mcmmo command" + "\nSupport through donations helps keep mcMMO development going." + - "\nDefault value: "+ SHOW_DONATION_DEFAULT) + "\nDefault value: " + SHOW_DONATION_DEFAULT) private boolean showDonationInfo = SHOW_DONATION_DEFAULT; @Setting(value = "Show-Patreon-Links", comment = "Shows patreon links for the mcMMO author in various mcMMO commands." + "\nSupport through Patreon helps keep mcMMO development going" + - "\nDefault value: "+SHOW_PATREON_DEFAULT) + "\nDefault value: " + SHOW_PATREON_DEFAULT) private boolean showPatreonInfo = SHOW_PATREON_DEFAULT; @Setting(value = "Show-Website-Links", comment = "Allows links to various affiliated websites for mcMMO." + @@ -31,7 +31,7 @@ public class ConfigAuthorAdvertisements { "\nThe mcMMO authors Patreon" + "\nThe Official mcMMO Spigot Listing" + "\nThe Official translation website for mcMMO" + - "\nDefault value: "+SHOW_WEBSITE_LINKS_DEFAULT) + "\nDefault value: " + SHOW_WEBSITE_LINKS_DEFAULT) private boolean showWebsiteLinks = SHOW_WEBSITE_LINKS_DEFAULT; public boolean isShowDonationInfo() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceAcrobatics.java b/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceAcrobatics.java index c973f1400..862f20841 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceAcrobatics.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceAcrobatics.java @@ -23,7 +23,7 @@ public class ConfigExperienceAcrobatics { @Setting(value = "Feather-Fall-XP-Multiplier", comment = "Feather Fall grants bonus XP to fall related XP gains." + "\nThis value is multiplied against your XP to give the bonus." + - "\nDefault value: "+FEATHER_FALL_MULTIPLIER_DEFAULT) + "\nDefault value: " + FEATHER_FALL_MULTIPLIER_DEFAULT) private Double featherFallMultiplier = FEATHER_FALL_MULTIPLIER_DEFAULT; public HashMap getAcrobaticsXPMap() { @@ -34,15 +34,15 @@ public class ConfigExperienceAcrobatics { return featherFallMultiplier; } - public int getDodgeXP(){ + public int getDodgeXP() { return acrobaticsXPMap.get("Dodge"); } - public int getRollXP(){ + public int getRollXP() { return acrobaticsXPMap.get("Roll"); } - public int getFallXP(){ + public int getFallXP() { return acrobaticsXPMap.get("Fall"); } diff --git a/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceAlchemy.java b/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceAlchemy.java index 823fe63a4..0b94ef93a 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceAlchemy.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceAlchemy.java @@ -11,11 +11,11 @@ public class ConfigExperienceAlchemy { private final static HashMap ALCHEMY_DEFAULT_XP_MAP; static { - ALCHEMY_DEFAULT_XP_MAP = new HashMap<>(); - ALCHEMY_DEFAULT_XP_MAP.put("Stage-One-Potion", 15); - ALCHEMY_DEFAULT_XP_MAP.put("Stage-Two-Potion", 30); - ALCHEMY_DEFAULT_XP_MAP.put("Stage-Three-Potion", 60); - ALCHEMY_DEFAULT_XP_MAP.put("Stage-Four-Potion", 120); + ALCHEMY_DEFAULT_XP_MAP = new HashMap<>(); + ALCHEMY_DEFAULT_XP_MAP.put("Stage-One-Potion", 15); + ALCHEMY_DEFAULT_XP_MAP.put("Stage-Two-Potion", 30); + ALCHEMY_DEFAULT_XP_MAP.put("Stage-Three-Potion", 60); + ALCHEMY_DEFAULT_XP_MAP.put("Stage-Four-Potion", 120); } @Setting(value = "Alchemy-Experience-Values", comment = "Experience values for alchemy.") @@ -26,23 +26,19 @@ public class ConfigExperienceAlchemy { return alchemyXPMap; } - public int getStageOnePotionXP() - { + public int getStageOnePotionXP() { return alchemyXPMap.get("Stage-One-Potion"); } - public int getStageTwoPotionXP() - { + public int getStageTwoPotionXP() { return alchemyXPMap.get("Stage-Two-Potion"); } - public int getStageThreePotionXP() - { + public int getStageThreePotionXP() { return alchemyXPMap.get("Stage-Three-Potion"); } - public int getStageFourPotionXP() - { + public int getStageFourPotionXP() { return alchemyXPMap.get("Stage-Four-Potion"); } @@ -52,10 +48,8 @@ public class ConfigExperienceAlchemy { return 0; }*/ - public int getPotionXPByStage(int potionStage) - { - switch(potionStage) - { + public int getPotionXPByStage(int potionStage) { + switch (potionStage) { case 1: return getStageOnePotionXP(); case 2: diff --git a/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceArchery.java b/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceArchery.java index d8bce6619..ad5c2a10d 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceArchery.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceArchery.java @@ -13,7 +13,7 @@ public class ConfigExperienceArchery { "\nThe maximum distance bonus is 50, so expect this multiplier to peak at being multiplied against 50." + "\nDistance is in blocks traveled." + "\nThis value is added on to normal XP gains from damage for Archery." + - "\nDefault value: "+DISTANCE_MULTIPLIER_DEFAULT) + "\nDefault value: " + DISTANCE_MULTIPLIER_DEFAULT) private double distanceMultiplier = DISTANCE_MULTIPLIER_DEFAULT; public double getDistanceMultiplier() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceCombat.java b/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceCombat.java index 7be4a9050..536c66cb4 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceCombat.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceCombat.java @@ -9,6 +9,7 @@ import java.util.HashMap; public class ConfigExperienceCombat { private static final HashMap COMBAT_EXPERIENCE_DEFAULT; + private static final boolean PVP_XP_ENABLED_DEFAULT = false; static { COMBAT_EXPERIENCE_DEFAULT = new HashMap<>(); @@ -73,14 +74,12 @@ public class ConfigExperienceCombat { COMBAT_EXPERIENCE_DEFAULT.put("phantom", 4.0D); } - private static final boolean PVP_XP_ENABLED_DEFAULT = false; - @Setting(value = "Combat-XP-Multipliers") private HashMap combatExperienceMap = COMBAT_EXPERIENCE_DEFAULT; @Setting(value = "PVP-XP", comment = "If true, players will gain XP from PVP interactions." + "\nBe careful turning this on as this can potentially allow for unwanted behaviour from players." + - "\nDefault value: "+PVP_XP_ENABLED_DEFAULT) + "\nDefault value: " + PVP_XP_ENABLED_DEFAULT) private boolean pvpXPEnabled = PVP_XP_ENABLED_DEFAULT; public boolean isPvpXPEnabled() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceFishing.java b/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceFishing.java index e7cd7d1c1..e88ae702a 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceFishing.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceFishing.java @@ -8,8 +8,8 @@ import java.util.HashMap; @ConfigSerializable public class ConfigExperienceFishing { - private final static HashMap FISHING_DEFAULT_XP_MAP; public static final int SHAKE_XP_DEFAULT = 50; + private final static HashMap FISHING_DEFAULT_XP_MAP; static { FISHING_DEFAULT_XP_MAP = new HashMap<>(); diff --git a/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceRepair.java b/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceRepair.java index 426547a90..30315d5cc 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceRepair.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/experience/ConfigExperienceRepair.java @@ -36,7 +36,7 @@ public class ConfigExperienceRepair { "\nThe Item XP multiplier defined in the Repair config (not this config)" + "\nThe Base Repair XP defined here (default 1000.0)" + "\nAnd finally, the XP multiplier of the item material category defined in this config." + - "\nDefault value: "+REPAIR_XP_BASE_DEFAULT) + "\nDefault value: " + REPAIR_XP_BASE_DEFAULT) private double repairXPBase = REPAIR_XP_BASE_DEFAULT; public HashMap getItemMaterialXPMultiplier() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/language/ConfigLanguage.java b/src/main/java/com/gmail/nossr50/config/hocon/language/ConfigLanguage.java index 2359d5cf5..791eb7c2c 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/language/ConfigLanguage.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/language/ConfigLanguage.java @@ -8,14 +8,14 @@ public class ConfigLanguage { public static final String TARGET_LANGUAGE_DEFAULT = "en_US"; public static final String AVAILABLE_LANGUAGE_LIST = "cs_CZ, cy, da, de, en_US, es, fi, fr, hu_HU, it, ja_JP, ko," + - "\n nl, pl, pt_BR, ru, sv, th_TH, zh_CN, zh_TW"; + "\n nl, pl, pt_BR, ru, sv, th_TH, zh_CN, zh_TW"; @Setting(value = "Language", comment = "Which language mcMMO will use." + "\nThe default language for mcMMO will be used for languages that do not have complete translations." + "\nIf you'd wish to contribute to available languages please submit a pull request on our github" + "\nhttps://github.com/mcMMO-Dev/mcMMO" + - "\nAvailable Languages: " + AVAILABLE_LANGUAGE_LIST + - "\n\nDefault value: "+TARGET_LANGUAGE_DEFAULT) + "\nAvailable Languages: " + AVAILABLE_LANGUAGE_LIST + + "\n\nDefault value: " + TARGET_LANGUAGE_DEFAULT) private String targetLanguage = TARGET_LANGUAGE_DEFAULT; public String getTargetLanguage() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/metrics/ConfigMetrics.java b/src/main/java/com/gmail/nossr50/config/hocon/metrics/ConfigMetrics.java index a985275ab..2ba414640 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/metrics/ConfigMetrics.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/metrics/ConfigMetrics.java @@ -11,7 +11,7 @@ public class ConfigMetrics { @Setting(value = "Allow-Anonymous-Statistic-Collection", comment = "Collects info about what version of mcMMO you are using and other information" + "\nAll information is completely anonymous, and that info is reported to bstats for data processing." + "\nThis setting should have no affect on your server whatsoever, so I'd like to discourage you from turning it off." + - "\nDefault value: "+ALLOW_STAT_TRACKING_DEFAULT) + "\nDefault value: " + ALLOW_STAT_TRACKING_DEFAULT) private boolean allowAnonymousUsageStatistics = ALLOW_STAT_TRACKING_DEFAULT; public boolean isAllowAnonymousUsageStatistics() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/mobs/ConfigSectionHealthBars.java b/src/main/java/com/gmail/nossr50/config/hocon/mobs/ConfigSectionHealthBars.java index e2882eda2..9a4fdb576 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/mobs/ConfigSectionHealthBars.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/mobs/ConfigSectionHealthBars.java @@ -13,16 +13,16 @@ public class ConfigSectionHealthBars { public static final String displayTypesList = "\nYou can use the following MobHealthBarType values: HEARTS, BAR"; @Setting(value = "Enable-Health-Bars", comment = "Turn this off to disable health bars appearing above mobs when damaged." + - "\nDefault value: "+MOB_HEALTH_BARS_DEFAULT) + "\nDefault value: " + MOB_HEALTH_BARS_DEFAULT) private boolean enableHealthBars = MOB_HEALTH_BARS_DEFAULT; @Setting(value = "Display-Bar-Type", comment = "The type of display to use for the mobs health bar." + displayTypesList + - "\nDefault value: "+HEARTS) + "\nDefault value: " + HEARTS) private MobHealthbarType displayBarType = MobHealthbarType.HEARTS; @Setting(value = "Display-Time-In-Seconds", comment = "How many seconds mob health bars should be displayed before being hidden." + - "\nDefault value: "+DISPLAY_TIME_SECONDS_DEFAULT) + "\nDefault value: " + DISPLAY_TIME_SECONDS_DEFAULT) private int displayTimeSeconds = DISPLAY_TIME_SECONDS_DEFAULT; public boolean isEnableHealthBars() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/motd/ConfigMOTD.java b/src/main/java/com/gmail/nossr50/config/hocon/motd/ConfigMOTD.java index 41827f83e..2b0741cd7 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/motd/ConfigMOTD.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/motd/ConfigMOTD.java @@ -11,7 +11,7 @@ public class ConfigMOTD { "\nHistorically this message is literally just telling players that the server runs mcMMO." + "\nSometimes the MOTD includes warnings about build stability if using a volatile dev build." + "\nIf you wish to edit the MOTD, that is done in the locale files inside the JAR." + - "\nDefault value: "+ENABLE_MOTD_DEFAULT) + "\nDefault value: " + ENABLE_MOTD_DEFAULT) private boolean enableMOTD = ENABLE_MOTD_DEFAULT; public boolean isEnableMOTD() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/notifications/ActionBarNotificationSetting.java b/src/main/java/com/gmail/nossr50/config/hocon/notifications/ActionBarNotificationSetting.java index 7f8fb7024..eb09c2949 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/notifications/ActionBarNotificationSetting.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/notifications/ActionBarNotificationSetting.java @@ -2,12 +2,10 @@ package com.gmail.nossr50.config.hocon.notifications; public class ActionBarNotificationSetting { - public ActionBarNotificationSetting(boolean enabled, boolean sendCopyOfMessageToChat) - { + public boolean enabled; + public boolean sendCopyOfMessageToChat; + public ActionBarNotificationSetting(boolean enabled, boolean sendCopyOfMessageToChat) { this.enabled = enabled; this.sendCopyOfMessageToChat = sendCopyOfMessageToChat; } - - public boolean enabled; - public boolean sendCopyOfMessageToChat; } \ No newline at end of file diff --git a/src/main/java/com/gmail/nossr50/config/hocon/notifications/ConfigNotificationGeneral.java b/src/main/java/com/gmail/nossr50/config/hocon/notifications/ConfigNotificationGeneral.java index 7b08b2806..888a90563 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/notifications/ConfigNotificationGeneral.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/notifications/ConfigNotificationGeneral.java @@ -8,7 +8,7 @@ public class ConfigNotificationGeneral { public static final boolean PLAYER_TIPS_DEFAULT = true; @Setting(value = "Player-Tips", comment = "Allows mcMMO to send players automated helpful tips." + - "\n Default value: "+PLAYER_TIPS_DEFAULT) + "\n Default value: " + PLAYER_TIPS_DEFAULT) public boolean playerTips = PLAYER_TIPS_DEFAULT; public boolean isPlayerTips() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/notifications/ConfigNotifications.java b/src/main/java/com/gmail/nossr50/config/hocon/notifications/ConfigNotifications.java index 35496c3d5..700449e2a 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/notifications/ConfigNotifications.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/notifications/ConfigNotifications.java @@ -7,7 +7,11 @@ import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; public class ConfigNotifications { public static final boolean SUPER_ABILITY_TOOL_NOTIFICATION_DEFAULT = true; - + @Setting(value = "Action-Bar-Notifications", comment = "Settings related to action bar messages." + + "\nThe action bar is the area above your health and armor.") + public ConfigActionBarNotifications actionBarNotifications = new ConfigActionBarNotifications(); + @Setting(value = "General", comment = "General settings for Notifications") + public ConfigNotificationGeneral configNotificationGeneral = new ConfigNotificationGeneral(); @Setting(value = "Super-Ability-Tool-Raising-Lowering-Notification", comment = "Notifies the player when they go into the tool readying state for super abilities.") private boolean superAbilityToolMessage = SUPER_ABILITY_TOOL_NOTIFICATION_DEFAULT; @@ -16,13 +20,6 @@ public class ConfigNotifications { return superAbilityToolMessage; } - @Setting(value = "Action-Bar-Notifications", comment = "Settings related to action bar messages." + - "\nThe action bar is the area above your health and armor.") - public ConfigActionBarNotifications actionBarNotifications = new ConfigActionBarNotifications(); - - @Setting(value = "General", comment = "General settings for Notifications") - public ConfigNotificationGeneral configNotificationGeneral = new ConfigNotificationGeneral(); - public ConfigActionBarNotifications getActionBarNotifications() { return actionBarNotifications; } diff --git a/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigParty.java b/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigParty.java index 002a9bb8d..94a7acfc9 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigParty.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigParty.java @@ -91,6 +91,8 @@ public class ConfigParty { return partyCombat.isPartyFriendlyFire(); } - public boolean isPartySystemEnabled() { return partyGeneral.isEnablePartySystem(); } + public boolean isPartySystemEnabled() { + return partyGeneral.isEnablePartySystem(); + } } diff --git a/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyChat.java b/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyChat.java index 573da9986..68d9bda73 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyChat.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyChat.java @@ -14,24 +14,24 @@ public class ConfigSectionPartyChat { @Setting(value = "Prefix-Party-Members", comment = "This is the formatting used for the prefix at the beginning of a party chat message." + - "Default value: "+PARTY_CHAT_PREFIX_FORMAT_DEFAULT) + "Default value: " + PARTY_CHAT_PREFIX_FORMAT_DEFAULT) private String partyChatPrefixFormat = PARTY_CHAT_PREFIX_FORMAT_DEFAULT; @Setting(value = "Prefix-Ally", comment = "This is the formatting used for the prefix at the beginning of a party chat message from an ally." + - "\nDefault value: "+PARTY_CHAT_PREFIX_ALLY_DEFAULT) + "\nDefault value: " + PARTY_CHAT_PREFIX_ALLY_DEFAULT) private String partyChatPrefixAlly = PARTY_CHAT_PREFIX_ALLY_DEFAULT; @Setting(value = "Party-Leaders-Name-Uses-Gold-Coloring", comment = "Changes the party leader to use a gold coloring for their name." + - "\nDefault value: "+PARTY_LEADER_GOLD_DEFAULT) + "\nDefault value: " + PARTY_LEADER_GOLD_DEFAULT) private boolean isPartyLeaderColoredGold = PARTY_LEADER_GOLD_DEFAULT; @Setting(value = "Use-Display-Names", comment = "Party chat will use formatted display names instead of the players raw nickname." + "\nDisplay names are often colored, modified, or styled differently from a players regular name." + "\nDisplay names are typically modified by chat plugins and the like." + "\nIf you'd rather player names were just their current Minecraft username, turn this off." + - "\nDefault value: "+PARTY_USE_DISPLAY_NAMES_DEFAULT) + "\nDefault value: " + PARTY_USE_DISPLAY_NAMES_DEFAULT) private boolean partyDisplayNamesEnabled = PARTY_USE_DISPLAY_NAMES_DEFAULT; public String getPartyChatPrefixFormat() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyCleanup.java b/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyCleanup.java index e6abf532c..4c0de4e83 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyCleanup.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyCleanup.java @@ -6,17 +6,16 @@ import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; @ConfigSerializable public class ConfigSectionPartyCleanup { - private static final int AUTO_KICK_HOURS_DEFAULT = 12; public static final int AUTO_KICK_CUTOFF_DAYS_DEFAULT = 7; - + private static final int AUTO_KICK_HOURS_DEFAULT = 12; @Setting(value = "Hours-Between-Cleanup-Operations", comment = "How many hours between checking parties for members that meet auto kick requirements." + - "\nDefault value: "+AUTO_KICK_HOURS_DEFAULT) + "\nDefault value: " + AUTO_KICK_HOURS_DEFAULT) private int partyAutoKickHoursInterval = AUTO_KICK_HOURS_DEFAULT; @Setting(value = "Offline-Day-Limit", comment = "How many days must pass before a player qualifies to be kicked from a party automatically." + - "\nDefault value: "+AUTO_KICK_CUTOFF_DAYS_DEFAULT) + "\nDefault value: " + AUTO_KICK_CUTOFF_DAYS_DEFAULT) private int partyAutoKickDaysCutoff = AUTO_KICK_CUTOFF_DAYS_DEFAULT; public int getPartyAutoKickHoursInterval() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyCombat.java b/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyCombat.java index 39644359c..68e67e7b5 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyCombat.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyCombat.java @@ -10,7 +10,7 @@ public class ConfigSectionPartyCombat { @Setting(value = "Friendly-Fire", comment = "When friendly fire is enabled, players in the same party can injure each other." + "\nThis also allows Party alliances to hurt each other." + - "\nDefault value: "+PARTY_FRIENDLY_FIRE_DEFAULT) + "\nDefault value: " + PARTY_FRIENDLY_FIRE_DEFAULT) private boolean partyFriendlyFire = PARTY_FRIENDLY_FIRE_DEFAULT; public boolean isPartyFriendlyFire() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyGeneral.java b/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyGeneral.java index 0433201c6..ffb0a974d 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyGeneral.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyGeneral.java @@ -12,7 +12,7 @@ public class ConfigSectionPartyGeneral { private ConfigSectionPartyLimit configSectionPartyLimit = new ConfigSectionPartyLimit(); @Setting(value = "Enable-Party-System", comment = "Turn this off to completely disable the mcMMO party system." + - "\nDefault value: "+PARTY_SYSTEM_DEFAULT) + "\nDefault value: " + PARTY_SYSTEM_DEFAULT) private boolean enablePartySystem = PARTY_SYSTEM_DEFAULT; public int getPartySizeLimit() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyItemShareSettings.java b/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyItemShareSettings.java index e4792d508..4d17ca68b 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyItemShareSettings.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyItemShareSettings.java @@ -13,6 +13,6 @@ public class ConfigSectionPartyItemShareSettings { "\nEQUAL: Party members have weighted dice rolls based on the quality of the loot they have recently received." + "\nRANDOM: Party members do a fair dice roll for every item dropped." + "\nNONE: Do not use item sharing" + - "\nDefault Value: "+"NONE") + "\nDefault Value: " + "NONE") private ShareMode shareMode = SHARE_MODE_DEFAULT; } \ No newline at end of file diff --git a/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyLevel.java b/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyLevel.java index b096547fd..bc28fa41d 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyLevel.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyLevel.java @@ -10,20 +10,14 @@ import java.util.Map; @ConfigSerializable public class ConfigSectionPartyLevel { - private static final HashMap PARTY_FEATURE_MAP_DEFAULT; public static final boolean INFORM_PARTY_ON_LEVELUP_DEFAULT = true; - public static final boolean PARTY_LEVELING_NEEDS_NERBY_MEMBERS_DEFAULT = true; - public static final int TELEPORT_DEFAULT = 2; - public static final int ALLIANCE_DEFAULT = 5; - public static final int ITEM_SHARE_DEFAULT = 8; - public static final int XP_SHARE_DEFAULT = 10; - public static final int PARTY_CHAT_DEFAULT = 1; + private static final HashMap PARTY_FEATURE_MAP_DEFAULT; static { PARTY_FEATURE_MAP_DEFAULT = new HashMap<>(); @@ -47,35 +41,34 @@ public class ConfigSectionPartyLevel { */ @Setting(value = "Party-XP-Formula-Parameters", - comment = "The Party XP Formula is borrowed from the Player XP formula to help determine the amount of XP needed to level the party." + - "\nThe Party XP Formula used to be based on your settings for player XP formula but I have separated it from those settings." + - "\nThe Party XP Curve Multiplier takes the final result of calculating one level of XP and multiplies it by this value to get the amount of XP needed to level the party." + - "\nParty Leveling used to have a level cap, I have removed this level cap as part of a feature request. It seems fun to level up parties indefinitely." + - "\nParty Leveling is now using exponential level scaling by default.") + comment = "The Party XP Formula is borrowed from the Player XP formula to help determine the amount of XP needed to level the party." + + "\nThe Party XP Formula used to be based on your settings for player XP formula but I have separated it from those settings." + + "\nThe Party XP Curve Multiplier takes the final result of calculating one level of XP and multiplies it by this value to get the amount of XP needed to level the party." + + "\nParty Leveling used to have a level cap, I have removed this level cap as part of a feature request. It seems fun to level up parties indefinitely." + + "\nParty Leveling is now using exponential level scaling by default.") private ConfigSectionPartyXPFormula partyXPFormula = new ConfigSectionPartyXPFormula(); @Setting(value = "Party-Leveling-Requires-Nearby-Party-Members", comment = "If leveling your Party requires being near another party member." + - "\nDefault value: "+PARTY_LEVELING_NEEDS_NERBY_MEMBERS_DEFAULT) + "\nDefault value: " + PARTY_LEVELING_NEEDS_NERBY_MEMBERS_DEFAULT) private boolean partyLevelingNeedsNearbyMembers = PARTY_LEVELING_NEEDS_NERBY_MEMBERS_DEFAULT; @Setting(value = "Send-Levelup-Notifications-To-Party", comment = "Sends level up notifications to nearby party members." + - "\nDefault value: "+INFORM_PARTY_ON_LEVELUP_DEFAULT) + "\nDefault value: " + INFORM_PARTY_ON_LEVELUP_DEFAULT) private boolean informPartyMembersOnLevelup = INFORM_PARTY_ON_LEVELUP_DEFAULT; @Setting(value = "Party-Feature-Unlock-Level-Requirements", comment = "What level your Party needs to be to unlock certain features." + "\nKeep in mind, parties no longer have a level cap." + "\n\nDefault values: " + - "\nCHAT: "+PARTY_CHAT_DEFAULT + - "\nTELEPORT: "+TELEPORT_DEFAULT + - "\nALIANCE: "+ALLIANCE_DEFAULT + - "\nITEM SHARE: "+ITEM_SHARE_DEFAULT + - "\nXP SHARE: "+XP_SHARE_DEFAULT) + "\nCHAT: " + PARTY_CHAT_DEFAULT + + "\nTELEPORT: " + TELEPORT_DEFAULT + + "\nALIANCE: " + ALLIANCE_DEFAULT + + "\nITEM SHARE: " + ITEM_SHARE_DEFAULT + + "\nXP SHARE: " + XP_SHARE_DEFAULT) private Map partyFeatureUnlockMap = PARTY_FEATURE_MAP_DEFAULT; - public int getPartyXpCurveMultiplier() { return partyXPFormula.getPartyXpCurveMultiplier(); } @@ -88,5 +81,7 @@ public class ConfigSectionPartyLevel { return informPartyMembersOnLevelup; } - public Map getPartyFeatureUnlockMap() { return partyFeatureUnlockMap; } + public Map getPartyFeatureUnlockMap() { + return partyFeatureUnlockMap; + } } \ No newline at end of file diff --git a/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyLimit.java b/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyLimit.java index d997f5ab8..2b8b43111 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyLimit.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyLimit.java @@ -10,17 +10,17 @@ public class ConfigSectionPartyLimit { public static final int PARTY_SIZE_LIMIT_DEFAULT = 5; @Setting(value = "Max-Party-Size", - comment = "The maximum size for parties, parties bigger than this size will be dismantled." + + comment = "The maximum size for parties, parties bigger than this size will be dismantled." + "\nThis setting is only used if \"Enforce-Size-Limit\" is true." + "\nPlayers can bypass this limit with the following permission node \"mcmmo.bypass.partylimit\"" + - "\nDefault value: "+PARTY_SIZE_LIMIT_DEFAULT) + "\nDefault value: " + PARTY_SIZE_LIMIT_DEFAULT) public int partyMaxSize = PARTY_SIZE_LIMIT_DEFAULT; @Setting(value = "Enforce-Size-Limit", - comment = "Limits parties to a maximum size defined by \"Max-Party-Size\"" + + comment = "Limits parties to a maximum size defined by \"Max-Party-Size\"" + "\nParties over the current limit will be dismantled" + "\nPlayers can bypass this limit with the following permission node \"mcmmo.bypass.partylimit\"" + - "\nDefault value: "+USE_LIMIT_DEFAULT) + "\nDefault value: " + USE_LIMIT_DEFAULT) public boolean useCap = USE_LIMIT_DEFAULT; } diff --git a/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyTeleportCommand.java b/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyTeleportCommand.java index 50f2536d3..0d52f4192 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyTeleportCommand.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyTeleportCommand.java @@ -14,24 +14,24 @@ public class ConfigSectionPartyTeleportCommand { public static final boolean PTP_WORLD_BASED_PERMISSIONS_DEFAULT = false; @Setting(value = "PTP-Cooldown", comment = "How many seconds a player must wait between usages of PTP." + - "\nDefault value: "+PTP_COOLDOWN_DEFAULT) + "\nDefault value: " + PTP_COOLDOWN_DEFAULT) private int ptpCooldown = PTP_COOLDOWN_DEFAULT; @Setting(value = "PTP-Warmup", comment = "How many seconds a player must stand still for a PTP to be successful." + - "\nDefault value: "+PTP_WARMUP_DEFAULT) + "\nDefault value: " + PTP_WARMUP_DEFAULT) private int ptpWarmup = PTP_WARMUP_DEFAULT; @Setting(value = "PTP-Hurt-Cooldown", comment = "How many seconds a player must wait from last taking damage in order to use PTP." + - "\nDefault value: "+PTP_RECENTLY_HURT_COOLDOWN_DEFAULT) + "\nDefault value: " + PTP_RECENTLY_HURT_COOLDOWN_DEFAULT) private int ptpRecentlyHurtCooldown = PTP_RECENTLY_HURT_COOLDOWN_DEFAULT; @Setting(value = "PTP-Requires-Accept", comment = "If a player tries to use PTP to another party member," + " that party member must then accept his request or the PTP will not execute." + - "\nDefault value: "+PTP_ACCEPT_REQUIRED_DEFAULT) + "\nDefault value: " + PTP_ACCEPT_REQUIRED_DEFAULT) private boolean ptpAcceptRequired = PTP_ACCEPT_REQUIRED_DEFAULT; @Setting(value = "PTP-Request-Timeout", comment = "How many seconds before a PTP request will become invalid." + - "\nDefault value: "+PTP_REQUEST_TIMEOUT) + "\nDefault value: " + PTP_REQUEST_TIMEOUT) private int ptpRequestTimeout = PTP_REQUEST_TIMEOUT; @Setting(value = "PTP-Require-World-Based-Permissions", comment = "If true, players need to use a special permission node in order to use PTP on that world or to that world." + diff --git a/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyXPFormula.java b/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyXPFormula.java index 4662f25c8..0ec4b5aa0 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyXPFormula.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/party/ConfigSectionPartyXPFormula.java @@ -10,7 +10,7 @@ public class ConfigSectionPartyXPFormula { @Setting(value = "Party-XP-Formula-Multiplier", comment = "Crank this up to make it harder to level parties" + - "\nDefault value: "+PARTY_XP_CURVE_MULTIPLIER_DEFAULT) + "\nDefault value: " + PARTY_XP_CURVE_MULTIPLIER_DEFAULT) private int partyXpCurveMultiplier = PARTY_XP_CURVE_MULTIPLIER_DEFAULT; public int getPartyXpCurveMultiplier() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigExperienceFormula.java b/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigExperienceFormula.java index 43cbcc83a..082862567 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigExperienceFormula.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigExperienceFormula.java @@ -31,10 +31,8 @@ public class ConfigExperienceFormula { return configExperienceFormulaExponential; } - public double getMultiplier(FormulaType formulaType) - { - switch(formulaType) - { + public double getMultiplier(FormulaType formulaType) { + switch (formulaType) { case LINEAR: return getLinearMultiplier(); case EXPONENTIAL: @@ -44,10 +42,8 @@ public class ConfigExperienceFormula { } } - public int getBase(FormulaType formulaType) - { - switch(formulaType) - { + public int getBase(FormulaType formulaType) { + switch (formulaType) { case LINEAR: return getLinearBaseModifier(); case EXPONENTIAL: diff --git a/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigExperienceFormulaExponential.java b/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigExperienceFormulaExponential.java index 97ff833a9..fa96823c3 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigExperienceFormulaExponential.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigExperienceFormulaExponential.java @@ -10,13 +10,13 @@ public class ConfigExperienceFormulaExponential { private static final double MULTIPLIER_DEFAULT = 0.1; private static final double EXPONENT_DEFAULT = 1.80; - @Setting(value = "Base-Amount", comment = "Default value: "+BASE_DEFAULT) + @Setting(value = "Base-Amount", comment = "Default value: " + BASE_DEFAULT) private int baseModifier = BASE_DEFAULT; - @Setting(value = "Multiplier", comment = "Default value: "+MULTIPLIER_DEFAULT) + @Setting(value = "Multiplier", comment = "Default value: " + MULTIPLIER_DEFAULT) private double multiplier = MULTIPLIER_DEFAULT; - @Setting(value = "Exponent", comment = "Default value: "+EXPONENT_DEFAULT) + @Setting(value = "Exponent", comment = "Default value: " + EXPONENT_DEFAULT) private double exponent = EXPONENT_DEFAULT; public int getExponentialBaseModifier() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigExperienceFormulaLinear.java b/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigExperienceFormulaLinear.java index 1d88c7fbd..1400bfdae 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigExperienceFormulaLinear.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigExperienceFormulaLinear.java @@ -9,10 +9,10 @@ public class ConfigExperienceFormulaLinear { private static final int BASE_DEFAULT = 1020; private static final double MULTIPLIER_DEFAULT = 20.0D; - @Setting(value = "Base-Amount", comment = "Default value: "+BASE_DEFAULT) + @Setting(value = "Base-Amount", comment = "Default value: " + BASE_DEFAULT) private int baseModifier = BASE_DEFAULT; - @Setting(value = "Multiplier", comment = "Default value: "+MULTIPLIER_DEFAULT) + @Setting(value = "Multiplier", comment = "Default value: " + MULTIPLIER_DEFAULT) private double multiplier = MULTIPLIER_DEFAULT; public int getLinearBaseModifier() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigLeveling.java b/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigLeveling.java index af18686fa..dffd623f4 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigLeveling.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigLeveling.java @@ -95,10 +95,8 @@ public class ConfigLeveling { * HELPER METHODS */ - public int getLevelCap(PrimarySkillType primarySkillType) - { - switch(primarySkillType) - { + public int getLevelCap(PrimarySkillType primarySkillType) { + switch (primarySkillType) { case ACROBATICS: return configSectionLevelCaps.getConfigSectionSkills().getAcrobatics().getLevelCap(); case ALCHEMY: @@ -134,10 +132,8 @@ public class ConfigLeveling { } } - public boolean isLevelCapEnabled(PrimarySkillType primarySkillType) - { - switch(primarySkillType) - { + public boolean isLevelCapEnabled(PrimarySkillType primarySkillType) { + switch (primarySkillType) { case ACROBATICS: return configSectionLevelCaps.getConfigSectionSkills().getAcrobatics().isLevelCapEnabled(); case ALCHEMY: diff --git a/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigSectionLevelCaps.java b/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigSectionLevelCaps.java index 93e73aa50..7f78c7143 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigSectionLevelCaps.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigSectionLevelCaps.java @@ -14,7 +14,7 @@ public class ConfigSectionLevelCaps { @Setting(value = "Reduce-Player-Skills-Above-Cap", comment = "Players with skills above the cap will have those skills reduced to the cap" + - "\nDefault value: "+TRUNCATE_SKILLS_ABOVE_CAP_DEFAULT) + "\nDefault value: " + TRUNCATE_SKILLS_ABOVE_CAP_DEFAULT) private boolean truncateSkillsAboveCap = TRUNCATE_SKILLS_ABOVE_CAP_DEFAULT; @Setting(value = "Power-Level", diff --git a/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigSectionLevelingGeneral.java b/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigSectionLevelingGeneral.java index e951f6878..52d0d5db7 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigSectionLevelingGeneral.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigSectionLevelingGeneral.java @@ -30,7 +30,7 @@ public class ConfigSectionLevelingGeneral { @Setting(value = "Player-Starting-Level", comment = "\nPlayers will start at this level in all skills if they aren't already saved in the database." + "\nHistorically this number has been 0, but this was changed in 2.1.X to 1 as I felt it was better to start from 1 than 0." + - "\nDefault value: "+STARTING_LEVEL_DEFAULT) + "\nDefault value: " + STARTING_LEVEL_DEFAULT) private int startingLevel = STARTING_LEVEL_DEFAULT; /* diff --git a/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigSectionSkillLevelCap.java b/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigSectionSkillLevelCap.java index 91229a09b..b0f8d635c 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigSectionSkillLevelCap.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/playerleveling/ConfigSectionSkillLevelCap.java @@ -19,7 +19,7 @@ public class ConfigSectionSkillLevelCap { @Setting(value = "Level-Cap", comment = "Players will be unable to level past this value" + - "\nThe cap is the same for both Retro and Standard, " + + "\nThe cap is the same for both Retro and Standard, " + "so a cap of 50 will be the same value in either mode.") private int levelCap = LEVEL_CAP_DEFAULT; diff --git a/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigScoreboard.java b/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigScoreboard.java index 4c1c6a32a..539a3fa86 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigScoreboard.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigScoreboard.java @@ -57,10 +57,8 @@ public class ConfigScoreboard { return configSectionGeneral.isUseAbilityNameInsteadOfGeneric(); } - public boolean isScoreboardEnabled(ScoreboardManager.SidebarType sidebarType) - { - switch(sidebarType) - { + public boolean isScoreboardEnabled(ScoreboardManager.SidebarType sidebarType) { + switch (sidebarType) { case TOP_BOARD: return getConfigSectionScoreboardTypes().getConfigSectionTopBoard().isUseThisBoard(); case RANK_BOARD: @@ -76,10 +74,8 @@ public class ConfigScoreboard { } } - public boolean isScoreboardPrinting(ScoreboardManager.SidebarType sidebarType) - { - switch(sidebarType) - { + public boolean isScoreboardPrinting(ScoreboardManager.SidebarType sidebarType) { + switch (sidebarType) { case TOP_BOARD: return getConfigSectionScoreboardTypes().getConfigSectionTopBoard().isPrintToChat(); case RANK_BOARD: @@ -94,10 +90,8 @@ public class ConfigScoreboard { } } - public int getScoreboardDisplayTime(ScoreboardManager.SidebarType sidebarType) - { - switch(sidebarType) - { + public int getScoreboardDisplayTime(ScoreboardManager.SidebarType sidebarType) { + switch (sidebarType) { case TOP_BOARD: return getConfigSectionScoreboardTypes().getConfigSectionTopBoard().getDisplayTimeInSeconds(); case RANK_BOARD: diff --git a/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionCooldownBoard.java b/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionCooldownBoard.java index 1ab96c3a9..4d9377051 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionCooldownBoard.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionCooldownBoard.java @@ -19,20 +19,20 @@ public class ConfigSectionCooldownBoard { comment = "Should the commands normal chat output be shown in chat?" + "\nIf you feel that the scoreboard does a good enough job at conveying the information, you can set this to false." + "\nIf you'd like to show the chat anyways, turn this to true, the scoreboard will still be shown if its enabled." + - "\nDefault value: "+PRINT_TO_CHAT_DEFAULT) + "\nDefault value: " + PRINT_TO_CHAT_DEFAULT) private boolean printToChat = PRINT_TO_CHAT_DEFAULT; @Setting(value = "Show-Scoreboard", comment = "Whether or not you wish to enable the display of this scoreboard." + "\nScoreboards are shown when the associated command is executed from the player." + "\nThis setting will only work if \"Use_Scoreboards\" is set to true, which is found elsewhere in this configuration file." + - "\nDefault value: "+USE_THIS_SCOREBOARD_DEFAULT) + "\nDefault value: " + USE_THIS_SCOREBOARD_DEFAULT) private boolean useThisBoard = USE_THIS_SCOREBOARD_DEFAULT; @Setting(value = "Display-Time-In-Seconds", comment = "How long to keep the scoreboard on a players screen after it is first shown." + "\nThis setting is not related to the command that keeps scoreboards on screen." + - "\nDefault value: "+DISPLAY_TIME_SECONDS_DEFAULT) + "\nDefault value: " + DISPLAY_TIME_SECONDS_DEFAULT) private int displayTimeInSeconds = DISPLAY_TIME_SECONDS_DEFAULT; /* diff --git a/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionGeneral.java b/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionGeneral.java index dc589b00a..69211f052 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionGeneral.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionGeneral.java @@ -24,7 +24,7 @@ public class ConfigSectionGeneral { "\nMost of their functionality has been replaced by the new XP bars (Boss Bars)" + "\nIf you still wish to use scoreboards, you still can, just turn this setting on." + "\nScoreboards can be used alongside XP bars, so don't worry about that!" + - "\nDefault value: "+ USE_SCOREBOARDS_DEFAULT) + "\nDefault value: " + USE_SCOREBOARDS_DEFAULT) private boolean useScoreboards = USE_SCOREBOARDS_DEFAULT; @Setting(value = "Display-Power-Levels-Below-Player-Names", @@ -34,23 +34,23 @@ public class ConfigSectionGeneral { " through the use of scoreboards." + "\nThis is off by default because a lot of Plugins for Minecraft make use of editing" + " a players \"nameplate\" and that can cause compatibility issues" + - "\nDefault value: "+ POWER_LEVEL_DISPLAY_DEFAULT) + "\nDefault value: " + POWER_LEVEL_DISPLAY_DEFAULT) private boolean powerLevelTags = POWER_LEVEL_DISPLAY_DEFAULT; @Setting(value = "Show-Stats-Scoreboard-On-Player-Login", comment = "Shows the player the /mcstats scoreboard" + " display after they login." + - "\nDefault value: "+ SHOW_PLAYER_STATS_SCOREBOARD_AFTER_LOGIN_DEFAULT) + "\nDefault value: " + SHOW_PLAYER_STATS_SCOREBOARD_AFTER_LOGIN_DEFAULT) private boolean showStatsAfterLogin = SHOW_PLAYER_STATS_SCOREBOARD_AFTER_LOGIN_DEFAULT; @Setting(value = "Show-Scoreboard-Tips-Only-This-Many-Times", comment = "This determines how many times players are" + " given tips about how to use the scoreboard system before they are never tipped again." + "\nPlayers are given tips once per login session." + - "\nDefault value: "+ SHOW_TIPS_LIMIT_DEFAULT) + "\nDefault value: " + SHOW_TIPS_LIMIT_DEFAULT) private int tipsAmount = SHOW_TIPS_LIMIT_DEFAULT; - @Setting(value ="Use-Rainbow-Styling-For-Skill-Names", comment = "If true, skills names will use rainbow style" + + @Setting(value = "Use-Rainbow-Styling-For-Skill-Names", comment = "If true, skills names will use rainbow style" + " colorings instead of having the same color" + - "\nDefault value: "+ USE_RAINBOW_SKILL_COLORING_DEFAULT) + "\nDefault value: " + USE_RAINBOW_SKILL_COLORING_DEFAULT) private boolean useRainbows = USE_RAINBOW_SKILL_COLORING_DEFAULT; @Setting(value = "Use-Super-Ability-Name-Instead-Of-Generic-Name", @@ -58,7 +58,7 @@ public class ConfigSectionGeneral { "instead of using a generic word from the locale, which by default in the locale is defined as " + "\"Ability\". The locale key for this entry is - Scoreboard.Misc.Ability " + "\nExample: If true Tree Feller will be shown instead of Super Ability with default en_us locale entries" + - "\nDefault value: "+ USE_SUPER_ABILITY_NAME_INSTEAD_OF_GENERIC) + "\nDefault value: " + USE_SUPER_ABILITY_NAME_INSTEAD_OF_GENERIC) private boolean useAbilityNameInsteadOfGeneric = USE_SUPER_ABILITY_NAME_INSTEAD_OF_GENERIC; public boolean isUseScoreboards() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionInspectBoard.java b/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionInspectBoard.java index dec3ff81d..62c4b821b 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionInspectBoard.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionInspectBoard.java @@ -19,20 +19,20 @@ public class ConfigSectionInspectBoard { comment = "Should the commands normal chat output be shown in chat?" + "\nIf you feel that the scoreboard does a good enough job at conveying the information, you can set this to false." + "\nIf you'd like to show the chat anyways, turn this to true, the scoreboard will still be shown if its enabled." + - "\nDefault value: "+PRINT_TO_CHAT_DEFAULT) + "\nDefault value: " + PRINT_TO_CHAT_DEFAULT) private boolean printToChat = PRINT_TO_CHAT_DEFAULT; @Setting(value = "Show-Scoreboard", comment = "Whether or not you wish to enable the display of this scoreboard." + "\nScoreboards are shown when the associated command is executed from the player." + "\nThis setting will only work if \"Use_Scoreboards\" is set to true, which is found elsewhere in this configuration file." + - "\nDefault value: "+USE_THIS_SCOREBOARD_DEFAULT) + "\nDefault value: " + USE_THIS_SCOREBOARD_DEFAULT) private boolean useThisBoard = USE_THIS_SCOREBOARD_DEFAULT; @Setting(value = "Display-Time-In-Seconds", comment = "How long to keep the scoreboard on a players screen after it is first shown." + "\nThis setting is not related to the command that keeps scoreboards on screen." + - "\nDefault value: "+DISPLAY_TIME_SECONDS_DEFAULT) + "\nDefault value: " + DISPLAY_TIME_SECONDS_DEFAULT) private int displayTimeInSeconds = DISPLAY_TIME_SECONDS_DEFAULT; /* diff --git a/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionRankBoard.java b/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionRankBoard.java index ec0372cc2..ff93c7701 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionRankBoard.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionRankBoard.java @@ -17,22 +17,22 @@ public class ConfigSectionRankBoard { @Setting(value = "Show-Command-Output-In-Chat", comment = "Should the commands normal chat output be shown in chat?" + - "\nIf you feel that the scoreboard does a good enough job at conveying the information, you can set this to false." + - "\nIf you'd like to show the chat anyways, turn this to true, the scoreboard will still be shown if its enabled." + - "\nDefault value: "+PRINT_TO_CHAT_DEFAULT) + "\nIf you feel that the scoreboard does a good enough job at conveying the information, you can set this to false." + + "\nIf you'd like to show the chat anyways, turn this to true, the scoreboard will still be shown if its enabled." + + "\nDefault value: " + PRINT_TO_CHAT_DEFAULT) private boolean printToChat = PRINT_TO_CHAT_DEFAULT; @Setting(value = "Show-Scoreboard", comment = "Whether or not you wish to enable the display of this scoreboard." + - "\nScoreboards are shown when the associated command is executed from the player." + - "\nThis setting will only work if \"Use_Scoreboards\" is set to true, which is found elsewhere in this configuration file." + - "\nDefault value: "+USE_THIS_SCOREBOARD_DEFAULT) + "\nScoreboards are shown when the associated command is executed from the player." + + "\nThis setting will only work if \"Use_Scoreboards\" is set to true, which is found elsewhere in this configuration file." + + "\nDefault value: " + USE_THIS_SCOREBOARD_DEFAULT) private boolean useThisBoard = USE_THIS_SCOREBOARD_DEFAULT; @Setting(value = "Display-Time-In-Seconds", comment = "How long to keep the scoreboard on a players screen after it is first shown." + "\nThis setting is not related to the command that keeps scoreboards on screen." + - "\nDefault value: "+DISPLAY_TIME_SECONDS_DEFAULT) + "\nDefault value: " + DISPLAY_TIME_SECONDS_DEFAULT) private int displayTimeInSeconds = DISPLAY_TIME_SECONDS_DEFAULT; /* diff --git a/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionSkillBoard.java b/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionSkillBoard.java index fd568fe85..a6f183fa4 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionSkillBoard.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionSkillBoard.java @@ -21,23 +21,23 @@ public class ConfigSectionSkillBoard { "\nScoreboards are shown when the associated command is executed from the player." + "\nThis setting will only work if \"Use_Scoreboards\" is set to true," + " which is found elsewhere in this configuration file." + - "\nDefault value: "+USE_THIS_SCOREBOARD_DEFAULT) + "\nDefault value: " + USE_THIS_SCOREBOARD_DEFAULT) private boolean useThisBoard = USE_THIS_SCOREBOARD_DEFAULT; @Setting(value = "Display-Time-In-Seconds", comment = "How long to keep the scoreboard on a players screen after it is first shown." + "\nThis setting is not related to the command that keeps scoreboards on screen." + - "\nDefault value: "+DISPLAY_TIME_SECONDS_DEFAULT) + "\nDefault value: " + DISPLAY_TIME_SECONDS_DEFAULT) private int displayTimeInSeconds = DISPLAY_TIME_SECONDS_DEFAULT; @Setting(value = "Show-Board-On-Player-Level-Up", comment = "Show a skill scoreboard when the player levels up in that skill" + - "\nDefault value: "+SHOW_BOARD_ON_PLAYER_LEVELUP) + "\nDefault value: " + SHOW_BOARD_ON_PLAYER_LEVELUP) private boolean showBoardOnPlayerLevelUp = SHOW_BOARD_ON_PLAYER_LEVELUP; @Setting(value = "Level-Up-Display-Time", comment = "How long to show a skill scoreboard when a player levels up?" + "\nIs only shown if Show_Board_On_Player_Level_Up is true" + - "\nDefault value: "+SHOW_BOARD_ON_LEVELUP_TIME) + "\nDefault value: " + SHOW_BOARD_ON_LEVELUP_TIME) private int showBoardOnPlayerLevelUpTime = SHOW_BOARD_ON_LEVELUP_TIME; /* diff --git a/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionStatsBoard.java b/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionStatsBoard.java index 5bb1783cf..7cc9194fb 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionStatsBoard.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionStatsBoard.java @@ -19,20 +19,20 @@ public class ConfigSectionStatsBoard { comment = "Should the commands normal chat output be shown in chat?" + "\nIf you feel that the scoreboard does a good enough job at conveying the information, you can set this to false." + "\nIf you'd like to show the chat anyways, turn this to true, the scoreboard will still be shown if its enabled." + - "\nDefault value: "+PRINT_TO_CHAT_DEFAULT) + "\nDefault value: " + PRINT_TO_CHAT_DEFAULT) private boolean printToChat = PRINT_TO_CHAT_DEFAULT; @Setting(value = "Show-Scoreboard", comment = "Whether or not you wish to enable the display of this scoreboard." + "\nScoreboards are shown when the associated command is executed from the player." + "\nThis setting will only work if \"Use_Scoreboards\" is set to true, which is found elsewhere in this configuration file." + - "\nDefault value: "+USE_THIS_SCOREBOARD_DEFAULT) + "\nDefault value: " + USE_THIS_SCOREBOARD_DEFAULT) private boolean useThisBoard = USE_THIS_SCOREBOARD_DEFAULT; @Setting(value = "Display-Time-In-Seconds", comment = "How long to keep the scoreboard on a players screen after it is first shown." + "\nThis setting is not related to the command that keeps scoreboards on screen." + - "\nDefault value: "+DISPLAY_TIME_SECONDS_DEFAULT) + "\nDefault value: " + DISPLAY_TIME_SECONDS_DEFAULT) private int displayTimeInSeconds = DISPLAY_TIME_SECONDS_DEFAULT; /* diff --git a/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionTopBoard.java b/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionTopBoard.java index 6ae1a39fd..6b3567d61 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionTopBoard.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/scoreboard/ConfigSectionTopBoard.java @@ -19,20 +19,20 @@ public class ConfigSectionTopBoard { comment = "Should the commands normal chat output be shown in chat?" + "\nIf you feel that the scoreboard does a good enough job at conveying the information, you can set this to false." + "\nIf you'd like to show the chat anyways, turn this to true, the scoreboard will still be shown if its enabled." + - "\nDefault value: "+PRINT_TO_CHAT_DEFAULT) + "\nDefault value: " + PRINT_TO_CHAT_DEFAULT) private boolean printToChat = PRINT_TO_CHAT_DEFAULT; @Setting(value = "Show-Scoreboard", comment = "Whether or not you wish to enable the display of this scoreboard." + "\nScoreboards are shown when the associated command is executed from the player." + "\nThis setting will only work if \"Use_Scoreboards\" is set to true, which is found elsewhere in this configuration file." + - "\nDefault value: "+USE_THIS_SCOREBOARD_DEFAULT) + "\nDefault value: " + USE_THIS_SCOREBOARD_DEFAULT) private boolean useThisBoard = USE_THIS_SCOREBOARD_DEFAULT; @Setting(value = "Display-Time-In-Seconds", comment = "How long to keep the scoreboard on a players screen after it is first shown." + "\nThis setting is not related to the command that keeps scoreboards on screen." + - "\nDefault value: "+DISPLAY_TIME_SECONDS_DEFAULT) + "\nDefault value: " + DISPLAY_TIME_SECONDS_DEFAULT) private int displayTimeInSeconds = DISPLAY_TIME_SECONDS_DEFAULT; /* diff --git a/src/main/java/com/gmail/nossr50/config/hocon/skills/ConfigScalingSubSkillRetro.java b/src/main/java/com/gmail/nossr50/config/hocon/skills/ConfigScalingSubSkillRetro.java index 8f40e4888..97fd64626 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/skills/ConfigScalingSubSkillRetro.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/skills/ConfigScalingSubSkillRetro.java @@ -16,7 +16,7 @@ public class ConfigScalingSubSkillRetro { "\nSkills dynamically adjust their rewards to match the max bonus level, you can think of it as a curve that calculates what bonuses " + "\n a player should have based on how far they are from the max bonus level value, and the other parameters used for the scaling of the sub-skill." + "\n\n-- NOTE: This setting is only valid for retro level scaling. --" + - "\nDefault value: "+MAX_BONUS_LEVEL_DEFAULT) + "\nDefault value: " + MAX_BONUS_LEVEL_DEFAULT) private int maxBonusLevel = MAX_BONUS_LEVEL_DEFAULT; @Setting(value = "Max-Success-Chance", comment = "The maximum success chance for this Sub-Skill." + @@ -26,7 +26,7 @@ public class ConfigScalingSubSkillRetro { "\nAs an example, imagine \"Max-Success-Chance\" was set to " + FIFTY_PERCENT_EXAMPLE + " and the \"Max-Bonus-Level\" was " + MAX_BONUS_LEVEL_EXAMPLE + "," + "\n and the player was level " + FIFTY_PERCENT_EXAMPLE + " for this skill, that would give the player " + ODDS_PERCENTAGE_EXAMPLE + " odds to succeed with this skill." + "\n\n-- NOTE: This setting is only valid for retro level scaling. --" + - "\nDefault value: "+CHANCE_AT_MAX_SKILL_DEFAULT) + "\nDefault value: " + CHANCE_AT_MAX_SKILL_DEFAULT) private double chanceAtMaxSkill = CHANCE_AT_MAX_SKILL_DEFAULT; public int getMaxBonusLevel() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/skills/ConfigScalingSubSkillStandard.java b/src/main/java/com/gmail/nossr50/config/hocon/skills/ConfigScalingSubSkillStandard.java index 9aee1edc1..1683b13b2 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/skills/ConfigScalingSubSkillStandard.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/skills/ConfigScalingSubSkillStandard.java @@ -16,7 +16,7 @@ public class ConfigScalingSubSkillStandard { "\nSkills dynamically adjust their rewards to match the max bonus level, you can think of it as a curve that calculates what bonuses " + "\n a player should have based on how far they are from the max bonus level value, and the other parameters used for the scaling of the sub-skill." + "\n\n-- NOTE: This setting is only valid for standard level scaling. --" + - "\nDefault value: "+MAX_BONUS_LEVEL_DEFAULT) + "\nDefault value: " + MAX_BONUS_LEVEL_DEFAULT) private int maxBonusLevel = MAX_BONUS_LEVEL_DEFAULT; @Setting(value = "Max-Success-Chance", comment = "The maximum success chance for this Sub-Skill." + @@ -26,7 +26,7 @@ public class ConfigScalingSubSkillStandard { "\nAs an example, imagine \"Max-Success-Chance\" was set to " + FIFTY_PERCENT_EXAMPLE + " and the \"Max-Bonus-Level\" was " + MAX_BONUS_LEVEL_EXAMPLE + "," + "\n and the player was level " + FIFTY_PERCENT_EXAMPLE + " for this skill, that would give the player " + ODDS_PERCENTAGE_EXAMPLE + " odds to succeed with this skill." + "\n\n-- NOTE: This setting is only valid for standard level scaling. --" + - "\nDefault value: "+CHANCE_AT_MAX_SKILL_DEFAULT) + "\nDefault value: " + CHANCE_AT_MAX_SKILL_DEFAULT) private double chanceAtMaxSkill = CHANCE_AT_MAX_SKILL_DEFAULT; public int getMaxBonusLevel() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/skills/ConfigSubSkillScalingRNG.java b/src/main/java/com/gmail/nossr50/config/hocon/skills/ConfigSubSkillScalingRNG.java index e17084eac..42e3cb71a 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/skills/ConfigSubSkillScalingRNG.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/skills/ConfigSubSkillScalingRNG.java @@ -34,17 +34,18 @@ public class ConfigSubSkillScalingRNG { /** * The max chance for the RNG component of a subskill from the user config + * * @return the max chance for the RNG component of a subskill */ public double getMaxChance() { - if(mcMMO.getConfigManager().getConfigLeveling().getConfigSectionLevelingGeneral().getConfigSectionLevelScaling().isRetroModeEnabled()) + if (mcMMO.getConfigManager().getConfigLeveling().getConfigSectionLevelingGeneral().getConfigSectionLevelScaling().isRetroModeEnabled()) return getRetroSettings().getChanceAtMaxSkill(); else return getStandardSettings().getChanceAtMaxSkill(); } public double getMaxBonusLevel() { - if(mcMMO.getConfigManager().getConfigLeveling().getConfigSectionLevelingGeneral().getConfigSectionLevelScaling().isRetroModeEnabled()) + if (mcMMO.getConfigManager().getConfigLeveling().getConfigSectionLevelingGeneral().getConfigSectionLevelScaling().isRetroModeEnabled()) return getRetroSettings().getMaxBonusLevel(); else return getStandardSettings().getMaxBonusLevel(); diff --git a/src/main/java/com/gmail/nossr50/config/hocon/skills/acrobatics/dodge/ConfigDodge.java b/src/main/java/com/gmail/nossr50/config/hocon/skills/acrobatics/dodge/ConfigDodge.java index a23933aa6..91fd04f07 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/skills/acrobatics/dodge/ConfigDodge.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/skills/acrobatics/dodge/ConfigDodge.java @@ -13,7 +13,7 @@ public class ConfigDodge { "\nPlayers can dodge almost all types of damage from other entities, such as player damage, monster damage, etc." + "\nAs an example, a value of 2.0 for this setting would result in the player taking half damage." + "\nHigher values would further decrease the amount of damage the player takes after a successful dodge." + - "\nDefault value: "+DAMAGE_REDUCTION_DIVISOR_DEFAULT) + "\nDefault value: " + DAMAGE_REDUCTION_DIVISOR_DEFAULT) private double damageReductionDivisor = DAMAGE_REDUCTION_DIVISOR_DEFAULT; @Setting(value = "RNG-Settings", comment = "Settings related to random chance elements for this Sub-Skill.") diff --git a/src/main/java/com/gmail/nossr50/config/hocon/skills/acrobatics/roll/ConfigRoll.java b/src/main/java/com/gmail/nossr50/config/hocon/skills/acrobatics/roll/ConfigRoll.java index 679ef22f8..0f0627ce0 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/skills/acrobatics/roll/ConfigRoll.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/skills/acrobatics/roll/ConfigRoll.java @@ -11,7 +11,7 @@ public class ConfigRoll { @Setting(value = "Damage-Threshold", comment = "Rolling will reduce up to this much damage." + "\nGraceful Rolls will reduce twice this value." + - "\nDefault value: "+ROLL_DAMAGE_THRESHOLD_DEFAULT) + "\nDefault value: " + ROLL_DAMAGE_THRESHOLD_DEFAULT) private double damageTheshold = ROLL_DAMAGE_THRESHOLD_DEFAULT; @Setting(value = "RNG-Settings", comment = "Settings related to random chance elements for this Sub-Skill.") diff --git a/src/main/java/com/gmail/nossr50/config/hocon/skills/exampleconfigs/ConfigNameRegisterDefaults.java b/src/main/java/com/gmail/nossr50/config/hocon/skills/exampleconfigs/ConfigNameRegisterDefaults.java index 4659e5596..19df506da 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/skills/exampleconfigs/ConfigNameRegisterDefaults.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/skills/exampleconfigs/ConfigNameRegisterDefaults.java @@ -8,7 +8,7 @@ import java.util.ArrayList; /** * This class is used to generate a table that can be referenced to compare Bukkit Material names - * to full qualified names used in internal registers for Minecraft + * to full qualified names used in internal registers for Minecraft */ @ConfigSerializable public class ConfigNameRegisterDefaults { @@ -17,8 +17,7 @@ public class ConfigNameRegisterDefaults { static { BUKKIT_MATERIAL_NAME_LOOKUP_EXAMPLE = new ArrayList<>(); - for(Material m : Material.values()) - { + for (Material m : Material.values()) { BUKKIT_MATERIAL_NAME_LOOKUP_EXAMPLE.add(new MinecraftMaterialWrapper((m))); } } diff --git a/src/main/java/com/gmail/nossr50/config/hocon/skills/exampleconfigs/MinecraftMaterialWrapper.java b/src/main/java/com/gmail/nossr50/config/hocon/skills/exampleconfigs/MinecraftMaterialWrapper.java index c7742c30b..e63703594 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/skills/exampleconfigs/MinecraftMaterialWrapper.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/skills/exampleconfigs/MinecraftMaterialWrapper.java @@ -7,8 +7,7 @@ public class MinecraftMaterialWrapper { private String fullyQualifiedName; private String bukkitMaterialName; - public MinecraftMaterialWrapper(Material material) - { + public MinecraftMaterialWrapper(Material material) { this.name = material.getKey().getKey(); this.fullyQualifiedName = material.getKey().toString(); this.bukkitMaterialName = material.toString(); diff --git a/src/main/java/com/gmail/nossr50/config/hocon/skills/fishing/ConfigFishing.java b/src/main/java/com/gmail/nossr50/config/hocon/skills/fishing/ConfigFishing.java index 9371c8158..650542a4b 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/skills/fishing/ConfigFishing.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/skills/fishing/ConfigFishing.java @@ -8,11 +8,10 @@ import java.util.HashMap; @ConfigSerializable public class ConfigFishing { - @Setting(value = "General") - private ConfigFishingGeneral fishingGeneral = new ConfigFishingGeneral(); - @Setting(value = "Sub-Skills") public ConfigFishingSubskills fishingSubskills = new ConfigFishingSubskills(); + @Setting(value = "General") + private ConfigFishingGeneral fishingGeneral = new ConfigFishingGeneral(); /* * GETTERS BOILERPLATE @@ -50,8 +49,7 @@ public class ConfigFishing { return getInnerPeace().getInnerPeaceVanillaXPMultiplier(); } - public int getVanillaXPMultInnerPeace(int rank) - { + public int getVanillaXPMultInnerPeace(int rank) { return getInnerPeaceVanillaXPMultiplier().get(rank); } } \ No newline at end of file diff --git a/src/main/java/com/gmail/nossr50/config/hocon/skills/fishing/ConfigFishingGeneral.java b/src/main/java/com/gmail/nossr50/config/hocon/skills/fishing/ConfigFishingGeneral.java index 360217131..5be66c913 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/skills/fishing/ConfigFishingGeneral.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/skills/fishing/ConfigFishingGeneral.java @@ -6,27 +6,27 @@ import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; @ConfigSerializable public class ConfigFishingGeneral { + public static final double LURE_MODIFIER_DEFAULT = 4.0D; private static final boolean ALWAYS_CATCH_FISH_DEFAULT = true; private static final boolean OVERRIDE_VANILLA_TREASURES = true; - public static final double LURE_MODIFIER_DEFAULT = 4.0D; private static final boolean ALLOW_MCMMO_FISHING_REWARDS = true; @Setting(value = "Always-Catch-Fish", comment = "Enables fish to be caught alongside treasure." + - "\nDefault value: "+ALWAYS_CATCH_FISH_DEFAULT) + "\nDefault value: " + ALWAYS_CATCH_FISH_DEFAULT) private boolean alwaysCatchFish = ALWAYS_CATCH_FISH_DEFAULT; @Setting(value = "Override-Vanilla-Fishing-Treasures", comment = "When set to true, mcMMO fishing loot tables will be used instead of vanilla." + "\nIt is recommended you use vanilla mcMMO fishing tables, as they are configurable." + - "\nDefault value: "+OVERRIDE_VANILLA_TREASURES) + "\nDefault value: " + OVERRIDE_VANILLA_TREASURES) private boolean overrideVanillaTreasures = OVERRIDE_VANILLA_TREASURES; @Setting(value = "Lure-Luck-Modifier", comment = "Lure luck modifier is used to determine how much to" + " increase drop chance by for fishing rods with the Luck enchantment." + - "\nDefault value: "+LURE_MODIFIER_DEFAULT) + "\nDefault value: " + LURE_MODIFIER_DEFAULT) private double lureLuckModifier = LURE_MODIFIER_DEFAULT; @Setting(value = "Allow-Custom-Fishing-Drops", comment = "If set to true, allows mcMMO fishing treasures to be found while fishing." + - "\nDefault value: "+ALLOW_MCMMO_FISHING_REWARDS) + "\nDefault value: " + ALLOW_MCMMO_FISHING_REWARDS) private boolean allowCustomDrops = ALLOW_MCMMO_FISHING_REWARDS; public boolean isAllowCustomDrops() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/skills/repair/ConfigRepair.java b/src/main/java/com/gmail/nossr50/config/hocon/skills/repair/ConfigRepair.java index 0eb0cb947..9c3d8e2fb 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/skills/repair/ConfigRepair.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/skills/repair/ConfigRepair.java @@ -16,8 +16,8 @@ import static org.bukkit.Material.*; @ConfigSerializable public class ConfigRepair { - public static final ArrayList CONFIG_REPAIRABLES_DEFAULTS; - public static final Material[] PLANKS = new Material[] { OAK_PLANKS, BIRCH_PLANKS, DARK_OAK_PLANKS, ACACIA_PLANKS, JUNGLE_PLANKS, SPRUCE_PLANKS}; + public static final ArrayList CONFIG_REPAIRABLES_DEFAULTS; + public static final Material[] PLANKS = new Material[]{OAK_PLANKS, BIRCH_PLANKS, DARK_OAK_PLANKS, ACACIA_PLANKS, JUNGLE_PLANKS, SPRUCE_PLANKS}; static { CONFIG_REPAIRABLES_DEFAULTS = new ArrayList<>(); diff --git a/src/main/java/com/gmail/nossr50/config/hocon/skills/repair/ConfigRepairArcaneForging.java b/src/main/java/com/gmail/nossr50/config/hocon/skills/repair/ConfigRepairArcaneForging.java index 381c24c32..997749707 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/skills/repair/ConfigRepairArcaneForging.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/skills/repair/ConfigRepairArcaneForging.java @@ -39,12 +39,12 @@ public class ConfigRepairArcaneForging { @Setting(value = "May-Lose-Enchants", comment = "With this on, players have a chance to have enchantments stripped from" + "\n their item when repairing." + "\nThe odds to lose your enchants decrease with higher levels of skill." + - "\nDefault value: "+LOSE_ENCHANTS_DEFAULT) + "\nDefault value: " + LOSE_ENCHANTS_DEFAULT) private boolean mayLoseEnchants = LOSE_ENCHANTS_DEFAULT; @Setting(value = "Chance-To-Downgrade-Enchants", comment = "With this on, players have a chance to have enchants downgraded when repairing." + "\nThe chance to downgrade decreases with higher levels of skill." + - "\nDefault value: "+DOWNGRADES_ENABLED_DEFAULT) + "\nDefault value: " + DOWNGRADES_ENABLED_DEFAULT) private boolean downgradesEnabled = DOWNGRADES_ENABLED_DEFAULT; @Setting(value = "Downgrade-Chance-Per-Rank", comment = "Chance to downgrade enchants per rank in this Sub-Skill.") diff --git a/src/main/java/com/gmail/nossr50/config/hocon/skills/repair/general/ConfigRepairGeneral.java b/src/main/java/com/gmail/nossr50/config/hocon/skills/repair/general/ConfigRepairGeneral.java index eea6ed5f9..30f6ecc4a 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/skills/repair/general/ConfigRepairGeneral.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/skills/repair/general/ConfigRepairGeneral.java @@ -12,24 +12,24 @@ public class ConfigRepairGeneral { public static final boolean ENCHANTED_ITEMS_REQUIRE_CONFIRM = true; @Setting(value = "Anvil-Block-Material", comment = "The block used for mcMMO repairs." + - "\nDefault value: "+"minecraft:iron_block") + "\nDefault value: " + "minecraft:iron_block") private String repairAnvilMaterial = Material.IRON_BLOCK.getKey().toString(); @Setting(value = "Anvil-Use-Sounds", comment = "If true, mcMMO will play a sound when a player uses an anvil." + - "\nDefault value: "+ANVIL_USE_SOUNDS_DEFAULT) + "\nDefault value: " + ANVIL_USE_SOUNDS_DEFAULT) private boolean anvilUseSounds = ANVIL_USE_SOUNDS_DEFAULT; @Setting(value = "Anvil-Notifications", comment = "Allows helpful messages to help players understand how to use the anvil." + - "\nDefault value: "+ANVIL_MESSAGES_DEFAULT) + "\nDefault value: " + ANVIL_MESSAGES_DEFAULT) private boolean anvilMessages = ANVIL_MESSAGES_DEFAULT; @Setting(value = "Anvil-Placed-Sounds", comment = "Placing an anvil in the world will play a sound effect." + - "\nDefault value: "+ANVIL_PLACED_SOUNDS_DEFAULT) + "\nDefault value: " + ANVIL_PLACED_SOUNDS_DEFAULT) private boolean anvilPlacedSounds = ANVIL_PLACED_SOUNDS_DEFAULT; @Setting(value = "Enchanted-Items-Require-Confirm", comment = "Warns players that using the anvil with an enchanted item is dangerous." + "\nPlayers will have to use the anvil twice in a row with an enchanted item." + - "\nDefault value: "+ENCHANTED_ITEMS_REQUIRE_CONFIRM) + "\nDefault value: " + ENCHANTED_ITEMS_REQUIRE_CONFIRM) private boolean enchantedItemsRequireConfirm = ENCHANTED_ITEMS_REQUIRE_CONFIRM; public Material getRepairAnvilMaterial() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/skills/repair/repairmastery/RepairMasteryRetro.java b/src/main/java/com/gmail/nossr50/config/hocon/skills/repair/repairmastery/RepairMasteryRetro.java index 9b6302d33..2297f7433 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/skills/repair/repairmastery/RepairMasteryRetro.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/skills/repair/repairmastery/RepairMasteryRetro.java @@ -16,7 +16,7 @@ public class RepairMasteryRetro { "\nSkills dynamically adjust their rewards to match the max bonus level, you can think of it as a curve that calculates what bonuses " + "\n a player should have based on how far they are from the max bonus level value, and the other parameters used for the scaling of the sub-skill." + "\n-- NOTE: This setting is only valid for retro level scaling. --" + - "\nDefault value: "+MAX_BONUS_LEVEL_DEFAULT) + "\nDefault value: " + MAX_BONUS_LEVEL_DEFAULT) private int maxBonusLevel = MAX_BONUS_LEVEL_DEFAULT; @Setting(value = "Max-Bonus-Percentage", comment = "This is the maximum benefit for additional repair amount from this skill when the player reaches \"Max-Bonus-Level\"." + @@ -24,7 +24,7 @@ public class RepairMasteryRetro { "\nAs an example, imagine \"Standard-Mode-Max-Bonus-Percentage\" was set to " + MAX_BONUS_PERCENTAGE + " and the \"Max-Bonus-Level\" was " + MAX_BONUS_LEVEL_EXAMPLE + "," + "\n and the player was level " + PLAYER_LEVEL_FIFTY_PERCENT_EXAMPLE + " for this skill, that would give the player " + BONUS_PERCENTAGE_EXAMPLE + "% added to the repair amount on the item before other bonuses." + "\n-- NOTE: This setting is only valid for retro level scaling. --" + - "\nDefault value: "+MAX_BONUS_PERCENTAGE) + "\nDefault value: " + MAX_BONUS_PERCENTAGE) private double maxBonusPercentage = MAX_BONUS_PERCENTAGE; public int getMaxBonusLevel() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/skills/repair/repairmastery/RepairMasteryStandard.java b/src/main/java/com/gmail/nossr50/config/hocon/skills/repair/repairmastery/RepairMasteryStandard.java index 72add35af..896d0426b 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/skills/repair/repairmastery/RepairMasteryStandard.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/skills/repair/repairmastery/RepairMasteryStandard.java @@ -16,7 +16,7 @@ public class RepairMasteryStandard { "\nSkills dynamically adjust their rewards to match the max bonus level, you can think of it as a curve that calculates what bonuses " + "\n a player should have based on how far they are from the max bonus level value, and the other parameters used for the scaling of the sub-skill." + "\n-- NOTE: This setting is only valid for standard level scaling. --" + - "\nDefault value: "+MAX_BONUS_LEVEL_DEFAULT) + "\nDefault value: " + MAX_BONUS_LEVEL_DEFAULT) public int maxBonusLevel = MAX_BONUS_LEVEL_DEFAULT; @Setting(value = "Max-Bonus-Percentage", comment = "This is the maximum benefit for additional repair amount from this skill when the player reaches \"Max-Bonus-Level\"." + @@ -24,6 +24,6 @@ public class RepairMasteryStandard { "\nAs an example, imagine \"Standard-Mode-Max-Bonus-Percentage\" was set to " + MAX_BONUS_PERCENTAGE + " and the \"Max-Bonus-Level\" was " + MAX_BONUS_LEVEL_EXAMPLE + "," + "\n and the player was level " + PLAYER_LEVEL_FIFTY_PERCENT_EXAMPLE + " for this skill, that would give the player " + BONUS_PERCENTAGE_EXAMPLE + "% added to the repair amount on the item before other bonuses." + "\n-- NOTE: This setting is only valid for standard level scaling. --" + - "\nDefault value: "+MAX_BONUS_PERCENTAGE) + "\nDefault value: " + MAX_BONUS_PERCENTAGE) public double maxBonusPercentage = MAX_BONUS_PERCENTAGE; } \ No newline at end of file diff --git a/src/main/java/com/gmail/nossr50/config/hocon/skills/salvage/ConfigArcaneSalvage.java b/src/main/java/com/gmail/nossr50/config/hocon/skills/salvage/ConfigArcaneSalvage.java index 989f91825..41878509f 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/skills/salvage/ConfigArcaneSalvage.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/skills/salvage/ConfigArcaneSalvage.java @@ -46,12 +46,12 @@ public class ConfigArcaneSalvage { @Setting(value = "May-Lose-Enchants", comment = "With this on, players have a chance to not receive the enchantments from the item they are salvaging." + "\nThe odds to lose your enchants decrease with higher levels of skill." + - "\nDefault value: "+LOSE_ENCHANTS_DEFAULT) + "\nDefault value: " + LOSE_ENCHANTS_DEFAULT) private boolean mayLoseEnchants = LOSE_ENCHANTS_DEFAULT; @Setting(value = "Chance-To-Downgrade-Enchants", comment = "With this on, players have a chance to have salvaged enchantments downgrade when salvaging." + "\nThe chance to downgrade decreases with higher levels of skill." + - "\nDefault value: "+DOWNGRADES_ENABLED_DEFAULT) + "\nDefault value: " + DOWNGRADES_ENABLED_DEFAULT) private boolean downgradesEnabled = DOWNGRADES_ENABLED_DEFAULT; public boolean isMayLoseEnchants() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/skills/salvage/general/ConfigSalvageGeneral.java b/src/main/java/com/gmail/nossr50/config/hocon/skills/salvage/general/ConfigSalvageGeneral.java index c68cefb41..add55f934 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/skills/salvage/general/ConfigSalvageGeneral.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/skills/salvage/general/ConfigSalvageGeneral.java @@ -13,24 +13,24 @@ public class ConfigSalvageGeneral { public static final boolean ENCHANTED_ITEMS_REQUIRE_CONFIRM = true; @Setting(value = "Anvil-Block-Material", comment = "The block used for mcMMO repairs." + - "Default value: "+"minecraft:gold_block") + "Default value: " + "minecraft:gold_block") private String salvageAnvilMaterial = Material.GOLD_BLOCK.getKey().toString(); @Setting(value = "Anvil-Use-Sounds", comment = "If true, mcMMO will play a sound when a player uses an anvil." + - "\nDefault value: "+ANVIL_USE_SOUNDS_DEFAULT) + "\nDefault value: " + ANVIL_USE_SOUNDS_DEFAULT) private boolean anvilUseSounds = ANVIL_USE_SOUNDS_DEFAULT; @Setting(value = "Anvil-Notifications", comment = "Allows helpful messages to help players understand how to use the anvil." + - "\nDefault value: "+ANVIL_MESSAGES_DEFAULT) + "\nDefault value: " + ANVIL_MESSAGES_DEFAULT) private boolean anvilMessages = ANVIL_MESSAGES_DEFAULT; @Setting(value = "Anvil-Placed-Sounds", comment = "Placing an anvil in the world will play a sound effect." + - "\nDefault value: "+ANVIL_PLACED_SOUNDS_DEFAULT) + "\nDefault value: " + ANVIL_PLACED_SOUNDS_DEFAULT) private boolean anvilPlacedSounds = ANVIL_PLACED_SOUNDS_DEFAULT; @Setting(value = "Enchanted-Items-Require-Confirm", comment = "Warns players that using the anvil with an enchanted item is dangerous." + "\nPlayers will have to use the anvil twice in a row with an enchanted item." + - "\nDefault value: "+ENCHANTED_ITEMS_REQUIRE_CONFIRM) + "\nDefault value: " + ENCHANTED_ITEMS_REQUIRE_CONFIRM) private boolean enchantedItemsRequireConfirm = ENCHANTED_ITEMS_REQUIRE_CONFIRM; public Material getSalvageAnvilMaterial() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/superabilities/ConfigSectionSuperAbilityLimits.java b/src/main/java/com/gmail/nossr50/config/hocon/superabilities/ConfigSectionSuperAbilityLimits.java index 48ca7bb77..39625b21c 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/superabilities/ConfigSectionSuperAbilityLimits.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/superabilities/ConfigSectionSuperAbilityLimits.java @@ -10,7 +10,7 @@ public class ConfigSectionSuperAbilityLimits { private ConfigSectionTreeFeller treeFeller = new ConfigSectionTreeFeller(); @Setting(value = "Tool-Durability-Damage", comment = "Increase this number to cause more durability loss for tools when using super abilities." + - "\nDefault value: "+TOOL_DURABILITY_DAMAGE_DEFAULT) + "\nDefault value: " + TOOL_DURABILITY_DAMAGE_DEFAULT) private int toolDurabilityDamage = TOOL_DURABILITY_DAMAGE_DEFAULT; public ConfigSectionTreeFeller getTreeFeller() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/superabilities/ConfigSectionTreeFeller.java b/src/main/java/com/gmail/nossr50/config/hocon/superabilities/ConfigSectionTreeFeller.java index e924373e0..3bb03d9b7 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/superabilities/ConfigSectionTreeFeller.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/superabilities/ConfigSectionTreeFeller.java @@ -10,7 +10,7 @@ public class ConfigSectionTreeFeller { @Setting(value = "Tree-Size-Limit", comment = "Trees over this many blocks in size will not activate" + "\nLower this number to improve performance." + - "\nDefault value: "+TREE_FELLER_LIMIT_DEFAULT) + "\nDefault value: " + TREE_FELLER_LIMIT_DEFAULT) private int treeFellerLimit = TREE_FELLER_LIMIT_DEFAULT; public int getTreeFellerLimit() { diff --git a/src/main/java/com/gmail/nossr50/config/hocon/superabilities/ConfigSuperAbilities.java b/src/main/java/com/gmail/nossr50/config/hocon/superabilities/ConfigSuperAbilities.java index 3f585ff12..27a7bcd8c 100644 --- a/src/main/java/com/gmail/nossr50/config/hocon/superabilities/ConfigSuperAbilities.java +++ b/src/main/java/com/gmail/nossr50/config/hocon/superabilities/ConfigSuperAbilities.java @@ -13,12 +13,12 @@ public class ConfigSuperAbilities { @Setting(value = "Enable-Super-Abilities", comment = "Turn this off to disable all super abilities." + - "\nDefault value: "+SUPER_ABILITY_DEFAULT) + "\nDefault value: " + SUPER_ABILITY_DEFAULT) private boolean superAbilitiesEnabled = SUPER_ABILITY_DEFAULT; @Setting(value = "Require-Sneaking", comment = "Players must be sneaking in order to activate super abilities." + - "\nDefault value: "+MUST_SNEAK_TO_ACTIVATE_DEFAULT) + "\nDefault value: " + MUST_SNEAK_TO_ACTIVATE_DEFAULT) private boolean mustSneakToActivate = MUST_SNEAK_TO_ACTIVATE_DEFAULT; @Setting(value = "Super-Ability-Cooldowns", @@ -27,7 +27,7 @@ public class ConfigSuperAbilities { @Setting(value = "Super-Ability-Max-Length", comment = "The maximum amount of time in seconds that a super ability can last." + - "\nMost super abilities get longer as a player grows in skill.") + "\nMost super abilities get longer as a player grows in skill.") private ConfigSectionSuperAbilityMaxLength superAbilityMaxLength = new ConfigSectionSuperAbilityMaxLength(); @Setting(value = "Super-Ability-Settings", comment = "Change specific parameters for super abilities.") @@ -53,10 +53,8 @@ public class ConfigSuperAbilities { return superAbilityLimits; } - public int getCooldownForSuper(SuperAbilityType superAbilityType) - { - switch(superAbilityType) - { + public int getCooldownForSuper(SuperAbilityType superAbilityType) { + switch (superAbilityType) { case BERSERK: return superAbilityCooldowns.getBerserk(); case GREEN_TERRA: @@ -74,15 +72,13 @@ public class ConfigSuperAbilities { case GIGA_DRILL_BREAKER: return superAbilityCooldowns.getGigaDrillBreaker(); default: - mcMMO.p.getLogger().severe("Cooldown Parameter not found for "+superAbilityType.toString()); + mcMMO.p.getLogger().severe("Cooldown Parameter not found for " + superAbilityType.toString()); return 240; } } - public int getMaxLengthForSuper(SuperAbilityType superAbilityType) - { - switch(superAbilityType) - { + public int getMaxLengthForSuper(SuperAbilityType superAbilityType) { + switch (superAbilityType) { case BERSERK: return superAbilityMaxLength.getBerserk(); case GREEN_TERRA: @@ -98,7 +94,7 @@ public class ConfigSuperAbilities { case GIGA_DRILL_BREAKER: return superAbilityMaxLength.getGigaDrillBreaker(); default: - mcMMO.p.getLogger().severe("Max Length Parameter not found for "+superAbilityType.toString()); + mcMMO.p.getLogger().severe("Max Length Parameter not found for " + superAbilityType.toString()); return 60; } } diff --git a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java index 3efeb7e46..42a4abc0e 100644 --- a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java +++ b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java @@ -71,13 +71,25 @@ public class PotionConfig extends ConfigCollection { register(); } + /** + * This grabs an instance of this config class from the Config Manager + * This method is deprecated and will be removed in the future + * + * @return the instance of this config + * @see mcMMO#getConfigManager() + * @deprecated Please use mcMMO.getConfigManager() to grab a specific config instead + */ + @Deprecated + public static PotionConfig getInstance() { + return mcMMO.getConfigManager().getPotionConfig(); + } + @Override public void unload() { potionMap.clear(); } - private void initIngredientLists() - { + private void initIngredientLists() { concoctionsIngredientsTierOne = new ArrayList<>(); concoctionsIngredientsTierTwo = new ArrayList<>(); concoctionsIngredientsTierThree = new ArrayList<>(); @@ -88,18 +100,6 @@ public class PotionConfig extends ConfigCollection { concoctionsIngredientsTierEight = new ArrayList<>(); } - /** - * This grabs an instance of this config class from the Config Manager - * This method is deprecated and will be removed in the future - * @see mcMMO#getConfigManager() - * @return the instance of this config - * @deprecated Please use mcMMO.getConfigManager() to grab a specific config instead - */ - @Deprecated - public static PotionConfig getInstance() { - return mcMMO.getConfigManager().getPotionConfig(); - } - /** * The version of this config * diff --git a/src/main/java/com/gmail/nossr50/config/treasure/ExcavationTreasureConfig.java b/src/main/java/com/gmail/nossr50/config/treasure/ExcavationTreasureConfig.java index baa501c11..04f9ea814 100644 --- a/src/main/java/com/gmail/nossr50/config/treasure/ExcavationTreasureConfig.java +++ b/src/main/java/com/gmail/nossr50/config/treasure/ExcavationTreasureConfig.java @@ -33,8 +33,9 @@ public class ExcavationTreasureConfig extends Config implements UnsafeValueValid /** * This grabs an instance of this config class from the Config Manager * This method is deprecated and will be removed in the future - * @see mcMMO#getConfigManager() + * * @return the instance of this config + * @see mcMMO#getConfigManager() * @deprecated Please use mcMMO.getConfigManager() to grab a specific config instead */ @Deprecated @@ -49,8 +50,7 @@ public class ExcavationTreasureConfig extends Config implements UnsafeValueValid public void register() { ConfigurationNode excavationTreasureNode = getUserRootNode().getNode(EXCAVATION); - if(excavationTreasureNode == null) - { + if (excavationTreasureNode == null) { mcMMO.p.getLogger().info("Excavation treasures in treasures config not defined"); return; } @@ -62,8 +62,7 @@ public class ExcavationTreasureConfig extends Config implements UnsafeValueValid //Treasure Material Definition Material treasureMaterial = Material.matchMaterial(treasureName.toUpperCase()); - if(treasureMaterial != null) - { + if (treasureMaterial != null) { ConfigurationNode currentTreasure = excavationTreasureNode.getNode(treasureName); //TODO: Rewrite the entire treasure system because it sucks @@ -84,40 +83,35 @@ public class ExcavationTreasureConfig extends Config implements UnsafeValueValid ArrayList dropsFrom = new ArrayList(currentTreasure.getNode("Drops_From").getList(TypeToken.of(String.class))); //VALIDATE AMOUNT - if(amount <= 0) - { - mcMMO.p.getLogger().severe("Excavation Treasure named "+treasureName+" in the config has an amount of 0 or below, is this intentional?"); - mcMMO.p.getLogger().severe("Skipping "+treasureName+" for being invalid"); + if (amount <= 0) { + mcMMO.p.getLogger().severe("Excavation Treasure named " + treasureName + " in the config has an amount of 0 or below, is this intentional?"); + mcMMO.p.getLogger().severe("Skipping " + treasureName + " for being invalid"); continue; } //VALIDATE XP - if(xp <= 0) - { - mcMMO.p.getLogger().info("Excavation Treasure named "+treasureName+" in the config has xp set to 0 or below, is this intentional?"); + if (xp <= 0) { + mcMMO.p.getLogger().info("Excavation Treasure named " + treasureName + " in the config has xp set to 0 or below, is this intentional?"); xp = 0; } //VALIDATE DROP CHANCE - if(dropChance <= 0) - { - mcMMO.p.getLogger().severe("Excavation Treasure named "+treasureName+" in the config has a drop chance of 0 or below, is this intentional?"); - mcMMO.p.getLogger().severe("Skipping "+treasureName+" for being invalid"); + if (dropChance <= 0) { + mcMMO.p.getLogger().severe("Excavation Treasure named " + treasureName + " in the config has a drop chance of 0 or below, is this intentional?"); + mcMMO.p.getLogger().severe("Skipping " + treasureName + " for being invalid"); continue; } //VALIDATE DROP LEVEL - if(dropLevel < 0) - { - mcMMO.p.getLogger().info("Excavation Treasure named "+treasureName+" in the config has a drop level below 0, is this intentional?"); + if (dropLevel < 0) { + mcMMO.p.getLogger().info("Excavation Treasure named " + treasureName + " in the config has a drop level below 0, is this intentional?"); dropLevel = 0; } //VALIDATE DROP SOURCES - if(dropsFrom == null || dropsFrom.isEmpty()) - { - mcMMO.p.getLogger().severe("Excavation Treasure named "+treasureName+" in the config has no drop targets, which would make it impossible to obtain, is this intentional?"); - mcMMO.p.getLogger().severe("Skipping "+treasureName+" for being invalid"); + if (dropsFrom == null || dropsFrom.isEmpty()) { + mcMMO.p.getLogger().severe("Excavation Treasure named " + treasureName + " in the config has no drop targets, which would make it impossible to obtain, is this intentional?"); + mcMMO.p.getLogger().severe("Skipping " + treasureName + " for being invalid"); continue; } @@ -125,8 +119,7 @@ public class ExcavationTreasureConfig extends Config implements UnsafeValueValid //Custom Name - if(currentTreasure.getNode(CUSTOM_NAME) != null && !currentTreasure.getNode(CUSTOM_NAME).getString().equalsIgnoreCase("ChangeMe")) - { + if (currentTreasure.getNode(CUSTOM_NAME) != null && !currentTreasure.getNode(CUSTOM_NAME).getString().equalsIgnoreCase("ChangeMe")) { customName = currentTreasure.getNode(CUSTOM_NAME).getString(); } @@ -139,15 +132,14 @@ public class ExcavationTreasureConfig extends Config implements UnsafeValueValid /* * Add to map */ - for(String dropBlock : dropsFrom) - { + for (String dropBlock : dropsFrom) { excavationMap.computeIfAbsent(dropBlock, k -> new ArrayList<>()); excavationMap.get(dropBlock).add(excavationTreasure); } } else { - mcMMO.p.getLogger().severe("Excavation Treasure Config - Material named "+treasureName+" does not match any known material."); + mcMMO.p.getLogger().severe("Excavation Treasure Config - Material named " + treasureName + " does not match any known material."); } } } catch (ObjectMappingException e) { diff --git a/src/main/java/com/gmail/nossr50/config/treasure/FishingTreasureConfig.java b/src/main/java/com/gmail/nossr50/config/treasure/FishingTreasureConfig.java index 169f95f4e..307418cdc 100644 --- a/src/main/java/com/gmail/nossr50/config/treasure/FishingTreasureConfig.java +++ b/src/main/java/com/gmail/nossr50/config/treasure/FishingTreasureConfig.java @@ -44,11 +44,17 @@ public class FishingTreasureConfig extends Config implements UnsafeValueValidati public HashMap> fishingRewards = new HashMap<>(); public HashMap> fishingEnchantments = new HashMap<>(); + public FishingTreasureConfig() { + super("fishing_drops", mcMMO.p.getDataFolder().getAbsoluteFile(), ConfigConstants.RELATIVE_PATH_CONFIG_DIR, true, false, true, false); + register(); + } + /** * This grabs an instance of this config class from the Config Manager * This method is deprecated and will be removed in the future - * @see mcMMO#getConfigManager() + * * @return the instance of this config + * @see mcMMO#getConfigManager() * @deprecated Please use mcMMO.getConfigManager() to grab a specific config instead */ @Deprecated @@ -56,11 +62,6 @@ public class FishingTreasureConfig extends Config implements UnsafeValueValidati return mcMMO.getConfigManager().getFishingTreasureConfig(); } - public FishingTreasureConfig() { - super("fishing_drops", mcMMO.p.getDataFolder().getAbsoluteFile(), ConfigConstants.RELATIVE_PATH_CONFIG_DIR, true, false, true, false); - register(); - } - /** * Register stuff */ @@ -70,14 +71,12 @@ public class FishingTreasureConfig extends Config implements UnsafeValueValidati ConfigurationNode fishingTreasureNode = getUserRootNode().getNode(FISHING); - if(fishingTreasureNode == null) - { + if (fishingTreasureNode == null) { mcMMO.p.getLogger().info("Fishing treasures in treasures config not defined"); return; } - // Initialize fishing HashMap for (Rarity rarity : Rarity.values()) { if (!fishingRewards.containsKey(rarity)) { @@ -92,8 +91,7 @@ public class FishingTreasureConfig extends Config implements UnsafeValueValidati //Treasure Material Definition Material treasureMaterial = Material.matchMaterial(treasureName.toUpperCase()); - if(treasureMaterial != null) - { + if (treasureMaterial != null) { ConfigurationNode currentTreasure = fishingTreasureNode.getNode(treasureName); //TODO: Rewrite the entire treasure system because it sucks @@ -112,25 +110,22 @@ public class FishingTreasureConfig extends Config implements UnsafeValueValidati ArrayList dropsFrom = new ArrayList(currentTreasure.getNode(DROPS_FROM).getList(TypeToken.of(String.class))); //VALIDATE AMOUNT - if(amount <= 0) - { - mcMMO.p.getLogger().severe("Excavation Treasure named "+treasureName+" in the config has an amount of 0 or below, is this intentional?"); - mcMMO.p.getLogger().severe("Skipping "+treasureName+" for being invalid"); + if (amount <= 0) { + mcMMO.p.getLogger().severe("Excavation Treasure named " + treasureName + " in the config has an amount of 0 or below, is this intentional?"); + mcMMO.p.getLogger().severe("Skipping " + treasureName + " for being invalid"); continue; } //VALIDATE XP - if(xp <= 0) - { - mcMMO.p.getLogger().info("Excavation Treasure named "+treasureName+" in the config has xp set to 0 or below, is this intentional?"); + if (xp <= 0) { + mcMMO.p.getLogger().info("Excavation Treasure named " + treasureName + " in the config has xp set to 0 or below, is this intentional?"); xp = 0; } //VALIDATE DROP SOURCES - if(dropsFrom == null || dropsFrom.isEmpty()) - { - mcMMO.p.getLogger().severe("Excavation Treasure named "+treasureName+" in the config has no drop targets, which would make it impossible to obtain, is this intentional?"); - mcMMO.p.getLogger().severe("Skipping "+treasureName+" for being invalid"); + if (dropsFrom == null || dropsFrom.isEmpty()) { + mcMMO.p.getLogger().severe("Excavation Treasure named " + treasureName + " in the config has no drop targets, which would make it impossible to obtain, is this intentional?"); + mcMMO.p.getLogger().severe("Skipping " + treasureName + " for being invalid"); continue; } @@ -138,8 +133,7 @@ public class FishingTreasureConfig extends Config implements UnsafeValueValidati //Custom Name - if(currentTreasure.getNode(CUSTOM_NAME) != null && !currentTreasure.getNode(CUSTOM_NAME).getString().equalsIgnoreCase("ChangeMe")) - { + if (currentTreasure.getNode(CUSTOM_NAME) != null && !currentTreasure.getNode(CUSTOM_NAME).getString().equalsIgnoreCase("ChangeMe")) { customName = currentTreasure.getNode(CUSTOM_NAME).getString(); } @@ -155,10 +149,8 @@ public class FishingTreasureConfig extends Config implements UnsafeValueValidati String configRarity = currentTreasure.getNode(RARITY).getString(); - for(Rarity rarity : Rarity.values()) - { - if(rarity.toString().equalsIgnoreCase(configRarity)) - { + for (Rarity rarity : Rarity.values()) { + if (rarity.toString().equalsIgnoreCase(configRarity)) { /*if(fishingRewards.get(rarity) == null) fishingRewards.put(rarity, new ArrayList<>());*/ @@ -167,7 +159,7 @@ public class FishingTreasureConfig extends Config implements UnsafeValueValidati } } else { - mcMMO.p.getLogger().severe("Excavation Treasure Config - Material named "+treasureName+" does not match any known material."); + mcMMO.p.getLogger().severe("Excavation Treasure Config - Material named " + treasureName + " does not match any known material."); } } } catch (ObjectMappingException e) { @@ -185,11 +177,10 @@ public class FishingTreasureConfig extends Config implements UnsafeValueValidati loadEnchantments(); } - private void loadShake(EntityType entityType) - { + private void loadShake(EntityType entityType) { ConfigurationNode shakeTreasureNode = getUserRootNode().getNode(SHAKE, entityType.toString()); - if(shakeTreasureNode != null) + if (shakeTreasureNode != null) return; try { @@ -199,8 +190,7 @@ public class FishingTreasureConfig extends Config implements UnsafeValueValidati //Treasure Material Definition Material treasureMaterial = Material.matchMaterial(treasureName.toUpperCase()); - if(treasureMaterial != null) - { + if (treasureMaterial != null) { ConfigurationNode currentTreasure = shakeTreasureNode.getNode(treasureName); //TODO: Rewrite the entire treasure system because it sucks @@ -221,40 +211,35 @@ public class FishingTreasureConfig extends Config implements UnsafeValueValidati ArrayList dropsFrom = new ArrayList(currentTreasure.getNode(DROPS_FROM).getList(TypeToken.of(String.class))); //VALIDATE AMOUNT - if(amount <= 0) - { - mcMMO.p.getLogger().severe("Excavation Treasure named "+treasureName+" in the config has an amount of 0 or below, is this intentional?"); - mcMMO.p.getLogger().severe("Skipping "+treasureName+" for being invalid"); + if (amount <= 0) { + mcMMO.p.getLogger().severe("Excavation Treasure named " + treasureName + " in the config has an amount of 0 or below, is this intentional?"); + mcMMO.p.getLogger().severe("Skipping " + treasureName + " for being invalid"); continue; } //VALIDATE XP - if(xp <= 0) - { - mcMMO.p.getLogger().info("Excavation Treasure named "+treasureName+" in the config has xp set to 0 or below, is this intentional?"); + if (xp <= 0) { + mcMMO.p.getLogger().info("Excavation Treasure named " + treasureName + " in the config has xp set to 0 or below, is this intentional?"); xp = 0; } //VALIDATE DROP CHANCE - if(dropChance <= 0) - { - mcMMO.p.getLogger().severe("Excavation Treasure named "+treasureName+" in the config has a drop chance of 0 or below, is this intentional?"); - mcMMO.p.getLogger().severe("Skipping "+treasureName+" for being invalid"); + if (dropChance <= 0) { + mcMMO.p.getLogger().severe("Excavation Treasure named " + treasureName + " in the config has a drop chance of 0 or below, is this intentional?"); + mcMMO.p.getLogger().severe("Skipping " + treasureName + " for being invalid"); continue; } //VALIDATE DROP LEVEL - if(dropLevel < 0) - { - mcMMO.p.getLogger().info("Excavation Treasure named "+treasureName+" in the config has a drop level below 0, is this intentional?"); + if (dropLevel < 0) { + mcMMO.p.getLogger().info("Excavation Treasure named " + treasureName + " in the config has a drop level below 0, is this intentional?"); dropLevel = 0; } //VALIDATE DROP SOURCES - if(dropsFrom == null || dropsFrom.isEmpty()) - { - mcMMO.p.getLogger().severe("Excavation Treasure named "+treasureName+" in the config has no drop targets, which would make it impossible to obtain, is this intentional?"); - mcMMO.p.getLogger().severe("Skipping "+treasureName+" for being invalid"); + if (dropsFrom == null || dropsFrom.isEmpty()) { + mcMMO.p.getLogger().severe("Excavation Treasure named " + treasureName + " in the config has no drop targets, which would make it impossible to obtain, is this intentional?"); + mcMMO.p.getLogger().severe("Skipping " + treasureName + " for being invalid"); continue; } @@ -262,8 +247,7 @@ public class FishingTreasureConfig extends Config implements UnsafeValueValidati //Custom Name - if(currentTreasure.getNode(CUSTOM_NAME) != null && !currentTreasure.getNode(CUSTOM_NAME).getString().equalsIgnoreCase("ChangeMe")) - { + if (currentTreasure.getNode(CUSTOM_NAME) != null && !currentTreasure.getNode(CUSTOM_NAME).getString().equalsIgnoreCase("ChangeMe")) { customName = currentTreasure.getNode(CUSTOM_NAME).getString(); } @@ -281,7 +265,7 @@ public class FishingTreasureConfig extends Config implements UnsafeValueValidati shakeMap.get(entityType).add(shakeTreasure); } else { - mcMMO.p.getLogger().severe("Excavation Treasure Config - Material named "+treasureName+" does not match any known material."); + mcMMO.p.getLogger().severe("Excavation Treasure Config - Material named " + treasureName + " does not match any known material."); } } } catch (ObjectMappingException e) { diff --git a/src/main/java/com/gmail/nossr50/config/treasure/HerbalismTreasureConfig.java b/src/main/java/com/gmail/nossr50/config/treasure/HerbalismTreasureConfig.java index b5c113b11..77df3d9a3 100644 --- a/src/main/java/com/gmail/nossr50/config/treasure/HerbalismTreasureConfig.java +++ b/src/main/java/com/gmail/nossr50/config/treasure/HerbalismTreasureConfig.java @@ -36,8 +36,9 @@ public class HerbalismTreasureConfig extends Config implements UnsafeValueValida /** * This grabs an instance of this config class from the Config Manager * This method is deprecated and will be removed in the future - * @see mcMMO#getConfigManager() + * * @return the instance of this config + * @see mcMMO#getConfigManager() * @deprecated Please use mcMMO.getConfigManager() to grab a specific config instead */ @Deprecated @@ -52,8 +53,7 @@ public class HerbalismTreasureConfig extends Config implements UnsafeValueValida public void register() { ConfigurationNode herbalismTreasureNode = getUserRootNode().getNode(HYLIAN_LUCK); - if(herbalismTreasureNode == null) - { + if (herbalismTreasureNode == null) { mcMMO.p.getLogger().info("Excavation treasures in treasures config not defined"); return; } @@ -65,8 +65,7 @@ public class HerbalismTreasureConfig extends Config implements UnsafeValueValida //Treasure Material Definition Material treasureMaterial = Material.matchMaterial(treasureName.toUpperCase()); - if(treasureMaterial != null) - { + if (treasureMaterial != null) { ConfigurationNode currentTreasure = herbalismTreasureNode.getNode(treasureName); //TODO: Rewrite the entire treasure system because it sucks @@ -87,40 +86,35 @@ public class HerbalismTreasureConfig extends Config implements UnsafeValueValida ArrayList dropsFrom = new ArrayList(currentTreasure.getNode("Drops_From").getList(TypeToken.of(String.class))); //VALIDATE AMOUNT - if(amount <= 0) - { - mcMMO.p.getLogger().severe("Herbalism Hylian Luck Treasure named "+treasureName+" in the config has an amount of 0 or below, is this intentional?"); - mcMMO.p.getLogger().severe("Skipping "+treasureName+" for being invalid"); + if (amount <= 0) { + mcMMO.p.getLogger().severe("Herbalism Hylian Luck Treasure named " + treasureName + " in the config has an amount of 0 or below, is this intentional?"); + mcMMO.p.getLogger().severe("Skipping " + treasureName + " for being invalid"); continue; } //VALIDATE XP - if(xp <= 0) - { - mcMMO.p.getLogger().info("Herbalism Hylian Luck Treasure named "+treasureName+" in the config has xp set to 0 or below, is this intentional?"); + if (xp <= 0) { + mcMMO.p.getLogger().info("Herbalism Hylian Luck Treasure named " + treasureName + " in the config has xp set to 0 or below, is this intentional?"); xp = 0; } //VALIDATE DROP CHANCE - if(dropChance <= 0) - { - mcMMO.p.getLogger().severe("Herbalism Hylian Luck Treasure named "+treasureName+" in the config has a drop chance of 0 or below, is this intentional?"); - mcMMO.p.getLogger().severe("Skipping "+treasureName+" for being invalid"); + if (dropChance <= 0) { + mcMMO.p.getLogger().severe("Herbalism Hylian Luck Treasure named " + treasureName + " in the config has a drop chance of 0 or below, is this intentional?"); + mcMMO.p.getLogger().severe("Skipping " + treasureName + " for being invalid"); continue; } //VALIDATE DROP LEVEL - if(dropLevel < 0) - { - mcMMO.p.getLogger().info("Herbalism Hylian Luck Treasure named "+treasureName+" in the config has a drop level below 0, is this intentional?"); + if (dropLevel < 0) { + mcMMO.p.getLogger().info("Herbalism Hylian Luck Treasure named " + treasureName + " in the config has a drop level below 0, is this intentional?"); dropLevel = 0; } //VALIDATE DROP SOURCES - if(dropsFrom == null || dropsFrom.isEmpty()) - { - mcMMO.p.getLogger().severe("Herbalism Hylian Luck Treasure named "+treasureName+" in the config has no drop targets, which would make it impossible to obtain, is this intentional?"); - mcMMO.p.getLogger().severe("Skipping "+treasureName+" for being invalid"); + if (dropsFrom == null || dropsFrom.isEmpty()) { + mcMMO.p.getLogger().severe("Herbalism Hylian Luck Treasure named " + treasureName + " in the config has no drop targets, which would make it impossible to obtain, is this intentional?"); + mcMMO.p.getLogger().severe("Skipping " + treasureName + " for being invalid"); continue; } @@ -128,8 +122,7 @@ public class HerbalismTreasureConfig extends Config implements UnsafeValueValida //Custom Name - if(currentTreasure.getNode(CUSTOM_NAME) != null && !currentTreasure.getNode(CUSTOM_NAME).getString().equalsIgnoreCase("ChangeMe")) - { + if (currentTreasure.getNode(CUSTOM_NAME) != null && !currentTreasure.getNode(CUSTOM_NAME).getString().equalsIgnoreCase("ChangeMe")) { customName = currentTreasure.getNode(CUSTOM_NAME).getString(); } @@ -142,8 +135,7 @@ public class HerbalismTreasureConfig extends Config implements UnsafeValueValida /* * Add to map */ - for(String dropBlock : dropsFrom) - { + for (String dropBlock : dropsFrom) { if (dropBlock.equals("Bushes")) { addHylianTreasure(StringUtils.getFriendlyConfigMaterialString(Material.FERN), hylianTreasure); addHylianTreasure(StringUtils.getFriendlyConfigMaterialString(Material.TALL_GRASS), hylianTreasure); @@ -176,7 +168,7 @@ public class HerbalismTreasureConfig extends Config implements UnsafeValueValida } } else { - mcMMO.p.getLogger().severe("Excavation Treasure Config - Material named "+treasureName+" does not match any known material."); + mcMMO.p.getLogger().severe("Excavation Treasure Config - Material named " + treasureName + " does not match any known material."); } } } catch (ObjectMappingException e) { diff --git a/src/main/java/com/gmail/nossr50/config/treasure/TreasureFactory.java b/src/main/java/com/gmail/nossr50/config/treasure/TreasureFactory.java index 18772e78b..5bf067171 100644 --- a/src/main/java/com/gmail/nossr50/config/treasure/TreasureFactory.java +++ b/src/main/java/com/gmail/nossr50/config/treasure/TreasureFactory.java @@ -24,6 +24,7 @@ public class TreasureFactory { /** * Make a new ExcavationTreasure + * * @param material * @param dropAmount * @param xpReward @@ -33,29 +34,25 @@ public class TreasureFactory { * @param customLore * @return */ - public static ExcavationTreasure makeExcavationTreasure(Material material, int dropAmount, int xpReward, double dropChance, int dropLevel, String customName, ConfigurationNode customLore) - { + public static ExcavationTreasure makeExcavationTreasure(Material material, int dropAmount, int xpReward, double dropChance, int dropLevel, String customName, ConfigurationNode customLore) { ItemStack treasure = makeItemStack(material, dropAmount, customName, customLore); return new ExcavationTreasure(treasure, xpReward, dropChance, dropLevel); } - public static ShakeTreasure makeShakeTreasure(Material material, int dropAmount, int xpReward, double dropChance, int dropLevel, String customName, ConfigurationNode customLore) - { + public static ShakeTreasure makeShakeTreasure(Material material, int dropAmount, int xpReward, double dropChance, int dropLevel, String customName, ConfigurationNode customLore) { ItemStack treasure = makeItemStack(material, dropAmount, customName, customLore); return new ShakeTreasure(treasure, xpReward, dropChance, dropLevel); } - public static FishingTreasure makeFishingTreasure(Material material, int dropAmount, int xpReward, String customName, ConfigurationNode customLore) - { + public static FishingTreasure makeFishingTreasure(Material material, int dropAmount, int xpReward, String customName, ConfigurationNode customLore) { ItemStack treasure = makeItemStack(material, dropAmount, customName, customLore); return new FishingTreasure(treasure, xpReward); } - public static HylianTreasure makeHylianTreasure(Material material, int dropAmount, int xpReward, double dropChance, int dropLevel, String customName, ConfigurationNode customLore) - { + public static HylianTreasure makeHylianTreasure(Material material, int dropAmount, int xpReward, double dropChance, int dropLevel, String customName, ConfigurationNode customLore) { ItemStack treasure = makeItemStack(material, dropAmount, customName, customLore); return new HylianTreasure(treasure, xpReward, dropChance, dropLevel); @@ -70,16 +67,14 @@ public class TreasureFactory { treasure = makePotionItemStack(material, dropAmount, customName, customLore);*/ /* ADD CUSTOM NAME */ - if(customName != null) - { + if (customName != null) { ItemMeta itemMeta = treasure.getItemMeta(); itemMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', customName)); treasure.setItemMeta(itemMeta); } /* ADD CUSTOM LORE */ - if(customLore != null && !customLore.getString().equalsIgnoreCase(CHANGE_ME)) - { + if (customLore != null && !customLore.getString().equalsIgnoreCase(CHANGE_ME)) { ItemMeta itemMeta = treasure.getItemMeta(); List lore = new ArrayList<>(); @@ -97,16 +92,13 @@ public class TreasureFactory { } - //TODO: Do this later return treasure; } - private static boolean isPotion(Material material) - { - switch(material) - { + private static boolean isPotion(Material material) { + switch (material) { case POTION: case SPLASH_POTION: case LINGERING_POTION: diff --git a/src/main/java/com/gmail/nossr50/database/DatabaseManager.java b/src/main/java/com/gmail/nossr50/database/DatabaseManager.java index 9a3a0ad50..ffc33a9f7 100644 --- a/src/main/java/com/gmail/nossr50/database/DatabaseManager.java +++ b/src/main/java/com/gmail/nossr50/database/DatabaseManager.java @@ -43,13 +43,13 @@ public interface DatabaseManager { boolean saveUser(PlayerProfile profile); /** - * Retrieve leaderboard info. - * - * @param skill The skill to retrieve info on - * @param pageNumber Which page in the leaderboards to retrieve - * @param statsPerPage The number of stats per page - * @return the requested leaderboard information - */ + * Retrieve leaderboard info. + * + * @param skill The skill to retrieve info on + * @param pageNumber Which page in the leaderboards to retrieve + * @param statsPerPage The number of stats per page + * @return the requested leaderboard information + */ List readLeaderboard(PrimarySkillType skill, int pageNumber, int statsPerPage); /** @@ -67,20 +67,19 @@ public interface DatabaseManager { * Add a new user to the database. * * @param playerName The name of the player to be added to the database - * @param uuid The uuid of the player to be added to the database + * @param uuid The uuid of the player to be added to the database */ void newUser(String playerName, UUID uuid); /** * Load a player from the database. * - * @deprecated replaced by {@link #loadPlayerProfile(String playerName, UUID uuid, boolean createNew)} - * * @param playerName The name of the player to load from the database - * @param createNew Whether to create a new record if the player is not - * found + * @param createNew Whether to create a new record if the player is not + * found * @return The player's data, or an unloaded PlayerProfile if not found - * and createNew is false + * and createNew is false + * @deprecated replaced by {@link #loadPlayerProfile(String playerName, UUID uuid, boolean createNew)} */ @Deprecated PlayerProfile loadPlayerProfile(String playerName, boolean createNew); @@ -97,11 +96,11 @@ public interface DatabaseManager { * Load a player from the database. Attempt to use uuid, fall back on playername * * @param playerName The name of the player to load from the database - * @param uuid The uuid of the player to load from the database - * @param createNew Whether to create a new record if the player is not - * found + * @param uuid The uuid of the player to load from the database + * @param createNew Whether to create a new record if the player is not + * found * @return The player's data, or an unloaded PlayerProfile if not found - * and createNew is false + * and createNew is false */ PlayerProfile loadPlayerProfile(String playerName, UUID uuid, boolean createNew); diff --git a/src/main/java/com/gmail/nossr50/database/DatabaseManagerFactory.java b/src/main/java/com/gmail/nossr50/database/DatabaseManagerFactory.java index 3b47662cb..faa98e7c3 100644 --- a/src/main/java/com/gmail/nossr50/database/DatabaseManagerFactory.java +++ b/src/main/java/com/gmail/nossr50/database/DatabaseManagerFactory.java @@ -10,12 +10,10 @@ public class DatabaseManagerFactory { if (customManager != null) { try { return createDefaultCustomDatabaseManager(); - } - catch (Exception e) { + } catch (Exception e) { mcMMO.p.debug("Could not create custom database manager"); e.printStackTrace(); - } - catch (Throwable e) { + } catch (Throwable e) { mcMMO.p.debug("Failed to create custom database manager"); e.printStackTrace(); } @@ -25,6 +23,10 @@ public class DatabaseManagerFactory { return mcMMO.getMySQLConfigSettings().isMySQLEnabled() ? new SQLDatabaseManager() : new FlatfileDatabaseManager(); } + public static Class getCustomDatabaseManagerClass() { + return customManager; + } + /** * Sets the custom DatabaseManager class for mcMMO to use. This should be * called prior to mcMMO enabling. @@ -37,7 +39,6 @@ public class DatabaseManagerFactory { * versions. * * @param clazz the DatabaseManager class to use - * * @throws IllegalArgumentException if the provided class does not have * an empty constructor */ @@ -45,16 +46,11 @@ public class DatabaseManagerFactory { try { clazz.getConstructor(); customManager = clazz; - } - catch (Throwable e) { + } catch (Throwable e) { throw new IllegalArgumentException("Provided database manager class must have an empty constructor", e); } } - public static Class getCustomDatabaseManagerClass() { - return customManager; - } - public static DatabaseManager createDatabaseManager(DatabaseType type) { switch (type) { case FLATFILE: @@ -66,8 +62,7 @@ public class DatabaseManagerFactory { case CUSTOM: try { return createDefaultCustomDatabaseManager(); - } - catch (Throwable e) { + } catch (Throwable e) { e.printStackTrace(); } diff --git a/src/main/java/com/gmail/nossr50/database/FlatfileDatabaseManager.java b/src/main/java/com/gmail/nossr50/database/FlatfileDatabaseManager.java index 938f30256..e9b652184 100644 --- a/src/main/java/com/gmail/nossr50/database/FlatfileDatabaseManager.java +++ b/src/main/java/com/gmail/nossr50/database/FlatfileDatabaseManager.java @@ -16,13 +16,52 @@ import java.io.*; import java.util.*; public final class FlatfileDatabaseManager implements DatabaseManager { + private static final Object fileWritingLock = new Object(); + public static int USERNAME = 0; + public static int SKILLS_MINING = 1; + public static int EXP_MINING = 4; + public static int SKILLS_WOODCUTTING = 5; + public static int EXP_WOODCUTTING = 6; + public static int SKILLS_REPAIR = 7; + public static int SKILLS_UNARMED = 8; + public static int SKILLS_HERBALISM = 9; + public static int SKILLS_EXCAVATION = 10; + public static int SKILLS_ARCHERY = 11; + public static int SKILLS_SWORDS = 12; + public static int SKILLS_AXES = 13; + public static int SKILLS_ACROBATICS = 14; + public static int EXP_REPAIR = 15; + public static int EXP_UNARMED = 16; + public static int EXP_HERBALISM = 17; + public static int EXP_EXCAVATION = 18; + public static int EXP_ARCHERY = 19; + public static int EXP_SWORDS = 20; + public static int EXP_AXES = 21; + public static int EXP_ACROBATICS = 22; + public static int SKILLS_TAMING = 24; + public static int EXP_TAMING = 25; + public static int COOLDOWN_BERSERK = 26; + public static int COOLDOWN_GIGA_DRILL_BREAKER = 27; + public static int COOLDOWN_TREE_FELLER = 28; + public static int COOLDOWN_GREEN_TERRA = 29; + public static int COOLDOWN_SERRATED_STRIKES = 30; + public static int COOLDOWN_SKULL_SPLITTER = 31; + public static int COOLDOWN_SUPER_BREAKER = 32; + public static int SKILLS_FISHING = 34; + public static int EXP_FISHING = 35; + public static int COOLDOWN_BLAST_MINING = 36; + public static int LAST_LOGIN = 37; + public static int HEALTHBAR = 38; + public static int SKILLS_ALCHEMY = 39; + public static int EXP_ALCHEMY = 40; + public static int UUID_INDEX = 41; + public static int SCOREBOARD_TIPS = 42; + public static int COOLDOWN_CHIMAERA_WING = 43; private final HashMap> playerStatHash = new HashMap<>(); private final List powerLevels = new ArrayList<>(); + private final File usersFile; private long lastUpdate = 0; private long updateWaitTime; - private final File usersFile; - private static final Object fileWritingLock = new Object(); - protected FlatfileDatabaseManager() { updateWaitTime = mcMMO.getConfigManager().getConfigDatabase().getConfigDatabaseFlatFile().getLeaderboardUpdateIntervalMinutes() * (1000 * 60); usersFile = new File(mcMMO.getUsersFilePath()); @@ -65,8 +104,7 @@ public final class FlatfileDatabaseManager implements DatabaseManager { // If they're still around, rewrite them to the file. if (!powerless) { writer.append(line).append("\r\n"); - } - else { + } else { purgedUsers++; } } @@ -74,24 +112,20 @@ public final class FlatfileDatabaseManager implements DatabaseManager { // Write the new file out = new FileWriter(usersFilePath); out.write(writer.toString()); - } - catch (IOException e) { + } catch (IOException e) { mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString()); - } - finally { + } finally { if (in != null) { try { in.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } if (out != null) { try { out.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } @@ -125,8 +159,7 @@ public final class FlatfileDatabaseManager implements DatabaseManager { boolean rewrite = false; try { lastPlayed = Long.parseLong(character[37]) * Misc.TIME_CONVERSION_FACTOR; - } - catch (NumberFormatException e) { + } catch (NumberFormatException e) { e.printStackTrace(); } if (lastPlayed == 0) { @@ -137,15 +170,13 @@ public final class FlatfileDatabaseManager implements DatabaseManager { if (currentTime - lastPlayed > PURGE_TIME) { removedPlayers++; - } - else { + } else { if (rewrite) { // Rewrite their data with a valid time character[37] = Long.toString(lastPlayed); String newLine = org.apache.commons.lang.StringUtils.join(character, ":"); writer.append(newLine).append("\r\n"); - } - else { + } else { writer.append(line).append("\r\n"); } } @@ -154,24 +185,20 @@ public final class FlatfileDatabaseManager implements DatabaseManager { // Write the new file out = new FileWriter(usersFilePath); out.write(writer.toString()); - } - catch (IOException e) { + } catch (IOException e) { mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString()); - } - finally { + } finally { if (in != null) { try { in.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } if (out != null) { try { out.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } @@ -207,24 +234,20 @@ public final class FlatfileDatabaseManager implements DatabaseManager { out = new FileWriter(usersFilePath); // Write out the new file out.write(writer.toString()); - } - catch (Exception e) { + } catch (Exception e) { mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString()); - } - finally { + } finally { if (in != null) { try { in.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } if (out != null) { try { out.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } @@ -258,8 +281,7 @@ public final class FlatfileDatabaseManager implements DatabaseManager { String[] character = line.split(":"); if (!(uuid != null && character[UUID_INDEX].equalsIgnoreCase(uuid.toString())) && !character[USERNAME].equalsIgnoreCase(playerName)) { writer.append(line).append("\r\n"); - } - else { + } else { // Otherwise write the new player information writeUserToLine(profile, playerName, uuid, writer); wroteUser = true; @@ -269,8 +291,7 @@ public final class FlatfileDatabaseManager implements DatabaseManager { /* * If we couldn't find the user in the DB we need to add him */ - if(!wroteUser) - { + if (!wroteUser) { writeUserToLine(profile, playerName, uuid, writer); } @@ -278,25 +299,21 @@ public final class FlatfileDatabaseManager implements DatabaseManager { out = new FileWriter(usersFilePath); out.write(writer.toString()); return true; - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); return false; - } - finally { + } finally { if (in != null) { try { in.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } if (out != null) { try { out.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } @@ -431,16 +448,13 @@ public final class FlatfileDatabaseManager implements DatabaseManager { // Add more in the same format as the line above out.newLine(); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); - } - finally { + } finally { if (out != null) { try { out.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } @@ -502,18 +516,15 @@ public final class FlatfileDatabaseManager implements DatabaseManager { newUser(playerName, uuid); return new PlayerProfile(playerName, uuid, true); } - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); - } - finally { + } finally { // I have no idea why it's necessary to inline tryClose() here, but it removes // a resource leak warning, and I'm trusting the compiler on this one. if (in != null) { try { in.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } @@ -545,23 +556,19 @@ public final class FlatfileDatabaseManager implements DatabaseManager { try { destination.saveUser(loadFromLine(character)); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } convertedUsers++; Misc.printProgress(convertedUsers, progressInterval, startMillis); } - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); - } - finally { + } finally { if (in != null) { try { in.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } @@ -602,25 +609,21 @@ public final class FlatfileDatabaseManager implements DatabaseManager { out = new FileWriter(usersFilePath); // Write out the new file out.write(writer.toString()); - } - catch (Exception e) { + } catch (Exception e) { mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString()); - } - finally { + } finally { mcMMO.p.getLogger().info(i + " entries written while saving UUID for " + userName); if (in != null) { try { in.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } if (out != null) { try { out.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } @@ -661,25 +664,21 @@ public final class FlatfileDatabaseManager implements DatabaseManager { out = new FileWriter(usersFilePath); // Write out the new file out.write(writer.toString()); - } - catch (Exception e) { + } catch (Exception e) { mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString()); - } - finally { + } finally { mcMMO.p.getLogger().info(i + " entries written while saving UUID batch"); if (in != null) { try { in.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } if (out != null) { try { out.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } @@ -704,16 +703,13 @@ public final class FlatfileDatabaseManager implements DatabaseManager { String[] character = line.split(":"); users.add(character[USERNAME]); } - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); - } - finally { + } finally { if (in != null) { try { in.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } @@ -781,16 +777,13 @@ public final class FlatfileDatabaseManager implements DatabaseManager { putStat(powerLevels, playerName, powerLevel); } - } - catch (Exception e) { + } catch (Exception e) { mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " during user " + playerName + " (Are you sure you formatted it correctly?) " + e.toString()); - } - finally { + } finally { if (in != null) { try { in.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } @@ -899,8 +892,7 @@ public final class FlatfileDatabaseManager implements DatabaseManager { continue; } //Level Cap - if(mcMMO.getPlayerLevelingSettings().isLevelCapEnabled(skill)) - { + if (mcMMO.getPlayerLevelingSettings().isLevelCapEnabled(skill)) { int cap = mcMMO.getPlayerLevelingSettings().getLevelCap(skill); if (Integer.valueOf(character[index]) > cap) { mcMMO.p.getLogger().warning("Truncating " + skill.getName() + " to configured max level for player " + character[USERNAME]); @@ -1005,11 +997,9 @@ public final class FlatfileDatabaseManager implements DatabaseManager { corrupted = true; if (i == 37) { character[i] = String.valueOf(System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR); - } - else if (i == 38) { + } else if (i == 38) { character[i] = mcMMO.getConfigManager().getConfigMobs().getCombat().getHealthBars().getDisplayBarType().toString(); - } - else { + } else { character[i] = "0"; } } @@ -1056,24 +1046,20 @@ public final class FlatfileDatabaseManager implements DatabaseManager { // Write the new file out = new FileWriter(usersFilePath); out.write(writer.toString()); - } - catch (IOException e) { + } catch (IOException e) { mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString()); - } - finally { + } finally { if (in != null) { try { in.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } if (out != null) { try { out.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } @@ -1095,8 +1081,7 @@ public final class FlatfileDatabaseManager implements DatabaseManager { try { mcMMO.p.debug("Creating mcmmo.users file..."); new File(mcMMO.getUsersFilePath()).createNewFile(); - } - catch (IOException e) { + } catch (IOException e) { e.printStackTrace(); } } @@ -1124,16 +1109,9 @@ public final class FlatfileDatabaseManager implements DatabaseManager { return statValue; } - private class SkillComparator implements Comparator { - @Override - public int compare(PlayerStat o1, PlayerStat o2) { - return (o2.statVal - o1.statVal); - } - } - private PlayerProfile loadFromLine(String[] character) { - Map skills = getSkillMapFromLine(character); // Skill levels - Map skillsXp = new EnumMap<>(PrimarySkillType.class); // Skill & XP + Map skills = getSkillMapFromLine(character); // Skill levels + Map skillsXp = new EnumMap<>(PrimarySkillType.class); // Skill & XP Map skillsDATS = new EnumMap<>(SuperAbilityType.class); // Ability & Cooldown Map uniquePlayerDataMap = new EnumMap<>(UniqueDataType.class); MobHealthbarType mobHealthbarType; @@ -1170,30 +1148,26 @@ public final class FlatfileDatabaseManager implements DatabaseManager { try { mobHealthbarType = MobHealthbarType.valueOf(character[HEALTHBAR]); - } - catch (Exception e) { + } catch (Exception e) { mobHealthbarType = mcMMO.getConfigManager().getConfigMobs().getCombat().getHealthBars().getDisplayBarType(); } UUID uuid; try { uuid = UUID.fromString(character[UUID_INDEX]); - } - catch (Exception e) { + } catch (Exception e) { uuid = null; } try { scoreboardTipsShown = Integer.valueOf(character[SCOREBOARD_TIPS]); - } - catch (Exception e) { + } catch (Exception e) { scoreboardTipsShown = 0; } try { uniquePlayerDataMap.put(UniqueDataType.CHIMAERA_WING_DATS, Integer.valueOf(character[COOLDOWN_CHIMAERA_WING])); - } - catch (Exception e) { + } catch (Exception e) { uniquePlayerDataMap.put(UniqueDataType.CHIMAERA_WING_DATS, 0); } @@ -1225,7 +1199,8 @@ public final class FlatfileDatabaseManager implements DatabaseManager { } @Override - public void onDisable() { } + public void onDisable() { + } private int getSkillIndex(PrimarySkillType skill) { switch (skill) { @@ -1257,50 +1232,9 @@ public final class FlatfileDatabaseManager implements DatabaseManager { return SKILLS_WOODCUTTING; default: throw new RuntimeException("Primary Skills only"); - + } } - - public static int USERNAME = 0; - public static int SKILLS_MINING = 1; - public static int EXP_MINING = 4; - public static int SKILLS_WOODCUTTING = 5; - public static int EXP_WOODCUTTING = 6; - public static int SKILLS_REPAIR = 7; - public static int SKILLS_UNARMED = 8; - public static int SKILLS_HERBALISM = 9; - public static int SKILLS_EXCAVATION = 10; - public static int SKILLS_ARCHERY = 11; - public static int SKILLS_SWORDS = 12; - public static int SKILLS_AXES = 13; - public static int SKILLS_ACROBATICS = 14; - public static int EXP_REPAIR = 15; - public static int EXP_UNARMED = 16; - public static int EXP_HERBALISM = 17; - public static int EXP_EXCAVATION = 18; - public static int EXP_ARCHERY = 19; - public static int EXP_SWORDS = 20; - public static int EXP_AXES = 21; - public static int EXP_ACROBATICS = 22; - public static int SKILLS_TAMING = 24; - public static int EXP_TAMING = 25; - public static int COOLDOWN_BERSERK = 26; - public static int COOLDOWN_GIGA_DRILL_BREAKER = 27; - public static int COOLDOWN_TREE_FELLER = 28; - public static int COOLDOWN_GREEN_TERRA = 29; - public static int COOLDOWN_SERRATED_STRIKES = 30; - public static int COOLDOWN_SKULL_SPLITTER = 31; - public static int COOLDOWN_SUPER_BREAKER = 32; - public static int SKILLS_FISHING = 34; - public static int EXP_FISHING = 35; - public static int COOLDOWN_BLAST_MINING = 36; - public static int LAST_LOGIN = 37; - public static int HEALTHBAR = 38; - public static int SKILLS_ALCHEMY = 39; - public static int EXP_ALCHEMY = 40; - public static int UUID_INDEX = 41; - public static int SCOREBOARD_TIPS = 42; - public static int COOLDOWN_CHIMAERA_WING = 43; public void resetMobHealthSettings() { BufferedReader in = null; @@ -1319,9 +1253,9 @@ public final class FlatfileDatabaseManager implements DatabaseManager { continue; } String[] character = line.split(":"); - + character[HEALTHBAR] = mcMMO.getConfigManager().getConfigMobs().getCombat().getHealthBars().getDisplayBarType().toString(); - + line = org.apache.commons.lang.StringUtils.join(character, ":") + ":"; writer.append(line).append("\r\n"); @@ -1330,28 +1264,31 @@ public final class FlatfileDatabaseManager implements DatabaseManager { // Write the new file out = new FileWriter(usersFilePath); out.write(writer.toString()); - } - catch (IOException e) { + } catch (IOException e) { mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString()); - } - finally { + } finally { if (in != null) { try { in.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } if (out != null) { try { out.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } } } } + + private class SkillComparator implements Comparator { + @Override + public int compare(PlayerStat o1, PlayerStat o2) { + return (o2.statVal - o1.statVal); + } + } } diff --git a/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java b/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java index 5c9481516..4d142c905 100644 --- a/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java +++ b/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java @@ -19,12 +19,10 @@ import java.util.*; import java.util.concurrent.locks.ReentrantLock; public final class SQLDatabaseManager implements DatabaseManager { - private static final String ALL_QUERY_VERSION = "total"; public static final String COM_MYSQL_JDBC_DRIVER = "com.mysql.jdbc.Driver"; - private String tablePrefix = mcMMO.getMySQLConfigSettings().getConfigSectionDatabase().getTablePrefix(); - + private static final String ALL_QUERY_VERSION = "total"; private final Map cachedUserIDs = new HashMap<>(); - + private String tablePrefix = mcMMO.getMySQLConfigSettings().getConfigSectionDatabase().getTablePrefix(); private DataSource miscPool; private DataSource loadPool; private DataSource savePool; @@ -35,20 +33,19 @@ public final class SQLDatabaseManager implements DatabaseManager { String connectionString = "jdbc:mysql://" + mcMMO.getMySQLConfigSettings().getUserConfigSectionServer().getServerAddress() + ":" + mcMMO.getMySQLConfigSettings().getUserConfigSectionServer().getServerPort() + "/" + mcMMO.getMySQLConfigSettings().getConfigSectionDatabase().getDatabaseName(); - if(mcMMO.getMySQLConfigSettings().getUserConfigSectionServer().isUseSSL()) + if (mcMMO.getMySQLConfigSettings().getUserConfigSectionServer().isUseSSL()) connectionString += - "?verifyServerCertificate=false"+ - "&useSSL=true"+ - "&requireSSL=true"; + "?verifyServerCertificate=false" + + "&useSSL=true" + + "&requireSSL=true"; else - connectionString+= + connectionString += "?useSSL=false"; try { // Force driver to load if not yet loaded Class.forName(COM_MYSQL_JDBC_DRIVER); - } - catch (ClassNotFoundException e) { + } catch (ClassNotFoundException e) { e.printStackTrace(); return; //throw e; // aborts onEnable() Riking if you want to do this, fully implement it. @@ -62,10 +59,10 @@ public final class SQLDatabaseManager implements DatabaseManager { /** * Set up our pools + * * @param connectionString the MySQL connection string */ - private void setupPools(String connectionString) - { + private void setupPools(String connectionString) { miscPool = new DataSource(setupPool(PoolIdentifier.MISC, connectionString)); loadPool = new DataSource(setupPool(PoolIdentifier.LOAD, connectionString)); savePool = new DataSource(setupPool(PoolIdentifier.SAVE, connectionString)); @@ -73,12 +70,12 @@ public final class SQLDatabaseManager implements DatabaseManager { /** * Sets up our pool using settings from the users config - * @param poolIdentifier the target pool + * + * @param poolIdentifier the target pool * @param connectionString the MySQL connection string * @return the pool properties ready for conversion */ - private PoolProperties setupPool(PoolIdentifier poolIdentifier, String connectionString) - { + private PoolProperties setupPool(PoolIdentifier poolIdentifier, String connectionString) { PoolProperties poolProperties = new PoolProperties(); poolProperties.setDriverClassName(COM_MYSQL_JDBC_DRIVER); poolProperties.setUrl(connectionString); @@ -139,11 +136,9 @@ public final class SQLDatabaseManager implements DatabaseManager { statement.executeUpdate("DELETE FROM `" + tablePrefix + "huds` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "skills` `s` WHERE `" + tablePrefix + "huds`.`user_id` = `s`.`user_id`)"); statement.executeUpdate("DELETE FROM `" + tablePrefix + "cooldowns` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "skills` `s` WHERE `" + tablePrefix + "cooldowns`.`user_id` = `s`.`user_id`)"); statement.executeUpdate("DELETE FROM `" + tablePrefix + "users` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "skills` `s` WHERE `" + tablePrefix + "users`.`id` = `s`.`user_id`)"); - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(statement); tryClose(connection); massUpdateLock.unlock(); @@ -170,11 +165,9 @@ public final class SQLDatabaseManager implements DatabaseManager { "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " + "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " + "WHERE ((UNIX_TIMESTAMP() - lastlogin) > " + PURGE_TIME + ")"); - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(statement); tryClose(connection); massUpdateLock.unlock(); @@ -201,11 +194,9 @@ public final class SQLDatabaseManager implements DatabaseManager { statement.setString(1, playerName); success = statement.executeUpdate() != 0; - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(statement); tryClose(connection); } @@ -331,11 +322,9 @@ public final class SQLDatabaseManager implements DatabaseManager { mcMMO.p.getLogger().severe("Failed to update hud settings for " + profile.getPlayerName()); return false; } - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(statement); tryClose(connection); } @@ -367,11 +356,9 @@ public final class SQLDatabaseManager implements DatabaseManager { stats.add(new PlayerStat(column.get(1), Integer.valueOf(column.get(0)))); } - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(resultSet); tryClose(statement); tryClose(connection); @@ -463,11 +450,9 @@ public final class SQLDatabaseManager implements DatabaseManager { resultSet.close(); statement.close(); - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(resultSet); tryClose(statement); tryClose(connection); @@ -482,11 +467,9 @@ public final class SQLDatabaseManager implements DatabaseManager { try { connection = getConnection(PoolIdentifier.MISC); newUser(connection, playerName, uuid); - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(connection); } } @@ -518,11 +501,9 @@ public final class SQLDatabaseManager implements DatabaseManager { writeMissingRows(connection, resultSet.getInt(1)); return resultSet.getInt(1); - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(resultSet); tryClose(statement); } @@ -610,17 +591,14 @@ public final class SQLDatabaseManager implements DatabaseManager { } return profile; - } - catch (SQLException e) { + } catch (SQLException e) { printErrors(e); } } resultSet.close(); - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(resultSet); tryClose(statement); tryClose(connection); @@ -666,19 +644,16 @@ public final class SQLDatabaseManager implements DatabaseManager { resultSet.next(); destination.saveUser(loadFromResult(playerName, resultSet)); resultSet.close(); - } - catch (SQLException e) { + } catch (SQLException e) { printErrors(e); // Ignore } convertedUsers++; Misc.printProgress(convertedUsers, progressInterval, startMillis); } - } - catch (SQLException e) { + } catch (SQLException e) { printErrors(e); - } - finally { + } finally { tryClose(resultSet); tryClose(statement); tryClose(connection); @@ -699,12 +674,10 @@ public final class SQLDatabaseManager implements DatabaseManager { statement.setString(2, userName); statement.execute(); return true; - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); return false; - } - finally { + } finally { tryClose(statement); tryClose(connection); } @@ -739,12 +712,10 @@ public final class SQLDatabaseManager implements DatabaseManager { } return true; - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); return false; - } - finally { + } finally { tryClose(statement); tryClose(connection); } @@ -764,11 +735,9 @@ public final class SQLDatabaseManager implements DatabaseManager { while (resultSet.next()) { users.add(resultSet.getString("user")); } - } - catch (SQLException e) { + } catch (SQLException e) { printErrors(e); - } - finally { + } finally { tryClose(resultSet); tryClose(statement); tryClose(connection); @@ -799,13 +768,13 @@ public final class SQLDatabaseManager implements DatabaseManager { if (!resultSet.next()) { createStatement = connection.createStatement(); createStatement.executeUpdate("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "users` (" - + "`id` int(10) unsigned NOT NULL AUTO_INCREMENT," - + "`user` varchar(40) NOT NULL," - + "`uuid` varchar(36) NULL DEFAULT NULL," - + "`lastlogin` int(32) unsigned NOT NULL," - + "PRIMARY KEY (`id`)," - + "INDEX(`user`(20) ASC)," - + "UNIQUE KEY `uuid` (`uuid`)) DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;"); + + "`id` int(10) unsigned NOT NULL AUTO_INCREMENT," + + "`user` varchar(40) NOT NULL," + + "`uuid` varchar(36) NULL DEFAULT NULL," + + "`lastlogin` int(32) unsigned NOT NULL," + + "PRIMARY KEY (`id`)," + + "INDEX(`user`(20) ASC)," + + "UNIQUE KEY `uuid` (`uuid`)) DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;"); tryClose(createStatement); } tryClose(resultSet); @@ -860,20 +829,20 @@ public final class SQLDatabaseManager implements DatabaseManager { createStatement = connection.createStatement(); createStatement.executeUpdate("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "skills` (" + "`user_id` int(10) unsigned NOT NULL," - + "`taming` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," - + "`mining` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," - + "`woodcutting` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," - + "`repair` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," - + "`unarmed` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," - + "`herbalism` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," - + "`excavation` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," - + "`archery` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," - + "`swords` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," - + "`axes` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," - + "`acrobatics` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," - + "`fishing` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," - + "`alchemy` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," - + "`total` int(10) unsigned NOT NULL DEFAULT "+totalLevel+"," + + "`taming` int(10) unsigned NOT NULL DEFAULT " + startingLevel + "," + + "`mining` int(10) unsigned NOT NULL DEFAULT " + startingLevel + "," + + "`woodcutting` int(10) unsigned NOT NULL DEFAULT " + startingLevel + "," + + "`repair` int(10) unsigned NOT NULL DEFAULT " + startingLevel + "," + + "`unarmed` int(10) unsigned NOT NULL DEFAULT " + startingLevel + "," + + "`herbalism` int(10) unsigned NOT NULL DEFAULT " + startingLevel + "," + + "`excavation` int(10) unsigned NOT NULL DEFAULT " + startingLevel + "," + + "`archery` int(10) unsigned NOT NULL DEFAULT " + startingLevel + "," + + "`swords` int(10) unsigned NOT NULL DEFAULT " + startingLevel + "," + + "`axes` int(10) unsigned NOT NULL DEFAULT " + startingLevel + "," + + "`acrobatics` int(10) unsigned NOT NULL DEFAULT " + startingLevel + "," + + "`fishing` int(10) unsigned NOT NULL DEFAULT " + startingLevel + "," + + "`alchemy` int(10) unsigned NOT NULL DEFAULT " + startingLevel + "," + + "`total` int(10) unsigned NOT NULL DEFAULT " + totalLevel + "," + "PRIMARY KEY (`user_id`)) " + "DEFAULT CHARSET=latin1;"); tryClose(createStatement); @@ -914,14 +883,14 @@ public final class SQLDatabaseManager implements DatabaseManager { //Level Cap Stuff if (mcMMO.getPlayerLevelingSettings().getConfigSectionLevelCaps().getReducePlayerSkillsAboveCap()) { for (PrimarySkillType skill : PrimarySkillType.NON_CHILD_SKILLS) { - if(!mcMMO.getPlayerLevelingSettings().isLevelCapEnabled(skill)) + if (!mcMMO.getPlayerLevelingSettings().isLevelCapEnabled(skill)) continue; //Shrink skills above the cap int cap = mcMMO.getPlayerLevelingSettings().getLevelCap(skill); - statement = connection.prepareStatement("UPDATE `" + tablePrefix + "skills` SET `" + skill.name().toLowerCase() + "` = " + cap + " WHERE `" + skill.name().toLowerCase() + "` > " + cap); - statement.executeUpdate(); - tryClose(statement); + statement = connection.prepareStatement("UPDATE `" + tablePrefix + "skills` SET `" + skill.name().toLowerCase() + "` = " + cap + " WHERE `" + skill.name().toLowerCase() + "` > " + cap); + statement.executeUpdate(); + tryClose(statement); } } @@ -931,11 +900,9 @@ public final class SQLDatabaseManager implements DatabaseManager { createStatement.executeUpdate("DELETE FROM `" + tablePrefix + "huds` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "users` `u` WHERE `" + tablePrefix + "huds`.`user_id` = `u`.`id`)"); createStatement.executeUpdate("DELETE FROM `" + tablePrefix + "cooldowns` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "users` `u` WHERE `" + tablePrefix + "cooldowns`.`user_id` = `u`.`id`)"); createStatement.executeUpdate("DELETE FROM `" + tablePrefix + "skills` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "users` `u` WHERE `" + tablePrefix + "skills`.`user_id` = `u`.`id`)"); - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(resultSet); tryClose(statement); tryClose(createStatement); @@ -1033,11 +1000,9 @@ public final class SQLDatabaseManager implements DatabaseManager { } //mcMMO.getUpgradeManager().setUpgradeCompleted(upgrade); - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(statement); } } @@ -1067,11 +1032,9 @@ public final class SQLDatabaseManager implements DatabaseManager { statement.setInt(3, 0); statement.execute(); statement.close(); - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(statement); } } @@ -1136,22 +1099,19 @@ public final class SQLDatabaseManager implements DatabaseManager { try { mobHealthbarType = MobHealthbarType.valueOf(result.getString(OFFSET_OTHER + 1)); - } - catch (Exception e) { + } catch (Exception e) { mobHealthbarType = mcMMO.getConfigManager().getConfigMobs().getCombat().getHealthBars().getDisplayBarType(); } try { scoreboardTipsShown = result.getInt(OFFSET_OTHER + 2); - } - catch (Exception e) { + } catch (Exception e) { scoreboardTipsShown = 0; } try { uuid = UUID.fromString(result.getString(OFFSET_OTHER + 3)); - } - catch (Exception e) { + } catch (Exception e) { uuid = null; } @@ -1182,7 +1142,7 @@ public final class SQLDatabaseManager implements DatabaseManager { } resultSet.close(); mcMMO.p.getLogger().info("Updating mcMMO MySQL tables to drop name uniqueness..."); - statement.execute("ALTER TABLE `" + tablePrefix + "users` " + statement.execute("ALTER TABLE `" + tablePrefix + "users` " + "DROP INDEX `user`," + "ADD INDEX `user` (`user`(20) ASC)"); } catch (SQLException ex) { @@ -1195,8 +1155,7 @@ public final class SQLDatabaseManager implements DatabaseManager { private void checkUpgradeAddAlchemy(final Statement statement) throws SQLException { try { statement.executeQuery("SELECT `alchemy` FROM `" + tablePrefix + "skills` LIMIT 1"); - } - catch (SQLException ex) { + } catch (SQLException ex) { mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Alchemy..."); statement.executeUpdate("ALTER TABLE `" + tablePrefix + "skills` ADD `alchemy` int(10) NOT NULL DEFAULT '0'"); statement.executeUpdate("ALTER TABLE `" + tablePrefix + "experience` ADD `alchemy` int(10) NOT NULL DEFAULT '0'"); @@ -1206,8 +1165,7 @@ public final class SQLDatabaseManager implements DatabaseManager { private void checkUpgradeAddBlastMiningCooldown(final Statement statement) throws SQLException { try { statement.executeQuery("SELECT `blast_mining` FROM `" + tablePrefix + "cooldowns` LIMIT 1"); - } - catch (SQLException ex) { + } catch (SQLException ex) { mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Blast Mining..."); statement.executeUpdate("ALTER TABLE `" + tablePrefix + "cooldowns` ADD `blast_mining` int(32) NOT NULL DEFAULT '0'"); } @@ -1216,8 +1174,7 @@ public final class SQLDatabaseManager implements DatabaseManager { private void checkUpgradeAddUniqueChimaeraWing(final Statement statement) throws SQLException { try { statement.executeQuery("SELECT `chimaera_wing` FROM `" + tablePrefix + "cooldowns` LIMIT 1"); - } - catch (SQLException ex) { + } catch (SQLException ex) { mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Chimaera Wing..."); statement.executeUpdate("ALTER TABLE `" + tablePrefix + "cooldowns` ADD `chimaera_wing` int(32) NOT NULL DEFAULT '0'"); } @@ -1226,8 +1183,7 @@ public final class SQLDatabaseManager implements DatabaseManager { private void checkUpgradeAddFishing(final Statement statement) throws SQLException { try { statement.executeQuery("SELECT `fishing` FROM `" + tablePrefix + "skills` LIMIT 1"); - } - catch (SQLException ex) { + } catch (SQLException ex) { mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Fishing..."); statement.executeUpdate("ALTER TABLE `" + tablePrefix + "skills` ADD `fishing` int(10) NOT NULL DEFAULT '0'"); statement.executeUpdate("ALTER TABLE `" + tablePrefix + "experience` ADD `fishing` int(10) NOT NULL DEFAULT '0'"); @@ -1237,8 +1193,7 @@ public final class SQLDatabaseManager implements DatabaseManager { private void checkUpgradeAddMobHealthbars(final Statement statement) throws SQLException { try { statement.executeQuery("SELECT `mobhealthbar` FROM `" + tablePrefix + "huds` LIMIT 1"); - } - catch (SQLException ex) { + } catch (SQLException ex) { mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for mob healthbars..."); statement.executeUpdate("ALTER TABLE `" + tablePrefix + "huds` ADD `mobhealthbar` varchar(50) NOT NULL DEFAULT '" + mcMMO.getConfigManager().getConfigMobs().getCombat().getHealthBars().getDisplayBarType() + "'"); } @@ -1247,8 +1202,7 @@ public final class SQLDatabaseManager implements DatabaseManager { private void checkUpgradeAddScoreboardTips(final Statement statement) throws SQLException { try { statement.executeQuery("SELECT `scoreboardtips` FROM `" + tablePrefix + "huds` LIMIT 1"); - } - catch (SQLException ex) { + } catch (SQLException ex) { mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for scoreboard tips..."); statement.executeUpdate("ALTER TABLE `" + tablePrefix + "huds` ADD `scoreboardtips` int(10) NOT NULL DEFAULT '0' ;"); } @@ -1269,17 +1223,14 @@ public final class SQLDatabaseManager implements DatabaseManager { try { statement.executeUpdate("ALTER TABLE `" + tablePrefix + "skills` ADD INDEX `idx_" + skill_name + "` (`" + skill_name + "`) USING BTREE"); - } - catch (SQLException ex) { + } catch (SQLException ex) { // Ignore } } } - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(resultSet); } } @@ -1305,11 +1256,9 @@ public final class SQLDatabaseManager implements DatabaseManager { statement.executeUpdate("ALTER TABLE `" + tablePrefix + "users` ADD `uuid` varchar(36) NULL DEFAULT NULL"); statement.executeUpdate("ALTER TABLE `" + tablePrefix + "users` ADD UNIQUE INDEX `uuid` (`uuid`) USING BTREE"); } - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(resultSet); } @@ -1369,11 +1318,9 @@ public final class SQLDatabaseManager implements DatabaseManager { mcMMO.p.getLogger().info("Removing party name from users table..."); statement.executeUpdate("ALTER TABLE `" + tablePrefix + "users` DROP COLUMN `party`"); } - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(resultSet); } } @@ -1404,11 +1351,9 @@ public final class SQLDatabaseManager implements DatabaseManager { statement.executeUpdate("ALTER TABLE `" + tablePrefix + "skills` ADD INDEX `idx_total` (`total`) USING BTREE"); connection.commit(); } - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { connection.setAutoCommit(true); tryClose(resultSet); tryClose(statement); @@ -1435,11 +1380,9 @@ public final class SQLDatabaseManager implements DatabaseManager { mcMMO.p.getLogger().info("Removing Spout HUD type from huds table..."); statement.executeUpdate("ALTER TABLE `" + tablePrefix + "huds` DROP COLUMN `hudtype`"); } - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(resultSet); } } @@ -1467,11 +1410,9 @@ public final class SQLDatabaseManager implements DatabaseManager { return id; } - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(resultSet); tryClose(statement); } @@ -1493,24 +1434,21 @@ public final class SQLDatabaseManager implements DatabaseManager { return id; } - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(resultSet); tryClose(statement); } return -1; } - + private void tryClose(AutoCloseable closeable) { if (closeable != null) { try { closeable.close(); - } - catch (Exception e) { + } catch (Exception e) { // Ignore } } @@ -1533,11 +1471,9 @@ public final class SQLDatabaseManager implements DatabaseManager { statement = connection.prepareStatement("UPDATE " + tablePrefix + "huds SET mobhealthbar = ?"); statement.setString(1, mcMMO.getConfigManager().getConfigMobs().getCombat().getHealthBars().getDisplayBarType().toString()); statement.executeUpdate(); - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(statement); tryClose(connection); } diff --git a/src/main/java/com/gmail/nossr50/datatypes/LimitedSizeList.java b/src/main/java/com/gmail/nossr50/datatypes/LimitedSizeList.java index c57b4996f..f03abda99 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/LimitedSizeList.java +++ b/src/main/java/com/gmail/nossr50/datatypes/LimitedSizeList.java @@ -4,12 +4,11 @@ package com.gmail.nossr50.datatypes; import org.bukkit.Location; public class LimitedSizeList { - public Location[] limitedSizeOrderedList; private final int size; + public Location[] limitedSizeOrderedList; - public LimitedSizeList(int size) - { + public LimitedSizeList(int size) { this.size = size; limitedSizeOrderedList = new Location[size]; } @@ -17,16 +16,15 @@ public class LimitedSizeList { /** * Adds objects to our limited size ordered list * New objects are added to the front + * * @param newItem */ - public void add(Location newItem) - { + public void add(Location newItem) { Location[] newList = new Location[size]; - for(int i = 0; i < size-1; i++) - { - if(i != 0) - newList[i] = limitedSizeOrderedList[i-1]; + for (int i = 0; i < size - 1; i++) { + if (i != 0) + newList[i] = limitedSizeOrderedList[i - 1]; else newList[i] = newItem; } @@ -36,17 +34,16 @@ public class LimitedSizeList { /** * Returns true if the object is anywhere in our list + * * @param targetLoc the object to check for * @return true if the object is in our list */ - public boolean contains(Location targetLoc) - { - for(Location iter : limitedSizeOrderedList) - { - if(iter == null) + public boolean contains(Location targetLoc) { + for (Location iter : limitedSizeOrderedList) { + if (iter == null) continue; - if(iter.getX() == targetLoc.getX() + if (iter.getX() == targetLoc.getX() && iter.getY() == targetLoc.getY() && iter.getZ() == targetLoc.getZ()) return true; diff --git a/src/main/java/com/gmail/nossr50/datatypes/chat/ChatMode.java b/src/main/java/com/gmail/nossr50/datatypes/chat/ChatMode.java index e2210739f..9fb25cb37 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/chat/ChatMode.java +++ b/src/main/java/com/gmail/nossr50/datatypes/chat/ChatMode.java @@ -10,7 +10,7 @@ public enum ChatMode { private String disabledMessage; ChatMode(String enabledMessage, String disabledMessage) { - this.enabledMessage = enabledMessage; + this.enabledMessage = enabledMessage; this.disabledMessage = disabledMessage; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/database/DatabaseType.java b/src/main/java/com/gmail/nossr50/datatypes/database/DatabaseType.java index c8e089ab6..11a01cdec 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/database/DatabaseType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/database/DatabaseType.java @@ -14,8 +14,7 @@ public enum DatabaseType { if (typeName.equalsIgnoreCase("file")) { return FLATFILE; - } - else if (typeName.equalsIgnoreCase("mysql")) { + } else if (typeName.equalsIgnoreCase("mysql")) { return SQL; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/experience/FormulaType.java b/src/main/java/com/gmail/nossr50/datatypes/experience/FormulaType.java index ea428d812..9637fe014 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/experience/FormulaType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/experience/FormulaType.java @@ -8,8 +8,7 @@ public enum FormulaType { public static FormulaType getFormulaType(String string) { try { return valueOf(string); - } - catch (IllegalArgumentException ex) { + } catch (IllegalArgumentException ex) { return UNKNOWN; } } diff --git a/src/main/java/com/gmail/nossr50/datatypes/experience/SkillXpGain.java b/src/main/java/com/gmail/nossr50/datatypes/experience/SkillXpGain.java index a6d645f39..d17a1f268 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/experience/SkillXpGain.java +++ b/src/main/java/com/gmail/nossr50/datatypes/experience/SkillXpGain.java @@ -17,6 +17,10 @@ public class SkillXpGain implements Delayed { this.type = type; } + private static long getDuration() { + return TimeUnit.MINUTES.toMillis(ExperienceConfig.getInstance().getDiminishedReturnsTimeInterval()); + } + public PrimarySkillType getSkill() { return type; } @@ -25,15 +29,10 @@ public class SkillXpGain implements Delayed { return xp; } - private static long getDuration() { - return TimeUnit.MINUTES.toMillis(ExperienceConfig.getInstance().getDiminishedReturnsTimeInterval()); - } - public int compareTo(SkillXpGain other) { if (this.expiryTime < other.expiryTime) { return -1; - } - else if (this.expiryTime > other.expiryTime) { + } else if (this.expiryTime > other.expiryTime) { return 1; } return 0; diff --git a/src/main/java/com/gmail/nossr50/datatypes/interactions/NotificationType.java b/src/main/java/com/gmail/nossr50/datatypes/interactions/NotificationType.java index 87787b8b2..37bc8b8cd 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/interactions/NotificationType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/interactions/NotificationType.java @@ -24,12 +24,12 @@ public enum NotificationType { final String niceName; - NotificationType(String niceName) - { + NotificationType(String niceName) { this.niceName = niceName; } @Override public String toString() { return niceName; - }} + } +} diff --git a/src/main/java/com/gmail/nossr50/datatypes/json/McMMOUrl.java b/src/main/java/com/gmail/nossr50/datatypes/json/McMMOUrl.java index 4f4886aeb..5ddacef89 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/json/McMMOUrl.java +++ b/src/main/java/com/gmail/nossr50/datatypes/json/McMMOUrl.java @@ -1,17 +1,15 @@ package com.gmail.nossr50.datatypes.json; public class McMMOUrl { - public static final String urlWebsite = "https://www.mcmmo.org"; - public static final String urlDiscord = "https://discord.gg/bJ7pFS9"; - public static final String urlPatreon = "https://www.patreon.com/nossr50"; - public static final String urlWiki = "https://www.mcmmo.org/wiki/"; - public static final String urlSpigot = "http://spigot.mcmmo.org"; + public static final String urlWebsite = "https://www.mcmmo.org"; + public static final String urlDiscord = "https://discord.gg/bJ7pFS9"; + public static final String urlPatreon = "https://www.patreon.com/nossr50"; + public static final String urlWiki = "https://www.mcmmo.org/wiki/"; + public static final String urlSpigot = "http://spigot.mcmmo.org"; public static final String urlTranslate = "https://www.mcmmo.org/translate/"; - public static String getUrl(McMMOWebLinks webLinks) - { - switch(webLinks) - { + public static String getUrl(McMMOWebLinks webLinks) { + switch (webLinks) { case WIKI: return urlWiki; case PATREON: diff --git a/src/main/java/com/gmail/nossr50/datatypes/json/McMMOWebLinks.java b/src/main/java/com/gmail/nossr50/datatypes/json/McMMOWebLinks.java index 0dbad85db..0fb3714df 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/json/McMMOWebLinks.java +++ b/src/main/java/com/gmail/nossr50/datatypes/json/McMMOWebLinks.java @@ -11,28 +11,24 @@ public enum McMMOWebLinks { HELP_TRANSLATE, WIKI; - public String getUrl() - { + public String getUrl() { return McMMOUrl.getUrl(this); } - public String getNiceTitle() - { + public String getNiceTitle() { return StringUtils.getCapitalized(toString()); } - public String getLocaleDescription() - { - switch (this) - { + public String getLocaleDescription() { + switch (this) { case WEBSITE: - return LocaleLoader.getString( "JSON.URL.Website"); + return LocaleLoader.getString("JSON.URL.Website"); case DISCORD: - return LocaleLoader.getString( "JSON.URL.Discord"); + return LocaleLoader.getString("JSON.URL.Discord"); case PATREON: - return LocaleLoader.getString( "JSON.URL.Patreon"); + return LocaleLoader.getString("JSON.URL.Patreon"); case HELP_TRANSLATE: - return LocaleLoader.getString( "JSON.URL.Translation"); + return LocaleLoader.getString("JSON.URL.Translation"); case SPIGOT: return LocaleLoader.getString("JSON.URL.Spigot"); case WIKI: diff --git a/src/main/java/com/gmail/nossr50/datatypes/meta/OldName.java b/src/main/java/com/gmail/nossr50/datatypes/meta/OldName.java index b300f92cc..60907b342 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/meta/OldName.java +++ b/src/main/java/com/gmail/nossr50/datatypes/meta/OldName.java @@ -8,8 +8,7 @@ import org.bukkit.metadata.FixedMetadataValue; */ public class OldName extends FixedMetadataValue { - public OldName(String oldName, mcMMO plugin) - { + public OldName(String oldName, mcMMO plugin) { super(plugin, oldName); } } diff --git a/src/main/java/com/gmail/nossr50/datatypes/party/ItemShareType.java b/src/main/java/com/gmail/nossr50/datatypes/party/ItemShareType.java index 685767a75..ee7a132db 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/party/ItemShareType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/party/ItemShareType.java @@ -16,17 +16,13 @@ public enum ItemShareType { public static ItemShareType getShareType(ItemStack itemStack) { if (ItemUtils.isMobDrop(itemStack)) { return LOOT; - } - else if (ItemUtils.isMiningDrop(itemStack)) { + } else if (ItemUtils.isMiningDrop(itemStack)) { return MINING; - } - else if (ItemUtils.isHerbalismDrop(itemStack)) { + } else if (ItemUtils.isHerbalismDrop(itemStack)) { return HERBALISM; - } - else if (ItemUtils.isWoodcuttingDrop(itemStack)) { + } else if (ItemUtils.isWoodcuttingDrop(itemStack)) { return WOODCUTTING; - } - else if (mcMMO.getConfigManager().getConfigParty().getPartyItemShare().getItemShareMap().get(itemStack.getType()) != null) { + } else if (mcMMO.getConfigManager().getConfigParty().getPartyItemShare().getItemShareMap().get(itemStack.getType()) != null) { return MISC; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/party/Party.java b/src/main/java/com/gmail/nossr50/datatypes/party/Party.java index 78120e804..747db3615 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/party/Party.java +++ b/src/main/java/com/gmail/nossr50/datatypes/party/Party.java @@ -23,12 +23,10 @@ import java.util.UUID; import java.util.stream.Collectors; public class Party { - private final LinkedHashMap members = new LinkedHashMap<>(); - private final List onlineMembers = new ArrayList<>(); - private static final String ONLINE_PLAYER_PREFIX = "⬤"; private static final String OFFLINE_PLAYER_PREFIX = "○"; - + private final LinkedHashMap members = new LinkedHashMap<>(); + private final List onlineMembers = new ArrayList<>(); private PartyLeader leader; private String name; private String password; @@ -37,14 +35,14 @@ public class Party { private int level; private float xp; - private ShareMode xpShareMode = ShareMode.NONE; + private ShareMode xpShareMode = ShareMode.NONE; private ShareMode itemShareMode = ShareMode.NONE; - private boolean shareLootDrops = true; - private boolean shareMiningDrops = true; - private boolean shareHerbalismDrops = true; + private boolean shareLootDrops = true; + private boolean shareMiningDrops = true; + private boolean shareHerbalismDrops = true; private boolean shareWoodcuttingDrops = true; - private boolean shareMiscDrops = true; + private boolean shareMiscDrops = true; public Party(String name) { this.name = name; @@ -81,13 +79,11 @@ public class Party { return onlineMembers; } - public List getVisibleMembers(Player player) - { + public List getVisibleMembers(Player player) { ArrayList visibleMembers = new ArrayList<>(); - for(Player p : onlineMembers) - { - if(player.canSee(p)) + for (Player p : onlineMembers) { + if (player.canSee(p)) visibleMembers.add(p); } @@ -119,22 +115,42 @@ public class Party { return name; } + public void setName(String name) { + this.name = name; + } + public PartyLeader getLeader() { return leader; } + public void setLeader(PartyLeader leader) { + this.leader = leader; + } + public String getPassword() { return password; } + public void setPassword(String password) { + this.password = password; + } + public boolean isLocked() { return locked; } + public void setLocked(boolean locked) { + this.locked = locked; + } + public Party getAlly() { return ally; } + public void setAlly(Party ally) { + this.ally = ally; + } + public List getItemShareCategories() { List shareCategories = new ArrayList<>(); @@ -147,26 +163,6 @@ public class Party { return shareCategories; } - public void setName(String name) { - this.name = name; - } - - public void setLeader(PartyLeader leader) { - this.leader = leader; - } - - public void setPassword(String password) { - this.password = password; - } - - public void setLocked(boolean locked) { - this.locked = locked; - } - - public void setAlly(Party ally) { - this.ally = ally; - } - public int getLevel() { return level; } @@ -252,22 +248,22 @@ public class Party { PartyManager.informPartyMembersLevelUp(this, levelsGained, getLevel()); } - public void setXpShareMode(ShareMode xpShareMode) { - this.xpShareMode = xpShareMode; - } - public ShareMode getXpShareMode() { return xpShareMode; } - public void setItemShareMode(ShareMode itemShareMode) { - this.itemShareMode = itemShareMode; + public void setXpShareMode(ShareMode xpShareMode) { + this.xpShareMode = xpShareMode; } public ShareMode getItemShareMode() { return itemShareMode; } + public void setItemShareMode(ShareMode itemShareMode) { + this.itemShareMode = itemShareMode; + } + public boolean sharingDrops(ItemShareType shareType) { switch (shareType) { case HERBALISM: @@ -328,6 +324,7 @@ public class Party { * Makes a formatted list of party members based on the perspective of a target player * Players that are hidden will be shown as offline (formatted in the same way) * Party leader will be formatted a specific way as well + * * @param player target player to use as POV * @return formatted list of party members from the POV of a player */ @@ -346,23 +343,21 @@ public class Party { boolean isPartyLeaderOfflineOrHidden = false; ArrayList offlineOrHiddenPartyList = new ArrayList<>(); - for(UUID onlineMember : onlineMembers) - { + for (UUID onlineMember : onlineMembers) { Player onlinePlayer = Bukkit.getPlayer(onlineMember); - if(!isNotSamePerson(player.getUniqueId(), onlineMember) || player.canSee(onlinePlayer)) - { + if (!isNotSamePerson(player.getUniqueId(), onlineMember) || player.canSee(onlinePlayer)) { visiblePartyList.add(onlineMember); } else { //Party leader and cannot be seen by this player - if(isNotSamePerson(leader.getUniqueId(), player.getUniqueId()) && onlineMember == leader.getUniqueId()) + if (isNotSamePerson(leader.getUniqueId(), player.getUniqueId()) && onlineMember == leader.getUniqueId()) isPartyLeaderOfflineOrHidden = true; offlineOrHiddenPartyList.add(onlineMember); } } - if(offlineMembers.contains(leader.getUniqueId())) + if (offlineMembers.contains(leader.getUniqueId())) isPartyLeaderOfflineOrHidden = true; //Add all the actually offline members @@ -386,23 +381,21 @@ public class Party { boolean useDisplayNames = mcMMO.getConfigManager().getConfigParty().isPartyDisplayNamesEnabled(); - if(isPartyLeaderOfflineOrHidden) - { - if(isNotSamePerson(player.getUniqueId(), leader.getUniqueId())) + if (isPartyLeaderOfflineOrHidden) { + if (isNotSamePerson(player.getUniqueId(), leader.getUniqueId())) applyOnlineAndRangeFormatting(memberList, false, false); memberList.append(ChatColor.GRAY) - .append(leader.getPlayerName()); - } - else { - if(isNotSamePerson(leader.getUniqueId(), player.getUniqueId())) + .append(leader.getPlayerName()); + } else { + if (isNotSamePerson(leader.getUniqueId(), player.getUniqueId())) applyOnlineAndRangeFormatting(memberList, true, nearbyPlayerList.contains(Bukkit.getPlayer(leader.getUniqueId()))); - if(useDisplayNames) { + if (useDisplayNames) { memberList.append(leader.getPlayerName()); } else { memberList.append(ChatColor.GOLD) - .append(Bukkit.getOfflinePlayer(leader.getUniqueId())); + .append(Bukkit.getOfflinePlayer(leader.getUniqueId())); } } @@ -410,20 +403,16 @@ public class Party { memberList.append(" "); //Now do online members - for(UUID onlinePlayerUUID : visiblePartyList) - { - if(onlinePlayerUUID == leader.getUniqueId()) + for (UUID onlinePlayerUUID : visiblePartyList) { + if (onlinePlayerUUID == leader.getUniqueId()) continue; - if(isNotSamePerson(onlinePlayerUUID, player.getUniqueId())) + if (isNotSamePerson(onlinePlayerUUID, player.getUniqueId())) applyOnlineAndRangeFormatting(memberList, true, nearbyPlayerList.contains(Bukkit.getPlayer(onlinePlayerUUID))); - if(useDisplayNames) - { + if (useDisplayNames) { memberList.append(Bukkit.getPlayer(onlinePlayerUUID).getDisplayName()); - } - else - { + } else { //Color allies green, players dark aqua memberList.append(ChatColor.GREEN) .append(Bukkit.getPlayer(onlinePlayerUUID).getName()); @@ -432,16 +421,15 @@ public class Party { memberList.append(" ").append(ChatColor.RESET); } - for(UUID offlineOrHiddenPlayer : offlineOrHiddenPartyList) - { - if(offlineOrHiddenPlayer == leader.getUniqueId()) + for (UUID offlineOrHiddenPlayer : offlineOrHiddenPartyList) { + if (offlineOrHiddenPlayer == leader.getUniqueId()) continue; applyOnlineAndRangeFormatting(memberList, false, false); memberList.append(ChatColor.GRAY) - .append(Bukkit.getOfflinePlayer(offlineOrHiddenPlayer).getName()) - .append(" ").append(ChatColor.RESET); + .append(Bukkit.getOfflinePlayer(offlineOrHiddenPlayer).getName()) + .append(" ").append(ChatColor.RESET); } @@ -476,12 +464,9 @@ public class Party { return onlinePlayerUUID != uniqueId; } - private void applyOnlineAndRangeFormatting(StringBuilder stringBuilder, boolean isVisibleOrOnline, boolean isNear) - { - if(isVisibleOrOnline) - { - if(isNear) - { + private void applyOnlineAndRangeFormatting(StringBuilder stringBuilder, boolean isVisibleOrOnline, boolean isNear) { + if (isVisibleOrOnline) { + if (isNear) { stringBuilder.append(ChatColor.GREEN); } else { stringBuilder.append(ChatColor.GRAY); diff --git a/src/main/java/com/gmail/nossr50/datatypes/party/PartyFeature.java b/src/main/java/com/gmail/nossr50/datatypes/party/PartyFeature.java index 4a5707b21..e8a67b4df 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/party/PartyFeature.java +++ b/src/main/java/com/gmail/nossr50/datatypes/party/PartyFeature.java @@ -21,7 +21,7 @@ public enum PartyFeature { public String getFeatureLockedLocaleString() { return LocaleLoader.getString("Ability.Generic.Template.Lock", LocaleLoader.getString("Party.Feature.Locked." - + StringUtils.getPrettyPartyFeatureString(this).replace(" ", ""), + + StringUtils.getPrettyPartyFeatureString(this).replace(" ", ""), PartyManager.getPartyFeatureUnlockLevel(this))); } diff --git a/src/main/java/com/gmail/nossr50/datatypes/party/PartyTeleportRecord.java b/src/main/java/com/gmail/nossr50/datatypes/party/PartyTeleportRecord.java index b3fa920c7..a6499d722 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/party/PartyTeleportRecord.java +++ b/src/main/java/com/gmail/nossr50/datatypes/party/PartyTeleportRecord.java @@ -5,9 +5,9 @@ import com.gmail.nossr50.util.Misc; import org.bukkit.entity.Player; public class PartyTeleportRecord { - private Player requestor; + private Player requestor; private boolean enabled, confirmRequired; - private int timeout, lastUse; + private int timeout, lastUse; public PartyTeleportRecord() { requestor = null; diff --git a/src/main/java/com/gmail/nossr50/datatypes/party/ShareMode.java b/src/main/java/com/gmail/nossr50/datatypes/party/ShareMode.java index 778ed08e6..33d64e51b 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/party/ShareMode.java +++ b/src/main/java/com/gmail/nossr50/datatypes/party/ShareMode.java @@ -10,12 +10,10 @@ public enum ShareMode { public static ShareMode getShareMode(String string) { try { return valueOf(string); - } - catch (IllegalArgumentException ex) { + } catch (IllegalArgumentException ex) { if (string.equalsIgnoreCase("even")) { return EQUAL; - } - else if (CommandUtils.shouldDisableToggle(string)) { + } else if (CommandUtils.shouldDisableToggle(string)) { return NONE; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java b/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java index dd44c5386..c470ff191 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java +++ b/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java @@ -64,41 +64,32 @@ import java.util.Set; import java.util.UUID; public class McMMOPlayer { - private Player player; - private PlayerProfile profile; - private final Map skillManagers = new HashMap<>(); + private final Map abilityMode = new HashMap<>(); + private final Map abilityInformed = new HashMap<>(); + private final Map toolMode = new HashMap<>(); + private final FixedMetadataValue playerMetadata; + private Player player; + private PlayerProfile profile; private ExperienceBarManager experienceBarManager; - - private Party party; - private Party invite; - private Party allianceInvite; - private int itemShareModifier; - + private Party party; + private Party invite; + private Party allianceInvite; + private int itemShareModifier; private PartyTeleportRecord ptpRecord; - private boolean partyChatMode; private boolean adminChatMode; private boolean displaySkillNotifications = true; - private boolean abilityUse = true; private boolean godMode; private boolean chatSpy = false; //Off by default - - private final Map abilityMode = new HashMap<>(); - private final Map abilityInformed = new HashMap<>(); - - private final Map toolMode = new HashMap<>(); - private int recentlyHurt; private int respawnATS; private long teleportATS; private long databaseATS; //private int chimeraWingLastUse; private Location teleportCommence; - private boolean isUsingUnarmed; - private final FixedMetadataValue playerMetadata; public McMMOPlayer(Player player, PlayerProfile profile) { String playerName = player.getName(); @@ -121,8 +112,7 @@ public class McMMOPlayer { for (PrimarySkillType primarySkillType : PrimarySkillType.values()) { skillManagers.put(primarySkillType, primarySkillType.getManagerClass().getConstructor(McMMOPlayer.class).newInstance(this)); } - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); mcMMO.p.getPluginLoader().disablePlugin(mcMMO.p); } @@ -144,37 +134,33 @@ public class McMMOPlayer { experienceBarManager.hideExperienceBar(primarySkillType); }*/ - public void processPostXpEvent(XPGainReason xpGainReason, PrimarySkillType primarySkillType, Plugin plugin, XPGainSource xpGainSource) - { + public void processPostXpEvent(XPGainReason xpGainReason, PrimarySkillType primarySkillType, Plugin plugin, XPGainSource xpGainSource) { //Updates from Party sources - if(xpGainSource == XPGainSource.PARTY_MEMBERS && !ExperienceConfig.getInstance().isPartyExperienceBarsEnabled()) + if (xpGainSource == XPGainSource.PARTY_MEMBERS && !ExperienceConfig.getInstance().isPartyExperienceBarsEnabled()) return; //Updates from passive sources (Alchemy, Smelting, etc...) - if(xpGainSource == XPGainSource.PASSIVE && !ExperienceConfig.getInstance().isPassiveGainsExperienceBarsEnabled()) + if (xpGainSource == XPGainSource.PASSIVE && !ExperienceConfig.getInstance().isPassiveGainsExperienceBarsEnabled()) return; updateXPBar(primarySkillType, plugin); } - public void processUnlockNotifications(mcMMO plugin, PrimarySkillType primarySkillType, int skillLevel) - { + public void processUnlockNotifications(mcMMO plugin, PrimarySkillType primarySkillType, int skillLevel) { RankUtils.executeSkillUnlockNotifications(plugin, this, primarySkillType, skillLevel); } - public void updateXPBar(PrimarySkillType primarySkillType, Plugin plugin) - { + public void updateXPBar(PrimarySkillType primarySkillType, Plugin plugin) { //Skill Unlock Notifications - if(primarySkillType.isChildSkill()) + if (primarySkillType.isChildSkill()) return; //XP BAR UPDATES experienceBarManager.updateExperienceBar(primarySkillType, plugin); } - public double getProgressInCurrentSkillLevel(PrimarySkillType primarySkillType) - { + public double getProgressInCurrentSkillLevel(PrimarySkillType primarySkillType) { double currentXP = profile.getSkillXpLevel(primarySkillType); double maxXP = profile.getXpToLevel(primarySkillType); @@ -268,7 +254,7 @@ public class McMMOPlayer { /** * Set the mode of an ability. * - * @param ability The ability to check + * @param ability The ability to check * @param isActive True if the ability is active, false otherwise */ public void setAbilityMode(SuperAbilityType ability, boolean isActive) { @@ -288,7 +274,7 @@ public class McMMOPlayer { /** * Set the informed state of an ability. * - * @param ability The ability to check + * @param ability The ability to check * @param isInformed True if the ability is informed, false otherwise */ public void setAbilityInformed(SuperAbilityType ability, boolean isInformed) { @@ -329,7 +315,7 @@ public class McMMOPlayer { /** * Set the current prep mode of a tool. * - * @param tool Tool to set the mode for + * @param tool Tool to set the mode for * @param isPrepared true if the tool should be prepped, false otherwise */ public void setToolPreparationMode(ToolType tool, boolean isPrepared) { @@ -420,9 +406,13 @@ public class McMMOPlayer { * Party Chat Spy */ - public boolean isPartyChatSpying() { return chatSpy; } + public boolean isPartyChatSpying() { + return chatSpy; + } - public void togglePartyChatSpying() { chatSpy = !chatSpy;} + public void togglePartyChatSpying() { + chatSpy = !chatSpy; + } /* * Skill notifications @@ -457,7 +447,7 @@ public class McMMOPlayer { * Begins an experience gain. The amount will be affected by skill modifiers, global rate, perks, and may be shared with the party * * @param skill Skill being used - * @param xp Experience amount to process + * @param xp Experience amount to process */ public void beginXpGain(PrimarySkillType skill, float xp, XPGainReason xpGainReason, XPGainSource xpGainSource) { Validate.isTrue(xp >= 0.0, "XP gained should be greater than or equal to zero."); @@ -491,7 +481,7 @@ public class McMMOPlayer { * Begins an experience gain. The amount will be affected by skill modifiers, global rate and perks * * @param skill Skill being used - * @param xp Experience amount to process + * @param xp Experience amount to process */ public void beginUnsharedXpGain(PrimarySkillType skill, float xp, XPGainReason xpGainReason, XPGainSource xpGainSource) { applyXpGain(skill, modifyXpGain(skill, xp), xpGainReason, xpGainSource); @@ -509,7 +499,7 @@ public class McMMOPlayer { * Applies an experience gain * * @param primarySkillType Skill being used - * @param xp Experience amount to add + * @param xp Experience amount to add */ public void applyXpGain(PrimarySkillType primarySkillType, float xp, XPGainReason xpGainReason, XPGainSource xpGainSource) { if (!primarySkillType.getPermissions(player)) { @@ -603,26 +593,26 @@ public class McMMOPlayer { } } - public void setPartyInvite(Party invite) { - this.invite = invite; - } - public Party getPartyInvite() { return invite; } + public void setPartyInvite(Party invite) { + this.invite = invite; + } + public boolean hasPartyInvite() { return (invite != null); } - public void setParty(Party party) { - this.party = party; - } - public Party getParty() { return party; } + public void setParty(Party party) { + this.party = party; + } + public boolean inParty() { return (party != null); } @@ -639,14 +629,14 @@ public class McMMOPlayer { return ptpRecord; } - public void setPartyAllianceInvite(Party allianceInvite) { - this.allianceInvite = allianceInvite; - } - public Party getPartyAllianceInvite() { return allianceInvite; } + public void setPartyAllianceInvite(Party allianceInvite) { + this.allianceInvite = allianceInvite; + } + public boolean hasPartyAllianceInvite() { return (allianceInvite != null); } @@ -743,13 +733,13 @@ public class McMMOPlayer { * Modifies an experience gain using skill modifiers, global rate and perks * * @param primarySkillType Skill being used - * @param xp Experience amount to process + * @param xp Experience amount to process * @return Modified experience */ private float modifyXpGain(PrimarySkillType primarySkillType, float xp) { if (player.getGameMode() == GameMode.CREATIVE || ((primarySkillType.getMaxLevel() <= getSkillLevel(primarySkillType)) - && mcMMO.getPlayerLevelingSettings().isLevelCapEnabled(primarySkillType)) + && mcMMO.getPlayerLevelingSettings().isLevelCapEnabled(primarySkillType)) || (mcMMO.getPlayerLevelingSettings().getConfigSectionLevelCaps().getPowerLevel().getLevelCap() <= getPowerLevel())) { return 0; } @@ -769,7 +759,7 @@ public class McMMOPlayer { public void checkGodMode() { if (godMode && !Permissions.mcgod(player) - || godMode && WorldBlacklist.isWorldBlacklisted(player.getWorld())) { + || godMode && WorldBlacklist.isWorldBlacklisted(player.getWorld())) { toggleGodMode(); player.sendMessage(LocaleLoader.getString("Commands.GodMode.Forbidden")); } @@ -798,8 +788,7 @@ public class McMMOPlayer { //TODO: This is hacky and temporary solution until skills are move to the new system //Potential problems with this include skills with two super abilities (ie mining) - if(!skill.isSuperAbilityUnlocked(getPlayer())) - { + if (!skill.isSuperAbilityUnlocked(getPlayer())) { int diff = RankUtils.getSuperAbilityUnlockRequirement(skill.getAbility()) - getSkillLevel(skill); //Inform the player they are not yet skilled enough @@ -833,8 +822,7 @@ public class McMMOPlayer { int ticks; //Ability cap of 0 or below means no cap - if(abilityLengthCap > 0) - { + if (abilityLengthCap > 0) { ticks = PerksUtils.handleActivationPerks(player, 2 + (Math.min(abilityLengthCap, getSkillLevel(skill)) / abilityLengthVar), ability.getMaxLength()); } else { ticks = PerksUtils.handleActivationPerks(player, 2 + (getSkillLevel(skill) / abilityLengthVar), ability.getMaxLength()); @@ -918,7 +906,6 @@ public class McMMOPlayer { * Calculate the time remaining until the ability's cooldown expires. * * @param ability SuperAbilityType whose cooldown to check - * * @return the number of seconds remaining before the cooldown expires */ public int calculateTimeRemaining(SuperAbilityType ability) { @@ -1000,7 +987,7 @@ public class McMMOPlayer { UserManager.remove(thisPlayer); - if(mcMMO.getScoreboardSettings().getScoreboardsEnabled()) + if (mcMMO.getScoreboardSettings().getScoreboardsEnabled()) ScoreboardManager.teardownPlayer(thisPlayer); if (inParty()) { diff --git a/src/main/java/com/gmail/nossr50/datatypes/player/PlayerProfile.java b/src/main/java/com/gmail/nossr50/datatypes/player/PlayerProfile.java index d79544c32..921fbe1cc 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/player/PlayerProfile.java +++ b/src/main/java/com/gmail/nossr50/datatypes/player/PlayerProfile.java @@ -20,21 +20,18 @@ import java.util.concurrent.DelayQueue; public class PlayerProfile { private final String playerName; + /* Skill Data */ + private final Map skills = new HashMap<>(); // Skill & Level + private final Map skillsXp = new HashMap<>(); // Skill & XP + private final Map abilityDATS = new HashMap<>(); // Ability & Cooldown + private final Map uniquePlayerData = new HashMap<>(); //Misc data that doesn't fit into other categories (chimaera wing, etc..) private UUID uuid; private boolean loaded; private volatile boolean changed; - /* HUDs */ private MobHealthbarType mobHealthbarType; private int scoreboardTipsShown; private int saveAttempts = 0; - - /* Skill Data */ - private final Map skills = new HashMap<>(); // Skill & Level - private final Map skillsXp = new HashMap<>(); // Skill & XP - private final Map abilityDATS = new HashMap<>(); // Ability & Cooldown - private final Map uniquePlayerData = new HashMap<>(); //Misc data that doesn't fit into other categories (chimaera wing, etc..) - // Store previous XP gains for diminished returns private DelayQueue gainedSkillsXp = new DelayQueue(); private HashMap rollingSkillsXp = new HashMap(); @@ -110,20 +107,18 @@ public class PlayerProfile { if (changed) { mcMMO.p.getLogger().severe("PlayerProfile saving failed for player: " + playerName + " " + uuid); - if(saveAttempts > 0) - { - mcMMO.p.getLogger().severe("Attempted to save profile for player "+getPlayerName() - + " resulted in failure. "+saveAttempts+" have been made so far."); + if (saveAttempts > 0) { + mcMMO.p.getLogger().severe("Attempted to save profile for player " + getPlayerName() + + " resulted in failure. " + saveAttempts + " have been made so far."); } - if(saveAttempts < 10) - { + if (saveAttempts < 10) { saveAttempts++; scheduleAsyncSaveDelay(); return; } else { mcMMO.p.getLogger().severe("mcMMO has failed to save the profile for " - +getPlayerName()+" numerous times." + + + getPlayerName() + " numerous times." + " mcMMO will now stop attempting to save this profile." + " Check your console for errors and inspect your DB for issues."); } @@ -183,7 +178,9 @@ public class PlayerProfile { * Cooldowns */ - public int getChimaerWingDATS() { return uniquePlayerData.get(UniqueDataType.CHIMAERA_WING_DATS);} + public int getChimaerWingDATS() { + return uniquePlayerData.get(UniqueDataType.CHIMAERA_WING_DATS); + } protected void setChimaeraWingDATS(int DATS) { changed = true; @@ -195,7 +192,9 @@ public class PlayerProfile { uniquePlayerData.put(uniqueDataType, newData); } - public long getUniqueData(UniqueDataType uniqueDataType) { return uniquePlayerData.get(uniqueDataType); } + public long getUniqueData(UniqueDataType uniqueDataType) { + return uniquePlayerData.get(uniqueDataType); + } /** * Get the current deactivation timestamp of an ability. @@ -211,7 +210,7 @@ public class PlayerProfile { * Set the current deactivation timestamp of an ability. * * @param ability The {@link SuperAbilityType} to set the DATS for - * @param DATS the DATS of the ability + * @param DATS the DATS of the ability */ protected void setAbilityDATS(SuperAbilityType ability, long DATS) { changed = true; @@ -271,7 +270,7 @@ public class PlayerProfile { * Remove Xp from a skill. * * @param skill Type of skill to modify - * @param xp Amount of xp to remove + * @param xp Amount of xp to remove */ public void removeXp(PrimarySkillType skill, int xp) { if (skill.isChildSkill()) { @@ -307,7 +306,7 @@ public class PlayerProfile { changed = true; //Don't allow levels to be negative - if(level < 0) + if (level < 0) level = 0; skills.put(skill, level); @@ -317,7 +316,7 @@ public class PlayerProfile { /** * Add levels to a skill. * - * @param skill Type of skill to add levels to + * @param skill Type of skill to add levels to * @param levels Number of levels to add */ public void addLevels(PrimarySkillType skill, int levels) { @@ -328,7 +327,7 @@ public class PlayerProfile { * Add Experience to a skill. * * @param skill Type of skill to add experience to - * @param xp Number of experience to add + * @param xp Number of experience to add */ public void addXp(PrimarySkillType skill, float xp) { changed = true; @@ -340,8 +339,7 @@ public class PlayerProfile { for (PrimarySkillType parentSkill : parentSkills) { skillsXp.put(parentSkill, skillsXp.get(parentSkill) + dividedXP); } - } - else { + } else { skillsXp.put(skill, skillsXp.get(skill) + xp); } } @@ -367,7 +365,7 @@ public class PlayerProfile { * This is used for diminished XP returns * * @param primarySkillType Skill being used - * @param xp Experience amount to add + * @param xp Experience amount to add */ public void registerXpGain(PrimarySkillType primarySkillType, float xp) { gainedSkillsXp.add(new SkillXpGain(primarySkillType, xp)); @@ -403,7 +401,7 @@ public class PlayerProfile { int sum = 0; for (PrimarySkillType parent : parents) { - if(mcMMO.getPlayerLevelingSettings().isLevelCapEnabled(parent)) + if (mcMMO.getPlayerLevelingSettings().isLevelCapEnabled(parent)) sum += Math.min(getSkillLevel(parent), parent.getMaxLevel()); else sum += getSkillLevel(parent); diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/ModConfigType.java b/src/main/java/com/gmail/nossr50/datatypes/skills/ModConfigType.java index df951d783..e6f0da0c5 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/ModConfigType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/ModConfigType.java @@ -9,11 +9,9 @@ public enum ModConfigType { public static ModConfigType getModConfigType(String materialName) { if (materialName.contains("HELM") || (materialName.contains("CHEST") && !materialName.contains("CHESTNUT")) || materialName.contains("LEGS") || materialName.contains("LEGGINGS") || materialName.contains("BOOT")) { return ARMOR; - } - else if (materialName.contains("PICKAXE") || materialName.contains("AXE") || (materialName.contains("BOW") && !materialName.contains("BOWL")) || materialName.contains("HOE") || materialName.contains("SHOVEL") || materialName.contains("SWORD")) { + } else if (materialName.contains("PICKAXE") || materialName.contains("AXE") || (materialName.contains("BOW") && !materialName.contains("BOWL")) || materialName.contains("HOE") || materialName.contains("SHOVEL") || materialName.contains("SWORD")) { return TOOLS; - } - else if (materialName.contains("LOG") || materialName.contains("LEAVES") || materialName.contains("FLOWER") || materialName.contains("PLANT") || materialName.contains("CROP") || materialName.contains("ORE") || materialName.contains("DIRT") || materialName.contains("SAND") || materialName.contains("GRASS")) { + } else if (materialName.contains("LOG") || materialName.contains("LEAVES") || materialName.contains("FLOWER") || materialName.contains("PLANT") || materialName.contains("CROP") || materialName.contains("ORE") || materialName.contains("DIRT") || materialName.contains("SAND") || materialName.contains("GRASS")) { return BLOCKS; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/PrimarySkillType.java b/src/main/java/com/gmail/nossr50/datatypes/skills/PrimarySkillType.java index 31d2b7750..48213499b 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/PrimarySkillType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/PrimarySkillType.java @@ -65,18 +65,10 @@ public enum PrimarySkillType { WOODCUTTING(WoodcuttingManager.class, Color.OLIVE, SuperAbilityType.TREE_FELLER, ToolType.AXE, ImmutableList.of(SubSkillType.WOODCUTTING_LEAF_BLOWER, SubSkillType.WOODCUTTING_TREE_FELLER, SubSkillType.WOODCUTTING_HARVEST_LUMBER)); - private Class managerClass; - private Color runescapeColor; - private SuperAbilityType ability; - private ToolType tool; - private List subSkillTypes; - public static final List SKILL_NAMES; public static final List SUBSKILL_NAMES; - public static final List CHILD_SKILLS; public static final List NON_CHILD_SKILLS; - public static final List COMBAT_SKILLS = ImmutableList.of(ARCHERY, AXES, SWORDS, TAMING, UNARMED); public static final List GATHERING_SKILLS = ImmutableList.of(EXCAVATION, FISHING, HERBALISM, MINING, WOODCUTTING); public static final List MISC_SKILLS = ImmutableList.of(ACROBATICS, ALCHEMY, REPAIR, SALVAGE, SMELTING); @@ -90,13 +82,11 @@ public enum PrimarySkillType { for (PrimarySkillType skill : values()) { if (skill.isChildSkill()) { childSkills.add(skill); - } - else { + } else { nonChildSkills.add(skill); } - for(SubSkillType subSkillType : skill.subSkillTypes) - { + for (SubSkillType subSkillType : skill.subSkillTypes) { subSkillNames.add(subSkillType.getNiceNameNoSpaces(subSkillType)); } names.add(skill.getName()); @@ -110,6 +100,12 @@ public enum PrimarySkillType { NON_CHILD_SKILLS = ImmutableList.copyOf(nonChildSkills); } + private Class managerClass; + private Color runescapeColor; + private SuperAbilityType ability; + private ToolType tool; + private List subSkillTypes; + PrimarySkillType(Class managerClass, Color runescapeColor, List subSkillTypes) { this(managerClass, runescapeColor, null, null, subSkillTypes); } @@ -122,65 +118,6 @@ public enum PrimarySkillType { this.subSkillTypes = subSkillTypes; } - public Class getManagerClass() { - return managerClass; - } - - public SuperAbilityType getAbility() { - return ability; - } - - /** - * Get the max level of this skill. - * - * @return the max level of this skill - */ - public int getMaxLevel() { - return mcMMO.getPlayerLevelingSettings().getLevelCap(this); - } - - public boolean isSuperAbilityUnlocked(Player player) { return RankUtils.getRank(player, getAbility().getSubSkillTypeDefinition()) >= 1; } - - public boolean getPVPEnabled() { - return MainConfig.getInstance().getPVPEnabled(this); - } - - public boolean getPVEEnabled() { - return MainConfig.getInstance().getPVEEnabled(this); - } - - /*public boolean getDoubleDropsDisabled() { - return MainConfig.getInstance().getDoubleDropsDisabled(this); - }*/ - - public boolean getHardcoreStatLossEnabled() { - return MainConfig.getInstance().getHardcoreStatLossEnabled(this); - } - - /*public void setHardcoreStatLossEnabled(boolean enable) { - MainConfig.getInstance().setHardcoreStatLossEnabled(this, enable); - }*/ - - public boolean getHardcoreVampirismEnabled() { - return MainConfig.getInstance().getHardcoreVampirismEnabled(this); - } - - /*public void setHardcoreVampirismEnabled(boolean enable) { - MainConfig.getInstance().setHardcoreVampirismEnabled(this, enable); - }*/ - - public ToolType getTool() { - return tool; - } - - public List getSkillAbilities() { - return subSkillTypes; - } - - public double getXpModifier() { - return ExperienceConfig.getInstance().getFormulaSkillModifier(this); - } - public static PrimarySkillType getSkill(String skillName) { if (!mcMMO.getConfigManager().getConfigLanguage().getTargetLanguage().equalsIgnoreCase("en_US")) { for (PrimarySkillType type : values()) { @@ -203,18 +140,6 @@ public enum PrimarySkillType { return null; } - // TODO: This is a little "hacky", we probably need to add something to distinguish child skills in the enum, or to use another enum for them - public boolean isChildSkill() { - switch (this) { - case SALVAGE: - case SMELTING: - return true; - - default: - return false; - } - } - public static PrimarySkillType bySecondaryAbility(SubSkillType subSkillType) { for (PrimarySkillType type : values()) { if (type.getSkillAbilities().contains(subSkillType)) { @@ -234,6 +159,79 @@ public enum PrimarySkillType { return null; } + public Class getManagerClass() { + return managerClass; + } + + public SuperAbilityType getAbility() { + return ability; + } + + /** + * Get the max level of this skill. + * + * @return the max level of this skill + */ + public int getMaxLevel() { + return mcMMO.getPlayerLevelingSettings().getLevelCap(this); + } + + /*public boolean getDoubleDropsDisabled() { + return MainConfig.getInstance().getDoubleDropsDisabled(this); + }*/ + + public boolean isSuperAbilityUnlocked(Player player) { + return RankUtils.getRank(player, getAbility().getSubSkillTypeDefinition()) >= 1; + } + + /*public void setHardcoreStatLossEnabled(boolean enable) { + MainConfig.getInstance().setHardcoreStatLossEnabled(this, enable); + }*/ + + public boolean getPVPEnabled() { + return MainConfig.getInstance().getPVPEnabled(this); + } + + /*public void setHardcoreVampirismEnabled(boolean enable) { + MainConfig.getInstance().setHardcoreVampirismEnabled(this, enable); + }*/ + + public boolean getPVEEnabled() { + return MainConfig.getInstance().getPVEEnabled(this); + } + + public boolean getHardcoreStatLossEnabled() { + return MainConfig.getInstance().getHardcoreStatLossEnabled(this); + } + + public boolean getHardcoreVampirismEnabled() { + return MainConfig.getInstance().getHardcoreVampirismEnabled(this); + } + + public ToolType getTool() { + return tool; + } + + public List getSkillAbilities() { + return subSkillTypes; + } + + public double getXpModifier() { + return ExperienceConfig.getInstance().getFormulaSkillModifier(this); + } + + // TODO: This is a little "hacky", we probably need to add something to distinguish child skills in the enum, or to use another enum for them + public boolean isChildSkill() { + switch (this) { + case SALVAGE: + case SMELTING: + return true; + + default: + return false; + } + } + public String getName() { //return MainConfig.getInstance().getLocale().equalsIgnoreCase("en_US") ? StringUtils.getCapitalized(this.toString()) : StringUtils.getCapitalized(LocaleLoader.getString(StringUtils.getCapitalized(this.toString()) + ".SkillName")); return StringUtils.getCapitalized(LocaleLoader.getString(StringUtils.getCapitalized(this.toString()) + ".SkillName")); diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillType.java b/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillType.java index 12b1aae00..c57b7a34d 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillType.java @@ -99,11 +99,11 @@ public enum SubSkillType { UNARMED_UNARMED_LIMIT_BREAK(10), /* Woodcutting */ -/* WOODCUTTING_BARK_SURGEON(3),*/ + /* WOODCUTTING_BARK_SURGEON(3),*/ WOODCUTTING_HARVEST_LUMBER(1), WOODCUTTING_LEAF_BLOWER(1), -/* WOODCUTTING_NATURES_BOUNTY(3), - WOODCUTTING_SPLINTER(3),*/ + /* WOODCUTTING_NATURES_BOUNTY(3), + WOODCUTTING_SPLINTER(3),*/ WOODCUTTING_TREE_FELLER(1); private final int numRanks; @@ -111,32 +111,34 @@ public enum SubSkillType { /** * If our SubSkillType has more than 1 rank define it + * * @param numRanks The number of ranks our SubSkillType has */ - SubSkillType(int numRanks) - { + SubSkillType(int numRanks) { this.numRanks = numRanks; } - SubSkillType() - { + SubSkillType() { this.numRanks = 0; } - public int getNumRanks() - { + public int getNumRanks() { return numRanks; } /** * !!! This relies on the immutable lists in PrimarySkillType being populated !!! * If we add skills, those immutable lists need to be updated + * * @return */ - public PrimarySkillType getParentSkill() { return PrimarySkillType.bySecondaryAbility(this); } + public PrimarySkillType getParentSkill() { + return PrimarySkillType.bySecondaryAbility(this); + } /** * Returns the root address for this skill in the advanced.yml file + * * @return the root address for this skill in advanced.yml */ public String[] getAdvConfigAddress() { @@ -147,6 +149,7 @@ public enum SubSkillType { /** * Returns the root address for this skill in the rankskills.yml file + * * @return the root address for this skill in rankskills.yml */ public String[] getRankConfigAddress() { @@ -157,16 +160,17 @@ public enum SubSkillType { /** * Get the string representation of the permission node for this subskill + * * @return the permission node for this subskill */ - public String getPermissionNodeAddress() - { + public String getPermissionNodeAddress() { //TODO: This could be optimized return "mcmmo.ability." + getParentSkill().toString().toLowerCase() + "." + getConfigName(toString()).toLowerCase(); } /** * Returns the name of the skill as it is used in advanced.yml and other config files + * * @return the yaml identifier for this skill */ private String getConfigName(String subSkillName) { @@ -190,12 +194,10 @@ public enum SubSkillType { * Split the string up so we can capitalize each part */ String subskillNameWithoutPrefix = subSkillName.substring(subStringIndex); - if(subskillNameWithoutPrefix.contains("_")) - { + if (subskillNameWithoutPrefix.contains("_")) { String[] splitStrings = subskillNameWithoutPrefix.split("_"); - for(String string : splitStrings) - { + for (String string : splitStrings) { endResult.append(StringUtils.getCapitalized(string)); } } else { @@ -216,13 +218,11 @@ public enum SubSkillType { * Split the string up so we can capitalize each part */ String subskillNameWithoutPrefix = subSkillName.substring(subStringIndex); - if(subskillNameWithoutPrefix.contains("_")) - { + if (subskillNameWithoutPrefix.contains("_")) { String[] splitStrings = subskillNameWithoutPrefix.split("_"); - for(int i = 0; i < splitStrings.length; i++) - { - if(i+1 >= splitStrings.length) + for (int i = 0; i < splitStrings.length; i++) { + if (i + 1 >= splitStrings.length) endResult.append(StringUtils.getCapitalized(splitStrings[i])); else { endResult.append(StringUtils.getCapitalized(splitStrings[i])); @@ -238,25 +238,26 @@ public enum SubSkillType { /** * Returns the name of the parent skill from the Locale file + * * @return The parent skill as defined in the locale */ - public String getParentNiceNameLocale() - { - return LocaleLoader.getString(StringUtils.getCapitalized(getParentSkill().toString())+".SkillName"); + public String getParentNiceNameLocale() { + return LocaleLoader.getString(StringUtils.getCapitalized(getParentSkill().toString()) + ".SkillName"); } /** * Gets the "nice" name of the subskill without spaces + * * @param subSkillType target subskill * @return the "nice" name without spaces */ - public String getNiceNameNoSpaces(SubSkillType subSkillType) - { + public String getNiceNameNoSpaces(SubSkillType subSkillType) { return getConfigName(subSkillType.toString()); } /** * This finds the substring index for our SubSkillType's name after its parent name prefix + * * @param subSkillName The name to process * @return The value of the substring index after our parent's prefix */ @@ -275,35 +276,40 @@ public enum SubSkillType { return subStringIndex; } - public String getLocaleKeyRoot() - { - return StringUtils.getCapitalized(getParentSkill().toString())+".SubSkill."+getConfigName(toString()); + public String getLocaleKeyRoot() { + return StringUtils.getCapitalized(getParentSkill().toString()) + ".SubSkill." + getConfigName(toString()); } - public String getLocaleName() - { + public String getLocaleName() { return getFromLocaleSubAddress(".Name"); } - public String getLocaleDescription() - { + public String getLocaleDescription() { return getFromLocaleSubAddress(".Description"); } - public String getLocaleStatDescription() { return getFromLocaleSubAddress(".Stat"); } - public String getLocaleKeyStatDescription() { return getLocaleKeyFromSubAddress(".Stat"); } + public String getLocaleStatDescription() { + return getFromLocaleSubAddress(".Stat"); + } - public String getLocaleStatExtraDescription() { return getFromLocaleSubAddress(".Stat.Extra"); } - public String getLocaleKeyStatExtraDescription() { return getLocaleKeyFromSubAddress(".Stat.Extra"); } + public String getLocaleKeyStatDescription() { + return getLocaleKeyFromSubAddress(".Stat"); + } - public String getLocaleStat(String... vars) - { + public String getLocaleStatExtraDescription() { + return getFromLocaleSubAddress(".Stat.Extra"); + } + + public String getLocaleKeyStatExtraDescription() { + return getLocaleKeyFromSubAddress(".Stat.Extra"); + } + + public String getLocaleStat(String... vars) { String statMsg = LocaleLoader.getString("Ability.Generic.Template", (Object[]) vars); return statMsg; } - public String getCustomLocaleStat(String... vars) - { + public String getCustomLocaleStat(String... vars) { String statMsg = LocaleLoader.getString("Ability.Generic.Template.Custom", (Object[]) vars); return statMsg; } @@ -312,8 +318,7 @@ public enum SubSkillType { return LocaleLoader.getString(getLocaleKeyRoot() + s); } - private String getLocaleKeyFromSubAddress(String s) - { + private String getLocaleKeyFromSubAddress(String s) { return getLocaleKeyRoot() + s; } } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/SuperAbilityType.java b/src/main/java/com/gmail/nossr50/datatypes/skills/SuperAbilityType.java index ad2d17dc7..438b98818 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/SuperAbilityType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/SuperAbilityType.java @@ -74,14 +74,14 @@ public enum SuperAbilityType { * This is a bit of a band-aid fix until the new skill system is in place */ static { - BERSERK.subSkillTypeDefinition = SubSkillType.UNARMED_BERSERK; - SUPER_BREAKER.subSkillTypeDefinition = SubSkillType.MINING_SUPER_BREAKER; - GIGA_DRILL_BREAKER.subSkillTypeDefinition = SubSkillType.EXCAVATION_GIGA_DRILL_BREAKER; - GREEN_TERRA.subSkillTypeDefinition = SubSkillType.HERBALISM_GREEN_TERRA; - SKULL_SPLITTER.subSkillTypeDefinition = SubSkillType.AXES_SKULL_SPLITTER; - TREE_FELLER.subSkillTypeDefinition = SubSkillType.WOODCUTTING_TREE_FELLER; - SERRATED_STRIKES.subSkillTypeDefinition = SubSkillType.SWORDS_SERRATED_STRIKES; - BLAST_MINING.subSkillTypeDefinition = SubSkillType.MINING_BLAST_MINING; + BERSERK.subSkillTypeDefinition = SubSkillType.UNARMED_BERSERK; + SUPER_BREAKER.subSkillTypeDefinition = SubSkillType.MINING_SUPER_BREAKER; + GIGA_DRILL_BREAKER.subSkillTypeDefinition = SubSkillType.EXCAVATION_GIGA_DRILL_BREAKER; + GREEN_TERRA.subSkillTypeDefinition = SubSkillType.HERBALISM_GREEN_TERRA; + SKULL_SPLITTER.subSkillTypeDefinition = SubSkillType.AXES_SKULL_SPLITTER; + TREE_FELLER.subSkillTypeDefinition = SubSkillType.WOODCUTTING_TREE_FELLER; + SERRATED_STRIKES.subSkillTypeDefinition = SubSkillType.SWORDS_SERRATED_STRIKES; + BLAST_MINING.subSkillTypeDefinition = SubSkillType.MINING_BLAST_MINING; } private String abilityOn; @@ -219,6 +219,7 @@ public enum SuperAbilityType { /** * Grabs the associated SubSkillType definition for this SuperAbilityType + * * @return the matching SubSkillType definition for this SuperAbilityType */ public SubSkillType getSubSkillTypeDefinition() { diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java index 1f522679a..06a123981 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java @@ -54,7 +54,7 @@ public class AlchemyPotion { meta.addCustomEffect(effect, true); } } - + if (this.getColor() != null) { meta.setColor(this.getColor()); } @@ -106,11 +106,11 @@ public class AlchemyPotion { public Color getColor() { return color; } - + public void setColor(Color color) { this.color = color; } - + public Map getChildren() { return children; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java index fe2778eed..95d1f7dd0 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java @@ -20,10 +20,6 @@ public enum PotionStage { this.numerical = numerical; } - public int toNumerical() { - return numerical; - } - private static PotionStage getPotionStageNumerical(int numerical) { for (PotionStage potionStage : values()) { if (numerical >= potionStage.toNumerical()) { @@ -59,12 +55,12 @@ public enum PotionStage { } // Check if potion has a glowstone dust amplifier - // Else check if the potion has a custom effect with an amplifier added by mcMMO + // Else check if the potion has a custom effect with an amplifier added by mcMMO if (data.isUpgraded()) { stage++; - } else if(!effects.isEmpty()) { - for (PotionEffect effect : effects){ - if(effect.getAmplifier() > 0){ + } else if (!effects.isEmpty()) { + for (PotionEffect effect : effects) { + if (effect.getAmplifier() > 0) { stage++; break; } @@ -83,4 +79,8 @@ public enum PotionStage { return PotionStage.getPotionStageNumerical(stage); } + + public int toNumerical() { + return numerical; + } } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/interfaces/ChildSkill.java b/src/main/java/com/gmail/nossr50/datatypes/skills/interfaces/ChildSkill.java index 0bfee0108..603bffa03 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/interfaces/ChildSkill.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/interfaces/ChildSkill.java @@ -5,6 +5,7 @@ import com.gmail.nossr50.datatypes.skills.PrimarySkillType; public interface ChildSkill extends Skill { /** * Get's the other parent for this Skill + * * @return the other parent */ PrimarySkillType getSecondParent(); diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/interfaces/CoreSkill.java b/src/main/java/com/gmail/nossr50/datatypes/skills/interfaces/CoreSkill.java index 51d4913ce..38ba10458 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/interfaces/CoreSkill.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/interfaces/CoreSkill.java @@ -11,6 +11,7 @@ import com.gmail.nossr50.datatypes.skills.SubSkillType; public interface CoreSkill { /** * Gets the associated SubSkillType for this subskill + * * @return the associated SubSkillType ENUM definition */ SubSkillType getSubSkillType(); diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/interfaces/Localized.java b/src/main/java/com/gmail/nossr50/datatypes/skills/interfaces/Localized.java index 468e19c1d..c74a60daf 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/interfaces/Localized.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/interfaces/Localized.java @@ -7,12 +7,14 @@ package com.gmail.nossr50.datatypes.skills.interfaces; public interface Localized { /** * The translated name for this locale + * * @return the translated name for this locale */ String getLocaleName(); /** * The translated name for this subskill description + * * @return */ String getLocaleDescription(); diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/interfaces/Skill.java b/src/main/java/com/gmail/nossr50/datatypes/skills/interfaces/Skill.java index 68cf7180e..280960c3c 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/interfaces/Skill.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/interfaces/Skill.java @@ -5,12 +5,14 @@ import com.gmail.nossr50.datatypes.skills.PrimarySkillType; public interface Skill { /** * The primary skill + * * @return this primary skill */ PrimarySkillType getPrimarySkill(); /** * Returns the key name used for this skill in conjunction with config files + * * @return config file key name */ String getPrimaryKeyName(); diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/interfaces/Toolable.java b/src/main/java/com/gmail/nossr50/datatypes/skills/interfaces/Toolable.java index 7b817bea1..1f5834b78 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/interfaces/Toolable.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/interfaces/Toolable.java @@ -8,12 +8,14 @@ public interface Toolable { /** * Whether or not this Skill requires a tool * Not all skills will require a tool + * * @return true if tool is required */ - boolean requiresTool(); + boolean requiresTool(); /** * The tools associated with this Skill + * * @return the tools */ Collection getTools(); diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/progression/Progression.java b/src/main/java/com/gmail/nossr50/datatypes/skills/progression/Progression.java index 30f00e0aa..191db9854 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/progression/Progression.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/progression/Progression.java @@ -6,6 +6,7 @@ import org.bukkit.event.Event; public interface Progression { /** * The interaction vector for gaining XP + * * @return the interaction vector for gaining XP */ InteractType getXpGainInteractType(); diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/properties/MaxBonusLevel.java b/src/main/java/com/gmail/nossr50/datatypes/skills/properties/MaxBonusLevel.java index 5f028c4e7..34e373675 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/properties/MaxBonusLevel.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/properties/MaxBonusLevel.java @@ -11,10 +11,10 @@ public class MaxBonusLevel extends AbstractScalingProperty { */ /** - * Returns the appropriate value for this scaling property whether it is Standard or Retro - * - * @return the value used in scaling calculations for this ScalingProperty - *//* + * Returns the appropriate value for this scaling property whether it is Standard or Retro + * + * @return the value used in scaling calculations for this ScalingProperty + *//* @Override public double getValue() { diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/properties/ScalingProperty.java b/src/main/java/com/gmail/nossr50/datatypes/skills/properties/ScalingProperty.java index e5783c1a9..88b2a09ed 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/properties/ScalingProperty.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/properties/ScalingProperty.java @@ -3,6 +3,7 @@ package com.gmail.nossr50.datatypes.skills.properties; public interface ScalingProperty extends SkillProperty { /** * Returns the appropriate value for this scaling property whether it is Standard or Retro + * * @return the value used in scaling calculations for this ScalingProperty */ double getValue(); diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/AbstractSubSkill.java b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/AbstractSubSkill.java index 2e7c9a1f5..2f295fbfa 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/AbstractSubSkill.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/AbstractSubSkill.java @@ -17,8 +17,7 @@ public abstract class AbstractSubSkill implements SubSkill, Interaction, Rank, S protected String configKeyPrimary; protected SubSkillType subSkillType; - public AbstractSubSkill(String configKeySubSkill, String configKeyPrimary, SubSkillType subSkillType) - { + public AbstractSubSkill(String configKeySubSkill, String configKeyPrimary, SubSkillType subSkillType) { this.configKeySubSkill = configKeySubSkill; this.configKeyPrimary = configKeyPrimary; this.subSkillType = subSkillType; @@ -31,7 +30,7 @@ public abstract class AbstractSubSkill implements SubSkill, Interaction, Rank, S */ @Override public String getDescription() { - return LocaleLoader.getString(getPrimaryKeyName()+".SubSkill."+getConfigKeyName()+".Description"); + return LocaleLoader.getString(getPrimaryKeyName() + ".SubSkill." + getConfigKeyName() + ".Description"); } /** @@ -39,7 +38,8 @@ public abstract class AbstractSubSkill implements SubSkill, Interaction, Rank, S * * @return true if enabled */ - @Override @Deprecated + @Override + @Deprecated public boolean isEnabled() { //TODO: This might be troublesome... return CoreSkillsConfig.getInstance().isSkillEnabled(this); diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/AcrobaticsSubSkill.java b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/AcrobaticsSubSkill.java index d692747b8..1f951dd30 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/AcrobaticsSubSkill.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/AcrobaticsSubSkill.java @@ -28,7 +28,7 @@ public abstract class AcrobaticsSubSkill extends AbstractSubSkill { */ @Override public String getNiceName() { - return LocaleLoader.getString(getPrimaryKeyName()+".SubSkill."+getConfigKeyName()+".Name"); + return LocaleLoader.getString(getPrimaryKeyName() + ".SubSkill." + getConfigKeyName() + ".Name"); } /** @@ -48,7 +48,7 @@ public abstract class AcrobaticsSubSkill extends AbstractSubSkill { */ @Override public String getTips() { - return LocaleLoader.getString("JSON."+StringUtils.getCapitalized(getPrimarySkill().toString())+".SubSkill."+getConfigKeyName()+".Details.Tips"); + return LocaleLoader.getString("JSON." + StringUtils.getCapitalized(getPrimarySkill().toString()) + ".SubSkill." + getConfigKeyName() + ".Details.Tips"); } /** diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java index a09d89a6a..fe21a6a8b 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java @@ -38,6 +38,10 @@ public class Roll extends AcrobaticsSubSkill { super("Roll", EventPriority.HIGHEST, SubSkillType.ACROBATICS_ROLL); } + protected static double calculateModifiedRollDamage(double damage, double damageThreshold) { + return Math.max(damage - damageThreshold, 0.0); + } + /** * Executes the interaction between this subskill and Minecraft * @@ -58,7 +62,7 @@ public class Roll extends AcrobaticsSubSkill { EntityDamageEvent entityDamageEvent = (EntityDamageEvent) event; //Make sure a real player was damaged in this event - if(!EventUtils.isRealPlayerDamaged(entityDamageEvent)) + if (!EventUtils.isRealPlayerDamaged(entityDamageEvent)) return false; switch (entityDamageEvent.getCause()) { @@ -67,7 +71,7 @@ public class Roll extends AcrobaticsSubSkill { //Grab the player McMMOPlayer mcMMOPlayer = EventUtils.getMcMMOPlayer(entityDamageEvent.getEntity()); - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) break; /* @@ -100,7 +104,7 @@ public class Roll extends AcrobaticsSubSkill { */ @Override public String getPermissionNode() { - return ("mcmmo.ability."+getPrimaryKeyName()+"."+getConfigKeyName()).toLowerCase(); + return ("mcmmo.ability." + getPrimaryKeyName() + "." + getConfigKeyName()).toLowerCase(); } /** @@ -118,7 +122,7 @@ public class Roll extends AcrobaticsSubSkill { * Adds detailed stats specific to this skill * * @param componentBuilder target component builder - * @param player target player + * @param player target player */ @Override public void addStats(ComponentBuilder componentBuilder, Player player) { @@ -158,8 +162,7 @@ public class Roll extends AcrobaticsSubSkill { //Advanced //Lucky Notice - if(isLucky) - { + if (isLucky) { componentBuilder.append(LocaleLoader.getString("JSON.JWrapper.Perks.Header")); componentBuilder.append("\n"); componentBuilder.append(LocaleLoader.getString("JSON.JWrapper.Perks.Lucky", "33")); @@ -207,18 +210,17 @@ public class Roll extends AcrobaticsSubSkill { NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, "Acrobatics.Roll.Text"); SoundManager.sendCategorizedSound(player, player.getLocation(), SoundType.ROLL_ACTIVATED, SoundCategory.PLAYERS); - if(!mcMMO.getConfigManager().getConfigExploitPrevention().getConfigSectionExploitAcrobatics().isPreventAcrobaticsAbuse()) + if (!mcMMO.getConfigManager().getConfigExploitPrevention().getConfigSectionExploitAcrobatics().isPreventAcrobaticsAbuse()) SkillUtils.applyXpGain(mcMMOPlayer, getPrimarySkill(), calculateRollXP(player, damage, true), XPGainReason.PVE); - else if(!isExploiting(player) && mcMMOPlayer.getAcrobaticsManager().canGainRollXP()) + else if (!isExploiting(player) && mcMMOPlayer.getAcrobaticsManager().canGainRollXP()) SkillUtils.applyXpGain(mcMMOPlayer, getPrimarySkill(), calculateRollXP(player, damage, true), XPGainReason.PVE); addFallLocation(player); return modifiedDamage; - } - else if (!isFatal(player, damage)) { - if(!mcMMO.getConfigManager().getConfigExploitPrevention().getConfigSectionExploitAcrobatics().isPreventAcrobaticsAbuse()) + } else if (!isFatal(player, damage)) { + if (!mcMMO.getConfigManager().getConfigExploitPrevention().getConfigSectionExploitAcrobatics().isPreventAcrobaticsAbuse()) SkillUtils.applyXpGain(mcMMOPlayer, getPrimarySkill(), calculateRollXP(player, damage, true), XPGainReason.PVE); - else if(!isExploiting(player) && mcMMOPlayer.getAcrobaticsManager().canGainRollXP()) + else if (!isExploiting(player) && mcMMOPlayer.getAcrobaticsManager().canGainRollXP()) SkillUtils.applyXpGain(mcMMOPlayer, getPrimarySkill(), calculateRollXP(player, damage, false), XPGainReason.PVE); } @@ -243,25 +245,23 @@ public class Roll extends AcrobaticsSubSkill { rcs.setSkillLevel(rcs.getSkillLevel() * 2); //Double the effective odds if (!isFatal(player, modifiedDamage) - && RandomChanceUtil.checkRandomChanceExecutionSuccess(rcs)) - { + && RandomChanceUtil.checkRandomChanceExecutionSuccess(rcs)) { NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, "Acrobatics.Ability.Proc"); - SoundManager.sendCategorizedSound(player, player.getLocation(), SoundType.ROLL_ACTIVATED, SoundCategory.PLAYERS,0.5F); + SoundManager.sendCategorizedSound(player, player.getLocation(), SoundType.ROLL_ACTIVATED, SoundCategory.PLAYERS, 0.5F); - if(!mcMMO.getConfigManager().getConfigExploitPrevention().getConfigSectionExploitAcrobatics().isPreventAcrobaticsAbuse()) + if (!mcMMO.getConfigManager().getConfigExploitPrevention().getConfigSectionExploitAcrobatics().isPreventAcrobaticsAbuse()) SkillUtils.applyXpGain(mcMMOPlayer, getPrimarySkill(), calculateRollXP(player, damage, true), XPGainReason.PVE); - else if(!isExploiting(player) && mcMMOPlayer.getAcrobaticsManager().canGainRollXP()) + else if (!isExploiting(player) && mcMMOPlayer.getAcrobaticsManager().canGainRollXP()) SkillUtils.applyXpGain(mcMMOPlayer, getPrimarySkill(), calculateRollXP(player, damage, true), XPGainReason.PVE); addFallLocation(player); return modifiedDamage; - } - else if (!isFatal(player, damage)) { - if(!mcMMO.getConfigManager().getConfigExploitPrevention().getConfigSectionExploitAcrobatics().isPreventAcrobaticsAbuse()) + } else if (!isFatal(player, damage)) { + if (!mcMMO.getConfigManager().getConfigExploitPrevention().getConfigSectionExploitAcrobatics().isPreventAcrobaticsAbuse()) SkillUtils.applyXpGain(mcMMOPlayer, getPrimarySkill(), calculateRollXP(player, damage, true), XPGainReason.PVE); - else if(!isExploiting(player) && mcMMOPlayer.getAcrobaticsManager().canGainRollXP()) + else if (!isExploiting(player) && mcMMOPlayer.getAcrobaticsManager().canGainRollXP()) SkillUtils.applyXpGain(mcMMOPlayer, getPrimarySkill(), calculateRollXP(player, damage, false), XPGainReason.PVE); - + addFallLocation(player); } @@ -284,10 +284,10 @@ public class Roll extends AcrobaticsSubSkill { } //Teleport CD - if(System.currentTimeMillis() < UserManager.getPlayer(player).getTeleportATS()) + if (System.currentTimeMillis() < UserManager.getPlayer(player).getTeleportATS()) return true; - if(UserManager.getPlayer(player).getAcrobaticsManager().hasFallenInLocationBefore(getBlockLocation(player))) + if (UserManager.getPlayer(player).getAcrobaticsManager().hasFallenInLocationBefore(getBlockLocation(player))) return true; return false; @@ -304,10 +304,6 @@ public class Roll extends AcrobaticsSubSkill { return xp; } - protected static double calculateModifiedRollDamage(double damage, double damageThreshold) { - return Math.max(damage - damageThreshold, 0.0); - } - private boolean isFatal(Player player, double damage) { return player.getHealth() - damage <= 0; } @@ -336,7 +332,7 @@ public class Roll extends AcrobaticsSubSkill { //player.sendMessage(getDescription()); //Player stats player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.Stats", - LocaleLoader.getString("Acrobatics.SubSkill.Roll.Stats", getStats(player)[0], getStats(player)[1]))); + LocaleLoader.getString("Acrobatics.SubSkill.Roll.Stats", getStats(player)[0], getStats(player)[1]))); //Mechanics player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.Mechanics")); @@ -381,13 +377,13 @@ public class Roll extends AcrobaticsSubSkill { rollGraceHalfMaxSkill.setSkillLevel(1); //Level 1 skill //Chance Stat Calculations - rollChanceHalfMax = RandomChanceUtil.getRandomChanceExecutionChance(rollHalfMaxSkill); - graceChanceHalfMax = RandomChanceUtil.getRandomChanceExecutionChance(rollGraceHalfMaxSkill); - damageThreshold = AdvancedConfig.getInstance().getRollDamageThreshold(); + rollChanceHalfMax = RandomChanceUtil.getRandomChanceExecutionChance(rollHalfMaxSkill); + graceChanceHalfMax = RandomChanceUtil.getRandomChanceExecutionChance(rollGraceHalfMaxSkill); + damageThreshold = AdvancedConfig.getInstance().getRollDamageThreshold(); - chancePerLevel = RandomChanceUtil.getRandomChanceExecutionChance(rollOneSkillLevel); + chancePerLevel = RandomChanceUtil.getRandomChanceExecutionChance(rollOneSkillLevel); - double maxLevel = AdvancedConfig.getInstance().getMaxBonusLevel(SubSkillType.ACROBATICS_ROLL); + double maxLevel = AdvancedConfig.getInstance().getMaxBonusLevel(SubSkillType.ACROBATICS_ROLL); return LocaleLoader.getString("Acrobatics.SubSkill.Roll.Mechanics", rollChanceHalfMax, graceChanceHalfMax, maxLevel, chancePerLevel, damageThreshold, damageThreshold * 2); } @@ -399,30 +395,27 @@ public class Roll extends AcrobaticsSubSkill { * @return stat array for target player for this skill */ @Override - public Double[] getStats(Player player) - { + public Double[] getStats(Player player) { double playerChanceRoll, playerChanceGrace; - RandomChanceSkill roll = new RandomChanceSkill(player, getSubSkillType()); - RandomChanceSkill graceful = new RandomChanceSkill(player, getSubSkillType()); + RandomChanceSkill roll = new RandomChanceSkill(player, getSubSkillType()); + RandomChanceSkill graceful = new RandomChanceSkill(player, getSubSkillType()); graceful.setSkillLevel(graceful.getSkillLevel() * 2); //Double odds //Calculate - playerChanceRoll = RandomChanceUtil.getRandomChanceExecutionChance(roll); - playerChanceGrace = RandomChanceUtil.getRandomChanceExecutionChance(graceful); + playerChanceRoll = RandomChanceUtil.getRandomChanceExecutionChance(roll); + playerChanceGrace = RandomChanceUtil.getRandomChanceExecutionChance(graceful); - Double[] stats = { playerChanceRoll, playerChanceGrace }; //DEBUG + Double[] stats = {playerChanceRoll, playerChanceGrace}; //DEBUG return stats; } - public void addFallLocation(Player player) - { + public void addFallLocation(Player player) { UserManager.getPlayer(player).getAcrobaticsManager().addLocationToFallMap(getBlockLocation(player)); } - public Location getBlockLocation(Player player) - { + public Location getBlockLocation(Player player) { return player.getLocation().getBlock().getLocation(); } } \ No newline at end of file diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/interfaces/Interaction.java b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/interfaces/Interaction.java index 1e0357c7a..d8c8d76bc 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/interfaces/Interaction.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/interfaces/Interaction.java @@ -7,13 +7,15 @@ import org.bukkit.event.EventPriority; public interface Interaction { /** * The type of interaction this subskill has with Minecraft + * * @return the interaction type */ InteractType getInteractType(); /** * Executes the interaction between this subskill and Minecraft - * @param event the vector of interaction + * + * @param event the vector of interaction * @param plugin the mcMMO plugin instance * @return true if interaction wasn't cancelled */ @@ -21,6 +23,7 @@ public interface Interaction { /** * The priority for this interaction + * * @return the priority for interaction */ EventPriority getEventPriority(); diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/interfaces/Rank.java b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/interfaces/Rank.java index 7e6267f18..dfdbb1548 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/interfaces/Rank.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/interfaces/Rank.java @@ -3,12 +3,14 @@ package com.gmail.nossr50.datatypes.skills.subskills.interfaces; public interface Rank { /** * Gets the number of ranks for this subskill, 0 for no ranks + * * @return the number of ranks for this subskill, 0 for no ranks */ int getNumRanks(); /** * Not all skills have ranks + * * @return true if the skill has ranks */ boolean hasRanks(); diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/interfaces/SubSkill.java b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/interfaces/SubSkill.java index 1bd26403d..952ca20e6 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/interfaces/SubSkill.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/interfaces/SubSkill.java @@ -7,18 +7,21 @@ import org.bukkit.entity.Player; public interface SubSkill extends Skill { /** * Grabs the permission node for this skill + * * @return permission node address */ String getPermissionNode(); /** * Returns a collection of strings about how a skill works + * * @return */ String getMechanics(); /** * Get an array of various stats for a player + * * @param player target player * @return stat array for target player for this skill */ @@ -26,6 +29,7 @@ public interface SubSkill extends Skill { /** * Checks if a player has permission to use this skill + * * @param player target player * @return true if player has permission */ @@ -34,43 +38,50 @@ public interface SubSkill extends Skill { /** * The name of this subskill * It's a good idea for this to return the localized name + * * @return the subskill name */ String getNiceName(); /** * This is the name that represents our subskill in the config + * * @return the config key name */ String getConfigKeyName(); /** * Returns the simple description of this subskill + * * @return the simple description of this subskill */ String getDescription(); /** * Grabs tips for the subskill + * * @return tips for the subskill */ String getTips(); /** * Adds detailed stats specific to this skill + * * @param componentBuilder target component builder - * @param player owner of this skill + * @param player owner of this skill */ void addStats(ComponentBuilder componentBuilder, Player player); /** * Whether or not this subskill is enabled + * * @return true if enabled */ boolean isEnabled(); /** * Prints detailed info about this subskill to the player + * * @param player the target player */ void printInfo(Player player); diff --git a/src/main/java/com/gmail/nossr50/datatypes/treasure/Rarity.java b/src/main/java/com/gmail/nossr50/datatypes/treasure/Rarity.java index 40cddb737..00390c442 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/treasure/Rarity.java +++ b/src/main/java/com/gmail/nossr50/datatypes/treasure/Rarity.java @@ -11,8 +11,7 @@ public enum Rarity { public static Rarity getRarity(String string) { try { return valueOf(string); - } - catch (IllegalArgumentException ex) { + } catch (IllegalArgumentException ex) { return COMMON; } } diff --git a/src/main/java/com/gmail/nossr50/datatypes/treasure/Treasure.java b/src/main/java/com/gmail/nossr50/datatypes/treasure/Treasure.java index 81d2e66f2..af7fb7563 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/treasure/Treasure.java +++ b/src/main/java/com/gmail/nossr50/datatypes/treasure/Treasure.java @@ -42,7 +42,7 @@ public abstract class Treasure { public int getDropLevel() { //If they are in retro mode all requirements are scaled up by 10 - if(mcMMO.isRetroModeEnabled()) + if (mcMMO.isRetroModeEnabled()) return dropLevel * 10; return dropLevel; diff --git a/src/main/java/com/gmail/nossr50/events/chat/McMMOChatEvent.java b/src/main/java/com/gmail/nossr50/events/chat/McMMOChatEvent.java index 9c4f3ae68..ce13caf12 100644 --- a/src/main/java/com/gmail/nossr50/events/chat/McMMOChatEvent.java +++ b/src/main/java/com/gmail/nossr50/events/chat/McMMOChatEvent.java @@ -6,6 +6,10 @@ import org.bukkit.event.HandlerList; import org.bukkit.plugin.Plugin; public abstract class McMMOChatEvent extends Event implements Cancellable { + /** + * Rest of file is required boilerplate for custom events + **/ + private static final HandlerList handlers = new HandlerList(); private boolean cancelled; private Plugin plugin; private String sender; @@ -27,6 +31,10 @@ public abstract class McMMOChatEvent extends Event implements Cancellable { this.message = message; } + public static HandlerList getHandlerList() { + return handlers; + } + /** * @return The plugin responsible for this event, note this can be null */ @@ -48,13 +56,6 @@ public abstract class McMMOChatEvent extends Event implements Cancellable { return displayName; } - /** - * @return String message that will be sent - */ - public String getMessage() { - return message; - } - /** * @param displayName String display name of the player who sent the chat */ @@ -62,6 +63,13 @@ public abstract class McMMOChatEvent extends Event implements Cancellable { this.displayName = displayName; } + /** + * @return String message that will be sent + */ + public String getMessage() { + return message; + } + /** * @param message String message to be sent in chat */ @@ -69,7 +77,9 @@ public abstract class McMMOChatEvent extends Event implements Cancellable { this.message = message; } - /** Following are required for Cancellable **/ + /** + * Following are required for Cancellable + **/ @Override public boolean isCancelled() { return cancelled; @@ -80,15 +90,8 @@ public abstract class McMMOChatEvent extends Event implements Cancellable { this.cancelled = cancelled; } - /** Rest of file is required boilerplate for custom events **/ - private static final HandlerList handlers = new HandlerList(); - @Override public HandlerList getHandlers() { return handlers; } - - public static HandlerList getHandlerList() { - return handlers; - } } diff --git a/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerExperienceEvent.java b/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerExperienceEvent.java index 78592b03b..e17e88f39 100644 --- a/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerExperienceEvent.java +++ b/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerExperienceEvent.java @@ -12,10 +12,11 @@ import org.bukkit.event.player.PlayerEvent; * Generic event for mcMMO experience events. */ public abstract class McMMOPlayerExperienceEvent extends PlayerEvent implements Cancellable { - private boolean cancelled; + private static final HandlerList handlers = new HandlerList(); protected PrimarySkillType skill; protected int skillLevel; protected XPGainReason xpGainReason; + private boolean cancelled; @Deprecated protected McMMOPlayerExperienceEvent(Player player, PrimarySkillType skill) { @@ -32,6 +33,10 @@ public abstract class McMMOPlayerExperienceEvent extends PlayerEvent implements this.xpGainReason = xpGainReason; } + public static HandlerList getHandlerList() { + return handlers; + } + /** * @return The skill involved in this event */ @@ -53,7 +58,9 @@ public abstract class McMMOPlayerExperienceEvent extends PlayerEvent implements return xpGainReason; } - /** Following are required for Cancellable **/ + /** + * Following are required for Cancellable + **/ @Override public boolean isCancelled() { return cancelled; @@ -63,15 +70,9 @@ public abstract class McMMOPlayerExperienceEvent extends PlayerEvent implements public void setCancelled(boolean cancelled) { this.cancelled = cancelled; } - - private static final HandlerList handlers = new HandlerList(); @Override public HandlerList getHandlers() { return handlers; } - - public static HandlerList getHandlerList() { - return handlers; - } } diff --git a/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerLevelDownEvent.java b/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerLevelDownEvent.java index 3834726f8..109ebcab9 100644 --- a/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerLevelDownEvent.java +++ b/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerLevelDownEvent.java @@ -9,6 +9,7 @@ import org.bukkit.event.HandlerList; * Called when a user loses levels in a skill */ public class McMMOPlayerLevelDownEvent extends McMMOPlayerLevelChangeEvent { + private static final HandlerList handlers = new HandlerList(); private int levelsLost; @Deprecated @@ -33,11 +34,8 @@ public class McMMOPlayerLevelDownEvent extends McMMOPlayerLevelChangeEvent { this.levelsLost = levelsLost; } - /** - * @param levelsLost Set the number of levels lost in this event - */ - public void setLevelsLost(int levelsLost) { - this.levelsLost = levelsLost; + public static HandlerList getHandlerList() { + return handlers; } /** @@ -47,14 +45,15 @@ public class McMMOPlayerLevelDownEvent extends McMMOPlayerLevelChangeEvent { return levelsLost; } - private static final HandlerList handlers = new HandlerList(); + /** + * @param levelsLost Set the number of levels lost in this event + */ + public void setLevelsLost(int levelsLost) { + this.levelsLost = levelsLost; + } @Override public HandlerList getHandlers() { return handlers; } - - public static HandlerList getHandlerList() { - return handlers; - } } diff --git a/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerLevelUpEvent.java b/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerLevelUpEvent.java index 062dd4a2a..333f3df82 100644 --- a/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerLevelUpEvent.java +++ b/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerLevelUpEvent.java @@ -9,6 +9,7 @@ import org.bukkit.event.HandlerList; * Called when a user levels up in a skill */ public class McMMOPlayerLevelUpEvent extends McMMOPlayerLevelChangeEvent { + private static final HandlerList handlers = new HandlerList(); private int levelsGained; @Deprecated @@ -33,11 +34,8 @@ public class McMMOPlayerLevelUpEvent extends McMMOPlayerLevelChangeEvent { this.levelsGained = levelsGained; } - /** - * @param levelsGained Set the number of levels gained in this event - */ - public void setLevelsGained(int levelsGained) { - this.levelsGained = levelsGained; + public static HandlerList getHandlerList() { + return handlers; } /** @@ -47,14 +45,15 @@ public class McMMOPlayerLevelUpEvent extends McMMOPlayerLevelChangeEvent { return levelsGained; } - private static final HandlerList handlers = new HandlerList(); + /** + * @param levelsGained Set the number of levels gained in this event + */ + public void setLevelsGained(int levelsGained) { + this.levelsGained = levelsGained; + } @Override public HandlerList getHandlers() { return handlers; } - - public static HandlerList getHandlerList() { - return handlers; - } } diff --git a/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerXpGainEvent.java b/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerXpGainEvent.java index d789fde70..5969c05c1 100644 --- a/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerXpGainEvent.java +++ b/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerXpGainEvent.java @@ -9,6 +9,7 @@ import org.bukkit.event.HandlerList; * Called when a player gains XP in a skill */ public class McMMOPlayerXpGainEvent extends McMMOPlayerExperienceEvent { + private static final HandlerList handlers = new HandlerList(); private float xpGained; @Deprecated @@ -22,6 +23,10 @@ public class McMMOPlayerXpGainEvent extends McMMOPlayerExperienceEvent { this.xpGained = xpGained; } + public static HandlerList getHandlerList() { + return handlers; + } + /** * @return The amount of experience gained in this event */ @@ -29,6 +34,13 @@ public class McMMOPlayerXpGainEvent extends McMMOPlayerExperienceEvent { return xpGained; } + /** + * @param xpGained int amount of experience gained in this event + */ + public void setRawXpGained(float xpGained) { + this.xpGained = xpGained; + } + /** * @return int amount of experience gained in this event */ @@ -37,13 +49,6 @@ public class McMMOPlayerXpGainEvent extends McMMOPlayerExperienceEvent { return (int) xpGained; } - /** - * @param xpGained int amount of experience gained in this event - */ - public void setRawXpGained(float xpGained) { - this.xpGained = xpGained; - } - /** * @param xpGained int amount of experience gained in this event */ @@ -52,14 +57,8 @@ public class McMMOPlayerXpGainEvent extends McMMOPlayerExperienceEvent { this.xpGained = xpGained; } - private static final HandlerList handlers = new HandlerList(); - @Override public HandlerList getHandlers() { return handlers; } - - public static HandlerList getHandlerList() { - return handlers; - } } diff --git a/src/main/java/com/gmail/nossr50/events/hardcore/McMMOPlayerDeathPenaltyEvent.java b/src/main/java/com/gmail/nossr50/events/hardcore/McMMOPlayerDeathPenaltyEvent.java index bf723375a..a6035351c 100644 --- a/src/main/java/com/gmail/nossr50/events/hardcore/McMMOPlayerDeathPenaltyEvent.java +++ b/src/main/java/com/gmail/nossr50/events/hardcore/McMMOPlayerDeathPenaltyEvent.java @@ -8,9 +8,12 @@ import org.bukkit.event.player.PlayerEvent; import java.util.HashMap; public class McMMOPlayerDeathPenaltyEvent extends PlayerEvent implements Cancellable { + /** + * Rest of file is required boilerplate for custom events + **/ + private static final HandlerList handlers = new HandlerList(); private HashMap levelChanged; private HashMap experienceChanged; - private boolean cancelled; public McMMOPlayerDeathPenaltyEvent(Player player, HashMap levelChanged, HashMap experienceChanged) { @@ -26,6 +29,10 @@ public class McMMOPlayerDeathPenaltyEvent extends PlayerEvent implements Cancell this.cancelled = false; } + public static HandlerList getHandlerList() { + return handlers; + } + public HashMap getLevelChanged() { return levelChanged; } @@ -42,7 +49,9 @@ public class McMMOPlayerDeathPenaltyEvent extends PlayerEvent implements Cancell this.experienceChanged = experienceChanged; } - /** Following are required for Cancellable **/ + /** + * Following are required for Cancellable + **/ @Override public boolean isCancelled() { return cancelled; @@ -53,15 +62,8 @@ public class McMMOPlayerDeathPenaltyEvent extends PlayerEvent implements Cancell this.cancelled = cancelled; } - /** Rest of file is required boilerplate for custom events **/ - private static final HandlerList handlers = new HandlerList(); - @Override public HandlerList getHandlers() { return handlers; } - - public static HandlerList getHandlerList() { - return handlers; - } } diff --git a/src/main/java/com/gmail/nossr50/events/hardcore/McMMOPlayerPreDeathPenaltyEvent.java b/src/main/java/com/gmail/nossr50/events/hardcore/McMMOPlayerPreDeathPenaltyEvent.java index b831f0426..7e8b8fb22 100644 --- a/src/main/java/com/gmail/nossr50/events/hardcore/McMMOPlayerPreDeathPenaltyEvent.java +++ b/src/main/java/com/gmail/nossr50/events/hardcore/McMMOPlayerPreDeathPenaltyEvent.java @@ -6,6 +6,10 @@ import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; public class McMMOPlayerPreDeathPenaltyEvent extends PlayerEvent implements Cancellable { + /** + * Rest of file is required boilerplate for custom events + **/ + private static final HandlerList handlers = new HandlerList(); private boolean cancelled; public McMMOPlayerPreDeathPenaltyEvent(Player player) { @@ -13,7 +17,13 @@ public class McMMOPlayerPreDeathPenaltyEvent extends PlayerEvent implements Canc this.cancelled = false; } - /** Following are required for Cancellable **/ + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Following are required for Cancellable + **/ @Override public boolean isCancelled() { return cancelled; @@ -24,15 +34,8 @@ public class McMMOPlayerPreDeathPenaltyEvent extends PlayerEvent implements Canc this.cancelled = cancelled; } - /** Rest of file is required boilerplate for custom events **/ - private static final HandlerList handlers = new HandlerList(); - @Override public HandlerList getHandlers() { return handlers; } - - public static HandlerList getHandlerList() { - return handlers; - } } diff --git a/src/main/java/com/gmail/nossr50/events/items/McMMOItemSpawnEvent.java b/src/main/java/com/gmail/nossr50/events/items/McMMOItemSpawnEvent.java index b6d7dcb94..5756fe5fe 100644 --- a/src/main/java/com/gmail/nossr50/events/items/McMMOItemSpawnEvent.java +++ b/src/main/java/com/gmail/nossr50/events/items/McMMOItemSpawnEvent.java @@ -10,6 +10,10 @@ import org.bukkit.inventory.ItemStack; * Called when mcMMO is preparing to drop an item. */ public class McMMOItemSpawnEvent extends Event implements Cancellable { + /** + * Rest of file is required boilerplate for custom events + **/ + private static final HandlerList handlers = new HandlerList(); private Location location; private ItemStack itemStack; private boolean cancelled; @@ -20,6 +24,10 @@ public class McMMOItemSpawnEvent extends Event implements Cancellable { this.cancelled = false; } + public static HandlerList getHandlerList() { + return handlers; + } + /** * @return Location where the item will be dropped */ @@ -48,7 +56,9 @@ public class McMMOItemSpawnEvent extends Event implements Cancellable { this.itemStack = itemStack; } - /** Following are required for Cancellable **/ + /** + * Following are required for Cancellable + **/ @Override public boolean isCancelled() { return cancelled; @@ -59,15 +69,8 @@ public class McMMOItemSpawnEvent extends Event implements Cancellable { this.cancelled = cancelled; } - /** Rest of file is required boilerplate for custom events **/ - private static final HandlerList handlers = new HandlerList(); - @Override public HandlerList getHandlers() { return handlers; } - - public static HandlerList getHandlerList() { - return handlers; - } } diff --git a/src/main/java/com/gmail/nossr50/events/party/McMMOPartyAllianceChangeEvent.java b/src/main/java/com/gmail/nossr50/events/party/McMMOPartyAllianceChangeEvent.java index 98a8d4e2a..deebdb28a 100644 --- a/src/main/java/com/gmail/nossr50/events/party/McMMOPartyAllianceChangeEvent.java +++ b/src/main/java/com/gmail/nossr50/events/party/McMMOPartyAllianceChangeEvent.java @@ -6,6 +6,10 @@ import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; public class McMMOPartyAllianceChangeEvent extends PlayerEvent implements Cancellable { + /** + * Rest of file is required boilerplate for custom events + **/ + private static final HandlerList handlers = new HandlerList(); private String oldAlly; private String newAlly; private EventReason reason; @@ -24,6 +28,10 @@ public class McMMOPartyAllianceChangeEvent extends PlayerEvent implements Cancel this.cancelled = false; } + public static HandlerList getHandlerList() { + return handlers; + } + /** * @return The party being left, or null if the player was not in a party */ @@ -45,6 +53,24 @@ public class McMMOPartyAllianceChangeEvent extends PlayerEvent implements Cancel return reason; } + /** + * Following are required for Cancellable + **/ + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + /** * A list of reasons why the event may have been fired */ @@ -64,27 +90,4 @@ public class McMMOPartyAllianceChangeEvent extends PlayerEvent implements Cancel */ CUSTOM } - - /** Following are required for Cancellable **/ - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - /** Rest of file is required boilerplate for custom events **/ - private static final HandlerList handlers = new HandlerList(); - - @Override - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } } diff --git a/src/main/java/com/gmail/nossr50/events/party/McMMOPartyChangeEvent.java b/src/main/java/com/gmail/nossr50/events/party/McMMOPartyChangeEvent.java index 584564b5f..12d486f26 100644 --- a/src/main/java/com/gmail/nossr50/events/party/McMMOPartyChangeEvent.java +++ b/src/main/java/com/gmail/nossr50/events/party/McMMOPartyChangeEvent.java @@ -9,6 +9,10 @@ import org.bukkit.event.player.PlayerEvent; * Called when a player attempts to join, leave, or change parties. */ public class McMMOPartyChangeEvent extends PlayerEvent implements Cancellable { + /** + * Rest of file is required boilerplate for custom events + **/ + private static final HandlerList handlers = new HandlerList(); private String oldParty; private String newParty; private EventReason reason; @@ -27,6 +31,10 @@ public class McMMOPartyChangeEvent extends PlayerEvent implements Cancellable { this.cancelled = false; } + public static HandlerList getHandlerList() { + return handlers; + } + /** * @return The party being left, or null if the player was not in a party */ @@ -48,6 +56,24 @@ public class McMMOPartyChangeEvent extends PlayerEvent implements Cancellable { return reason; } + /** + * Following are required for Cancellable + **/ + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + /** * A list of reasons why the event may have been fired */ @@ -77,27 +103,4 @@ public class McMMOPartyChangeEvent extends PlayerEvent implements Cancellable { */ CUSTOM } - - /** Following are required for Cancellable **/ - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - /** Rest of file is required boilerplate for custom events **/ - private static final HandlerList handlers = new HandlerList(); - - @Override - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } } diff --git a/src/main/java/com/gmail/nossr50/events/party/McMMOPartyLevelUpEvent.java b/src/main/java/com/gmail/nossr50/events/party/McMMOPartyLevelUpEvent.java index 0fcdabd7a..70a3c930f 100644 --- a/src/main/java/com/gmail/nossr50/events/party/McMMOPartyLevelUpEvent.java +++ b/src/main/java/com/gmail/nossr50/events/party/McMMOPartyLevelUpEvent.java @@ -6,6 +6,10 @@ import org.bukkit.event.Event; import org.bukkit.event.HandlerList; public class McMMOPartyLevelUpEvent extends Event implements Cancellable { + /** + * Rest of file is required boilerplate for custom events + **/ + private static final HandlerList handlers = new HandlerList(); private Party party; private int levelsChanged; private boolean cancelled; @@ -16,6 +20,10 @@ public class McMMOPartyLevelUpEvent extends Event implements Cancellable { this.cancelled = false; } + public static HandlerList getHandlerList() { + return handlers; + } + public Party getParty() { return party; } @@ -28,7 +36,9 @@ public class McMMOPartyLevelUpEvent extends Event implements Cancellable { this.levelsChanged = levelsChanged; } - /** Following are required for Cancellable **/ + /** + * Following are required for Cancellable + **/ @Override public boolean isCancelled() { return cancelled; @@ -39,15 +49,8 @@ public class McMMOPartyLevelUpEvent extends Event implements Cancellable { this.cancelled = cancelled; } - /** Rest of file is required boilerplate for custom events **/ - private static final HandlerList handlers = new HandlerList(); - @Override public HandlerList getHandlers() { return handlers; } - - public static HandlerList getHandlerList() { - return handlers; - } } diff --git a/src/main/java/com/gmail/nossr50/events/party/McMMOPartyTeleportEvent.java b/src/main/java/com/gmail/nossr50/events/party/McMMOPartyTeleportEvent.java index 9bc1fe1ee..7139e3264 100644 --- a/src/main/java/com/gmail/nossr50/events/party/McMMOPartyTeleportEvent.java +++ b/src/main/java/com/gmail/nossr50/events/party/McMMOPartyTeleportEvent.java @@ -8,6 +8,10 @@ import org.bukkit.event.player.PlayerTeleportEvent; * Called just before a player teleports using the /ptp command. */ public class McMMOPartyTeleportEvent extends PlayerTeleportEvent { + /** + * Rest of file is required boilerplate for custom events + **/ + private static final HandlerList handlers = new HandlerList(); private String party; private Player target; @@ -17,6 +21,10 @@ public class McMMOPartyTeleportEvent extends PlayerTeleportEvent { this.target = target; } + public static HandlerList getHandlerList() { + return handlers; + } + /** * @return The party the teleporting player is in */ @@ -31,15 +39,8 @@ public class McMMOPartyTeleportEvent extends PlayerTeleportEvent { return target; } - /** Rest of file is required boilerplate for custom events **/ - private static final HandlerList handlers = new HandlerList(); - @Override public HandlerList getHandlers() { return handlers; } - - public static HandlerList getHandlerList() { - return handlers; - } } diff --git a/src/main/java/com/gmail/nossr50/events/party/McMMOPartyXpGainEvent.java b/src/main/java/com/gmail/nossr50/events/party/McMMOPartyXpGainEvent.java index 16dbd95a2..a3c74d0af 100644 --- a/src/main/java/com/gmail/nossr50/events/party/McMMOPartyXpGainEvent.java +++ b/src/main/java/com/gmail/nossr50/events/party/McMMOPartyXpGainEvent.java @@ -6,6 +6,10 @@ import org.bukkit.event.Event; import org.bukkit.event.HandlerList; public class McMMOPartyXpGainEvent extends Event implements Cancellable { + /** + * Rest of file is required boilerplate for custom events + **/ + private static final HandlerList handlers = new HandlerList(); private Party party; private float xpGained; private boolean cancelled; @@ -16,6 +20,10 @@ public class McMMOPartyXpGainEvent extends Event implements Cancellable { this.cancelled = false; } + public static HandlerList getHandlerList() { + return handlers; + } + public Party getParty() { return party; } @@ -27,6 +35,13 @@ public class McMMOPartyXpGainEvent extends Event implements Cancellable { return xpGained; } + /** + * @param xpGained set amount of experience gained in this event + */ + public void setRawXpGained(float xpGained) { + this.xpGained = xpGained; + } + /** * @return int amount of experience gained in this event */ @@ -35,13 +50,6 @@ public class McMMOPartyXpGainEvent extends Event implements Cancellable { return (int) xpGained; } - /** - * @param xpGained set amount of experience gained in this event - */ - public void setRawXpGained(float xpGained) { - this.xpGained = xpGained; - } - /** * @param xpGained set int amount of experience gained in this event */ @@ -50,7 +58,9 @@ public class McMMOPartyXpGainEvent extends Event implements Cancellable { this.xpGained = xpGained; } - /** Following are required for Cancellable **/ + /** + * Following are required for Cancellable + **/ @Override public boolean isCancelled() { return cancelled; @@ -61,15 +71,8 @@ public class McMMOPartyXpGainEvent extends Event implements Cancellable { this.cancelled = cancelled; } - /** Rest of file is required boilerplate for custom events **/ - private static final HandlerList handlers = new HandlerList(); - @Override public HandlerList getHandlers() { return handlers; } - - public static HandlerList getHandlerList() { - return handlers; - } } diff --git a/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardEvent.java b/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardEvent.java index d9647adf3..90ccd9fa3 100644 --- a/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardEvent.java +++ b/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardEvent.java @@ -11,24 +11,31 @@ import org.bukkit.scoreboard.Scoreboard; */ abstract public class McMMOScoreboardEvent extends Event { - protected Scoreboard targetBoard; //ConfigScoreboard involved in this event + /** + * Rest of file is required boilerplate for custom events + **/ + private static final HandlerList handlers = new HandlerList(); final Scoreboard currentBoard; //Can be null + private final ScoreboardEventReason scoreboardEventReason; + protected Scoreboard targetBoard; //ConfigScoreboard involved in this event protected Player targetPlayer; - private final ScoreboardEventReason scoreboardEventReason; + /** GETTER & SETTER BOILERPLATE **/ - public McMMOScoreboardEvent(Scoreboard targetBoard, Scoreboard currentBoard, Player targetPlayer, ScoreboardEventReason scoreboardEventReason) - { + public McMMOScoreboardEvent(Scoreboard targetBoard, Scoreboard currentBoard, Player targetPlayer, ScoreboardEventReason scoreboardEventReason) { this.scoreboardEventReason = scoreboardEventReason; this.targetBoard = targetBoard; this.currentBoard = currentBoard; this.targetPlayer = targetPlayer; } - /** GETTER & SETTER BOILERPLATE **/ + public static HandlerList getHandlerList() { + return handlers; + } /** * This is the scoreboard the player will be assigned to after this event + * * @return the target board to assign the player after this event fires */ public Scoreboard getTargetBoard() { @@ -37,6 +44,7 @@ abstract public class McMMOScoreboardEvent extends Event { /** * Change the scoreboard that the player will be assigned to after this event fires + * * @param targetBoard the new board to assign the player to */ public void setTargetBoard(Scoreboard targetBoard) { @@ -45,15 +53,26 @@ abstract public class McMMOScoreboardEvent extends Event { /** * The player involved in this event (this can be changed) + * * @return the player involved in this event */ public Player getTargetPlayer() { return targetPlayer; } + /** + * Change the target player for this event + * + * @param targetPlayer the new target for this event + */ + public void setTargetPlayer(Player targetPlayer) { + this.targetPlayer = targetPlayer; + } + /** * This is the scoreboard the player is currently assigned to at the time the event was fired * Grabbed via player.getScoreboard() + * * @return players current scoreboard */ public Scoreboard getCurrentBoard() { @@ -62,29 +81,15 @@ abstract public class McMMOScoreboardEvent extends Event { /** * The ENUM defining the reason for this event + * * @return the reason for this event */ public ScoreboardEventReason getScoreboardEventReason() { return scoreboardEventReason; } - /** - * Change the target player for this event - * @param targetPlayer the new target for this event - */ - public void setTargetPlayer(Player targetPlayer) { - this.targetPlayer = targetPlayer; - } - - /** Rest of file is required boilerplate for custom events **/ - private static final HandlerList handlers = new HandlerList(); - @Override public HandlerList getHandlers() { return handlers; } - - public static HandlerList getHandlerList() { - return handlers; - } } diff --git a/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardObjectiveEvent.java b/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardObjectiveEvent.java index 2f883f19e..41ffb01a2 100644 --- a/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardObjectiveEvent.java +++ b/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardObjectiveEvent.java @@ -6,10 +6,9 @@ import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Scoreboard; public class McMMOScoreboardObjectiveEvent extends McMMOScoreboardEvent implements Cancellable { - protected boolean cancelled; - - protected Objective targetObjective; protected final ScoreboardObjectiveEventReason objectiveEventReason; + protected boolean cancelled; + protected Objective targetObjective; public McMMOScoreboardObjectiveEvent(Objective targetObjective, ScoreboardObjectiveEventReason objectiveEventReason, Scoreboard scoreboard, Scoreboard oldboard, Player targetPlayer, ScoreboardEventReason scoreboardEventReason) { super(scoreboard, oldboard, targetPlayer, scoreboardEventReason); @@ -20,6 +19,7 @@ public class McMMOScoreboardObjectiveEvent extends McMMOScoreboardEvent implemen /** * The objective that will be modified by this event + * * @return */ public Objective getTargetObjective() { @@ -28,6 +28,7 @@ public class McMMOScoreboardObjectiveEvent extends McMMOScoreboardEvent implemen /** * Change the target objective for this event + * * @param newObjective new target objective */ public void setTargetObjective(Objective newObjective) { diff --git a/src/main/java/com/gmail/nossr50/events/skills/McMMOPlayerNotificationEvent.java b/src/main/java/com/gmail/nossr50/events/skills/McMMOPlayerNotificationEvent.java index 05ed0f510..6a44181ff 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/McMMOPlayerNotificationEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/McMMOPlayerNotificationEvent.java @@ -12,6 +12,10 @@ import org.bukkit.event.HandlerList; * This event is sent for when mcMMO informs a player about various important information */ public class McMMOPlayerNotificationEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + protected final NotificationType notificationType; + protected ChatMessageType chatMessageType; + protected TextComponent notificationTextComponent; private boolean isCancelled; /* * Messages can be sent to both places, as configured in advanced.yml @@ -20,12 +24,6 @@ public class McMMOPlayerNotificationEvent extends Event implements Cancellable { */ private boolean isMessageAlsoBeingSentToChat; - private static final HandlerList handlers = new HandlerList(); - protected ChatMessageType chatMessageType; - - protected TextComponent notificationTextComponent; - protected final NotificationType notificationType; - public McMMOPlayerNotificationEvent(Player who, NotificationType notificationType, TextComponent notificationTextComponent, ChatMessageType chatMessageType, boolean isMessageAlsoBeingSentToChat) { super(false); this.notificationType = notificationType; @@ -39,6 +37,10 @@ public class McMMOPlayerNotificationEvent extends Event implements Cancellable { * Getters & Setters */ + public static HandlerList getHandlerList() { + return handlers; + } + public boolean isMessageAlsoBeingSentToChat() { return isMessageAlsoBeingSentToChat; } @@ -63,27 +65,24 @@ public class McMMOPlayerNotificationEvent extends Event implements Cancellable { this.chatMessageType = chatMessageType; } + /* + * Custom Event Boilerplate + */ + /** * The notification type for this event + * * @return this event's notification type */ public NotificationType getEventNotificationType() { return notificationType; } - /* - * Custom Event Boilerplate - */ - @Override public HandlerList getHandlers() { return handlers; } - public static HandlerList getHandlerList() { - return handlers; - } - /* * Cancellable Interface Boilerplate */ diff --git a/src/main/java/com/gmail/nossr50/events/skills/McMMOPlayerSkillEvent.java b/src/main/java/com/gmail/nossr50/events/skills/McMMOPlayerSkillEvent.java index b9a5af433..13ef2710a 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/McMMOPlayerSkillEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/McMMOPlayerSkillEvent.java @@ -10,6 +10,10 @@ import org.bukkit.event.player.PlayerEvent; * Generic event for mcMMO skill handling. */ public abstract class McMMOPlayerSkillEvent extends PlayerEvent { + /** + * Rest of file is required boilerplate for custom events + **/ + private static final HandlerList handlers = new HandlerList(); protected PrimarySkillType skill; protected int skillLevel; @@ -19,6 +23,10 @@ public abstract class McMMOPlayerSkillEvent extends PlayerEvent { this.skillLevel = UserManager.getPlayer(player).getSkillLevel(skill); } + public static HandlerList getHandlerList() { + return handlers; + } + /** * @return The skill involved in this event */ @@ -33,15 +41,8 @@ public abstract class McMMOPlayerSkillEvent extends PlayerEvent { return skillLevel; } - /** Rest of file is required boilerplate for custom events **/ - private static final HandlerList handlers = new HandlerList(); - @Override public HandlerList getHandlers() { return handlers; } - - public static HandlerList getHandlerList() { - return handlers; - } } diff --git a/src/main/java/com/gmail/nossr50/events/skills/repair/McMMOPlayerRepairCheckEvent.java b/src/main/java/com/gmail/nossr50/events/skills/repair/McMMOPlayerRepairCheckEvent.java index 638f8c202..ed2a53531 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/repair/McMMOPlayerRepairCheckEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/repair/McMMOPlayerRepairCheckEvent.java @@ -44,7 +44,9 @@ public class McMMOPlayerRepairCheckEvent extends McMMOPlayerSkillEvent implement return repairedObject; } - /** Following are required for Cancellable **/ + /** + * Following are required for Cancellable + **/ @Override public boolean isCancelled() { return cancelled; diff --git a/src/main/java/com/gmail/nossr50/events/skills/salvage/McMMOPlayerSalvageCheckEvent.java b/src/main/java/com/gmail/nossr50/events/skills/salvage/McMMOPlayerSalvageCheckEvent.java index 0a44c2621..3fe909e49 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/salvage/McMMOPlayerSalvageCheckEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/salvage/McMMOPlayerSalvageCheckEvent.java @@ -44,7 +44,9 @@ public class McMMOPlayerSalvageCheckEvent extends McMMOPlayerSkillEvent implemen return enchantedBook; } - /** Following are required for Cancellable **/ + /** + * Following are required for Cancellable + **/ @Override public boolean isCancelled() { return cancelled; diff --git a/src/main/java/com/gmail/nossr50/events/skills/secondaryabilities/SubSkillEvent.java b/src/main/java/com/gmail/nossr50/events/skills/secondaryabilities/SubSkillEvent.java index 30351d9e3..68e9147ac 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/secondaryabilities/SubSkillEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/secondaryabilities/SubSkillEvent.java @@ -13,7 +13,8 @@ public class SubSkillEvent extends McMMOPlayerSkillEvent implements Cancellable /** * Only skills using the old system will fire this event - * @param player target player + * + * @param player target player * @param subSkillType target subskill * @Deprecated Skills will be using a new system stemming from the AbstractSubSkill class so make sure you check for both events, this event will be removed eventually. */ @@ -23,13 +24,13 @@ public class SubSkillEvent extends McMMOPlayerSkillEvent implements Cancellable this.subSkillType = subSkillType; } - public SubSkillEvent(Player player, AbstractSubSkill abstractSubSkill) - { + public SubSkillEvent(Player player, AbstractSubSkill abstractSubSkill) { super(player, abstractSubSkill.getPrimarySkill()); } /** * Gets the SubSkillType involved in the event + * * @return the SubSkillType */ public SubSkillType getSubSkillType() { diff --git a/src/main/java/com/gmail/nossr50/events/skills/secondaryabilities/SubSkillRandomCheckEvent.java b/src/main/java/com/gmail/nossr50/events/skills/secondaryabilities/SubSkillRandomCheckEvent.java index c1a90a425..32af79dde 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/secondaryabilities/SubSkillRandomCheckEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/secondaryabilities/SubSkillRandomCheckEvent.java @@ -12,8 +12,7 @@ public class SubSkillRandomCheckEvent extends SubSkillEvent { this.chance = chance; } - public SubSkillRandomCheckEvent(Player player, AbstractSubSkill abstractSubSkill, double chance) - { + public SubSkillRandomCheckEvent(Player player, AbstractSubSkill abstractSubSkill, double chance) { super(player, abstractSubSkill); this.chance = chance; } diff --git a/src/main/java/com/gmail/nossr50/events/skills/unarmed/McMMOPlayerDisarmEvent.java b/src/main/java/com/gmail/nossr50/events/skills/unarmed/McMMOPlayerDisarmEvent.java index 0859a37d1..5b991ebda 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/unarmed/McMMOPlayerDisarmEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/unarmed/McMMOPlayerDisarmEvent.java @@ -18,7 +18,9 @@ public class McMMOPlayerDisarmEvent extends McMMOPlayerSkillEvent implements Can return defender; } - /** Following are required for Cancellable **/ + /** + * Following are required for Cancellable + **/ @Override public boolean isCancelled() { return cancelled; diff --git a/src/main/java/com/gmail/nossr50/listeners/BlockListener.java b/src/main/java/com/gmail/nossr50/listeners/BlockListener.java index 3650fb2cf..ae135ee05 100644 --- a/src/main/java/com/gmail/nossr50/listeners/BlockListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/BlockListener.java @@ -55,26 +55,21 @@ public class BlockListener implements Listener { } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockDropItemEvent(BlockDropItemEvent event) - { - for(Item item : event.getItems()) - { + public void onBlockDropItemEvent(BlockDropItemEvent event) { + for (Item item : event.getItems()) { ItemStack is = new ItemStack(item.getItemStack()); - if(is.getAmount() <= 0) + if (is.getAmount() <= 0) continue; - if(!mcMMO.getConfigManager().getBonusDropManager().isBonusDropWhitelisted(is.getType())) + if (!mcMMO.getConfigManager().getBonusDropManager().isBonusDropWhitelisted(is.getType())) continue; //TODO: Should just store the amount of drops in the metadata itself and use a loop - if(event.getBlock().getState().getMetadata(mcMMO.doubleDrops).size() > 0) - { + if (event.getBlock().getState().getMetadata(mcMMO.doubleDrops).size() > 0) { event.getBlock().getState().getWorld().dropItemNaturally(event.getBlockState().getLocation(), is); event.getBlock().getState().removeMetadata(mcMMO.doubleDrops, plugin); - } - else if(event.getBlock().getState().getMetadata(mcMMO.tripleDrops).size() > 0) - { + } else if (event.getBlock().getState().getMetadata(mcMMO.tripleDrops).size() > 0) { event.getBlock().getState().getWorld().dropItemNaturally(event.getBlockState().getLocation(), is); event.getBlock().getState().getWorld().dropItemNaturally(event.getBlockState().getLocation(), is); event.getBlock().getState().removeMetadata(mcMMO.tripleDrops, plugin); @@ -166,7 +161,7 @@ public class BlockListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockPistonExtend(BlockPistonExtendEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; BlockFace direction = event.getDirection(); @@ -177,7 +172,7 @@ public class BlockListener implements Listener { if (BlockUtils.shouldBeWatched(b.getState())) { movedBlock = b.getRelative(direction); - if(mcMMO.getConfigManager().getConfigExploitPrevention().doPistonsMarkBlocksUnnatural()) + if (mcMMO.getConfigManager().getConfigExploitPrevention().doPistonsMarkBlocksUnnatural()) mcMMO.getPlaceStore().setTrue(movedBlock); } } @@ -191,7 +186,7 @@ public class BlockListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockPistonRetract(BlockPistonRetractEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; // Get opposite direction so we get correct block @@ -211,14 +206,12 @@ public class BlockListener implements Listener { * @param event The event to watch */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onEntityBlockFormEvent(EntityBlockFormEvent event) - { + public void onEntityBlockFormEvent(EntityBlockFormEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; - if(BlockUtils.shouldBeWatched(event.getBlock().getState())) - { + if (BlockUtils.shouldBeWatched(event.getBlock().getState())) { mcMMO.getPlaceStore().setTrue(event.getBlock()); } } @@ -231,14 +224,14 @@ public class BlockListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onFallingBlock(EntityChangeBlockEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; if (BlockUtils.shouldBeWatched(event.getBlock().getState()) && event.getEntityType().equals(EntityType.FALLING_BLOCK)) { if (event.getTo().equals(Material.AIR) && mcMMO.getPlaceStore().isTrue(event.getBlock())) { - event.getEntity().setMetadata("mcMMOBlockFall", new FixedMetadataValue( plugin, event.getBlock().getLocation())); + event.getEntity().setMetadata("mcMMOBlockFall", new FixedMetadataValue(plugin, event.getBlock().getLocation())); } else { - List values = event.getEntity().getMetadata( "mcMMOBlockFall" ); + List values = event.getEntity().getMetadata("mcMMOBlockFall"); if (!values.isEmpty()) { @@ -246,8 +239,8 @@ public class BlockListener implements Listener { Block spawn = ((org.bukkit.Location) values.get(0).value()).getBlock(); - mcMMO.getPlaceStore().setTrue( event.getBlock() ); - mcMMO.getPlaceStore().setFalse( spawn ); + mcMMO.getPlaceStore().setTrue(event.getBlock()); + mcMMO.getPlaceStore().setFalse(spawn); } } @@ -262,7 +255,7 @@ public class BlockListener implements Listener { @EventHandler(priority = EventPriority.MONITOR) public void onBlockPlace(BlockPlaceEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; Player player = event.getPlayer(); @@ -305,7 +298,7 @@ public class BlockListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockMultiPlace(BlockMultiPlaceEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; Player player = event.getPlayer(); @@ -314,8 +307,7 @@ public class BlockListener implements Listener { return; } - for (BlockState replacedBlockState : event.getReplacedBlockStates()) - { + for (BlockState replacedBlockState : event.getReplacedBlockStates()) { BlockState blockState = replacedBlockState.getBlock().getState(); /* Check if the blocks placed should be monitored so they do not give out XP in the future */ @@ -326,10 +318,9 @@ public class BlockListener implements Listener { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockGrow(BlockGrowEvent event) - { + public void onBlockGrow(BlockGrowEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; BlockState blockState = event.getBlock().getState(); @@ -349,13 +340,12 @@ public class BlockListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockBreak(BlockBreakEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) return; } @@ -384,7 +374,7 @@ public class BlockListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Check if profile is loaded - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) return; ItemStack heldItem = player.getInventory().getItemInMainHand(); @@ -418,8 +408,7 @@ public class BlockListener implements Listener { WoodcuttingManager woodcuttingManager = mcMMOPlayer.getWoodcuttingManager(); if (woodcuttingManager.canUseTreeFeller(heldItem)) { woodcuttingManager.processTreeFeller(blockState); - } - else { + } else { woodcuttingManager.woodcuttingBlockCheck(blockState); } } @@ -446,13 +435,12 @@ public class BlockListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockBreakHigher(BlockBreakEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) return; } @@ -467,8 +455,7 @@ public class BlockListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -487,8 +474,7 @@ public class BlockListener implements Listener { if (herbalismManager.processHylianLuck(blockState)) { blockState.update(true); event.setCancelled(true); - } - else if (blockState.getType() == Material.FLOWER_POT) { + } else if (blockState.getType() == Material.FLOWER_POT) { blockState.setType(Material.AIR); blockState.update(true); event.setCancelled(true); @@ -518,13 +504,12 @@ public class BlockListener implements Listener { BlockState blockState = event.getBlock().getState(); /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) return; } @@ -538,8 +523,7 @@ public class BlockListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Profile not loaded - if(mcMMOPlayer == null) - { + if (mcMMOPlayer == null) { return; } @@ -553,17 +537,13 @@ public class BlockListener implements Listener { if (mcMMOPlayer.getToolPreparationMode(ToolType.HOE) && ItemUtils.isHoe(heldItem) && (BlockUtils.affectedByGreenTerra(blockState) || BlockUtils.canMakeMossy(blockState)) && Permissions.greenTerra(player)) { mcMMOPlayer.checkAbilityActivation(PrimarySkillType.HERBALISM); - } - else if (mcMMOPlayer.getToolPreparationMode(ToolType.AXE) && ItemUtils.isAxe(heldItem) && BlockUtils.isLog(blockState) && Permissions.treeFeller(player)) { + } else if (mcMMOPlayer.getToolPreparationMode(ToolType.AXE) && ItemUtils.isAxe(heldItem) && BlockUtils.isLog(blockState) && Permissions.treeFeller(player)) { mcMMOPlayer.checkAbilityActivation(PrimarySkillType.WOODCUTTING); - } - else if (mcMMOPlayer.getToolPreparationMode(ToolType.PICKAXE) && ItemUtils.isPickaxe(heldItem) && BlockUtils.affectedBySuperBreaker(blockState) && Permissions.superBreaker(player)) { + } else if (mcMMOPlayer.getToolPreparationMode(ToolType.PICKAXE) && ItemUtils.isPickaxe(heldItem) && BlockUtils.affectedBySuperBreaker(blockState) && Permissions.superBreaker(player)) { mcMMOPlayer.checkAbilityActivation(PrimarySkillType.MINING); - } - else if (mcMMOPlayer.getToolPreparationMode(ToolType.SHOVEL) && ItemUtils.isShovel(heldItem) && BlockUtils.affectedByGigaDrillBreaker(blockState) && Permissions.gigaDrillBreaker(player)) { + } else if (mcMMOPlayer.getToolPreparationMode(ToolType.SHOVEL) && ItemUtils.isShovel(heldItem) && BlockUtils.affectedByGigaDrillBreaker(blockState) && Permissions.gigaDrillBreaker(player)) { mcMMOPlayer.checkAbilityActivation(PrimarySkillType.EXCAVATION); - } - else if (mcMMOPlayer.getToolPreparationMode(ToolType.FISTS) && heldItem.getType() == Material.AIR && (BlockUtils.affectedByGigaDrillBreaker(blockState) || blockState.getType() == Material.SNOW || BlockUtils.affectedByBlockCracker(blockState) && Permissions.berserk(player))) { + } else if (mcMMOPlayer.getToolPreparationMode(ToolType.FISTS) && heldItem.getType() == Material.AIR && (BlockUtils.affectedByGigaDrillBreaker(blockState) || blockState.getType() == Material.SNOW || BlockUtils.affectedByBlockCracker(blockState) && Permissions.berserk(player))) { mcMMOPlayer.checkAbilityActivation(PrimarySkillType.UNARMED); } } @@ -596,13 +576,12 @@ public class BlockListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockDamageHigher(BlockDamageEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) return; } @@ -619,8 +598,7 @@ public class BlockListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -637,19 +615,16 @@ public class BlockListener implements Listener { if (mcMMOPlayer.getHerbalismManager().processGreenTerra(blockState)) { blockState.update(true); } - } - else if (mcMMOPlayer.getAbilityMode(SuperAbilityType.BERSERK) && heldItem.getType() == Material.AIR) { + } else if (mcMMOPlayer.getAbilityMode(SuperAbilityType.BERSERK) && heldItem.getType() == Material.AIR) { if (SuperAbilityType.BERSERK.blockCheck(block.getState()) && EventUtils.simulateBlockBreak(block, player, true)) { event.setInstaBreak(true); SoundManager.sendSound(player, block.getLocation(), SoundType.POP); - } - else if (mcMMOPlayer.getUnarmedManager().canUseBlockCracker() && BlockUtils.affectedByBlockCracker(blockState) && EventUtils.simulateBlockBreak(block, player, true)) { + } else if (mcMMOPlayer.getUnarmedManager().canUseBlockCracker() && BlockUtils.affectedByBlockCracker(blockState) && EventUtils.simulateBlockBreak(block, player, true)) { if (mcMMOPlayer.getUnarmedManager().blockCrackerCheck(blockState)) { blockState.update(); } } - } - else if (mcMMOPlayer.getWoodcuttingManager().canUseLeafBlower(heldItem) && BlockUtils.isLeaves(blockState) && EventUtils.simulateBlockBreak(block, player, true)) { + } else if (mcMMOPlayer.getWoodcuttingManager().canUseLeafBlower(heldItem) && BlockUtils.isLeaves(blockState) && EventUtils.simulateBlockBreak(block, player, true)) { event.setInstaBreak(true); SoundManager.sendSound(player, block.getLocation(), SoundType.POP); } @@ -661,8 +636,7 @@ public class BlockListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -678,51 +652,43 @@ public class BlockListener implements Listener { public void debugStickDump(Player player, BlockState blockState) { //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } - if(player.getInventory().getItemInMainHand().getType() == Material.DEBUG_STICK) - { - if(mcMMO.getPlaceStore().isTrue(blockState)) + if (player.getInventory().getItemInMainHand().getType() == Material.DEBUG_STICK) { + if (mcMMO.getPlaceStore().isTrue(blockState)) player.sendMessage("[mcMMO DEBUG] This block is not natural and does not reward treasures/XP"); - else - { + else { player.sendMessage("[mcMMO DEBUG] This block is considered natural by mcMMO"); UserManager.getPlayer(player).getExcavationManager().printExcavationDebug(player, blockState); } - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (WorldGuardManager.getInstance().hasMainFlag(player)) player.sendMessage("[mcMMO DEBUG] World Guard main flag is permitted for this player in this region"); else player.sendMessage("[mcMMO DEBUG] World Guard main flag is DENIED for this player in this region"); - if(WorldGuardManager.getInstance().hasXPFlag(player)) + if (WorldGuardManager.getInstance().hasXPFlag(player)) player.sendMessage("[mcMMO DEBUG] World Guard xp flag is permitted for this player in this region"); else player.sendMessage("[mcMMO DEBUG] World Guard xp flag is not permitted for this player in this region"); } - if(blockState instanceof Furnace) - { + if (blockState instanceof Furnace) { Furnace furnace = (Furnace) blockState; - if(furnace.hasMetadata(mcMMO.furnaceMetadataKey)) - { + if (furnace.hasMetadata(mcMMO.furnaceMetadataKey)) { player.sendMessage("[mcMMO DEBUG] This furnace has a registered owner"); Player furnacePlayer = getPlayerFromFurnace(furnace.getBlock()); - if(furnacePlayer != null) - { - player.sendMessage("[mcMMO DEBUG] This furnace is owned by player "+furnacePlayer.getName()); + if (furnacePlayer != null) { + player.sendMessage("[mcMMO DEBUG] This furnace is owned by player " + furnacePlayer.getName()); } - } - else + } else player.sendMessage("[mcMMO DEBUG] This furnace does not have a registered owner"); } - if(ExperienceConfig.getInstance().isExperienceBarsEnabled()) + if (ExperienceConfig.getInstance().isExperienceBarsEnabled()) player.sendMessage("[mcMMO DEBUG] XP bars are enabled, however you should check per-skill settings to make sure those are enabled."); } } diff --git a/src/main/java/com/gmail/nossr50/listeners/EntityListener.java b/src/main/java/com/gmail/nossr50/listeners/EntityListener.java index ebcafc760..d1896562a 100644 --- a/src/main/java/com/gmail/nossr50/listeners/EntityListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/EntityListener.java @@ -52,28 +52,23 @@ public class EntityListener implements Listener { } @EventHandler(priority = EventPriority.MONITOR) - public void onEntityTransform(EntityTransformEvent event) - { + public void onEntityTransform(EntityTransformEvent event) { //Transfer metadata keys from mob-spawned mobs to new mobs - if(event.getEntity().getMetadata(mcMMO.entityMetadataKey) != null || event.getEntity().getMetadata(mcMMO.entityMetadataKey).size() >= 1) - { - for(Entity entity : event.getTransformedEntities()) - { + if (event.getEntity().getMetadata(mcMMO.entityMetadataKey) != null || event.getEntity().getMetadata(mcMMO.entityMetadataKey).size() >= 1) { + for (Entity entity : event.getTransformedEntities()) { entity.setMetadata(mcMMO.entityMetadataKey, mcMMO.metadataValue); } } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onEntityTargetEntity(EntityTargetLivingEntityEvent event) - { - if(!mcMMO.getConfigManager().getConfigExploitPrevention().getEndermenEndermiteFix()) + public void onEntityTargetEntity(EntityTargetLivingEntityEvent event) { + if (!mcMMO.getConfigManager().getConfigExploitPrevention().getEndermenEndermiteFix()) return; //Prevent entities from giving XP if they target endermite - if(event.getTarget() instanceof Endermite) - { - if(event.getEntity().getMetadata(mcMMO.entityMetadataKey) == null || event.getEntity().getMetadata(mcMMO.entityMetadataKey).size() <= 0) + if (event.getTarget() instanceof Endermite) { + if (event.getEntity().getMetadata(mcMMO.entityMetadataKey) == null || event.getEntity().getMetadata(mcMMO.entityMetadataKey).size() <= 0) event.getEntity().setMetadata(mcMMO.entityMetadataKey, mcMMO.metadataValue); } } @@ -81,17 +76,15 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityShootBow(EntityShootBowEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; - if(event.getEntity() instanceof Player) - { + if (event.getEntity() instanceof Player) { Player player = (Player) event.getEntity(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } } @@ -115,17 +108,15 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onProjectileLaunch(ProjectileLaunchEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; - if(event.getEntity() instanceof Player) - { + if (event.getEntity() instanceof Player) { Player player = (Player) event.getEntity(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } } @@ -143,13 +134,12 @@ public class EntityListener implements Listener { /** * Monitor EntityChangeBlock events. * - * @param event - * The event to watch + * @param event The event to watch */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityChangeBlock(EntityChangeBlockEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; Block block = event.getBlock(); @@ -169,13 +159,11 @@ public class EntityListener implements Listener { if (mcMMO.getPlaceStore().isTrue(block) && !isTracked) { mcMMO.getPlaceStore().setFalse(block); entity.setMetadata(mcMMO.entityMetadataKey, mcMMO.metadataValue); - } - else if (isTracked) { + } else if (isTracked) { mcMMO.getPlaceStore().setTrue(block); } } else if ((block.getType() == Material.REDSTONE_ORE)) { - } - else { + } else { if (mcMMO.getPlaceStore().isTrue(block)) { mcMMO.getPlaceStore().setFalse(block); } @@ -232,16 +220,13 @@ public class EntityListener implements Listener { }*/ @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onEntityDamageLowest(EntityDamageByEntityEvent event) - { + public void onEntityDamageLowest(EntityDamageByEntityEvent event) { Entity defender = event.getEntity(); - if(defender.getMetadata(mcMMO.CUSTOM_DAMAGE_METAKEY).size() > 0) - { + if (defender.getMetadata(mcMMO.CUSTOM_DAMAGE_METAKEY).size() > 0) { defender.removeMetadata(mcMMO.CUSTOM_DAMAGE_METAKEY, plugin); - if(defender instanceof Player) - { + if (defender instanceof Player) { LivingEntity defLive = (LivingEntity) defender; defLive.setHealth(Math.max(0, (defLive.getHealth() - event.getFinalDamage()))); event.setCancelled(true); @@ -253,8 +238,7 @@ public class EntityListener implements Listener { /** * Handle EntityDamageByEntity events that involve modifying the event. * - * @param event - * The event to watch + * @param event The event to watch */ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { @@ -263,7 +247,7 @@ public class EntityListener implements Listener { Entity attacker = event.getDamager(); /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; if (event instanceof FakeEntityDamageByEntityEvent) { @@ -273,21 +257,18 @@ public class EntityListener implements Listener { if (event.getEntity() instanceof ArmorStand) { return; } - - if (event.getDamager().hasMetadata(mcMMO.funfettiMetadataKey)) - { + + if (event.getDamager().hasMetadata(mcMMO.funfettiMetadataKey)) { event.setCancelled(true); return; } - if(attacker instanceof Player) - { + if (attacker instanceof Player) { Player player = (Player) attacker; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } } @@ -298,7 +279,7 @@ public class EntityListener implements Listener { Player attackingPlayer = (Player) attacker; if (event.getDamage(DamageModifier.ABSORPTION) > 0) { //If friendly fire is off don't allow players to hurt one another - if(!mcMMO.getConfigManager().getConfigParty().isPartyFriendlyFireEnabled()) + if (!mcMMO.getConfigManager().getConfigParty().isPartyFriendlyFireEnabled()) if ((PartyManager.inSameParty(defendingPlayer, attackingPlayer) || PartyManager.areAllies(defendingPlayer, attackingPlayer)) && !(Permissions.friendlyFire(attackingPlayer) && Permissions.friendlyFire(defendingPlayer))) { event.setCancelled(true); return; @@ -338,15 +319,13 @@ public class EntityListener implements Listener { if (projectileSource instanceof LivingEntity) { attacker = (LivingEntity) projectileSource; } - } - else if (attacker instanceof Tameable) { + } else if (attacker instanceof Tameable) { AnimalTamer animalTamer = ((Tameable) attacker).getOwner(); if (animalTamer != null && ((OfflinePlayer) animalTamer).isOnline()) { attacker = (Entity) animalTamer; } - } - else if (attacker instanceof TNTPrimed && defender instanceof Player) { + } else if (attacker instanceof TNTPrimed && defender instanceof Player) { if (BlastMining.processBlastMiningExplosion(event, (TNTPrimed) attacker, (Player) defender)) { return; } @@ -367,12 +346,12 @@ public class EntityListener implements Listener { } //Party Friendly Fire - if(!mcMMO.getConfigManager().getConfigParty().isPartyFriendlyFireEnabled()) + if (!mcMMO.getConfigManager().getConfigParty().isPartyFriendlyFireEnabled()) if ((PartyManager.inSameParty(defendingPlayer, attackingPlayer) || PartyManager.areAllies(defendingPlayer, attackingPlayer)) && !(Permissions.friendlyFire(attackingPlayer) && Permissions.friendlyFire(defendingPlayer))) { event.setCancelled(true); return; - } + } } CombatUtils.processCombatAttack(event, attacker, target); @@ -381,17 +360,14 @@ public class EntityListener implements Listener { /** * This sets entity names back to whatever they are supposed to be */ - if(!(attacker instanceof Player) && defender instanceof Player) - { - if(event.getFinalDamage() >= ((LivingEntity) defender).getHealth()) - { + if (!(attacker instanceof Player) && defender instanceof Player) { + if (event.getFinalDamage() >= ((LivingEntity) defender).getHealth()) { List metadataValue = attacker.getMetadata("mcMMO_oldName"); - if(metadataValue.size() <= 0) + if (metadataValue.size() <= 0) return; - if(metadataValue != null) - { + if (metadataValue != null) { OldName oldName = (OldName) metadataValue.get(0); attacker.setCustomName(oldName.asString()); attacker.setCustomNameVisible(false); @@ -405,22 +381,19 @@ public class EntityListener implements Listener { /** * Handle EntityDamage events that involve modifying the event. * - * @param event - * The event to modify + * @param event The event to modify */ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEntityDamage(EntityDamageEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; - if(event.getEntity() instanceof Player) - { + if (event.getEntity() instanceof Player) { Player player = (Player) event.getEntity(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } } @@ -477,7 +450,7 @@ public class EntityListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Profile not loaded - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) return; /* Check for invincibility */ @@ -490,19 +463,15 @@ public class EntityListener implements Listener { mcMMOPlayer.actualizeRecentlyHurt(); } - } - - else if (livingEntity instanceof Tameable) { + } else if (livingEntity instanceof Tameable) { Tameable pet = (Tameable) livingEntity; AnimalTamer owner = pet.getOwner(); - if(owner instanceof Player) - { + if (owner instanceof Player) { Player player = (Player) owner; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } } @@ -512,8 +481,7 @@ public class EntityListener implements Listener { Wolf wolf = (Wolf) pet; //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -580,13 +548,12 @@ public class EntityListener implements Listener { /** * Monitor EntityDeath events. * - * @param event - * The event to watch + * @param event The event to watch */ @EventHandler(priority = EventPriority.LOWEST) public void onEntityDeathLowest(EntityDeathEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; LivingEntity entity = event.getEntity(); @@ -613,13 +580,12 @@ public class EntityListener implements Listener { /** * Monitor EntityDeath events. * - * @param event - * The event to watch + * @param event The event to watch */ @EventHandler(priority = EventPriority.MONITOR) public void onEntityDeath(EntityDeathEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; LivingEntity entity = event.getEntity(); @@ -634,13 +600,12 @@ public class EntityListener implements Listener { /** * Monitor CreatureSpawn events. * - * @param event - * The event to watch + * @param event The event to watch */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onCreatureSpawn(CreatureSpawnEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; LivingEntity entity = event.getEntity(); @@ -649,8 +614,7 @@ public class EntityListener implements Listener { case NETHER_PORTAL: case SPAWNER: case SPAWNER_EGG: - if(mcMMO.getConfigManager().getConfigExploitPrevention().doSpawnedEntitiesGiveModifiedXP()) - { + if (mcMMO.getConfigManager().getConfigExploitPrevention().doSpawnedEntitiesGiveModifiedXP()) { entity.setMetadata(mcMMO.entityMetadataKey, mcMMO.metadataValue); Entity passenger = entity.getPassenger(); @@ -672,13 +636,12 @@ public class EntityListener implements Listener { /** * Handle ExplosionPrime events that involve modifying the event. * - * @param event - * The event to modify + * @param event The event to modify */ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onExplosionPrime(ExplosionPrimeEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; Entity entity = event.getEntity(); @@ -696,15 +659,13 @@ public class EntityListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -718,13 +679,12 @@ public class EntityListener implements Listener { /** * Handle EntityExplode events that involve modifying the event. * - * @param event - * The event to modify + * @param event The event to modify */ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEnitityExplode(EntityExplodeEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; Entity entity = event.getEntity(); @@ -742,15 +702,13 @@ public class EntityListener implements Listener { } /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -765,13 +723,12 @@ public class EntityListener implements Listener { /** * Handle EntityExplode events that involve modifying the event. * - * @param event - * The event to modify + * @param event The event to modify */ @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onEntityExplodeMonitor(EntityExplodeEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; Entity entity = event.getEntity(); @@ -786,13 +743,12 @@ public class EntityListener implements Listener { /** * Handle FoodLevelChange events that involve modifying the event. * - * @param event - * The event to modify + * @param event The event to modify */ @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onFoodLevelChange(FoodLevelChangeEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; Entity entity = event.getEntity(); @@ -804,15 +760,13 @@ public class EntityListener implements Listener { Player player = (Player) entity; //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -835,34 +789,34 @@ public class EntityListener implements Listener { */ switch (player.getInventory().getItemInMainHand().getType()) { case BAKED_POTATO: /* - * RESTORES 3 HUNGER - RESTORES 5 1/2 HUNGER @ - * 1000 - */ + * RESTORES 3 HUNGER - RESTORES 5 1/2 HUNGER @ + * 1000 + */ case BEETROOT: case BREAD: /* RESTORES 2 1/2 HUNGER - RESTORES 5 HUNGER @ 1000 */ case CARROT: /* - * RESTORES 2 HUNGER - RESTORES 4 1/2 HUNGER @ - * 1000 - */ + * RESTORES 2 HUNGER - RESTORES 4 1/2 HUNGER @ + * 1000 + */ case GOLDEN_CARROT: /* - * RESTORES 3 HUNGER - RESTORES 5 1/2 HUNGER @ - * 1000 - */ + * RESTORES 3 HUNGER - RESTORES 5 1/2 HUNGER @ + * 1000 + */ case MUSHROOM_STEW: /* - * RESTORES 4 HUNGER - RESTORES 6 1/2 HUNGER @ - * 1000 - */ + * RESTORES 4 HUNGER - RESTORES 6 1/2 HUNGER @ + * 1000 + */ case PUMPKIN_PIE: /* - * RESTORES 4 HUNGER - RESTORES 6 1/2 HUNGER @ - * 1000 - */ + * RESTORES 4 HUNGER - RESTORES 6 1/2 HUNGER @ + * 1000 + */ case COOKIE: /* RESTORES 1/2 HUNGER - RESTORES 2 HUNGER @ 1000 */ case MELON_SLICE: /* RESTORES 1 HUNGER - RESTORES 2 1/2 HUNGER @ 1000 */ case POISONOUS_POTATO: /* - * RESTORES 1 HUNGER - RESTORES 2 1/2 HUNGER - * @ 1000 - */ + * RESTORES 1 HUNGER - RESTORES 2 1/2 HUNGER + * @ 1000 + */ case POTATO: /* RESTORES 1/2 HUNGER - RESTORES 2 HUNGER @ 1000 */ if (Permissions.isSubSkillEnabled(player, SubSkillType.HERBALISM_FARMERS_DIET)) { event.setFoodLevel(UserManager.getPlayer(player).getHerbalismManager().farmersDiet(newFoodLevel)); @@ -885,13 +839,12 @@ public class EntityListener implements Listener { /** * Monitor EntityTame events. * - * @param event - * The event to watch + * @param event The event to watch */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityTame(EntityTameEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; if (event instanceof FakeEntityTameEvent) { @@ -901,9 +854,8 @@ public class EntityListener implements Listener { Player player = (Player) event.getOwner(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -913,7 +865,7 @@ public class EntityListener implements Listener { return; } - if(mcMMO.getConfigManager().getConfigExploitPrevention().doTamedEntitiesGiveXP()) + if (mcMMO.getConfigManager().getConfigExploitPrevention().doTamedEntitiesGiveXP()) entity.setMetadata(mcMMO.entityMetadataKey, mcMMO.metadataValue); //Profile not loaded @@ -930,13 +882,12 @@ public class EntityListener implements Listener { /** * Handle EntityTarget events. * - * @param event - * The event to process + * @param event The event to process */ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEntityTarget(EntityTargetEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; Entity entity = event.getEntity(); @@ -949,9 +900,8 @@ public class EntityListener implements Listener { Player player = (Player) target; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -973,13 +923,12 @@ public class EntityListener implements Listener { * Handle PotionSplash events in order to fix broken Splash Potion of * Saturation. * - * @param event - * The event to process + * @param event The event to process */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPotionSplash(PotionSplashEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; for (PotionEffect effect : ((PotionMeta) event.getPotion().getItem().getItemMeta()).getCustomEffects()) { @@ -993,11 +942,11 @@ public class EntityListener implements Listener { } } } - + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPigZapEvent(PigZapEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; if (event.getEntity().hasMetadata(mcMMO.entityMetadataKey)) { diff --git a/src/main/java/com/gmail/nossr50/listeners/InteractionManager.java b/src/main/java/com/gmail/nossr50/listeners/InteractionManager.java index a12f8ae18..2a7689d4a 100644 --- a/src/main/java/com/gmail/nossr50/listeners/InteractionManager.java +++ b/src/main/java/com/gmail/nossr50/listeners/InteractionManager.java @@ -17,22 +17,22 @@ public class InteractionManager { /** * Registers subskills with the Interaction registration + * * @param abstractSubSkill the target subskill to register */ - public static void registerSubSkill(AbstractSubSkill abstractSubSkill) - { + public static void registerSubSkill(AbstractSubSkill abstractSubSkill) { /* INIT MAPS */ - if(interactRegister == null) + if (interactRegister == null) interactRegister = new HashMap<>(); - if(subSkillList == null) + if (subSkillList == null) subSkillList = new ArrayList<>(); - if(subSkillNameMap == null) + if (subSkillNameMap == null) subSkillNameMap = new HashMap<>(); //Store a unique copy of each subskill - if(!subSkillList.contains(abstractSubSkill)) + if (!subSkillList.contains(abstractSubSkill)) subSkillList.add(abstractSubSkill); //Init ArrayList @@ -49,30 +49,29 @@ public class InteractionManager { //Register in name map subSkillNameMap.putIfAbsent(lowerCaseName, abstractSubSkill); - System.out.println("[mcMMO] registered subskill: "+ abstractSubSkill.getConfigKeyName()); + System.out.println("[mcMMO] registered subskill: " + abstractSubSkill.getConfigKeyName()); } /** * Grabs the registered abstract skill by its name * Is not case sensitive + * * @param name name of subskill, not case sensitive * @return null if the subskill is not registered */ - public static AbstractSubSkill getAbstractByName(String name) - { + public static AbstractSubSkill getAbstractByName(String name) { return subSkillNameMap.get(name.toLowerCase()); } /** * Processes the associated Interactions for this event - * @param event target event - * @param plugin instance of mcMMO plugin + * + * @param event target event + * @param plugin instance of mcMMO plugin * @param curInteractType the associated interaction type */ - public static void processEvent(Event event, mcMMO plugin, InteractType curInteractType) - { - for(Interaction interaction : interactRegister.get(curInteractType)) - { + public static void processEvent(Event event, mcMMO plugin, InteractType curInteractType) { + for (Interaction interaction : interactRegister.get(curInteractType)) { interaction.doInteraction(event, plugin); } } @@ -80,25 +79,24 @@ public class InteractionManager { /** * Returns the list that contains all unique instances of registered Interaction classes * Interactions are extensions of abstract classes that represent modifying behaviours in Minecraft through events + * * @return the unique collection of all registered Interaction classes */ - public static ArrayList getSubSkillList() - { + public static ArrayList getSubSkillList() { return subSkillList; } - public static boolean hasSubSkill(String name) - { + public static boolean hasSubSkill(String name) { return getAbstractByName(name) != null; } - public static boolean hasSubSkill(SubSkillType subSkillType) - { + public static boolean hasSubSkill(SubSkillType subSkillType) { return hasSubSkill(subSkillType.getNiceNameNoSpaces(subSkillType)); } /** * Returns the associative map which contains all registered interactions + * * @return the interact register */ public static HashMap> getInteractRegister() { diff --git a/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java b/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java index c4926f5f3..77ffa7642 100644 --- a/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java @@ -42,7 +42,7 @@ public class InventoryListener implements Listener { @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onInventoryOpen(InventoryOpenEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) return; Block furnaceBlock = processInventoryOpenOrCloseEvent(event.getInventory()); @@ -58,19 +58,18 @@ public class InventoryListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer((Player) player) == null) - { + if (UserManager.getPlayer((Player) player) == null) { return; } - if(!furnaceBlock.hasMetadata(mcMMO.furnaceMetadataKey) && furnaceBlock.getMetadata(mcMMO.furnaceMetadataKey).size() == 0) + if (!furnaceBlock.hasMetadata(mcMMO.furnaceMetadataKey) && furnaceBlock.getMetadata(mcMMO.furnaceMetadataKey).size() == 0) furnaceBlock.setMetadata(mcMMO.furnaceMetadataKey, UserManager.getPlayer((Player) player).getPlayerMetadata()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onInventoryClose(InventoryCloseEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) return; Block furnaceBlock = processInventoryOpenOrCloseEvent(event.getInventory()); @@ -91,7 +90,7 @@ public class InventoryListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onFurnaceBurnEvent(FurnaceBurnEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; Block furnaceBlock = event.getBlock(); @@ -105,9 +104,8 @@ public class InventoryListener implements Listener { Player player = getPlayerFromFurnace(furnaceBlock); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -116,8 +114,7 @@ public class InventoryListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -127,7 +124,7 @@ public class InventoryListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onFurnaceSmeltEvent(FurnaceSmeltEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; Block furnaceBlock = event.getBlock(); @@ -140,9 +137,8 @@ public class InventoryListener implements Listener { Player player = getPlayerFromFurnace(furnaceBlock); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -151,8 +147,7 @@ public class InventoryListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -162,7 +157,7 @@ public class InventoryListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onFurnaceExtractEvent(FurnaceExtractEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) return; Block furnaceBlock = event.getBlock(); @@ -174,9 +169,8 @@ public class InventoryListener implements Listener { Player player = getPlayerFromFurnace(furnaceBlock); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -185,8 +179,7 @@ public class InventoryListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -197,24 +190,21 @@ public class InventoryListener implements Listener { @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onInventoryClickEventNormal(InventoryClickEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getWhoClicked().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getWhoClicked().getWorld())) return; Inventory inventory = event.getInventory(); - if(event.getWhoClicked() instanceof Player) - { + if (event.getWhoClicked() instanceof Player) { Player player = ((Player) event.getWhoClicked()).getPlayer(); Block furnaceBlock = processInventoryOpenOrCloseEvent(event.getInventory()); - if (furnaceBlock != null) - { + if (furnaceBlock != null) { if (furnaceBlock.getMetadata(mcMMO.furnaceMetadataKey).size() > 0) furnaceBlock.removeMetadata(mcMMO.furnaceMetadataKey, mcMMO.p); //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -241,9 +231,8 @@ public class InventoryListener implements Listener { Player player = (Player) whoClicked; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -280,8 +269,7 @@ public class InventoryListener implements Listener { return; default: } - } - else if (slot == InventoryType.SlotType.FUEL) { + } else if (slot == InventoryType.SlotType.FUEL) { boolean emptyClicked = AlchemyPotionBrewer.isEmpty(clicked); if (AlchemyPotionBrewer.isEmpty(cursor)) { @@ -291,8 +279,7 @@ public class InventoryListener implements Listener { } AlchemyPotionBrewer.scheduleCheck(player, stand); - } - else if (emptyClicked) { + } else if (emptyClicked) { if (AlchemyPotionBrewer.isValidIngredient(player, cursor)) { int amount = cursor.getAmount(); @@ -303,8 +290,7 @@ public class InventoryListener implements Listener { AlchemyPotionBrewer.scheduleUpdate(inventory); AlchemyPotionBrewer.scheduleCheck(player, stand); - } - else if (click == ClickType.RIGHT) { + } else if (click == ClickType.RIGHT) { event.setCancelled(true); ItemStack one = cursor.clone(); @@ -327,7 +313,7 @@ public class InventoryListener implements Listener { @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onInventoryDragEvent(InventoryDragEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getWhoClicked().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getWhoClicked().getWorld())) return; Inventory inventory = event.getInventory(); @@ -359,9 +345,8 @@ public class InventoryListener implements Listener { Player player = (Player) whoClicked; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -378,10 +363,9 @@ public class InventoryListener implements Listener { // Apparently sometimes vanilla brewing beats our task listener to the actual brew. We handle this by cancelling the vanilla event and finishing our brew ourselves. @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onBrew(BrewEvent event) - { + public void onBrew(BrewEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; if (event instanceof FakeBrewEvent) @@ -396,7 +380,7 @@ public class InventoryListener implements Listener { @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onInventoryMoveItemEvent(InventoryMoveItemEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getSource().getLocation().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getSource().getLocation().getWorld())) return; Inventory inventory = event.getDestination(); @@ -444,7 +428,7 @@ public class InventoryListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onCraftItem(CraftItemEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getWhoClicked().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getWhoClicked().getWorld())) return; final HumanEntity whoClicked = event.getWhoClicked(); @@ -462,9 +446,8 @@ public class InventoryListener implements Listener { Player player = (Player) whoClicked; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } diff --git a/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java b/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java index 6e0720561..952cf7a69 100644 --- a/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java @@ -66,15 +66,14 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerTeleport(PlayerTeleportEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) return; Player player = event.getPlayer(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -83,12 +82,11 @@ public class PlayerListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } - if(mcMMO.getConfigManager().getConfigExploitPrevention().getConfigSectionExploitAcrobatics().isPreventAcrobaticsAbuse()) + if (mcMMO.getConfigManager().getConfigExploitPrevention().getConfigSectionExploitAcrobatics().isPreventAcrobaticsAbuse()) UserManager.getPlayer(player).actualizeTeleportATS(); @@ -107,15 +105,14 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPlayerDeathLowest(PlayerDeathEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; String deathMessage = event.getDeathMessage(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(event.getEntity())) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(event.getEntity())) return; } @@ -140,7 +137,7 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerDeathMonitor(PlayerDeathEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; boolean statLossEnabled = HardcoreManager.isStatLossEnabled(); @@ -159,9 +156,8 @@ public class PlayerListener implements Listener { Player killer = killedPlayer.getKiller(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(killedPlayer)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(killedPlayer)) return; } @@ -198,8 +194,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -221,13 +216,12 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerDropItem(PlayerDropItemEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) return; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) return; } @@ -252,15 +246,14 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPlayerFishHighest(PlayerFishEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) return; Player player = event.getPlayer(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -269,8 +262,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -281,20 +273,18 @@ public class PlayerListener implements Listener { //TODO Update to new API once available! Waiting for case CAUGHT_TREASURE: Item fishingCatch = (Item) event.getCaught(); - if (mcMMO.getConfigManager().getConfigFishing().isOverrideVanillaTreasures()) - { - if(fishingCatch.getItemStack().getType() != Material.SALMON && + if (mcMMO.getConfigManager().getConfigFishing().isOverrideVanillaTreasures()) { + if (fishingCatch.getItemStack().getType() != Material.SALMON && fishingCatch.getItemStack().getType() != Material.COD && fishingCatch.getItemStack().getType() != Material.TROPICAL_FISH && - fishingCatch.getItemStack().getType() != Material.PUFFERFISH) - { + fishingCatch.getItemStack().getType() != Material.PUFFERFISH) { fishingCatch.setItemStack(new ItemStack(Material.SALMON, 1)); } } if (Permissions.isSubSkillEnabled(player, SubSkillType.FISHING_INNER_PEACE)) { //Don't modify XP below vanilla values - if(fishingManager.addInnerPeaceVanillaXPBoost(event.getExpToDrop()) > 1) + if (fishingManager.addInnerPeaceVanillaXPBoost(event.getExpToDrop()) > 1) event.setExpToDrop(fishingManager.addInnerPeaceVanillaXPBoost(event.getExpToDrop())); } return; @@ -331,15 +321,14 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerFishMonitor(PlayerFishEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) return; Player player = event.getPlayer(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -348,8 +337,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -357,27 +345,22 @@ public class PlayerListener implements Listener { FishingManager fishingManager = UserManager.getPlayer(player).getFishingManager(); //Track the hook - if(mcMMO.getConfigManager().getConfigExploitPrevention().getConfigSectionExploitFishing().isPreventFishingExploits()) - { - if(event.getHook().getMetadata(mcMMO.FISH_HOOK_REF_METAKEY).size() == 0) - { + if (mcMMO.getConfigManager().getConfigExploitPrevention().getConfigSectionExploitFishing().isPreventFishingExploits()) { + if (event.getHook().getMetadata(mcMMO.FISH_HOOK_REF_METAKEY).size() == 0) { fishingManager.setFishHookReference(event.getHook()); } //Spam Fishing - if(event.getState() == PlayerFishEvent.State.CAUGHT_FISH && fishingManager.isFishingTooOften()) - { + if (event.getState() == PlayerFishEvent.State.CAUGHT_FISH && fishingManager.isFishingTooOften()) { event.setExpToDrop(0); - fishingManager.setFishHookReference(event.getHook()); + fishingManager.setFishHookReference(event.getHook()); } //Spam Fishing - if(event.getState() == PlayerFishEvent.State.CAUGHT_FISH && fishingManager.isFishingTooOften()) - { + if (event.getState() == PlayerFishEvent.State.CAUGHT_FISH && fishingManager.isFishingTooOften()) { event.setExpToDrop(0); - if(caught instanceof Item) - { + if (caught instanceof Item) { Item caughtItem = (Item) caught; caughtItem.remove(); } @@ -395,10 +378,8 @@ public class PlayerListener implements Listener { } return; case CAUGHT_FISH: - if(mcMMO.getConfigManager().getConfigExploitPrevention().getConfigSectionExploitFishing().isPreventFishingExploits()) - { - if(fishingManager.isExploitingFishing(event.getHook().getLocation().toVector())) - { + if (mcMMO.getConfigManager().getConfigExploitPrevention().getConfigSectionExploitFishing().isPreventFishingExploits()) { + if (fishingManager.isExploitingFishing(event.getHook().getLocation().toVector())) { player.sendMessage(LocaleLoader.getString("Fishing.Scarcity")); event.setExpToDrop(0); Item caughtItem = (Item) caught; @@ -432,17 +413,15 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPlayerPickupItem(EntityPickupItemEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; - if(event.getEntity() instanceof Player) - { + if (event.getEntity() instanceof Player) { Player player = (Player) event.getEntity(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -451,8 +430,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -470,7 +448,6 @@ public class PlayerListener implements Listener { } - if (!drop.hasMetadata(mcMMO.droppedItemKey) && mcMMOPlayer.inParty() && ItemUtils.isSharable(dropStack)) { event.setCancelled(ShareHandler.handleItemShare(drop, mcMMOPlayer)); @@ -508,8 +485,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -546,9 +522,8 @@ public class PlayerListener implements Listener { } //TODO: Remove this warning - if(mcMMO.p.getDescription().getVersion().contains("SNAPSHOT")) - { - event.getPlayer().sendMessage(ChatColor.RED+"WARNING: "+ChatColor.WHITE+"This dev build version of mcMMO is in the MIDDLE of completely rewriting the configs, there may be game breaking bugs. It is not recommended to play on this version of mcMMO, please grab the latest stable release from https://www.mcmmo.org and use that instead!"); + if (mcMMO.p.getDescription().getVersion().contains("SNAPSHOT")) { + event.getPlayer().sendMessage(ChatColor.RED + "WARNING: " + ChatColor.WHITE + "This dev build version of mcMMO is in the MIDDLE of completely rewriting the configs, there may be game breaking bugs. It is not recommended to play on this version of mcMMO, please grab the latest stable release from https://www.mcmmo.org and use that instead!"); } } @@ -570,8 +545,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -586,15 +560,14 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPlayerInteractLowest(PlayerInteractEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) return; Player player = event.getPlayer(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -603,8 +576,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -646,8 +618,7 @@ public class PlayerListener implements Listener { else if (miningManager.canDetonate()) { if (type == Material.TNT) { event.setCancelled(true); // Don't detonate the TNT if they're too close - } - else { + } else { miningManager.remoteDetonation(); } } @@ -695,15 +666,14 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.MONITOR) public void onPlayerInteractMonitor(PlayerInteractEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) return; Player player = event.getPlayer(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -712,8 +682,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -721,12 +690,9 @@ public class PlayerListener implements Listener { ItemStack heldItem = player.getInventory().getItemInMainHand(); //Spam Fishing Detection - if(mcMMO.getConfigManager().getConfigExploitPrevention().getConfigSectionExploitFishing().isPreventFishingExploits()) - { - if(event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_AIR) - { - if(player.isInsideVehicle() && (player.getVehicle() instanceof Minecart || player.getVehicle() instanceof PoweredMinecart)) - { + if (mcMMO.getConfigManager().getConfigExploitPrevention().getConfigSectionExploitFishing().isPreventFishingExploits()) { + if (event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_AIR) { + if (player.isInsideVehicle() && (player.getVehicle() instanceof Minecart || player.getVehicle() instanceof PoweredMinecart)) { player.getVehicle().eject(); player.setVelocity(player.getEyeLocation().getDirection().multiply(10)); } @@ -738,10 +704,10 @@ public class PlayerListener implements Listener { switch (event.getAction()) { case RIGHT_CLICK_BLOCK: - if(player.getInventory().getItemInOffHand().getType() != Material.AIR && !player.isInsideVehicle() && !player.isSneaking()) { + if (player.getInventory().getItemInOffHand().getType() != Material.AIR && !player.isInsideVehicle() && !player.isSneaking()) { break; } - + Block block = event.getClickedBlock(); BlockState blockState = block.getState(); @@ -796,10 +762,10 @@ public class PlayerListener implements Listener { break; case RIGHT_CLICK_AIR: - if(player.getInventory().getItemInOffHand().getType() != Material.AIR && !player.isInsideVehicle() && !player.isSneaking()) { + if (player.getInventory().getItemInOffHand().getType() != Material.AIR && !player.isInsideVehicle() && !player.isSneaking()) { break; } - + /* ACTIVATION CHECKS */ if (mcMMO.getConfigManager().getConfigSuperAbilities().isSuperAbilitiesEnabled()) { mcMMOPlayer.processAbilityActivation(PrimarySkillType.AXES); @@ -835,11 +801,9 @@ public class PlayerListener implements Listener { if (type == MainConfig.getInstance().getTamingCOTWMaterial(EntityType.WOLF)) { tamingManager.summonWolf(); - } - else if (type == MainConfig.getInstance().getTamingCOTWMaterial(EntityType.OCELOT)) { + } else if (type == MainConfig.getInstance().getTamingCOTWMaterial(EntityType.OCELOT)) { tamingManager.summonOcelot(); - } - else if (type == MainConfig.getInstance().getTamingCOTWMaterial(EntityType.HORSE)) { + } else if (type == MainConfig.getInstance().getTamingCOTWMaterial(EntityType.HORSE)) { tamingManager.summonHorse(); } @@ -884,8 +848,7 @@ public class PlayerListener implements Listener { chatManager = ChatManagerFactory.getChatManager(plugin, ChatMode.PARTY); ((PartyChatManager) chatManager).setParty(party); - } - else if (mcMMOPlayer.isChatEnabled(ChatMode.ADMIN)) { + } else if (mcMMOPlayer.isChatEnabled(ChatMode.ADMIN)) { chatManager = ChatManagerFactory.getChatManager(plugin, ChatMode.ADMIN); } diff --git a/src/main/java/com/gmail/nossr50/listeners/SelfListener.java b/src/main/java/com/gmail/nossr50/listeners/SelfListener.java index a521079da..5f949e0d1 100644 --- a/src/main/java/com/gmail/nossr50/listeners/SelfListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/SelfListener.java @@ -23,8 +23,7 @@ public class SelfListener implements Listener { //Used in task scheduling and other things private final mcMMO plugin; - public SelfListener(mcMMO plugin) - { + public SelfListener(mcMMO plugin) { this.plugin = plugin; } @@ -34,8 +33,7 @@ public class SelfListener implements Listener { PrimarySkillType skill = event.getSkill(); //Players can gain multiple levels especially during xprate events - for(int i = 0; i < event.getLevelsGained(); i++) - { + for (int i = 0; i < event.getLevelsGained(); i++) { int previousLevelGained = event.getSkillLevel() - i; //Send player skill unlock notifications UserManager.getPlayer(player).processUnlockNotifications(plugin, event.getSkill(), previousLevelGained); @@ -44,7 +42,7 @@ public class SelfListener implements Listener { //Reset the delay timer RankUtils.resetUnlockDelayTimer(); - if(mcMMO.getScoreboardSettings().getScoreboardsEnabled()) + if (mcMMO.getScoreboardSettings().getScoreboardsEnabled()) ScoreboardManager.handleLevelUp(player, skill); if (!MainConfig.getInstance().getLevelUpEffectsEnabled()) { @@ -57,13 +55,13 @@ public class SelfListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerXp(McMMOPlayerXpGainEvent event) { - if(mcMMO.getScoreboardSettings().getScoreboardsEnabled()) + if (mcMMO.getScoreboardSettings().getScoreboardsEnabled()) ScoreboardManager.handleXp(event.getPlayer(), event.getSkill()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onAbility(McMMOPlayerAbilityActivateEvent event) { - if(mcMMO.getScoreboardSettings().getScoreboardsEnabled()) + if (mcMMO.getScoreboardSettings().getScoreboardsEnabled()) ScoreboardManager.cooldownUpdate(event.getPlayer(), event.getSkill()); } @@ -74,23 +72,19 @@ public class SelfListener implements Listener { PrimarySkillType primarySkillType = event.getSkill(); //WorldGuard XP Check - if(event.getXpGainReason() == XPGainReason.PVE || + if (event.getXpGainReason() == XPGainReason.PVE || event.getXpGainReason() == XPGainReason.PVP || event.getXpGainReason() == XPGainReason.SHARED_PVE || - event.getXpGainReason() == XPGainReason.SHARED_PVP) - { - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasXPFlag(player)) - { + event.getXpGainReason() == XPGainReason.SHARED_PVP) { + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasXPFlag(player)) { event.setRawXpGained(0); event.setCancelled(true); } } } - if (event.getXpGainReason() == XPGainReason.COMMAND) - { + if (event.getXpGainReason() == XPGainReason.COMMAND) { return; } @@ -116,8 +110,7 @@ public class SelfListener implements Listener { int earlyGameBonusXP = 0; //Give some bonus XP for low levels - if(mcMMOPlayer.getSkillLevel(primarySkillType) < earlyLevelBonusXPCap) - { + if (mcMMOPlayer.getSkillLevel(primarySkillType) < earlyLevelBonusXPCap) { earlyGameBonusXP += (mcMMOPlayer.getXpToLevel(primarySkillType) * 0.05); event.setRawXpGained(event.getRawXpGained() + earlyGameBonusXP); } @@ -140,12 +133,10 @@ public class SelfListener implements Listener { * Make sure players get a guaranteed minimum of XP */ //If there is no guaranteed minimum proceed, otherwise only proceed if newValue would be higher than our guaranteed minimum - if(guaranteedMinimum <= 0 || newValue > guaranteedMinimum) - { + if (guaranteedMinimum <= 0 || newValue > guaranteedMinimum) { if (newValue > 0) { event.setRawXpGained(newValue); - } - else { + } else { event.setCancelled(true); } } else { diff --git a/src/main/java/com/gmail/nossr50/listeners/WorldListener.java b/src/main/java/com/gmail/nossr50/listeners/WorldListener.java index 5fc386c86..2ae1a0769 100644 --- a/src/main/java/com/gmail/nossr50/listeners/WorldListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/WorldListener.java @@ -30,7 +30,7 @@ public class WorldListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onStructureGrow(StructureGrowEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getWorld())) return; if (!mcMMO.getPlaceStore().isTrue(event.getLocation().getBlock())) { @@ -50,7 +50,7 @@ public class WorldListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onWorldInit(WorldInitEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getWorld())) return; World world = event.getWorld(); @@ -72,7 +72,7 @@ public class WorldListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onWorldUnload(WorldUnloadEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getWorld())) return; mcMMO.getPlaceStore().unloadWorld(event.getWorld()); @@ -86,7 +86,7 @@ public class WorldListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onChunkUnload(ChunkUnloadEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getWorld())) return; Chunk chunk = event.getChunk(); diff --git a/src/main/java/com/gmail/nossr50/locale/LocaleLoader.java b/src/main/java/com/gmail/nossr50/locale/LocaleLoader.java index 1a0d0b72b..7454e3520 100644 --- a/src/main/java/com/gmail/nossr50/locale/LocaleLoader.java +++ b/src/main/java/com/gmail/nossr50/locale/LocaleLoader.java @@ -13,7 +13,8 @@ public final class LocaleLoader { private static ResourceBundle bundle = null; private static ResourceBundle enBundle = null; - private LocaleLoader() {} + private LocaleLoader() { + } public static String getString(String key) { return getString(key, (Object[]) null); @@ -22,7 +23,7 @@ public final class LocaleLoader { /** * Gets the appropriate string from the Locale files. * - * @param key The key to look up the string with + * @param key The key to look up the string with * @param messageArguments Any arguments to be added to the string * @return The properly formatted locale string */ @@ -33,12 +34,10 @@ public final class LocaleLoader { try { return getString(key, bundle, messageArguments); - } - catch (MissingResourceException ex) { + } catch (MissingResourceException ex) { try { return getString(key, enBundle, messageArguments); - } - catch (MissingResourceException ex2) { + } catch (MissingResourceException ex2) { if (!key.contains("Guides")) { mcMMO.p.getLogger().warning("Could not find locale string: " + key); } @@ -79,8 +78,7 @@ public final class LocaleLoader { if (myLocale.length == 1) { locale = new Locale(myLocale[0]); - } - else if (myLocale.length >= 2) { + } else if (myLocale.length >= 2) { locale = new Locale(myLocale[0], myLocale[1]); } diff --git a/src/main/java/com/gmail/nossr50/mcMMO.java b/src/main/java/com/gmail/nossr50/mcMMO.java index 4d21c4d08..6f826703b 100644 --- a/src/main/java/com/gmail/nossr50/mcMMO.java +++ b/src/main/java/com/gmail/nossr50/mcMMO.java @@ -54,60 +54,173 @@ public class mcMMO extends JavaPlugin { public static final String COMPATIBLE_SERVER_SOFTWARE = "Spigot, Paper"; public static final String INCOMPATIBLE_SERVER_SOFTWARE = "CraftBukkit"; public static final String COMPATIBLE_MINECRAFT_VERSIONS = "1.13.2"; - + /* Metadata Values */ + public static final String FISH_HOOK_REF_METAKEY = "mcMMO: Fish Hook Tracker"; + public static final String CUSTOM_DAMAGE_METAKEY = "mcMMO: Custom Damage"; + public final static String entityMetadataKey = "mcMMO: Spawned Entity"; + public final static String blockMetadataKey = "mcMMO: Piston Tracking"; + public final static String furnaceMetadataKey = "mcMMO: Tracked Furnace"; + public final static String tntMetadataKey = "mcMMO: Tracked TNT"; + public final static String funfettiMetadataKey = "mcMMO: Funfetti"; + public final static String tntsafeMetadataKey = "mcMMO: Safe TNT"; + public final static String customNameKey = "mcMMO: Custom Name"; + public final static String customVisibleKey = "mcMMO: Name Visibility"; + public final static String droppedItemKey = "mcMMO: Tracked Item"; + public final static String infiniteArrowKey = "mcMMO: Infinite Arrow"; + public final static String bowForceKey = "mcMMO: Bow Force"; + public final static String arrowDistanceKey = "mcMMO: Arrow Distance"; + public final static String doubleDrops = "mcMMO: Double Drops"; + public final static String tripleDrops = "mcMMO: Triple Drops"; + //public final static String customDamageKey = "mcMMO: Custom Damage"; + public final static String disarmedItemKey = "mcMMO: Disarmed Item"; + public final static String playerDataKey = "mcMMO: Player Data"; + public final static String greenThumbDataKey = "mcMMO: Green Thumb"; + public final static String databaseCommandKey = "mcMMO: Processing Database Command"; + public final static String bredMetadataKey = "mcMMO: Bred Animal"; + public static mcMMO p; + // Jar Stuff + public static File mcmmo; + public static FixedMetadataValue metadataValue; /* Managers */ - private static ChunkManager placeStore; - private static ConfigManager configManager; + private static ChunkManager placeStore; + private static ConfigManager configManager; //private static ModManager modManager; - private static DatabaseManager databaseManager; - private static FormulaManager formulaManager; + private static DatabaseManager databaseManager; + private static FormulaManager formulaManager; private static MaterialMapStore materialMapStore; - /* File Paths */ private static String mainDirectory; private static String flatFileDirectory; private static String usersFile; private static String modDirectory; - - public static mcMMO p; - - // Jar Stuff - public static File mcmmo; - /* Plugin Checks */ private static boolean healthBarPluginEnabled; - // API checks private static boolean serverAPIOutdated = false; - // XP Event Check private boolean xpEventEnabled; - /* Metadata Values */ - public static final String FISH_HOOK_REF_METAKEY = "mcMMO: Fish Hook Tracker"; - public static final String CUSTOM_DAMAGE_METAKEY = "mcMMO: Custom Damage"; - public final static String entityMetadataKey = "mcMMO: Spawned Entity"; - public final static String blockMetadataKey = "mcMMO: Piston Tracking"; - public final static String furnaceMetadataKey = "mcMMO: Tracked Furnace"; - public final static String tntMetadataKey = "mcMMO: Tracked TNT"; - public final static String funfettiMetadataKey = "mcMMO: Funfetti"; - public final static String tntsafeMetadataKey = "mcMMO: Safe TNT"; - public final static String customNameKey = "mcMMO: Custom Name"; - public final static String customVisibleKey = "mcMMO: Name Visibility"; - public final static String droppedItemKey = "mcMMO: Tracked Item"; - public final static String infiniteArrowKey = "mcMMO: Infinite Arrow"; - public final static String bowForceKey = "mcMMO: Bow Force"; - public final static String arrowDistanceKey = "mcMMO: Arrow Distance"; - public final static String doubleDrops = "mcMMO: Double Drops"; - public final static String tripleDrops = "mcMMO: Triple Drops"; - //public final static String customDamageKey = "mcMMO: Custom Damage"; - public final static String disarmedItemKey = "mcMMO: Disarmed Item"; - public final static String playerDataKey = "mcMMO: Player Data"; - public final static String greenThumbDataKey = "mcMMO: Green Thumb"; - public final static String databaseCommandKey = "mcMMO: Processing Database Command"; - public final static String bredMetadataKey = "mcMMO: Bred Animal"; + public static MaterialMapStore getMaterialMapStore() { + return materialMapStore; + } - public static FixedMetadataValue metadataValue; + public static String getMainDirectory() { + return mainDirectory; + } + + public static String getFlatFileDirectory() { + return flatFileDirectory; + } + + public static String getUsersFilePath() { + return usersFile; + } + + public static String getModDirectory() { + return modDirectory; + } + + public static FormulaManager getFormulaManager() { + return formulaManager; + } + + public static ChunkManager getPlaceStore() { + return placeStore; + } + + public static RepairableManager getRepairableManager() { + return configManager.getRepairableManager(); + } + + public static SalvageableManager getSalvageableManager() { + return configManager.getSalvageableManager(); + } + + public static DatabaseManager getDatabaseManager() { + return databaseManager; + } + + @Deprecated + public static void setDatabaseManager(DatabaseManager databaseManager) { + mcMMO.databaseManager = databaseManager; + } + + /** + * Returns settings for MySQL from the users config + * + * @return settings for MySQL from the users config + */ + public static ConfigSectionMySQL getMySQLConfigSettings() { + return configManager.getConfigDatabase().getConfigSectionMySQL(); + } + + /** + * Returns settings for Player Leveling from the users config + * + * @return settings for Player Leveling from the users config + */ + public static ConfigLeveling getPlayerLevelingSettings() { + return configManager.getConfigLeveling(); + } + + /** + * Returns settings for Database cleaning from the users config + * + * @return settings for Database cleaning from the users config + */ + public static ConfigSectionCleaning getDatabaseCleaningSettings() { + return configManager.getConfigDatabase().getConfigSectionCleaning(); + } + + /** + * Returns settings for Party XP sharing from the users config + * + * @return settings for the Party XP sharing from the users config + */ + public static ConfigSectionPartyExperienceSharing getPartyXPShareSettings() { + return configManager.getConfigParty().getPartyXP().getPartyExperienceSharing(); + } + + /** + * Returns settings for Party Leveling from the users config + * + * @return settings for the Party Leveling from the users config + */ + public static ConfigSectionPartyLevel getPartyLevelSettings() { + return configManager.getConfigParty().getPartyXP().getPartyLevel(); + } + + /** + * Returns settings for Scoreboards from the users config + * + * @return settings for Scoreboards from the users config + */ + public static ConfigScoreboard getScoreboardSettings() { + return configManager.getConfigScoreboard(); + } + + /*public static HolidayManager getHolidayManager() { + return holidayManager; + }*/ + + public static boolean isHealthBarPluginEnabled() { + return healthBarPluginEnabled; + } + + /** + * Checks if this plugin is using retro mode + * Retro mode is a 0-1000 skill system + * Standard mode is scaled for 1-100 + * + * @return true if retro mode is enabled + */ + public static boolean isRetroModeEnabled() { + return configManager.isRetroMode(); + } + + public static ConfigManager getConfigManager() { + return configManager; + } /** * Things to be run when the plugin is enabled. @@ -149,30 +262,28 @@ public class mcMMO extends JavaPlugin { //Check for the newer API and tell them what to do if its missing checkForOutdatedAPI(); - if(serverAPIOutdated) - { + if (serverAPIOutdated) { Bukkit .getScheduler() .scheduleSyncRepeatingTask(this, - () -> getLogger().severe("You are running an outdated version of "+getServerSoftware()+", mcMMO will not work unless you update to a newer version!"), - 20, 20*60*30); + () -> getLogger().severe("You are running an outdated version of " + getServerSoftware() + ", mcMMO will not work unless you update to a newer version!"), + 20, 20 * 60 * 30); - if(getServerSoftware() == ServerSoftwareType.CRAFTBUKKIT) - { + if (getServerSoftware() == ServerSoftwareType.CRAFTBUKKIT) { Bukkit.getScheduler() .scheduleSyncRepeatingTask(this, () -> getLogger().severe("We have detected you are using incompatible server software, our best guess is that you are using CraftBukkit. mcMMO requires Spigot or Paper, if you are not using CraftBukkit, you will still need to update your custom server software before mcMMO will work."), - 20, 20*60*30); + 20, 20 * 60 * 30); } } else { registerEvents(); registerCoreSkills(); registerCustomRecipes(); - if(getConfigManager().getConfigParty().isPartySystemEnabled()) - PartyManager.loadParties(); + if (getConfigManager().getConfigParty().isPartySystemEnabled()) + PartyManager.loadParties(); - formulaManager = new FormulaManager(); + formulaManager = new FormulaManager(); for (Player player : getServer().getOnlinePlayers()) { new PlayerProfileLoadingTask(player).runTaskLaterAsynchronously(mcMMO.p, 1); // 1 Tick delay to ensure the player is marked as online before we begin loading @@ -185,37 +296,36 @@ public class mcMMO extends JavaPlugin { placeStore = ChunkManagerFactory.getChunkManager(); // Get our ChunkletManager - if (mcMMO.getConfigManager().getConfigParty().getPTP().isPtpWorldBasedPermissions()) { - Permissions.generateWorldTeleportPermissions(); - } + if (mcMMO.getConfigManager().getConfigParty().getPTP().isPtpWorldBasedPermissions()) { + Permissions.generateWorldTeleportPermissions(); + } //Populate Ranked Skill Maps (DO THIS LAST) RankUtils.populateRanks(); } //If anonymous statistics are enabled then use them - if(getConfigManager().getConfigMetrics().isAllowAnonymousUsageStatistics()) { + if (getConfigManager().getConfigMetrics().isAllowAnonymousUsageStatistics()) { Metrics metrics; metrics = new Metrics(this); metrics.addCustomChart(new Metrics.SimplePie("version", () -> getDescription().getVersion())); - if(!configManager.getConfigLeveling().getConfigSectionLevelingGeneral().getConfigSectionLevelScaling().isRetroModeEnabled()) + if (!configManager.getConfigLeveling().getConfigSectionLevelingGeneral().getConfigSectionLevelScaling().isRetroModeEnabled()) metrics.addCustomChart(new Metrics.SimplePie("scaling", () -> "Standard")); else metrics.addCustomChart(new Metrics.SimplePie("scaling", () -> "Retro")); //Simplified Server Software Tracking - if(Bukkit.getServer().getVersion().contains("paper")) + if (Bukkit.getServer().getVersion().contains("paper")) metrics.addCustomChart(new Metrics.SimplePie("Server_software", () -> "Paper")); - else if(Bukkit.getServer().getVersion().contains("spigot") && !Bukkit.getServer().getVersion().contains("paper")) + else if (Bukkit.getServer().getVersion().contains("spigot") && !Bukkit.getServer().getVersion().contains("paper")) metrics.addCustomChart(new Metrics.SimplePie("Server_software", () -> "Spigot")); - else if(Bukkit.getServer().getVersion().contains("bukkit")) + else if (Bukkit.getServer().getVersion().contains("bukkit")) metrics.addCustomChart(new Metrics.SimplePie("Server_software", () -> "CraftBukkit")); else metrics.addCustomChart(new Metrics.SimplePie("Server_software", () -> "Unknown")); } - } - catch (Throwable t) { + } catch (Throwable t) { getLogger().severe("There was an error while enabling mcMMO!"); t.printStackTrace(); getLogger().severe("End of error report for mcMMO"); @@ -228,14 +338,10 @@ public class mcMMO extends JavaPlugin { materialMapStore = new MaterialMapStore(); } - public static MaterialMapStore getMaterialMapStore() { - return materialMapStore; - } - private void checkForOutdatedAPI() { try { Class checkForClass = Class.forName("org.bukkit.event.block.BlockDropItemEvent"); - Method newerAPIMethod = checkForClass.getMethod("getItems"); + Method newerAPIMethod = checkForClass.getMethod("getItems"); Class checkForClassBaseComponent = Class.forName("net.md_5.bungee.api.chat.BaseComponent"); } catch (ClassNotFoundException | NoSuchMethodException e) { serverAPIOutdated = true; @@ -244,26 +350,17 @@ public class mcMMO extends JavaPlugin { } } - private enum ServerSoftwareType { - PAPER, - SPIGOT, - CRAFTBUKKIT - } - - private ServerSoftwareType getServerSoftware() - { - if(Bukkit.getVersion().toLowerCase().contains("paper")) + private ServerSoftwareType getServerSoftware() { + if (Bukkit.getVersion().toLowerCase().contains("paper")) return ServerSoftwareType.PAPER; - else if(Bukkit.getVersion().toLowerCase().contains("spigot")) + else if (Bukkit.getVersion().toLowerCase().contains("spigot")) return ServerSoftwareType.SPIGOT; else return ServerSoftwareType.CRAFTBUKKIT; } - private String getServerSoftwareStr() - { - switch(getServerSoftware()) - { + private String getServerSoftwareStr() { + switch (getServerSoftware()) { case PAPER: return "Paper"; case SPIGOT: @@ -274,9 +371,8 @@ public class mcMMO extends JavaPlugin { } @Override - public void onLoad() - { - if(getServer().getPluginManager().getPlugin("WorldGuard") != null) + public void onLoad() { + if (getServer().getPluginManager().getPlugin("WorldGuard") != null) WorldGuardManager.getInstance().registerFlags(); } @@ -292,15 +388,16 @@ public class mcMMO extends JavaPlugin { PartyManager.saveParties(); // Save our parties //TODO: Needed? - if(mcMMO.getScoreboardSettings().getScoreboardsEnabled()) + if (mcMMO.getScoreboardSettings().getScoreboardsEnabled()) ScoreboardManager.teardownAll(); formulaManager.saveFormula(); /*holidayManager.saveAnniversaryFiles();*/ placeStore.saveAll(); // Save our metadata placeStore.cleanUp(); // Cleanup empty metadata stores + } catch (NullPointerException e) { + e.printStackTrace(); } - catch (NullPointerException e) { e.printStackTrace(); } debug("Canceling all tasks..."); getServer().getScheduler().cancelTasks(this); // This removes our tasks @@ -311,16 +408,13 @@ public class mcMMO extends JavaPlugin { // Remove other tasks BEFORE starting the Backup, or we just cancel it straight away. try { ZipLibrary.mcMMOBackup(); - } - catch (IOException e) { + } catch (IOException e) { getLogger().severe(e.toString()); - } - catch (Throwable e) { + } catch (Throwable e) { if (e instanceof NoClassDefFoundError) { getLogger().severe("Backup class not found!"); getLogger().info("Please do not replace the mcMMO jar while the server is running."); - } - else { + } else { getLogger().severe(e.toString()); } } @@ -335,26 +429,18 @@ public class mcMMO extends JavaPlugin { debug("Was disabled."); // How informative! } - public static String getMainDirectory() { - return mainDirectory; - } - - public static String getFlatFileDirectory() { - return flatFileDirectory; - } - - public static String getUsersFilePath() { - return usersFile; - } - - public static String getModDirectory() { - return modDirectory; - } - public boolean isXPEventEnabled() { return xpEventEnabled; } + /*public static ModManager getModManager() { + return modManager; + }*/ + + /*public static UpgradeManager getUpgradeManager() { + return upgradeManager; + }*/ + public void setXPEventEnabled(boolean enabled) { this.xpEventEnabled = enabled; } @@ -367,101 +453,6 @@ public class mcMMO extends JavaPlugin { getLogger().info("[Debug] " + message); } - public static FormulaManager getFormulaManager() { - return formulaManager; - } - - /*public static HolidayManager getHolidayManager() { - return holidayManager; - }*/ - - public static ChunkManager getPlaceStore() { - return placeStore; - } - - public static RepairableManager getRepairableManager() { - return configManager.getRepairableManager(); - } - - public static SalvageableManager getSalvageableManager() { - return configManager.getSalvageableManager(); - } - - public static DatabaseManager getDatabaseManager() { - return databaseManager; - } - - /** - * Returns settings for MySQL from the users config - * @return settings for MySQL from the users config - */ - public static ConfigSectionMySQL getMySQLConfigSettings() - { - return configManager.getConfigDatabase().getConfigSectionMySQL(); - } - - /** - * Returns settings for Player Leveling from the users config - * @return settings for Player Leveling from the users config - */ - public static ConfigLeveling getPlayerLevelingSettings() - { - return configManager.getConfigLeveling(); - } - - /** - * Returns settings for Database cleaning from the users config - * @return settings for Database cleaning from the users config - */ - public static ConfigSectionCleaning getDatabaseCleaningSettings() - { - return configManager.getConfigDatabase().getConfigSectionCleaning(); - } - - /** - * Returns settings for Party XP sharing from the users config - * @return settings for the Party XP sharing from the users config - */ - public static ConfigSectionPartyExperienceSharing getPartyXPShareSettings() - { - return configManager.getConfigParty().getPartyXP().getPartyExperienceSharing(); - } - - /** - * Returns settings for Party Leveling from the users config - * @return settings for the Party Leveling from the users config - */ - public static ConfigSectionPartyLevel getPartyLevelSettings() - { - return configManager.getConfigParty().getPartyXP().getPartyLevel(); - } - - /** - * Returns settings for Scoreboards from the users config - * @return settings for Scoreboards from the users config - */ - public static ConfigScoreboard getScoreboardSettings() - { - return configManager.getConfigScoreboard(); - } - - /*public static ModManager getModManager() { - return modManager; - }*/ - - /*public static UpgradeManager getUpgradeManager() { - return upgradeManager; - }*/ - - @Deprecated - public static void setDatabaseManager(DatabaseManager databaseManager) { - mcMMO.databaseManager = databaseManager; - } - - public static boolean isHealthBarPluginEnabled() { - return healthBarPluginEnabled; - } - /** * Setup the various storage file paths */ @@ -490,10 +481,10 @@ public class mcMMO extends JavaPlugin { } } - File oldArmorFile = new File(modDirectory + "armor.yml"); - File oldBlocksFile = new File(modDirectory + "blocks.yml"); + File oldArmorFile = new File(modDirectory + "armor.yml"); + File oldBlocksFile = new File(modDirectory + "blocks.yml"); File oldEntitiesFile = new File(modDirectory + "entities.yml"); - File oldToolsFile = new File(modDirectory + "tools.yml"); + File oldToolsFile = new File(modDirectory + "tools.yml"); if (oldArmorFile.exists()) { if (!oldArmorFile.renameTo(new File(modDirectory + "armor.default.yml"))) { @@ -549,8 +540,7 @@ public class mcMMO extends JavaPlugin { * Acrobatics skills */ - if(CoreSkillsConfig.getInstance().isPrimarySkillEnabled(PrimarySkillType.ACROBATICS)) - { + if (CoreSkillsConfig.getInstance().isPrimarySkillEnabled(PrimarySkillType.ACROBATICS)) { System.out.println("[mcMMO]" + " enabling Acrobatics Skills"); //TODO: Should do this differently @@ -568,60 +558,6 @@ public class mcMMO extends JavaPlugin { }, 40); } - private void scheduleTasks() { - // Periodic save timer (Saves every 10 minutes by default) - long saveIntervalTicks = Math.max(1200, (getConfigManager().getConfigDatabase().getConfigSectionDatabaseGeneral().getSaveIntervalMinutes() * (20 * 60))); - new SaveTimerTask().runTaskTimer(this, saveIntervalTicks, saveIntervalTicks); - - // Cleanup the backups folder - new CleanBackupsTask().runTaskAsynchronously(mcMMO.p); - - // Bleed timer (Runs every 0.5 seconds) - new BleedTimerTask().runTaskTimer(this, Misc.TICK_CONVERSION_FACTOR, (Misc.TICK_CONVERSION_FACTOR / 2)); - - // Old & Powerless User remover - long purgeIntervalTicks = getConfigManager().getConfigDatabase().getConfigSectionCleaning().getPurgeInterval() * 60L * 60L * Misc.TICK_CONVERSION_FACTOR; - - if (mcMMO.getDatabaseCleaningSettings().isOnlyPurgeAtStartup()) { - new UserPurgeTask().runTaskLaterAsynchronously(this, 2 * Misc.TICK_CONVERSION_FACTOR); // Start 2 seconds after startup. - } - else if (purgeIntervalTicks > 0) { - new UserPurgeTask().runTaskTimerAsynchronously(this, purgeIntervalTicks, purgeIntervalTicks); - } - - //Party System Stuff - if(mcMMO.configManager.getConfigParty().isPartySystemEnabled()) - { - // Automatically remove old members from parties - long kickIntervalTicks = getConfigManager().getConfigParty().getPartyCleanup().getPartyAutoKickHoursInterval() * 60L * 60L * Misc.TICK_CONVERSION_FACTOR; - - if (kickIntervalTicks == 0) { - new PartyAutoKickTask().runTaskLater(this, 2 * Misc.TICK_CONVERSION_FACTOR); // Start 2 seconds after startup. - } - else if (kickIntervalTicks > 0) { - new PartyAutoKickTask().runTaskTimer(this, kickIntervalTicks, kickIntervalTicks); - } - } - - - // Update power level tag scoreboards - new PowerLevelUpdatingTask().runTaskTimer(this, 2 * Misc.TICK_CONVERSION_FACTOR, 2 * Misc.TICK_CONVERSION_FACTOR); - - /*if (getHolidayManager().nearingAprilFirst()) { - new CheckDateTask().runTaskTimer(this, 10L * Misc.TICK_CONVERSION_FACTOR, 1L * 60L * 60L * Misc.TICK_CONVERSION_FACTOR); - }*/ - - // Clear the registered XP data so players can earn XP again - if (ExperienceConfig.getInstance().getDiminishedReturnsEnabled()) { - new ClearRegisteredXPGainTask().runTaskTimer(this, 60, 60); - } - - if(configManager.getConfigNotifications().getConfigNotificationGeneral().isPlayerTips()) - { - new NotifySquelchReminderTask().runTaskTimer(this, 60, ((20 * 60) * 60)); - } - } - /*private void checkModConfigs() { if (!MainConfig.getInstance().getToolModsEnabled()) { getLogger().warning("Cauldron implementation found, but the custom tool config for mcMMO is disabled!"); @@ -644,17 +580,59 @@ public class mcMMO extends JavaPlugin { } }*/ - /** - * Checks if this plugin is using retro mode - * Retro mode is a 0-1000 skill system - * Standard mode is scaled for 1-100 - * @return true if retro mode is enabled - */ - public static boolean isRetroModeEnabled() { - return configManager.isRetroMode(); + private void scheduleTasks() { + // Periodic save timer (Saves every 10 minutes by default) + long saveIntervalTicks = Math.max(1200, (getConfigManager().getConfigDatabase().getConfigSectionDatabaseGeneral().getSaveIntervalMinutes() * (20 * 60))); + new SaveTimerTask().runTaskTimer(this, saveIntervalTicks, saveIntervalTicks); + + // Cleanup the backups folder + new CleanBackupsTask().runTaskAsynchronously(mcMMO.p); + + // Bleed timer (Runs every 0.5 seconds) + new BleedTimerTask().runTaskTimer(this, Misc.TICK_CONVERSION_FACTOR, (Misc.TICK_CONVERSION_FACTOR / 2)); + + // Old & Powerless User remover + long purgeIntervalTicks = getConfigManager().getConfigDatabase().getConfigSectionCleaning().getPurgeInterval() * 60L * 60L * Misc.TICK_CONVERSION_FACTOR; + + if (mcMMO.getDatabaseCleaningSettings().isOnlyPurgeAtStartup()) { + new UserPurgeTask().runTaskLaterAsynchronously(this, 2 * Misc.TICK_CONVERSION_FACTOR); // Start 2 seconds after startup. + } else if (purgeIntervalTicks > 0) { + new UserPurgeTask().runTaskTimerAsynchronously(this, purgeIntervalTicks, purgeIntervalTicks); + } + + //Party System Stuff + if (mcMMO.configManager.getConfigParty().isPartySystemEnabled()) { + // Automatically remove old members from parties + long kickIntervalTicks = getConfigManager().getConfigParty().getPartyCleanup().getPartyAutoKickHoursInterval() * 60L * 60L * Misc.TICK_CONVERSION_FACTOR; + + if (kickIntervalTicks == 0) { + new PartyAutoKickTask().runTaskLater(this, 2 * Misc.TICK_CONVERSION_FACTOR); // Start 2 seconds after startup. + } else if (kickIntervalTicks > 0) { + new PartyAutoKickTask().runTaskTimer(this, kickIntervalTicks, kickIntervalTicks); + } + } + + + // Update power level tag scoreboards + new PowerLevelUpdatingTask().runTaskTimer(this, 2 * Misc.TICK_CONVERSION_FACTOR, 2 * Misc.TICK_CONVERSION_FACTOR); + + /*if (getHolidayManager().nearingAprilFirst()) { + new CheckDateTask().runTaskTimer(this, 10L * Misc.TICK_CONVERSION_FACTOR, 1L * 60L * 60L * Misc.TICK_CONVERSION_FACTOR); + }*/ + + // Clear the registered XP data so players can earn XP again + if (ExperienceConfig.getInstance().getDiminishedReturnsEnabled()) { + new ClearRegisteredXPGainTask().runTaskTimer(this, 60, 60); + } + + if (configManager.getConfigNotifications().getConfigNotificationGeneral().isPlayerTips()) { + new NotifySquelchReminderTask().runTaskTimer(this, 60, ((20 * 60) * 60)); + } } - public static ConfigManager getConfigManager() { - return configManager; + private enum ServerSoftwareType { + PAPER, + SPIGOT, + CRAFTBUKKIT } } diff --git a/src/main/java/com/gmail/nossr50/party/PartyManager.java b/src/main/java/com/gmail/nossr50/party/PartyManager.java index 4dacf29d1..42b3d32c4 100644 --- a/src/main/java/com/gmail/nossr50/party/PartyManager.java +++ b/src/main/java/com/gmail/nossr50/party/PartyManager.java @@ -32,16 +32,17 @@ public final class PartyManager { private static List parties = new ArrayList<>(); private static File partyFile = new File(partiesFilePath); - private PartyManager() {} + private PartyManager() { + } /** * Grab the appropriate unlock level for a party feature + * * @param partyFeature target party feature * @return the unlock level for the feature */ - public static int getPartyFeatureUnlockLevel(PartyFeature partyFeature) - { - if(mcMMO.getConfigManager().getPartyFeatureUnlocks().get(partyFeature) == null) + public static int getPartyFeatureUnlockLevel(PartyFeature partyFeature) { + if (mcMMO.getConfigManager().getPartyFeatureUnlocks().get(partyFeature) == null) return 0; else return mcMMO.getConfigManager().getPartyFeatureUnlocks().get(partyFeature); @@ -50,7 +51,7 @@ public final class PartyManager { /** * Check if a party with a given name already exists. * - * @param player The player to notify + * @param player The player to notify * @param partyName The name of the party to check * @return true if a party with that name exists, false otherwise */ @@ -65,12 +66,12 @@ public final class PartyManager { /** * Checks if the player can join a party, parties can have a size limit, although there is a permission to bypass this - * @param player player who is attempting to join the party + * + * @param player player who is attempting to join the party * @param targetParty the target party * @return true if party is full and cannot be joined */ - public static boolean isPartyFull(Player player, Party targetParty) - { + public static boolean isPartyFull(Player player, Party targetParty) { return !Permissions.partySizeBypass(player) && targetParty.getMembers().size() >= mcMMO.getConfigManager().getConfigParty().getPartySizeLimit(); } @@ -78,7 +79,7 @@ public final class PartyManager { /** * Attempt to change parties or join a new party. * - * @param mcMMOPlayer The player changing or joining parties + * @param mcMMOPlayer The player changing or joining parties * @param newPartyName The name of the party being joined * @return true if the party was joined successfully, false otherwise */ @@ -93,8 +94,7 @@ public final class PartyManager { } removeFromParty(mcMMOPlayer); - } - else return handlePartyChangeEvent(player, null, newPartyName, EventReason.JOINED_PARTY); + } else return handlePartyChangeEvent(player, null, newPartyName, EventReason.JOINED_PARTY); return true; } @@ -102,24 +102,22 @@ public final class PartyManager { /** * Check if two online players are in the same party. * - * @param firstPlayer The first player + * @param firstPlayer The first player * @param secondPlayer The second player * @return true if they are in the same party, false otherwise */ public static boolean inSameParty(Player firstPlayer, Player secondPlayer) { //If the party system is disabled, return false - if(!mcMMO.getConfigManager().getConfigParty().isPartySystemEnabled()) + if (!mcMMO.getConfigManager().getConfigParty().isPartySystemEnabled()) return false; //Profile not loaded - if(UserManager.getPlayer(firstPlayer) == null) - { + if (UserManager.getPlayer(firstPlayer) == null) { return false; } //Profile not loaded - if(UserManager.getPlayer(secondPlayer) == null) - { + if (UserManager.getPlayer(secondPlayer) == null) { return false; } @@ -135,18 +133,16 @@ public final class PartyManager { public static boolean areAllies(Player firstPlayer, Player secondPlayer) { //If the party system is disabled, return false - if(!mcMMO.getConfigManager().getConfigParty().isPartySystemEnabled()) + if (!mcMMO.getConfigManager().getConfigParty().isPartySystemEnabled()) return false; //Profile not loaded - if(UserManager.getPlayer(firstPlayer) == null) - { + if (UserManager.getPlayer(firstPlayer) == null) { return false; } //Profile not loaded - if(UserManager.getPlayer(secondPlayer) == null) - { + if (UserManager.getPlayer(secondPlayer) == null) { return false; } @@ -249,7 +245,7 @@ public final class PartyManager { */ public static Party getParty(String partyName) { //If the party system is disabled, return null - if(!mcMMO.getConfigManager().getConfigParty().isPartySystemEnabled()) + if (!mcMMO.getConfigManager().getConfigParty().isPartySystemEnabled()) return null; for (Party party : parties) { @@ -270,7 +266,7 @@ public final class PartyManager { @Deprecated public static Party getPlayerParty(String playerName) { //If the party system is disabled, return null - if(!mcMMO.getConfigManager().getConfigParty().isPartySystemEnabled()) + if (!mcMMO.getConfigManager().getConfigParty().isPartySystemEnabled()) return null; for (Party party : parties) { @@ -290,7 +286,7 @@ public final class PartyManager { */ public static Party getPlayerParty(String playerName, UUID uuid) { //If the party system is disabled, return null - if(!mcMMO.getConfigManager().getConfigParty().isPartySystemEnabled()) + if (!mcMMO.getConfigManager().getConfigParty().isPartySystemEnabled()) return null; for (Party party : parties) { @@ -317,8 +313,7 @@ public final class PartyManager { */ public static Party getParty(Player player) { //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return null; } @@ -340,7 +335,7 @@ public final class PartyManager { * Remove a player from a party. * * @param player The player to remove - * @param party The party + * @param party The party */ public static void removeFromParty(OfflinePlayer player, Party party) { LinkedHashMap members = party.getMembers(); @@ -354,8 +349,7 @@ public final class PartyManager { if (members.isEmpty()) { parties.remove(party); - } - else { + } else { // If the leaving player was the party leader, appoint a new leader from the party members if (party.getLeader().getUniqueId().equals(player.getUniqueId())) { setPartyLeader(members.keySet().iterator().next(), party); @@ -384,8 +378,7 @@ public final class PartyManager { //TODO: Potential issues with unloaded profile? for (Player member : party.getOnlineMembers()) { //Profile not loaded - if(UserManager.getPlayer(member) == null) - { + if (UserManager.getPlayer(member) == null) { continue; } @@ -404,8 +397,8 @@ public final class PartyManager { * Create a new party * * @param mcMMOPlayer The player to add to the party - * @param partyName The party to add the player to - * @param password The password for this party, null if there was no password + * @param partyName The party to add the player to + * @param password The password for this party, null if there was no password */ public static void createParty(McMMOPlayer mcMMOPlayer, String partyName, String password) { Player player = mcMMOPlayer.getPlayer(); @@ -425,8 +418,8 @@ public final class PartyManager { /** * Check if a player can join a party * - * @param player The player trying to join a party - * @param party The party + * @param player The player trying to join a party + * @param party The party * @param password The password provided by the player * @return true if the player can join the party */ @@ -470,11 +463,10 @@ public final class PartyManager { /* * Don't let players join a full party */ - if(mcMMO.getConfigManager().getConfigParty().isPartySizeCapped() && invite.getMembers().size() >= mcMMO.getConfigManager().getConfigParty().getPartySizeLimit()) - { + if (mcMMO.getConfigManager().getConfigParty().isPartySizeCapped() && invite.getMembers().size() >= mcMMO.getConfigManager().getConfigParty().getPartySizeLimit()) { NotificationManager.sendPlayerInformation(mcMMOPlayer.getPlayer(), NotificationType.PARTY_MESSAGE, "Commands.Party.PartyFull.InviteAccept", - invite.getName(), String.valueOf(mcMMO.getConfigManager().getConfigParty().getPartySizeLimit())); + invite.getName(), String.valueOf(mcMMO.getConfigManager().getConfigParty().getPartySizeLimit())); return; } @@ -521,7 +513,7 @@ public final class PartyManager { } } - public static void disbandAlliance(Player player, Party firstParty, Party secondParty){ + public static void disbandAlliance(Player player, Party firstParty, Party secondParty) { if (!handlePartyChangeAllianceEvent(player, firstParty.getName(), secondParty.getName(), McMMOPartyAllianceChangeEvent.EventReason.DISBAND_ALLIANCE)) { return; } @@ -546,7 +538,7 @@ public final class PartyManager { * Add a player to a party * * @param mcMMOPlayer The player to add to the party - * @param party The party + * @param party The party */ public static void addToParty(McMMOPlayer mcMMOPlayer, Party party) { Player player = mcMMOPlayer.getPlayer(); @@ -573,7 +565,7 @@ public final class PartyManager { /** * Set the leader of a party. * - * @param uuid The uuid of the player to set as leader + * @param uuid The uuid of the player to set as leader * @param party The party */ public static void setPartyLeader(UUID uuid, Party party) { @@ -585,11 +577,9 @@ public final class PartyManager { if (memberUniqueId.equals(player.getUniqueId())) { member.sendMessage(LocaleLoader.getString("Party.Owner.Player")); - } - else if (memberUniqueId.equals(leaderUniqueId)) { + } else if (memberUniqueId.equals(leaderUniqueId)) { member.sendMessage(LocaleLoader.getString("Party.Owner.NotLeader")); - } - else { + } else { member.sendMessage(LocaleLoader.getString("Party.Owner.New", player.getName())); } } @@ -709,8 +699,7 @@ public final class PartyManager { try { partiesFile.save(partyFile); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } } @@ -785,10 +774,10 @@ public final class PartyManager { /** * Handle party change event. * - * @param player The player changing parties + * @param player The player changing parties * @param oldPartyName The name of the old party * @param newPartyName The name of the new party - * @param reason The reason for changing parties + * @param reason The reason for changing parties * @return true if the change event was successful, false otherwise */ public static boolean handlePartyChangeEvent(Player player, String oldPartyName, String newPartyName, EventReason reason) { @@ -801,10 +790,10 @@ public final class PartyManager { /** * Handle party alliance change event. * - * @param player The player changing party alliances + * @param player The player changing party alliances * @param oldAllyName The name of the old ally * @param newAllyName The name of the new ally - * @param reason The reason for changing allies + * @param reason The reason for changing allies * @return true if the change event was successful, false otherwise */ public static boolean handlePartyChangeAllianceEvent(Player player, String oldAllyName, String newAllyName, McMMOPartyAllianceChangeEvent.EventReason reason) { @@ -828,9 +817,9 @@ public final class PartyManager { /** * Notify party members when the party levels up. * - * @param party The concerned party + * @param party The concerned party * @param levelsGained The amount of levels gained - * @param level The current party level + * @param level The current party level */ public static void informPartyMembersLevelUp(Party party, int levelsGained, int level) { boolean levelUpSoundsEnabled = MainConfig.getInstance().getLevelUpSoundsEnabled(); @@ -846,7 +835,7 @@ public final class PartyManager { /** * Notify party members when a player joins. * - * @param party The concerned party + * @param party The concerned party * @param playerName The name of the player that joined */ private static void informPartyMembersJoin(Party party, String playerName) { @@ -858,7 +847,7 @@ public final class PartyManager { /** * Notify party members when a party member quits. * - * @param party The concerned party + * @param party The concerned party * @param playerName The name of the player that left */ private static void informPartyMembersQuit(Party party, String playerName) { diff --git a/src/main/java/com/gmail/nossr50/party/ShareHandler.java b/src/main/java/com/gmail/nossr50/party/ShareHandler.java index 499a82763..8a1063177 100644 --- a/src/main/java/com/gmail/nossr50/party/ShareHandler.java +++ b/src/main/java/com/gmail/nossr50/party/ShareHandler.java @@ -18,13 +18,14 @@ import org.bukkit.inventory.ItemStack; import java.util.List; public final class ShareHandler { - private ShareHandler() {} + private ShareHandler() { + } /** * Distribute Xp amongst party members. * - * @param xp Xp without party sharing - * @param mcMMOPlayer Player initiating the Xp gain + * @param xp Xp without party sharing + * @param mcMMOPlayer Player initiating the Xp gain * @param primarySkillType Skill being used * @return True is the xp has been shared */ @@ -45,14 +46,13 @@ public final class ShareHandler { int partySize = nearMembers.size(); double shareBonus = Math.min(mcMMO.getPartyXPShareSettings().getPartyShareXPBonusBase() - + (partySize * mcMMO.getPartyXPShareSettings().getPartyShareBonusIncrease()), - mcMMO.getPartyXPShareSettings().getPartyShareBonusCap()); + + (partySize * mcMMO.getPartyXPShareSettings().getPartyShareBonusIncrease()), + mcMMO.getPartyXPShareSettings().getPartyShareBonusCap()); float splitXp = (float) (xp / partySize * shareBonus); for (Player member : nearMembers) { //Profile not loaded - if(UserManager.getPlayer(member) == null) - { + if (UserManager.getPlayer(member) == null) { continue; } @@ -65,7 +65,7 @@ public final class ShareHandler { /** * Distribute Items amongst party members. * - * @param drop Item that will get shared + * @param drop Item that will get shared * @param mcMMOPlayer Player who picked up the item * @return True if the item has been shared */ @@ -115,8 +115,7 @@ public final class ShareHandler { McMMOPlayer mcMMOMember = UserManager.getPlayer(member); //Profile not loaded - if(UserManager.getPlayer(member) == null) - { + if (UserManager.getPlayer(member) == null) { continue; } @@ -159,7 +158,7 @@ public final class ShareHandler { } public static int getItemWeight(Material material) { - if(mcMMO.getConfigManager().getConfigParty().getPartyItemShare().getItemShareMap().get(material) == null) + if (mcMMO.getConfigManager().getConfigParty().getPartyItemShare().getItemShareMap().get(material) == null) return 5; else return mcMMO.getConfigManager().getConfigParty().getPartyItemShare().getItemShareMap().get(material); @@ -168,11 +167,9 @@ public final class ShareHandler { public static XPGainReason getSharedXpGainReason(XPGainReason xpGainReason) { if (xpGainReason == XPGainReason.PVE) { return XPGainReason.SHARED_PVE; - } - else if (xpGainReason == XPGainReason.PVP) { + } else if (xpGainReason == XPGainReason.PVP) { return XPGainReason.SHARED_PVP; - } - else { + } else { return xpGainReason; } } diff --git a/src/main/java/com/gmail/nossr50/runnables/PistonTrackerTask.java b/src/main/java/com/gmail/nossr50/runnables/PistonTrackerTask.java index 9f01d64e5..0deced042 100644 --- a/src/main/java/com/gmail/nossr50/runnables/PistonTrackerTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/PistonTrackerTask.java @@ -36,8 +36,7 @@ public class PistonTrackerTask extends BukkitRunnable { if (nextBlock.hasMetadata(mcMMO.blockMetadataKey)) { mcMMO.getPlaceStore().setTrue(nextBlock); nextBlock.removeMetadata(mcMMO.blockMetadataKey, mcMMO.p); - } - else if (mcMMO.getPlaceStore().isTrue(nextBlock)) { + } else if (mcMMO.getPlaceStore().isTrue(nextBlock)) { // Block doesn't have metadatakey but isTrue - set it to false mcMMO.getPlaceStore().setFalse(nextBlock); } diff --git a/src/main/java/com/gmail/nossr50/runnables/backups/CleanBackupsTask.java b/src/main/java/com/gmail/nossr50/runnables/backups/CleanBackupsTask.java index e8f68b447..09c215d41 100644 --- a/src/main/java/com/gmail/nossr50/runnables/backups/CleanBackupsTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/backups/CleanBackupsTask.java @@ -31,7 +31,7 @@ public class CleanBackupsTask extends BukkitRunnable { //if(BACKUP_DIR.listFiles().length < mcMMO.getConfigManager().getConfigAutomatedBackups().getMinimumBackupCount()) //Don't remove files unless there is at least 10 of them - if(BACKUP_DIR.listFiles().length < 10) + if (BACKUP_DIR.listFiles().length < 10) return; // Check files in backup folder from oldest to newest @@ -54,8 +54,7 @@ public class CleanBackupsTask extends BukkitRunnable { long currentTime = System.currentTimeMillis(); //File is not old enough so don't delete it - if((fileSaveTimeStamp + (oldFileAgeLimit * TimeUnit.MILLISECONDS.convert(24, TimeUnit.HOURS))) >= currentTime) - { + if ((fileSaveTimeStamp + (oldFileAgeLimit * TimeUnit.MILLISECONDS.convert(24, TimeUnit.HOURS))) >= currentTime) { continue; } @@ -80,7 +79,6 @@ public class CleanBackupsTask extends BukkitRunnable { * Check if date is within last 24 hours * * @param date date to check - * * @return true is date is within last 24 hours, false if otherwise */ private boolean isPast24Hours(Date date) { @@ -92,7 +90,6 @@ public class CleanBackupsTask extends BukkitRunnable { * Check if date is within the last week * * @param date date to check - * * @return true is date is within the last week, false if otherwise */ private boolean isLastWeek(Date date) { @@ -106,8 +103,7 @@ public class CleanBackupsTask extends BukkitRunnable { try { date = dateFormat.parse(fileName); - } - catch (ParseException e) { + } catch (ParseException e) { return null; } diff --git a/src/main/java/com/gmail/nossr50/runnables/commands/McrankCommandDisplayTask.java b/src/main/java/com/gmail/nossr50/runnables/commands/McrankCommandDisplayTask.java index e284b2745..6cf40aabe 100644 --- a/src/main/java/com/gmail/nossr50/runnables/commands/McrankCommandDisplayTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/commands/McrankCommandDisplayTask.java @@ -62,8 +62,7 @@ public class McrankCommandDisplayTask extends BukkitRunnable { public void displayBoard() { if (sender.getName().equalsIgnoreCase(playerName)) { ScoreboardManager.showPlayerRankScoreboard((Player) sender, skills); - } - else { + } else { ScoreboardManager.showPlayerRankScoreboardOthers((Player) sender, playerName, skills); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java b/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java index dd25ecc63..41c1ae7ce 100644 --- a/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java @@ -44,25 +44,22 @@ public class MctopCommandDisplayTask extends BukkitRunnable { if (sender instanceof Player) { ((Player) sender).removeMetadata(mcMMO.databaseCommandKey, mcMMO.p); } - if(sender instanceof Player) + if (sender instanceof Player) sender.sendMessage(LocaleLoader.getString("Commands.mctop.Tip")); } private void displayChat() { if (skill == null) { - if(sender instanceof Player) { + if (sender instanceof Player) { sender.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Leaderboard")); - } - else { + } else { sender.sendMessage(ChatColor.stripColor(LocaleLoader.getString("Commands.PowerLevel.Leaderboard"))); } - } - else { - if(sender instanceof Player) { + } else { + if (sender instanceof Player) { sender.sendMessage(LocaleLoader.getString("Commands.Skill.Leaderboard", skill.getName())); - } - else { + } else { sender.sendMessage(ChatColor.stripColor(LocaleLoader.getString("Commands.Skill.Leaderboard", skill.getName()))); } } @@ -73,13 +70,12 @@ public class MctopCommandDisplayTask extends BukkitRunnable { // Format: // 01. Playername - skill value // 12. Playername - skill value - if(sender instanceof Player) { + if (sender instanceof Player) { sender.sendMessage(String.format("%2d. %s%s - %s%s", place, ChatColor.GREEN, stat.name, ChatColor.WHITE, stat.statVal)); - } - else { + } else { sender.sendMessage(String.format("%2d. %s - %s", place, stat.name, stat.statVal)); } - + place++; } } @@ -87,8 +83,7 @@ public class MctopCommandDisplayTask extends BukkitRunnable { private void displayBoard() { if (skill == null) { ScoreboardManager.showTopPowerScoreboard((Player) sender, page, userStats); - } - else { + } else { ScoreboardManager.showTopScoreboard((Player) sender, skill, page, userStats); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/commands/NotifySquelchReminderTask.java b/src/main/java/com/gmail/nossr50/runnables/commands/NotifySquelchReminderTask.java index 4d7b11fc6..1f347bac4 100644 --- a/src/main/java/com/gmail/nossr50/runnables/commands/NotifySquelchReminderTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/commands/NotifySquelchReminderTask.java @@ -11,10 +11,8 @@ public class NotifySquelchReminderTask extends BukkitRunnable { @Override public void run() { for (Player player : Bukkit.getOnlinePlayers()) { - if(UserManager.getPlayer(player) != null) - { - if(!UserManager.getPlayer(player).useChatNotifications()) - { + if (UserManager.getPlayer(player) != null) { + if (!UserManager.getPlayer(player).useChatNotifications()) { player.sendMessage(LocaleLoader.getString("Reminder.Squelched")); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/database/FormulaConversionTask.java b/src/main/java/com/gmail/nossr50/runnables/database/FormulaConversionTask.java index f818cebba..6cfbe782f 100644 --- a/src/main/java/com/gmail/nossr50/runnables/database/FormulaConversionTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/database/FormulaConversionTask.java @@ -42,8 +42,7 @@ public class FormulaConversionTask extends BukkitRunnable { editValues(profile); // Since this is a temporary profile, we save it here. profile.scheduleAsyncSave(); - } - else { + } else { profile = mcMMOPlayer.getProfile(); editValues(profile); } diff --git a/src/main/java/com/gmail/nossr50/runnables/database/UserPurgeTask.java b/src/main/java/com/gmail/nossr50/runnables/database/UserPurgeTask.java index baf5574c5..a841b3a8f 100644 --- a/src/main/java/com/gmail/nossr50/runnables/database/UserPurgeTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/database/UserPurgeTask.java @@ -7,10 +7,11 @@ import java.util.concurrent.locks.ReentrantLock; public class UserPurgeTask extends BukkitRunnable { private ReentrantLock lock = new ReentrantLock(); + @Override public void run() { lock.lock(); - if(mcMMO.getDatabaseCleaningSettings().isPurgePowerlessUsers()) + if (mcMMO.getDatabaseCleaningSettings().isPurgePowerlessUsers()) mcMMO.getDatabaseManager().purgePowerlessUsers(); if (mcMMO.getDatabaseCleaningSettings().isPurgeOldUsers()) { diff --git a/src/main/java/com/gmail/nossr50/runnables/player/PlayerProfileLoadingTask.java b/src/main/java/com/gmail/nossr50/runnables/player/PlayerProfileLoadingTask.java index 590011a39..623028c56 100644 --- a/src/main/java/com/gmail/nossr50/runnables/player/PlayerProfileLoadingTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/player/PlayerProfileLoadingTask.java @@ -44,8 +44,7 @@ public class PlayerProfileLoadingTask extends BukkitRunnable { } // Print errors to console/logs if we're failing at least 2 times in a row to load the profile - if (attempt >= 3) - { + if (attempt >= 3) { //Log the error mcMMO.p.getLogger().severe(LocaleLoader.getString("Profile.Loading.FailureNotice", player.getName(), String.valueOf(attempt))); diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java index 904aebc35..f978b5d29 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java @@ -31,8 +31,7 @@ public class AlchemyBrewCheckTask extends BukkitRunnable { if (oldInventory[Alchemy.INGREDIENT_SLOT] == null || newInventory[Alchemy.INGREDIENT_SLOT] == null || !oldInventory[Alchemy.INGREDIENT_SLOT].isSimilar(newInventory[Alchemy.INGREDIENT_SLOT]) || !validBrew) { Alchemy.brewingStandMap.get(location).cancelBrew(); } - } - else if (validBrew) { + } else if (validBrew) { Alchemy.brewingStandMap.put(location, new AlchemyBrewTask(brewingStand, player)); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewTask.java index c942fcb19..4ecb1455b 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewTask.java @@ -86,8 +86,7 @@ public class AlchemyBrewTask extends BukkitRunnable { if (brewTimer < Math.max(brewSpeed, 2)) { this.cancel(); finish(); - } - else { + } else { ((BrewingStand) brewingStand).setBrewingTime((int) brewTimer); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/BleedContainer.java b/src/main/java/com/gmail/nossr50/runnables/skills/BleedContainer.java index 32b4b9eca..fc0a335a6 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/BleedContainer.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/BleedContainer.java @@ -9,12 +9,11 @@ public class BleedContainer { public LivingEntity target; public LivingEntity damageSource; - public BleedContainer(LivingEntity target, int bleedTicks, int bleedRank, int toolTier, LivingEntity damageSource) - { - this.target = target; - this.bleedTicks = bleedTicks; - this.bleedRank = bleedRank; - this.toolTier = toolTier; - this.damageSource = damageSource; + public BleedContainer(LivingEntity target, int bleedTicks, int bleedRank, int toolTier, LivingEntity damageSource) { + this.target = target; + this.bleedTicks = bleedTicks; + this.bleedRank = bleedRank; + this.toolTier = toolTier; + this.damageSource = damageSource; } } diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/BleedTimerTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/BleedTimerTask.java index 4d731fb1a..051c69458 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/BleedTimerTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/BleedTimerTask.java @@ -22,123 +22,7 @@ import java.util.Map.Entry; public class BleedTimerTask extends BukkitRunnable { private static Map bleedList = new HashMap<>(); - @Override - public void run() { - Iterator> bleedIterator = bleedList.entrySet().iterator(); - - while (bleedIterator.hasNext()) { - Entry containerEntry = bleedIterator.next(); - LivingEntity target = containerEntry.getKey(); - int toolTier = containerEntry.getValue().toolTier; - -// String debugMessage = ""; -// debugMessage += ChatColor.GOLD + "Target ["+target.getName()+"]: " + ChatColor.RESET; - -// debugMessage+="RemainingTicks=["+containerEntry.getValue().bleedTicks+"], "; - - if (containerEntry.getValue().bleedTicks <= 0 || !target.isValid()) { - if(target instanceof Player) - { - NotificationManager.sendPlayerInformation((Player) target, NotificationType.SUBSKILL_MESSAGE, "Swords.Combat.Bleeding.Stopped"); - } - - bleedIterator.remove(); - continue; - } - - int armorCount = 0; - - double damage; - - if (target instanceof Player) { - damage = AdvancedConfig.getInstance().getRuptureDamagePlayer(); - - //Above Bleed Rank 3 deals 50% more damage - if (containerEntry.getValue().toolTier >= 4 && containerEntry.getValue().bleedRank >= 3) - damage = damage * 1.5; - - Player player = (Player) target; - - if (!player.isOnline()) { - continue; - } - - //Count Armor - for(ItemStack armorPiece : ((Player) target).getInventory().getArmorContents()) - { - if(armorPiece != null) - armorCount++; - } - - } else { - damage = AdvancedConfig.getInstance().getRuptureDamageMobs(); - -// debugMessage+="BaseDMG=["+damage+"], "; - - //Above Bleed Rank 3 deals 50% more damage - if (containerEntry.getValue().bleedRank >= 3) - { - damage = damage * 1.5; - } - -// debugMessage+="Rank4Bonus=["+String.valueOf(containerEntry.getValue().bleedRank >= 3)+"], "; - - - MobHealthbarUtils.handleMobHealthbars(target, damage, mcMMO.p); //Update health bars - } - -// debugMessage+="FullArmor=["+String.valueOf(armorCount > 3)+"], "; - - if(armorCount > 3) - { - damage = damage * .75; - } - -// debugMessage+="AfterRankAndArmorChecks["+damage+"], "; - - //Weapons below Diamond get damage cut in half - if(toolTier < 4) - damage = damage / 2; - -// debugMessage+="AfterDiamondCheck=["+String.valueOf(damage)+"], "; - - //Wood weapons get damage cut in half again - if(toolTier < 2) - damage = damage / 2; - -// debugMessage+="AfterWoodenCheck=["+String.valueOf(damage)+"], "; - - double victimHealth = target.getHealth(); - -// debugMessage+="TargetHealthBeforeDMG=["+String.valueOf(target.getHealth())+"], "; - - CombatUtils.dealNoInvulnerabilityTickDamageRupture(target, damage, containerEntry.getValue().damageSource, toolTier); - - double victimHealthAftermath = target.getHealth(); - -// debugMessage+="TargetHealthAfterDMG=["+String.valueOf(target.getHealth())+"], "; - - if(victimHealthAftermath <= 0 || victimHealth != victimHealthAftermath) - { - //Play Bleed Sound - SoundManager.worldSendSound(target.getWorld(), target.getLocation(), SoundType.BLEED); - - ParticleEffectUtils.playBleedEffect(target); - } - - //Lower Bleed Ticks - BleedContainer loweredBleedContainer = copyContainer(containerEntry.getValue()); - loweredBleedContainer.bleedTicks -= 1; - -// debugMessage+="RemainingTicks=["+loweredBleedContainer.bleedTicks+"]"; - containerEntry.setValue(loweredBleedContainer); - -// Bukkit.broadcastMessage(debugMessage); - } - } - - public static BleedContainer copyContainer(BleedContainer container) - { + public static BleedContainer copyContainer(BleedContainer container) { LivingEntity target = container.target; LivingEntity source = container.damageSource; int bleedTicks = container.bleedTicks; @@ -168,10 +52,10 @@ public class BleedTimerTask extends BukkitRunnable { * Add a LivingEntity to the bleedList if it is not in it. * * @param entity LivingEntity to add - * @param ticks Number of bleeding ticks + * @param ticks Number of bleeding ticks */ public static void add(LivingEntity entity, LivingEntity attacker, int ticks, int bleedRank, int toolTier) { - if(toolTier < 4) + if (toolTier < 4) ticks = Math.max(1, (ticks / 3)); BleedContainer newBleedContainer = new BleedContainer(entity, ticks, bleedRank, toolTier, attacker); @@ -181,4 +65,114 @@ public class BleedTimerTask extends BukkitRunnable { public static boolean isBleeding(LivingEntity entity) { return bleedList.containsKey(entity); } + + @Override + public void run() { + Iterator> bleedIterator = bleedList.entrySet().iterator(); + + while (bleedIterator.hasNext()) { + Entry containerEntry = bleedIterator.next(); + LivingEntity target = containerEntry.getKey(); + int toolTier = containerEntry.getValue().toolTier; + +// String debugMessage = ""; +// debugMessage += ChatColor.GOLD + "Target ["+target.getName()+"]: " + ChatColor.RESET; + +// debugMessage+="RemainingTicks=["+containerEntry.getValue().bleedTicks+"], "; + + if (containerEntry.getValue().bleedTicks <= 0 || !target.isValid()) { + if (target instanceof Player) { + NotificationManager.sendPlayerInformation((Player) target, NotificationType.SUBSKILL_MESSAGE, "Swords.Combat.Bleeding.Stopped"); + } + + bleedIterator.remove(); + continue; + } + + int armorCount = 0; + + double damage; + + if (target instanceof Player) { + damage = AdvancedConfig.getInstance().getRuptureDamagePlayer(); + + //Above Bleed Rank 3 deals 50% more damage + if (containerEntry.getValue().toolTier >= 4 && containerEntry.getValue().bleedRank >= 3) + damage = damage * 1.5; + + Player player = (Player) target; + + if (!player.isOnline()) { + continue; + } + + //Count Armor + for (ItemStack armorPiece : ((Player) target).getInventory().getArmorContents()) { + if (armorPiece != null) + armorCount++; + } + + } else { + damage = AdvancedConfig.getInstance().getRuptureDamageMobs(); + +// debugMessage+="BaseDMG=["+damage+"], "; + + //Above Bleed Rank 3 deals 50% more damage + if (containerEntry.getValue().bleedRank >= 3) { + damage = damage * 1.5; + } + +// debugMessage+="Rank4Bonus=["+String.valueOf(containerEntry.getValue().bleedRank >= 3)+"], "; + + + MobHealthbarUtils.handleMobHealthbars(target, damage, mcMMO.p); //Update health bars + } + +// debugMessage+="FullArmor=["+String.valueOf(armorCount > 3)+"], "; + + if (armorCount > 3) { + damage = damage * .75; + } + +// debugMessage+="AfterRankAndArmorChecks["+damage+"], "; + + //Weapons below Diamond get damage cut in half + if (toolTier < 4) + damage = damage / 2; + +// debugMessage+="AfterDiamondCheck=["+String.valueOf(damage)+"], "; + + //Wood weapons get damage cut in half again + if (toolTier < 2) + damage = damage / 2; + +// debugMessage+="AfterWoodenCheck=["+String.valueOf(damage)+"], "; + + double victimHealth = target.getHealth(); + +// debugMessage+="TargetHealthBeforeDMG=["+String.valueOf(target.getHealth())+"], "; + + CombatUtils.dealNoInvulnerabilityTickDamageRupture(target, damage, containerEntry.getValue().damageSource, toolTier); + + double victimHealthAftermath = target.getHealth(); + +// debugMessage+="TargetHealthAfterDMG=["+String.valueOf(target.getHealth())+"], "; + + if (victimHealthAftermath <= 0 || victimHealth != victimHealthAftermath) { + //Play Bleed Sound + SoundManager.worldSendSound(target.getWorld(), target.getLocation(), SoundType.BLEED); + + ParticleEffectUtils.playBleedEffect(target); + } + + //Lower Bleed Ticks + BleedContainer loweredBleedContainer = copyContainer(containerEntry.getValue()); + loweredBleedContainer.bleedTicks -= 1; + +// debugMessage+="RemainingTicks=["+loweredBleedContainer.bleedTicks+"]"; + containerEntry.setValue(loweredBleedContainer); + +// Bukkit.broadcastMessage(debugMessage); + } + } } diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/ExperienceBarHideTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/ExperienceBarHideTask.java index 23e78909c..cf9654b26 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/ExperienceBarHideTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/ExperienceBarHideTask.java @@ -10,8 +10,7 @@ public class ExperienceBarHideTask extends BukkitRunnable { public final PrimarySkillType primarySkillType; public final ExperienceBarManager experienceBarManagerRef; - public ExperienceBarHideTask(ExperienceBarManager experienceBarManagerRef, McMMOPlayer mcMMOPlayer, PrimarySkillType primarySkillType) - { + public ExperienceBarHideTask(ExperienceBarManager experienceBarManagerRef, McMMOPlayer mcMMOPlayer, PrimarySkillType primarySkillType) { this.experienceBarManagerRef = experienceBarManagerRef; this.mcMMOPlayer = mcMMOPlayer; this.primarySkillType = primarySkillType; @@ -30,7 +29,7 @@ public class ExperienceBarHideTask extends BukkitRunnable { */ @Override public void run() { - if(experienceBarManagerRef == null || mcMMOPlayer == null) + if (experienceBarManagerRef == null || mcMMOPlayer == null) return; experienceBarManagerRef.hideExperienceBar(primarySkillType); diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/SkillUnlockNotificationTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/SkillUnlockNotificationTask.java index 2e23e42eb..0add04cac 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/SkillUnlockNotificationTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/SkillUnlockNotificationTask.java @@ -10,18 +10,20 @@ public class SkillUnlockNotificationTask extends BukkitRunnable { private McMMOPlayer mcMMOPlayer; private SubSkillType subSkillType; private int rank; + /** * Notify a player about a newly unlocked subskill - * @param mcMMOPlayer target player + * + * @param mcMMOPlayer target player * @param subSkillType the subskill that they just unlocked - * @param rank the rank of the subskill + * @param rank the rank of the subskill */ - public SkillUnlockNotificationTask(McMMOPlayer mcMMOPlayer, SubSkillType subSkillType, int rank) - { + public SkillUnlockNotificationTask(McMMOPlayer mcMMOPlayer, SubSkillType subSkillType, int rank) { this.mcMMOPlayer = mcMMOPlayer; this.subSkillType = subSkillType; this.rank = rank; } + /** * When an object implementing interface Runnable is used * to create a thread, starting the thread causes the object's diff --git a/src/main/java/com/gmail/nossr50/skills/SkillManager.java b/src/main/java/com/gmail/nossr50/skills/SkillManager.java index ccfd3fe8f..153d394b8 100644 --- a/src/main/java/com/gmail/nossr50/skills/SkillManager.java +++ b/src/main/java/com/gmail/nossr50/skills/SkillManager.java @@ -27,7 +27,8 @@ public abstract class SkillManager { /** * Applies XP to a player, provides SELF as an XpGainSource source - * @param xp amount of XP to apply + * + * @param xp amount of XP to apply * @param xpGainReason the reason for the XP gain * @deprecated use applyXpGain(float, XPGainReason, XPGainSource) */ @@ -38,7 +39,8 @@ public abstract class SkillManager { /** * Applies XP to a player - * @param xp amount of XP to apply + * + * @param xp amount of XP to apply * @param xpGainReason the reason for the XP gain * @param xpGainSource the source of the XP */ diff --git a/src/main/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsManager.java b/src/main/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsManager.java index 3536e4a83..47fd4be7b 100644 --- a/src/main/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsManager.java +++ b/src/main/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsManager.java @@ -22,37 +22,32 @@ import org.bukkit.entity.Player; public class AcrobaticsManager extends SkillManager { + private long rollXPCooldown = 0; + private long rollXPInterval; + private long rollXPIntervalLengthen = (1000 * 10); //10 Seconds + private LimitedSizeList fallLocationMap; public AcrobaticsManager(McMMOPlayer mcMMOPlayer) { super(mcMMOPlayer, PrimarySkillType.ACROBATICS); rollXPInterval = (1000 * mcMMO.getConfigManager().getConfigExploitPrevention().getConfigSectionExploitAcrobatics().getRollXPGainCooldownSeconds()); //Save some memory if exploit prevention is off - if(mcMMO.getConfigManager().getConfigExploitPrevention().getConfigSectionExploitAcrobatics().isPreventAcrobaticsAbuse()) + if (mcMMO.getConfigManager().getConfigExploitPrevention().getConfigSectionExploitAcrobatics().isPreventAcrobaticsAbuse()) fallLocationMap = new LimitedSizeList(mcMMO.getConfigManager().getConfigExploitPrevention().getAcrobaticLocationLimit()); } - private long rollXPCooldown = 0; - private long rollXPInterval; - private long rollXPIntervalLengthen = (1000 * 10); //10 Seconds - private LimitedSizeList fallLocationMap; - - public boolean hasFallenInLocationBefore(Location location) - { + public boolean hasFallenInLocationBefore(Location location) { return fallLocationMap.contains(location); } - public void addLocationToFallMap(Location location) - { + public void addLocationToFallMap(Location location) { fallLocationMap.add(location); } - public boolean canGainRollXP() - { - if(!mcMMO.getConfigManager().getConfigExploitPrevention().getConfigSectionExploitAcrobatics().isPreventAcrobaticsAbuse()) + public boolean canGainRollXP() { + if (!mcMMO.getConfigManager().getConfigExploitPrevention().getConfigSectionExploitAcrobatics().isPreventAcrobaticsAbuse()) return true; - if(System.currentTimeMillis() >= rollXPCooldown) - { + if (System.currentTimeMillis() >= rollXPCooldown) { rollXPCooldown = System.currentTimeMillis() + rollXPInterval; rollXPIntervalLengthen = (1000 * 10); //5 Seconds return true; @@ -64,7 +59,7 @@ public class AcrobaticsManager extends SkillManager { } public boolean canDodge(Entity damager) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ACROBATICS_DODGE)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ACROBATICS_DODGE)) return false; if (Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.ACROBATICS_DODGE)) { @@ -96,7 +91,7 @@ public class AcrobaticsManager extends SkillManager { } //Check respawn to prevent abuse - if(!mcMMO.getConfigManager().getConfigExploitPrevention().getConfigSectionExploitAcrobatics().isPreventAcrobaticsAbuse()) + if (!mcMMO.getConfigManager().getConfigExploitPrevention().getConfigSectionExploitAcrobatics().isPreventAcrobaticsAbuse()) applyXpGain((float) (damage * Acrobatics.dodgeXpModifier), XPGainReason.PVP); else if (SkillUtils.cooldownExpired(mcMMOPlayer.getRespawnATS(), Misc.PLAYER_RESPAWN_COOLDOWN_SECONDS) && mcMMOPlayer.getTeleportATS() < System.currentTimeMillis()) { diff --git a/src/main/java/com/gmail/nossr50/skills/alchemy/Alchemy.java b/src/main/java/com/gmail/nossr50/skills/alchemy/Alchemy.java index 2553854d5..dac62a3ce 100644 --- a/src/main/java/com/gmail/nossr50/skills/alchemy/Alchemy.java +++ b/src/main/java/com/gmail/nossr50/skills/alchemy/Alchemy.java @@ -49,14 +49,15 @@ public final class Alchemy { public static final int INGREDIENT_SLOT = 3; - public static int catalysisUnlockLevel = RankUtils.getUnlockLevel(SubSkillType.ALCHEMY_CATALYSIS); - public static int catalysisMaxBonusLevel = AdvancedConfig.getInstance().getCatalysisMaxBonusLevel(); - public static double catalysisMinSpeed = AdvancedConfig.getInstance().getCatalysisMinSpeed(); - public static double catalysisMaxSpeed = AdvancedConfig.getInstance().getCatalysisMaxSpeed(); + public static int catalysisUnlockLevel = RankUtils.getUnlockLevel(SubSkillType.ALCHEMY_CATALYSIS); + public static int catalysisMaxBonusLevel = AdvancedConfig.getInstance().getCatalysisMaxBonusLevel(); + public static double catalysisMinSpeed = AdvancedConfig.getInstance().getCatalysisMinSpeed(); + public static double catalysisMaxSpeed = AdvancedConfig.getInstance().getCatalysisMaxSpeed(); public static Map brewingStandMap = new HashMap<>(); - private Alchemy() {} + private Alchemy() { + } /** * Finish all active brews. Used upon Disable to prevent vanilla potions from being brewed upon next Enable. diff --git a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java index 8343d2f4f..1b4614acf 100644 --- a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java +++ b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java @@ -59,11 +59,9 @@ public final class AlchemyPotionBrewer { ItemStack ingredient = inventory.getIngredient() == null ? null : inventory.getIngredient().clone(); if (isEmpty(ingredient) || !isValidIngredient(player, ingredient)) { - } - else if (ingredient.getAmount() <= 1) { + } else if (ingredient.getAmount() <= 1) { inventory.setIngredient(null); - } - else { + } else { ingredient.setAmount(ingredient.getAmount() - 1); inventory.setIngredient(ingredient); } @@ -90,8 +88,7 @@ public final class AlchemyPotionBrewer { } private static List getValidIngredients(Player player) { - if(player == null || UserManager.getPlayer(player) == null) - { + if (player == null || UserManager.getPlayer(player) == null) { return PotionConfig.getInstance().getIngredients(1); } @@ -161,8 +158,7 @@ public final class AlchemyPotionBrewer { if (click.isLeftClick()) { success = transferItems(view, fromSlot); - } - else if (click.isRightClick()) { + } else if (click.isRightClick()) { success = transferOneItem(view, fromSlot); } @@ -182,13 +178,11 @@ public final class AlchemyPotionBrewer { if (!emptyTo && fromAmount >= from.getType().getMaxStackSize()) { return false; - } - else if (emptyTo || from.isSimilar(to)) { + } else if (emptyTo || from.isSimilar(to)) { if (emptyTo) { to = from.clone(); to.setAmount(1); - } - else { + } else { to.setAmount(to.getAmount() + 1); } @@ -211,14 +205,12 @@ public final class AlchemyPotionBrewer { if (isEmpty(from)) { return false; - } - else if (isEmpty(to)) { + } else if (isEmpty(to)) { view.setItem(Alchemy.INGREDIENT_SLOT, from); view.setItem(fromSlot, null); return true; - } - else if (from.isSimilar(to)) { + } else if (from.isSimilar(to)) { int fromAmount = from.getAmount(); int toAmount = to.getAmount(); int maxSize = to.getType().getMaxStackSize(); diff --git a/src/main/java/com/gmail/nossr50/skills/alchemy/PotionGenerator.java b/src/main/java/com/gmail/nossr50/skills/alchemy/PotionGenerator.java index 151f78db7..f4797903a 100644 --- a/src/main/java/com/gmail/nossr50/skills/alchemy/PotionGenerator.java +++ b/src/main/java/com/gmail/nossr50/skills/alchemy/PotionGenerator.java @@ -14,114 +14,6 @@ import java.util.Map.Entry; public class PotionGenerator { - public static class Ingredient { - - public Material mat; - public int data; - public String name; - - public Ingredient(Material mat) { - this.mat = mat; - this.data = 0; - name = mat.name(); - } - - } - public static class WriteablePotion { - - public String name; - public Material mat; - public PotionData data; - public PotionEffect effect; - public String baseName; - - public WriteablePotion(PotionData data) { - this(Material.POTION, data); - } - - public WriteablePotion(Material type, PotionData data) { - this(type, data, null, getMCName(data.getType())); - } - - public WriteablePotion(Material mat, PotionType type, PotionEffect effect, String baseName) { - this(mat, new PotionData(type, false, false), effect, baseName); - } - - public WriteablePotion(Material type, PotionData data, PotionEffect effect, String baseName) { - this.data = data; - this.effect = effect; - this.mat = type; - this.baseName = baseName; - this.name = "POTION_OF_" + baseName; - if (mat == Material.SPLASH_POTION) { - this.name = "SPLASH_" + this.name; - } - if (mat == Material.LINGERING_POTION) { - this.name = "LINGERING_" + this.name; - } - if (data.isExtended()) { - this.name += "_EXTENDED"; - } - if (data.isUpgraded()) { - this.name += "_II"; - } - } - - public WriteablePotion(PotionType type) { - this(new PotionData(type, false, false)); - } - - public WriteablePotion(Material mat, PotionType type) { - this(mat, new PotionData(type, false, false)); - } - - private static String getMCName(PotionType type) { - switch (type) { - case INSTANT_DAMAGE : - return "HARMING"; - case INSTANT_HEAL : - return "HEALING"; - case JUMP : - return "LEAPING"; - case REGEN : - return "REGENERATION"; - case SPEED : - return "SWIFTNESS"; - case UNCRAFTABLE : - return "EMPTY"; - case LUCK : - case MUNDANE : - case NIGHT_VISION : - case POISON : - case INVISIBILITY : - case SLOWNESS : - case AWKWARD : - case STRENGTH : - case THICK : - case FIRE_RESISTANCE : - case WATER : - case WATER_BREATHING : - case WEAKNESS : - case TURTLE_MASTER: - case SLOW_FALLING: - return type.name(); - default : - return ""; - } - } - - public int hashCode() { - return name.hashCode(); - } - - public boolean equals(Object obj) { - if (!(obj instanceof WriteablePotion)) { - return false; - } - return name.equals(((WriteablePotion) obj).name); - } - } - public static void main(String[] args) { Map> vanillaPotions = new HashMap<>(); populateVanillaPotions(vanillaPotions); @@ -250,59 +142,59 @@ public class PotionGenerator { private static String getName(PotionEffectType type) { switch (type.getId()) { - case 1 : + case 1: return "SPEED"; - case 2 : + case 2: return "SLOW"; - case 3 : + case 3: return "FAST_DIGGING"; - case 4 : + case 4: return "SLOW_DIGGING"; - case 5 : + case 5: return "INCREASE_DAMAGE"; - case 6 : + case 6: return "HEAL"; - case 7 : + case 7: return "HARM"; - case 8 : + case 8: return "JUMP"; - case 9 : + case 9: return "CONFUSION"; - case 10 : + case 10: return "REGENERATION"; - case 11 : + case 11: return "DAMAGE_RESISTANCE"; - case 12 : + case 12: return "FIRE_RESISTANCE"; - case 13 : + case 13: return "WATER_BREATHING"; - case 14 : + case 14: return "INVISIBILITY"; - case 15 : + case 15: return "BLINDNESS"; - case 16 : + case 16: return "NIGHT_VISION"; - case 17 : + case 17: return "HUNGER"; - case 18 : + case 18: return "WEAKNESS"; - case 19 : + case 19: return "POISON"; - case 20 : + case 20: return "WITHER"; - case 21 : + case 21: return "HEALTH_BOOST"; - case 22 : + case 22: return "ABSORPTION"; - case 23 : + case 23: return "SATURATION"; - case 24 : + case 24: return "GLOWING"; - case 25 : + case 25: return "LEVITATION"; - case 26 : + case 26: return "LUCK"; - case 27 : + case 27: return "UNLUCK"; case 28: return "SLOW_FALLING"; @@ -310,7 +202,7 @@ public class PotionGenerator { return "CONDUIT_POWER"; case 30: return "DOLPHINS_GRACE"; - default : + default: return "UNKNOWN_EFFECT_TYPE_" + type.getId(); } } @@ -348,9 +240,9 @@ public class PotionGenerator { private static void getChildren(WriteablePotion current, HashMap children) { switch (current.data.getType()) { - case WATER : - assert(!current.data.isExtended()); - assert(!current.data.isUpgraded()); + case WATER: + assert (!current.data.isExtended()); + assert (!current.data.isUpgraded()); children.put(new Ingredient(Material.NETHER_WART), new WriteablePotion(current.mat, PotionType.AWKWARD)); children.put(new Ingredient(Material.FERMENTED_SPIDER_EYE), new WriteablePotion(current.mat, PotionType.WEAKNESS)); children.put(new Ingredient(Material.REDSTONE), new WriteablePotion(current.mat, PotionType.MUNDANE)); @@ -363,9 +255,9 @@ public class PotionGenerator { children.put(new Ingredient(Material.GLISTERING_MELON_SLICE), new WriteablePotion(current.mat, PotionType.MUNDANE)); children.put(new Ingredient(Material.GHAST_TEAR), new WriteablePotion(current.mat, PotionType.MUNDANE)); return; - case AWKWARD : - assert(!current.data.isExtended()); - assert(!current.data.isUpgraded()); + case AWKWARD: + assert (!current.data.isExtended()); + assert (!current.data.isUpgraded()); children.put(new Ingredient(Material.GOLDEN_CARROT), new WriteablePotion(current.mat, PotionType.NIGHT_VISION)); children.put(new Ingredient(Material.RABBIT_FOOT), new WriteablePotion(current.mat, PotionType.JUMP)); children.put(new Ingredient(Material.MAGMA_CREAM), new WriteablePotion(current.mat, PotionType.FIRE_RESISTANCE)); @@ -396,8 +288,8 @@ public class PotionGenerator { children.put(new Ingredient(Material.FERN), new WriteablePotion(current.mat, PotionType.UNCRAFTABLE, new PotionEffect(PotionEffectType.SATURATION, (int) (8 * mod), 0), "SATURATION")); children.put(new Ingredient(Material.APPLE), new WriteablePotion(current.mat, PotionType.UNCRAFTABLE, new PotionEffect(PotionEffectType.HEALTH_BOOST, (int) (1800 * mod), 0), "HEALTH_BOOST")); return; - case FIRE_RESISTANCE : - assert(!current.data.isUpgraded()); + case FIRE_RESISTANCE: + assert (!current.data.isUpgraded()); if (current.data.isExtended()) { children.put(new Ingredient(Material.FERMENTED_SPIDER_EYE), new WriteablePotion(current.mat, new PotionData(PotionType.SLOWNESS, true, false))); } else { @@ -405,14 +297,14 @@ public class PotionGenerator { children.put(new Ingredient(Material.REDSTONE), new WriteablePotion(current.mat, new PotionData(current.data.getType(), true, false))); } return; - case INSTANT_DAMAGE : - assert(!current.data.isExtended()); + case INSTANT_DAMAGE: + assert (!current.data.isExtended()); if (!current.data.isUpgraded()) { children.put(new Ingredient(Material.GLOWSTONE_DUST), new WriteablePotion(current.mat, new PotionData(current.data.getType(), false, true))); } return; - case INSTANT_HEAL : - assert(!current.data.isExtended()); + case INSTANT_HEAL: + assert (!current.data.isExtended()); if (!current.data.isUpgraded()) { children.put(new Ingredient(Material.FERMENTED_SPIDER_EYE), new WriteablePotion(current.mat, PotionType.INSTANT_DAMAGE)); children.put(new Ingredient(Material.GLOWSTONE_DUST), new WriteablePotion(current.mat, new PotionData(current.data.getType(), false, true))); @@ -420,21 +312,21 @@ public class PotionGenerator { children.put(new Ingredient(Material.FERMENTED_SPIDER_EYE), new WriteablePotion(current.mat, new PotionData(PotionType.INSTANT_DAMAGE, false, true))); } return; - case INVISIBILITY : - assert(!current.data.isUpgraded()); + case INVISIBILITY: + assert (!current.data.isUpgraded()); if (!current.data.isExtended()) { children.put(new Ingredient(Material.REDSTONE), new WriteablePotion(current.mat, new PotionData(current.data.getType(), true, false))); } return; - case JUMP : + case JUMP: if (!current.data.isUpgraded() && !current.data.isExtended()) { children.put(new Ingredient(Material.FERMENTED_SPIDER_EYE), new WriteablePotion(current.mat, PotionType.SLOWNESS)); children.put(new Ingredient(Material.GLOWSTONE_DUST), new WriteablePotion(current.mat, new PotionData(current.data.getType(), false, true))); children.put(new Ingredient(Material.REDSTONE), new WriteablePotion(current.mat, new PotionData(current.data.getType(), true, false))); } return; - case NIGHT_VISION : - assert(!current.data.isUpgraded()); + case NIGHT_VISION: + assert (!current.data.isUpgraded()); if (!current.data.isExtended()) { children.put(new Ingredient(Material.FERMENTED_SPIDER_EYE), new WriteablePotion(current.mat, PotionType.INVISIBILITY)); children.put(new Ingredient(Material.REDSTONE), new WriteablePotion(current.mat, new PotionData(current.data.getType(), true, false))); @@ -442,7 +334,7 @@ public class PotionGenerator { children.put(new Ingredient(Material.FERMENTED_SPIDER_EYE), new WriteablePotion(current.mat, new PotionData(PotionType.INVISIBILITY, true, false))); } return; - case POISON : + case POISON: if (!current.data.isUpgraded() && !current.data.isExtended()) { children.put(new Ingredient(Material.FERMENTED_SPIDER_EYE), new WriteablePotion(current.mat, PotionType.INSTANT_DAMAGE)); children.put(new Ingredient(Material.GLOWSTONE_DUST), new WriteablePotion(current.mat, new PotionData(current.data.getType(), false, true))); @@ -451,25 +343,25 @@ public class PotionGenerator { children.put(new Ingredient(Material.FERMENTED_SPIDER_EYE), new WriteablePotion(current.mat, new PotionData(PotionType.INSTANT_DAMAGE, false, true))); } return; - case REGEN : + case REGEN: if (!current.data.isUpgraded() && !current.data.isExtended()) { children.put(new Ingredient(Material.GLOWSTONE_DUST), new WriteablePotion(current.mat, new PotionData(current.data.getType(), false, true))); children.put(new Ingredient(Material.REDSTONE), new WriteablePotion(current.mat, new PotionData(current.data.getType(), true, false))); } return; - case SLOWNESS : - assert(!current.data.isUpgraded()); + case SLOWNESS: + assert (!current.data.isUpgraded()); if (!current.data.isExtended()) { children.put(new Ingredient(Material.REDSTONE), new WriteablePotion(current.mat, new PotionData(current.data.getType(), true, false))); } return; - case SLOW_FALLING : - assert(!current.data.isUpgraded()); + case SLOW_FALLING: + assert (!current.data.isUpgraded()); if (!current.data.isExtended()) { children.put(new Ingredient(Material.REDSTONE), new WriteablePotion(current.mat, new PotionData(current.data.getType(), true, false))); } return; - case SPEED : + case SPEED: if (!current.data.isUpgraded() && !current.data.isExtended()) { children.put(new Ingredient(Material.FERMENTED_SPIDER_EYE), new WriteablePotion(current.mat, PotionType.SLOWNESS)); children.put(new Ingredient(Material.GLOWSTONE_DUST), new WriteablePotion(current.mat, new PotionData(current.data.getType(), false, true))); @@ -478,7 +370,7 @@ public class PotionGenerator { children.put(new Ingredient(Material.FERMENTED_SPIDER_EYE), new WriteablePotion(current.mat, new PotionData(PotionType.SLOWNESS, true, false))); } return; - case STRENGTH : + case STRENGTH: if (!current.data.isUpgraded() && !current.data.isExtended()) { children.put(new Ingredient(Material.GLOWSTONE_DUST), new WriteablePotion(current.mat, new PotionData(current.data.getType(), false, true))); children.put(new Ingredient(Material.REDSTONE), new WriteablePotion(current.mat, new PotionData(current.data.getType(), true, false))); @@ -490,28 +382,28 @@ public class PotionGenerator { children.put(new Ingredient(Material.REDSTONE), new WriteablePotion(current.mat, new PotionData(current.data.getType(), true, false))); } return; - case WATER_BREATHING : - assert(!current.data.isUpgraded()); + case WATER_BREATHING: + assert (!current.data.isUpgraded()); if (!current.data.isExtended()) { children.put(new Ingredient(Material.FERMENTED_SPIDER_EYE), new WriteablePotion(current.mat, PotionType.INSTANT_DAMAGE)); children.put(new Ingredient(Material.REDSTONE), new WriteablePotion(current.mat, new PotionData(current.data.getType(), true, false))); } return; - case WEAKNESS : - assert(!current.data.isUpgraded()); + case WEAKNESS: + assert (!current.data.isUpgraded()); if (!current.data.isExtended()) { children.put(new Ingredient(Material.REDSTONE), new WriteablePotion(current.mat, new PotionData(current.data.getType(), true, false))); } return; - case LUCK : - case MUNDANE : - case THICK : - case UNCRAFTABLE : - assert(!current.data.isExtended()); - assert(!current.data.isUpgraded()); + case LUCK: + case MUNDANE: + case THICK: + case UNCRAFTABLE: + assert (!current.data.isExtended()); + assert (!current.data.isUpgraded()); return; - default : - assert(false); + default: + assert (false); break; } } @@ -608,7 +500,7 @@ public class PotionGenerator { } mcMMOPotions.put(data, children); } - + // Add all material state changes for (Entry> entry : mcMMOPotions.entrySet()) { if (entry.getKey().mat == Material.POTION) { @@ -620,4 +512,113 @@ public class PotionGenerator { } } } + + public static class Ingredient { + + public Material mat; + public int data; + public String name; + + public Ingredient(Material mat) { + this.mat = mat; + this.data = 0; + name = mat.name(); + } + + } + + public static class WriteablePotion { + + public String name; + public Material mat; + public PotionData data; + public PotionEffect effect; + public String baseName; + + public WriteablePotion(PotionData data) { + this(Material.POTION, data); + } + + public WriteablePotion(Material type, PotionData data) { + this(type, data, null, getMCName(data.getType())); + } + + public WriteablePotion(Material mat, PotionType type, PotionEffect effect, String baseName) { + this(mat, new PotionData(type, false, false), effect, baseName); + } + + public WriteablePotion(Material type, PotionData data, PotionEffect effect, String baseName) { + this.data = data; + this.effect = effect; + this.mat = type; + this.baseName = baseName; + this.name = "POTION_OF_" + baseName; + if (mat == Material.SPLASH_POTION) { + this.name = "SPLASH_" + this.name; + } + if (mat == Material.LINGERING_POTION) { + this.name = "LINGERING_" + this.name; + } + if (data.isExtended()) { + this.name += "_EXTENDED"; + } + if (data.isUpgraded()) { + this.name += "_II"; + } + } + + public WriteablePotion(PotionType type) { + this(new PotionData(type, false, false)); + } + + public WriteablePotion(Material mat, PotionType type) { + this(mat, new PotionData(type, false, false)); + } + + private static String getMCName(PotionType type) { + switch (type) { + case INSTANT_DAMAGE: + return "HARMING"; + case INSTANT_HEAL: + return "HEALING"; + case JUMP: + return "LEAPING"; + case REGEN: + return "REGENERATION"; + case SPEED: + return "SWIFTNESS"; + case UNCRAFTABLE: + return "EMPTY"; + case LUCK: + case MUNDANE: + case NIGHT_VISION: + case POISON: + case INVISIBILITY: + case SLOWNESS: + case AWKWARD: + case STRENGTH: + case THICK: + case FIRE_RESISTANCE: + case WATER: + case WATER_BREATHING: + case WEAKNESS: + case TURTLE_MASTER: + case SLOW_FALLING: + return type.name(); + default: + return ""; + } + } + + public int hashCode() { + return name.hashCode(); + } + + public boolean equals(Object obj) { + if (!(obj instanceof WriteablePotion)) { + return false; + } + return name.equals(((WriteablePotion) obj).name); + } + } } diff --git a/src/main/java/com/gmail/nossr50/skills/archery/Archery.java b/src/main/java/com/gmail/nossr50/skills/archery/Archery.java index 1daa49d8e..34856c132 100644 --- a/src/main/java/com/gmail/nossr50/skills/archery/Archery.java +++ b/src/main/java/com/gmail/nossr50/skills/archery/Archery.java @@ -25,15 +25,7 @@ public class Archery { private static Archery archery; - public static Archery getInstance() { - if(archery == null) - archery = new Archery(); - - return archery; - } - - public Archery() - { + public Archery() { List trackedEntities = new ArrayList<>(); skillShotDamageCap = AdvancedConfig.getInstance().getSkillShotDamageMax(); @@ -43,6 +35,13 @@ public class Archery { distanceXpMultiplier = mcMMO.getConfigManager().getConfigExperience().getDistanceMultiplier(); } + public static Archery getInstance() { + if (archery == null) + archery = new Archery(); + + return archery; + } + protected static void incrementTrackerValue(LivingEntity livingEntity) { for (TrackedEntity trackedEntity : trackedEntities) { if (trackedEntity.getLivingEntity().getEntityId() == livingEntity.getEntityId()) { @@ -71,7 +70,7 @@ public class Archery { * @param livingEntity The entity hit by the arrows */ public static void arrowRetrievalCheck(LivingEntity livingEntity) { - for (Iterator entityIterator = trackedEntities.iterator(); entityIterator.hasNext();) { + for (Iterator entityIterator = trackedEntities.iterator(); entityIterator.hasNext(); ) { TrackedEntity trackedEntity = entityIterator.next(); if (trackedEntity.getID() == livingEntity.getUniqueId()) { @@ -82,8 +81,7 @@ public class Archery { } } - public static double getSkillShotBonusDamage(Player player, double oldDamage) - { + public static double getSkillShotBonusDamage(Player player, double oldDamage) { double damageBonusPercent = getDamageBonusPercent(player); double newDamage = oldDamage + (oldDamage * damageBonusPercent); return Math.min(newDamage, Archery.skillShotDamageCap); diff --git a/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java b/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java index 55e949119..04e706b4c 100644 --- a/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java +++ b/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java @@ -25,21 +25,21 @@ public class ArcheryManager extends SkillManager { } public boolean canDaze(LivingEntity target) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ARCHERY_DAZE)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ARCHERY_DAZE)) return false; return target instanceof Player && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.ARCHERY_DAZE); } public boolean canSkillShot() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ARCHERY_SKILL_SHOT)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ARCHERY_SKILL_SHOT)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.ARCHERY_SKILL_SHOT); } public boolean canRetrieveArrows() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ARCHERY_ARROW_RETRIEVAL)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ARCHERY_ARROW_RETRIEVAL)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.ARCHERY_ARROW_RETRIEVAL); @@ -48,7 +48,7 @@ public class ArcheryManager extends SkillManager { /** * Calculate bonus XP awarded for Archery when hitting a far-away target. * - * @param target The {@link LivingEntity} damaged by the arrow + * @param target The {@link LivingEntity} damaged by the arrow * @param damager The {@link Entity} who shot the arrow */ public double distanceXpBonusMultiplier(LivingEntity target, Entity damager) { diff --git a/src/main/java/com/gmail/nossr50/skills/axes/Axes.java b/src/main/java/com/gmail/nossr50/skills/axes/Axes.java index 3d508e88a..b4b3ca0ef 100644 --- a/src/main/java/com/gmail/nossr50/skills/axes/Axes.java +++ b/src/main/java/com/gmail/nossr50/skills/axes/Axes.java @@ -11,14 +11,14 @@ import org.bukkit.inventory.ItemStack; public class Axes { public static double axeMasteryRankDamageMultiplier = AdvancedConfig.getInstance().getAxeMasteryRankDamageMultiplier(); - public static double criticalHitPVPModifier = AdvancedConfig.getInstance().getCriticalStrikesPVPModifier(); - public static double criticalHitPVEModifier = AdvancedConfig.getInstance().getCriticalStrikesPVEModifier(); + public static double criticalHitPVPModifier = AdvancedConfig.getInstance().getCriticalStrikesPVPModifier(); + public static double criticalHitPVEModifier = AdvancedConfig.getInstance().getCriticalStrikesPVEModifier(); - public static int impactIncreaseLevel = AdvancedConfig.getInstance().getArmorImpactIncreaseLevel(); + public static int impactIncreaseLevel = AdvancedConfig.getInstance().getArmorImpactIncreaseLevel(); //public static double impactChance = AdvancedConfig.getInstance().getImpactChance(); public static double impactMaxDurabilityModifier = AdvancedConfig.getInstance().getArmorImpactMaxDurabilityDamage() / 100D; - public static double greaterImpactBonusDamage = AdvancedConfig.getInstance().getGreaterImpactBonusDamage(); + public static double greaterImpactBonusDamage = AdvancedConfig.getInstance().getGreaterImpactBonusDamage(); //public static double greaterImpactChance = AdvancedConfig.getInstance().getGreaterImpactChance(); public static double greaterImpactKnockbackMultiplier = AdvancedConfig.getInstance().getGreaterImpactModifier(); @@ -36,11 +36,11 @@ public class Axes { /** * For every rank in Axe Mastery we add RankDamageMultiplier to get the total bonus damage from Axe Mastery + * * @param player The target player * @return The axe mastery bonus damage which will be added to their attack */ - public static double getAxeMasteryBonusDamage(Player player) - { + public static double getAxeMasteryBonusDamage(Player player) { return RankUtils.getRank(player, SubSkillType.AXES_AXE_MASTERY) * Axes.axeMasteryRankDamageMultiplier; } } diff --git a/src/main/java/com/gmail/nossr50/skills/axes/AxesManager.java b/src/main/java/com/gmail/nossr50/skills/axes/AxesManager.java index 2346faa9c..0684fa0a9 100644 --- a/src/main/java/com/gmail/nossr50/skills/axes/AxesManager.java +++ b/src/main/java/com/gmail/nossr50/skills/axes/AxesManager.java @@ -25,35 +25,35 @@ public class AxesManager extends SkillManager { } public boolean canUseAxeMastery() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_AXE_MASTERY)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_AXE_MASTERY)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.AXES_AXE_MASTERY); } public boolean canCriticalHit(LivingEntity target) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_CRITICAL_STRIKES)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_CRITICAL_STRIKES)) return false; return target.isValid() && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.AXES_CRITICAL_STRIKES); } public boolean canImpact(LivingEntity target) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_ARMOR_IMPACT)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_ARMOR_IMPACT)) return false; return target.isValid() && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.AXES_ARMOR_IMPACT) && Axes.hasArmor(target); } public boolean canGreaterImpact(LivingEntity target) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_GREATER_IMPACT)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_GREATER_IMPACT)) return false; return target.isValid() && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.AXES_GREATER_IMPACT) && !Axes.hasArmor(target); } public boolean canUseSkullSplitter(LivingEntity target) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_SKULL_SPLITTER)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_SKULL_SPLITTER)) return false; return target.isValid() && mcMMOPlayer.getAbilityMode(SuperAbilityType.SKULL_SPLITTER) && Permissions.skullSplitter(getPlayer()); @@ -99,8 +99,7 @@ public class AxesManager extends SkillManager { } damage = (damage * Axes.criticalHitPVPModifier) - damage; - } - else { + } else { damage = (damage * Axes.criticalHitPVEModifier) - damage; } diff --git a/src/main/java/com/gmail/nossr50/skills/child/FamilyTree.java b/src/main/java/com/gmail/nossr50/skills/child/FamilyTree.java index 84b36dcda..1e6d786b4 100644 --- a/src/main/java/com/gmail/nossr50/skills/child/FamilyTree.java +++ b/src/main/java/com/gmail/nossr50/skills/child/FamilyTree.java @@ -25,7 +25,7 @@ public class FamilyTree { } public static Set getParents(PrimarySkillType childSkill) { - if(childSkill == PrimarySkillType.SALVAGE) + if (childSkill == PrimarySkillType.SALVAGE) return salvageTree; else return smeltingTree; diff --git a/src/main/java/com/gmail/nossr50/skills/excavation/ExcavationManager.java b/src/main/java/com/gmail/nossr50/skills/excavation/ExcavationManager.java index b6aa956bc..9e43b5c15 100644 --- a/src/main/java/com/gmail/nossr50/skills/excavation/ExcavationManager.java +++ b/src/main/java/com/gmail/nossr50/skills/excavation/ExcavationManager.java @@ -50,18 +50,17 @@ public class ExcavationManager extends SkillManager { applyXpGain(xp, XPGainReason.PVE); } - public void printExcavationDebug(Player player, BlockState blockState) - { + public void printExcavationDebug(Player player, BlockState blockState) { if (Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.EXCAVATION_ARCHAEOLOGY)) { List treasures = Excavation.getTreasures(blockState); if (!treasures.isEmpty()) { for (ExcavationTreasure treasure : treasures) { player.sendMessage("|||||||||||||||||||||||||||||||||"); - player.sendMessage("[mcMMO DEBUG] Treasure found: ("+treasure.getDrop().getType().toString()+")"); - player.sendMessage("[mcMMO DEBUG] Drop Chance for Treasure: "+treasure.getDropChance()); - player.sendMessage("[mcMMO DEBUG] Skill Level Required: "+treasure.getDropLevel()); - player.sendMessage("[mcMMO DEBUG] XP for Treasure: "+treasure.getXp()); + player.sendMessage("[mcMMO DEBUG] Treasure found: (" + treasure.getDrop().getType().toString() + ")"); + player.sendMessage("[mcMMO DEBUG] Drop Chance for Treasure: " + treasure.getDropChance()); + player.sendMessage("[mcMMO DEBUG] Skill Level Required: " + treasure.getDropLevel()); + player.sendMessage("[mcMMO DEBUG] XP for Treasure: " + treasure.getXp()); } } else { player.sendMessage("[mcMMO DEBUG] No treasures found for this block."); diff --git a/src/main/java/com/gmail/nossr50/skills/fishing/Fishing.java b/src/main/java/com/gmail/nossr50/skills/fishing/Fishing.java index e0715069d..dedd01848 100644 --- a/src/main/java/com/gmail/nossr50/skills/fishing/Fishing.java +++ b/src/main/java/com/gmail/nossr50/skills/fishing/Fishing.java @@ -17,22 +17,14 @@ import java.util.Set; public final class Fishing { - private HashMap> enchantableCache = new HashMap<>(); - private HashMap fishingXpRewardMap; - private Set masterAnglerBiomes = BiomeAdapter.WATER_BIOMES; - private Set iceFishingBiomes = BiomeAdapter.ICE_BIOMES; + public static Fishing instance; private final long fishingRodCastCdMilliseconds; private final int overfishLimit; private final float boundingBoxSize; - - public static Fishing instance; - - public static Fishing getInstance() { - if(instance == null) - instance = new Fishing(); - - return instance; - } + private HashMap> enchantableCache = new HashMap<>(); + private HashMap fishingXpRewardMap; + private Set masterAnglerBiomes = BiomeAdapter.WATER_BIOMES; + private Set iceFishingBiomes = BiomeAdapter.ICE_BIOMES; public Fishing() { overfishLimit = mcMMO.getConfigManager().getConfigExploitPrevention().getOverfishingLimit() + 1; @@ -41,21 +33,25 @@ public final class Fishing { initFishingXPRewardMap(); } + public static Fishing getInstance() { + if (instance == null) + instance = new Fishing(); + + return instance; + } + /** * Inits the Fishing Catch -> XP Reward map */ - private void initFishingXPRewardMap() - { + private void initFishingXPRewardMap() { fishingXpRewardMap = new HashMap<>(); HashMap nameRegisterMap = mcMMO.getConfigManager().getConfigExperience().getFishingXPMap(); - for(String qualifiedName : nameRegisterMap.keySet()) - { + for (String qualifiedName : nameRegisterMap.keySet()) { Material material = Material.matchMaterial(qualifiedName); - if(material == null) - { - mcMMO.p.getLogger().info("Unable to match qualified name to item for fishing xp map: "+qualifiedName); + if (material == null) { + mcMMO.p.getLogger().info("Unable to match qualified name to item for fishing xp map: " + qualifiedName); continue; } @@ -66,8 +62,7 @@ public final class Fishing { /** * Finds the possible drops of an entity * - * @param target - * Targeted entity + * @param target Targeted entity * @return possibleDrops List of ItemStack that can be dropped */ public List findPossibleDrops(LivingEntity target) { @@ -80,8 +75,7 @@ public final class Fishing { /** * Randomly chooses a drop among the list * - * @param possibleDrops - * List of ItemStack that can be dropped + * @param possibleDrops List of ItemStack that can be dropped * @return Chosen ItemStack */ public ItemStack chooseDrop(List possibleDrops) { @@ -115,8 +109,7 @@ public final class Fishing { return iceFishingBiomes; } - public int getFishXPValue(Material material) - { + public int getFishXPValue(Material material) { return fishingXpRewardMap.get(material); } diff --git a/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java b/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java index f33a9ef75..7e888b4d1 100644 --- a/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java @@ -66,21 +66,18 @@ public class FishingManager extends SkillManager { return getSkillLevel() >= RankUtils.getUnlockLevel(SubSkillType.FISHING_MASTER_ANGLER) && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.FISHING_MASTER_ANGLER); } - public void setFishingRodCastTimestamp() - { + public void setFishingRodCastTimestamp() { long currentTime = System.currentTimeMillis(); //Only track spam casting if the fishing hook is fresh - if(currentTime > fishHookSpawnTimestamp + 1000) + if (currentTime > fishHookSpawnTimestamp + 1000) return; - if(currentTime < fishingRodCastTimestamp + Fishing.getInstance().getFishingRodCastCdMilliseconds()) - { + if (currentTime < fishingRodCastTimestamp + Fishing.getInstance().getFishingRodCastCdMilliseconds()) { getPlayer().setFoodLevel(Math.max(getPlayer().getFoodLevel() - 1, 0)); getPlayer().getInventory().getItemInMainHand().setDurability((short) (getPlayer().getInventory().getItemInMainHand().getDurability() + 5)); getPlayer().updateInventory(); - if(lastWarnedExhaust + (1000) < currentTime) - { + if (lastWarnedExhaust + (1000) < currentTime) { getPlayer().sendMessage(LocaleLoader.getString("Fishing.Exhausting")); lastWarnedExhaust = currentTime; SoundManager.sendSound(getPlayer(), getPlayer().getLocation(), SoundType.TIRED); @@ -90,9 +87,8 @@ public class FishingManager extends SkillManager { fishingRodCastTimestamp = System.currentTimeMillis(); } - public void setFishHookReference(FishHook fishHook) - { - if(fishHook.getMetadata(mcMMO.FISH_HOOK_REF_METAKEY).size() > 0) + public void setFishHookReference(FishHook fishHook) { + if (fishHook.getMetadata(mcMMO.FISH_HOOK_REF_METAKEY).size() > 0) return; fishHook.setMetadata(mcMMO.FISH_HOOK_REF_METAKEY, mcMMO.metadataValue); @@ -100,14 +96,12 @@ public class FishingManager extends SkillManager { fishingRodCastTimestamp = System.currentTimeMillis(); } - public boolean isFishingTooOften() - { + public boolean isFishingTooOften() { long currentTime = System.currentTimeMillis(); long fishHookSpawnCD = fishHookSpawnTimestamp + 1000; boolean hasFished = (currentTime < fishHookSpawnCD); - if(hasFished && (lastWarned + (1000) < currentTime)) - { + if (hasFished && (lastWarned + (1000) < currentTime)) { getPlayer().sendMessage(LocaleLoader.getString("Fishing.Scared")); lastWarned = System.currentTimeMillis(); } @@ -129,32 +123,27 @@ public class FishingManager extends SkillManager { boolean sameTarget = lastFishingBoundingBox != null && lastFishingBoundingBox.overlaps(newCastBoundingBox); - if(sameTarget) + if (sameTarget) fishCaughtCounter++; else fishCaughtCounter = 1; - if(fishCaughtCounter + 1 == overfishLimit) - { + if (fishCaughtCounter + 1 == overfishLimit) { getPlayer().sendMessage(LocaleLoader.getString("Fishing.LowResources")); } //If the new bounding box does not intersect with the old one, then update our bounding box reference - if(!sameTarget) + if (!sameTarget) lastFishingBoundingBox = newCastBoundingBox; - if(sameTarget && fishCaughtCounter >= overfishLimit) - { + if (sameTarget && fishCaughtCounter >= overfishLimit) { overFishCount++; } else - overFishCount=0; + overFishCount = 0; - if(overFishCount == 2) - { - for(Player player : Bukkit.getOnlinePlayers()) - { - if(player.isOp() || Permissions.adminChat(player)) - { + if (overFishCount == 2) { + for (Player player : Bukkit.getOnlinePlayers()) { + if (player.isOp() || Permissions.adminChat(player)) { player.sendMessage(LocaleLoader.getString("Fishing.OverFishingDetected", getPlayer().getDisplayName())); } } @@ -225,7 +214,6 @@ public class FishingManager extends SkillManager { * Handle the Fisherman's Diet ability * * @param eventFoodLevel The initial change in hunger from the event - * * @return the modified change in hunger for the event */ public int handleFishermanDiet(int eventFoodLevel) { @@ -268,8 +256,7 @@ public class FishingManager extends SkillManager { hook.setBiteChance(Math.min(biteChance, 1.0)); } - public boolean isMagicHunterEnabled() - { + public boolean isMagicHunterEnabled() { return RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.FISHING_MAGIC_HUNTER) && RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.FISHING_TREASURE_HUNTER) && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.FISHING_TREASURE_HUNTER); @@ -305,8 +292,7 @@ public class FishingManager extends SkillManager { if (!event.isCancelled()) { treasureDrop = event.getTreasure(); treasureXp = event.getXp(); - } - else { + } else { treasureDrop = null; treasureXp = 0; } @@ -340,7 +326,6 @@ public class FishingManager extends SkillManager { * Handle the vanilla XP boost for Fishing * * @param experience The amount of experience initially awarded by the event - * * @return the modified event damage */ public int addInnerPeaceVanillaXPBoost(int experience) { @@ -397,8 +382,7 @@ public class FishingManager extends SkillManager { if (FishingTreasureConfig.getInstance().getInventoryStealStacks()) { inventory.setItem(slot, null); - } - else { + } else { inventory.setItem(slot, (drop.getAmount() > 1) ? new ItemStack(drop.getType(), drop.getAmount() - 1) : null); drop.setAmount(1); } @@ -451,8 +435,7 @@ public class FishingManager extends SkillManager { if (getPlayer().getInventory().getItemInMainHand().getType() == Material.FISHING_ROD) { luck = getPlayer().getInventory().getItemInMainHand().getEnchantmentLevel(Enchantment.LUCK); - } - else { + } else { // We know something was caught, so if the rod wasn't in the main hand it must be in the offhand luck = getPlayer().getInventory().getItemInOffHand().getEnchantmentLevel(Enchantment.LUCK); } @@ -508,7 +491,6 @@ public class FishingManager extends SkillManager { * Process the Magic Hunter ability * * @param treasureDrop The {@link ItemStack} to enchant - * * @return true if the item has been enchanted */ private Map handleMagicHunter(ItemStack treasureDrop) { diff --git a/src/main/java/com/gmail/nossr50/skills/herbalism/Herbalism.java b/src/main/java/com/gmail/nossr50/skills/herbalism/Herbalism.java index a51cab404..41b974441 100644 --- a/src/main/java/com/gmail/nossr50/skills/herbalism/Herbalism.java +++ b/src/main/java/com/gmail/nossr50/skills/herbalism/Herbalism.java @@ -15,8 +15,7 @@ public class Herbalism { /** * Convert blocks affected by the Green Thumb & Green Terra abilities. * - * @param blockState - * The {@link BlockState} to check ability activation for + * @param blockState The {@link BlockState} to check ability activation for * @return true if the ability was successful, false otherwise */ protected static boolean convertGreenTerraBlocks(BlockState blockState) { @@ -29,16 +28,16 @@ public class Herbalism { blockState.setType(Material.MOSSY_STONE_BRICKS); return true; - case DIRT : - case GRASS_PATH : + case DIRT: + case GRASS_PATH: blockState.setType(Material.GRASS_BLOCK); return true; - case COBBLESTONE : + case COBBLESTONE: blockState.setType(Material.MOSSY_COBBLESTONE); return true; - default : + default: return false; } } @@ -62,15 +61,14 @@ public class Herbalism { if (mcMMO.getPlaceStore().isTrue(target)) mcMMO.getPlaceStore().setFalse(target); - else - { + else { dropAmount++; - if(herbalismManager.checkDoubleDrop(target.getState())) + if (herbalismManager.checkDoubleDrop(target.getState())) BlockUtils.markDropsAsBonus(target.getState(), triple); } - for (BlockFace blockFace : new BlockFace[] { BlockFace.UP, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST ,BlockFace.WEST}) + for (BlockFace blockFace : new BlockFace[]{BlockFace.UP, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}) dropAmount += calculateChorusPlantDropsRecursive(target.getRelative(blockFace, 1), traversed, triple, herbalismManager); return dropAmount; @@ -80,8 +78,7 @@ public class Herbalism { * Calculate the drop amounts for multi block plants based on the blocks * relative to them. * - * @param blockState - * The {@link BlockState} of the bottom block of the plant + * @param blockState The {@link BlockState} of the bottom block of the plant * @return the number of bonus drops to award from the blocks in this plant */ protected static int countAndMarkDoubleDropsMultiBlockPlant(BlockState blockState, boolean triple, HerbalismManager herbalismManager) { @@ -109,7 +106,7 @@ public class Herbalism { } else { dropAmount++; - if(herbalismManager.checkDoubleDrop(relativeBlock.getState())) + if (herbalismManager.checkDoubleDrop(relativeBlock.getState())) BlockUtils.markDropsAsBonus(relativeBlock.getState(), triple); } } @@ -122,8 +119,7 @@ public class Herbalism { * Calculate the drop amounts for kelp plants based on the blocks * relative to them. * - * @param blockState - * The {@link BlockState} of the bottom block of the plant + * @param blockState The {@link BlockState} of the bottom block of the plant * @return the number of bonus drops to award from the blocks in this plant */ protected static int countAndMarkDoubleDropsKelp(BlockState blockState, boolean triple, HerbalismManager herbalismManager) { @@ -136,12 +132,12 @@ public class Herbalism { for (int y = 1; y < kelpMaxHeight; y++) { Block relativeUpBlock = block.getRelative(BlockFace.UP, y); - if(!isKelp(relativeUpBlock)) + if (!isKelp(relativeUpBlock)) break; amount += 1; - if(herbalismManager.checkDoubleDrop(relativeUpBlock.getState())) + if (herbalismManager.checkDoubleDrop(relativeUpBlock.getState())) BlockUtils.markDropsAsBonus(relativeUpBlock.getState(), triple); } @@ -169,19 +165,18 @@ public class Herbalism { /** * Convert blocks affected by the Green Thumb & Green Terra abilities. * - * @param blockState - * The {@link BlockState} to check ability activation for + * @param blockState The {@link BlockState} to check ability activation for * @return true if the ability was successful, false otherwise */ protected static boolean convertShroomThumb(BlockState blockState) { switch (blockState.getType()) { - case DIRT : + case DIRT: case GRASS_BLOCK: - case GRASS_PATH : + case GRASS_PATH: blockState.setType(Material.MYCELIUM); return true; - default : + default: return false; } } @@ -189,8 +184,7 @@ public class Herbalism { /** * Check if the block has a recently grown crop from Green Thumb * - * @param blockState - * The {@link BlockState} to check green thumb regrown for + * @param blockState The {@link BlockState} to check green thumb regrown for * @return true if the block is recently regrown, false otherwise */ public static boolean isRecentlyRegrown(BlockState blockState) { diff --git a/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java b/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java index 5f789b492..5b08646f1 100644 --- a/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java +++ b/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java @@ -42,7 +42,7 @@ public class HerbalismManager extends SkillManager { } public boolean canGreenThumbBlock(BlockState blockState) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.HERBALISM_GREEN_THUMB)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.HERBALISM_GREEN_THUMB)) return false; Player player = getPlayer(); @@ -52,7 +52,7 @@ public class HerbalismManager extends SkillManager { } public boolean canUseShroomThumb(BlockState blockState) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.HERBALISM_SHROOM_THUMB)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.HERBALISM_SHROOM_THUMB)) return false; Player player = getPlayer(); @@ -63,7 +63,7 @@ public class HerbalismManager extends SkillManager { } public boolean canUseHylianLuck() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.HERBALISM_HYLIAN_LUCK)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.HERBALISM_HYLIAN_LUCK)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.HERBALISM_HYLIAN_LUCK); @@ -148,26 +148,26 @@ public class HerbalismManager extends SkillManager { // } // } // else { - xp = ExperienceConfig.getInstance().getXp(skill, blockState.getType()); + xp = ExperienceConfig.getInstance().getXp(skill, blockState.getType()); - if (!oneBlockPlant) { - //Kelp is actually two blocks mixed together - if(material == Material.KELP_PLANT || material == Material.KELP) { - amount = Herbalism.countAndMarkDoubleDropsKelp(blockState, greenTerra,this); - } else { - amount = Herbalism.countAndMarkDoubleDropsMultiBlockPlant(blockState, greenTerra, this); - } - - xp *= amount; + if (!oneBlockPlant) { + //Kelp is actually two blocks mixed together + if (material == Material.KELP_PLANT || material == Material.KELP) { + amount = Herbalism.countAndMarkDoubleDropsKelp(blockState, greenTerra, this); } else { - /* MARK SINGLE BLOCK CROP FOR DOUBLE DROP */ - if(checkDoubleDrop(blockState)) - BlockUtils.markDropsAsBonus(blockState, greenTerra); + amount = Herbalism.countAndMarkDoubleDropsMultiBlockPlant(blockState, greenTerra, this); } - if (Permissions.greenThumbPlant(player, material)) { - processGreenThumbPlants(blockState, greenTerra); - } + xp *= amount; + } else { + /* MARK SINGLE BLOCK CROP FOR DOUBLE DROP */ + if (checkDoubleDrop(blockState)) + BlockUtils.markDropsAsBonus(blockState, greenTerra); + } + + if (Permissions.greenThumbPlant(player, material)) { + processGreenThumbPlants(blockState, greenTerra); + } //} mod config close applyXpGain(xp, XPGainReason.PVE); @@ -181,11 +181,11 @@ public class HerbalismManager extends SkillManager { /** * Check for success on herbalism double drops + * * @param blockState target block state * @return true if double drop succeeds */ - public boolean checkDoubleDrop(BlockState blockState) - { + public boolean checkDoubleDrop(BlockState blockState) { return BlockUtils.checkDoubleDrops(getPlayer(), blockState, SubSkillType.HERBALISM_DOUBLE_DROPS); } @@ -252,7 +252,7 @@ public class HerbalismManager extends SkillManager { public boolean processShroomThumb(BlockState blockState) { Player player = getPlayer(); PlayerInventory playerInventory = player.getInventory(); - + if (!playerInventory.contains(Material.BROWN_MUSHROOM, 1)) { NotificationManager.sendPlayerInformation(player, NotificationType.REQUIREMENTS_NOT_MET, "Skills.NeedMore", StringUtils.getPrettyItemString(Material.BROWN_MUSHROOM)); return false; @@ -328,8 +328,7 @@ public class HerbalismManager extends SkillManager { return; } - if(!ItemUtils.isHoe(getPlayer().getInventory().getItemInMainHand())) - { + if (!ItemUtils.isHoe(getPlayer().getInventory().getItemInMainHand())) { if (!playerInventory.containsAtLeast(seedStack, 1)) { return; } @@ -355,8 +354,7 @@ public class HerbalismManager extends SkillManager { if (greenTerra) { crops.setAge(3); - } - else { + } else { crops.setAge(greenThumbStage); } break; @@ -366,21 +364,18 @@ public class HerbalismManager extends SkillManager { if (greenTerra || greenThumbStage > 2) { crops.setAge(2); - } - else if (greenThumbStage == 2) { + } else if (greenThumbStage == 2) { crops.setAge(1); - } - else { + } else { crops.setAge(0); } - break; + break; case COCOA: if (greenTerra || getGreenThumbStage() > 1) { crops.setAge(1); - } - else { + } else { crops.setAge(0); } break; diff --git a/src/main/java/com/gmail/nossr50/skills/mining/BlastMining.java b/src/main/java/com/gmail/nossr50/skills/mining/BlastMining.java index a299bb0be..ed7927404 100644 --- a/src/main/java/com/gmail/nossr50/skills/mining/BlastMining.java +++ b/src/main/java/com/gmail/nossr50/skills/mining/BlastMining.java @@ -46,13 +46,11 @@ public class BlastMining { } - public static double getBlastDamageDecrease(int rank) { return AdvancedConfig.getInstance().getBlastDamageDecrease(rank); } - public static int getDemolitionExpertUnlockLevel() { /*List tierList = Arrays.asList(Tier.values()); for (Tier tier : tierList) { @@ -63,10 +61,9 @@ public class BlastMining { return tier == Tier.EIGHT ? tier.getLevel() : tierList.get(tierList.indexOf(tier) - 1).getLevel(); }*/ - for(int i = 0; i < SubSkillType.MINING_BLAST_MINING.getNumRanks()-1; i++) - { - if(getBlastDamageDecrease(i+1) > 0) - return RankUtils.getRankUnlockLevel(SubSkillType.MINING_BLAST_MINING, i+1); + for (int i = 0; i < SubSkillType.MINING_BLAST_MINING.getNumRanks() - 1; i++) { + if (getBlastDamageDecrease(i + 1) > 0) + return RankUtils.getRankUnlockLevel(SubSkillType.MINING_BLAST_MINING, i + 1); } return 0; @@ -82,10 +79,9 @@ public class BlastMining { return tier == Tier.EIGHT ? tier.getLevel() : tierList.get(tierList.indexOf(tier) - 1).getLevel(); }*/ - for(int i = 0; i < SubSkillType.MINING_BLAST_MINING.getNumRanks()-1; i++) - { - if(getBlastRadiusModifier(i+1) > 0) - return RankUtils.getRankUnlockLevel(SubSkillType.MINING_BLAST_MINING, i+1); + for (int i = 0; i < SubSkillType.MINING_BLAST_MINING.getNumRanks() - 1; i++) { + if (getBlastRadiusModifier(i + 1) > 0) + return RankUtils.getRankUnlockLevel(SubSkillType.MINING_BLAST_MINING, i + 1); } return 0; @@ -103,12 +99,11 @@ public class BlastMining { return false; } - if(UserManager.getPlayer(defender) == null) - { + if (UserManager.getPlayer(defender) == null) { return false; } - MiningManager miningManager = UserManager.getPlayer(defender).getMiningManager(); + MiningManager miningManager = UserManager.getPlayer(defender).getMiningManager(); if (!miningManager.canUseDemolitionsExpertise()) { return false; diff --git a/src/main/java/com/gmail/nossr50/skills/mining/Mining.java b/src/main/java/com/gmail/nossr50/skills/mining/Mining.java index 1af85a189..51672ea9e 100644 --- a/src/main/java/com/gmail/nossr50/skills/mining/Mining.java +++ b/src/main/java/com/gmail/nossr50/skills/mining/Mining.java @@ -13,37 +13,19 @@ import java.util.List; public class Mining { - private List detonators; private static Mining instance; - - public static Mining getInstance() { - if(instance == null) - instance = new Mining(); - - return instance; - } + private List detonators; public Mining() { //Init detonators this.detonators = ItemUtils.matchMaterials(mcMMO.getConfigManager().getConfigMining().getDetonators()); } - /** - * Retrieve a list of Blast Mining detonator types - * @return blast mining detonator materials - */ - public List getDetonators() { - return detonators; - } + public static Mining getInstance() { + if (instance == null) + instance = new Mining(); - /** - * Check if an itemStack is a valid blast mining detonator - * @param itemStack target itemstack - * @return true if valid blast mining detonator - */ - public Boolean isDetonator(ItemStack itemStack) - { - return getDetonators().contains(itemStack.getType()); + return instance; } /** @@ -201,4 +183,23 @@ public class Mining { }*/ } } + + /** + * Retrieve a list of Blast Mining detonator types + * + * @return blast mining detonator materials + */ + public List getDetonators() { + return detonators; + } + + /** + * Check if an itemStack is a valid blast mining detonator + * + * @param itemStack target itemstack + * @return true if valid blast mining detonator + */ + public Boolean isDetonator(ItemStack itemStack) { + return getDetonators().contains(itemStack.getType()); + } } diff --git a/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java b/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java index eea28e648..f3069db20 100644 --- a/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java +++ b/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java @@ -35,8 +35,20 @@ public class MiningManager extends SkillManager { super(mcMMOPlayer, PrimarySkillType.MINING); } + public static double getOreBonus(int rank) { + return AdvancedConfig.getInstance().getOreBonus(rank); + } + + public static double getDebrisReduction(int rank) { + return AdvancedConfig.getInstance().getDebrisReduction(rank); + } + + public static int getDropMultiplier(int rank) { + return AdvancedConfig.getInstance().getDropMultiplier(rank); + } + public boolean canUseDemolitionsExpertise() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.MINING_DEMOLITIONS_EXPERTISE)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.MINING_DEMOLITIONS_EXPERTISE)) return false; return getSkillLevel() >= BlastMining.getDemolitionExpertUnlockLevel() && Permissions.demolitionsExpertise(getPlayer()); @@ -56,7 +68,7 @@ public class MiningManager extends SkillManager { } public boolean canUseBiggerBombs() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.MINING_BIGGER_BOMBS)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.MINING_BIGGER_BOMBS)) return false; return getSkillLevel() >= BlastMining.getBiggerBombsUnlockLevel() && Permissions.biggerBombs(getPlayer()); @@ -83,13 +95,13 @@ public class MiningManager extends SkillManager { } //if ((mcMMO.getModManager().isCustomMiningBlock(blockState) && !mcMMO.getModManager().getBlock(blockState).isDoubleDropEnabled()) || !MainConfig.getInstance().getDoubleDropsEnabled(skill, material)) { - if(!MainConfig.getInstance().getDoubleDropsEnabled(skill, material)) { + if (!MainConfig.getInstance().getDoubleDropsEnabled(skill, material)) { return; } boolean silkTouch = player.getInventory().getItemInMainHand().containsEnchantment(Enchantment.SILK_TOUCH); - if(silkTouch && !AdvancedConfig.getInstance().getDoubleDropSilkTouchEnabled()) + if (silkTouch && !AdvancedConfig.getInstance().getDoubleDropSilkTouchEnabled()) return; //TODO: Make this readable @@ -128,7 +140,7 @@ public class MiningManager extends SkillManager { /** * Handler for explosion drops and XP gain. * - * @param yield The % of blocks to drop + * @param yield The % of blocks to drop * @param blockList The list of blocks to drop */ public void blastMiningDropProcessing(float yield, List blockList) { @@ -147,8 +159,7 @@ public class MiningManager extends SkillManager { if (BlockUtils.isOre(blockState)) { ores.add(blockState); - } - else { + } else { debris.add(blockState); } } @@ -212,14 +223,6 @@ public class MiningManager extends SkillManager { return getOreBonus(getBlastMiningTier()); } - public static double getOreBonus(int rank) { - return AdvancedConfig.getInstance().getOreBonus(rank); - } - - public static double getDebrisReduction(int rank) { - return AdvancedConfig.getInstance().getDebrisReduction(rank); - } - /** * Gets the Blast Mining tier * @@ -229,10 +232,6 @@ public class MiningManager extends SkillManager { return getDebrisReduction(getBlastMiningTier()); } - public static int getDropMultiplier(int rank) { - return AdvancedConfig.getInstance().getDropMultiplier(rank); - } - /** * Gets the Blast Mining tier * diff --git a/src/main/java/com/gmail/nossr50/skills/repair/Repair.java b/src/main/java/com/gmail/nossr50/skills/repair/Repair.java index 392712fe5..6917283c9 100644 --- a/src/main/java/com/gmail/nossr50/skills/repair/Repair.java +++ b/src/main/java/com/gmail/nossr50/skills/repair/Repair.java @@ -13,8 +13,7 @@ public class Repair { anvilMaterial = mcMMO.getConfigManager().getConfigRepair().getRepairGeneral().getRepairAnvilMaterial(); //TODO: Replace this horrid shit - if(mcMMO.isRetroModeEnabled()) - { + if (mcMMO.isRetroModeEnabled()) { repairMasteryMaxBonus = mcMMO.getConfigManager().getConfigRepair().getRepairSubSkills().getRepairMastery().getSettings().getRetro().getMaxBonusPercentage(); repairMasteryMaxBonusLevel = mcMMO.getConfigManager().getConfigRepair().getRepairSubSkills().getRepairMastery().getSettings().getRetro().getMaxBonusLevel(); } else { @@ -23,9 +22,8 @@ public class Repair { } } - public static Repair getInstance() - { - if(instance == null) + public static Repair getInstance() { + if (instance == null) instance = new Repair(); return instance; diff --git a/src/main/java/com/gmail/nossr50/skills/repair/RepairManager.java b/src/main/java/com/gmail/nossr50/skills/repair/RepairManager.java index 9c2c9405e..3761bdb5e 100644 --- a/src/main/java/com/gmail/nossr50/skills/repair/RepairManager.java +++ b/src/main/java/com/gmail/nossr50/skills/repair/RepairManager.java @@ -34,7 +34,7 @@ import java.util.Map.Entry; public class RepairManager extends SkillManager { private boolean placedAnvil; - private int lastClick; + private int lastClick; public RepairManager(McMMOPlayer mcMMOPlayer) { super(mcMMOPlayer, PrimarySkillType.REPAIR); @@ -62,7 +62,6 @@ public class RepairManager extends SkillManager { } - public void handleRepair(ItemStack item) { Player player = getPlayer(); Repairable repairable = mcMMO.getRepairableManager().getRepairable(item.getType()); @@ -97,14 +96,10 @@ public class RepairManager extends SkillManager { boolean foundNonBasicMaterial = false; //Find the first compatible repair material - for(Material repairMaterialCandidate : repairable.getRepairMaterials()) - { - for(ItemStack is : player.getInventory().getContents()) - { - if(is.getType() == repairMaterialCandidate) - { - if(is.getItemMeta().getLore().isEmpty()) - { + for (Material repairMaterialCandidate : repairable.getRepairMaterials()) { + for (ItemStack is : player.getInventory().getContents()) { + if (is.getType() == repairMaterialCandidate) { + if (is.getItemMeta().getLore().isEmpty()) { repairMaterial = repairMaterialCandidate; break; } else { @@ -115,8 +110,7 @@ public class RepairManager extends SkillManager { } /* Abort the repair if no compatible basic repairing item found */ - if(repairMaterial == null && foundNonBasicMaterial == true) - { + if (repairMaterial == null && foundNonBasicMaterial == true) { player.sendMessage(LocaleLoader.getString("Repair.NoBasicRepairMatsFound")); return; } @@ -286,7 +280,7 @@ public class RepairManager extends SkillManager { /** * Computes repair bonuses. * - * @param durability The durability of the item being repaired + * @param durability The durability of the item being repaired * @param repairAmount The base amount of durability repaired to the item * @return The final amount of durability repaired to the item */ @@ -320,7 +314,7 @@ public class RepairManager extends SkillManager { * @return true if bonus granted, false otherwise */ private boolean checkPlayerProcRepair() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.REPAIR_SUPER_REPAIR)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.REPAIR_SUPER_REPAIR)) return false; if (RandomChanceUtil.isActivationSuccessful(SkillActivationType.RANDOM_LINEAR_100_SCALE_WITH_CAP, SubSkillType.REPAIR_SUPER_REPAIR, getPlayer())) { @@ -372,8 +366,7 @@ public class RepairManager extends SkillManager { item.addUnsafeEnchantment(enchantment, enchantLevel - 1); downgraded = true; } - } - else { + } else { item.removeEnchantment(enchantment); } } @@ -382,11 +375,9 @@ public class RepairManager extends SkillManager { if (newEnchants.isEmpty()) { NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE_FAILED, "Repair.Arcane.Fail"); - } - else if (downgraded || newEnchants.size() < enchants.size()) { + } else if (downgraded || newEnchants.size() < enchants.size()) { NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE_FAILED, "Repair.Arcane.Downgrade"); - } - else { + } else { NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Repair.Arcane.Perfect"); } } diff --git a/src/main/java/com/gmail/nossr50/skills/repair/repairables/RepairableManager.java b/src/main/java/com/gmail/nossr50/skills/repair/repairables/RepairableManager.java index b4aa43c06..0d4a41528 100644 --- a/src/main/java/com/gmail/nossr50/skills/repair/repairables/RepairableManager.java +++ b/src/main/java/com/gmail/nossr50/skills/repair/repairables/RepairableManager.java @@ -10,16 +10,16 @@ import java.util.List; public class RepairableManager implements Unload { private HashMap repairables; - @Override - public void unload() { - repairables.clear(); - } - public RepairableManager(List repairablesCollection) { this.repairables = new HashMap<>(repairablesCollection.size()); registerRepairables(repairablesCollection); } + @Override + public void unload() { + repairables.clear(); + } + public void registerRepairable(Repairable repairable) { Material item = repairable.getItemMaterial(); repairables.put(item, repairable); diff --git a/src/main/java/com/gmail/nossr50/skills/salvage/SalvageManager.java b/src/main/java/com/gmail/nossr50/skills/salvage/SalvageManager.java index 151b31d85..acb4447ba 100644 --- a/src/main/java/com/gmail/nossr50/skills/salvage/SalvageManager.java +++ b/src/main/java/com/gmail/nossr50/skills/salvage/SalvageManager.java @@ -32,7 +32,7 @@ import java.util.Map.Entry; public class SalvageManager extends SkillManager { private boolean placedAnvil; - private int lastClick; + private int lastClick; public SalvageManager(McMMOPlayer mcMMOPlayer) { super(mcMMOPlayer, PrimarySkillType.SALVAGE); @@ -179,7 +179,7 @@ public class SalvageManager extends SkillManager { }*/ public double getExtractFullEnchantChance() { - if(Permissions.hasSalvageEnchantBypassPerk(getPlayer())) + if (Permissions.hasSalvageEnchantBypassPerk(getPlayer())) return 100.0D; return AdvancedConfig.getInstance().getArcaneSalvageExtractFullEnchantsChance(getArcaneSalvageRank()); @@ -208,8 +208,7 @@ public class SalvageManager extends SkillManager { || Permissions.hasSalvageEnchantBypassPerk(player) || RandomChanceUtil.checkRandomChanceExecutionSuccess(new RandomChanceSkillStatic(getExtractFullEnchantChance(), getPlayer(), SubSkillType.SALVAGE_ARCANE_SALVAGE))) { enchantMeta.addStoredEnchant(enchant.getKey(), enchant.getValue(), true); - } - else if (enchant.getValue() > 1 + } else if (enchant.getValue() > 1 && Salvage.arcaneSalvageDowngrades && RandomChanceUtil.checkRandomChanceExecutionSuccess(new RandomChanceSkillStatic(getExtractPartialEnchantChance(), getPlayer(), SubSkillType.SALVAGE_ARCANE_SALVAGE))) { enchantMeta.addStoredEnchant(enchant.getKey(), enchant.getValue() - 1, true); @@ -219,12 +218,10 @@ public class SalvageManager extends SkillManager { } } - if(failedAllEnchants(arcaneFailureCount, enchants.entrySet().size())) - { + if (failedAllEnchants(arcaneFailureCount, enchants.entrySet().size())) { NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE_FAILED, "Salvage.Skills.ArcaneFailed"); return null; - } else if(downgraded) - { + } else if (downgraded) { NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE_FAILED, "Salvage.Skills.ArcanePartial"); } @@ -238,8 +235,8 @@ public class SalvageManager extends SkillManager { /** * Check if the player has tried to use an Anvil before. - * @param actualize * + * @param actualize * @return true if the player has confirmed using an Anvil */ public boolean checkConfirmation(boolean actualize) { diff --git a/src/main/java/com/gmail/nossr50/skills/salvage/salvageables/Salvageable.java b/src/main/java/com/gmail/nossr50/skills/salvage/salvageables/Salvageable.java index 16a9886e2..495b4a916 100644 --- a/src/main/java/com/gmail/nossr50/skills/salvage/salvageables/Salvageable.java +++ b/src/main/java/com/gmail/nossr50/skills/salvage/salvageables/Salvageable.java @@ -17,18 +17,15 @@ public class Salvageable { private final ItemMaterialCategory salvageItemMaterialCategory; private final double xpMultiplier; - public Salvageable(String itemRegisterKey, String salvagedMaterialRegisterKey) - { + public Salvageable(String itemRegisterKey, String salvagedMaterialRegisterKey) { this(Material.matchMaterial(itemRegisterKey), Material.matchMaterial(salvagedMaterialRegisterKey), 0, 1); } - public Salvageable(String itemRegisterKey, String salvagedMaterialRegisterKey, int minimumLevel, int maximumQuantity) - { + public Salvageable(String itemRegisterKey, String salvagedMaterialRegisterKey, int minimumLevel, int maximumQuantity) { this(Material.matchMaterial(itemRegisterKey), Material.matchMaterial(salvagedMaterialRegisterKey), minimumLevel, maximumQuantity); } - public Salvageable(Material itemMaterial, Material salvagedItemMaterial, int minimumLevel, int maximumQuantity) - { + public Salvageable(Material itemMaterial, Material salvagedItemMaterial, int minimumLevel, int maximumQuantity) { this.itemMaterial = itemMaterial; this.salvagedItemMaterial = salvagedItemMaterial; this.salvageItemType = ItemUtils.determineItemType(itemMaterial); diff --git a/src/main/java/com/gmail/nossr50/skills/salvage/salvageables/SalvageableManager.java b/src/main/java/com/gmail/nossr50/skills/salvage/salvageables/SalvageableManager.java index 7554dad27..b4a026e65 100644 --- a/src/main/java/com/gmail/nossr50/skills/salvage/salvageables/SalvageableManager.java +++ b/src/main/java/com/gmail/nossr50/skills/salvage/salvageables/SalvageableManager.java @@ -15,16 +15,16 @@ public class SalvageableManager implements Unload { this(55); }*/ - @Override - public void unload() { - salvageables.clear(); - } - public SalvageableManager(List salvageablesCollection) { this.salvageables = new HashMap<>(salvageablesCollection.size()); registerSalvageables(salvageablesCollection); } + @Override + public void unload() { + salvageables.clear(); + } + public void registerSalvageable(Salvageable salvageable) { Material item = salvageable.getItemMaterial(); salvageables.put(item, salvageable); diff --git a/src/main/java/com/gmail/nossr50/skills/smelting/Smelting.java b/src/main/java/com/gmail/nossr50/skills/smelting/Smelting.java index 21b6d06fc..0aa00b58d 100644 --- a/src/main/java/com/gmail/nossr50/skills/smelting/Smelting.java +++ b/src/main/java/com/gmail/nossr50/skills/smelting/Smelting.java @@ -9,8 +9,7 @@ import org.bukkit.inventory.ItemStack; public class Smelting { - public static int getRank(Player player) - { + public static int getRank(Player player) { return RankUtils.getRank(player, SubSkillType.SMELTING_UNDERSTANDING_THE_ART); } diff --git a/src/main/java/com/gmail/nossr50/skills/smelting/SmeltingManager.java b/src/main/java/com/gmail/nossr50/skills/smelting/SmeltingManager.java index f5991e00f..3728347a8 100644 --- a/src/main/java/com/gmail/nossr50/skills/smelting/SmeltingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/smelting/SmeltingManager.java @@ -93,10 +93,8 @@ public class SmeltingManager extends SkillManager { return burnTime * getFuelEfficiencyMultiplier(); } - public int getFuelEfficiencyMultiplier() - { - switch(RankUtils.getRank(getPlayer(), SubSkillType.SMELTING_FUEL_EFFICIENCY)) - { + public int getFuelEfficiencyMultiplier() { + switch (RankUtils.getRank(getPlayer(), SubSkillType.SMELTING_FUEL_EFFICIENCY)) { case 1: return 2; case 2: diff --git a/src/main/java/com/gmail/nossr50/skills/swords/SwordsManager.java b/src/main/java/com/gmail/nossr50/skills/swords/SwordsManager.java index 13d5cc251..f1a24187d 100644 --- a/src/main/java/com/gmail/nossr50/skills/swords/SwordsManager.java +++ b/src/main/java/com/gmail/nossr50/skills/swords/SwordsManager.java @@ -42,14 +42,14 @@ public class SwordsManager extends SkillManager { } public boolean canUseCounterAttack(Entity target) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.SWORDS_COUNTER_ATTACK)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.SWORDS_COUNTER_ATTACK)) return false; return target instanceof LivingEntity && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.SWORDS_COUNTER_ATTACK); } public boolean canUseSerratedStrike() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.SWORDS_SERRATED_STRIKES)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.SWORDS_SERRATED_STRIKES)) return false; return mcMMOPlayer.getAbilityMode(SuperAbilityType.SERRATED_STRIKES); @@ -67,11 +67,11 @@ public class SwordsManager extends SkillManager { Player defender = (Player) target; //Don't start or add to a bleed if they are blocking - if(defender.isBlocking()) + if (defender.isBlocking()) return; if (NotificationManager.doesPlayerUseNotifications(defender)) { - if(!BleedTimerTask.isBleeding(defender)) + if (!BleedTimerTask.isBleeding(defender)) NotificationManager.sendPlayerInformation(defender, NotificationType.SUBSKILL_MESSAGE, "Swords.Combat.Bleeding.Started"); } } @@ -84,12 +84,10 @@ public class SwordsManager extends SkillManager { } } - public double getStabDamage() - { + public double getStabDamage() { int rank = RankUtils.getRank(getPlayer(), SubSkillType.SWORDS_STAB); - if(rank > 0) - { + if (rank > 0) { double stabDamage = 1.0D + (rank * 1.5); return stabDamage; } @@ -97,23 +95,21 @@ public class SwordsManager extends SkillManager { return 0; } - public int getToolTier(ItemStack itemStack) - { - if(ItemUtils.isDiamondTool(itemStack)) + public int getToolTier(ItemStack itemStack) { + if (ItemUtils.isDiamondTool(itemStack)) return 4; - else if(ItemUtils.isIronTool(itemStack) || ItemUtils.isGoldTool(itemStack)) + else if (ItemUtils.isIronTool(itemStack) || ItemUtils.isGoldTool(itemStack)) return 3; - else if(ItemUtils.isStoneTool(itemStack)) + else if (ItemUtils.isStoneTool(itemStack)) return 2; else return 1; } - public int getRuptureBleedTicks() - { + public int getRuptureBleedTicks() { int bleedTicks = 2 * RankUtils.getRank(getPlayer(), SubSkillType.SWORDS_RUPTURE); - if(bleedTicks > AdvancedConfig.getInstance().getRuptureMaxTicks()) + if (bleedTicks > AdvancedConfig.getInstance().getRuptureMaxTicks()) bleedTicks = AdvancedConfig.getInstance().getRuptureMaxTicks(); return bleedTicks; @@ -123,7 +119,7 @@ public class SwordsManager extends SkillManager { * Handle the effects of the Counter Attack ability * * @param attacker The {@link LivingEntity} being affected by the ability - * @param damage The amount of damage initially dealt by the event + * @param damage The amount of damage initially dealt by the event */ public void counterAttackChecks(LivingEntity attacker, double damage) { if (RandomChanceUtil.isActivationSuccessful(SkillActivationType.RANDOM_LINEAR_100_SCALE_WITH_CAP, SubSkillType.SWORDS_COUNTER_ATTACK, getPlayer())) { @@ -132,7 +128,7 @@ public class SwordsManager extends SkillManager { NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Swords.Combat.Countered"); if (attacker instanceof Player) { - NotificationManager.sendPlayerInformation((Player)attacker, NotificationType.SUBSKILL_MESSAGE, "Swords.Combat.Counter.Hit"); + NotificationManager.sendPlayerInformation((Player) attacker, NotificationType.SUBSKILL_MESSAGE, "Swords.Combat.Counter.Hit"); } } } diff --git a/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java b/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java index a335d4a59..cf49dc153 100644 --- a/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java @@ -32,11 +32,29 @@ import java.util.HashMap; import java.util.List; public class TamingManager extends SkillManager { + private static HashMap> summonedEntities = new HashMap<>(); + public TamingManager(McMMOPlayer mcMMOPlayer) { super(mcMMOPlayer, PrimarySkillType.TAMING); } - private static HashMap> summonedEntities = new HashMap<>(); + protected static void addToTracker(LivingEntity livingEntity) { + TrackedTamingEntity trackedEntity = new TrackedTamingEntity(livingEntity); + + if (!summonedEntities.containsKey(livingEntity.getType())) { + summonedEntities.put(livingEntity.getType(), new ArrayList<>()); + } + + summonedEntities.get(livingEntity.getType()).add(trackedEntity); + } + + protected static List getTrackedEntities(EntityType entityType) { + return summonedEntities.get(entityType); + } + + protected static void removeFromTracker(TrackedTamingEntity trackedEntity) { + summonedEntities.get(trackedEntity.getLivingEntity().getType()).remove(trackedEntity); + } public boolean canUseThickFur() { return RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_THICK_FUR) @@ -69,14 +87,14 @@ public class TamingManager extends SkillManager { } public boolean canUseGore() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_GORE)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_GORE)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.TAMING_GORE); } public boolean canUseBeastLore() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_BEAST_LORE)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_BEAST_LORE)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.TAMING_BEAST_LORE); @@ -94,7 +112,7 @@ public class TamingManager extends SkillManager { /** * Apply the Fast Food Service ability. * - * @param wolf The wolf using the ability + * @param wolf The wolf using the ability * @param damage The damage being absorbed by the wolf */ public void fastFoodService(Wolf wolf, double damage) { @@ -126,7 +144,7 @@ public class TamingManager extends SkillManager { BleedTimerTask.add(target, getPlayer(), Taming.getInstance().getGoreBleedTicks(), 1, 2); if (target instanceof Player) { - NotificationManager.sendPlayerInformation((Player)target, NotificationType.SUBSKILL_MESSAGE, "Combat.StruckByGore"); + NotificationManager.sendPlayerInformation((Player) target, NotificationType.SUBSKILL_MESSAGE, "Combat.StruckByGore"); } NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Combat.Gore"); @@ -143,7 +161,7 @@ public class TamingManager extends SkillManager { * Summon an ocelot to your side. */ public void summonOcelot() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_CALL_OF_THE_WILD)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_CALL_OF_THE_WILD)) return; if (!Permissions.callOfTheWild(getPlayer(), EntityType.OCELOT)) { @@ -157,7 +175,7 @@ public class TamingManager extends SkillManager { * Summon a wolf to your side. */ public void summonWolf() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_CALL_OF_THE_WILD)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_CALL_OF_THE_WILD)) return; if (!Permissions.callOfTheWild(getPlayer(), EntityType.WOLF)) { @@ -171,7 +189,7 @@ public class TamingManager extends SkillManager { * Summon a horse to your side. */ public void summonHorse() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_CALL_OF_THE_WILD)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_CALL_OF_THE_WILD)) return; if (!Permissions.callOfTheWild(getPlayer(), EntityType.HORSE)) { @@ -212,10 +230,10 @@ public class TamingManager extends SkillManager { } public void pummel(LivingEntity target, Wolf wolf) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_PUMMEL)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_PUMMEL)) return; - if(!RandomChanceUtil.checkRandomChanceExecutionSuccess(new RandomChanceSkillStatic(AdvancedConfig.getInstance().getPummelChance(), getPlayer(), SubSkillType.TAMING_PUMMEL))) + if (!RandomChanceUtil.checkRandomChanceExecutionSuccess(new RandomChanceSkillStatic(AdvancedConfig.getInstance().getPummelChance(), getPlayer(), SubSkillType.TAMING_PUMMEL))) return; ParticleEffectUtils.playGreaterImpactEffect(target); @@ -252,7 +270,7 @@ public class TamingManager extends SkillManager { /** * Handle the Call of the Wild ability. * - * @param type The type of entity to summon. + * @param type The type of entity to summon. * @param summonAmount The amount of material needed to summon the entity */ private void callOfTheWild(EntityType type, int summonAmount) { @@ -378,22 +396,4 @@ public class TamingManager extends SkillManager { return true; } - - protected static void addToTracker(LivingEntity livingEntity) { - TrackedTamingEntity trackedEntity = new TrackedTamingEntity(livingEntity); - - if (!summonedEntities.containsKey(livingEntity.getType())) { - summonedEntities.put(livingEntity.getType(), new ArrayList<>()); - } - - summonedEntities.get(livingEntity.getType()).add(trackedEntity); - } - - protected static List getTrackedEntities(EntityType entityType) { - return summonedEntities.get(entityType); - } - - protected static void removeFromTracker(TrackedTamingEntity trackedEntity) { - summonedEntities.get(trackedEntity.getLivingEntity().getType()).remove(trackedEntity); - } } diff --git a/src/main/java/com/gmail/nossr50/skills/unarmed/Unarmed.java b/src/main/java/com/gmail/nossr50/skills/unarmed/Unarmed.java index 9bdbbb173..0029ca763 100644 --- a/src/main/java/com/gmail/nossr50/skills/unarmed/Unarmed.java +++ b/src/main/java/com/gmail/nossr50/skills/unarmed/Unarmed.java @@ -21,27 +21,22 @@ public class Unarmed { int amount = itemDrop.getAmount(); boolean grabbedItem = false; - for(int i = 0; i <= storageContents.length-1; i++) - { - if(amount <= 0) + for (int i = 0; i <= storageContents.length - 1; i++) { + if (amount <= 0) break; - if(i == heldItemSlotID) + if (i == heldItemSlotID) continue; //EMPTY SLOT! - if(storageContents[i] == null) - { + if (storageContents[i] == null) { player.getInventory().setItem(i, itemDrop); amount = 0; grabbedItem = true; break; - } - else if(itemDrop.isSimilar(storageContents[i]) && storageContents[i].getAmount() < storageContents[i].getMaxStackSize()) - { + } else if (itemDrop.isSimilar(storageContents[i]) && storageContents[i].getAmount() < storageContents[i].getMaxStackSize()) { //If we can fit this whole itemstack into this item - if(amount + storageContents[i].getAmount() <= storageContents[i].getMaxStackSize()) - { + if (amount + storageContents[i].getAmount() <= storageContents[i].getMaxStackSize()) { ItemStack modifiedAmount = storageContents[i]; modifiedAmount.setAmount(amount + storageContents[i].getAmount()); @@ -63,15 +58,14 @@ public class Unarmed { } } - if(amount <= 0) + if (amount <= 0) event.getItem().remove(); //Cleanup Item else event.getItem().getItemStack().setAmount(amount); event.setCancelled(true); - if(grabbedItem) - { + if (grabbedItem) { SoundManager.sendSound(player, player.getLocation(), SoundType.POP); player.updateInventory(); } diff --git a/src/main/java/com/gmail/nossr50/skills/unarmed/UnarmedManager.java b/src/main/java/com/gmail/nossr50/skills/unarmed/UnarmedManager.java index 1ce5733f9..02d2b10c8 100644 --- a/src/main/java/com/gmail/nossr50/skills/unarmed/UnarmedManager.java +++ b/src/main/java/com/gmail/nossr50/skills/unarmed/UnarmedManager.java @@ -36,7 +36,7 @@ public class UnarmedManager extends SkillManager { } public boolean canUseIronArm() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_IRON_ARM_STYLE)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_IRON_ARM_STYLE)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.UNARMED_IRON_ARM_STYLE); @@ -47,14 +47,14 @@ public class UnarmedManager extends SkillManager { } public boolean canDisarm(LivingEntity target) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_DISARM)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_DISARM)) return false; return target instanceof Player && ((Player) target).getInventory().getItemInMainHand().getType() != Material.AIR && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.UNARMED_DISARM); } public boolean canDeflect() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_ARROW_DEFLECT)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_ARROW_DEFLECT)) return false; Player player = getPlayer(); @@ -63,7 +63,7 @@ public class UnarmedManager extends SkillManager { } public boolean canUseBlockCracker() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_BLOCK_CRACKER)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_BLOCK_CRACKER)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.UNARMED_BLOCK_CRACKER); @@ -101,7 +101,7 @@ public class UnarmedManager extends SkillManager { return; } - if(UserManager.getPlayer(defender) == null) + if (UserManager.getPlayer(defender) == null) return; Item item = Misc.dropItem(defender.getLocation(), defender.getInventory().getItemInMainHand()); @@ -156,8 +156,7 @@ public class UnarmedManager extends SkillManager { public double getIronArmDamage() { int rank = RankUtils.getRank(getPlayer(), SubSkillType.UNARMED_IRON_ARM_STYLE); - if(rank == 1) - { + if (rank == 1) { return 4; } else { return 3 + (rank * 2); diff --git a/src/main/java/com/gmail/nossr50/skills/woodcutting/Woodcutting.java b/src/main/java/com/gmail/nossr50/skills/woodcutting/Woodcutting.java index 7f72765c0..20a60127a 100644 --- a/src/main/java/com/gmail/nossr50/skills/woodcutting/Woodcutting.java +++ b/src/main/java/com/gmail/nossr50/skills/woodcutting/Woodcutting.java @@ -17,19 +17,26 @@ import java.util.List; import java.util.Set; public final class Woodcutting { + /** + * The x/y differences to the blocks in a flat cylinder around the center + * block, which is excluded. + */ + private static final int[][] directions = { + new int[]{-2, -1}, new int[]{-2, 0}, new int[]{-2, 1}, + new int[]{-1, -2}, new int[]{-1, -1}, new int[]{-1, 0}, new int[]{-1, 1}, new int[]{-1, 2}, + new int[]{0, -2}, new int[]{0, -1}, new int[]{0, 1}, new int[]{0, 2}, + new int[]{1, -2}, new int[]{1, -1}, new int[]{1, 0}, new int[]{1, 1}, new int[]{1, 2}, + new int[]{2, -1}, new int[]{2, 0}, new int[]{2, 1}, + }; protected static boolean treeFellerReachedThreshold = false; - protected enum ExperienceGainMethod { - DEFAULT, - TREE_FELLER, + private Woodcutting() { } - private Woodcutting() {} - /** * Retrieves the experience reward from a log * - * @param blockState Log being broken + * @param blockState Log being broken * @param experienceGainMethod How the log is being broken * @return Amount of experience */ @@ -51,28 +58,16 @@ public final class Woodcutting { Misc.dropItems(Misc.getBlockCenter(blockState), blockState.getBlock().getDrops()); } else {*/ - if (MainConfig.getInstance().getWoodcuttingDoubleDropsEnabled(blockState.getBlockData())) { - Misc.dropItems(Misc.getBlockCenter(blockState), blockState.getBlock().getDrops()); - } + if (MainConfig.getInstance().getWoodcuttingDoubleDropsEnabled(blockState.getBlockData())) { + Misc.dropItems(Misc.getBlockCenter(blockState), blockState.getBlock().getDrops()); + } //} } - /** - * The x/y differences to the blocks in a flat cylinder around the center - * block, which is excluded. - */ - private static final int[][] directions = { - new int[] {-2, -1}, new int[] {-2, 0}, new int[] {-2, 1}, - new int[] {-1, -2}, new int[] {-1, -1}, new int[] {-1, 0}, new int[] {-1, 1}, new int[] {-1, 2}, - new int[] { 0, -2}, new int[] { 0, -1}, new int[] { 0, 1}, new int[] { 0, 2}, - new int[] { 1, -2}, new int[] { 1, -1}, new int[] { 1, 0}, new int[] { 1, 1}, new int[] { 1, 2}, - new int[] { 2, -1}, new int[] { 2, 0}, new int[] { 2, 1}, - }; - /** * Processes Tree Feller in a recursive manner * - * @param blockState Block being checked + * @param blockState Block being checked * @param treeFellerBlocks List of blocks to be removed */ /* @@ -110,8 +105,7 @@ public final class Woodcutting { return; } } - } - else { + } else { // Cover DOWN handleBlock(blockState.getBlock().getRelative(BlockFace.DOWN).getState(), futureCenterBlocks, treeFellerBlocks); // Search in a cube @@ -140,7 +134,7 @@ public final class Woodcutting { * Handles the durability loss * * @param treeFellerBlocks List of blocks to be removed - * @param inHand tool being used + * @param inHand tool being used * @return True if the tool can sustain the durability loss */ protected static boolean handleDurabilityLoss(Set treeFellerBlocks, ItemStack inHand) { @@ -162,12 +156,12 @@ public final class Woodcutting { * list of blocks used for future recursive calls of * 'processTree()' * - * @param blockState Block to be added + * @param blockState Block to be added * @param futureCenterBlocks List of blocks that will be used to call - * 'processTree()' - * @param treeFellerBlocks List of blocks to be removed + * 'processTree()' + * @param treeFellerBlocks List of blocks to be removed * @return true if and only if the given blockState was a Log not already - * in treeFellerBlocks. + * in treeFellerBlocks. */ private static boolean handleBlock(BlockState blockState, List futureCenterBlocks, Set treeFellerBlocks) { if (treeFellerBlocks.contains(blockState) || mcMMO.getPlaceStore().isTrue(blockState)) { @@ -183,11 +177,15 @@ public final class Woodcutting { treeFellerBlocks.add(blockState); futureCenterBlocks.add(blockState); return true; - } - else if (BlockUtils.isLeaves(blockState)) { + } else if (BlockUtils.isLeaves(blockState)) { treeFellerBlocks.add(blockState); return false; } return false; } + + protected enum ExperienceGainMethod { + DEFAULT, + TREE_FELLER, + } } diff --git a/src/main/java/com/gmail/nossr50/util/BlockUtils.java b/src/main/java/com/gmail/nossr50/util/BlockUtils.java index a82bbd249..cfe04c354 100644 --- a/src/main/java/com/gmail/nossr50/util/BlockUtils.java +++ b/src/main/java/com/gmail/nossr50/util/BlockUtils.java @@ -38,10 +38,8 @@ public final class BlockUtils { * @param blockState the blockstate * @return true if the player succeeded in the check */ - public static boolean checkDoubleDrops(Player player, BlockState blockState, SubSkillType subSkillType) - { - if(mcMMO.getConfigManager().isBonusDropsEnabled(blockState.getType()) && Permissions.isSubSkillEnabled(player, subSkillType)) - { + public static boolean checkDoubleDrops(Player player, BlockState blockState, SubSkillType subSkillType) { + if (mcMMO.getConfigManager().isBonusDropsEnabled(blockState.getType()) && Permissions.isSubSkillEnabled(player, subSkillType)) { return RandomChanceUtil.checkRandomChanceExecutionSuccess(new RandomChanceSkill(player, subSkillType, true)); } @@ -125,10 +123,8 @@ public final class BlockUtils { return isMineable(blockState); } - public static boolean isMineable(BlockState blockState) - { - switch (blockState.getType()) - { + public static boolean isMineable(BlockState blockState) { + switch (blockState.getType()) { case COAL_ORE: case DIAMOND_ORE: case EMERALD_ORE: @@ -163,7 +159,7 @@ public final class BlockUtils { * otherwise */ public static boolean affectedByGigaDrillBreaker(BlockState blockState) { - if(mcMMO.getConfigManager().getExperienceMapManager().hasExcavationXp(blockState.getType())) + if (mcMMO.getConfigManager().getExperienceMapManager().hasExcavationXp(blockState.getType())) return true; return isDiggable(blockState); @@ -171,13 +167,12 @@ public final class BlockUtils { /** * Returns true if a shovel is used for digging this block + * * @param blockState target blockstate * @return true if a shovel is typically used for digging this block */ - public static boolean isDiggable(BlockState blockState) - { - switch(blockState.getType()) - { + public static boolean isDiggable(BlockState blockState) { + switch (blockState.getType()) { case CLAY: case FARMLAND: case GRASS_BLOCK: @@ -205,7 +200,7 @@ public final class BlockUtils { * @return true if the block is a log, false otherwise */ public static boolean isLog(BlockState blockState) { - if(mcMMO.getConfigManager().getExperienceMapManager().hasWoodcuttingXp(blockState.getType())) + if (mcMMO.getConfigManager().getExperienceMapManager().hasWoodcuttingXp(blockState.getType())) return true; return isLoggingRelated(blockState); @@ -214,13 +209,12 @@ public final class BlockUtils { /** * Determines if this particular block is typically gathered using an Axe + * * @param blockState target blockstate * @return true if the block is gathered via axe */ - public static boolean isLoggingRelated(BlockState blockState) - { - switch(blockState.getType()) - { + public static boolean isLoggingRelated(BlockState blockState) { + switch (blockState.getType()) { case ACACIA_LOG: case BIRCH_LOG: case DARK_OAK_LOG: @@ -275,7 +269,7 @@ public final class BlockUtils { default: return false; - //return mcMMO.getModManager().isCustomLeaf(blockState); + //return mcMMO.getModManager().isCustomLeaf(blockState); } } diff --git a/src/main/java/com/gmail/nossr50/util/ChimaeraWing.java b/src/main/java/com/gmail/nossr50/util/ChimaeraWing.java index de5fb9cab..d7e82e2e2 100644 --- a/src/main/java/com/gmail/nossr50/util/ChimaeraWing.java +++ b/src/main/java/com/gmail/nossr50/util/ChimaeraWing.java @@ -29,7 +29,8 @@ public final class ChimaeraWing { private static McMMOPlayer mcMMOPlayer; private static Location location; - private ChimaeraWing() {} + private ChimaeraWing() { + } /** * Check for item usage. @@ -55,7 +56,7 @@ public final class ChimaeraWing { mcMMOPlayer = UserManager.getPlayer(player); //Not loaded - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) return; if (mcMMOPlayer.getTeleportCommenceLocation() != null) { @@ -65,7 +66,7 @@ public final class ChimaeraWing { int amount = inHand.getAmount(); if (amount < MainConfig.getInstance().getChimaeraUseCost()) { - NotificationManager.sendPlayerInformation(player, NotificationType.REQUIREMENTS_NOT_MET, "Item.ChimaeraWing.NotEnough",String.valueOf(MainConfig.getInstance().getChimaeraUseCost() - amount), "Item.ChimaeraWing.Name"); + NotificationManager.sendPlayerInformation(player, NotificationType.REQUIREMENTS_NOT_MET, "Item.ChimaeraWing.NotEnough", String.valueOf(MainConfig.getInstance().getChimaeraUseCost() - amount), "Item.ChimaeraWing.Name"); return; } @@ -114,8 +115,7 @@ public final class ChimaeraWing { if (warmup > 0) { NotificationManager.sendPlayerInformation(player, NotificationType.ITEM_MESSAGE, "Teleport.Commencing", String.valueOf(warmup)); new ChimaeraWingWarmup(mcMMOPlayer).runTaskLater(mcMMO.p, 20 * warmup); - } - else { + } else { chimaeraExecuteTeleport(); } } @@ -125,13 +125,11 @@ public final class ChimaeraWing { if (MainConfig.getInstance().getChimaeraUseBedSpawn() && player.getBedSpawnLocation() != null) { player.teleport(player.getBedSpawnLocation()); - } - else { + } else { Location spawnLocation = player.getWorld().getSpawnLocation(); if (spawnLocation.getBlock().getType() == Material.AIR) { player.teleport(spawnLocation); - } - else { + } else { player.teleport(player.getWorld().getHighestBlockAt(spawnLocation).getLocation()); } } diff --git a/src/main/java/com/gmail/nossr50/util/EnchantmentUtils.java b/src/main/java/com/gmail/nossr50/util/EnchantmentUtils.java index 6aab49b3d..9d704ab1e 100644 --- a/src/main/java/com/gmail/nossr50/util/EnchantmentUtils.java +++ b/src/main/java/com/gmail/nossr50/util/EnchantmentUtils.java @@ -40,7 +40,6 @@ public class EnchantmentUtils { * Method to get an {@link Enchantment} using it's Vanilla Minecraft name or Bukkit enum name * * @param enchantmentName Vanilla or Bukkit name of enchantment - * * @return Enchantment or null if no enchantment was found */ public static Enchantment getByName(String enchantmentName) { diff --git a/src/main/java/com/gmail/nossr50/util/EventUtils.java b/src/main/java/com/gmail/nossr50/util/EventUtils.java index 3f84cd5c3..5ed7c4ff2 100644 --- a/src/main/java/com/gmail/nossr50/util/EventUtils.java +++ b/src/main/java/com/gmail/nossr50/util/EventUtils.java @@ -55,6 +55,7 @@ public class EventUtils { /* * Quality of Life methods */ + /** * Checks to see if damage is from natural sources * This cannot be used to determine if damage is from vanilla MC, it just checks to see if the damage is from a complex behaviour in mcMMO such as bleed. @@ -71,19 +72,19 @@ public class EventUtils { /** * This little method is just to make the code more readable + * * @param entity target entity * @return the associated McMMOPlayer for this entity */ - public static McMMOPlayer getMcMMOPlayer(Entity entity) - { - return UserManager.getPlayer((Player)entity); + public static McMMOPlayer getMcMMOPlayer(Entity entity) { + return UserManager.getPlayer((Player) entity); } /** * Checks to see if a Player was damaged in this EntityDamageEvent - * + *

* This method checks for the following things and if they are all true it returns true - * + *

* 1) The player is real and not an NPC * 2) The player is not in god mode * 3) The damage dealt is above 0 (if a player has Absorption, check if damage and final damage are above 0) @@ -92,8 +93,7 @@ public class EventUtils { * @param entityDamageEvent * @return */ - public static boolean isRealPlayerDamaged(EntityDamageEvent entityDamageEvent) - { + public static boolean isRealPlayerDamaged(EntityDamageEvent entityDamageEvent) { //Make sure the damage is above 0 double damage = entityDamageEvent.getDamage(); double finalDamage = entityDamageEvent.getFinalDamage(); @@ -119,7 +119,7 @@ public class EventUtils { Entity entity = entityDamageEvent.getEntity(); //Check to make sure the entity is not an NPC - if(Misc.isNPCEntity(entity)) + if (Misc.isNPCEntity(entity)) return false; if (!entity.isValid() || !(entity instanceof LivingEntity)) { @@ -141,8 +141,7 @@ public class EventUtils { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if(mcMMOPlayer == null) - { + if (mcMMOPlayer == null) { return true; } @@ -171,7 +170,8 @@ public class EventUtils { /** * Calls a new SubSkillEvent for this SubSkill and then returns it - * @param player target player + * + * @param player target player * @param subSkillType target subskill * @return the event after it has been fired */ @@ -185,7 +185,8 @@ public class EventUtils { /** * Calls a new SubSkillEvent for this SubSkill and then returns it - * @param player target player + * + * @param player target player * @param abstractSubSkill target subskill * @return the event after it has been fired */ @@ -236,8 +237,8 @@ public class EventUtils { /** * Simulate a block break event. * - * @param block The block to break - * @param player The player breaking the block + * @param block The block to break + * @param player The player breaking the block * @param shouldArmSwing true if an armswing event should be fired, false otherwise * @return true if the event wasn't cancelled, false otherwise */ @@ -261,7 +262,7 @@ public class EventUtils { public static void handlePartyTeleportEvent(Player teleportingPlayer, Player targetPlayer) { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(teleportingPlayer); - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) return; McMMOPartyTeleportEvent event = new McMMOPartyTeleportEvent(teleportingPlayer, targetPlayer, mcMMOPlayer.getParty().getName()); @@ -322,7 +323,7 @@ public class EventUtils { } public static boolean handleStatsLossEvent(Player player, HashMap levelChanged, HashMap experienceChanged) { - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) return true; McMMOPlayerStatLossEvent event = new McMMOPlayerStatLossEvent(player, levelChanged, experienceChanged); @@ -373,11 +374,11 @@ public class EventUtils { McMMOPlayer killerPlayer = UserManager.getPlayer(killer); //Not loaded - if(killerPlayer == null) + if (killerPlayer == null) return true; //Not loaded - if(UserManager.getPlayer(victim) == null) + if (UserManager.getPlayer(victim) == null) return true; PlayerProfile victimProfile = UserManager.getPlayer(victim).getProfile(); diff --git a/src/main/java/com/gmail/nossr50/util/HardcoreManager.java b/src/main/java/com/gmail/nossr50/util/HardcoreManager.java index 22979214e..90208f37e 100644 --- a/src/main/java/com/gmail/nossr50/util/HardcoreManager.java +++ b/src/main/java/com/gmail/nossr50/util/HardcoreManager.java @@ -11,13 +11,14 @@ import org.bukkit.entity.Player; import java.util.HashMap; public final class HardcoreManager { - private HardcoreManager() {} + private HardcoreManager() { + } public static void invokeStatPenalty(Player player) { double statLossPercentage = MainConfig.getInstance().getHardcoreDeathStatPenaltyPercentage(); int levelThreshold = MainConfig.getInstance().getHardcoreDeathStatPenaltyLevelThreshold(); - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) return; PlayerProfile playerProfile = UserManager.getPlayer(player).getProfile(); @@ -62,7 +63,7 @@ public final class HardcoreManager { double vampirismStatLeechPercentage = MainConfig.getInstance().getHardcoreVampirismStatLeechPercentage(); int levelThreshold = MainConfig.getInstance().getHardcoreVampirismLevelThreshold(); - if(UserManager.getPlayer(killer) == null || UserManager.getPlayer(victim) == null) + if (UserManager.getPlayer(killer) == null || UserManager.getPlayer(victim) == null) return; PlayerProfile killerProfile = UserManager.getPlayer(killer).getProfile(); @@ -106,8 +107,7 @@ public final class HardcoreManager { if (totalLevelsStolen > 0) { NotificationManager.sendPlayerInformation(killer, NotificationType.HARDCORE_MODE, "Hardcore.Vampirism.Killer.Success", String.valueOf(totalLevelsStolen), victim.getName()); NotificationManager.sendPlayerInformation(victim, NotificationType.HARDCORE_MODE, "Hardcore.Vampirism.Victim.Success", killer.getName(), String.valueOf(totalLevelsStolen)); - } - else { + } else { NotificationManager.sendPlayerInformation(killer, NotificationType.HARDCORE_MODE, "Hardcore.Vampirism.Killer.Failure", victim.getName()); NotificationManager.sendPlayerInformation(victim, NotificationType.HARDCORE_MODE, "Hardcore.Vampirism.Victim.Failure", killer.getName()); } diff --git a/src/main/java/com/gmail/nossr50/util/ItemUtils.java b/src/main/java/com/gmail/nossr50/util/ItemUtils.java index b13ccce32..01f361cc1 100644 --- a/src/main/java/com/gmail/nossr50/util/ItemUtils.java +++ b/src/main/java/com/gmail/nossr50/util/ItemUtils.java @@ -16,26 +16,23 @@ import java.util.ArrayList; import java.util.List; public final class ItemUtils { - private ItemUtils() {} + private ItemUtils() { + } - public static ArrayList getRepairItemMaterials(List repairItemList) - { + public static ArrayList getRepairItemMaterials(List repairItemList) { ArrayList repairMaterialList = new ArrayList<>(); - for(Material m : repairItemList) - { + for (Material m : repairItemList) { repairMaterialList.add(m.getKey().toString()); } return repairMaterialList; } - public static ArrayList matchMaterials(List ItemBlockRegistryKeyList) - { + public static ArrayList matchMaterials(List ItemBlockRegistryKeyList) { ArrayList matchedMaterials = new ArrayList<>(); - for(String s : ItemBlockRegistryKeyList) - { + for (String s : ItemBlockRegistryKeyList) { matchedMaterials.add(Material.matchMaterial(s)); } @@ -44,15 +41,14 @@ public final class ItemUtils { /** * Determines the item type, currently used for repairables/salvageables + * * @param material target material * @return the matching ItemType returns OTHER if no match */ - public static ItemType determineItemType(Material material) - { + public static ItemType determineItemType(Material material) { if (ItemUtils.isMinecraftTool(new ItemStack(material))) { return ItemType.TOOL; - } - else if (ItemUtils.isArmor(new ItemStack((material)))) { + } else if (ItemUtils.isArmor(new ItemStack((material)))) { return ItemType.ARMOR; } else { return ItemType.OTHER; @@ -61,6 +57,7 @@ public final class ItemUtils { /** * Determines the material category, currently used for repairables/salvageables + * * @param material target material * @return the matching ItemMaterialCategory, return OTHER if no match */ @@ -112,7 +109,7 @@ public final class ItemUtils { default: return false; - //return mcMMO.getModManager().isCustomBow(type); + //return mcMMO.getModManager().isCustomBow(type); } } @@ -135,7 +132,7 @@ public final class ItemUtils { default: return false; - //return mcMMO.getModManager().isCustomSword(type); + //return mcMMO.getModManager().isCustomSword(type); } } @@ -158,7 +155,7 @@ public final class ItemUtils { default: return false; - //return mcMMO.getModManager().isCustomHoe(type); + //return mcMMO.getModManager().isCustomHoe(type); } } @@ -181,7 +178,7 @@ public final class ItemUtils { default: return false; - //return mcMMO.getModManager().isCustomShovel(type); + //return mcMMO.getModManager().isCustomShovel(type); } } @@ -204,7 +201,7 @@ public final class ItemUtils { default: return false; - //return mcMMO.getModManager().isCustomAxe(type); + //return mcMMO.getModManager().isCustomAxe(type); } } @@ -227,7 +224,7 @@ public final class ItemUtils { default: return false; - //return mcMMO.getModManager().isCustomPickaxe(type); + //return mcMMO.getModManager().isCustomPickaxe(type); } } @@ -264,7 +261,7 @@ public final class ItemUtils { default: return false; - //return mcMMO.getModManager().isCustomHelmet(type); + //return mcMMO.getModManager().isCustomHelmet(type); } } @@ -287,7 +284,7 @@ public final class ItemUtils { default: return false; - //return mcMMO.getModManager().isCustomChestplate(type); + //return mcMMO.getModManager().isCustomChestplate(type); } } @@ -310,7 +307,7 @@ public final class ItemUtils { default: return false; - //return mcMMO.getModManager().isCustomLeggings(type); + //return mcMMO.getModManager().isCustomLeggings(type); } } @@ -333,7 +330,7 @@ public final class ItemUtils { default: return false; - //return mcMMO.getModManager().isCustomBoots(type); + //return mcMMO.getModManager().isCustomBoots(type); } } diff --git a/src/main/java/com/gmail/nossr50/util/MaterialMapStore.java b/src/main/java/com/gmail/nossr50/util/MaterialMapStore.java index e9a30066e..cdf83324b 100644 --- a/src/main/java/com/gmail/nossr50/util/MaterialMapStore.java +++ b/src/main/java/com/gmail/nossr50/util/MaterialMapStore.java @@ -7,9 +7,8 @@ import java.util.HashSet; /** * Stores hash tables for item and block names * This allows for better support across multiple versions of Minecraft - * + *

* This is a temporary class, mcMMO is spaghetti and I'l clean it up later - * */ public class MaterialMapStore { @@ -21,8 +20,7 @@ public class MaterialMapStore { private HashSet blockCrackerWhiteList; private HashSet canMakeShroomyWhiteList; - public MaterialMapStore() - { + public MaterialMapStore() { abilityBlackList = new HashSet<>(); toolBlackList = new HashSet<>(); mossyWhiteList = new HashSet<>(); @@ -34,43 +32,35 @@ public class MaterialMapStore { fillHardcodedHashSets(); } - public boolean isAbilityActivationBlackListed(Material material) - { + public boolean isAbilityActivationBlackListed(Material material) { return abilityBlackList.contains(material.getKey().getKey()); } - public boolean isToolActivationBlackListed(Material material) - { + public boolean isToolActivationBlackListed(Material material) { return toolBlackList.contains(material.getKey().getKey()); } - public boolean isMossyWhiteListed(Material material) - { + public boolean isMossyWhiteListed(Material material) { return mossyWhiteList.contains(material.getKey().getKey()); } - public boolean isLeavesWhiteListed(Material material) - { + public boolean isLeavesWhiteListed(Material material) { return leavesWhiteList.contains(material.getKey().getKey()); } - public boolean isHerbalismAbilityWhiteListed(Material material) - { + public boolean isHerbalismAbilityWhiteListed(Material material) { return herbalismAbilityBlackList.contains(material.getKey().getKey()); } - public boolean isBlockCrackerWhiteListed(Material material) - { + public boolean isBlockCrackerWhiteListed(Material material) { return blockCrackerWhiteList.contains(material.getKey().getKey()); } - public boolean isShroomyWhiteListed(Material material) - { + public boolean isShroomyWhiteListed(Material material) { return canMakeShroomyWhiteList.contains(material.getKey().getKey()); } - private void fillHardcodedHashSets() - { + private void fillHardcodedHashSets() { fillAbilityBlackList(); filltoolBlackList(); fillMossyWhiteList(); @@ -80,28 +70,24 @@ public class MaterialMapStore { fillShroomyWhiteList(); } - private void fillShroomyWhiteList() - { + private void fillShroomyWhiteList() { canMakeShroomyWhiteList.add("dirt"); canMakeShroomyWhiteList.add("grass"); canMakeShroomyWhiteList.add("grass_path"); } - private void fillBlockCrackerWhiteList() - { + private void fillBlockCrackerWhiteList() { blockCrackerWhiteList.add("stone_bricks"); } - private void fillHerbalismAbilityBlackList() - { + private void fillHerbalismAbilityBlackList() { herbalismAbilityBlackList.add("dirt"); herbalismAbilityBlackList.add("grass"); herbalismAbilityBlackList.add("grass_path"); herbalismAbilityBlackList.add("farmland"); } - private void fillLeavesWhiteList() - { + private void fillLeavesWhiteList() { leavesWhiteList.add("oak_leaves"); leavesWhiteList.add("acacia_leaves"); leavesWhiteList.add("birch_leaves"); @@ -110,8 +96,7 @@ public class MaterialMapStore { leavesWhiteList.add("spruce_leaves"); } - private void fillMossyWhiteList() - { + private void fillMossyWhiteList() { mossyWhiteList.add("cobblestone"); mossyWhiteList.add("dirt"); mossyWhiteList.add("grass_path"); @@ -119,8 +104,7 @@ public class MaterialMapStore { mossyWhiteList.add("cobblestone_wall"); } - private void fillAbilityBlackList() - { + private void fillAbilityBlackList() { abilityBlackList.add("black_bed"); abilityBlackList.add("blue_bed"); abilityBlackList.add("brown_bed"); @@ -219,9 +203,8 @@ public class MaterialMapStore { abilityBlackList.add("wall_sign"); //1.13 and lower? abilityBlackList.add("sign"); //1.13 and lower? } - - private void filltoolBlackList() - { + + private void filltoolBlackList() { //TODO: Add anvils / missing logs toolBlackList.add("black_bed"); toolBlackList.add("blue_bed"); @@ -344,8 +327,7 @@ public class MaterialMapStore { toolBlackList.add("spruce_wood"); } - private void addToHashSet(String string, HashSet stringHashSet) - { + private void addToHashSet(String string, HashSet stringHashSet) { stringHashSet.add(string.toLowerCase()); } } diff --git a/src/main/java/com/gmail/nossr50/util/MaterialUtils.java b/src/main/java/com/gmail/nossr50/util/MaterialUtils.java index 8c6983ba2..eefd9cdce 100644 --- a/src/main/java/com/gmail/nossr50/util/MaterialUtils.java +++ b/src/main/java/com/gmail/nossr50/util/MaterialUtils.java @@ -3,7 +3,8 @@ package com.gmail.nossr50.util; import org.bukkit.Material; public final class MaterialUtils { - private MaterialUtils() {} + private MaterialUtils() { + } protected static boolean isOre(Material data) { switch (data) { diff --git a/src/main/java/com/gmail/nossr50/util/Misc.java b/src/main/java/com/gmail/nossr50/util/Misc.java index 9715e0ed6..b429ba1a3 100644 --- a/src/main/java/com/gmail/nossr50/util/Misc.java +++ b/src/main/java/com/gmail/nossr50/util/Misc.java @@ -16,13 +16,11 @@ import java.util.Random; import java.util.Set; public final class Misc { - private static Random random = new Random(); - public static final int TIME_CONVERSION_FACTOR = 1000; public static final int TICK_CONVERSION_FACTOR = 20; - public static final int PLAYER_RESPAWN_COOLDOWN_SECONDS = 5; public static final double SKILL_MESSAGE_MAX_SENDING_DISTANCE = 10.0; + public static final Set modNames = ImmutableSet.of("LOTR", "BUILDCRAFT", "ENDERIO", "ENHANCEDBIOMES", "IC2", "METALLURGY", "FORESTRY", "GALACTICRAFT", "RAILCRAFT", "TWILIGHTFOREST", "THAUMCRAFT", "GRAVESTONEMOD", "GROWTHCRAFT", "ARCTICMOBS", "DEMONMOBS", "INFERNOMOBS", "SWAMPMOBS", "MARICULTURE", "MINESTRAPPOLATION"); // Sound Pitches & Volumes from CB /* public static final float ANVIL_USE_PITCH = 0.3F; // Not in CB directly, I went off the place sound values @@ -34,10 +32,10 @@ public final class Misc { public static final float GHAST_VOLUME = 1.0F * MainConfig.getInstance().getMasterVolume(); public static final float LEVELUP_PITCH = 0.5F; // Reduced to differentiate between vanilla level-up public static final float LEVELUP_VOLUME = 0.75F * MainConfig.getInstance().getMasterVolume(); // Use max volume always*/ + private static Random random = new Random(); - public static final Set modNames = ImmutableSet.of("LOTR", "BUILDCRAFT", "ENDERIO", "ENHANCEDBIOMES", "IC2", "METALLURGY", "FORESTRY", "GALACTICRAFT", "RAILCRAFT", "TWILIGHTFOREST", "THAUMCRAFT", "GRAVESTONEMOD", "GROWTHCRAFT", "ARCTICMOBS", "DEMONMOBS", "INFERNOMOBS", "SWAMPMOBS", "MARICULTURE", "MINESTRAPPOLATION"); - - private Misc() {} + private Misc() { + } public static boolean isNPCEntity(Entity entity) { return (entity == null @@ -49,8 +47,8 @@ public final class Misc { /** * Determine if two locations are near each other. * - * @param first The first location - * @param second The second location + * @param first The first location + * @param second The second location * @param maxDistance The max distance apart * @return true if the distance between {@code first} and {@code second} is less than {@code maxDistance}, false otherwise */ @@ -60,7 +58,7 @@ public final class Misc { /** * Get the center of the given block. - * + * * @param blockState The {@link BlockState} of the block * @return A {@link Location} lying at the center of the block */ @@ -78,7 +76,7 @@ public final class Misc { * Drop items at a given location. * * @param location The location to drop the items at - * @param is The items to drop + * @param is The items to drop * @param quantity The amount of items to drop */ public static void dropItems(Location location, ItemStack is, int quantity) { @@ -90,7 +88,7 @@ public final class Misc { /** * Drop an item at a given location. * - * @param location The location to drop the item at + * @param location The location to drop the item at * @param itemStack The item to drop * @return Dropped Item entity or null if invalid or cancelled */ diff --git a/src/main/java/com/gmail/nossr50/util/MobHealthbarUtils.java b/src/main/java/com/gmail/nossr50/util/MobHealthbarUtils.java index 99d79346c..d6a226c05 100644 --- a/src/main/java/com/gmail/nossr50/util/MobHealthbarUtils.java +++ b/src/main/java/com/gmail/nossr50/util/MobHealthbarUtils.java @@ -12,13 +12,14 @@ import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.metadata.FixedMetadataValue; public final class MobHealthbarUtils { - private MobHealthbarUtils() {} + private MobHealthbarUtils() { + } /** * Fix issues with death messages caused by the mob healthbars. * * @param deathMessage The original death message - * @param player The player who died + * @param player The player who died * @return the fixed death message */ public static String fixDeathMessage(String deathMessage, Player player) { @@ -30,7 +31,8 @@ public final class MobHealthbarUtils { /** * Handle the creation of mob healthbars. - * @param target the targetted entity + * + * @param target the targetted entity * @param damage damage done by the attack triggering this */ public static void handleMobHealthbars(LivingEntity target, double damage, mcMMO plugin) { @@ -48,7 +50,7 @@ public final class MobHealthbarUtils { /* * Store the name in metadata */ - if(target.getMetadata("mcMMO_oldName").size() <= 0 && originalName != null) + if (target.getMetadata("mcMMO_oldName").size() <= 0 && originalName != null) target.setMetadata("mcMMO_oldName", new OldName(originalName, plugin)); if (oldName == null) { @@ -69,8 +71,7 @@ public final class MobHealthbarUtils { if (updateName) { target.setMetadata(mcMMO.customNameKey, new FixedMetadataValue(mcMMO.p, oldName)); target.setMetadata(mcMMO.customVisibleKey, new FixedMetadataValue(mcMMO.p, oldNameVisible)); - } - else if (!target.hasMetadata(mcMMO.customNameKey)) { + } else if (!target.hasMetadata(mcMMO.customNameKey)) { target.setMetadata(mcMMO.customNameKey, new FixedMetadataValue(mcMMO.p, "")); target.setMetadata(mcMMO.customVisibleKey, new FixedMetadataValue(mcMMO.p, false)); } @@ -100,20 +101,15 @@ public final class MobHealthbarUtils { if (healthPercentage >= 85) { color = ChatColor.DARK_GREEN; - } - else if (healthPercentage >= 70) { + } else if (healthPercentage >= 70) { color = ChatColor.GREEN; - } - else if (healthPercentage >= 55) { + } else if (healthPercentage >= 55) { color = ChatColor.GOLD; - } - else if (healthPercentage >= 40) { + } else if (healthPercentage >= 40) { color = ChatColor.YELLOW; - } - else if (healthPercentage >= 25) { + } else if (healthPercentage >= 25) { color = ChatColor.RED; - } - else if (healthPercentage >= 0) { + } else if (healthPercentage >= 0) { color = ChatColor.DARK_RED; } diff --git a/src/main/java/com/gmail/nossr50/util/Motd.java b/src/main/java/com/gmail/nossr50/util/Motd.java index 35ba51053..1d861069f 100644 --- a/src/main/java/com/gmail/nossr50/util/Motd.java +++ b/src/main/java/com/gmail/nossr50/util/Motd.java @@ -14,7 +14,8 @@ public final class Motd { public static final String PERK_PREFIX = LocaleLoader.getString("MOTD.PerksPrefix") + " "; private static final PluginDescriptionFile pluginDescription = mcMMO.p.getDescription(); - private Motd() {} + private Motd() { + } public static void displayAll(Player player) { displayVersion(player, pluginDescription.getVersion()); diff --git a/src/main/java/com/gmail/nossr50/util/Permissions.java b/src/main/java/com/gmail/nossr50/util/Permissions.java index 07dfa6490..164a51d31 100644 --- a/src/main/java/com/gmail/nossr50/util/Permissions.java +++ b/src/main/java/com/gmail/nossr50/util/Permissions.java @@ -17,86 +17,217 @@ import org.bukkit.permissions.PermissionDefault; import org.bukkit.plugin.PluginManager; public final class Permissions { - private Permissions() {} + private Permissions() { + } /* * GENERAL */ - public static boolean motd(Permissible permissible) { return permissible.hasPermission("mcmmo.motd"); } - public static boolean mobHealthDisplay(Permissible permissible) { return permissible.hasPermission("mcmmo.mobhealthdisplay"); } - public static boolean updateNotifications(Permissible permissible) {return permissible.hasPermission("mcmmo.tools.updatecheck"); } - public static boolean chimaeraWing(Permissible permissible) { return permissible.hasPermission("mcmmo.item.chimaerawing"); } - public static boolean showversion(Permissible permissible) { return permissible.hasPermission("mcmmo.showversion"); } + public static boolean motd(Permissible permissible) { + return permissible.hasPermission("mcmmo.motd"); + } + + public static boolean mobHealthDisplay(Permissible permissible) { + return permissible.hasPermission("mcmmo.mobhealthdisplay"); + } + + public static boolean updateNotifications(Permissible permissible) { + return permissible.hasPermission("mcmmo.tools.updatecheck"); + } + + public static boolean chimaeraWing(Permissible permissible) { + return permissible.hasPermission("mcmmo.item.chimaerawing"); + } + + public static boolean showversion(Permissible permissible) { + return permissible.hasPermission("mcmmo.showversion"); + } /* BYPASS */ - public static boolean hardcoreBypass(Permissible permissible) { return permissible.hasPermission("mcmmo.bypass.hardcoremode"); } - public static boolean arcaneBypass(Permissible permissible) { return permissible.hasPermission("mcmmo.bypass.arcanebypass"); } - public static boolean trapsBypass(Permissible permissible) { return permissible.hasPermission("mcmmo.bypass.fishingtraps"); } + public static boolean hardcoreBypass(Permissible permissible) { + return permissible.hasPermission("mcmmo.bypass.hardcoremode"); + } + + public static boolean arcaneBypass(Permissible permissible) { + return permissible.hasPermission("mcmmo.bypass.arcanebypass"); + } + + public static boolean trapsBypass(Permissible permissible) { + return permissible.hasPermission("mcmmo.bypass.fishingtraps"); + } /* CHAT */ - public static boolean partyChat(Permissible permissible) { return permissible.hasPermission("mcmmo.chat.partychat"); } - public static boolean adminChat(Permissible permissible) { return permissible.hasPermission("mcmmo.chat.adminchat"); } + public static boolean partyChat(Permissible permissible) { + return permissible.hasPermission("mcmmo.chat.partychat"); + } + + public static boolean adminChat(Permissible permissible) { + return permissible.hasPermission("mcmmo.chat.adminchat"); + } /* * COMMANDS */ - public static boolean mmoinfo(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.mmoinfo"); } - public static boolean addlevels(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.addlevels"); } - public static boolean addlevelsOthers(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.addlevels.others"); } + public static boolean mmoinfo(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.mmoinfo"); + } - public static boolean addxp(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.addxp"); } - public static boolean addxpOthers(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.addxp.others"); } + public static boolean addlevels(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.addlevels"); + } - public static boolean hardcoreModify(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.hardcore.modify"); } - public static boolean hardcoreToggle(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.hardcore.toggle"); } + public static boolean addlevelsOthers(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.addlevels.others"); + } - public static boolean inspect(Permissible permissible) { return (permissible.hasPermission("mcmmo.commands.inspect")); } - public static boolean inspectFar(Permissible permissible) { return (permissible.hasPermission("mcmmo.commands.inspect.far")); } - public static boolean inspectHidden(Permissible permissible) { return (permissible.hasPermission("mcmmo.commands.inspect.hidden")); } - public static boolean inspectOffline(Permissible permissible) { return (permissible.hasPermission("mcmmo.commands.inspect.offline")); } + public static boolean addxp(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.addxp"); + } - public static boolean mcability(Permissible permissible) { return (permissible.hasPermission("mcmmo.commands.mcability")); } - public static boolean mcabilityOthers(Permissible permissible) { return (permissible.hasPermission("mcmmo.commands.mcability.others")); } + public static boolean addxpOthers(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.addxp.others"); + } - public static boolean adminChatSpy(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.mcchatspy");} - public static boolean adminChatSpyOthers(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.mcchatspy.others");} + public static boolean hardcoreModify(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.hardcore.modify"); + } - public static boolean mcgod(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.mcgod"); } - public static boolean mcgodOthers(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.mcgod.others"); } + public static boolean hardcoreToggle(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.hardcore.toggle"); + } - public static boolean mcmmoDescription(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.mcmmo.description"); } - public static boolean mcmmoHelp(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.mcmmo.help"); } + public static boolean inspect(Permissible permissible) { + return (permissible.hasPermission("mcmmo.commands.inspect")); + } - public static boolean mcrank(Permissible permissible) { return (permissible.hasPermission("mcmmo.commands.mcrank")); } - public static boolean mcrankOthers(Permissible permissible) { return (permissible.hasPermission("mcmmo.commands.mcrank.others")); } - public static boolean mcrankFar(Permissible permissible) { return (permissible.hasPermission("mcmmo.commands.mcrank.others.far")); } - public static boolean mcrankOffline(Permissible permissible) { return (permissible.hasPermission("mcmmo.commands.mcrank.others.offline")); } + public static boolean inspectFar(Permissible permissible) { + return (permissible.hasPermission("mcmmo.commands.inspect.far")); + } - public static boolean mcrefresh(Permissible permissible) { return (permissible.hasPermission("mcmmo.commands.mcrefresh")); } - public static boolean mcrefreshOthers(Permissible permissible) { return (permissible.hasPermission("mcmmo.commands.mcrefresh.others")); } + public static boolean inspectHidden(Permissible permissible) { + return (permissible.hasPermission("mcmmo.commands.inspect.hidden")); + } - public static boolean mctop(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.commands.mctop." + skill.toString().toLowerCase()); } + public static boolean inspectOffline(Permissible permissible) { + return (permissible.hasPermission("mcmmo.commands.inspect.offline")); + } - public static boolean mmoedit(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.mmoedit"); } - public static boolean mmoeditOthers(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.mmoedit.others"); } + public static boolean mcability(Permissible permissible) { + return (permissible.hasPermission("mcmmo.commands.mcability")); + } - public static boolean skillreset(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.skillreset"); } - public static boolean skillreset(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.commands.skillreset." + skill.toString().toLowerCase()); } - public static boolean skillresetOthers(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.skillreset.others"); } - public static boolean skillresetOthers(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.commands.skillreset.others." + skill.toString().toLowerCase()); } + public static boolean mcabilityOthers(Permissible permissible) { + return (permissible.hasPermission("mcmmo.commands.mcability.others")); + } - public static boolean xplock(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.commands.xplock." + skill.toString().toLowerCase()); } + public static boolean adminChatSpy(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.mcchatspy"); + } - public static boolean xprateSet(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.xprate.set"); } - public static boolean xprateReset(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.xprate.reset"); } + public static boolean adminChatSpyOthers(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.mcchatspy.others"); + } - public static boolean vampirismModify(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.vampirism.modify"); } - public static boolean vampirismToggle(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.vampirism.toggle"); } + public static boolean mcgod(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.mcgod"); + } - public static boolean mcpurge(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.mcpurge"); } - public static boolean mcremove(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.mcremove"); } - public static boolean mmoupdate(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.mmoupdate"); } + public static boolean mcgodOthers(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.mcgod.others"); + } + + public static boolean mcmmoDescription(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.mcmmo.description"); + } + + public static boolean mcmmoHelp(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.mcmmo.help"); + } + + public static boolean mcrank(Permissible permissible) { + return (permissible.hasPermission("mcmmo.commands.mcrank")); + } + + public static boolean mcrankOthers(Permissible permissible) { + return (permissible.hasPermission("mcmmo.commands.mcrank.others")); + } + + public static boolean mcrankFar(Permissible permissible) { + return (permissible.hasPermission("mcmmo.commands.mcrank.others.far")); + } + + public static boolean mcrankOffline(Permissible permissible) { + return (permissible.hasPermission("mcmmo.commands.mcrank.others.offline")); + } + + public static boolean mcrefresh(Permissible permissible) { + return (permissible.hasPermission("mcmmo.commands.mcrefresh")); + } + + public static boolean mcrefreshOthers(Permissible permissible) { + return (permissible.hasPermission("mcmmo.commands.mcrefresh.others")); + } + + public static boolean mctop(Permissible permissible, PrimarySkillType skill) { + return permissible.hasPermission("mcmmo.commands.mctop." + skill.toString().toLowerCase()); + } + + public static boolean mmoedit(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.mmoedit"); + } + + public static boolean mmoeditOthers(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.mmoedit.others"); + } + + public static boolean skillreset(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.skillreset"); + } + + public static boolean skillreset(Permissible permissible, PrimarySkillType skill) { + return permissible.hasPermission("mcmmo.commands.skillreset." + skill.toString().toLowerCase()); + } + + public static boolean skillresetOthers(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.skillreset.others"); + } + + public static boolean skillresetOthers(Permissible permissible, PrimarySkillType skill) { + return permissible.hasPermission("mcmmo.commands.skillreset.others." + skill.toString().toLowerCase()); + } + + public static boolean xplock(Permissible permissible, PrimarySkillType skill) { + return permissible.hasPermission("mcmmo.commands.xplock." + skill.toString().toLowerCase()); + } + + public static boolean xprateSet(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.xprate.set"); + } + + public static boolean xprateReset(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.xprate.reset"); + } + + public static boolean vampirismModify(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.vampirism.modify"); + } + + public static boolean vampirismToggle(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.vampirism.toggle"); + } + + public static boolean mcpurge(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.mcpurge"); + } + + public static boolean mcremove(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.mcremove"); + } + + public static boolean mmoupdate(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.mmoupdate"); + } /* * PERKS @@ -104,114 +235,270 @@ public final class Permissions { /* BYPASS PERKS */ - public static boolean hasRepairEnchantBypassPerk(Permissible permissible) { return permissible.hasPermission("mcmmo.perks.bypass.repairenchant"); } - public static boolean hasSalvageEnchantBypassPerk(Permissible permissible) { return permissible.hasPermission("mcmmo.perks.bypass.salvageenchant"); } + public static boolean hasRepairEnchantBypassPerk(Permissible permissible) { + return permissible.hasPermission("mcmmo.perks.bypass.repairenchant"); + } - public static boolean lucky(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.lucky." + skill.toString().toLowerCase()); } + public static boolean hasSalvageEnchantBypassPerk(Permissible permissible) { + return permissible.hasPermission("mcmmo.perks.bypass.salvageenchant"); + } + + public static boolean lucky(Permissible permissible, PrimarySkillType skill) { + return permissible.hasPermission("mcmmo.perks.lucky." + skill.toString().toLowerCase()); + } /* XP PERKS */ - public static boolean quadrupleXp(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.xp.quadruple." + skill.toString().toLowerCase()); } - public static boolean tripleXp(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.xp.triple." + skill.toString().toLowerCase()); } - public static boolean doubleAndOneHalfXp(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.xp.150percentboost." + skill.toString().toLowerCase()); } - public static boolean doubleXp(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.xp.double." + skill.toString().toLowerCase()); } - public static boolean oneAndOneHalfXp(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.xp.50percentboost." + skill.toString().toLowerCase()); } - public static boolean oneAndOneTenthXp(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.xp.10percentboost." + skill.toString().toLowerCase()); } - public static boolean customXpBoost(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.xp.customboost." + skill.toString().toLowerCase()); } + public static boolean quadrupleXp(Permissible permissible, PrimarySkillType skill) { + return permissible.hasPermission("mcmmo.perks.xp.quadruple." + skill.toString().toLowerCase()); + } + + public static boolean tripleXp(Permissible permissible, PrimarySkillType skill) { + return permissible.hasPermission("mcmmo.perks.xp.triple." + skill.toString().toLowerCase()); + } + + public static boolean doubleAndOneHalfXp(Permissible permissible, PrimarySkillType skill) { + return permissible.hasPermission("mcmmo.perks.xp.150percentboost." + skill.toString().toLowerCase()); + } + + public static boolean doubleXp(Permissible permissible, PrimarySkillType skill) { + return permissible.hasPermission("mcmmo.perks.xp.double." + skill.toString().toLowerCase()); + } + + public static boolean oneAndOneHalfXp(Permissible permissible, PrimarySkillType skill) { + return permissible.hasPermission("mcmmo.perks.xp.50percentboost." + skill.toString().toLowerCase()); + } + + public static boolean oneAndOneTenthXp(Permissible permissible, PrimarySkillType skill) { + return permissible.hasPermission("mcmmo.perks.xp.10percentboost." + skill.toString().toLowerCase()); + } + + public static boolean customXpBoost(Permissible permissible, PrimarySkillType skill) { + return permissible.hasPermission("mcmmo.perks.xp.customboost." + skill.toString().toLowerCase()); + } /* ACTIVATION PERKS */ - public static boolean twelveSecondActivationBoost(Permissible permissible) { return permissible.hasPermission("mcmmo.perks.activationtime.twelveseconds"); } - public static boolean eightSecondActivationBoost(Permissible permissible) { return permissible.hasPermission("mcmmo.perks.activationtime.eightseconds"); } - public static boolean fourSecondActivationBoost(Permissible permissible) { return permissible.hasPermission("mcmmo.perks.activationtime.fourseconds"); } + public static boolean twelveSecondActivationBoost(Permissible permissible) { + return permissible.hasPermission("mcmmo.perks.activationtime.twelveseconds"); + } + + public static boolean eightSecondActivationBoost(Permissible permissible) { + return permissible.hasPermission("mcmmo.perks.activationtime.eightseconds"); + } + + public static boolean fourSecondActivationBoost(Permissible permissible) { + return permissible.hasPermission("mcmmo.perks.activationtime.fourseconds"); + } /* COOLDOWN PERKS */ - public static boolean halvedCooldowns(Permissible permissible) { return permissible.hasPermission("mcmmo.perks.cooldowns.halved"); } - public static boolean thirdedCooldowns(Permissible permissible) { return permissible.hasPermission("mcmmo.perks.cooldowns.thirded"); } - public static boolean quarteredCooldowns(Permissible permissible) { return permissible.hasPermission("mcmmo.perks.cooldowns.quartered"); } + public static boolean halvedCooldowns(Permissible permissible) { + return permissible.hasPermission("mcmmo.perks.cooldowns.halved"); + } + + public static boolean thirdedCooldowns(Permissible permissible) { + return permissible.hasPermission("mcmmo.perks.cooldowns.thirded"); + } + + public static boolean quarteredCooldowns(Permissible permissible) { + return permissible.hasPermission("mcmmo.perks.cooldowns.quartered"); + } /* * SKILLS */ - public static boolean skillEnabled(Permissible permissible, PrimarySkillType skill) {return permissible.hasPermission("mcmmo.skills." + skill.toString().toLowerCase()); } - public static boolean vanillaXpBoost(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.ability." + skill.toString().toLowerCase() + ".vanillaxpboost"); } - public static boolean isSubSkillEnabled(Permissible permissible, SubSkillType subSkillType) { return permissible.hasPermission(subSkillType.getPermissionNodeAddress()); } - public static boolean isSubSkillEnabled(Permissible permissible, AbstractSubSkill abstractSubSkill) { return permissible.hasPermission(abstractSubSkill.getPermissionNode()); } - public static boolean bonusDamage(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.ability." + skill.toString().toLowerCase() + ".bonusdamage"); } + public static boolean skillEnabled(Permissible permissible, PrimarySkillType skill) { + return permissible.hasPermission("mcmmo.skills." + skill.toString().toLowerCase()); + } + + public static boolean vanillaXpBoost(Permissible permissible, PrimarySkillType skill) { + return permissible.hasPermission("mcmmo.ability." + skill.toString().toLowerCase() + ".vanillaxpboost"); + } + + public static boolean isSubSkillEnabled(Permissible permissible, SubSkillType subSkillType) { + return permissible.hasPermission(subSkillType.getPermissionNodeAddress()); + } + + public static boolean isSubSkillEnabled(Permissible permissible, AbstractSubSkill abstractSubSkill) { + return permissible.hasPermission(abstractSubSkill.getPermissionNode()); + } + + public static boolean bonusDamage(Permissible permissible, PrimarySkillType skill) { + return permissible.hasPermission("mcmmo.ability." + skill.toString().toLowerCase() + ".bonusdamage"); + } /* ACROBATICS */ - public static boolean dodge(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.acrobatics.dodge"); } - public static boolean gracefulRoll(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.acrobatics.gracefulroll"); } - public static boolean roll(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.acrobatics.roll"); } + public static boolean dodge(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.acrobatics.dodge"); + } + + public static boolean gracefulRoll(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.acrobatics.gracefulroll"); + } + + public static boolean roll(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.acrobatics.roll"); + } /* ALCHEMY */ - public static boolean catalysis(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.alchemy.catalysis"); } - public static boolean concoctions(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.alchemy.concoctions"); } + public static boolean catalysis(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.alchemy.catalysis"); + } + + public static boolean concoctions(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.alchemy.concoctions"); + } /* ARCHERY */ - public static boolean arrowRetrieval(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.archery.trackarrows"); } - public static boolean daze(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.archery.daze"); } + public static boolean arrowRetrieval(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.archery.trackarrows"); + } + + public static boolean daze(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.archery.daze"); + } /* AXES */ - public static boolean skullSplitter(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.axes.skullsplitter"); } + public static boolean skullSplitter(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.axes.skullsplitter"); + } /* EXCAVATION */ - public static boolean gigaDrillBreaker(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.excavation.gigadrillbreaker"); } + public static boolean gigaDrillBreaker(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.excavation.gigadrillbreaker"); + } /* HERBALISM */ - public static boolean greenTerra(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.herbalism.greenterra"); } - public static boolean greenThumbBlock(Permissible permissible, Material material) { return permissible.hasPermission("mcmmo.ability.herbalism.greenthumb.blocks." + material.toString().replace("_", "").toLowerCase()); } - public static boolean greenThumbPlant(Permissible permissible, Material material) { return permissible.hasPermission("mcmmo.ability.herbalism.greenthumb.plants." + material.toString().replace("_", "").toLowerCase()); } + public static boolean greenTerra(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.herbalism.greenterra"); + } + + public static boolean greenThumbBlock(Permissible permissible, Material material) { + return permissible.hasPermission("mcmmo.ability.herbalism.greenthumb.blocks." + material.toString().replace("_", "").toLowerCase()); + } + + public static boolean greenThumbPlant(Permissible permissible, Material material) { + return permissible.hasPermission("mcmmo.ability.herbalism.greenthumb.plants." + material.toString().replace("_", "").toLowerCase()); + } /* MINING */ - public static boolean biggerBombs(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.mining.blastmining.biggerbombs"); } - public static boolean demolitionsExpertise(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.mining.blastmining.demolitionsexpertise"); } - public static boolean remoteDetonation(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.mining.blastmining.detonate"); } - public static boolean superBreaker(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.mining.superbreaker"); } + public static boolean biggerBombs(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.mining.blastmining.biggerbombs"); + } + + public static boolean demolitionsExpertise(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.mining.blastmining.demolitionsexpertise"); + } + + public static boolean remoteDetonation(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.mining.blastmining.detonate"); + } + + public static boolean superBreaker(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.mining.superbreaker"); + } /* REPAIR */ - public static boolean repairItemType(Permissible permissible, ItemType repairItemType) { return permissible.hasPermission("mcmmo.ability.repair." + repairItemType.toString().toLowerCase() + "repair"); } - public static boolean repairMaterialType(Permissible permissible, ItemMaterialCategory repairItemMaterialCategory) { return permissible.hasPermission("mcmmo.ability.repair." + repairItemMaterialCategory.toString().toLowerCase() + "repair"); } + public static boolean repairItemType(Permissible permissible, ItemType repairItemType) { + return permissible.hasPermission("mcmmo.ability.repair." + repairItemType.toString().toLowerCase() + "repair"); + } + + public static boolean repairMaterialType(Permissible permissible, ItemMaterialCategory repairItemMaterialCategory) { + return permissible.hasPermission("mcmmo.ability.repair." + repairItemMaterialCategory.toString().toLowerCase() + "repair"); + } /* SALVAGE */ - public static boolean advancedSalvage(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.salvage.advancedsalvage"); } - public static boolean arcaneSalvage(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.salvage.arcanesalvage"); } + public static boolean advancedSalvage(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.salvage.advancedsalvage"); + } - public static boolean salvageItemType(Permissible permissible, ItemType salvageItemType) { return permissible.hasPermission("mcmmo.ability.salvage." + salvageItemType.toString().toLowerCase() + "salvage"); } - public static boolean salvageMaterialType(Permissible permissible, ItemMaterialCategory salvageItemMaterialCategory) { return permissible.hasPermission("mcmmo.ability.salvage." + salvageItemMaterialCategory.toString().toLowerCase() + "salvage"); } + public static boolean arcaneSalvage(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.salvage.arcanesalvage"); + } + + public static boolean salvageItemType(Permissible permissible, ItemType salvageItemType) { + return permissible.hasPermission("mcmmo.ability.salvage." + salvageItemType.toString().toLowerCase() + "salvage"); + } + + public static boolean salvageMaterialType(Permissible permissible, ItemMaterialCategory salvageItemMaterialCategory) { + return permissible.hasPermission("mcmmo.ability.salvage." + salvageItemMaterialCategory.toString().toLowerCase() + "salvage"); + } /* SMELTING */ - public static boolean fluxMining(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.smelting.fluxmining"); } - public static boolean fuelEfficiency(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.smelting.fuelefficiency"); } + public static boolean fluxMining(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.smelting.fluxmining"); + } + + public static boolean fuelEfficiency(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.smelting.fuelefficiency"); + } /* SWORDS */ - public static boolean serratedStrikes(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.swords.serratedstrikes"); } + public static boolean serratedStrikes(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.swords.serratedstrikes"); + } /* TAMING */ - public static boolean callOfTheWild(Permissible permissible, EntityType type) { return permissible.hasPermission("mcmmo.ability.taming.callofthewild." + type.toString().toLowerCase()); } - public static boolean renamePets(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.taming.callofthewild.renamepets"); } + public static boolean callOfTheWild(Permissible permissible, EntityType type) { + return permissible.hasPermission("mcmmo.ability.taming.callofthewild." + type.toString().toLowerCase()); + } + + public static boolean renamePets(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.taming.callofthewild.renamepets"); + } /* UNARMED */ - public static boolean berserk(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.unarmed.berserk"); } + public static boolean berserk(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.unarmed.berserk"); + } /* WOODCUTTING */ - public static boolean treeFeller(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.woodcutting.treefeller"); } + public static boolean treeFeller(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.woodcutting.treefeller"); + } /* * PARTY */ - public static boolean partySizeBypass(Permissible permissible) { return permissible.hasPermission("mcmmo.bypass.partylimit" ); } - public static boolean party(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.party"); } - public static boolean partySubcommand(Permissible permissible, PartySubcommandType subcommand) { return permissible.hasPermission("mcmmo.commands.party." + subcommand.toString().toLowerCase()); } - public static boolean friendlyFire(Permissible permissible) { return permissible.hasPermission("mcmmo.party.friendlyfire"); } + public static boolean partySizeBypass(Permissible permissible) { + return permissible.hasPermission("mcmmo.bypass.partylimit"); + } + + public static boolean party(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.party"); + } + + public static boolean partySubcommand(Permissible permissible, PartySubcommandType subcommand) { + return permissible.hasPermission("mcmmo.commands.party." + subcommand.toString().toLowerCase()); + } + + public static boolean friendlyFire(Permissible permissible) { + return permissible.hasPermission("mcmmo.party.friendlyfire"); + } /* TELEPORT */ - public static boolean partyTeleportSend(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.ptp.send"); } - public static boolean partyTeleportAccept(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.ptp.accept"); } - public static boolean partyTeleportAcceptAll(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.ptp.acceptall"); } - public static boolean partyTeleportToggle(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.ptp.toggle"); } + public static boolean partyTeleportSend(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.ptp.send"); + } - public static boolean partyTeleportAllWorlds(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.ptp.world.all"); } - public static boolean partyTeleportWorld(Permissible permissible, World world) { return permissible.hasPermission("mcmmo.commands.ptp.world." + world.getName()); } + public static boolean partyTeleportAccept(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.ptp.accept"); + } + + public static boolean partyTeleportAcceptAll(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.ptp.acceptall"); + } + + public static boolean partyTeleportToggle(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.ptp.toggle"); + } + + public static boolean partyTeleportAllWorlds(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.ptp.world.all"); + } + + public static boolean partyTeleportWorld(Permissible permissible, World world) { + return permissible.hasPermission("mcmmo.commands.ptp.world." + world.getName()); + } public static void generateWorldTeleportPermissions() { Server server = mcMMO.p.getServer(); diff --git a/src/main/java/com/gmail/nossr50/util/StringUtils.java b/src/main/java/com/gmail/nossr50/util/StringUtils.java index 6649fe0ee..1b6fed8fc 100644 --- a/src/main/java/com/gmail/nossr50/util/StringUtils.java +++ b/src/main/java/com/gmail/nossr50/util/StringUtils.java @@ -12,8 +12,7 @@ public class StringUtils { /** * Gets a capitalized version of the target string. * - * @param target - * String to capitalize + * @param target String to capitalize * @return the capitalized string */ public static String getCapitalized(String target) { @@ -22,11 +21,11 @@ public class StringUtils { /** * Gets the name of the entity that the config file is expecting + * * @param entityType target entity type * @return the config friendly entity type string */ - public static String getEntityConfigName(EntityType entityType) - { + public static String getEntityConfigName(EntityType entityType) { return getCapitalized(entityType.toString()); } @@ -41,7 +40,7 @@ public class StringUtils { public static String getPrettyAbilityString(SuperAbilityType ability) { return createPrettyString(ability.toString()); } - + public static String getWildcardConfigBlockDataString(BlockData data) { return getWildcardConfigMaterialString(data.getMaterial()); } @@ -51,7 +50,7 @@ public class StringUtils { } public static String getFriendlyConfigBlockDataString(BlockData data) { - switch(data.getMaterial()){ + switch (data.getMaterial()) { case CHORUS_FLOWER: case COCOA: case WHEAT: @@ -108,8 +107,7 @@ public class StringUtils { /** * Determine if a string represents an Integer * - * @param string - * String to check + * @param string String to check * @return true if the string is an Integer, false otherwise */ public static boolean isInt(String string) { @@ -124,8 +122,7 @@ public class StringUtils { /** * Determine if a string represents a Double * - * @param string - * String to check + * @param string String to check * @return true if the string is a Double, false otherwise */ public static boolean isDouble(String string) { diff --git a/src/main/java/com/gmail/nossr50/util/TextComponentFactory.java b/src/main/java/com/gmail/nossr50/util/TextComponentFactory.java index 44f6d5fa3..b78ff6f8c 100644 --- a/src/main/java/com/gmail/nossr50/util/TextComponentFactory.java +++ b/src/main/java/com/gmail/nossr50/util/TextComponentFactory.java @@ -26,38 +26,34 @@ public class TextComponentFactory { /** * Makes a text component using strings from a locale and supports passing an undefined number of variables to the LocaleLoader - * @param localeKey target locale string address + * + * @param localeKey target locale string address * @param notificationType type of notification - * @param values vars to be passed to the locale loader + * @param values vars to be passed to the locale loader * @return */ - public static TextComponent getNotificationMultipleValues(String localeKey, NotificationType notificationType, String... values) - { + public static TextComponent getNotificationMultipleValues(String localeKey, NotificationType notificationType, String... values) { String preColoredString = LocaleLoader.getString(localeKey, (Object[]) values); TextComponent msg = new TextComponent(preColoredString); return new TextComponent(msg); } - public static TextComponent getNotificationTextComponentFromLocale(String localeKey, NotificationType notificationType) - { + public static TextComponent getNotificationTextComponentFromLocale(String localeKey, NotificationType notificationType) { return getNotificationTextComponent(LocaleLoader.getString(localeKey)); } - public static TextComponent getNotificationLevelUpTextComponent(PrimarySkillType skill, int levelsGained, int currentLevel) - { - TextComponent textComponent = new TextComponent(LocaleLoader.getString("Overhaul.Levelup", LocaleLoader.getString("Overhaul.Name."+StringUtils.getCapitalized(skill.toString())), levelsGained, currentLevel)); + public static TextComponent getNotificationLevelUpTextComponent(PrimarySkillType skill, int levelsGained, int currentLevel) { + TextComponent textComponent = new TextComponent(LocaleLoader.getString("Overhaul.Levelup", LocaleLoader.getString("Overhaul.Name." + StringUtils.getCapitalized(skill.toString())), levelsGained, currentLevel)); return textComponent; } - private static TextComponent getNotificationTextComponent(String text) - { + private static TextComponent getNotificationTextComponent(String text) { //textComponent.setColor(getNotificationColor(notificationType)); return new TextComponent(text); } - public static void sendPlayerSubSkillWikiLink(Player player, String subskillformatted) - { - if(!mcMMO.getConfigManager().getConfigAds().isShowWebsiteLinks()) + public static void sendPlayerSubSkillWikiLink(Player player, String subskillformatted) { + if (!mcMMO.getConfigManager().getConfigAds().isShowWebsiteLinks()) return; Player.Spigot spigotPlayer = player.spigot(); @@ -65,7 +61,7 @@ public class TextComponentFactory { TextComponent wikiLinkComponent = new TextComponent(LocaleLoader.getString("Overhaul.mcMMO.MmoInfo.Wiki")); wikiLinkComponent.setUnderlined(true); - String wikiUrl = "https://mcmmo.org/wiki/"+subskillformatted; + String wikiUrl = "https://mcmmo.org/wiki/" + subskillformatted; wikiLinkComponent.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, wikiUrl)); @@ -81,13 +77,12 @@ public class TextComponentFactory { TextComponent prefix = new TextComponent(LocaleLoader.getString("Overhaul.mcMMO.Url.Wrap.Prefix") + " "); /*prefix.setColor(ChatColor.DARK_AQUA);*/ - TextComponent suffix = new TextComponent(" "+LocaleLoader.getString("Overhaul.mcMMO.Url.Wrap.Suffix")); + TextComponent suffix = new TextComponent(" " + LocaleLoader.getString("Overhaul.mcMMO.Url.Wrap.Suffix")); /*suffix.setColor(ChatColor.DARK_AQUA);*/ TextComponent emptySpace = new TextComponent(" "); - if(mcMMO.getConfigManager().getConfigAds().isShowPatreonInfo()) - { + if (mcMMO.getConfigManager().getConfigAds().isShowPatreonInfo()) { BaseComponent[] baseComponents = {new TextComponent(prefix), getWebLinkTextComponent(McMMOWebLinks.WEBSITE), emptySpace, @@ -120,8 +115,7 @@ public class TextComponentFactory { } } - public static void sendPlayerSubSkillList(Player player, List textComponents) - { + public static void sendPlayerSubSkillList(Player player, List textComponents) { TextComponent emptySpace = new TextComponent(" "); ArrayList bulkMessage = new ArrayList<>(); @@ -129,8 +123,7 @@ public class TextComponentFactory { for (TextComponent textComponent : textComponents) { //Don't send more than 3 subskills per line to avoid MOST wordwrap problems - if(newLineCount > 2) - { + if (newLineCount > 2) { TextComponent[] bulkArray = new TextComponent[bulkMessage.size()]; bulkArray = bulkMessage.toArray(bulkArray); @@ -144,10 +137,10 @@ public class TextComponentFactory { TextComponent stylizedText = new TextComponent(LocaleLoader.getString("JSON.Hover.AtSymbolSkills")); addChild(stylizedText, originalTxt); - if(textComponent.getHoverEvent() != null) + if (textComponent.getHoverEvent() != null) stylizedText.setHoverEvent(textComponent.getHoverEvent()); - if(textComponent.getClickEvent() != null) + if (textComponent.getClickEvent() != null) stylizedText.setClickEvent(textComponent.getClickEvent()); bulkMessage.add(stylizedText); @@ -165,12 +158,10 @@ public class TextComponentFactory { player.spigot().sendMessage(bulkArray); } - private static TextComponent getWebLinkTextComponent(McMMOWebLinks webLinks) - { + private static TextComponent getWebLinkTextComponent(McMMOWebLinks webLinks) { TextComponent webTextComponent; - switch(webLinks) - { + switch (webLinks) { case WEBSITE: webTextComponent = new TextComponent(LocaleLoader.getString("JSON.Hover.AtSymbolURL")); addChild(webTextComponent, "Web"); @@ -217,12 +208,10 @@ public class TextComponentFactory { webTextComponent.addExtra(childComponent); } - private static BaseComponent[] getUrlHoverEvent(McMMOWebLinks webLinks) - { + private static BaseComponent[] getUrlHoverEvent(McMMOWebLinks webLinks) { ComponentBuilder componentBuilder = new ComponentBuilder(webLinks.getNiceTitle()); - switch(webLinks) - { + switch (webLinks) { case WEBSITE: addUrlHeaderHover(webLinks, componentBuilder); componentBuilder.append("\n\n").italic(false); @@ -271,13 +260,11 @@ public class TextComponentFactory { componentBuilder.append(webLinks.getUrl()).color(ChatColor.GRAY).italic(true); } - private static ClickEvent getUrlClickEvent(String url) - { + private static ClickEvent getUrlClickEvent(String url) { return new ClickEvent(ClickEvent.Action.OPEN_URL, url); } - private static TextComponent getSubSkillTextComponent(Player player, SubSkillType subSkillType) - { + private static TextComponent getSubSkillTextComponent(Player player, SubSkillType subSkillType) { //Get skill name String skillName = subSkillType.getLocaleName(); @@ -298,8 +285,7 @@ public class TextComponentFactory { textComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, baseComponent)); } - private static TextComponent getSubSkillTextComponent(Player player, AbstractSubSkill abstractSubSkill) - { + private static TextComponent getSubSkillTextComponent(Player player, AbstractSubSkill abstractSubSkill) { //String key = abstractSubSkill.getConfigKeyName(); String skillName = abstractSubSkill.getNiceName(); @@ -338,47 +324,44 @@ public class TextComponentFactory { return textComponent; } - private static BaseComponent[] getSubSkillHoverComponent(Player player, AbstractSubSkill abstractSubSkill) - { + private static BaseComponent[] getSubSkillHoverComponent(Player player, AbstractSubSkill abstractSubSkill) { return getSubSkillHoverEventJSON(abstractSubSkill, player); } - private static BaseComponent[] getSubSkillHoverComponent(Player player, SubSkillType subSkillType) - { + private static BaseComponent[] getSubSkillHoverComponent(Player player, SubSkillType subSkillType) { return getSubSkillHoverEventJSON(subSkillType, player); } /** * Used for the skill in the new skill system (Deriving from AbstractSubSkill) + * * @param abstractSubSkill this subskill - * @param player the player who owns this subskill + * @param player the player who owns this subskill * @return the hover basecomponent object for this subskill */ - private static BaseComponent[] getSubSkillHoverEventJSON(AbstractSubSkill abstractSubSkill, Player player) - { + private static BaseComponent[] getSubSkillHoverEventJSON(AbstractSubSkill abstractSubSkill, Player player) { String skillName = abstractSubSkill.getNiceName(); /* * Hover Event BaseComponent color table */ - ChatColor ccSubSkillHeader = ChatColor.GOLD; - ChatColor ccRank = ChatColor.BLUE; - ChatColor ccCurRank = ChatColor.GREEN; - ChatColor ccPossessive = ChatColor.WHITE; - ChatColor ccNumRanks = ccCurRank; + ChatColor ccSubSkillHeader = ChatColor.GOLD; + ChatColor ccRank = ChatColor.BLUE; + ChatColor ccCurRank = ChatColor.GREEN; + ChatColor ccPossessive = ChatColor.WHITE; + ChatColor ccNumRanks = ccCurRank; //ChatColor ccDescriptionHeader = ChatColor.DARK_PURPLE; //ChatColor ccDescription = ChatColor.WHITE; - ChatColor ccLocked = ChatColor.DARK_GRAY; - ChatColor ccLevelRequirement = ChatColor.BLUE; - ChatColor ccLevelRequired = ChatColor.RED; + ChatColor ccLocked = ChatColor.DARK_GRAY; + ChatColor ccLevelRequirement = ChatColor.BLUE; + ChatColor ccLevelRequired = ChatColor.RED; SubSkillType subSkillType = abstractSubSkill.getSubSkillType(); //SubSkillType Name ComponentBuilder componentBuilder = setupSkillComponentNameStyle(player, skillName, subSkillType, RankUtils.hasUnlockedSubskill(player, abstractSubSkill)); - if(!RankUtils.hasUnlockedSubskill(player, abstractSubSkill)) - { + if (!RankUtils.hasUnlockedSubskill(player, abstractSubSkill)) { //Skill is not unlocked yet addLocked(abstractSubSkill, ccLocked, ccLevelRequirement, ccLevelRequired, componentBuilder); } else { @@ -388,9 +371,8 @@ public class TextComponentFactory { int curRank = RankUtils.getRank(player, abstractSubSkill); int nextRank = 0; - if(curRank < abstractSubSkill.getNumRanks() && abstractSubSkill.getNumRanks() > 0) - { - nextRank = RankUtils.getRankUnlockLevel(abstractSubSkill, curRank+1); + if (curRank < abstractSubSkill.getNumRanks() && abstractSubSkill.getNumRanks() > 0) { + nextRank = RankUtils.getRankUnlockLevel(abstractSubSkill, curRank + 1); } addRanked(ccRank, ccCurRank, ccPossessive, ccNumRanks, componentBuilder, abstractSubSkill.getNumRanks(), RankUtils.getRank(player, abstractSubSkill), nextRank); @@ -435,7 +417,7 @@ public class TextComponentFactory { .bold(false).italic(false).strikethrough(false).underlined(false); //Next Rank: x - if(nextRank > rank) + if (nextRank > rank) componentBuilder.append(LocaleLoader.getString("JSON.Hover.NextRank", String.valueOf(nextRank))).append("\n") .bold(false).italic(false).strikethrough(false).underlined(false); @@ -463,43 +445,39 @@ public class TextComponentFactory { } @Deprecated - private static BaseComponent[] getSubSkillHoverEventJSON(SubSkillType subSkillType, Player player) - { + private static BaseComponent[] getSubSkillHoverEventJSON(SubSkillType subSkillType, Player player) { String skillName = subSkillType.getLocaleName(); /* * Hover Event BaseComponent color table */ - ChatColor ccSubSkillHeader = ChatColor.GOLD; - ChatColor ccRank = ChatColor.BLUE; - ChatColor ccCurRank = ChatColor.GREEN; - ChatColor ccPossessive = ChatColor.WHITE; - ChatColor ccNumRanks = ccCurRank; - ChatColor ccDescriptionHeader = ChatColor.DARK_PURPLE; - ChatColor ccDescription = ChatColor.DARK_GRAY; - ChatColor ccLocked = ChatColor.DARK_GRAY; - ChatColor ccLevelRequirement = ChatColor.BLUE; - ChatColor ccLevelRequired = ChatColor.RED; + ChatColor ccSubSkillHeader = ChatColor.GOLD; + ChatColor ccRank = ChatColor.BLUE; + ChatColor ccCurRank = ChatColor.GREEN; + ChatColor ccPossessive = ChatColor.WHITE; + ChatColor ccNumRanks = ccCurRank; + ChatColor ccDescriptionHeader = ChatColor.DARK_PURPLE; + ChatColor ccDescription = ChatColor.DARK_GRAY; + ChatColor ccLocked = ChatColor.DARK_GRAY; + ChatColor ccLevelRequirement = ChatColor.BLUE; + ChatColor ccLevelRequired = ChatColor.RED; //SubSkillType Name ComponentBuilder componentBuilder = setupSkillComponentNameStyle(player, skillName, subSkillType, RankUtils.hasUnlockedSubskill(player, subSkillType)); - if(!RankUtils.hasUnlockedSubskill(player, subSkillType)) - { + if (!RankUtils.hasUnlockedSubskill(player, subSkillType)) { //Skill is not unlocked yet addLocked(subSkillType, ccLocked, ccLevelRequirement, ccLevelRequired, componentBuilder); } else { //addSubSkillTypeToHoverEventJSON(subSkillType, componentBuilder); //RANK - if(subSkillType.getNumRanks() > 0) - { + if (subSkillType.getNumRanks() > 0) { int curRank = RankUtils.getRank(player, subSkillType); int nextRank = 0; - if(curRank < subSkillType.getNumRanks() && subSkillType.getNumRanks() > 0) - { - nextRank = RankUtils.getRankUnlockLevel(subSkillType, curRank+1); + if (curRank < subSkillType.getNumRanks() && subSkillType.getNumRanks() > 0) { + nextRank = RankUtils.getRankUnlockLevel(subSkillType, curRank + 1); } addRanked(ccRank, ccCurRank, ccPossessive, ccNumRanks, componentBuilder, subSkillType.getNumRanks(), RankUtils.getRank(player, subSkillType), nextRank); @@ -517,14 +495,11 @@ public class TextComponentFactory { return componentBuilder.create(); } - private static void addSubSkillTypeToHoverEventJSON(AbstractSubSkill abstractSubSkill, ComponentBuilder componentBuilder) - { - if(abstractSubSkill.isSuperAbility()) - { + private static void addSubSkillTypeToHoverEventJSON(AbstractSubSkill abstractSubSkill, ComponentBuilder componentBuilder) { + if (abstractSubSkill.isSuperAbility()) { componentBuilder.append(LocaleLoader.getString("JSON.Type.SuperAbility")).color(ChatColor.LIGHT_PURPLE); componentBuilder.bold(true); - } else if(abstractSubSkill.isActiveUse()) - { + } else if (abstractSubSkill.isActiveUse()) { componentBuilder.append(LocaleLoader.getString("JSON.Type.Active")).color(ChatColor.DARK_RED); componentBuilder.bold(true); } else { @@ -536,35 +511,29 @@ public class TextComponentFactory { } public static void getSubSkillTextComponents(Player player, List textComponents, PrimarySkillType parentSkill) { - for(SubSkillType subSkillType : SubSkillType.values()) - { - if(subSkillType.getParentSkill() == parentSkill) - { - if(Permissions.isSubSkillEnabled(player, subSkillType)) - { - if(!InteractionManager.hasSubSkill(subSkillType)) + for (SubSkillType subSkillType : SubSkillType.values()) { + if (subSkillType.getParentSkill() == parentSkill) { + if (Permissions.isSubSkillEnabled(player, subSkillType)) { + if (!InteractionManager.hasSubSkill(subSkillType)) textComponents.add(TextComponentFactory.getSubSkillTextComponent(player, subSkillType)); } } } /* NEW SKILL SYSTEM */ - for(AbstractSubSkill abstractSubSkill : InteractionManager.getSubSkillList()) - { - if(abstractSubSkill.getPrimarySkill() == parentSkill) - { - if(Permissions.isSubSkillEnabled(player, abstractSubSkill)) + for (AbstractSubSkill abstractSubSkill : InteractionManager.getSubSkillList()) { + if (abstractSubSkill.getPrimarySkill() == parentSkill) { + if (Permissions.isSubSkillEnabled(player, abstractSubSkill)) textComponents.add(TextComponentFactory.getSubSkillTextComponent(player, abstractSubSkill)); } } } - public static TextComponent getSubSkillUnlockedNotificationComponents(Player player, SubSkillType subSkillType) - { + public static TextComponent getSubSkillUnlockedNotificationComponents(Player player, SubSkillType subSkillType) { TextComponent unlockMessage = new TextComponent(""); unlockMessage.setText(LocaleLoader.getString("JSON.SkillUnlockMessage", subSkillType.getLocaleName(), RankUtils.getRank(player, subSkillType))); unlockMessage.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, getSubSkillHoverComponent(player, subSkillType))); - unlockMessage.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/"+subSkillType.getParentSkill().toString().toLowerCase())); + unlockMessage.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/" + subSkillType.getParentSkill().toString().toLowerCase())); return unlockMessage; } } diff --git a/src/main/java/com/gmail/nossr50/util/adapter/BiomeAdapter.java b/src/main/java/com/gmail/nossr50/util/adapter/BiomeAdapter.java index b9d19e6eb..64c54f65a 100644 --- a/src/main/java/com/gmail/nossr50/util/adapter/BiomeAdapter.java +++ b/src/main/java/com/gmail/nossr50/util/adapter/BiomeAdapter.java @@ -7,7 +7,7 @@ import java.util.*; public class BiomeAdapter { public static final Set WATER_BIOMES; public static final Set ICE_BIOMES; - + static { List allBiomes = Arrays.asList(Biome.values()); List waterBiomes = new ArrayList<>(); @@ -26,6 +26,7 @@ public class BiomeAdapter { private static boolean isWater(String name) { return name.contains("RIVER") || name.contains("OCEAN"); } + private static boolean isCold(String name) { return (name.contains("COLD") || name.contains("ICE") || name.contains("FROZEN") || name.contains("TAIGA")) && !(name.contains("WARM")); } diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/ChunkletManager.java b/src/main/java/com/gmail/nossr50/util/blockmeta/ChunkletManager.java index feb54acd3..41c67b042 100755 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/ChunkletManager.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/ChunkletManager.java @@ -7,9 +7,9 @@ public interface ChunkletManager { /** * Loads a specific chunklet * - * @param cx Chunklet X coordinate that needs to be loaded - * @param cy Chunklet Y coordinate that needs to be loaded - * @param cz Chunklet Z coordinate that needs to be loaded + * @param cx Chunklet X coordinate that needs to be loaded + * @param cy Chunklet Y coordinate that needs to be loaded + * @param cz Chunklet Z coordinate that needs to be loaded * @param world World that the chunklet needs to be loaded in */ void loadChunklet(int cx, int cy, int cz, World world); @@ -17,9 +17,9 @@ public interface ChunkletManager { /** * Unload a specific chunklet * - * @param cx Chunklet X coordinate that needs to be unloaded - * @param cy Chunklet Y coordinate that needs to be unloaded - * @param cz Chunklet Z coordinate that needs to be unloaded + * @param cx Chunklet X coordinate that needs to be unloaded + * @param cy Chunklet Y coordinate that needs to be unloaded + * @param cz Chunklet Z coordinate that needs to be unloaded * @param world World that the chunklet needs to be unloaded from */ void unloadChunklet(int cx, int cy, int cz, World world); @@ -27,8 +27,8 @@ public interface ChunkletManager { /** * Load a given Chunk's Chunklet data * - * @param cx Chunk X coordinate that is to be loaded - * @param cz Chunk Z coordinate that is to be loaded + * @param cx Chunk X coordinate that is to be loaded + * @param cz Chunk Z coordinate that is to be loaded * @param world World that the Chunk is in */ void loadChunk(int cx, int cz, World world); @@ -36,8 +36,8 @@ public interface ChunkletManager { /** * Unload a given Chunk's Chunklet data * - * @param cx Chunk X coordinate that is to be unloaded - * @param cz Chunk Z coordinate that is to be unloaded + * @param cx Chunk X coordinate that is to be unloaded + * @param cz Chunk Z coordinate that is to be unloaded * @param world World that the Chunk is in */ void unloadChunk(int cx, int cz, World world); @@ -45,8 +45,8 @@ public interface ChunkletManager { /** * Informs the ChunkletManager a chunk is loaded * - * @param cx Chunk X coordinate that is loaded - * @param cz Chunk Z coordinate that is loaded + * @param cx Chunk X coordinate that is loaded + * @param cz Chunk Z coordinate that is loaded * @param world World that the chunk was loaded in */ void chunkLoaded(int cx, int cz, World world); @@ -54,8 +54,8 @@ public interface ChunkletManager { /** * Informs the ChunkletManager a chunk is unloaded * - * @param cx Chunk X coordinate that is unloaded - * @param cz Chunk Z coordinate that is unloaded + * @param cx Chunk X coordinate that is unloaded + * @param cz Chunk Z coordinate that is unloaded * @param world World that the chunk was unloaded in */ void chunkUnloaded(int cx, int cz, World world); @@ -94,9 +94,9 @@ public interface ChunkletManager { /** * Check to see if a given location is set to true * - * @param x X coordinate to check - * @param y Y coordinate to check - * @param z Z coordinate to check + * @param x X coordinate to check + * @param y Y coordinate to check + * @param z Z coordinate to check * @param world World to check in * @return true if the given location is set to true, false if otherwise */ @@ -113,9 +113,9 @@ public interface ChunkletManager { /** * Set a given location to true, should create stores as necessary if the location does not exist * - * @param x X coordinate to set - * @param y Y coordinate to set - * @param z Z coordinate to set + * @param x X coordinate to set + * @param y Y coordinate to set + * @param z Z coordinate to set * @param world World to set in */ void setTrue(int x, int y, int z, World world); @@ -130,9 +130,9 @@ public interface ChunkletManager { /** * Set a given location to false, should not create stores if one does not exist for the given location * - * @param x X coordinate to set - * @param y Y coordinate to set - * @param z Z coordinate to set + * @param x X coordinate to set + * @param y Y coordinate to set + * @param z Z coordinate to set * @param world World to set in */ void setFalse(int x, int y, int z, World world); diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/HashChunkletManager.java b/src/main/java/com/gmail/nossr50/util/blockmeta/HashChunkletManager.java index e634eefa7..43f500b81 100755 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/HashChunkletManager.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/HashChunkletManager.java @@ -295,7 +295,7 @@ public class HashChunkletManager implements ChunkletManager { } /** - * @param cStore ChunkletStore to save + * @param cStore ChunkletStore to save * @param location Where on the disk to put it */ private void serializeChunkletStore(ChunkletStore cStore, File location) { @@ -309,17 +309,14 @@ public class HashChunkletManager implements ChunkletManager { fileOut = new FileOutputStream(location); objOut = new ObjectOutputStream(fileOut); objOut.writeObject(cStore); - } - catch (IOException ex) { + } catch (IOException ex) { ex.printStackTrace(); - } - finally { + } finally { if (objOut != null) { try { objOut.flush(); objOut.close(); - } - catch (IOException ex) { + } catch (IOException ex) { ex.printStackTrace(); } } @@ -327,8 +324,7 @@ public class HashChunkletManager implements ChunkletManager { if (fileOut != null) { try { fileOut.close(); - } - catch (IOException ex) { + } catch (IOException ex) { ex.printStackTrace(); } } @@ -348,35 +344,29 @@ public class HashChunkletManager implements ChunkletManager { fileIn = new FileInputStream(location); objIn = new ObjectInputStream(fileIn); storeIn = (ChunkletStore) objIn.readObject(); - } - catch (IOException ex) { + } catch (IOException ex) { if (ex instanceof EOFException) { // EOF should only happen on Chunklets that somehow have been corrupted. //mcMMO.p.getLogger().severe("Chunklet data at " + location.toString() + " could not be read due to an EOFException, data in this area will be lost."); return ChunkletStoreFactory.getChunkletStore(); - } - else if (ex instanceof StreamCorruptedException) { + } else if (ex instanceof StreamCorruptedException) { // StreamCorrupted happens when the Chunklet is no good. //mcMMO.p.getLogger().severe("Chunklet data at " + location.toString() + " is corrupted, data in this area will be lost."); return ChunkletStoreFactory.getChunkletStore(); - } - else if (ex instanceof UTFDataFormatException) { + } else if (ex instanceof UTFDataFormatException) { // UTF happens when the Chunklet cannot be read or is corrupted //mcMMO.p.getLogger().severe("Chunklet data at " + location.toString() + " could not be read due to an UTFDataFormatException, data in this area will be lost."); return ChunkletStoreFactory.getChunkletStore(); } ex.printStackTrace(); - } - catch (ClassNotFoundException ex) { + } catch (ClassNotFoundException ex) { ex.printStackTrace(); - } - finally { + } finally { if (objIn != null) { try { objIn.close(); - } - catch (IOException ex) { + } catch (IOException ex) { ex.printStackTrace(); } } @@ -384,8 +374,7 @@ public class HashChunkletManager implements ChunkletManager { if (fileIn != null) { try { fileIn.close(); - } - catch (IOException ex) { + } catch (IOException ex) { ex.printStackTrace(); } } diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/NullChunkletManager.java b/src/main/java/com/gmail/nossr50/util/blockmeta/NullChunkletManager.java index 304ef8780..b9ba68985 100755 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/NullChunkletManager.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/NullChunkletManager.java @@ -5,7 +5,7 @@ import org.bukkit.block.Block; /** * A ChunkletManager implementation that does nothing and returns false for all checks. - * + *

* Useful for turning off Chunklets without actually doing much work */ public class NullChunkletManager implements ChunkletManager { diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/PrimitiveChunkletStore.java b/src/main/java/com/gmail/nossr50/util/blockmeta/PrimitiveChunkletStore.java index 8dfe3cb8d..763835d02 100755 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/PrimitiveChunkletStore.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/PrimitiveChunkletStore.java @@ -3,7 +3,9 @@ package com.gmail.nossr50.util.blockmeta; public class PrimitiveChunkletStore implements ChunkletStore { private static final long serialVersionUID = -3453078050608607478L; - /** X, Z, Y */ + /** + * X, Z, Y + */ public boolean[][][] store = new boolean[16][16][64]; @Override diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/PrimitiveExChunkletStore.java b/src/main/java/com/gmail/nossr50/util/blockmeta/PrimitiveExChunkletStore.java index 187ad0dff..8f8d2d255 100755 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/PrimitiveExChunkletStore.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/PrimitiveExChunkletStore.java @@ -8,9 +8,42 @@ import java.io.ObjectOutput; public class PrimitiveExChunkletStore implements ChunkletStore, Externalizable { private static final long serialVersionUID = 8603603827094383873L; - /** X, Z, Y */ + /** + * X, Z, Y + */ public boolean[][][] store = new boolean[16][16][64]; + /* + * The address byte: A single byte which contains x and z values which correspond to the x and z Chunklet-coordinates + * + * In Chunklet-coordinates, the only valid values are 0-15, so we can fit both into a single byte. + * + * The top 4 bits of the address byte are for the x value + * The bottom 4 bits of the address byte are for the z value + * + * Examples: + * An address byte with a value 00000001 would be split like so: + * - x = 0000 = 0 + * - z = 0001 = 1 + * => Chunklet coordinates (0, 1) + * + * 01011111 + * - x = 0101 = 5 + * - z = 1111 = 15 + * => Chunklet coordinates (5, 15) + */ + protected static byte makeAddressByte(int x, int z) { + return (byte) ((x << 4) + z); + } + + protected static int addressByteX(byte address) { + return (address & 0xF0) >>> 4; + } + + protected static int addressByteZ(byte address) { + return address & 0x0F; + } + @Override public boolean isTrue(int x, int y, int z) { return store[x][z][y]; @@ -146,35 +179,4 @@ public class PrimitiveExChunkletStore implements ChunkletStore, Externalizable { return column; } - - /* - * The address byte: A single byte which contains x and z values which correspond to the x and z Chunklet-coordinates - * - * In Chunklet-coordinates, the only valid values are 0-15, so we can fit both into a single byte. - * - * The top 4 bits of the address byte are for the x value - * The bottom 4 bits of the address byte are for the z value - * - * Examples: - * An address byte with a value 00000001 would be split like so: - * - x = 0000 = 0 - * - z = 0001 = 1 - * => Chunklet coordinates (0, 1) - * - * 01011111 - * - x = 0101 = 5 - * - z = 1111 = 15 - * => Chunklet coordinates (5, 15) - */ - protected static byte makeAddressByte(int x, int z) { - return (byte) ((x << 4) + z); - } - - protected static int addressByteX(byte address) { - return (address & 0xF0) >>> 4; - } - - protected static int addressByteZ(byte address) { - return address & 0x0F; - } } diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/chunkmeta/ChunkManager.java b/src/main/java/com/gmail/nossr50/util/blockmeta/chunkmeta/ChunkManager.java index d64824a0e..2dcb898b4 100755 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/chunkmeta/ChunkManager.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/chunkmeta/ChunkManager.java @@ -19,9 +19,9 @@ public interface ChunkManager { /** * Loads a specific chunklet * - * @param cx Chunklet X coordinate that needs to be loaded - * @param cy Chunklet Y coordinate that needs to be loaded - * @param cz Chunklet Z coordinate that needs to be loaded + * @param cx Chunklet X coordinate that needs to be loaded + * @param cy Chunklet Y coordinate that needs to be loaded + * @param cz Chunklet Z coordinate that needs to be loaded * @param world World that the chunklet needs to be loaded in */ void loadChunklet(int cx, int cy, int cz, World world); @@ -29,9 +29,9 @@ public interface ChunkManager { /** * Unload a specific chunklet * - * @param cx Chunklet X coordinate that needs to be unloaded - * @param cy Chunklet Y coordinate that needs to be unloaded - * @param cz Chunklet Z coordinate that needs to be unloaded + * @param cx Chunklet X coordinate that needs to be unloaded + * @param cy Chunklet Y coordinate that needs to be unloaded + * @param cz Chunklet Z coordinate that needs to be unloaded * @param world World that the chunklet needs to be unloaded from */ void unloadChunklet(int cx, int cy, int cz, World world); @@ -39,8 +39,8 @@ public interface ChunkManager { /** * Load a given Chunk's Chunklet data * - * @param cx Chunk X coordinate that is to be loaded - * @param cz Chunk Z coordinate that is to be loaded + * @param cx Chunk X coordinate that is to be loaded + * @param cz Chunk Z coordinate that is to be loaded * @param world World that the Chunk is in */ void loadChunk(int cx, int cz, World world, Entity[] entities); @@ -48,8 +48,8 @@ public interface ChunkManager { /** * Unload a given Chunk's Chunklet data * - * @param cx Chunk X coordinate that is to be unloaded - * @param cz Chunk Z coordinate that is to be unloaded + * @param cx Chunk X coordinate that is to be unloaded + * @param cz Chunk Z coordinate that is to be unloaded * @param world World that the Chunk is in */ void unloadChunk(int cx, int cz, World world); @@ -57,8 +57,8 @@ public interface ChunkManager { /** * Saves a given Chunk's Chunklet data * - * @param cx Chunk X coordinate that is to be saved - * @param cz Chunk Z coordinate that is to be saved + * @param cx Chunk X coordinate that is to be saved + * @param cz Chunk Z coordinate that is to be saved * @param world World that the Chunk is in */ void saveChunk(int cx, int cz, World world); @@ -68,8 +68,8 @@ public interface ChunkManager { /** * Informs the ChunkletManager a chunk is loaded * - * @param cx Chunk X coordinate that is loaded - * @param cz Chunk Z coordinate that is loaded + * @param cx Chunk X coordinate that is loaded + * @param cz Chunk Z coordinate that is loaded * @param world World that the chunk was loaded in */ void chunkLoaded(int cx, int cz, World world); @@ -77,8 +77,8 @@ public interface ChunkManager { /** * Informs the ChunkletManager a chunk is unloaded * - * @param cx Chunk X coordinate that is unloaded - * @param cz Chunk Z coordinate that is unloaded + * @param cx Chunk X coordinate that is unloaded + * @param cz Chunk Z coordinate that is unloaded * @param world World that the chunk was unloaded in */ void chunkUnloaded(int cx, int cz, World world); @@ -117,9 +117,9 @@ public interface ChunkManager { /** * Check to see if a given location is set to true * - * @param x X coordinate to check - * @param y Y coordinate to check - * @param z Z coordinate to check + * @param x X coordinate to check + * @param y Y coordinate to check + * @param z Z coordinate to check * @param world World to check in * @return true if the given location is set to true, false if otherwise */ @@ -144,9 +144,9 @@ public interface ChunkManager { /** * Set a given location to true, should create stores as necessary if the location does not exist * - * @param x X coordinate to set - * @param y Y coordinate to set - * @param z Z coordinate to set + * @param x X coordinate to set + * @param y Y coordinate to set + * @param z Z coordinate to set * @param world World to set in */ void setTrue(int x, int y, int z, World world); @@ -168,9 +168,9 @@ public interface ChunkManager { /** * Set a given location to false, should not create stores if one does not exist for the given location * - * @param x X coordinate to set - * @param y Y coordinate to set - * @param z Z coordinate to set + * @param x X coordinate to set + * @param y Y coordinate to set + * @param z Z coordinate to set * @param world World to set in */ void setFalse(int x, int y, int z, World world); diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/chunkmeta/HashChunkManager.java b/src/main/java/com/gmail/nossr50/util/blockmeta/chunkmeta/HashChunkManager.java index b38f2199a..d8cee27e3 100755 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/chunkmeta/HashChunkManager.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/chunkmeta/HashChunkManager.java @@ -11,9 +11,9 @@ import java.io.*; import java.util.*; public class HashChunkManager implements ChunkManager { - private HashMap> regionFiles = new HashMap<>(); public HashMap store = new HashMap<>(); public ArrayList converters = new ArrayList<>(); + private HashMap> regionFiles = new HashMap<>(); private HashMap oldData = new HashMap<>(); @Override @@ -65,8 +65,7 @@ public class HashChunkManager implements ChunkManager { objectStream.flush(); objectStream.close(); data.setDirty(false); - } - catch (IOException e) { + } catch (IOException e) { throw new RuntimeException("Unable to write chunk meta data for " + x + ", " + z, e); } } @@ -129,8 +128,7 @@ public class HashChunkManager implements ChunkManager { if (!oldData.containsKey(key)) { oldData.put(key, (new File(world.getWorldFolder(), "mcmmo_data")).exists()); - } - else if (oldData.get(key)) { + } else if (oldData.get(key)) { if (convertChunk(new File(world.getWorldFolder(), "mcmmo_data"), cx, cz, world, true)) { return; } @@ -140,8 +138,9 @@ public class HashChunkManager implements ChunkManager { try { chunkStore = readChunkStore(world, cx, cz); + } catch (Exception e) { + e.printStackTrace(); } - catch (Exception e) { e.printStackTrace(); } if (chunkStore == null) { return; @@ -187,7 +186,8 @@ public class HashChunkManager implements ChunkManager { } @Override - public synchronized void chunkLoaded(int cx, int cz, World world) {} + public synchronized void chunkLoaded(int cx, int cz, World world) { + } @Override public synchronized void chunkUnloaded(int cx, int cz, World world) { @@ -213,8 +213,7 @@ public class HashChunkManager implements ChunkManager { if (worldName.equals(info[0])) { try { saveChunk(Integer.parseInt(info[1]), Integer.parseInt(info[2]), world); - } - catch (Exception e) { + } catch (Exception e) { // Ignore } } @@ -236,8 +235,7 @@ public class HashChunkManager implements ChunkManager { if (worldName.equals(info[0])) { try { unloadChunk(Integer.parseInt(info[1]), Integer.parseInt(info[2]), world); - } - catch (Exception e) { + } catch (Exception e) { // Ignore } } @@ -245,7 +243,8 @@ public class HashChunkManager implements ChunkManager { } @Override - public synchronized void loadWorld(World world) {} + public synchronized void loadWorld(World world) { + } @Override public synchronized void saveAll() { @@ -401,7 +400,8 @@ public class HashChunkManager implements ChunkManager { } @Override - public synchronized void cleanUp() {} + public synchronized void cleanUp() { + } public synchronized void convertChunk(File dataDir, int cx, int cz, World world) { convertChunk(dataDir, cx, cz, world, false); diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/chunkmeta/McMMOSimpleRegionFile.java b/src/main/java/com/gmail/nossr50/util/blockmeta/chunkmeta/McMMOSimpleRegionFile.java index e04ef11c9..39f86b6de 100644 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/chunkmeta/McMMOSimpleRegionFile.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/chunkmeta/McMMOSimpleRegionFile.java @@ -25,21 +25,21 @@ import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; public class McMMOSimpleRegionFile { - private RandomAccessFile file; + @SuppressWarnings("unused") + private static long TIMEOUT_TIME = 300000; // 5 min private final int[] dataStart = new int[1024]; private final int[] dataActualLength = new int[1024]; private final int[] dataLength = new int[1024]; private final ArrayList inuse = new ArrayList<>(); - private int segmentSize; - private int segmentMask; private final int rx; private final int rz; private final int defaultSegmentSize; private final File parent; + private RandomAccessFile file; + private int segmentSize; + private int segmentMask; @SuppressWarnings("unused") private long lastAccessTime = System.currentTimeMillis(); - @SuppressWarnings("unused") - private static long TIMEOUT_TIME = 300000; // 5 min public McMMOSimpleRegionFile(File f, int rx, int rz) { this(f, rx, rz, 10); @@ -91,8 +91,7 @@ public class McMMOSimpleRegionFile { } extendFile(); - } - catch (IOException fnfe) { + } catch (IOException fnfe) { throw new RuntimeException(fnfe); } } @@ -139,16 +138,15 @@ public class McMMOSimpleRegionFile { } extendFile(); - } - catch (IOException fnfe) { + } catch (IOException fnfe) { throw new RuntimeException(fnfe); } } return file; } -/* public synchronized boolean testCloseTimeout() { - *//* + /* public synchronized boolean testCloseTimeout() { + *//* if (System.currentTimeMillis() - TIMEOUT_TIME > lastAccessTime) { close(); return true; @@ -197,8 +195,7 @@ public class McMMOSimpleRegionFile { } file = null; - } - catch (IOException ioe) { + } catch (IOException ioe) { throw new RuntimeException("Unable to close file", ioe); } } @@ -261,8 +258,7 @@ public class McMMOSimpleRegionFile { if (inuse.get(end)) { end++; start = end; - } - else { + } else { end++; } diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/chunkmeta/NullChunkManager.java b/src/main/java/com/gmail/nossr50/util/blockmeta/chunkmeta/NullChunkManager.java index a7040c982..6b8043009 100755 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/chunkmeta/NullChunkManager.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/chunkmeta/NullChunkManager.java @@ -8,7 +8,8 @@ import org.bukkit.entity.Entity; public class NullChunkManager implements ChunkManager { @Override - public void closeAll() {} + public void closeAll() { + } @Override public ChunkStore readChunkStore(World world, int x, int z) { @@ -16,25 +17,32 @@ public class NullChunkManager implements ChunkManager { } @Override - public void writeChunkStore(World world, int x, int z, ChunkStore data) {} + public void writeChunkStore(World world, int x, int z, ChunkStore data) { + } @Override - public void closeChunkStore(World world, int x, int z) {} + public void closeChunkStore(World world, int x, int z) { + } @Override - public void loadChunklet(int cx, int cy, int cz, World world) {} + public void loadChunklet(int cx, int cy, int cz, World world) { + } @Override - public void unloadChunklet(int cx, int cy, int cz, World world) {} + public void unloadChunklet(int cx, int cy, int cz, World world) { + } @Override - public void loadChunk(int cx, int cz, World world, Entity[] entities) {} + public void loadChunk(int cx, int cz, World world, Entity[] entities) { + } @Override - public void unloadChunk(int cx, int cz, World world) {} + public void unloadChunk(int cx, int cz, World world) { + } @Override - public void saveChunk(int cx, int cz, World world) {} + public void saveChunk(int cx, int cz, World world) { + } @Override public boolean isChunkLoaded(int cx, int cz, World world) { @@ -42,25 +50,32 @@ public class NullChunkManager implements ChunkManager { } @Override - public void chunkLoaded(int cx, int cz, World world) {} + public void chunkLoaded(int cx, int cz, World world) { + } @Override - public void chunkUnloaded(int cx, int cz, World world) {} + public void chunkUnloaded(int cx, int cz, World world) { + } @Override - public void saveWorld(World world) {} + public void saveWorld(World world) { + } @Override - public void unloadWorld(World world) {} + public void unloadWorld(World world) { + } @Override - public void loadWorld(World world) {} + public void loadWorld(World world) { + } @Override - public void saveAll() {} + public void saveAll() { + } @Override - public void unloadAll() {} + public void unloadAll() { + } @Override public boolean isTrue(int x, int y, int z, World world) { @@ -78,23 +93,30 @@ public class NullChunkManager implements ChunkManager { } @Override - public void setTrue(int x, int y, int z, World world) {} + public void setTrue(int x, int y, int z, World world) { + } @Override - public void setTrue(Block block) {} + public void setTrue(Block block) { + } @Override - public void setTrue(BlockState blockState) {} + public void setTrue(BlockState blockState) { + } @Override - public void setFalse(int x, int y, int z, World world) {} + public void setFalse(int x, int y, int z, World world) { + } @Override - public void setFalse(Block block) {} + public void setFalse(Block block) { + } @Override - public void setFalse(BlockState blockState) {} + public void setFalse(BlockState blockState) { + } @Override - public void cleanUp() {} + public void cleanUp() { + } } diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/chunkmeta/PrimitiveChunkStore.java b/src/main/java/com/gmail/nossr50/util/blockmeta/chunkmeta/PrimitiveChunkStore.java index d1866acab..df0ecdbb1 100755 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/chunkmeta/PrimitiveChunkStore.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/chunkmeta/PrimitiveChunkStore.java @@ -11,11 +11,13 @@ import java.util.UUID; public class PrimitiveChunkStore implements ChunkStore { private static final long serialVersionUID = -1L; - transient private boolean dirty = false; - /** X, Z, Y */ - public boolean[][][] store; private static final int CURRENT_VERSION = 7; private static final int MAGIC_NUMBER = 0xEA5EDEBB; + /** + * X, Z, Y + */ + public boolean[][][] store; + transient private boolean dirty = false; private int cx; private int cz; private UUID worldUid; @@ -138,8 +140,9 @@ public class PrimitiveChunkStore implements ChunkStore { for (int y = 0; y < store[0][0].length; y++) { try { store[x][z][y] = temp[x][y][z]; + } catch (Exception e) { + e.printStackTrace(); } - catch (Exception e) { e.printStackTrace(); } } } } diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/conversion/BlockStoreConversionMain.java b/src/main/java/com/gmail/nossr50/util/blockmeta/conversion/BlockStoreConversionMain.java index 77ff10714..448109258 100755 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/conversion/BlockStoreConversionMain.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/conversion/BlockStoreConversionMain.java @@ -7,12 +7,12 @@ import org.bukkit.scheduler.BukkitScheduler; import java.io.File; public class BlockStoreConversionMain implements Runnable { - private int taskID; - private org.bukkit.World world; BukkitScheduler scheduler; File dataDir; File[] xDirs; BlockStoreConversionXDirectory[] converters; + private int taskID; + private org.bukkit.World world; public BlockStoreConversionMain(org.bukkit.World world) { this.taskID = -1; diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/conversion/BlockStoreConversionXDirectory.java b/src/main/java/com/gmail/nossr50/util/blockmeta/conversion/BlockStoreConversionXDirectory.java index de53a70f1..567c13a15 100755 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/conversion/BlockStoreConversionXDirectory.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/conversion/BlockStoreConversionXDirectory.java @@ -7,12 +7,12 @@ import org.bukkit.scheduler.BukkitScheduler; import java.io.File; public class BlockStoreConversionXDirectory implements Runnable { - private int taskID; - private org.bukkit.World world; BukkitScheduler scheduler; File dataDir; File[] zDirs; BlockStoreConversionZDirectory[] converters; + private int taskID; + private org.bukkit.World world; public BlockStoreConversionXDirectory() { this.taskID = -1; diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/conversion/BlockStoreConversionZDirectory.java b/src/main/java/com/gmail/nossr50/util/blockmeta/conversion/BlockStoreConversionZDirectory.java index 66ab78a42..ccc144ef6 100755 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/conversion/BlockStoreConversionZDirectory.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/conversion/BlockStoreConversionZDirectory.java @@ -70,8 +70,7 @@ public class BlockStoreConversionZDirectory implements Runnable { try { this.cx = Integer.parseInt(this.cxs); this.cz = Integer.parseInt(this.czs); - } - catch (Exception e) { + } catch (Exception e) { this.dataDir.delete(); stop(); return; @@ -85,8 +84,7 @@ public class BlockStoreConversionZDirectory implements Runnable { if (this.tempChunklet instanceof PrimitiveChunkletStore) { this.primitiveChunklet = (PrimitiveChunkletStore) this.tempChunklet; - } - else if (this.tempChunklet instanceof PrimitiveExChunkletStore) { + } else if (this.tempChunklet instanceof PrimitiveExChunkletStore) { this.primitiveExChunklet = (PrimitiveExChunkletStore) this.tempChunklet; } @@ -113,8 +111,9 @@ public class BlockStoreConversionZDirectory implements Runnable { } this.newManager.setTrue(this.cxPos, this.y2, this.czPos, this.world); + } catch (Exception e) { + e.printStackTrace(); } - catch (Exception e) { e.printStackTrace(); } } } } @@ -132,8 +131,7 @@ public class BlockStoreConversionZDirectory implements Runnable { if (this.primitiveExChunklet != null) { oldArray = this.primitiveExChunklet.store[x][z]; - } - else { + } else { return; } @@ -141,8 +139,7 @@ public class BlockStoreConversionZDirectory implements Runnable { if (oldArray.length < 64) { return; - } - else if (newArray.length < ((this.y * 64) + 64)) { + } else if (newArray.length < ((this.y * 64) + 64)) { return; } diff --git a/src/main/java/com/gmail/nossr50/util/commands/CommandRegistrationManager.java b/src/main/java/com/gmail/nossr50/util/commands/CommandRegistrationManager.java index 0f73efc90..11f1e9372 100644 --- a/src/main/java/com/gmail/nossr50/util/commands/CommandRegistrationManager.java +++ b/src/main/java/com/gmail/nossr50/util/commands/CommandRegistrationManager.java @@ -25,10 +25,11 @@ import java.util.ArrayList; import java.util.List; public final class CommandRegistrationManager { - private CommandRegistrationManager() {} - private static String permissionsMessage = LocaleLoader.getString("mcMMO.NoPermission"); + private CommandRegistrationManager() { + } + private static void registerSkillCommands() { for (PrimarySkillType skill : PrimarySkillType.values()) { String commandName = skill.toString().toLowerCase(); @@ -323,9 +324,9 @@ public final class CommandRegistrationManager { PluginCommand command = mcMMO.p.getCommand("party"); command.setDescription(LocaleLoader.getString("Commands.Description.party")); command.setPermission("mcmmo.commands.party;mcmmo.commands.party.accept;mcmmo.commands.party.create;mcmmo.commands.party.disband;" + - "mcmmo.commands.party.xpshare;mcmmo.commands.party.invite;mcmmo.commands.party.itemshare;mcmmo.commands.party.join;" + - "mcmmo.commands.party.kick;mcmmo.commands.party.lock;mcmmo.commands.party.owner;mcmmo.commands.party.password;" + - "mcmmo.commands.party.quit;mcmmo.commands.party.rename;mcmmo.commands.party.unlock"); + "mcmmo.commands.party.xpshare;mcmmo.commands.party.invite;mcmmo.commands.party.itemshare;mcmmo.commands.party.join;" + + "mcmmo.commands.party.kick;mcmmo.commands.party.lock;mcmmo.commands.party.owner;mcmmo.commands.party.password;" + + "mcmmo.commands.party.quit;mcmmo.commands.party.rename;mcmmo.commands.party.unlock"); command.setPermissionMessage(permissionsMessage); command.setExecutor(new PartyCommand()); } @@ -368,7 +369,7 @@ public final class CommandRegistrationManager { command.setUsage(LocaleLoader.getString("Commands.Usage.0", "mcnotify")); command.setExecutor(new McnotifyCommand()); } - + private static void registerMHDCommand() { PluginCommand command = mcMMO.p.getCommand("mhd"); command.setDescription("Resets all mob health bar settings for all players to the default"); //TODO: Localize diff --git a/src/main/java/com/gmail/nossr50/util/commands/CommandUtils.java b/src/main/java/com/gmail/nossr50/util/commands/CommandUtils.java index 7c5352306..3b47fbb9f 100644 --- a/src/main/java/com/gmail/nossr50/util/commands/CommandUtils.java +++ b/src/main/java/com/gmail/nossr50/util/commands/CommandUtils.java @@ -22,7 +22,8 @@ public final class CommandUtils { public static final List TRUE_FALSE_OPTIONS = ImmutableList.of("on", "off", "true", "false", "enabled", "disabled"); public static final List RESET_OPTIONS = ImmutableList.of("clear", "reset"); - private CommandUtils() {} + private CommandUtils() { + } public static boolean isChildSkill(CommandSender sender, PrimarySkillType skill) { if (skill == null || !skill.isChildSkill()) { @@ -51,8 +52,8 @@ public final class CommandUtils { && mcMMO.getConfigManager().getConfigCommands().isLimitInspectRange() && !hasPermission && !Misc.isNear(((Player) sender).getLocation(), - target.getLocation(), - mcMMO.getConfigManager().getConfigCommands().getInspectCommandMaxDistance())) { + target.getLocation(), + mcMMO.getConfigManager().getConfigCommands().getInspectCommandMaxDistance())) { sender.sendMessage(LocaleLoader.getString("Inspect.TooFar")); return true; } @@ -85,10 +86,9 @@ public final class CommandUtils { /** * Checks if there is a valid mcMMOPlayer object. * - * @param sender CommandSender who used the command - * @param playerName name of the target player + * @param sender CommandSender who used the command + * @param playerName name of the target player * @param mcMMOPlayer mcMMOPlayer object of the target player - * * @return true if the player is online and a valid mcMMOPlayer object was found */ public static boolean checkPlayerExistence(CommandSender sender, String playerName, McMMOPlayer mcMMOPlayer) { @@ -228,7 +228,7 @@ public final class CommandUtils { } private static void printGroupedSkillData(Player inspect, CommandSender display, String header, List skillGroup) { - if(UserManager.getPlayer(inspect) == null) + if (UserManager.getPlayer(inspect) == null) return; PlayerProfile profile = UserManager.getPlayer(inspect).getProfile(); @@ -266,7 +266,6 @@ public final class CommandUtils { * Get a matched player name if one was found in the database. * * @param partialName Name to match - * * @return Matched name or {@code partialName} if no match was found */ public static String getMatchedPlayerName(String partialName) { @@ -276,8 +275,7 @@ public final class CommandUtils { if (matches.size() == 1) { partialName = matches.get(0); } - } - else { + } else { Player player = mcMMO.p.getServer().getPlayer(partialName); if (player != null) { @@ -290,7 +288,7 @@ public final class CommandUtils { /** * Attempts to match any player names with the given name, and returns a list of all possibly matches. - * + *

* This list is not sorted in any particular order. * If an exact match is found, the returned list will only contain a single result. * @@ -302,10 +300,10 @@ public final class CommandUtils { for (OfflinePlayer offlinePlayer : mcMMO.p.getServer().getOfflinePlayers()) { String playerName = offlinePlayer.getName(); - + if (playerName == null) { //Do null checking here to detect corrupted data before sending it throuogh .equals - System.err.println("[McMMO] Player data file with UIID " + offlinePlayer.getUniqueId() + " is missing a player name. This may be a legacy file from before bukkit.lastKnownName. This should be okay to ignore."); - continue; //Don't let an error here interrupt the loop + System.err.println("[McMMO] Player data file with UIID " + offlinePlayer.getUniqueId() + " is missing a player name. This may be a legacy file from before bukkit.lastKnownName. This should be okay to ignore."); + continue; //Don't let an error here interrupt the loop } if (partialName.equalsIgnoreCase(playerName)) { diff --git a/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarManager.java b/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarManager.java index e21843c8a..42d7e86ac 100644 --- a/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarManager.java +++ b/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarManager.java @@ -13,13 +13,11 @@ import java.util.HashMap; * Each ExperienceBarManager only manages a single player */ public class ExperienceBarManager { - private McMMOPlayer mcMMOPlayer; - HashMap experienceBars; HashMap experienceBarHideTaskHashMap; + private McMMOPlayer mcMMOPlayer; - public ExperienceBarManager(McMMOPlayer mcMMOPlayer) - { + public ExperienceBarManager(McMMOPlayer mcMMOPlayer) { //Init map experienceBars = new HashMap<>(); experienceBarHideTaskHashMap = new HashMap<>(); @@ -27,13 +25,12 @@ public class ExperienceBarManager { this.mcMMOPlayer = mcMMOPlayer; } - public void updateExperienceBar(PrimarySkillType primarySkillType, Plugin plugin) - { - if(!ExperienceConfig.getInstance().isExperienceBarsEnabled() || !ExperienceConfig.getInstance().isExperienceBarEnabled(primarySkillType)) + public void updateExperienceBar(PrimarySkillType primarySkillType, Plugin plugin) { + if (!ExperienceConfig.getInstance().isExperienceBarsEnabled() || !ExperienceConfig.getInstance().isExperienceBarEnabled(primarySkillType)) return; //Init Bar - if(experienceBars.get(primarySkillType) == null) + if (experienceBars.get(primarySkillType) == null) experienceBars.put(primarySkillType, new ExperienceBarWrapper(primarySkillType, mcMMOPlayer)); //Get Bar @@ -46,8 +43,7 @@ public class ExperienceBarManager { experienceBarWrapper.showExperienceBar(); //Setup Hide Bar Task - if(experienceBarHideTaskHashMap.get(primarySkillType) != null) - { + if (experienceBarHideTaskHashMap.get(primarySkillType) != null) { experienceBarHideTaskHashMap.get(primarySkillType).cancel(); scheduleHideTask(primarySkillType, plugin); } else { @@ -57,17 +53,15 @@ public class ExperienceBarManager { private void scheduleHideTask(PrimarySkillType primarySkillType, Plugin plugin) { ExperienceBarHideTask experienceBarHideTask = new ExperienceBarHideTask(this, mcMMOPlayer, primarySkillType); - experienceBarHideTask.runTaskLater(plugin, 20*2); + experienceBarHideTask.runTaskLater(plugin, 20 * 2); experienceBarHideTaskHashMap.put(primarySkillType, experienceBarHideTask); } - public void hideExperienceBar(PrimarySkillType primarySkillType) - { + public void hideExperienceBar(PrimarySkillType primarySkillType) { experienceBars.get(primarySkillType).hideExperienceBar(); } - public void clearTask(PrimarySkillType primarySkillType) - { + public void clearTask(PrimarySkillType primarySkillType) { experienceBarHideTaskHashMap.remove(primarySkillType); } } diff --git a/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarWrapper.java b/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarWrapper.java index 9fcad6fbb..3278dbd1e 100644 --- a/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarWrapper.java +++ b/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarWrapper.java @@ -18,20 +18,18 @@ import java.util.List; */ public class ExperienceBarWrapper { - private final PrimarySkillType primarySkillType; //Primary Skill - private BossBar bossBar; - private final Server server; protected final McMMOPlayer mcMMOPlayer; - private int lastLevelUpdated; - + private final PrimarySkillType primarySkillType; //Primary Skill + private final Server server; /* * This is stored to help optimize updating the title */ protected String niceSkillName; protected String title; + private BossBar bossBar; + private int lastLevelUpdated; - public ExperienceBarWrapper(PrimarySkillType primarySkillType, McMMOPlayer mcMMOPlayer) - { + public ExperienceBarWrapper(PrimarySkillType primarySkillType, McMMOPlayer mcMMOPlayer) { this.mcMMOPlayer = mcMMOPlayer; this.server = mcMMOPlayer.getPlayer().getServer(); //Might not be good for bungee to do this this.primarySkillType = primarySkillType; @@ -45,8 +43,7 @@ public class ExperienceBarWrapper { initBar(); } - private void initBar() - { + private void initBar() { title = getTitleTemplate(); createBossBar(); } @@ -58,19 +55,31 @@ public class ExperienceBarWrapper { private String getTitleTemplate() { //If they are using extra details - if(ExperienceConfig.getInstance().getAddExtraDetails()) - return LocaleLoader.getString("XPBar.Complex.Template", LocaleLoader.getString("XPBar."+niceSkillName, getLevel()), getCurrentXP(), getMaxXP(), getPowerLevel(), getPercentageOfLevel()); + if (ExperienceConfig.getInstance().getAddExtraDetails()) + return LocaleLoader.getString("XPBar.Complex.Template", LocaleLoader.getString("XPBar." + niceSkillName, getLevel()), getCurrentXP(), getMaxXP(), getPowerLevel(), getPercentageOfLevel()); - return LocaleLoader.getString("XPBar."+niceSkillName, getLevel(), getCurrentXP(), getMaxXP(), getPowerLevel(), getPercentageOfLevel()); + return LocaleLoader.getString("XPBar." + niceSkillName, getLevel(), getCurrentXP(), getMaxXP(), getPowerLevel(), getPercentageOfLevel()); } private int getLevel() { return mcMMOPlayer.getSkillLevel(primarySkillType); } - private int getCurrentXP() { return mcMMOPlayer.getSkillXpLevel(primarySkillType); } - private int getMaxXP() { return mcMMOPlayer.getXpToLevel(primarySkillType); } - private int getPowerLevel() { return mcMMOPlayer.getPowerLevel(); } - private int getPercentageOfLevel() { return (int) (mcMMOPlayer.getProgressInCurrentSkillLevel(primarySkillType) * 100); } + + private int getCurrentXP() { + return mcMMOPlayer.getSkillXpLevel(primarySkillType); + } + + private int getMaxXP() { + return mcMMOPlayer.getXpToLevel(primarySkillType); + } + + private int getPowerLevel() { + return mcMMOPlayer.getPowerLevel(); + } + + private int getPercentageOfLevel() { + return (int) (mcMMOPlayer.getProgressInCurrentSkillLevel(primarySkillType) * 100); + } public String getTitle() { return bossBar.getTitle(); @@ -96,28 +105,27 @@ public class ExperienceBarWrapper { bossBar.setStyle(barStyle); } + public double getProgress() { + return bossBar.getProgress(); + } + public void setProgress(double v) { //Clamp Values - if(v < 0) + if (v < 0) bossBar.setProgress(0.0D); - else if(v > 1) + else if (v > 1) bossBar.setProgress(1.0D); else bossBar.setProgress(v); //Every time progress updates we need to check for a title update - if(getLevel() != lastLevelUpdated || ExperienceConfig.getInstance().getDoExperienceBarsAlwaysUpdateTitle()) - { + if (getLevel() != lastLevelUpdated || ExperienceConfig.getInstance().getDoExperienceBarsAlwaysUpdateTitle()) { updateTitle(); lastLevelUpdated = getLevel(); } } - public double getProgress() { - return bossBar.getProgress(); - } - public List getPlayers() { return bossBar.getPlayers(); } @@ -126,13 +134,11 @@ public class ExperienceBarWrapper { return bossBar.isVisible(); } - public void hideExperienceBar() - { + public void hideExperienceBar() { bossBar.setVisible(false); } - public void showExperienceBar() - { + public void showExperienceBar() { bossBar.setVisible(true); } @@ -141,8 +147,7 @@ public class ExperienceBarWrapper { return bossBar }*/ - private void createBossBar() - { + private void createBossBar() { bossBar = mcMMOPlayer.getPlayer().getServer().createBossBar(title, ExperienceConfig.getInstance().getExperienceBarColor(primarySkillType), ExperienceConfig.getInstance().getExperienceBarStyle(primarySkillType)); bossBar.addPlayer(mcMMOPlayer.getPlayer()); } diff --git a/src/main/java/com/gmail/nossr50/util/experience/ExperienceMapManager.java b/src/main/java/com/gmail/nossr50/util/experience/ExperienceMapManager.java index 08cba6d23..9de8b00e3 100644 --- a/src/main/java/com/gmail/nossr50/util/experience/ExperienceMapManager.java +++ b/src/main/java/com/gmail/nossr50/util/experience/ExperienceMapManager.java @@ -15,8 +15,7 @@ public class ExperienceMapManager implements Unload { public HashMap woodcuttingXpMap; public HashMap excavationXpMap; - public ExperienceMapManager() - { + public ExperienceMapManager() { miningXpMap = new HashMap<>(); herbalismXpMap = new HashMap<>(); woodcuttingXpMap = new HashMap<>(); @@ -28,81 +27,81 @@ public class ExperienceMapManager implements Unload { /** * Determines whether or not a block has Mining XP + * * @param material target block material type * @return true if the block has valid xp registers */ - public boolean hasMiningXp(Material material) - { + public boolean hasMiningXp(Material material) { return miningXpMap.get(material) != null; } /** * Determines whether or not a block has Herbalism XP + * * @param material target block material type * @return true if the block has valid xp registers */ - public boolean hasHerbalismXp(Material material) - { + public boolean hasHerbalismXp(Material material) { return herbalismXpMap.get(material) != null; } /** * Determines whether or not a block has Woodcutting XP + * * @param material target block material type * @return true if the block has valid xp registers */ - public boolean hasWoodcuttingXp(Material material) - { + public boolean hasWoodcuttingXp(Material material) { return woodcuttingXpMap.get(material) != null; } /** * Determines whether or not a block has Excavation XP + * * @param material target block material type * @return true if the block has valid xp registers */ - public boolean hasExcavationXp(Material material) - { + public boolean hasExcavationXp(Material material) { return excavationXpMap.get(material) != null; } /** * Gets the XP value for breaking this block from the xp map + * * @param material the target block material * @return the raw XP value before any modifiers are applied */ - public int getMiningXp(Material material) - { + public int getMiningXp(Material material) { return miningXpMap.get(material); } /** * Gets the XP value for breaking this block from the xp map + * * @param material the target block material * @return the raw XP value before any modifiers are applied */ - public int getHerbalismXp(Material material) - { + public int getHerbalismXp(Material material) { return herbalismXpMap.get(material); } /** * Gets the XP value for breaking this block from the xp map + * * @param material the target block material * @return the raw XP value before any modifiers are applied */ - public int getWoodcuttingXp(Material material) - { + public int getWoodcuttingXp(Material material) { return woodcuttingXpMap.get(material); } /** * Gets the XP value for breaking this block from the xp map + * * @param material the target block material * @return the raw XP value before any modifiers are applied */ - public int getExcavationXp(Material material) - { + public int getExcavationXp(Material material) { return excavationXpMap.get(material); } diff --git a/src/main/java/com/gmail/nossr50/util/experience/FormulaManager.java b/src/main/java/com/gmail/nossr50/util/experience/FormulaManager.java index abb85e8f3..f4e3a67c5 100644 --- a/src/main/java/com/gmail/nossr50/util/experience/FormulaManager.java +++ b/src/main/java/com/gmail/nossr50/util/experience/FormulaManager.java @@ -50,7 +50,7 @@ public class FormulaManager { * the amount of levels and experience, using the previously * used formula type. * - * @param skillLevel Amount of levels + * @param skillLevel Amount of levels * @param skillXPLevel Amount of experience * @return The total amount of experience */ @@ -71,8 +71,8 @@ public class FormulaManager { * the new formula type. * * @param primarySkillType skill where new levels and experience are calculated for - * @param experience total amount of experience - * @param formulaType The new {@link FormulaType} + * @param experience total amount of experience + * @param formulaType The new {@link FormulaType} * @return the amount of levels and experience */ public int[] calculateNewLevel(PrimarySkillType primarySkillType, int experience, FormulaType formulaType) { @@ -82,15 +82,14 @@ public class FormulaManager { while (experience > 0 && newLevel < Integer.MAX_VALUE) { //Level Cap - if(mcMMO.getPlayerLevelingSettings().isLevelCapEnabled(primarySkillType)) - { + if (mcMMO.getPlayerLevelingSettings().isLevelCapEnabled(primarySkillType)) { //Break the loop if we're at the cap - if(newLevel+1 > mcMMO.getPlayerLevelingSettings().getLevelCap(primarySkillType)) + if (newLevel + 1 > mcMMO.getPlayerLevelingSettings().getLevelCap(primarySkillType)) break; //If the maximum level is at or below our starting level, then the player can't level up anymore - if(maxLevel <= mcMMO.getPlayerLevelingSettings().getConfigSectionLevelingGeneral().getStartingLevel()) - return new int[]{ newLevel, remainder }; + if (maxLevel <= mcMMO.getPlayerLevelingSettings().getConfigSectionLevelingGeneral().getStartingLevel()) + return new int[]{newLevel, remainder}; } int experienceToNextLevel = getCachedXpToLevel(newLevel, formulaType); @@ -104,7 +103,7 @@ public class FormulaManager { experience -= experienceToNextLevel; } - return new int[]{ newLevel, remainder }; + return new int[]{newLevel, remainder}; } /** @@ -112,7 +111,7 @@ public class FormulaManager { * if cache doesn't contain the given value it is calculated and added * to the cached data. * - * @param level level to check + * @param level level to check * @param formulaType The {@link FormulaType} used * @return amount of experience needed to reach next level */ @@ -136,7 +135,7 @@ public class FormulaManager { switch (formulaType) { case LINEAR: if (!experienceNeededLinear.containsKey(level)) { - experience = (int) Math.floor( xpNeededMultiplier * (base + level * multiplier)); + experience = (int) Math.floor(xpNeededMultiplier * (base + level * multiplier)); experienceNeededLinear.put(level, experience); } @@ -144,7 +143,7 @@ public class FormulaManager { case EXPONENTIAL: if (!experienceNeededExponential.containsKey(level)) { - experience = (int) Math.floor( xpNeededMultiplier * (multiplier * Math.pow(level, exponent) + base)); + experience = (int) Math.floor(xpNeededMultiplier * (multiplier * Math.pow(level, exponent) + base)); experienceNeededExponential.put(level, experience); } @@ -159,7 +158,7 @@ public class FormulaManager { * Get the cached amount of experience needed to reach the next party level, * if cache doesn't contain the given value it is calculated and added * to the cached data. - * + *

* Parties use the exponential leveling formula * * @param level level to check @@ -207,8 +206,7 @@ public class FormulaManager { try { formulasFile.save(formulaFile); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } } diff --git a/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java b/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java index 2f46df5a0..50a45fd75 100644 --- a/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java +++ b/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java @@ -22,13 +22,13 @@ public class NotificationManager { /** * Sends players notifications from mcMMO * This does this by sending out an event so other plugins can cancel it - * @param player target player + * + * @param player target player * @param notificationType notifications defined type - * @param key the locale key for the notifications defined message + * @param key the locale key for the notifications defined message */ - public static void sendPlayerInformation(Player player, NotificationType notificationType, String key) - { - if(UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) + public static void sendPlayerInformation(Player player, NotificationType notificationType, String key) { + if (UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) return; ChatMessageType destination = AdvancedConfig.getInstance().doesNotificationUseActionBar(notificationType) ? ChatMessageType.ACTION_BAR : ChatMessageType.SYSTEM; @@ -40,9 +40,8 @@ public class NotificationManager { } - public static boolean doesPlayerUseNotifications(Player player) - { - if(UserManager.getPlayer(player) == null) + public static boolean doesPlayerUseNotifications(Player player) { + if (UserManager.getPlayer(player) == null) return false; else return UserManager.getPlayer(player).useChatNotifications(); @@ -52,13 +51,13 @@ public class NotificationManager { * Sends players notifications from mcMMO * This does this by sending out an event so other plugins can cancel it * This event in particular is provided with a source player, and players near the source player are sent the information - * @param source the source player for this event + * + * @param source the source player for this event * @param notificationType type of notification - * @param key Locale Key for the string to use with this event - * @param values values to be injected into the locale string + * @param key Locale Key for the string to use with this event + * @param values values to be injected into the locale string */ - public static void sendNearbyPlayersInformation(Player source, NotificationType notificationType, String key, String... values) - { + public static void sendNearbyPlayersInformation(Player source, NotificationType notificationType, String key, String... values) { Location location = source.getLocation(); for (Player otherPlayer : source.getWorld().getPlayers()) { if (otherPlayer != source && Misc.isNear(location, otherPlayer.getLocation(), Misc.SKILL_MESSAGE_MAX_SENDING_DISTANCE)) { @@ -67,9 +66,8 @@ public class NotificationManager { } } - public static void sendPlayerInformation(Player player, NotificationType notificationType, String key, String... values) - { - if(UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) + public static void sendPlayerInformation(Player player, NotificationType notificationType, String key, String... values) { + if (UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) return; ChatMessageType destination = AdvancedConfig.getInstance().doesNotificationUseActionBar(notificationType) ? ChatMessageType.ACTION_BAR : ChatMessageType.SYSTEM; @@ -85,12 +83,10 @@ public class NotificationManager { return; //If the message is being sent to the action bar we need to check if the copy if a copy is sent to the chat system - if(customEvent.getChatMessageType() == ChatMessageType.ACTION_BAR) - { + if (customEvent.getChatMessageType() == ChatMessageType.ACTION_BAR) { player.spigot().sendMessage(customEvent.getChatMessageType(), customEvent.getNotificationTextComponent()); - if(customEvent.isMessageAlsoBeingSentToChat()) - { + if (customEvent.isMessageAlsoBeingSentToChat()) { //Send copy to chat system player.spigot().sendMessage(ChatMessageType.SYSTEM, customEvent.getNotificationTextComponent()); } @@ -111,13 +107,13 @@ public class NotificationManager { /** * Handles sending level up notifications to a mcMMOPlayer + * * @param mcMMOPlayer target mcMMOPlayer - * @param skillName skill that leveled up - * @param newLevel new level of that skill + * @param skillName skill that leveled up + * @param newLevel new level of that skill */ - public static void sendPlayerLevelUpNotification(McMMOPlayer mcMMOPlayer, PrimarySkillType skillName, int levelsGained, int newLevel) - { - if(!mcMMOPlayer.useChatNotifications()) + public static void sendPlayerLevelUpNotification(McMMOPlayer mcMMOPlayer, PrimarySkillType skillName, int levelsGained, int newLevel) { + if (!mcMMOPlayer.useChatNotifications()) return; ChatMessageType destination = AdvancedConfig.getInstance().doesNotificationUseActionBar(NotificationType.LEVEL_UP_MESSAGE) ? ChatMessageType.ACTION_BAR : ChatMessageType.SYSTEM; @@ -128,17 +124,14 @@ public class NotificationManager { sendNotification(mcMMOPlayer.getPlayer(), customEvent); } - public static void broadcastTitle(Server server, String title, String subtitle, int i1, int i2, int i3) - { - for(Player player : server.getOnlinePlayers()) - { + public static void broadcastTitle(Server server, String title, String subtitle, int i1, int i2, int i3) { + for (Player player : server.getOnlinePlayers()) { player.sendTitle(title, subtitle, i1, i2, i3); } } - public static void sendPlayerUnlockNotification(McMMOPlayer mcMMOPlayer, SubSkillType subSkillType) - { - if(!mcMMOPlayer.useChatNotifications()) + public static void sendPlayerUnlockNotification(McMMOPlayer mcMMOPlayer, SubSkillType subSkillType) { + if (!mcMMOPlayer.useChatNotifications()) return; //CHAT MESSAGE diff --git a/src/main/java/com/gmail/nossr50/util/player/UserManager.java b/src/main/java/com/gmail/nossr50/util/player/UserManager.java index 73f3b16cc..0ce90f361 100644 --- a/src/main/java/com/gmail/nossr50/util/player/UserManager.java +++ b/src/main/java/com/gmail/nossr50/util/player/UserManager.java @@ -13,7 +13,8 @@ import java.util.Collection; public final class UserManager { - private UserManager() {} + private UserManager() { + } /** * Track a new user. @@ -50,12 +51,9 @@ public final class UserManager { mcMMO.p.debug("Saving mcMMOPlayers... (" + onlinePlayers.size() + ")"); for (Player player : onlinePlayers) { - try - { + try { getPlayer(player).getProfile().save(); - } - catch (Exception e) - { + } catch (Exception e) { mcMMO.p.getLogger().warning("Could not save mcMMO player data for player: " + player.getName()); } } @@ -97,12 +95,13 @@ public final class UserManager { /** * Gets the McMMOPlayer object for a player, this can be null if the player has not yet been loaded. + * * @param player target player * @return McMMOPlayer object for this player, null if Player has not been loaded */ public static McMMOPlayer getPlayer(Player player) { //Avoid Array Index out of bounds - if(player != null && player.hasMetadata(mcMMO.playerDataKey)) + if (player != null && player.hasMetadata(mcMMO.playerDataKey)) return (McMMOPlayer) player.getMetadata(mcMMO.playerDataKey).get(0).value(); else return null; diff --git a/src/main/java/com/gmail/nossr50/util/random/RandomChanceExecution.java b/src/main/java/com/gmail/nossr50/util/random/RandomChanceExecution.java index 8d0da9285..e5d51d740 100644 --- a/src/main/java/com/gmail/nossr50/util/random/RandomChanceExecution.java +++ b/src/main/java/com/gmail/nossr50/util/random/RandomChanceExecution.java @@ -3,6 +3,7 @@ package com.gmail.nossr50.util.random; public interface RandomChanceExecution { /** * Gets the XPos used in the formula for success + * * @return value of x for our success probability graph */ double getXPos(); @@ -10,6 +11,7 @@ public interface RandomChanceExecution { /** * The maximum odds for this RandomChanceExecution * For example, if this value is 10, then 10% odds would be the maximum and would be achieved only when xPos equaled the LinearCurvePeak + * * @return maximum probability odds from 0.00 (no chance of ever happened) to 100.0 (probability can be guaranteed) */ double getProbabilityCap(); diff --git a/src/main/java/com/gmail/nossr50/util/random/RandomChanceSkill.java b/src/main/java/com/gmail/nossr50/util/random/RandomChanceSkill.java index 7a520d3f9..14b6d6d94 100644 --- a/src/main/java/com/gmail/nossr50/util/random/RandomChanceSkill.java +++ b/src/main/java/com/gmail/nossr50/util/random/RandomChanceSkill.java @@ -15,26 +15,24 @@ public class RandomChanceSkill implements RandomChanceExecution { protected final boolean isLucky; private int skillLevel; - public RandomChanceSkill(Player player, SubSkillType subSkillType) - { + public RandomChanceSkill(Player player, SubSkillType subSkillType) { this.primarySkillType = subSkillType.getParentSkill(); this.subSkillType = subSkillType; this.probabilityCap = RandomChanceUtil.LINEAR_CURVE_VAR; - if(player != null) + if (player != null) this.skillLevel = UserManager.getPlayer(player).getSkillLevel(primarySkillType); else this.skillLevel = 0; - if(player != null) + if (player != null) isLucky = Permissions.lucky(player, primarySkillType); else isLucky = false; } - public RandomChanceSkill(Player player, SubSkillType subSkillType, boolean hasCap) - { - if(hasCap) + public RandomChanceSkill(Player player, SubSkillType subSkillType, boolean hasCap) { + if (hasCap) this.probabilityCap = mcMMO.getConfigManager().getSkillMaxChance(subSkillType); else this.probabilityCap = RandomChanceUtil.LINEAR_CURVE_VAR; @@ -42,12 +40,12 @@ public class RandomChanceSkill implements RandomChanceExecution { this.primarySkillType = subSkillType.getParentSkill(); this.subSkillType = subSkillType; - if(player != null) + if (player != null) this.skillLevel = UserManager.getPlayer(player).getSkillLevel(primarySkillType); else this.skillLevel = 0; - if(player != null) + if (player != null) isLucky = Permissions.lucky(player, primarySkillType); else isLucky = false; @@ -55,6 +53,7 @@ public class RandomChanceSkill implements RandomChanceExecution { /** * The subskill corresponding to this RandomChanceSkill + * * @return this subskill */ public SubSkillType getSubSkill() { @@ -63,15 +62,16 @@ public class RandomChanceSkill implements RandomChanceExecution { /** * Gets the skill level of the player who owns this RandomChanceSkill + * * @return the current skill level relating to this RandomChanceSkill */ - public int getSkillLevel() - { + public int getSkillLevel() { return skillLevel; } /** * Modify the skill level used for this skill's RNG calculations + * * @param newSkillLevel new skill level */ public void setSkillLevel(int newSkillLevel) { diff --git a/src/main/java/com/gmail/nossr50/util/random/RandomChanceSkillStatic.java b/src/main/java/com/gmail/nossr50/util/random/RandomChanceSkillStatic.java index 0e00849f7..eb95c04b8 100644 --- a/src/main/java/com/gmail/nossr50/util/random/RandomChanceSkillStatic.java +++ b/src/main/java/com/gmail/nossr50/util/random/RandomChanceSkillStatic.java @@ -6,8 +6,7 @@ import org.bukkit.entity.Player; public class RandomChanceSkillStatic extends RandomChanceSkill { private final double xPos; - public RandomChanceSkillStatic(double xPos, Player player, SubSkillType subSkillType) - { + public RandomChanceSkillStatic(double xPos, Player player, SubSkillType subSkillType) { super(player, subSkillType); this.xPos = xPos; diff --git a/src/main/java/com/gmail/nossr50/util/random/RandomChanceStatic.java b/src/main/java/com/gmail/nossr50/util/random/RandomChanceStatic.java index 30f84cfbf..3204a348d 100644 --- a/src/main/java/com/gmail/nossr50/util/random/RandomChanceStatic.java +++ b/src/main/java/com/gmail/nossr50/util/random/RandomChanceStatic.java @@ -5,8 +5,7 @@ public class RandomChanceStatic implements RandomChanceExecution { private final double probabilityCap; private final boolean isLucky; - public RandomChanceStatic(double xPos, boolean isLucky) - { + public RandomChanceStatic(double xPos, boolean isLucky) { this.xPos = xPos; this.probabilityCap = xPos; this.isLucky = isLucky; diff --git a/src/main/java/com/gmail/nossr50/util/random/RandomChanceUtil.java b/src/main/java/com/gmail/nossr50/util/random/RandomChanceUtil.java index 6bb213c5e..994abbd67 100644 --- a/src/main/java/com/gmail/nossr50/util/random/RandomChanceUtil.java +++ b/src/main/java/com/gmail/nossr50/util/random/RandomChanceUtil.java @@ -14,8 +14,7 @@ import org.bukkit.entity.Player; import java.text.DecimalFormat; import java.util.Random; -public class RandomChanceUtil -{ +public class RandomChanceUtil { public static final DecimalFormat percent = new DecimalFormat("##0.00%"); //public static final DecimalFormat decimal = new DecimalFormat("##0.00"); public static final double LINEAR_CURVE_VAR = 100.0D; @@ -26,14 +25,12 @@ public class RandomChanceUtil * non-RNG skills just fire the cancellable event and succeed if they go uncancelled * * @param skillActivationType this value represents what kind of activation procedures this sub-skill uses - * @param subSkillType The identifier for this specific sub-skill - * @param player The owner of this sub-skill + * @param subSkillType The identifier for this specific sub-skill + * @param player The owner of this sub-skill * @return returns true if all conditions are met and they event is not cancelled */ - public static boolean isActivationSuccessful(SkillActivationType skillActivationType, SubSkillType subSkillType, Player player) - { - switch(skillActivationType) - { + public static boolean isActivationSuccessful(SkillActivationType skillActivationType, SubSkillType subSkillType, Player player) { + switch (skillActivationType) { case RANDOM_LINEAR_100_SCALE_WITH_CAP: return checkRandomChanceExecutionSuccess(player, subSkillType, true); case RANDOM_STATIC_CHANCE: @@ -46,10 +43,8 @@ public class RandomChanceUtil } } - public static double getActivationChance(SkillActivationType skillActivationType, SubSkillType subSkillType, Player player) - { - switch(skillActivationType) - { + public static double getActivationChance(SkillActivationType skillActivationType, SubSkillType subSkillType, Player player) { + switch (skillActivationType) { case RANDOM_LINEAR_100_SCALE_WITH_CAP: return getRandomChanceExecutionSuccess(player, subSkillType, true); case RANDOM_STATIC_CHANCE: @@ -61,10 +56,10 @@ public class RandomChanceUtil /** * Checks whether or not the random chance succeeds + * * @return true if the random chance succeeds */ - public static boolean checkRandomChanceExecutionSuccess(Player player, PrimarySkillType primarySkillType, double chance) - { + public static boolean checkRandomChanceExecutionSuccess(Player player, PrimarySkillType primarySkillType, double chance) { //Check the odds chance *= 100; @@ -88,19 +83,18 @@ public class RandomChanceUtil /** * Used for stuff like Excavation, Fishing, etc... + * * @param randomChance * @return */ - public static boolean checkRandomChanceExecutionSuccess(RandomChanceSkillStatic randomChance) - { + public static boolean checkRandomChanceExecutionSuccess(RandomChanceSkillStatic randomChance) { double chanceOfSuccess = calculateChanceOfSuccess(randomChance); //Check the odds return rollDice(chanceOfSuccess, 100); } - public static boolean checkRandomChanceExecutionSuccess(RandomChanceSkill randomChance) - { + public static boolean checkRandomChanceExecutionSuccess(RandomChanceSkill randomChance) { double chanceOfSuccess = calculateChanceOfSuccess(randomChance); Random random = new Random(); @@ -118,6 +112,7 @@ public class RandomChanceUtil /** * Gets the Static Chance for something to activate + * * @param randomChance * @return */ @@ -176,27 +171,23 @@ public class RandomChanceUtil * * @return the chance of success from 0-100 (100 = guaranteed) */ - private static int getChanceOfSuccess(double skillLevel, double maxProbability, double maxLevel) - { + private static int getChanceOfSuccess(double skillLevel, double maxProbability, double maxLevel) { //return (int) (x / (y / LINEAR_CURVE_VAR)); - return (int) (maxProbability * (skillLevel/maxLevel)); + return (int) (maxProbability * (skillLevel / maxLevel)); // max probability * (weight/maxlevel) = chance of success } - private static int getChanceOfSuccess(double x, double y) - { + private static int getChanceOfSuccess(double x, double y) { return (int) (x / (y / LINEAR_CURVE_VAR)); // max probability * (weight/maxlevel) = chance of success } - public static double getRandomChanceExecutionSuccess(Player player, SubSkillType subSkillType, boolean hasCap) - { + public static double getRandomChanceExecutionSuccess(Player player, SubSkillType subSkillType, boolean hasCap) { RandomChanceSkill rcs = new RandomChanceSkill(player, subSkillType, hasCap); return calculateChanceOfSuccess(rcs); } - public static double getRandomStaticChanceExecutionSuccess(Player player, SubSkillType subSkillType) - { + public static double getRandomStaticChanceExecutionSuccess(Player player, SubSkillType subSkillType) { try { return getRandomChanceExecutionChance(new RandomChanceSkillStatic(getStaticRandomChance(subSkillType), player, subSkillType)); } catch (InvalidStaticChance invalidStaticChance) { @@ -207,18 +198,15 @@ public class RandomChanceUtil return 0.1337; //Puts on shades } - public static boolean checkRandomChanceExecutionSuccess(Player player, SubSkillType subSkillType, boolean hasCap) - { + public static boolean checkRandomChanceExecutionSuccess(Player player, SubSkillType subSkillType, boolean hasCap) { return checkRandomChanceExecutionSuccess(new RandomChanceSkill(player, subSkillType, hasCap)); } - public static boolean checkRandomChanceExecutionSuccess(Player player, SubSkillType subSkillType) - { + public static boolean checkRandomChanceExecutionSuccess(Player player, SubSkillType subSkillType) { return checkRandomChanceExecutionSuccess(new RandomChanceSkill(player, subSkillType)); } - public static boolean checkRandomStaticChanceExecutionSuccess(Player player, SubSkillType subSkillType) - { + public static boolean checkRandomStaticChanceExecutionSuccess(Player player, SubSkillType subSkillType) { try { return checkRandomChanceExecutionSuccess(new RandomChanceSkillStatic(getStaticRandomChance(subSkillType), player, subSkillType)); } catch (InvalidStaticChance invalidStaticChance) { @@ -231,14 +219,13 @@ public class RandomChanceUtil /** * Grabs static activation rolls for Secondary Abilities + * * @param subSkillType The secondary ability to grab properties of - * @throws InvalidStaticChance if the skill has no defined static chance this exception will be thrown and you should know you're a naughty boy * @return The static activation roll involved in the RNG calculation + * @throws InvalidStaticChance if the skill has no defined static chance this exception will be thrown and you should know you're a naughty boy */ - public static double getStaticRandomChance(SubSkillType subSkillType) throws InvalidStaticChance - { - switch(subSkillType) - { + public static double getStaticRandomChance(SubSkillType subSkillType) throws InvalidStaticChance { + switch (subSkillType) { case AXES_ARMOR_IMPACT: return AdvancedConfig.getInstance().getImpactChance(); case AXES_GREATER_IMPACT: @@ -250,8 +237,7 @@ public class RandomChanceUtil } } - public static boolean sendSkillEvent(Player player, SubSkillType subSkillType, double activationChance) - { + public static boolean sendSkillEvent(Player player, SubSkillType subSkillType, double activationChance) { SubSkillRandomCheckEvent event = new SubSkillRandomCheckEvent(player, subSkillType, activationChance); return !event.isCancelled(); } @@ -262,8 +248,7 @@ public class RandomChanceUtil return (event.getChance() * activationChance) > (Misc.getRandom().nextDouble() * activationChance) && !event.isCancelled(); }*/ - public static boolean isActivationSuccessful(SkillActivationType skillActivationType, AbstractSubSkill abstractSubSkill, Player player) - { + public static boolean isActivationSuccessful(SkillActivationType skillActivationType, AbstractSubSkill abstractSubSkill, Player player) { return isActivationSuccessful(skillActivationType, abstractSubSkill.getSubSkillType(), player); } @@ -311,17 +296,15 @@ public class RandomChanceUtil return displayValues; } - public static double addLuck(Player player, PrimarySkillType primarySkillType, double chance) - { - if(Permissions.lucky(player, primarySkillType)) + public static double addLuck(Player player, PrimarySkillType primarySkillType, double chance) { + if (Permissions.lucky(player, primarySkillType)) return chance * 1.333D; else return chance; } - public static double addLuck(boolean isLucky, double chance) - { - if(isLucky) + public static double addLuck(boolean isLucky, double chance) { + if (isLucky) return chance * 1.333D; else return chance; diff --git a/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardManager.java b/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardManager.java index 803010e5b..bc75b558f 100644 --- a/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardManager.java +++ b/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardManager.java @@ -43,9 +43,10 @@ public class ScoreboardManager { static final String LABEL_ABILITY_COOLDOWN = LocaleLoader.getString("Scoreboard.Misc.Cooldown"); static final String LABEL_OVERALL = LocaleLoader.getString("Scoreboard.Misc.Overall"); - static final Map skillLabels; + static final Map skillLabels; static final Map abilityLabelsColored; static final Map abilityLabelsSkill; + private static List dirtyPowerLevels = new ArrayList<>(); /* * Initializes the static properties of this class @@ -128,17 +129,6 @@ public class ScoreboardManager { abilityLabelsSkill = abilityLabelSkillBuilder.build(); } - private static List dirtyPowerLevels = new ArrayList<>(); - - public enum SidebarType { - NONE, - SKILL_BOARD, - STATS_BOARD, - COOLDOWNS_BOARD, - RANK_BOARD, - TOP_BOARD - } - private static String formatAbility(String abilityName) { return formatAbility(ChatColor.AQUA, abilityName); } @@ -146,8 +136,7 @@ public class ScoreboardManager { private static String formatAbility(ChatColor color, String abilityName) { if (mcMMO.getScoreboardSettings().getUseAbilityNamesOverGenerics()) { return getShortenedName(color + abilityName); - } - else { + } else { return color + LocaleLoader.getString("Scoreboard.Misc.Ability"); } } @@ -164,14 +153,14 @@ public class ScoreboardManager { return name; } - // **** Listener call-ins **** // - // Called by PlayerJoinEvent listener public static void setupPlayer(Player player) { PLAYER_SCOREBOARDS.put(player.getName(), ScoreboardWrapper.create(player)); dirtyPowerLevels.add(player.getName()); } + // **** Listener call-ins **** // + // Called by PlayerQuitEvent listener public static void teardownPlayer(Player player) { ScoreboardWrapper wrapper = PLAYER_SCOREBOARDS.remove(player.getName()); @@ -246,8 +235,6 @@ public class ScoreboardManager { } } - // **** Setup methods **** // - public static void enablePlayerSkillScoreboard(Player player, PrimarySkillType skill) { ScoreboardWrapper wrapper = PLAYER_SCOREBOARDS.get(player.getName()); @@ -257,6 +244,8 @@ public class ScoreboardManager { changeScoreboard(wrapper, mcMMO.getScoreboardSettings().getScoreboardDisplayTime(SidebarType.SKILL_BOARD)); } + // **** Setup methods **** // + public static void enablePlayerSkillLevelUpScoreboard(Player player, PrimarySkillType skill) { ScoreboardWrapper wrapper = PLAYER_SCOREBOARDS.get(player.getName()); @@ -338,8 +327,6 @@ public class ScoreboardManager { changeScoreboard(wrapper, mcMMO.getScoreboardSettings().getScoreboardDisplayTime(SidebarType.TOP_BOARD)); } - // **** Helper methods **** // - /** * @return false if power levels are disabled */ @@ -371,6 +358,8 @@ public class ScoreboardManager { return true; } + // **** Helper methods **** // + /** * Gets or creates the power level objective on the main targetBoard. *

@@ -405,8 +394,7 @@ public class ScoreboardManager { private static void changeScoreboard(ScoreboardWrapper wrapper, int displayTime) { if (displayTime == -1) { wrapper.showBoardWithNoRevert(); - } - else { + } else { wrapper.showBoardAndScheduleRevert(displayTime * Misc.TICK_CONVERSION_FACTOR); } } @@ -426,4 +414,13 @@ public class ScoreboardManager { public static void setRevertTimer(String playerName, int seconds) { PLAYER_SCOREBOARDS.get(playerName).showBoardAndScheduleRevert(seconds * Misc.TICK_CONVERSION_FACTOR); } + + public enum SidebarType { + NONE, + SKILL_BOARD, + STATS_BOARD, + COOLDOWNS_BOARD, + RANK_BOARD, + TOP_BOARD + } } diff --git a/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardWrapper.java b/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardWrapper.java index d19fb999c..e5c316bcd 100644 --- a/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardWrapper.java +++ b/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardWrapper.java @@ -30,20 +30,21 @@ public class ScoreboardWrapper { public final String playerName; public final Player player; private final Scoreboard scoreboard; + public String targetPlayer = null; + public PrimarySkillType targetSkill = null; + public int leaderboardPage = -1; + public BukkitTask updateTask = null; + public BukkitTask revertTask = null; + public BukkitTask cooldownTask = null; private boolean tippedKeep = false; private boolean tippedClear = false; - // Internal usage variables (should exist) private SidebarType sidebarType; private Objective sidebarObjective; private Objective powerObjective; - // Parameter variables (May be null / invalid) private Scoreboard oldBoard = null; - public String targetPlayer = null; - public PrimarySkillType targetSkill = null; private PlayerProfile targetProfile = null; - public int leaderboardPage = -1; private ScoreboardWrapper(Player player, Scoreboard scoreboard) { this.player = player; @@ -71,42 +72,6 @@ public class ScoreboardWrapper { return new ScoreboardWrapper(event.getTargetPlayer(), event.getTargetBoard()); } - public BukkitTask updateTask = null; - - private class ScoreboardQuickUpdate extends BukkitRunnable { - @Override - public void run() { - updateSidebar(); - updateTask = null; - } - } - - public BukkitTask revertTask = null; - - private class ScoreboardChangeTask extends BukkitRunnable { - @Override - public void run() { - tryRevertBoard(); - revertTask = null; - } - } - - public BukkitTask cooldownTask = null; - - private class ScoreboardCooldownTask extends BukkitRunnable { - @Override - public void run() { - // Stop updating if it's no longer something displaying cooldowns - if (isBoardShown() && (isSkillScoreboard() || isCooldownScoreboard())) { - doSidebarUpdateSoon(); - } - else { - stopCooldownUpdating(); - } - } - } - - public void doSidebarUpdateSoon() { if (updateTask == null) { // To avoid spamming the scheduler, store the instance and run 2 ticks later @@ -126,8 +91,7 @@ public class ScoreboardWrapper { if (cooldownTask != null) { try { cooldownTask.cancel(); - } - catch (Throwable ignored) { + } catch (Throwable ignored) { } cooldownTask = null; @@ -164,8 +128,7 @@ public class ScoreboardWrapper { // (Shouldn't happen) Use failsafe value - we're already displaying our board, but we don't have the one we should revert to this.oldBoard = mcMMO.p.getServer().getScoreboardManager().getMainScoreboard(); } - } - else { + } else { this.oldBoard = oldBoard; } } @@ -204,7 +167,7 @@ public class ScoreboardWrapper { // TODO is there any way to do the time that looks acceptable? // player.sendMessage(LocaleLoader.getString("Commands.ConfigScoreboard.Timer", StringUtils.capitalize(sidebarType.toString().toLowerCase()), ticks / 20F)); - if(UserManager.getPlayer(playerName) == null) + if (UserManager.getPlayer(playerName) == null) return; PlayerProfile profile = UserManager.getPlayer(player).getProfile(); @@ -216,8 +179,7 @@ public class ScoreboardWrapper { if (!tippedKeep) { tippedKeep = true; player.sendMessage(LocaleLoader.getString("Commands.Scoreboard.Tip.Keep")); - } - else if (!tippedClear) { + } else if (!tippedClear) { tippedClear = true; player.sendMessage(LocaleLoader.getString("Commands.Scoreboard.Tip.Clear")); profile.increaseTipsShown(); @@ -242,8 +204,7 @@ public class ScoreboardWrapper { //Modify the player based on the event event.getTargetPlayer().setScoreboard(event.getTargetBoard()); oldBoard = null; - } - else { + } else { mcMMO.p.debug("Not reverting targetBoard for " + playerName + " - targetBoard was changed by another plugin (Consider disabling the mcMMO scoreboards if you don't want them!)"); } } @@ -277,8 +238,6 @@ public class ScoreboardWrapper { revertTask = null; } - // Board Type Changing 'API' methods - public void setTypeNone() { this.sidebarType = SidebarType.NONE; @@ -312,6 +271,8 @@ public class ScoreboardWrapper { loadObjective(ScoreboardManager.HEADER_STATS); } + // Board Type Changing 'API' methods + public void setTypeInspectStats(PlayerProfile profile) { this.sidebarType = SidebarType.STATS_BOARD; targetPlayer = profile.getPlayerName(); @@ -386,13 +347,13 @@ public class ScoreboardWrapper { protected void loadObjective(String displayName) { //Unregister objective McMMOScoreboardObjectiveEvent unregisterEvent = callObjectiveEvent(ScoreboardObjectiveEventReason.UNREGISTER_THIS_OBJECTIVE); - if(!unregisterEvent.isCancelled()) { + if (!unregisterEvent.isCancelled()) { sidebarObjective.unregister(); } //Register objective McMMOScoreboardObjectiveEvent registerEvent = callObjectiveEvent(ScoreboardObjectiveEventReason.REGISTER_NEW_OBJECTIVE); - if(!registerEvent.isCancelled()) + if (!registerEvent.isCancelled()) sidebarObjective = registerEvent.getTargetBoard().registerNewObjective(ScoreboardManager.SIDEBAR_OBJECTIVE, "dummy"); if (displayName.length() > 32) { @@ -418,8 +379,7 @@ public class ScoreboardWrapper { private void updateSidebar() { try { updateTask.cancel(); - } - catch (Throwable ignored) { + } catch (Throwable ignored) { } // catch NullPointerException and IllegalStateException and any Error; don't care updateTask = null; @@ -437,7 +397,7 @@ public class ScoreboardWrapper { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) return; switch (sidebarType) { @@ -450,8 +410,7 @@ public class ScoreboardWrapper { sidebarObjective.getScore(ScoreboardManager.LABEL_CURRENT_XP).setScore(currentXP); sidebarObjective.getScore(ScoreboardManager.LABEL_REMAINING_XP).setScore(mcMMOPlayer.getXpToLevel(targetSkill) - currentXP); - } - else { + } else { for (PrimarySkillType parentSkill : FamilyTree.getParents(targetSkill)) { sidebarObjective.getScore(ScoreboardManager.skillLabels.get(parentSkill)).setScore(mcMMOPlayer.getSkillLevel(parentSkill)); } @@ -473,8 +432,7 @@ public class ScoreboardWrapper { cooldownBM.setScore(secondsBM); stopUpdating = (secondsSB == 0 && secondsBM == 0); - } - else { + } else { SuperAbilityType ability = targetSkill.getAbility(); Score cooldown = sidebarObjective.getScore(ScoreboardManager.abilityLabelsSkill.get(ability)); int seconds = Math.max(mcMMOPlayer.calculateTimeRemaining(ability), 0); @@ -486,8 +444,7 @@ public class ScoreboardWrapper { if (stopUpdating) { stopCooldownUpdating(); - } - else { + } else { startCooldownUpdating(); } } @@ -508,8 +465,7 @@ public class ScoreboardWrapper { if (anyCooldownsActive) { startCooldownUpdating(); - } - else { + } else { stopCooldownUpdating(); } break; @@ -520,11 +476,9 @@ public class ScoreboardWrapper { if (targetProfile != null) { newProfile = targetProfile; // offline - } - else if (targetPlayer == null) { + } else if (targetPlayer == null) { newProfile = mcMMOPlayer.getProfile(); // self - } - else { + } else { newProfile = UserManager.getPlayer(targetPlayer).getProfile(); // online } @@ -548,10 +502,10 @@ public class ScoreboardWrapper { case RANK_BOARD: case TOP_BOARD: - /* - * @see #acceptRankData(Map rank) - * @see #acceptLeaderboardData(List stats) - */ + /* + * @see #acceptRankData(Map rank) + * @see #acceptLeaderboardData(List stats) + */ break; default: @@ -597,4 +551,32 @@ public class ScoreboardWrapper { public void updatePowerLevel(Player player, int newPowerLevel) { powerObjective.getScore(player.getName()).setScore(newPowerLevel); } + + private class ScoreboardQuickUpdate extends BukkitRunnable { + @Override + public void run() { + updateSidebar(); + updateTask = null; + } + } + + private class ScoreboardChangeTask extends BukkitRunnable { + @Override + public void run() { + tryRevertBoard(); + revertTask = null; + } + } + + private class ScoreboardCooldownTask extends BukkitRunnable { + @Override + public void run() { + // Stop updating if it's no longer something displaying cooldowns + if (isBoardShown() && (isSkillScoreboard() || isCooldownScoreboard())) { + doSidebarUpdateSoon(); + } else { + stopCooldownUpdating(); + } + } + } } diff --git a/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java b/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java index c9c3194bb..89a857d76 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java @@ -37,13 +37,14 @@ import java.util.HashMap; import java.util.Map; public final class CombatUtils { - private CombatUtils() {} + private CombatUtils() { + } private static void processSwordCombat(LivingEntity target, Player player, EntityDamageByEntityEvent event) { if (event.getCause() == DamageCause.THORNS) { return; } - + McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); SwordsManager swordsManager = mcMMOPlayer.getSwordsManager(); double initialDamage = event.getDamage(); @@ -55,26 +56,23 @@ public final class CombatUtils { mcMMOPlayer.checkAbilityActivation(PrimarySkillType.SWORDS); } - if(target.getHealth() - event.getFinalDamage() >= 1) - { + if (target.getHealth() - event.getFinalDamage() >= 1) { if (swordsManager.canUseRupture()) { swordsManager.ruptureCheck(target); } } //Add Stab Damage - if(swordsManager.canUseStab()) - { - finalDamage+=swordsManager.getStabDamage(); + if (swordsManager.canUseStab()) { + finalDamage += swordsManager.getStabDamage(); } if (swordsManager.canUseSerratedStrike()) { swordsManager.serratedStrikes(target, initialDamage, modifiers); } - if(canUseLimitBreak(player, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK)) - { - finalDamage+=getLimitBreakDamage(player, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK); + if (canUseLimitBreak(player, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK)) { + finalDamage += getLimitBreakDamage(player, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK); } applyScaledModifiers(initialDamage, finalDamage, event); @@ -85,7 +83,7 @@ public final class CombatUtils { if (event.getCause() == DamageCause.THORNS) { return; } - + double initialDamage = event.getDamage(); double finalDamage = initialDamage; Map modifiers = getModifiers(event); @@ -98,14 +96,13 @@ public final class CombatUtils { } if (axesManager.canUseAxeMastery()) { - finalDamage+=axesManager.axeMastery(); + finalDamage += axesManager.axeMastery(); } if (axesManager.canImpact(target)) { axesManager.impactCheck(target); - } - else if (axesManager.canGreaterImpact(target)) { - finalDamage+=axesManager.greaterImpact(target); + } else if (axesManager.canGreaterImpact(target)) { + finalDamage += axesManager.greaterImpact(target); } if (axesManager.canUseSkullSplitter(target)) { @@ -113,12 +110,11 @@ public final class CombatUtils { } if (axesManager.canCriticalHit(target)) { - finalDamage+=axesManager.criticalHit(target, finalDamage); + finalDamage += axesManager.criticalHit(target, finalDamage); } - if(canUseLimitBreak(player, SubSkillType.AXES_AXES_LIMIT_BREAK)) - { - finalDamage+=getLimitBreakDamage(player, SubSkillType.AXES_AXES_LIMIT_BREAK); + if (canUseLimitBreak(player, SubSkillType.AXES_AXES_LIMIT_BREAK)) { + finalDamage += getLimitBreakDamage(player, SubSkillType.AXES_AXES_LIMIT_BREAK); } applyScaledModifiers(initialDamage, finalDamage, event); @@ -140,24 +136,22 @@ public final class CombatUtils { mcMMOPlayer.checkAbilityActivation(PrimarySkillType.UNARMED); } - if(unarmedManager.isPunchingCooldownOver()) - { + if (unarmedManager.isPunchingCooldownOver()) { //Only execute bonuses if the player is not spamming if (unarmedManager.canUseIronArm()) { - finalDamage+=unarmedManager.ironArm(); + finalDamage += unarmedManager.ironArm(); } if (unarmedManager.canUseBerserk()) { - finalDamage+=unarmedManager.berserkDamage(finalDamage); + finalDamage += unarmedManager.berserkDamage(finalDamage); } if (unarmedManager.canDisarm(target)) { unarmedManager.disarmCheck((Player) target); } - if(canUseLimitBreak(player, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK)) - { - finalDamage+=getLimitBreakDamage(player, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK); + if (canUseLimitBreak(player, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK)) { + finalDamage += getLimitBreakDamage(player, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK); } } @@ -180,11 +174,11 @@ public final class CombatUtils { tamingManager.pummel(target, wolf); if (tamingManager.canUseSharpenedClaws()) { - finalDamage+=tamingManager.getSharpenedClawsDamage(); + finalDamage += tamingManager.getSharpenedClawsDamage(); } if (tamingManager.canUseGore()) { - finalDamage+=tamingManager.gore(target, initialDamage); + finalDamage += tamingManager.gore(target, initialDamage); } applyScaledModifiers(initialDamage, finalDamage, event); @@ -196,7 +190,7 @@ public final class CombatUtils { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); ArcheryManager archeryManager = mcMMOPlayer.getArcheryManager(); - + double finalDamage = event.getDamage(); if (target instanceof Player && PrimarySkillType.UNARMED.getPVPEnabled()) { @@ -212,20 +206,19 @@ public final class CombatUtils { } if (archeryManager.canSkillShot()) { - finalDamage+=archeryManager.skillShot(initialDamage); + finalDamage += archeryManager.skillShot(initialDamage); } if (archeryManager.canDaze(target)) { - finalDamage+=archeryManager.daze((Player) target); + finalDamage += archeryManager.daze((Player) target); } if (!arrow.hasMetadata(mcMMO.infiniteArrowKey) && archeryManager.canRetrieveArrows()) { archeryManager.retrieveArrows(target); } - if(canUseLimitBreak(player, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK)) - { - finalDamage+=getLimitBreakDamage(player, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK); + if (canUseLimitBreak(player, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK)) { + finalDamage += getLimitBreakDamage(player, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK); } double distanceMultiplier = archeryManager.distanceXpBonusMultiplier(target, arrow); @@ -305,8 +298,7 @@ public final class CombatUtils { if (PrimarySkillType.SWORDS.getPermissions(player)) { processSwordCombat(target, player, event); } - } - else if (ItemUtils.isAxe(heldItem)) { + } else if (ItemUtils.isAxe(heldItem)) { if (!PrimarySkillType.AXES.shouldProcess(target)) { return; } @@ -314,8 +306,7 @@ public final class CombatUtils { if (PrimarySkillType.AXES.getPermissions(player)) { processAxeCombat(target, player, event); } - } - else if (ItemUtils.isUnarmed(heldItem)) { + } else if (ItemUtils.isUnarmed(heldItem)) { if (!PrimarySkillType.UNARMED.shouldProcess(target)) { return; } @@ -324,9 +315,7 @@ public final class CombatUtils { processUnarmedCombat(target, player, event); } } - } - - else if (entityType == EntityType.WOLF) { + } else if (entityType == EntityType.WOLF) { Wolf wolf = (Wolf) damager; AnimalTamer tamer = wolf.getOwner(); @@ -337,8 +326,7 @@ public final class CombatUtils { processTamingCombat(target, master, wolf, event); } } - } - else if (entityType == EntityType.ARROW) { + } else if (entityType == EntityType.ARROW) { Arrow arrow = (Arrow) damager; ProjectileSource projectileSource = arrow.getShooter(); @@ -364,6 +352,7 @@ public final class CombatUtils { /** * Checks if player has access to their weapons limit break + * * @param player target player * @return true if the player has access to the limit break */ @@ -386,8 +375,8 @@ public final class CombatUtils { /** * Attempt to damage target for value dmg with reason ENTITY_ATTACK with damager attacker * - * @param target LivingEntity which to attempt to damage - * @param damage Amount of damage to attempt to do + * @param target LivingEntity which to attempt to damage + * @param damage Amount of damage to attempt to do * @param attacker Player to pass to event as damager */ @Deprecated @@ -398,8 +387,8 @@ public final class CombatUtils { /** * Attempt to damage target for value dmg with reason ENTITY_ATTACK with damager attacker * - * @param target LivingEntity which to attempt to damage - * @param damage Amount of damage to attempt to do + * @param target LivingEntity which to attempt to damage + * @param damage Amount of damage to attempt to do * @param attacker Player to pass to event as damager */ public static void dealDamage(LivingEntity target, double damage, Map modifiers, LivingEntity attacker) { @@ -414,8 +403,8 @@ public final class CombatUtils { /** * Attempt to damage target for value dmg with reason ENTITY_ATTACK with damager attacker * - * @param target LivingEntity which to attempt to damage - * @param damage Amount of damage to attempt to do + * @param target LivingEntity which to attempt to damage + * @param damage Amount of damage to attempt to do * @param attacker Player to pass to event as damager */ @Deprecated @@ -424,7 +413,7 @@ public final class CombatUtils { return; } - if(canDamage(attacker, target, cause, damage)) + if (canDamage(attacker, target, cause, damage)) target.damage(damage); } @@ -437,11 +426,9 @@ public final class CombatUtils { double newHealth = Math.max(0, target.getHealth() - incDmg); - if(newHealth == 0) - { + if (newHealth == 0) { target.damage(9999, attacker); - } - else + } else target.setHealth(newHealth); } @@ -487,9 +474,9 @@ public final class CombatUtils { * Apply Area-of-Effect ability actions. * * @param attacker The attacking player - * @param target The defending entity - * @param damage The initial damage amount - * @param type The type of skill being used + * @param target The defending entity + * @param damage The initial damage amount + * @param type The type of skill being used */ public static void applyAbilityAoE(Player attacker, LivingEntity target, double damage, Map modifiers, PrimarySkillType type) { int numberOfTargets = getTier(attacker.getInventory().getItemInMainHand()); // The higher the weapon tier, the more targets you hit @@ -510,7 +497,7 @@ public final class CombatUtils { switch (type) { case SWORDS: if (entity instanceof Player) { - NotificationManager.sendPlayerInformation((Player)entity, NotificationType.SUBSKILL_MESSAGE, "Swords.Combat.SS.Struck"); + NotificationManager.sendPlayerInformation((Player) entity, NotificationType.SUBSKILL_MESSAGE, "Swords.Combat.SS.Struck"); } UserManager.getPlayer(attacker).getSwordsManager().ruptureCheck(target); @@ -518,7 +505,7 @@ public final class CombatUtils { case AXES: if (entity instanceof Player) { - NotificationManager.sendPlayerInformation((Player)entity, NotificationType.SUBSKILL_MESSAGE, "Axes.Combat.SS.Struck"); + NotificationManager.sendPlayerInformation((Player) entity, NotificationType.SUBSKILL_MESSAGE, "Axes.Combat.SS.Struck"); } break; @@ -539,8 +526,8 @@ public final class CombatUtils { /** * Start the task that gives combat XP. * - * @param mcMMOPlayer The attacking player - * @param target The defending entity + * @param mcMMOPlayer The attacking player + * @param target The defending entity * @param primarySkillType The skill being used */ private static void startGainXp(McMMOPlayer mcMMOPlayer, LivingEntity target, PrimarySkillType primarySkillType, double multiplier) { @@ -558,8 +545,7 @@ public final class CombatUtils { if (defender.isOnline() && SkillUtils.cooldownExpired(mcMMOPlayer.getRespawnATS(), Misc.PLAYER_RESPAWN_COOLDOWN_SECONDS)) { baseXP = 20 * ExperienceConfig.getInstance().getPlayerVersusPlayerXP(); } - } - else { + } else { /*if (mcMMO.getModManager().isCustomEntity(target)) { baseXP = mcMMO.getModManager().getEntity(target).getXpMultiplier(); }*/ @@ -567,29 +553,21 @@ public final class CombatUtils { if (target instanceof Animals) { EntityType type = target.getType(); baseXP = ExperienceConfig.getInstance().getAnimalsXP(type); - } - else if (target instanceof Monster) - { + } else if (target instanceof Monster) { EntityType type = target.getType(); baseXP = ExperienceConfig.getInstance().getCombatXP(type); - } - else { + } else { EntityType type = target.getType(); if (ExperienceConfig.getInstance().hasCombatXP(type)) { - if (type == EntityType.IRON_GOLEM) - { + if (type == EntityType.IRON_GOLEM) { if (!((IronGolem) target).isPlayerCreated()) { baseXP = ExperienceConfig.getInstance().getCombatXP(type); } - } - else - { + } else { baseXP = ExperienceConfig.getInstance().getCombatXP(type); } - } - else - { + } else { baseXP = 1.0; //mcMMO.getModManager().addCustomEntity(target); } @@ -627,7 +605,7 @@ public final class CombatUtils { Player defender = (Player) entity; //TODO: NPC Interaction? - if(UserManager.getPlayer(defender) == null) + if (UserManager.getPlayer(defender) == null) return true; if (!defender.getWorld().getPVP() || defender == player || UserManager.getPlayer(defender).getGodMode()) { @@ -642,7 +620,7 @@ public final class CombatUtils { if (!player.canSee(defender)) { return false; } - + // Spectators should not be affected if (defender.getGameMode() == GameMode.SPECTATOR) { return false; @@ -652,8 +630,7 @@ public final class CombatUtils { if (getFakeDamageFinalResult(player, entity, 1.0) == 0) { return false; } - } - else if (entity instanceof Tameable) { + } else if (entity instanceof Tameable) { if (isFriendlyPet(player, (Tameable) entity)) { // isFriendlyPet ensures that the Tameable is: Tamed, owned by a player, and the owner is in the same party // So we can make some assumptions here, about our casting and our check @@ -670,7 +647,7 @@ public final class CombatUtils { /** * Checks to see if an entity is currently invincible. * - * @param entity The {@link LivingEntity} to check + * @param entity The {@link LivingEntity} to check * @param eventDamage The damage from the event the entity is involved in * @return true if the entity is invincible, false otherwise */ @@ -686,7 +663,7 @@ public final class CombatUtils { * Checks to see if an entity is currently friendly toward a given player. * * @param attacker The player to check. - * @param pet The entity to check. + * @param pet The entity to check. * @return true if the entity is friendly, false otherwise */ public static boolean isFriendlyPet(Player attacker, Tameable pet) { @@ -810,17 +787,13 @@ public final class CombatUtils { if (ItemUtils.isWoodTool(inHand)) { tier = 1; - } - else if (ItemUtils.isStoneTool(inHand)) { + } else if (ItemUtils.isStoneTool(inHand)) { tier = 2; - } - else if (ItemUtils.isIronTool(inHand)) { + } else if (ItemUtils.isIronTool(inHand)) { tier = 3; - } - else if (ItemUtils.isGoldTool(inHand)) { + } else if (ItemUtils.isGoldTool(inHand)) { tier = 1; - } - else if (ItemUtils.isDiamondTool(inHand)) { + } else if (ItemUtils.isDiamondTool(inHand)) { tier = 4; } /*else if (mcMMO.getModManager().isCustomTool(inHand)) { diff --git a/src/main/java/com/gmail/nossr50/util/skills/ParticleEffectUtils.java b/src/main/java/com/gmail/nossr50/util/skills/ParticleEffectUtils.java index fd952c38e..bc0d7f9ce 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/ParticleEffectUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/ParticleEffectUtils.java @@ -12,7 +12,8 @@ import org.bukkit.entity.Player; public final class ParticleEffectUtils { - private ParticleEffectUtils() {} + private ParticleEffectUtils() { + } public static void playBleedEffect(LivingEntity livingEntity) { if (!MainConfig.getInstance().getBleedEffectEnabled()) { diff --git a/src/main/java/com/gmail/nossr50/util/skills/PerksUtils.java b/src/main/java/com/gmail/nossr50/util/skills/PerksUtils.java index 962b0922e..aa00be243 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/PerksUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/PerksUtils.java @@ -9,16 +9,15 @@ public final class PerksUtils { private static final int LUCKY_SKILL_ACTIVATION_CHANCE = 75; private static final int NORMAL_SKILL_ACTIVATION_CHANCE = 100; - private PerksUtils() {} + private PerksUtils() { + } public static int handleCooldownPerks(Player player, int cooldown) { if (Permissions.halvedCooldowns(player)) { cooldown *= 0.5; - } - else if (Permissions.thirdedCooldowns(player)) { + } else if (Permissions.thirdedCooldowns(player)) { cooldown *= (2.0 / 3.0); - } - else if (Permissions.quarteredCooldowns(player)) { + } else if (Permissions.quarteredCooldowns(player)) { cooldown *= 0.75; } @@ -32,11 +31,9 @@ public final class PerksUtils { if (Permissions.twelveSecondActivationBoost(player)) { ticks += 12; - } - else if (Permissions.eightSecondActivationBoost(player)) { + } else if (Permissions.eightSecondActivationBoost(player)) { ticks += 8; - } - else if (Permissions.fourSecondActivationBoost(player)) { + } else if (Permissions.fourSecondActivationBoost(player)) { ticks += 4; } @@ -46,23 +43,17 @@ public final class PerksUtils { public static float handleXpPerks(Player player, float xp, PrimarySkillType skill) { if (Permissions.customXpBoost(player, skill)) { xp *= ExperienceConfig.getInstance().getCustomXpPerkBoost(); - } - else if (Permissions.quadrupleXp(player, skill)) { + } else if (Permissions.quadrupleXp(player, skill)) { xp *= 4; - } - else if (Permissions.tripleXp(player, skill)) { + } else if (Permissions.tripleXp(player, skill)) { xp *= 3; - } - else if (Permissions.doubleAndOneHalfXp(player, skill)) { + } else if (Permissions.doubleAndOneHalfXp(player, skill)) { xp *= 2.5; - } - else if (Permissions.doubleXp(player, skill)) { + } else if (Permissions.doubleXp(player, skill)) { xp *= 2; - } - else if (Permissions.oneAndOneHalfXp(player, skill)) { + } else if (Permissions.oneAndOneHalfXp(player, skill)) { xp *= 1.5; - } - else if (Permissions.oneAndOneTenthXp(player, skill)) { + } else if (Permissions.oneAndOneTenthXp(player, skill)) { xp *= 1.1; } @@ -73,7 +64,7 @@ public final class PerksUtils { * Calculate activation chance for a skill. * * @param player Player to check the activation chance for - * @param skill PrimarySkillType to check the activation chance of + * @param skill PrimarySkillType to check the activation chance of * @return the activation chance with "lucky perk" accounted for */ public static int handleLuckyPerks(Player player, PrimarySkillType skill) { diff --git a/src/main/java/com/gmail/nossr50/util/skills/RankUtils.java b/src/main/java/com/gmail/nossr50/util/skills/RankUtils.java index 061d8a616..9cabbdfec 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/RankUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/RankUtils.java @@ -19,27 +19,23 @@ public class RankUtils { private static int count = 0; /** - * - * @param plugin plugin instance ref - * @param mcMMOPlayer target player + * @param plugin plugin instance ref + * @param mcMMOPlayer target player * @param primarySkillType - * @param newLevel the new level of this skill + * @param newLevel the new level of this skill */ - public static void executeSkillUnlockNotifications(Plugin plugin, McMMOPlayer mcMMOPlayer, PrimarySkillType primarySkillType, int newLevel) - { - for(SubSkillType subSkillType : primarySkillType.getSkillAbilities()) - { + public static void executeSkillUnlockNotifications(Plugin plugin, McMMOPlayer mcMMOPlayer, PrimarySkillType primarySkillType, int newLevel) { + for (SubSkillType subSkillType : primarySkillType.getSkillAbilities()) { int playerRankInSkill = getRank(mcMMOPlayer.getPlayer(), subSkillType); HashMap innerMap = subSkillRanks.get(subSkillType.toString()); //If the skill doesn't have registered ranks gtfo - if(innerMap == null || innerMap.get(playerRankInSkill) == null) + if (innerMap == null || innerMap.get(playerRankInSkill) == null) continue; //The players level is the exact level requirement for this skill - if(newLevel == innerMap.get(playerRankInSkill)) - { + if (newLevel == innerMap.get(playerRankInSkill)) { SkillUnlockNotificationTask skillUnlockNotificationTask = new SkillUnlockNotificationTask(mcMMOPlayer, subSkillType, newLevel); skillUnlockNotificationTask.runTaskLater(plugin, (count * 100)); @@ -49,32 +45,27 @@ public class RankUtils { } } - public static void resetUnlockDelayTimer() - { + public static void resetUnlockDelayTimer() { count = 0; } /* NEW SYSTEM */ - private static void addRanks(AbstractSubSkill abstractSubSkill) - { + private static void addRanks(AbstractSubSkill abstractSubSkill) { //Fill out the rank array - for(int i = 0; i < abstractSubSkill.getNumRanks(); i++) - { + for (int i = 0; i < abstractSubSkill.getNumRanks(); i++) { //This adds the highest ranks first - addRank(abstractSubSkill, abstractSubSkill.getNumRanks()-i); + addRank(abstractSubSkill, abstractSubSkill.getNumRanks() - i); //TODO: Remove debug code /*System.out.println("DEBUG: Adding rank "+(numRanks-i)+" to "+subSkillType.toString());*/ } } - private static void addRanks(SubSkillType subSkillType) - { + private static void addRanks(SubSkillType subSkillType) { //Fill out the rank array - for(int i = 0; i < subSkillType.getNumRanks(); i++) - { + for (int i = 0; i < subSkillType.getNumRanks(); i++) { //This adds the highest ranks first - addRank(subSkillType, subSkillType.getNumRanks()-i); + addRank(subSkillType, subSkillType.getNumRanks() - i); //TODO: Remove debug code /*System.out.println("DEBUG: Adding rank "+(numRanks-i)+" to "+subSkillType.toString());*/ @@ -84,27 +75,24 @@ public class RankUtils { /** * Populates the ranks for every skill we know about */ - public static void populateRanks() - { - for(SubSkillType subSkillType : SubSkillType.values()) - { + public static void populateRanks() { + for (SubSkillType subSkillType : SubSkillType.values()) { addRanks(subSkillType); } - for(AbstractSubSkill abstractSubSkill : InteractionManager.getSubSkillList()) - { + for (AbstractSubSkill abstractSubSkill : InteractionManager.getSubSkillList()) { addRanks(abstractSubSkill); } } /** * Returns whether or not the player has unlocked the first rank in target subskill - * @param player the player + * + * @param player the player * @param subSkillType the target subskill * @return true if the player has at least one rank in the skill */ - public static boolean hasUnlockedSubskill(Player player, SubSkillType subSkillType) - { + public static boolean hasUnlockedSubskill(Player player, SubSkillType subSkillType) { int curRank = getRank(player, subSkillType); //-1 means the skill has no unlockable levels and is therefor unlocked @@ -113,12 +101,12 @@ public class RankUtils { /** * Returns whether or not the player has unlocked the first rank in target subskill - * @param player the player + * + * @param player the player * @param abstractSubSkill the target subskill * @return true if the player has at least one rank in the skill */ - public static boolean hasUnlockedSubskill(Player player, AbstractSubSkill abstractSubSkill) - { + public static boolean hasUnlockedSubskill(Player player, AbstractSubSkill abstractSubSkill) { int curRank = getRank(player, abstractSubSkill); //-1 means the skill has no unlockable levels and is therefor unlocked @@ -127,69 +115,68 @@ public class RankUtils { /** * Returns whether or not the player has reached the specified rank in target subskill - * @param rank the target rank - * @param player the player + * + * @param rank the target rank + * @param player the player * @param subSkillType the target subskill * @return true if the player is at least that rank in this subskill */ - public static boolean hasReachedRank(int rank, Player player, SubSkillType subSkillType) - { + public static boolean hasReachedRank(int rank, Player player, SubSkillType subSkillType) { return getRank(player, subSkillType) >= rank; } /** * Returns whether or not the player has reached the specified rank in target subskill - * @param rank the target rank - * @param player the player + * + * @param rank the target rank + * @param player the player * @param abstractSubSkill the target subskill * @return true if the player is at least that rank in this subskill */ - public static boolean hasReachedRank(int rank, Player player, AbstractSubSkill abstractSubSkill) - { + public static boolean hasReachedRank(int rank, Player player, AbstractSubSkill abstractSubSkill) { return getRank(player, abstractSubSkill) >= rank; } /** * Gets the current rank of the subskill for the player - * @param player The player in question + * + * @param player The player in question * @param subSkillType Target subskill * @return The rank the player currently has achieved in this skill. -1 for skills without ranks. */ - public static int getRank(Player player, SubSkillType subSkillType) - { + public static int getRank(Player player, SubSkillType subSkillType) { String skillName = subSkillType.toString(); int numRanks = subSkillType.getNumRanks(); - if(subSkillRanks == null) + if (subSkillRanks == null) subSkillRanks = new HashMap<>(); - if(numRanks == 0) + if (numRanks == 0) return -1; //-1 Means the skill doesn't have ranks - if(subSkillRanks.get(skillName) == null && numRanks > 0) + if (subSkillRanks.get(skillName) == null && numRanks > 0) addRanks(subSkillType); //Get our rank map HashMap rankMap = subSkillRanks.get(skillName); - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) return 0; //Skill level of parent skill int currentSkillLevel = UserManager.getPlayer(player).getSkillLevel(subSkillType.getParentSkill()); - for(int i = 0; i < numRanks; i++) - { + for (int i = 0; i < numRanks; i++) { //Compare against the highest to lowest rank in that order - int rank = numRanks-i; + int rank = numRanks - i; int unlockLevel = getRankUnlockLevel(subSkillType, rank); //If we check all ranks and still cannot unlock the skill, we return rank 0 - if(rank == 0) + if (rank == 0) return 0; //True if our skill level can unlock the current rank - if(currentSkillLevel >= unlockLevel) + if (currentSkillLevel >= unlockLevel) return rank; } @@ -198,45 +185,44 @@ public class RankUtils { /** * Gets the current rank of the subskill for the player - * @param player The player in question + * + * @param player The player in question * @param abstractSubSkill Target subskill * @return The rank the player currently has achieved in this skill. -1 for skills without ranks. */ - public static int getRank(Player player, AbstractSubSkill abstractSubSkill) - { + public static int getRank(Player player, AbstractSubSkill abstractSubSkill) { String skillName = abstractSubSkill.getConfigKeyName(); int numRanks = abstractSubSkill.getNumRanks(); - if(subSkillRanks == null) + if (subSkillRanks == null) subSkillRanks = new HashMap<>(); - if(numRanks == 0) + if (numRanks == 0) return -1; //-1 Means the skill doesn't have ranks - if(subSkillRanks.get(skillName) == null && numRanks > 0) + if (subSkillRanks.get(skillName) == null && numRanks > 0) addRanks(abstractSubSkill); //Get our rank map HashMap rankMap = subSkillRanks.get(skillName); - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) return 0; //Skill level of parent skill int currentSkillLevel = UserManager.getPlayer(player).getSkillLevel(abstractSubSkill.getPrimarySkill()); - for(int i = 0; i < numRanks; i++) - { + for (int i = 0; i < numRanks; i++) { //Compare against the highest to lowest rank in that order - int rank = numRanks-i; + int rank = numRanks - i; int unlockLevel = getRankUnlockLevel(abstractSubSkill, rank); //If we check all ranks and still cannot unlock the skill, we return rank 0 - if(rank == 0) + if (rank == 0) return 0; //True if our skill level can unlock the current rank - if(currentSkillLevel >= unlockLevel) + if (currentSkillLevel >= unlockLevel) return rank; } @@ -245,11 +231,11 @@ public class RankUtils { /** * Adds ranks to our map + * * @param abstractSubSkill The subskill to add ranks for - * @param rank The rank to add + * @param rank The rank to add */ - private static void addRank(AbstractSubSkill abstractSubSkill, int rank) - { + private static void addRank(AbstractSubSkill abstractSubSkill, int rank) { initMaps(abstractSubSkill.getConfigKeyName()); HashMap rankMap = subSkillRanks.get(abstractSubSkill.getConfigKeyName()); @@ -258,8 +244,7 @@ public class RankUtils { } @Deprecated - private static void addRank(SubSkillType subSkillType, int rank) - { + private static void addRank(SubSkillType subSkillType, int rank) { initMaps(subSkillType.toString()); HashMap rankMap = subSkillRanks.get(subSkillType.toString()); @@ -293,68 +278,65 @@ public class RankUtils { /** * Gets the unlock level for a specific rank in a subskill + * * @param subSkillType The target subskill - * @param rank The target rank + * @param rank The target rank * @return The level at which this rank unlocks */ @Deprecated - public static int getRankUnlockLevel(SubSkillType subSkillType, int rank) - { + public static int getRankUnlockLevel(SubSkillType subSkillType, int rank) { return RankConfig.getInstance().getSubSkillUnlockLevel(subSkillType, rank); } - public static int getRankUnlockLevel(AbstractSubSkill abstractSubSkill, int rank) - { + public static int getRankUnlockLevel(AbstractSubSkill abstractSubSkill, int rank) { return RankConfig.getInstance().getSubSkillUnlockLevel(abstractSubSkill, rank); } /** * Get the level at which a skill is unlocked for a player (this is the first rank of a skill) + * * @param subSkillType target subskill * @return The unlock requirements for rank 1 in this skill */ - public static int getUnlockLevel(SubSkillType subSkillType) - { + public static int getUnlockLevel(SubSkillType subSkillType) { return RankConfig.getInstance().getSubSkillUnlockLevel(subSkillType, 1); } /** * Get the level at which a skill is unlocked for a player (this is the first rank of a skill) + * * @param abstractSubSkill target subskill * @return The unlock requirements for rank 1 in this skill */ - public static int getUnlockLevel(AbstractSubSkill abstractSubSkill) - { + public static int getUnlockLevel(AbstractSubSkill abstractSubSkill) { return RankConfig.getInstance().getSubSkillUnlockLevel(abstractSubSkill, 1); } /** * Get the highest rank of a subskill + * * @param subSkillType target subskill * @return the last rank of a subskill */ - public static int getHighestRank(SubSkillType subSkillType) - { + public static int getHighestRank(SubSkillType subSkillType) { return subSkillType.getNumRanks(); } - public static String getHighestRankStr(SubSkillType subSkillType) - { + public static String getHighestRankStr(SubSkillType subSkillType) { return String.valueOf(subSkillType.getNumRanks()); } /** * Get the highest rank of a subskill + * * @param abstractSubSkill target subskill * @return the last rank of a subskill */ - public static int getHighestRank(AbstractSubSkill abstractSubSkill) - { + public static int getHighestRank(AbstractSubSkill abstractSubSkill) { return abstractSubSkill.getNumRanks(); } - public static int getSuperAbilityUnlockRequirement(SuperAbilityType superAbilityType) - { + public static int getSuperAbilityUnlockRequirement(SuperAbilityType superAbilityType) { return getRankUnlockLevel(superAbilityType.getSubSkillTypeDefinition(), 1); } } \ No newline at end of file diff --git a/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java b/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java index e947b918d..9db4db90c 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java @@ -47,9 +47,8 @@ public class SkillUtils { int length; - if(abilityLengthCap > 0) - { - length = (int) Math.min(abilityLengthCap, 2 + (skillValue / abilityLengthVar)); + if (abilityLengthCap > 0) { + length = (int) Math.min(abilityLengthCap, 2 + (skillValue / abilityLengthVar)); } else { length = 2 + (int) (skillValue / abilityLengthVar); } @@ -60,7 +59,7 @@ public class SkillUtils { length = Math.min(length, maxLength); } - return new String[] { String.valueOf(length), String.valueOf(enduranceLength) }; + return new String[]{String.valueOf(length), String.valueOf(enduranceLength)}; } /* @@ -73,7 +72,7 @@ public class SkillUtils { int currentFoodLevel = player.getFoodLevel(); int foodChange = eventFoodLevel - currentFoodLevel; - foodChange+=curRank; + foodChange += curRank; return currentFoodLevel + foodChange; } @@ -82,9 +81,8 @@ public class SkillUtils { * Calculate the time remaining until the cooldown expires. * * @param deactivatedTimeStamp Time of deactivation - * @param cooldown The length of the cooldown - * @param player The Player to check for cooldown perks - * + * @param cooldown The length of the cooldown + * @param player The Player to check for cooldown perks * @return the number of seconds remaining before the cooldown expires */ public static int calculateTimeLeft(long deactivatedTimeStamp, int cooldown, Player player) { @@ -96,8 +94,7 @@ public class SkillUtils { * This does NOT account for cooldown perks! * * @param deactivatedTimeStamp Time of deactivation in seconds - * @param cooldown The length of the cooldown in seconds - * + * @param cooldown The length of the cooldown in seconds * @return true if the cooldown is expired */ public static boolean cooldownExpired(long deactivatedTimeStamp, int cooldown) { @@ -207,8 +204,7 @@ public class SkillUtils { if (efficiencyLevel <= AdvancedConfig.getInstance().getEnchantBuff()) { itemMeta.removeEnchant(Enchantment.DIG_SPEED); - } - else { + } else { itemMeta.addEnchant(Enchantment.DIG_SPEED, efficiencyLevel - AdvancedConfig.getInstance().getEnchantBuff(), true); } @@ -225,9 +221,9 @@ public class SkillUtils { /** * Modify the durability of an ItemStack. * - * @param itemStack The ItemStack which durability should be modified + * @param itemStack The ItemStack which durability should be modified * @param durabilityModifier the amount to modify the durability by - * @param maxDamageModifier the amount to adjust the max damage by + * @param maxDamageModifier the amount to adjust the max damage by */ public static void handleDurabilityChange(ItemStack itemStack, int durabilityModifier, double maxDamageModifier) { if (itemStack.hasItemMeta() && itemStack.getItemMeta().isUnbreakable()) { @@ -254,26 +250,19 @@ public class SkillUtils { protected static Material getRepairAndSalvageItem(ItemStack inHand) { if (ItemUtils.isDiamondTool(inHand) || ItemUtils.isDiamondArmor(inHand)) { return Material.DIAMOND; - } - else if (ItemUtils.isGoldTool(inHand) || ItemUtils.isGoldArmor(inHand)) { + } else if (ItemUtils.isGoldTool(inHand) || ItemUtils.isGoldArmor(inHand)) { return Material.GOLD_INGOT; - } - else if (ItemUtils.isIronTool(inHand) || ItemUtils.isIronArmor(inHand)) { + } else if (ItemUtils.isIronTool(inHand) || ItemUtils.isIronArmor(inHand)) { return Material.IRON_INGOT; - } - else if (ItemUtils.isStoneTool(inHand)) { + } else if (ItemUtils.isStoneTool(inHand)) { return Material.COBBLESTONE; - } - else if (ItemUtils.isWoodTool(inHand)) { + } else if (ItemUtils.isWoodTool(inHand)) { return Material.OAK_WOOD; - } - else if (ItemUtils.isLeatherArmor(inHand)) { + } else if (ItemUtils.isLeatherArmor(inHand)) { return Material.LEATHER; - } - else if (ItemUtils.isStringTool(inHand)) { + } else if (ItemUtils.isStringTool(inHand)) { return Material.STRING; - } - else { + } else { return null; } } @@ -302,8 +291,7 @@ public class SkillUtils { quantity += ingredient.getAmount(); } } - } - else if (recipe instanceof ShapedRecipe) { + } else if (recipe instanceof ShapedRecipe) { for (ItemStack ingredient : ((ShapedRecipe) recipe).getIngredientMap().values()) { if (ingredient != null && (repairMaterial == null || ingredient.getType() == repairMaterial) && (repairMetadata == -1 || ingredient.getType().equals(repairMaterial))) { quantity += ingredient.getAmount(); diff --git a/src/main/java/com/gmail/nossr50/util/sounds/SoundManager.java b/src/main/java/com/gmail/nossr50/util/sounds/SoundManager.java index 3437873fd..dd9c603d6 100644 --- a/src/main/java/com/gmail/nossr50/util/sounds/SoundManager.java +++ b/src/main/java/com/gmail/nossr50/util/sounds/SoundManager.java @@ -11,47 +11,43 @@ import org.bukkit.entity.Player; public class SoundManager { /** * Sends a sound to the player + * * @param soundType the type of sound */ - public static void sendSound(Player player, Location location, SoundType soundType) - { - if(SoundConfig.getInstance().getIsEnabled(soundType)) + public static void sendSound(Player player, Location location, SoundType soundType) { + if (SoundConfig.getInstance().getIsEnabled(soundType)) player.playSound(location, getSound(soundType), SoundCategory.MASTER, getVolume(soundType), getPitch(soundType)); } - public static void sendCategorizedSound(Player player, Location location, SoundType soundType, SoundCategory soundCategory) - { - if(SoundConfig.getInstance().getIsEnabled(soundType)) + public static void sendCategorizedSound(Player player, Location location, SoundType soundType, SoundCategory soundCategory) { + if (SoundConfig.getInstance().getIsEnabled(soundType)) player.playSound(location, getSound(soundType), soundCategory, getVolume(soundType), getPitch(soundType)); } - public static void sendCategorizedSound(Player player, Location location, SoundType soundType, SoundCategory soundCategory, float pitchModifier) - { + public static void sendCategorizedSound(Player player, Location location, SoundType soundType, SoundCategory soundCategory, float pitchModifier) { float totalPitch = Math.min(2.0F, (getPitch(soundType) + pitchModifier)); - if(SoundConfig.getInstance().getIsEnabled(soundType)) + if (SoundConfig.getInstance().getIsEnabled(soundType)) player.playSound(location, getSound(soundType), soundCategory, getVolume(soundType), totalPitch); } - public static void worldSendSound(World world, Location location, SoundType soundType) - { - if(SoundConfig.getInstance().getIsEnabled(soundType)) + public static void worldSendSound(World world, Location location, SoundType soundType) { + if (SoundConfig.getInstance().getIsEnabled(soundType)) world.playSound(location, getSound(soundType), getVolume(soundType), getPitch(soundType)); } /** * All volume is multiplied by the master volume to get its final value + * * @param soundType target soundtype * @return the volume for this soundtype */ - private static float getVolume(SoundType soundType) - { + private static float getVolume(SoundType soundType) { return SoundConfig.getInstance().getVolume(soundType) * SoundConfig.getInstance().getMasterVolume(); } - private static float getPitch(SoundType soundType) - { - if(soundType == SoundType.FIZZ) + private static float getPitch(SoundType soundType) { + if (soundType == SoundType.FIZZ) return getFizzPitch(); else if (soundType == SoundType.POP) return getPopPitch(); @@ -59,10 +55,8 @@ public class SoundManager { return SoundConfig.getInstance().getPitch(soundType); } - private static Sound getSound(SoundType soundType) - { - switch(soundType) - { + private static Sound getSound(SoundType soundType) { + switch (soundType) { case ANVIL: return Sound.BLOCK_ANVIL_PLACE; case ITEM_BREAK: diff --git a/src/main/java/com/gmail/nossr50/util/sounds/SoundType.java b/src/main/java/com/gmail/nossr50/util/sounds/SoundType.java index 6ebaa3a71..c4d428be5 100644 --- a/src/main/java/com/gmail/nossr50/util/sounds/SoundType.java +++ b/src/main/java/com/gmail/nossr50/util/sounds/SoundType.java @@ -16,9 +16,8 @@ public enum SoundType { BLEED, TIRED; - public boolean usesCustomPitch() - { - switch(this){ + public boolean usesCustomPitch() { + switch (this) { case POP: case FIZZ: return true; diff --git a/src/main/java/com/gmail/nossr50/util/uuid/UUIDFetcher.java b/src/main/java/com/gmail/nossr50/util/uuid/UUIDFetcher.java index 683e0ab08..70c00888f 100644 --- a/src/main/java/com/gmail/nossr50/util/uuid/UUIDFetcher.java +++ b/src/main/java/com/gmail/nossr50/util/uuid/UUIDFetcher.java @@ -28,37 +28,6 @@ public class UUIDFetcher implements Callable> { this(names, true); } - public Map call() throws Exception { - Map uuidMap = new HashMap<>(); - int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST); - for (int i = 0; i < requests; i++) { - HttpURLConnection connection = createConnection(); - - List nameSubList = names.subList(i * PROFILES_PER_REQUEST, Math.min((i + 1) * PROFILES_PER_REQUEST, names.size())); - JsonArray array = new JsonArray(); - - for(String name : nameSubList) - { - JsonPrimitive element = new JsonPrimitive(name); - array.add(element); - } - - String body = array.getAsString(); - writeBody(connection, body); - for (Object profile : array) { - JsonObject jsonProfile = (JsonObject) profile; - String id = jsonProfile.get("id").getAsString(); - String name = jsonProfile.get("name").getAsString(); - UUID uuid = UUIDFetcher.getUUID(id); - uuidMap.put(name, uuid); - } - if (rateLimiting && i != requests - 1) { - Thread.sleep(RATE_LIMIT); - } - } - return uuidMap; - } - private static void writeBody(HttpURLConnection connection, String body) throws Exception { OutputStream stream = connection.getOutputStream(); stream.write(body.getBytes()); @@ -101,4 +70,34 @@ public class UUIDFetcher implements Callable> { public static UUID getUUIDOf(String name) throws Exception { return new UUIDFetcher(Collections.singletonList(name)).call().get(name); } + + public Map call() throws Exception { + Map uuidMap = new HashMap<>(); + int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST); + for (int i = 0; i < requests; i++) { + HttpURLConnection connection = createConnection(); + + List nameSubList = names.subList(i * PROFILES_PER_REQUEST, Math.min((i + 1) * PROFILES_PER_REQUEST, names.size())); + JsonArray array = new JsonArray(); + + for (String name : nameSubList) { + JsonPrimitive element = new JsonPrimitive(name); + array.add(element); + } + + String body = array.getAsString(); + writeBody(connection, body); + for (Object profile : array) { + JsonObject jsonProfile = (JsonObject) profile; + String id = jsonProfile.get("id").getAsString(); + String name = jsonProfile.get("name").getAsString(); + UUID uuid = UUIDFetcher.getUUID(id); + uuidMap.put(name, uuid); + } + if (rateLimiting && i != requests - 1) { + Thread.sleep(RATE_LIMIT); + } + } + return uuidMap; + } } diff --git a/src/main/java/com/gmail/nossr50/worldguard/WorldGuardManager.java b/src/main/java/com/gmail/nossr50/worldguard/WorldGuardManager.java index 07c2de7e0..78197c6a7 100644 --- a/src/main/java/com/gmail/nossr50/worldguard/WorldGuardManager.java +++ b/src/main/java/com/gmail/nossr50/worldguard/WorldGuardManager.java @@ -17,21 +17,19 @@ public class WorldGuardManager { private static WorldGuardManager instance; private WorldGuardPlugin worldGuardPluginRef; + public WorldGuardManager() { + + } + public static WorldGuardManager getInstance() { - if(instance == null) + if (instance == null) instance = new WorldGuardManager(); return instance; } - public WorldGuardManager() - { - - } - - public boolean hasMainFlag(Player player) - { - if(player == null) + public boolean hasMainFlag(Player player) { + if (player == null) return false; BukkitPlayer localPlayer = BukkitAdapter.adapt(player); @@ -47,9 +45,8 @@ public class WorldGuardManager { return query.testState(loc, WorldGuardPlugin.inst().wrapPlayer(player), WorldGuardFlags.MCMMO_ENABLE_WG_FLAG); } - public boolean hasXPFlag(Player player) - { - if(player == null) + public boolean hasXPFlag(Player player) { + if (player == null) return false; BukkitPlayer localPlayer = BukkitAdapter.adapt(player); @@ -76,9 +73,8 @@ public class WorldGuardManager { return worldGuardPluginRef; } - public void registerFlags() - { - if(getWorldGuard() == null) + public void registerFlags() { + if (getWorldGuard() == null) return; FlagRegistry registry = WorldGuard.getInstance().getFlagRegistry(); diff --git a/src/main/java/com/gmail/nossr50/worldguard/WorldGuardUtils.java b/src/main/java/com/gmail/nossr50/worldguard/WorldGuardUtils.java index d04ee6c11..bceadc725 100644 --- a/src/main/java/com/gmail/nossr50/worldguard/WorldGuardUtils.java +++ b/src/main/java/com/gmail/nossr50/worldguard/WorldGuardUtils.java @@ -11,8 +11,7 @@ public class WorldGuardUtils { private static boolean isLoaded = false; private static boolean hasWarned = false; - public static boolean isWorldGuardLoaded() - { + public static boolean isWorldGuardLoaded() { WorldGuardPlugin plugin = getWorldGuard(); try { @@ -31,25 +30,21 @@ public class WorldGuardUtils { return true; } - private static WorldGuardPlugin getWorldGuard() - { - if(isLoaded) + private static WorldGuardPlugin getWorldGuard() { + if (isLoaded) return worldGuardPluginRef; Plugin plugin = getServer().getPluginManager().getPlugin("WorldGuard"); - if(plugin instanceof WorldGuardPlugin) - { - if(plugin.getDescription().getVersion().startsWith("7")) - { + if (plugin instanceof WorldGuardPlugin) { + if (plugin.getDescription().getVersion().startsWith("7")) { worldGuardPluginRef = (WorldGuardPlugin) plugin; - if(worldGuardPluginRef != null) + if (worldGuardPluginRef != null) isLoaded = true; } else { - if(!hasWarned) - { + if (!hasWarned) { mcMMO.p.getLogger().severe("mcMMO only supports WorldGuard version 7! Make sure you have WG 7! This warning will not appear again."); hasWarned = true; } diff --git a/src/main/java/net/shatteredlands/shatt/backup/ZipLibrary.java b/src/main/java/net/shatteredlands/shatt/backup/ZipLibrary.java index e254bd7c4..dba472df1 100644 --- a/src/main/java/net/shatteredlands/shatt/backup/ZipLibrary.java +++ b/src/main/java/net/shatteredlands/shatt/backup/ZipLibrary.java @@ -35,8 +35,7 @@ public class ZipLibrary { if (BACKUP_DIR.mkdir()) { mcMMO.p.debug("Created Backup Directory."); } - } - catch (Exception e) { + } catch (Exception e) { mcMMO.p.getLogger().severe(e.toString()); } @@ -68,8 +67,7 @@ public class ZipLibrary { for (File source : sources) { if (source.isDirectory()) { zipDir(zipOut, "", source); - } - else { + } else { zipFile(zipOut, "", source); } } @@ -99,8 +97,7 @@ public class ZipLibrary { for (File source : files) { if (source.isDirectory()) { zipDir(zos, path, source); - } - else { + } else { zipFile(zos, path, source); } }