From e52371aeb3d23bc4adff2ca55fd1b093d4690a96 Mon Sep 17 00:00:00 2001 From: nossr50 Date: Thu, 3 Jul 2025 14:03:43 -0700 Subject: [PATCH] formatting applied to most of the source code to tidy things up, and misc refactors --- Changelog.txt | 2 +- pom.xml | 4 +- .../com/gmail/nossr50/api/AbilityAPI.java | 11 +- .../java/com/gmail/nossr50/api/ChatAPI.java | 71 +- .../com/gmail/nossr50/api/DatabaseAPI.java | 8 +- .../com/gmail/nossr50/api/ExperienceAPI.java | 371 ++++----- .../nossr50/api/FakeBlockBreakEventType.java | 3 +- .../gmail/nossr50/api/ItemSpawnReason.java | 3 +- .../java/com/gmail/nossr50/api/PartyAPI.java | 54 +- .../java/com/gmail/nossr50/api/SkillAPI.java | 22 +- .../IncompleteNamespacedKeyRegister.java | 2 + .../InvalidFormulaTypeException.java | 3 + .../exceptions/InvalidPlayerException.java | 3 + .../api/exceptions/InvalidSkillException.java | 3 + .../InvalidXPGainReasonException.java | 3 + .../McMMOPlayerNotFoundException.java | 5 +- .../exceptions/ValueOutOfBoundsException.java | 9 - .../com/gmail/nossr50/chat/ChatManager.java | 75 +- .../nossr50/chat/SamePartyPredicate.java | 13 +- .../chat/author/AbstractPlayerAuthor.java | 49 +- .../com/gmail/nossr50/chat/author/Author.java | 7 +- .../nossr50/chat/author/ConsoleAuthor.java | 3 +- .../nossr50/chat/mailer/AdminChatMailer.java | 33 +- .../gmail/nossr50/chat/mailer/ChatMailer.java | 1 + .../nossr50/chat/mailer/PartyChatMailer.java | 29 +- .../chat/message/AbstractChatMessage.java | 32 +- .../chat/message/AdminChatMessage.java | 4 +- .../nossr50/chat/message/ChatMessage.java | 38 +- .../chat/message/PartyChatMessage.java | 40 +- .../nossr50/commands/CommandManager.java | 29 +- .../nossr50/commands/McabilityCommand.java | 7 +- .../nossr50/commands/McconvertCommand.java | 28 +- .../gmail/nossr50/commands/McgodCommand.java | 7 +- .../gmail/nossr50/commands/McmmoCommand.java | 17 +- .../nossr50/commands/McnotifyCommand.java | 18 +- .../nossr50/commands/McrefreshCommand.java | 12 +- .../nossr50/commands/McscoreboardCommand.java | 17 +- .../gmail/nossr50/commands/ToggleCommand.java | 27 +- .../gmail/nossr50/commands/XprateCommand.java | 47 +- .../commands/admin/CompatibilityCommand.java | 8 +- .../commands/admin/DropTreasureCommand.java | 57 -- .../admin/McmmoReloadLocaleCommand.java | 4 +- .../commands/admin/PlayerDebugCommand.java | 11 +- .../commands/chat/AdminChatCommand.java | 17 +- .../nossr50/commands/chat/McChatSpy.java | 8 +- .../commands/chat/PartyChatCommand.java | 27 +- .../database/ConvertDatabaseCommand.java | 39 +- .../commands/database/McpurgeCommand.java | 9 +- .../commands/database/McremoveCommand.java | 22 +- .../commands/database/MmoshowdbCommand.java | 12 +- .../commands/experience/AddlevelsCommand.java | 23 +- .../commands/experience/AddxpCommand.java | 21 +- .../experience/ConvertExperienceCommand.java | 19 +- .../experience/ExperienceCommand.java | 61 +- .../commands/experience/MmoeditCommand.java | 23 +- .../experience/SkillresetCommand.java | 48 +- .../commands/party/PartyAcceptCommand.java | 15 +- .../party/PartyChangeOwnerCommand.java | 6 +- .../party/PartyChangePasswordCommand.java | 9 +- .../nossr50/commands/party/PartyCommand.java | 114 +-- .../commands/party/PartyCreateCommand.java | 15 +- .../commands/party/PartyDisbandCommand.java | 14 +- .../commands/party/PartyHelpCommand.java | 6 +- .../commands/party/PartyInfoCommand.java | 48 +- .../commands/party/PartyInviteCommand.java | 23 +- .../commands/party/PartyItemShareCommand.java | 40 +- .../commands/party/PartyJoinCommand.java | 24 +- .../commands/party/PartyKickCommand.java | 9 +- .../commands/party/PartyLockCommand.java | 9 +- .../commands/party/PartyQuitCommand.java | 15 +- .../commands/party/PartyRenameCommand.java | 20 +- .../commands/party/PartySubcommandType.java | 6 +- .../commands/party/PartyXpShareCommand.java | 19 +- .../alliance/PartyAllianceAcceptCommand.java | 16 +- .../party/alliance/PartyAllianceCommand.java | 42 +- .../alliance/PartyAllianceDisbandCommand.java | 12 +- .../alliance/PartyAllianceInviteCommand.java | 15 +- .../party/teleport/PtpAcceptAnyCommand.java | 6 +- .../party/teleport/PtpAcceptCommand.java | 17 +- .../commands/party/teleport/PtpCommand.java | 343 +++++---- .../party/teleport/PtpToggleCommand.java | 6 +- .../commands/player/InspectCommand.java | 43 +- .../commands/player/McRankCommand.java | 48 +- .../nossr50/commands/player/McTopCommand.java | 46 +- .../commands/player/MccooldownCommand.java | 24 +- .../commands/player/McstatsCommand.java | 20 +- .../nossr50/commands/player/XPBarCommand.java | 64 +- .../nossr50/commands/server/Mcmmoupgrade.java | 3 +- .../commands/skills/AcrobaticsCommand.java | 25 +- .../commands/skills/AlchemyCommand.java | 25 +- .../nossr50/commands/skills/AprilCommand.java | 2 +- .../commands/skills/ArcheryCommand.java | 34 +- .../nossr50/commands/skills/AxesCommand.java | 47 +- .../commands/skills/CrossbowsCommand.java | 20 +- .../commands/skills/ExcavationCommand.java | 20 +- .../commands/skills/FishingCommand.java | 89 ++- .../commands/skills/HerbalismCommand.java | 78 +- .../nossr50/commands/skills/MacesCommand.java | 35 +- .../commands/skills/MiningCommand.java | 62 +- .../commands/skills/MmoInfoCommand.java | 36 +- .../commands/skills/PowerLevelCommand.java | 7 +- .../commands/skills/RepairCommand.java | 44 +- .../commands/skills/SalvageCommand.java | 22 +- .../nossr50/commands/skills/SkillCommand.java | 92 ++- .../commands/skills/SkillGuideCommand.java | 18 +- .../commands/skills/SmeltingCommand.java | 34 +- .../commands/skills/SwordsCommand.java | 59 +- .../commands/skills/TamingCommand.java | 58 +- .../commands/skills/TridentsCommand.java | 26 +- .../commands/skills/UnarmedCommand.java | 50 +- .../commands/skills/WoodcuttingCommand.java | 42 +- .../gmail/nossr50/config/AdvancedConfig.java | 122 +-- .../config/AutoUpdateLegacyConfigLoader.java | 13 +- .../gmail/nossr50/config/BukkitConfig.java | 31 +- .../com/gmail/nossr50/config/ChatConfig.java | 10 +- .../nossr50/config/CoreSkillsConfig.java | 16 +- .../config/CustomItemSupportConfig.java | 6 +- .../gmail/nossr50/config/GeneralConfig.java | 173 +++-- .../gmail/nossr50/config/HiddenConfig.java | 3 +- .../nossr50/config/LegacyConfigLoader.java | 19 +- .../com/gmail/nossr50/config/RankConfig.java | 52 +- .../com/gmail/nossr50/config/SoundConfig.java | 9 +- .../gmail/nossr50/config/WorldBlacklist.java | 24 +- .../config/experience/ExperienceConfig.java | 98 ++- .../config/party/ItemWeightConfig.java | 11 +- .../nossr50/config/party/PartyConfig.java | 1 - .../config/skills/alchemy/PotionConfig.java | 197 +++-- .../config/skills/repair/RepairConfig.java | 41 +- .../skills/repair/RepairConfigManager.java | 4 +- .../config/skills/salvage/SalvageConfig.java | 91 ++- .../skills/salvage/SalvageConfigManager.java | 4 +- .../treasure/FishingTreasureConfig.java | 139 ++-- .../config/treasure/TreasureConfig.java | 198 +++-- .../nossr50/database/DatabaseManager.java | 39 +- .../database/DatabaseManagerFactory.java | 52 +- .../database/FlatFileDataProcessor.java | 125 +++- .../database/FlatFileDatabaseManager.java | 614 +++++++++------ .../nossr50/database/SQLDatabaseManager.java | 701 ++++++++++-------- .../gmail/nossr50/database/UserQueryFull.java | 3 +- .../gmail/nossr50/database/UserQueryUUID.java | 3 +- .../nossr50/database/UserQueryUUIDImpl.java | 3 +- .../flatfile/BadCategorizedFlatFileData.java | 19 +- .../flatfile/CategorizedFlatFileData.java | 17 +- .../flatfile/FlatFileDataBuilder.java | 6 +- .../flatfile/FlatFileDataContainer.java | 3 +- .../database/flatfile/FlatFileDataUtil.java | 96 ++- .../datatypes/BlockLocationHistory.java | 12 +- .../nossr50/datatypes/BlockSnapshot.java | 4 +- .../datatypes/LevelUpBroadcastPredicate.java | 21 +- .../PowerLevelUpBroadcastPredicate.java | 21 +- .../nossr50/datatypes/chat/ChatChannel.java | 8 +- .../datatypes/experience/FormulaType.java | 3 +- .../datatypes/experience/SkillXpGain.java | 6 +- .../nossr50/datatypes/json/McMMOUrl.java | 12 +- .../nossr50/datatypes/json/McMMOWebLinks.java | 8 +- .../datatypes/meta/RuptureTaskMeta.java | 3 +- .../nossr50/datatypes/meta/UUIDMeta.java | 5 +- .../nossr50/datatypes/mods/CustomEntity.java | 3 +- .../datatypes/party/ItemShareType.java | 3 +- .../gmail/nossr50/datatypes/party/Party.java | 62 +- .../nossr50/datatypes/party/PartyFeature.java | 9 +- .../datatypes/party/PartyTeleportRecord.java | 4 +- .../nossr50/datatypes/party/ShareMode.java | 3 +- .../nossr50/datatypes/player/McMMOPlayer.java | 296 +++++--- .../datatypes/player/PlayerProfile.java | 92 ++- .../datatypes/skills/MaterialType.java | 5 +- .../datatypes/skills/PrimarySkillType.java | 130 +++- .../datatypes/skills/SubSkillFlags.java | 18 +- .../datatypes/skills/SubSkillType.java | 53 +- .../datatypes/skills/SuperAbilityType.java | 30 +- .../skills/alchemy/AlchemyPotion.java | 33 +- .../datatypes/skills/alchemy/PotionStage.java | 10 +- .../skills/interfaces/ChildSkill.java | 1 + .../skills/interfaces/CoreSkill.java | 9 +- .../skills/interfaces/Localized.java | 6 +- .../datatypes/skills/interfaces/Skill.java | 2 + .../datatypes/skills/interfaces/Toolable.java | 10 +- .../skills/progression/Progression.java | 1 + .../skills/subskills/AbstractSubSkill.java | 12 +- .../acrobatics/AcrobaticsSubSkill.java | 15 +- .../skills/subskills/acrobatics/Roll.java | 114 +-- .../subskills/acrobatics/RollResult.java | 6 +- .../subskills/interfaces/Interaction.java | 3 + .../skills/subskills/interfaces/Rank.java | 2 + .../skills/subskills/interfaces/SubSkill.java | 14 +- .../subskills/taming/CallOfTheWildType.java | 5 +- .../skills/subskills/taming/TamingSummon.java | 5 +- .../treasure/EnchantmentWrapper.java | 11 +- .../treasure/FishingTreasureBook.java | 24 +- .../nossr50/datatypes/treasure/Rarity.java | 6 +- .../nossr50/datatypes/treasure/Treasure.java | 12 +- .../McMMOReplaceVanillaTreasureEvent.java | 10 +- .../events/chat/McMMOAdminChatEvent.java | 3 +- .../nossr50/events/chat/McMMOChatEvent.java | 27 +- .../events/chat/McMMOPartyChatEvent.java | 4 +- .../McMMOPlayerExperienceEvent.java | 9 +- .../McMMOPlayerLevelChangeEvent.java | 3 +- .../experience/McMMOPlayerLevelDownEvent.java | 6 +- .../experience/McMMOPlayerLevelUpEvent.java | 6 +- .../experience/McMMOPlayerPreXpGainEvent.java | 3 +- .../experience/McMMOPlayerXpGainEvent.java | 3 +- .../events/fake/FakeBlockDamageEvent.java | 3 +- .../nossr50/events/fake/FakeBrewEvent.java | 6 +- .../gmail/nossr50/events/fake/FakeEvent.java | 9 +- .../events/fake/FakePlayerAnimationEvent.java | 2 +- .../McMMOPlayerDeathPenaltyEvent.java | 14 +- .../McMMOPlayerPreDeathPenaltyEvent.java | 8 +- .../hardcore/McMMOPlayerStatLossEvent.java | 6 +- .../hardcore/McMMOPlayerVampirismEvent.java | 6 +- .../events/items/McMMOItemSpawnEvent.java | 18 +- .../party/McMMOPartyAllianceChangeEvent.java | 11 +- .../events/party/McMMOPartyChangeEvent.java | 11 +- .../events/party/McMMOPartyLevelUpEvent.java | 8 +- .../events/party/McMMOPartyTeleportEvent.java | 4 +- .../events/party/McMMOPartyXpGainEvent.java | 8 +- .../players/McMMOPlayerProfileLoadEvent.java | 13 +- .../scoreboard/McMMOScoreboardEvent.java | 16 +- .../McMMOScoreboardMakeboardEvent.java | 9 +- .../McMMOScoreboardObjectiveEvent.java | 6 +- .../McMMOScoreboardRevertEvent.java | 9 +- .../skills/McMMOPlayerNotificationEvent.java | 5 +- .../events/skills/McMMOPlayerSkillEvent.java | 13 +- .../skills/SkillActivationPerkEvent.java | 2 - .../McMMOPlayerAbilityActivateEvent.java | 6 +- .../McMMOPlayerAbilityDeactivateEvent.java | 10 +- .../abilities/McMMOPlayerAbilityEvent.java | 4 +- .../skills/alchemy/McMMOPlayerBrewEvent.java | 4 +- .../alchemy/McMMOPlayerCatalysisEvent.java | 4 +- .../McMMOPlayerFishingTreasureEvent.java | 7 +- .../fishing/McMMOPlayerMagicHunterEvent.java | 15 +- .../fishing/McMMOPlayerMasterAnglerEvent.java | 20 +- .../repair/McMMOPlayerRepairCheckEvent.java | 7 +- .../McMMOEntityDamageByRuptureEvent.java | 17 +- .../salvage/McMMOPlayerSalvageCheckEvent.java | 10 +- .../SubSkillBlockEvent.java | 4 +- .../secondaryabilities/SubSkillEvent.java | 24 +- .../taming/McMMOPlayerTameEntityEvent.java | 6 +- .../unarmed/McMMOPlayerDisarmEvent.java | 4 +- .../nossr50/listeners/BlockListener.java | 300 +++++--- .../nossr50/listeners/ChunkListener.java | 12 +- .../nossr50/listeners/EntityListener.java | 404 ++++++---- .../nossr50/listeners/InteractionManager.java | 37 +- .../nossr50/listeners/InventoryListener.java | 133 +++- .../nossr50/listeners/PlayerListener.java | 438 ++++++----- .../gmail/nossr50/listeners/SelfListener.java | 60 +- .../nossr50/listeners/WorldListener.java | 9 +- .../gmail/nossr50/locale/LocaleLoader.java | 158 ++-- src/main/java/com/gmail/nossr50/mcMMO.java | 210 ++++-- .../com/gmail/nossr50/party/PartyManager.java | 267 ++++--- .../com/gmail/nossr50/party/ShareHandler.java | 39 +- .../nossr50/placeholders/PapiExpansion.java | 75 +- .../PartyIsMemberPlaceholder.java | 1 + .../nossr50/protocollib/ProtocolHandler.java | 36 - .../protocollib/ProtocolLibManager.java | 40 - .../MobHealthDisplayUpdaterTask.java | 8 +- .../nossr50/runnables/SaveTimerTask.java | 8 +- .../runnables/backups/CleanBackupsTask.java | 38 +- .../commands/McRankCommandAsyncTask.java | 15 +- .../commands/McRankCommandDisplayTask.java | 18 +- .../commands/McTopCommandAsyncTask.java | 18 +- .../commands/MctopCommandDisplayTask.java | 28 +- .../database/DatabaseConversionTask.java | 3 +- .../database/FormulaConversionTask.java | 28 +- .../database/UUIDUpdateAsyncTask.java | 36 +- .../runnables/database/UserPurgeTask.java | 2 +- .../runnables/items/ChimaeraWingWarmup.java | 25 +- .../runnables/items/TeleportationWarmup.java | 37 +- .../runnables/party/PartyAutoKickTask.java | 9 +- .../player/ClearRegisteredXPGainTask.java | 4 +- .../player/PlayerProfileLoadingTask.java | 43 +- .../runnables/skills/AbilityCooldownTask.java | 13 +- .../runnables/skills/AbilityDisableTask.java | 27 +- .../skills/AlchemyBrewCheckTask.java | 16 +- .../runnables/skills/AlchemyBrewTask.java | 25 +- .../nossr50/runnables/skills/AprilTask.java | 2 +- .../runnables/skills/AwardCombatXpTask.java | 11 +- .../runnables/skills/BleedContainer.java | 13 +- .../runnables/skills/BleedTimerTask.java | 6 +- .../runnables/skills/DelayedCropReplant.java | 26 +- .../skills/DelayedHerbalismXPCheckTask.java | 10 +- .../skills/ExperienceBarHideTask.java | 18 +- .../runnables/skills/MasterAnglerTask.java | 3 +- .../nossr50/runnables/skills/RuptureTask.java | 51 +- .../skills/SkillUnlockNotificationTask.java | 23 +- .../runnables/skills/ToolLowerTask.java | 13 +- .../gmail/nossr50/skills/SkillManager.java | 5 +- .../nossr50/skills/acrobatics/Acrobatics.java | 10 +- .../skills/acrobatics/AcrobaticsManager.java | 50 +- .../gmail/nossr50/skills/alchemy/Alchemy.java | 15 +- .../skills/alchemy/AlchemyManager.java | 22 +- .../skills/alchemy/AlchemyPotionBrewer.java | 45 +- .../gmail/nossr50/skills/archery/Archery.java | 23 +- .../skills/archery/ArcheryManager.java | 44 +- .../nossr50/skills/archery/TrackedEntity.java | 3 +- .../com/gmail/nossr50/skills/axes/Axes.java | 35 +- .../nossr50/skills/axes/AxesManager.java | 76 +- .../nossr50/skills/crossbows/Crossbows.java | 18 +- .../skills/crossbows/CrossbowsManager.java | 39 +- .../nossr50/skills/excavation/Excavation.java | 19 +- .../skills/excavation/ExcavationManager.java | 31 +- .../gmail/nossr50/skills/fishing/Fishing.java | 17 +- .../skills/fishing/FishingManager.java | 178 +++-- .../nossr50/skills/herbalism/Herbalism.java | 2 - .../skills/herbalism/HerbalismManager.java | 246 ++++-- .../nossr50/skills/maces/MacesManager.java | 9 +- .../nossr50/skills/mining/BlastMining.java | 25 +- .../nossr50/skills/mining/MiningManager.java | 95 ++- .../nossr50/skills/repair/ArcaneForging.java | 6 +- .../gmail/nossr50/skills/repair/Repair.java | 8 +- .../nossr50/skills/repair/RepairManager.java | 138 ++-- .../skills/repair/repairables/Repairable.java | 7 +- .../repair/repairables/RepairableFactory.java | 32 +- .../repair/repairables/RepairableManager.java | 6 +- .../repair/repairables/SimpleRepairable.java | 17 +- .../repairables/SimpleRepairableManager.java | 5 +- .../gmail/nossr50/skills/salvage/Salvage.java | 21 +- .../skills/salvage/SalvageManager.java | 100 ++- .../salvage/salvageables/Salvageable.java | 7 +- .../salvageables/SalvageableFactory.java | 22 +- .../salvageables/SalvageableManager.java | 6 +- .../salvageables/SimpleSalvageable.java | 4 +- .../SimpleSalvageableManager.java | 5 +- .../skills/smelting/SmeltingManager.java | 28 +- .../gmail/nossr50/skills/swords/Swords.java | 5 +- .../nossr50/skills/swords/SwordsManager.java | 59 +- .../gmail/nossr50/skills/taming/Taming.java | 20 +- .../nossr50/skills/taming/TamingManager.java | 191 +++-- .../skills/taming/TrackedTamingEntity.java | 14 +- .../gmail/nossr50/skills/unarmed/Unarmed.java | 25 +- .../skills/unarmed/UnarmedManager.java | 77 +- .../woodcutting/WoodcuttingManager.java | 167 +++-- .../gmail/nossr50/util/AttributeMapper.java | 21 +- .../com/gmail/nossr50/util/BlockUtils.java | 132 ++-- .../nossr50/util/CancellableRunnable.java | 1 - .../com/gmail/nossr50/util/ChimaeraWing.java | 56 +- .../nossr50/util/ContainerMetadataUtils.java | 36 +- .../gmail/nossr50/util/EnchantmentMapper.java | 5 +- .../gmail/nossr50/util/EnchantmentUtils.java | 7 +- .../com/gmail/nossr50/util/EventUtils.java | 267 ++++--- .../util/FixSpellingNetheriteUtil.java | 10 +- .../gmail/nossr50/util/HardcoreManager.java | 48 +- .../gmail/nossr50/util/HolidayManager.java | 5 +- .../gmail/nossr50/util/ItemMetadataUtils.java | 37 +- .../com/gmail/nossr50/util/ItemUtils.java | 295 ++++---- .../com/gmail/nossr50/util/LogFilter.java | 5 +- .../java/com/gmail/nossr50/util/LogUtils.java | 3 +- .../gmail/nossr50/util/MaterialMapStore.java | 25 +- .../com/gmail/nossr50/util/MaterialUtils.java | 5 +- .../gmail/nossr50/util/MetadataConstants.java | 29 +- .../gmail/nossr50/util/MetadataService.java | 16 +- .../java/com/gmail/nossr50/util/Misc.java | 86 ++- .../gmail/nossr50/util/MobHealthbarUtils.java | 51 +- .../gmail/nossr50/util/MobMetadataUtils.java | 67 +- .../java/com/gmail/nossr50/util/Motd.java | 41 +- .../com/gmail/nossr50/util/Permissions.java | 550 ++++++++++---- .../gmail/nossr50/util/PotionEffectUtil.java | 19 +- .../com/gmail/nossr50/util/PotionUtil.java | 100 ++- .../nossr50/util/TransientEntityTracker.java | 50 +- .../nossr50/util/TransientMetadataTools.java | 14 +- .../nossr50/util/adapter/BiomeAdapter.java | 18 +- .../util/blockmeta/BitSetChunkStore.java | 102 ++- .../nossr50/util/blockmeta/ChunkManager.java | 2 + .../nossr50/util/blockmeta/ChunkStore.java | 4 +- .../util/blockmeta/HashChunkManager.java | 102 ++- .../util/blockmeta/McMMOSimpleRegionFile.java | 75 +- .../util/blockmeta/NullChunkManager.java | 21 +- .../util/blockmeta/UserBlockTracker.java | 28 +- .../commands/CommandRegistrationManager.java | 178 +++-- .../nossr50/util/commands/CommandUtils.java | 100 ++- .../util/compat/CompatibilityLayer.java | 6 +- .../util/compat/CompatibilityManager.java | 25 +- .../layers/AbstractCompatibilityLayer.java | 7 +- .../layers/AbstractNMSCompatibilityLayer.java | 7 +- .../PlayerAttackCooldownMethods.java | 24 +- .../PlayerAttackCooldownToolLayer.java | 2 +- ...actBungeeSerializerCompatibilityLayer.java | 2 +- ...geeLegacySerializerCompatibilityLayer.java | 3 +- ...geeModernSerializerCompatibilityLayer.java | 3 +- .../MasterAnglerCompatibilityLayer.java | 40 +- .../util/experience/ExperienceBarManager.java | 66 +- .../util/experience/ExperienceBarWrapper.java | 66 +- .../util/experience/FormulaManager.java | 61 +- .../gmail/nossr50/util/nms/NMSConstants.java | 9 +- .../gmail/nossr50/util/nms/NMSVersion.java | 3 +- .../util/platform/AbstractPlatform.java | 11 +- .../nossr50/util/platform/BukkitPlatform.java | 9 +- .../util/platform/MajorMinorPatchVersion.java | 35 +- .../util/platform/MinecraftGameVersion.java | 22 +- .../gmail/nossr50/util/platform/Platform.java | 9 +- .../util/platform/PlatformBuilder.java | 9 +- .../util/platform/PlatformManager.java | 23 +- .../util/player/NotificationManager.java | 205 +++-- .../nossr50/util/player/PlayerLevelUtils.java | 14 +- .../nossr50/util/player/UserManager.java | 79 +- .../nossr50/util/random/Probability.java | 74 +- .../nossr50/util/random/ProbabilityImpl.java | 26 +- .../nossr50/util/random/ProbabilityUtil.java | 276 ++++--- .../util/scoreboards/ScoreboardManager.java | 139 ++-- .../util/scoreboards/ScoreboardWrapper.java | 154 ++-- .../nossr50/util/skills/CombatUtils.java | 440 ++++++----- .../util/skills/ParticleEffectUtils.java | 28 +- .../gmail/nossr50/util/skills/PerksUtils.java | 24 +- .../nossr50/util/skills/ProjectileUtils.java | 11 +- .../gmail/nossr50/util/skills/RankUtils.java | 116 ++- .../gmail/nossr50/util/skills/SkillTools.java | 96 ++- .../gmail/nossr50/util/skills/SkillUtils.java | 163 ++-- .../nossr50/util/sounds/SoundManager.java | 59 +- .../gmail/nossr50/util/sounds/SoundType.java | 2 +- .../nossr50/util/text/ConfigStringUtils.java | 24 +- .../nossr50/util/text/McMMOMessageType.java | 8 +- .../gmail/nossr50/util/text/StringUtils.java | 51 +- .../util/text/TextComponentFactory.java | 274 ++++--- .../gmail/nossr50/util/text/TextUtils.java | 40 +- .../nossr50/util/upgrade/UpgradeManager.java | 17 +- .../nossr50/worldguard/WorldGuardManager.java | 34 +- .../nossr50/worldguard/WorldGuardUtils.java | 46 +- .../shatt/backup/ZipLibrary.java | 22 +- .../com/gmail/nossr50/MMOTestEnvironment.java | 45 +- .../database/FlatFileDatabaseManagerTest.java | 264 ++++--- .../flatfile/FlatFileDataUtilTest.java | 6 +- .../nossr50/locale/LocaleLoaderTest.java | 10 +- .../gmail/nossr50/party/PartyManagerTest.java | 29 +- .../skills/acrobatics/AcrobaticsTest.java | 33 +- .../skills/excavation/ExcavationTest.java | 45 +- .../nossr50/skills/tridents/TridentsTest.java | 8 +- .../skills/woodcutting/WoodcuttingTest.java | 49 +- .../nossr50/util/PotionEffectUtilTest.java | 17 +- .../gmail/nossr50/util/PotionUtilTest.java | 12 +- .../util/blockmeta/BitSetChunkStoreTest.java | 46 +- .../util/blockmeta/BlockStoreTestUtils.java | 30 +- .../util/blockmeta/ChunkStoreTest.java | 41 +- .../util/blockmeta/LegacyChunkStore.java | 17 +- .../blockmeta/UnitTestObjectOutputStream.java | 6 +- .../util/blockmeta/UserBlockTrackerTest.java | 79 +- .../platform/MinecraftGameVersionTest.java | 32 +- .../nossr50/util/random/ProbabilityTest.java | 10 +- .../util/random/ProbabilityTestUtils.java | 6 +- .../util/random/ProbabilityUtilTest.java | 61 +- .../nossr50/util/text/StringUtilsTest.java | 23 +- .../nossr50/util/text/TextUtilsTest.java | 11 +- 440 files changed, 11762 insertions(+), 7365 deletions(-) delete mode 100644 src/main/java/com/gmail/nossr50/api/exceptions/ValueOutOfBoundsException.java delete mode 100644 src/main/java/com/gmail/nossr50/commands/admin/DropTreasureCommand.java delete mode 100644 src/main/java/com/gmail/nossr50/protocollib/ProtocolHandler.java delete mode 100644 src/main/java/com/gmail/nossr50/protocollib/ProtocolLibManager.java diff --git a/Changelog.txt b/Changelog.txt index 3a7ed17c0..82f2e8de3 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -3252,7 +3252,7 @@ Version 1.5.01 = Fixed bug where pistons would mess with the block tracking = Fixed bug where the Updater was running on the main thread. = Fixed bug when players would use /ptp without being in a party - = Fixed bug where player didn't have a mcMMOPlayer object in AsyncPlayerChatEvent + = Fixed bug where player didn't have a mmoPlayer object in AsyncPlayerChatEvent = Fixed bug where dodge would check the wrong player skill level = Fixed bug which causes /party teleport to stop working = Fixed bug where SaveTimerTask would produce an IndexOutOfBoundsException diff --git a/pom.xml b/pom.xml index 57aa17ac8..362d76172 100644 --- a/pom.xml +++ b/pom.xml @@ -14,7 +14,7 @@ - 1.21.6-R0.1-SNAPSHOT + 1.21.7-R0.1-SNAPSHOT 4.23.0 4.4.1-SNAPSHOT 1.1.0 @@ -100,13 +100,11 @@ maven-failsafe-plugin 3.2.5 - org.junit.jupiter:junit-jupiter false - org.apache.maven.plugins maven-release-plugin diff --git a/src/main/java/com/gmail/nossr50/api/AbilityAPI.java b/src/main/java/com/gmail/nossr50/api/AbilityAPI.java index 1597fbb20..c2fb9901a 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); @@ -39,10 +40,10 @@ public final class AbilityAPI { } public static boolean isAnyAbilityEnabled(Player player) { - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); for (SuperAbilityType ability : SuperAbilityType.values()) { - if (mcMMOPlayer.getAbilityMode(ability)) { + if (mmoPlayer.getAbilityMode(ability)) { return true; } } @@ -84,9 +85,7 @@ public final class AbilityAPI { public static boolean isBleeding(LivingEntity entity) { if (entity.isValid()) { - if (entity.hasMetadata(MetadataConstants.METADATA_KEY_RUPTURE)) { - return true; - } + return entity.hasMetadata(MetadataConstants.METADATA_KEY_RUPTURE); } return false; diff --git a/src/main/java/com/gmail/nossr50/api/ChatAPI.java b/src/main/java/com/gmail/nossr50/api/ChatAPI.java index e4d61957a..bfbfb29ba 100644 --- a/src/main/java/com/gmail/nossr50/api/ChatAPI.java +++ b/src/main/java/com/gmail/nossr50/api/ChatAPI.java @@ -6,63 +6,8 @@ import com.gmail.nossr50.util.player.UserManager; import org.bukkit.entity.Player; public final class 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 displayName The display name of the sender -// * @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); -// } -// -// /** -// * 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 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) { -// getPartyChatManager(plugin, party).handleChat(sender, message); -// } -// -// /** -// * Send a message to administrators -// *
-// * This function is designed for API usage. -// * -// * @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 -// */ -// public static void sendAdminChat(Plugin plugin, String sender, String displayName, String message) { -// ChatManagerFactory.getChatManager(plugin, ChatChannel.ADMIN).handleChat(sender, displayName, message); -// } -// -// /** -// * Send a message to administrators -// *
-// * 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 message The message to send -// */ -// public static void sendAdminChat(Plugin plugin, String sender, String message) { -// ChatManagerFactory.getChatManager(plugin, ChatChannel.ADMIN).handleChat(sender, message); -// } + private ChatAPI() { + } /** * Check if a player is currently talking in party chat. @@ -110,7 +55,8 @@ public final class ChatAPI { * @param player The player to toggle party chat on. */ public static void togglePartyChat(Player player) { - mcMMO.p.getChatManager().setOrToggleChatChannel(UserManager.getPlayer(player), ChatChannel.PARTY); + mcMMO.p.getChatManager() + .setOrToggleChatChannel(UserManager.getPlayer(player), ChatChannel.PARTY); } /** @@ -119,7 +65,8 @@ public final class ChatAPI { * @param playerName The name of the player to toggle party chat on. */ public static void togglePartyChat(String playerName) { - mcMMO.p.getChatManager().setOrToggleChatChannel(UserManager.getPlayer(playerName), ChatChannel.PARTY); + mcMMO.p.getChatManager() + .setOrToggleChatChannel(UserManager.getPlayer(playerName), ChatChannel.PARTY); } /** @@ -128,7 +75,8 @@ public final class ChatAPI { * @param player The player to toggle admin chat on. */ public static void toggleAdminChat(Player player) { - mcMMO.p.getChatManager().setOrToggleChatChannel(UserManager.getPlayer(player), ChatChannel.ADMIN); + mcMMO.p.getChatManager() + .setOrToggleChatChannel(UserManager.getPlayer(player), ChatChannel.ADMIN); } /** @@ -137,6 +85,7 @@ public final class ChatAPI { * @param playerName The name of the player to toggle party chat on. */ public static void toggleAdminChat(String playerName) { - mcMMO.p.getChatManager().setOrToggleChatChannel(UserManager.getPlayer(playerName), ChatChannel.ADMIN); + mcMMO.p.getChatManager() + .setOrToggleChatChannel(UserManager.getPlayer(playerName), ChatChannel.ADMIN); } } diff --git a/src/main/java/com/gmail/nossr50/api/DatabaseAPI.java b/src/main/java/com/gmail/nossr50/api/DatabaseAPI.java index 55f682377..7e4007c0d 100644 --- a/src/main/java/com/gmail/nossr50/api/DatabaseAPI.java +++ b/src/main/java/com/gmail/nossr50/api/DatabaseAPI.java @@ -2,15 +2,17 @@ package com.gmail.nossr50.api; import com.gmail.nossr50.datatypes.player.PlayerProfile; import com.gmail.nossr50.mcMMO; +import java.util.UUID; import org.bukkit.OfflinePlayer; import org.jetbrains.annotations.NotNull; -import java.util.UUID; - public class DatabaseAPI { + private DatabaseAPI() { + } /** * Checks if a player exists in the mcMMO Database + * * @param offlinePlayer target player * @return true if the player exists in the DB, false if they do not */ @@ -22,6 +24,7 @@ public class DatabaseAPI { /** * Checks if a player exists in the mcMMO Database + * * @param uuid target player * @return true if the player exists in the DB, false if they do not */ @@ -38,6 +41,7 @@ public class DatabaseAPI { /** * Checks if a player exists in the mcMMO Database + * * @param playerName target player * @return true if the player exists in the DB, false if they do not */ diff --git a/src/main/java/com/gmail/nossr50/api/ExperienceAPI.java b/src/main/java/com/gmail/nossr50/api/ExperienceAPI.java index 98d37358a..52f85e1b4 100644 --- a/src/main/java/com/gmail/nossr50/api/ExperienceAPI.java +++ b/src/main/java/com/gmail/nossr50/api/ExperienceAPI.java @@ -1,10 +1,17 @@ package com.gmail.nossr50.api; -import com.gmail.nossr50.api.exceptions.*; +import static com.gmail.nossr50.datatypes.experience.XPGainReason.PVE; +import static com.gmail.nossr50.datatypes.experience.XPGainSource.CUSTOM; +import static com.gmail.nossr50.datatypes.experience.XPGainSource.SELF; + +import com.gmail.nossr50.api.exceptions.InvalidFormulaTypeException; +import com.gmail.nossr50.api.exceptions.InvalidPlayerException; +import com.gmail.nossr50.api.exceptions.InvalidSkillException; +import com.gmail.nossr50.api.exceptions.InvalidXPGainReasonException; +import com.gmail.nossr50.api.exceptions.McMMOPlayerNotFoundException; import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.datatypes.experience.FormulaType; import com.gmail.nossr50.datatypes.experience.XPGainReason; -import com.gmail.nossr50.datatypes.experience.XPGainSource; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.PlayerProfile; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; @@ -12,21 +19,21 @@ import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.SkillTools; +import java.util.ArrayList; +import java.util.UUID; import org.bukkit.OfflinePlayer; import org.bukkit.block.BlockState; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -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 - * other API calls in this class. + * Returns whether given string is a valid type of skill suitable for the other API calls in + * this class. *
* This function is designed for API usage. * @@ -38,38 +45,40 @@ public final class ExperienceAPI { } /** - * Start the task that gives combat XP. - * Processes combat XP like mcMMO normally would, so mcMMO will check whether the entity should reward XP when giving out the XP + * Start the task that gives combat XP. Processes combat XP like mcMMO normally would, so mcMMO + * will check whether the entity should reward XP when giving out the XP * - * @param mcMMOPlayer The attacking player + * @param mmoPlayer The attacking player * @param target The defending entity * @param primarySkillType The skill being used * @param multiplier final XP result will be multiplied by this * @deprecated Draft API */ @Deprecated - public static void addCombatXP(McMMOPlayer mcMMOPlayer, LivingEntity target, PrimarySkillType primarySkillType, double multiplier) { - CombatUtils.processCombatXP(mcMMOPlayer, target, primarySkillType, multiplier); + public static void addCombatXP(McMMOPlayer mmoPlayer, LivingEntity target, + PrimarySkillType primarySkillType, + double multiplier) { + CombatUtils.processCombatXP(mmoPlayer, target, primarySkillType, multiplier); } /** - * Start the task that gives combat XP. - * Processes combat XP like mcMMO normally would, so mcMMO will check whether the entity should reward XP when giving out the XP + * Start the task that gives combat XP. Processes combat XP like mcMMO normally would, so mcMMO + * will check whether the entity should reward XP when giving out the XP * - * @param mcMMOPlayer The attacking player + * @param mmoPlayer The attacking player * @param target The defending entity * @param primarySkillType The skill being used * @deprecated Draft API */ @Deprecated - public static void addCombatXP(McMMOPlayer mcMMOPlayer, LivingEntity target, PrimarySkillType primarySkillType) { - CombatUtils.processCombatXP(mcMMOPlayer, target, primarySkillType); + public static void addCombatXP(McMMOPlayer mmoPlayer, LivingEntity target, + PrimarySkillType primarySkillType) { + CombatUtils.processCombatXP(mmoPlayer, target, primarySkillType); } /** - * Returns whether the given skill type string is both valid and not a - * child skill. (Child skills have no XP of their own, and their level is - * derived from the parent(s).) + * Returns whether the given skill type string is both valid and not a child skill. (Child + * skills have no XP of their own, and their level is derived from the parent(s).) *
* This function is designed for API usage. * @@ -77,7 +86,7 @@ public final class ExperienceAPI { * @return true if this is a valid, non-child mcMMO skill */ public static boolean isNonChildSkill(String skillType) { - PrimarySkillType skill = mcMMO.p.getSkillTools().matchSkill(skillType); + final PrimarySkillType skill = mcMMO.p.getSkillTools().matchSkill(skillType); return skill != null && !SkillTools.isChildSkill(skill); } @@ -95,7 +104,6 @@ public final class ExperienceAPI { * @param player 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 */ @Deprecated @@ -112,7 +120,6 @@ public final class ExperienceAPI { * @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 InvalidXPGainReasonException if the given xpGainReason is not valid */ @@ -130,17 +137,19 @@ public final class ExperienceAPI { * @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 * @throws InvalidXPGainReasonException if the given xpGainReason is not valid */ - public static void addRawXP(Player player, String skillType, float XP, String xpGainReason, boolean isUnshared) { + public static void addRawXP(Player player, String skillType, float XP, String xpGainReason, + boolean isUnshared) { if (isUnshared) { - getPlayer(player).beginUnsharedXpGain(getSkillType(skillType), XP, getXPGainReason(xpGainReason), XPGainSource.CUSTOM); + getPlayer(player).beginUnsharedXpGain(getSkillType(skillType), XP, + getXPGainReason(xpGainReason), CUSTOM); return; } - getPlayer(player).applyXpGain(getSkillType(skillType), XP, getXPGainReason(xpGainReason), XPGainSource.CUSTOM); + getPlayer(player).applyXpGain(getSkillType(skillType), XP, getXPGainReason(xpGainReason), + CUSTOM); } /** @@ -148,8 +157,8 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @deprecated We're using float for our XP values now - * replaced by {@link #addRawXPOffline(String playerName, String skillType, float XP)} + * @deprecated We're using float for our XP values now replaced by + * {@link #addRawXPOffline(String playerName, String skillType, float XP)} */ @Deprecated public static void addRawXPOffline(String playerName, String skillType, int XP) { @@ -161,15 +170,13 @@ public final class ExperienceAPI { *
* This function is designed for API usage. * - * @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 We're using uuids to get an offline player replaced by + * {@link #addRawXPOffline(UUID uuid, String skillType, float XP)} */ @Deprecated public static void addRawXPOffline(String playerName, String skillType, float XP) { @@ -184,7 +191,6 @@ public final class ExperienceAPI { * @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 * @throws InvalidPlayerException if the given player does not exist in the database */ @@ -200,7 +206,6 @@ public final class ExperienceAPI { * @param player 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 */ @Deprecated @@ -217,12 +222,15 @@ public final class ExperienceAPI { * @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 InvalidXPGainReasonException if the given xpGainReason is not valid */ - public static void addMultipliedXP(Player player, String skillType, int XP, String xpGainReason) { - getPlayer(player).applyXpGain(getSkillType(skillType), (int) (XP * ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier()), getXPGainReason(xpGainReason), XPGainSource.CUSTOM); + public static void addMultipliedXP(Player player, String skillType, int XP, + String xpGainReason) { + getPlayer(player).applyXpGain( + getSkillType(skillType), + (int) (XP * ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier()), + getXPGainReason(xpGainReason), CUSTOM); } /** @@ -233,13 +241,14 @@ public final class ExperienceAPI { * @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 addMultipliedXPOffline(String playerName, String skillType, int XP) { - addOfflineXP(playerName, getSkillType(skillType), (int) (XP * ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier())); + addOfflineXP( + playerName, getSkillType(skillType), + (int) (XP * ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier())); } /** @@ -250,7 +259,6 @@ public final class ExperienceAPI { * @param player 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 */ @Deprecated @@ -267,7 +275,6 @@ public final class ExperienceAPI { * @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 InvalidXPGainReasonException if the given xpGainReason is not valid */ @@ -285,20 +292,26 @@ public final class ExperienceAPI { * @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 * @throws InvalidXPGainReasonException if the given xpGainReason is not valid */ - public static void addModifiedXP(Player player, String skillType, int XP, String xpGainReason, boolean isUnshared) { - PrimarySkillType skill = getSkillType(skillType); + public static void addModifiedXP(Player player, String skillType, int XP, String xpGainReason, + boolean isUnshared) { + final PrimarySkillType skill = getSkillType(skillType); + final ExperienceConfig expConf = ExperienceConfig.getInstance(); if (isUnshared) { - getPlayer(player).beginUnsharedXpGain(skill, - (int) (XP / ExperienceConfig.getInstance().getFormulaSkillModifier(skill) * ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier()), getXPGainReason(xpGainReason), XPGainSource.CUSTOM); + getPlayer(player).beginUnsharedXpGain( + skill, (int) (XP / expConf.getFormulaSkillModifier( + skill) * expConf.getExperienceGainsGlobalMultiplier()), + getXPGainReason(xpGainReason), CUSTOM); return; } - getPlayer(player).applyXpGain(skill, (int) (XP / ExperienceConfig.getInstance().getFormulaSkillModifier(skill) * ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier()), getXPGainReason(xpGainReason), XPGainSource.CUSTOM); + getPlayer(player).applyXpGain( + skill, (int) (XP / expConf.getFormulaSkillModifier( + skill) * expConf.getExperienceGainsGlobalMultiplier()), + getXPGainReason(xpGainReason), CUSTOM); } /** @@ -309,27 +322,29 @@ public final class ExperienceAPI { * @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 addModifiedXPOffline(String playerName, String skillType, int XP) { - PrimarySkillType skill = getSkillType(skillType); + final PrimarySkillType skill = getSkillType(skillType); - addOfflineXP(playerName, skill, (int) (XP / ExperienceConfig.getInstance().getFormulaSkillModifier(skill) * ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier())); + addOfflineXP( + playerName, skill, + (int) (XP / ExperienceConfig.getInstance().getFormulaSkillModifier( + skill) * ExperienceConfig.getInstance() + .getExperienceGainsGlobalMultiplier())); } /** - * Adds XP to the player, calculates for XP Rate, skill modifiers, perks, child skills, - * and party sharing. + * Adds XP to the player, calculates for XP Rate, skill modifiers, perks, child skills, and + * party sharing. *
* 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 - * * @throws InvalidSkillException if the given skill is not valid */ @Deprecated @@ -338,8 +353,8 @@ public final class ExperienceAPI { } /** - * Adds XP to the player, calculates for XP Rate, skill modifiers, perks, child skills, - * and party sharing. + * Adds XP to the player, calculates for XP Rate, skill modifiers, perks, child skills, and + * party sharing. *
* This function is designed for API usage. * @@ -347,7 +362,6 @@ public final class ExperienceAPI { * @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 InvalidXPGainReasonException if the given xpGainReason is not valid */ @@ -356,8 +370,8 @@ public final class ExperienceAPI { } /** - * Adds XP to the player, calculates for XP Rate, skill modifiers, perks, child skills, - * and party sharing. + * Adds XP to the player, calculates for XP Rate, skill modifiers, perks, child skills, and + * party sharing. *
* This function is designed for API usage. * @@ -366,17 +380,19 @@ public final class ExperienceAPI { * @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 * @throws InvalidXPGainReasonException if the given xpGainReason is not valid */ - public static void addXP(Player player, String skillType, int XP, String xpGainReason, boolean isUnshared) { + public static void addXP(Player player, String skillType, int XP, String xpGainReason, + boolean isUnshared) { if (isUnshared) { - getPlayer(player).beginUnsharedXpGain(getSkillType(skillType), XP, getXPGainReason(xpGainReason), XPGainSource.CUSTOM); + getPlayer(player).beginUnsharedXpGain(getSkillType(skillType), XP, + getXPGainReason(xpGainReason), CUSTOM); return; } - getPlayer(player).beginXpGain(getSkillType(skillType), XP, getXPGainReason(xpGainReason), XPGainSource.CUSTOM); + getPlayer(player).beginXpGain(getSkillType(skillType), XP, getXPGainReason(xpGainReason), + CUSTOM); } /** @@ -387,7 +403,6 @@ public final class ExperienceAPI { * @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 UnsupportedOperationException if the given skill is a child skill */ @@ -403,7 +418,6 @@ public final class ExperienceAPI { * @param playerName 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 UnsupportedOperationException if the given skill is a child skill @@ -421,7 +435,6 @@ public final class ExperienceAPI { * @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 UnsupportedOperationException if the given skill is a child skill @@ -438,12 +451,12 @@ public final class ExperienceAPI { * @param offlinePlayer 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 UnsupportedOperationException if the given skill is a child skill */ - public static int getOfflineXP(@NotNull OfflinePlayer offlinePlayer, @NotNull String skillType) throws InvalidPlayerException { + public static int getOfflineXP(@NotNull OfflinePlayer offlinePlayer, @NotNull String skillType) + throws InvalidPlayerException { return getOfflineProfile(offlinePlayer).getSkillXpLevel(getNonChildSkillType(skillType)); } @@ -455,7 +468,6 @@ public final class ExperienceAPI { * @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 UnsupportedOperationException if the given skill is a child skill */ @@ -471,7 +483,6 @@ public final class ExperienceAPI { * @param playerName 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 UnsupportedOperationException if the given skill is a child skill @@ -489,7 +500,6 @@ public final class ExperienceAPI { * @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 UnsupportedOperationException if the given skill is a child skill @@ -506,18 +516,22 @@ public final class ExperienceAPI { * @param offlinePlayer 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 UnsupportedOperationException if the given skill is a child skill */ - public static float getOfflineXPRaw(@NotNull OfflinePlayer offlinePlayer, @NotNull String skillType) throws InvalidPlayerException, UnsupportedOperationException, InvalidSkillException { + public static float getOfflineXPRaw(@NotNull OfflinePlayer offlinePlayer, + @NotNull String skillType) + throws InvalidPlayerException, UnsupportedOperationException, InvalidSkillException { return getOfflineProfile(offlinePlayer).getSkillXpLevelRaw(getNonChildSkillType(skillType)); } - public static float getOfflineXPRaw(@NotNull OfflinePlayer offlinePlayer, @NotNull PrimarySkillType skillType) throws InvalidPlayerException, UnsupportedOperationException { - if (SkillTools.isChildSkill(skillType)) + public static float getOfflineXPRaw(@NotNull OfflinePlayer offlinePlayer, + @NotNull PrimarySkillType skillType) + throws InvalidPlayerException, UnsupportedOperationException { + if (SkillTools.isChildSkill(skillType)) { throw new UnsupportedOperationException(); + } return getOfflineProfile(offlinePlayer).getSkillXpLevelRaw(skillType); } @@ -530,7 +544,6 @@ public final class ExperienceAPI { * @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 UnsupportedOperationException if the given skill is a child skill */ @@ -546,7 +559,6 @@ public final class ExperienceAPI { * @param playerName 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 UnsupportedOperationException if the given skill is a child skill @@ -564,7 +576,6 @@ public final class ExperienceAPI { * @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 UnsupportedOperationException if the given skill is a child skill @@ -581,12 +592,13 @@ public final class ExperienceAPI { * @param offlinePlayer 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 UnsupportedOperationException if the given skill is a child skill */ - public static int getOfflineXPToNextLevel(@NotNull OfflinePlayer offlinePlayer, @NotNull String skillType) throws UnsupportedOperationException, InvalidSkillException, InvalidPlayerException { + public static int getOfflineXPToNextLevel(@NotNull OfflinePlayer offlinePlayer, + @NotNull String skillType) + throws UnsupportedOperationException, InvalidSkillException, InvalidPlayerException { return getOfflineProfile(offlinePlayer).getXpToLevel(getNonChildSkillType(skillType)); } @@ -598,14 +610,13 @@ public final class ExperienceAPI { * @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 UnsupportedOperationException if the given skill is a child skill */ public static int getXPRemaining(Player player, String skillType) { - PrimarySkillType skill = getNonChildSkillType(skillType); + final PrimarySkillType skill = getNonChildSkillType(skillType); - PlayerProfile profile = getPlayer(player).getProfile(); + final PlayerProfile profile = getPlayer(player).getProfile(); return profile.getXpToLevel(skill) - profile.getSkillXpLevel(skill); } @@ -618,15 +629,14 @@ public final class ExperienceAPI { * @param playerName 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 UnsupportedOperationException if the given skill is a child skill */ @Deprecated public static int getOfflineXPRemaining(String playerName, String skillType) { - PrimarySkillType skill = getNonChildSkillType(skillType); - PlayerProfile profile = getOfflineProfile(playerName); + final PrimarySkillType skill = getNonChildSkillType(skillType); + final PlayerProfile profile = getOfflineProfile(playerName); return profile.getXpToLevel(skill) - profile.getSkillXpLevel(skill); } @@ -639,14 +649,13 @@ public final class ExperienceAPI { * @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 UnsupportedOperationException if the given skill is a child skill */ public static float getOfflineXPRemaining(UUID uuid, String skillType) { - PrimarySkillType skill = getNonChildSkillType(skillType); - PlayerProfile profile = getOfflineProfile(uuid); + final PrimarySkillType skill = getNonChildSkillType(skillType); + final PlayerProfile profile = getOfflineProfile(uuid); return profile.getXpToLevel(skill) - profile.getSkillXpLevelRaw(skill); } @@ -659,14 +668,14 @@ public final class ExperienceAPI { * @param offlinePlayer 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 UnsupportedOperationException if the given skill is a child skill */ - public static float getOfflineXPRemaining(OfflinePlayer offlinePlayer, String skillType) throws InvalidSkillException, InvalidPlayerException, UnsupportedOperationException { - PrimarySkillType skill = getNonChildSkillType(skillType); - PlayerProfile profile = getOfflineProfile(offlinePlayer); + public static float getOfflineXPRemaining(OfflinePlayer offlinePlayer, String skillType) + throws InvalidSkillException, InvalidPlayerException, UnsupportedOperationException { + final PrimarySkillType skill = getNonChildSkillType(skillType); + final PlayerProfile profile = getOfflineProfile(offlinePlayer); return profile.getXpToLevel(skill) - profile.getSkillXpLevelRaw(skill); } @@ -679,7 +688,6 @@ public final class ExperienceAPI { * @param player 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 */ public static void addLevel(Player player, String skillType, int levels) { @@ -694,14 +702,13 @@ public final class ExperienceAPI { * @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 * @throws InvalidPlayerException if the given player does not exist in the database */ @Deprecated public static void addLevelOffline(String playerName, String skillType, int levels) { - PlayerProfile profile = getOfflineProfile(playerName); - PrimarySkillType skill = getSkillType(skillType); + final PlayerProfile profile = getOfflineProfile(playerName); + final PrimarySkillType skill = getSkillType(skillType); if (SkillTools.isChildSkill(skill)) { var parentSkills = mcMMO.p.getSkillTools().getChildSkillParents(skill); @@ -726,13 +733,12 @@ public final class ExperienceAPI { * @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 * @throws InvalidPlayerException if the given player does not exist in the database */ public static void addLevelOffline(UUID uuid, String skillType, int levels) { - PlayerProfile profile = getOfflineProfile(uuid); - PrimarySkillType skill = getSkillType(skillType); + final PlayerProfile profile = getOfflineProfile(uuid); + final PrimarySkillType skill = getSkillType(skillType); if (SkillTools.isChildSkill(skill)) { var parentSkills = mcMMO.p.getSkillTools().getChildSkillParents(skill); @@ -757,7 +763,6 @@ public final class ExperienceAPI { * @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 * @deprecated Use getLevel(Player player, PrimarySkillType skillType) instead */ @@ -774,7 +779,6 @@ public final class ExperienceAPI { * @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, PrimarySkillType skillType) { @@ -789,7 +793,6 @@ public final class ExperienceAPI { * @param playerName 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 InvalidPlayerException if the given player does not exist in the database */ @@ -805,7 +808,6 @@ public final class ExperienceAPI { * @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 InvalidPlayerException if the given player does not exist in the database */ @@ -832,13 +834,12 @@ 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 public static int getPowerLevelOffline(String playerName) { int powerLevel = 0; - PlayerProfile profile = getOfflineProfile(playerName); + final PlayerProfile profile = getOfflineProfile(playerName); for (PrimarySkillType type : SkillTools.NON_CHILD_SKILLS) { powerLevel += profile.getSkillLevel(type); @@ -854,12 +855,11 @@ 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) { int powerLevel = 0; - PlayerProfile profile = getOfflineProfile(uuid); + final PlayerProfile profile = getOfflineProfile(uuid); for (PrimarySkillType type : SkillTools.NON_CHILD_SKILLS) { powerLevel += profile.getSkillLevel(type); @@ -875,7 +875,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) { @@ -900,16 +899,16 @@ public final class ExperienceAPI { * * @param playerName The name of the player to check * @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 - * - * @return the position on the leaderboard */ @Deprecated public static int getPlayerRankSkill(String playerName, String skillType) { - return mcMMO.getDatabaseManager().readRank(mcMMO.p.getServer().getOfflinePlayer(playerName).getName()).get(getNonChildSkillType(skillType)); + return mcMMO.getDatabaseManager() + .readRank(mcMMO.p.getServer().getOfflinePlayer(playerName).getName()).get( + getNonChildSkillType(skillType)); } /** @@ -919,15 +918,15 @@ public final class ExperienceAPI { * * @param uuid The name of the player to check * @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 - * - * @return the position on the leaderboard */ public static int getPlayerRankSkill(UUID uuid, String skillType) { - return mcMMO.getDatabaseManager().readRank(mcMMO.p.getServer().getOfflinePlayer(uuid).getName()).get(getNonChildSkillType(skillType)); + return mcMMO.getDatabaseManager() + .readRank(mcMMO.p.getServer().getOfflinePlayer(uuid).getName()).get( + getNonChildSkillType(skillType)); } /** @@ -936,14 +935,14 @@ 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) { - return mcMMO.getDatabaseManager().readRank(mcMMO.p.getServer().getOfflinePlayer(playerName).getName()).get(null); + return mcMMO.getDatabaseManager() + .readRank(mcMMO.p.getServer().getOfflinePlayer(playerName).getName()).get( + null); } /** @@ -952,13 +951,12 @@ 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); + return mcMMO.getDatabaseManager() + .readRank(mcMMO.p.getServer().getOfflinePlayer(uuid).getName()).get(null); } /** @@ -969,7 +967,6 @@ public final class ExperienceAPI { * @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) { @@ -984,7 +981,6 @@ public final class ExperienceAPI { * @param playerName 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 InvalidPlayerException if the given player does not exist in the database */ @@ -1001,7 +997,6 @@ public final class ExperienceAPI { * @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 InvalidPlayerException if the given player does not exist in the database */ @@ -1017,7 +1012,6 @@ public final class ExperienceAPI { * @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 * @throws UnsupportedOperationException if the given skill is a child skill */ @@ -1033,7 +1027,6 @@ public final class ExperienceAPI { * @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 * @throws UnsupportedOperationException if the given skill is a child skill @@ -1051,7 +1044,6 @@ public final class ExperienceAPI { * @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 * @throws UnsupportedOperationException if the given skill is a child skill @@ -1068,7 +1060,6 @@ public final class ExperienceAPI { * @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 * @throws UnsupportedOperationException if the given skill is a child skill */ @@ -1084,7 +1075,6 @@ public final class ExperienceAPI { * @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 * @throws UnsupportedOperationException if the given skill is a child skill @@ -1102,7 +1092,6 @@ public final class ExperienceAPI { * @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 * @throws UnsupportedOperationException if the given skill is a child skill @@ -1117,11 +1106,11 @@ 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) { - return mcMMO.getFormulaManager().getXPtoNextLevel(level, ExperienceConfig.getInstance().getFormulaType()); + return mcMMO.getFormulaManager() + .getXPtoNextLevel(level, ExperienceConfig.getInstance().getFormulaType()); } /** @@ -1131,7 +1120,6 @@ public final class ExperienceAPI { * * @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) { @@ -1139,82 +1127,102 @@ 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 + * 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 + * @param mmoPlayer the target player */ - public static void addXpFromBlocks(ArrayList blockStates, McMMOPlayer mcMMOPlayer) { - for(BlockState bs : blockStates) { - for(PrimarySkillType skillType : PrimarySkillType.values()) { + public static void addXpFromBlocks(ArrayList blockStates, McMMOPlayer mmoPlayer) { + 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); + mmoPlayer.applyXpGain( + skillType, + ExperienceConfig.getInstance().getXp(skillType, bs.getType()), PVE, + SELF); } } } } /** - * 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 + * 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 mmoPlayer the target player * @param skillType target primary skill */ - public static void addXpFromBlocksBySkill(ArrayList blockStates, McMMOPlayer mcMMOPlayer, - PrimarySkillType skillType) { - for(BlockState bs : blockStates) { + public static void addXpFromBlocksBySkill(ArrayList blockStates, + McMMOPlayer mmoPlayer, + 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); + mmoPlayer.applyXpGain( + skillType, ExperienceConfig.getInstance().getXp(skillType, bs.getType()), + PVE, + SELF); } } } /** - * Will add the appropriate type of XP from the block to the player based on the material of the blocks given + * 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 mcMMOPlayer The target player + * @param mmoPlayer The target player */ - public static void addXpFromBlock(BlockState blockState, McMMOPlayer mcMMOPlayer) { - for(PrimarySkillType skillType : PrimarySkillType.values()) { + public static void addXpFromBlock(BlockState blockState, McMMOPlayer mmoPlayer) { + 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); + mmoPlayer.applyXpGain( + skillType, + ExperienceConfig.getInstance().getXp(skillType, blockState.getType()), + PVE, SELF); } } } /** - * 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 + * 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 mcMMOPlayer The target player + * @param mmoPlayer The target player * @param skillType target primary skill */ - public static void addXpFromBlockBySkill(BlockState blockState, McMMOPlayer mcMMOPlayer, PrimarySkillType skillType) { + public static void addXpFromBlockBySkill(BlockState blockState, McMMOPlayer mmoPlayer, + PrimarySkillType skillType) { if (ExperienceConfig.getInstance().getXp(skillType, blockState.getType()) > 0) { - mcMMOPlayer.applyXpGain(skillType, ExperienceConfig.getInstance().getXp(skillType, blockState.getType()), - XPGainReason.PVE, XPGainSource.SELF); + mmoPlayer.applyXpGain( + skillType, + ExperienceConfig.getInstance().getXp(skillType, blockState.getType()), PVE, + SELF); } } // Utility methods follow. - private static void addOfflineXP(@NotNull UUID playerUniqueId, @NotNull PrimarySkillType skill, int XP) { - PlayerProfile profile = getOfflineProfile(playerUniqueId); + private static void addOfflineXP(@NotNull UUID playerUniqueId, @NotNull PrimarySkillType skill, + int XP) { + final PlayerProfile profile = getOfflineProfile(playerUniqueId); profile.addXp(skill, XP); profile.save(true); } - private static void addOfflineXP(@NotNull String playerName, @NotNull PrimarySkillType skill, int XP) { - PlayerProfile profile = getOfflineProfile(playerName); + private static void addOfflineXP(@NotNull String playerName, @NotNull PrimarySkillType skill, + int XP) { + final PlayerProfile profile = getOfflineProfile(playerName); profile.addXp(skill, XP); profile.scheduleAsyncSave(); } - private static @NotNull PlayerProfile getOfflineProfile(@NotNull UUID uuid) throws InvalidPlayerException { - PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(uuid); + private static @NotNull PlayerProfile getOfflineProfile(@NotNull UUID uuid) + throws InvalidPlayerException { + final PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(uuid); if (!profile.isLoaded()) { throw new InvalidPlayerException(); @@ -1223,8 +1231,9 @@ public final class ExperienceAPI { return profile; } - private static @NotNull PlayerProfile getOfflineProfile(@NotNull OfflinePlayer offlinePlayer) throws InvalidPlayerException { - PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(offlinePlayer); + private static @NotNull PlayerProfile getOfflineProfile(@NotNull OfflinePlayer offlinePlayer) + throws InvalidPlayerException { + final PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(offlinePlayer); if (!profile.isLoaded()) { throw new InvalidPlayerException(); @@ -1233,8 +1242,9 @@ public final class ExperienceAPI { return profile; } - private static @NotNull PlayerProfile getOfflineProfile(@NotNull String playerName) throws InvalidPlayerException { - PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(playerName); + private static @NotNull PlayerProfile getOfflineProfile(@NotNull String playerName) + throws InvalidPlayerException { + final PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(playerName); if (!profile.isLoaded()) { throw new InvalidPlayerException(); @@ -1244,7 +1254,7 @@ public final class ExperienceAPI { } private static PrimarySkillType getSkillType(String skillType) throws InvalidSkillException { - PrimarySkillType skill = mcMMO.p.getSkillTools().matchSkill(skillType); + final PrimarySkillType skill = mcMMO.p.getSkillTools().matchSkill(skillType); if (skill == null) { throw new InvalidSkillException(); @@ -1253,8 +1263,9 @@ public final class ExperienceAPI { return skill; } - private static PrimarySkillType getNonChildSkillType(String skillType) throws InvalidSkillException, UnsupportedOperationException { - PrimarySkillType skill = getSkillType(skillType); + private static PrimarySkillType getNonChildSkillType(String skillType) + throws InvalidSkillException, UnsupportedOperationException { + final PrimarySkillType skill = getSkillType(skillType); if (SkillTools.isChildSkill(skill)) { throw new UnsupportedOperationException("Child skills do not have XP"); @@ -1274,7 +1285,7 @@ public final class ExperienceAPI { } private static FormulaType getFormulaType(String formula) throws InvalidFormulaTypeException { - FormulaType formulaType = FormulaType.getFormulaType(formula); + final FormulaType formulaType = FormulaType.getFormulaType(formula); if (formulaType == null) { throw new InvalidFormulaTypeException(); @@ -1284,12 +1295,12 @@ 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 + @Deprecated(forRemoval = true) private static McMMOPlayer getPlayer(Player player) throws McMMOPlayerNotFoundException { if (!UserManager.hasPlayerDataKey(player)) { throw new McMMOPlayerNotFoundException(player); diff --git a/src/main/java/com/gmail/nossr50/api/FakeBlockBreakEventType.java b/src/main/java/com/gmail/nossr50/api/FakeBlockBreakEventType.java index 3476b294f..dd7c309e3 100644 --- a/src/main/java/com/gmail/nossr50/api/FakeBlockBreakEventType.java +++ b/src/main/java/com/gmail/nossr50/api/FakeBlockBreakEventType.java @@ -1,6 +1,5 @@ package com.gmail.nossr50.api; public enum FakeBlockBreakEventType { - FAKE, - TREE_FELLER + FAKE, TREE_FELLER } diff --git a/src/main/java/com/gmail/nossr50/api/ItemSpawnReason.java b/src/main/java/com/gmail/nossr50/api/ItemSpawnReason.java index 29fdc1d29..838384bcf 100644 --- a/src/main/java/com/gmail/nossr50/api/ItemSpawnReason.java +++ b/src/main/java/com/gmail/nossr50/api/ItemSpawnReason.java @@ -12,6 +12,5 @@ public enum ItemSpawnReason { UNARMED_DISARMED_ITEM, //When you disarm an opponent and they drop their weapon SALVAGE_ENCHANTMENT_BOOK, //When you salvage an enchanted item and get the enchantment back in book form SALVAGE_MATERIALS, //When you salvage an item and get materials back - TREE_FELLER_DISPLACED_BLOCK, - BONUS_DROPS, //Can be from Mining, Woodcutting, Herbalism, etc + TREE_FELLER_DISPLACED_BLOCK, BONUS_DROPS, //Can be from Mining, Woodcutting, Herbalism, etc } diff --git a/src/main/java/com/gmail/nossr50/api/PartyAPI.java b/src/main/java/com/gmail/nossr50/api/PartyAPI.java index f18dcf6fe..314d60c43 100644 --- a/src/main/java/com/gmail/nossr50/api/PartyAPI.java +++ b/src/main/java/com/gmail/nossr50/api/PartyAPI.java @@ -7,14 +7,18 @@ import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.player.NotificationManager; import com.gmail.nossr50.util.player.UserManager; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.UUID; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.jetbrains.annotations.Nullable; -import java.util.*; - public final class PartyAPI { - private PartyAPI() {} + private PartyAPI() { + } /** * Get the name of the party a player is in. @@ -50,8 +54,9 @@ public final class PartyAPI { * @return true if the player is in a party, false otherwise */ public static boolean inParty(Player player) { - if (!mcMMO.p.getPartyConfig().isPartyEnabled() || UserManager.getPlayer(player) == null) + if (!mcMMO.p.getPartyConfig().isPartyEnabled() || UserManager.getPlayer(player) == null) { return false; + } return UserManager.getPlayer(player).inParty(); } @@ -66,8 +71,9 @@ public final class PartyAPI { * @return true if the two players are in the same party, false otherwise */ public static boolean inSameParty(Player playerA, Player playerB) { - if (!mcMMO.p.getPartyConfig().isPartyEnabled()) + if (!mcMMO.p.getPartyConfig().isPartyEnabled()) { return false; + } return mcMMO.p.getPartyManager().inSameParty(playerA, playerB); } @@ -101,8 +107,9 @@ public final class PartyAPI { //Check if player profile is loaded final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if (mmoPlayer == null) + if (mmoPlayer == null) { return; + } Party party = mcMMO.p.getPartyManager().getParty(partyName); @@ -110,7 +117,9 @@ public final class PartyAPI { party = new Party(new PartyLeader(player.getUniqueId(), player.getName()), partyName); } else { if (mcMMO.p.getPartyManager().isPartyFull(player, party)) { - NotificationManager.sendPlayerInformation(player, NotificationType.PARTY_MESSAGE, "Commands.Party.PartyFull", party.toString()); + NotificationManager.sendPlayerInformation( + player, NotificationType.PARTY_MESSAGE, + "Commands.Party.PartyFull", party.toString()); return; } } @@ -119,8 +128,8 @@ public final class PartyAPI { } /** - * The max party size of the server - * 0 or less for no size limit + * The max party size of the server 0 or less for no size limit + * * @return the max party size on this server */ public static int getMaxPartySize() { @@ -138,8 +147,9 @@ public final class PartyAPI { */ public static void addToParty(Player player, String partyName, boolean bypassLimit) { //Check if player profile is loaded - if (!mcMMO.p.getPartyConfig().isPartyEnabled() || UserManager.getPlayer(player) == null) + if (!mcMMO.p.getPartyConfig().isPartyEnabled() || UserManager.getPlayer(player) == null) { return; + } Party party = mcMMO.p.getPartyManager().getParty(partyName); @@ -159,8 +169,9 @@ public final class PartyAPI { */ public static void removeFromParty(Player player) { //Check if player profile is loaded - if (!mcMMO.p.getPartyConfig().isPartyEnabled() || UserManager.getPlayer(player) == null) + if (!mcMMO.p.getPartyConfig().isPartyEnabled() || UserManager.getPlayer(player) == null) { return; + } mcMMO.p.getPartyManager().removeFromParty(UserManager.getPlayer(player)); } @@ -174,8 +185,9 @@ public final class PartyAPI { * @return the leader of the party */ public static @Nullable String getPartyLeader(String partyName) { - if (!mcMMO.p.getPartyConfig().isPartyEnabled()) + if (!mcMMO.p.getPartyConfig().isPartyEnabled()) { return null; + } return mcMMO.p.getPartyManager().getPartyLeaderName(partyName); } @@ -190,10 +202,13 @@ public final class PartyAPI { */ @Deprecated public static void setPartyLeader(String partyName, String playerName) { - if (!mcMMO.p.getPartyConfig().isPartyEnabled()) + if (!mcMMO.p.getPartyConfig().isPartyEnabled()) { return; + } - mcMMO.p.getPartyManager().setPartyLeader(mcMMO.p.getServer().getOfflinePlayer(playerName).getUniqueId(), mcMMO.p.getPartyManager().getParty(partyName)); + mcMMO.p.getPartyManager().setPartyLeader( + mcMMO.p.getServer().getOfflinePlayer(playerName).getUniqueId(), + mcMMO.p.getPartyManager().getParty(partyName)); } /** @@ -210,7 +225,7 @@ public final class PartyAPI { return null; } - List members = new ArrayList<>(); + final List members = new ArrayList<>(); for (UUID memberUniqueId : mcMMO.p.getPartyManager().getAllMembers(player).keySet()) { OfflinePlayer member = mcMMO.p.getServer().getOfflinePlayer(memberUniqueId); members.add(member); @@ -228,8 +243,9 @@ public final class PartyAPI { */ @Deprecated public static LinkedHashSet getMembers(Player player) { - if (!mcMMO.p.getPartyConfig().isPartyEnabled()) + if (!mcMMO.p.getPartyConfig().isPartyEnabled()) { return null; + } return (LinkedHashSet) mcMMO.p.getPartyManager().getAllMembers(player).values(); } @@ -243,8 +259,9 @@ public final class PartyAPI { * @return all the player names and uuids in the player's party */ public static LinkedHashMap getMembersMap(Player player) { - if (!mcMMO.p.getPartyConfig().isPartyEnabled()) + if (!mcMMO.p.getPartyConfig().isPartyEnabled()) { return null; + } return mcMMO.p.getPartyManager().getAllMembers(player); } @@ -258,8 +275,9 @@ public final class PartyAPI { * @return all online players in this party */ public static List getOnlineMembers(String partyName) { - if (!mcMMO.p.getPartyConfig().isPartyEnabled()) + if (!mcMMO.p.getPartyConfig().isPartyEnabled()) { return null; + } return mcMMO.p.getPartyManager().getOnlineMembers(partyName); } diff --git a/src/main/java/com/gmail/nossr50/api/SkillAPI.java b/src/main/java/com/gmail/nossr50/api/SkillAPI.java index be8315a28..df2bee56e 100644 --- a/src/main/java/com/gmail/nossr50/api/SkillAPI.java +++ b/src/main/java/com/gmail/nossr50/api/SkillAPI.java @@ -3,17 +3,16 @@ package com.gmail.nossr50.api; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.skills.SkillTools; - import java.util.ArrayList; 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 - * This includes parent and child skills + * Returns a list of strings with mcMMO's skills This includes parent and child skills *
* This function is designed for API usage. * @@ -24,8 +23,7 @@ public final class SkillAPI { } /** - * Returns a list of strings with mcMMO's skills - * This only includes parent skills + * Returns a list of strings with mcMMO's skills This only includes parent skills *
* This function is designed for API usage. * @@ -36,8 +34,7 @@ public final class SkillAPI { } /** - * Returns a list of strings with mcMMO's skills - * This only includes child skills + * Returns a list of strings with mcMMO's skills This only includes child skills *
* This function is designed for API usage. * @@ -48,8 +45,7 @@ public final class SkillAPI { } /** - * Returns a list of strings with mcMMO's skills - * This only includes combat skills + * Returns a list of strings with mcMMO's skills This only includes combat skills *
* This function is designed for API usage. * @@ -60,8 +56,7 @@ public final class SkillAPI { } /** - * Returns a list of strings with mcMMO's skills - * This only includes gathering skills + * Returns a list of strings with mcMMO's skills This only includes gathering skills *
* This function is designed for API usage. * @@ -72,8 +67,7 @@ public final class SkillAPI { } /** - * Returns a list of strings with mcMMO's skills - * This only includes misc skills + * Returns a list of strings with mcMMO's skills This only includes misc skills *
* This function is designed for API usage. * diff --git a/src/main/java/com/gmail/nossr50/api/exceptions/IncompleteNamespacedKeyRegister.java b/src/main/java/com/gmail/nossr50/api/exceptions/IncompleteNamespacedKeyRegister.java index 5bc8b5c9f..c875ecebe 100644 --- a/src/main/java/com/gmail/nossr50/api/exceptions/IncompleteNamespacedKeyRegister.java +++ b/src/main/java/com/gmail/nossr50/api/exceptions/IncompleteNamespacedKeyRegister.java @@ -1,8 +1,10 @@ package com.gmail.nossr50.api.exceptions; +import java.io.Serial; import org.jetbrains.annotations.NotNull; public class IncompleteNamespacedKeyRegister extends RuntimeException { + @Serial private static final long serialVersionUID = -6905157273569301219L; public IncompleteNamespacedKeyRegister(@NotNull String message) { diff --git a/src/main/java/com/gmail/nossr50/api/exceptions/InvalidFormulaTypeException.java b/src/main/java/com/gmail/nossr50/api/exceptions/InvalidFormulaTypeException.java index c46332b99..169150f04 100644 --- a/src/main/java/com/gmail/nossr50/api/exceptions/InvalidFormulaTypeException.java +++ b/src/main/java/com/gmail/nossr50/api/exceptions/InvalidFormulaTypeException.java @@ -1,6 +1,9 @@ package com.gmail.nossr50.api.exceptions; +import java.io.Serial; + public class InvalidFormulaTypeException extends RuntimeException { + @Serial private static final long serialVersionUID = 3368670229490121886L; public InvalidFormulaTypeException() { diff --git a/src/main/java/com/gmail/nossr50/api/exceptions/InvalidPlayerException.java b/src/main/java/com/gmail/nossr50/api/exceptions/InvalidPlayerException.java index 47d065e4a..ed167c4f3 100644 --- a/src/main/java/com/gmail/nossr50/api/exceptions/InvalidPlayerException.java +++ b/src/main/java/com/gmail/nossr50/api/exceptions/InvalidPlayerException.java @@ -1,6 +1,9 @@ package com.gmail.nossr50.api.exceptions; +import java.io.Serial; + public class InvalidPlayerException extends RuntimeException { + @Serial private static final long serialVersionUID = 907213002618581385L; public InvalidPlayerException() { diff --git a/src/main/java/com/gmail/nossr50/api/exceptions/InvalidSkillException.java b/src/main/java/com/gmail/nossr50/api/exceptions/InvalidSkillException.java index de0f847db..ed8e90941 100644 --- a/src/main/java/com/gmail/nossr50/api/exceptions/InvalidSkillException.java +++ b/src/main/java/com/gmail/nossr50/api/exceptions/InvalidSkillException.java @@ -1,6 +1,9 @@ package com.gmail.nossr50.api.exceptions; +import java.io.Serial; + public class InvalidSkillException extends RuntimeException { + @Serial private static final long serialVersionUID = 942705284195791157L; public InvalidSkillException() { diff --git a/src/main/java/com/gmail/nossr50/api/exceptions/InvalidXPGainReasonException.java b/src/main/java/com/gmail/nossr50/api/exceptions/InvalidXPGainReasonException.java index b2c1232b2..aeb4fd0f0 100644 --- a/src/main/java/com/gmail/nossr50/api/exceptions/InvalidXPGainReasonException.java +++ b/src/main/java/com/gmail/nossr50/api/exceptions/InvalidXPGainReasonException.java @@ -1,6 +1,9 @@ package com.gmail.nossr50.api.exceptions; +import java.io.Serial; + public class InvalidXPGainReasonException extends RuntimeException { + @Serial private static final long serialVersionUID = 4427052841957931157L; public InvalidXPGainReasonException() { diff --git a/src/main/java/com/gmail/nossr50/api/exceptions/McMMOPlayerNotFoundException.java b/src/main/java/com/gmail/nossr50/api/exceptions/McMMOPlayerNotFoundException.java index 374c04a9a..e2506ed36 100644 --- a/src/main/java/com/gmail/nossr50/api/exceptions/McMMOPlayerNotFoundException.java +++ b/src/main/java/com/gmail/nossr50/api/exceptions/McMMOPlayerNotFoundException.java @@ -1,12 +1,15 @@ package com.gmail.nossr50.api.exceptions; +import java.io.Serial; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; public class McMMOPlayerNotFoundException extends RuntimeException { + @Serial private static final long serialVersionUID = 761917904993202836L; public McMMOPlayerNotFoundException(@NotNull Player player) { - super("McMMOPlayer object was not found for [NOTE: This can mean the profile is not loaded yet! : " + player.getName() + " " + player.getUniqueId()); + super("McMMOPlayer object was not found for [NOTE: This can mean the profile is not loaded yet! : " + + player.getName() + " " + player.getUniqueId()); } } diff --git a/src/main/java/com/gmail/nossr50/api/exceptions/ValueOutOfBoundsException.java b/src/main/java/com/gmail/nossr50/api/exceptions/ValueOutOfBoundsException.java deleted file mode 100644 index 4fc4a7a6f..000000000 --- a/src/main/java/com/gmail/nossr50/api/exceptions/ValueOutOfBoundsException.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.gmail.nossr50.api.exceptions; - -import org.jetbrains.annotations.NotNull; - -public class ValueOutOfBoundsException extends RuntimeException { - public ValueOutOfBoundsException(@NotNull String message) { - super(message); - } -} diff --git a/src/main/java/com/gmail/nossr50/chat/ChatManager.java b/src/main/java/com/gmail/nossr50/chat/ChatManager.java index 0d7c21c65..1d4dd5341 100644 --- a/src/main/java/com/gmail/nossr50/chat/ChatManager.java +++ b/src/main/java/com/gmail/nossr50/chat/ChatManager.java @@ -23,7 +23,6 @@ public class ChatManager { private final @NotNull AdminChatMailer adminChatMailer; private final @NotNull PartyChatMailer partyChatMailer; - private final @NotNull ConsoleAuthor consoleAuthor; private final @NotNull Audience consoleAudience; @@ -34,7 +33,8 @@ public class ChatManager { partyChatMailer = new PartyChatMailer(pluginRef); this.consoleAuthor = new ConsoleAuthor(LocaleLoader.getString("Chat.Identity.Console")); - this.consoleAudience = mcMMO.getAudiences().filter((cs) -> cs instanceof ConsoleCommandSender); + this.consoleAudience = mcMMO.getAudiences() + .filter((cs) -> cs instanceof ConsoleCommandSender); this.isChatEnabled = ChatConfig.getInstance().isChatEnabled(); } @@ -45,7 +45,8 @@ public class ChatManager { * @param rawMessage the raw message from the player as it was typed * @param isAsync whether this is getting processed via async */ - public void processPlayerMessage(@NotNull McMMOPlayer mmoPlayer, @NotNull String rawMessage, boolean isAsync) { + public void processPlayerMessage(@NotNull McMMOPlayer mmoPlayer, @NotNull String rawMessage, + boolean isAsync) { processPlayerMessage(mmoPlayer, mmoPlayer.getChatChannel(), rawMessage, isAsync); } @@ -56,7 +57,8 @@ public class ChatManager { * @param args the raw command arguments from the player * @param chatChannel target channel */ - public void processPlayerMessage(@NotNull McMMOPlayer mmoPlayer, @NotNull String[] args, @NotNull ChatChannel chatChannel) { + public void processPlayerMessage(@NotNull McMMOPlayer mmoPlayer, @NotNull String[] args, + @NotNull ChatChannel chatChannel) { String chatMessageWithoutCommand = buildChatMessage(args); //Commands are never async @@ -71,13 +73,20 @@ public class ChatManager { * @param rawMessage raw chat message as it was typed * @param isAsync whether this is getting processed via async */ - private void processPlayerMessage(@NotNull McMMOPlayer mmoPlayer, @NotNull ChatChannel chatChannel, @NotNull String rawMessage, boolean isAsync) { + private void processPlayerMessage(@NotNull McMMOPlayer mmoPlayer, + @NotNull ChatChannel chatChannel, + @NotNull String rawMessage, boolean isAsync) { switch (chatChannel) { case ADMIN: - adminChatMailer.processChatMessage(mmoPlayer.getPlayerAuthor(), rawMessage, isAsync, Permissions.colorChat(mmoPlayer.getPlayer())); + adminChatMailer.processChatMessage( + mmoPlayer.getPlayerAuthor(), rawMessage, isAsync, + Permissions.colorChat(mmoPlayer.getPlayer())); break; case PARTY: - partyChatMailer.processChatMessage(mmoPlayer.getPlayerAuthor(), rawMessage, mmoPlayer.getParty(), isAsync, Permissions.colorChat(mmoPlayer.getPlayer()), Misc.isPartyLeader(mmoPlayer)); + partyChatMailer.processChatMessage( + mmoPlayer.getPlayerAuthor(), rawMessage, mmoPlayer.getParty(), + isAsync, Permissions.colorChat(mmoPlayer.getPlayer()), + Misc.isPartyLeader(mmoPlayer)); break; case PARTY_OFFICER: case NONE: @@ -87,6 +96,7 @@ public class ChatManager { /** * Handles console messaging to admins + * * @param rawMessage raw message from the console */ public void processConsoleMessage(@NotNull String rawMessage) { @@ -95,6 +105,7 @@ public class ChatManager { /** * Handles console messaging to admins + * * @param args raw command args from the console */ public void processConsoleMessage(@NotNull String[] args) { @@ -103,15 +114,18 @@ public class ChatManager { /** * Handles console messaging to a specific party + * * @param rawMessage raw message from the console * @param party target party */ public void processConsoleMessage(@NotNull String rawMessage, @NotNull Party party) { - partyChatMailer.processChatMessage(getConsoleAuthor(), rawMessage, party, false, true, false); + partyChatMailer.processChatMessage(getConsoleAuthor(), rawMessage, party, false, true, + false); } /** * Gets a console author + * * @return a {@link ConsoleAuthor} */ private @NotNull Author getConsoleAuthor() { @@ -119,31 +133,38 @@ public class ChatManager { } /** - * Change the chat channel of a {@link McMMOPlayer} - * Targeting the channel a player is already in will remove that player from the chat channel + * Change the chat channel of a {@link McMMOPlayer} Targeting the channel a player is already in + * will remove that player from the chat channel + * * @param mmoPlayer target player * @param targetChatChannel target chat channel */ - public void setOrToggleChatChannel(@NotNull McMMOPlayer mmoPlayer, @NotNull ChatChannel targetChatChannel) { + public void setOrToggleChatChannel(@NotNull McMMOPlayer mmoPlayer, + @NotNull ChatChannel targetChatChannel) { if (targetChatChannel == mmoPlayer.getChatChannel()) { //Disabled message - mmoPlayer.getPlayer().sendMessage(LocaleLoader.getString("Chat.Channel.Off", StringUtils.getCapitalized(targetChatChannel.toString()))); + mmoPlayer.getPlayer().sendMessage(LocaleLoader.getString( + "Chat.Channel.Off", + StringUtils.getCapitalized(targetChatChannel.toString()))); mmoPlayer.setChatMode(ChatChannel.NONE); } else { mmoPlayer.setChatMode(targetChatChannel); - mmoPlayer.getPlayer().sendMessage(LocaleLoader.getString("Chat.Channel.On", StringUtils.getCapitalized(targetChatChannel.toString()))); + mmoPlayer.getPlayer().sendMessage(LocaleLoader.getString( + "Chat.Channel.On", + StringUtils.getCapitalized(targetChatChannel.toString()))); } } /** * Create a chat message from an array of {@link String} + * * @param args array of {@link String} * @return a String built from the array */ private @NotNull String buildChatMessage(@NotNull String[] args) { StringBuilder stringBuilder = new StringBuilder(); - for(int i = 0; i < args.length; i++) { + for (int i = 0; i < args.length; i++) { if (i + 1 >= args.length) { stringBuilder.append(args[i]); } else { @@ -156,6 +177,7 @@ public class ChatManager { /** * Whether the player is allowed to send a message to the chat channel they are targeting + * * @param mmoPlayer target player * @return true if the player can send messages to that chat channel */ @@ -181,6 +203,7 @@ public class ChatManager { /** * Sends just the console a message + * * @param author author of the message * @param message message contents in component form */ @@ -190,6 +213,7 @@ public class ChatManager { /** * Whether the mcMMO chat system which handles party and admin chat is enabled or disabled + * * @return true if mcMMO chat processing (for party/admin chat) is enabled */ public boolean isChatEnabled() { @@ -197,11 +221,11 @@ public class ChatManager { } /** - * Whether a specific chat channel is enabled - * ChatChannels are enabled/disabled via user config + * Whether a specific chat channel is enabled ChatChannels are enabled/disabled via user config + *

+ * If chat is disabled, this always returns false If NONE is passed as a {@link ChatChannel} it + * will return true * - * If chat is disabled, this always returns false - * If NONE is passed as a {@link ChatChannel} it will return true * @param chatChannel target chat channel * @return true if the chat channel is enabled */ @@ -209,16 +233,11 @@ public class ChatManager { if (!isChatEnabled) { return false; } else { - switch(chatChannel) { - case ADMIN: - case PARTY: - case PARTY_OFFICER: - return ChatConfig.getInstance().isChatChannelEnabled(chatChannel); - case NONE: - return true; - default: - return false; - } + return switch (chatChannel) { + case ADMIN, PARTY, PARTY_OFFICER -> + ChatConfig.getInstance().isChatChannelEnabled(chatChannel); + case NONE -> true; + }; } } diff --git a/src/main/java/com/gmail/nossr50/chat/SamePartyPredicate.java b/src/main/java/com/gmail/nossr50/chat/SamePartyPredicate.java index 318460222..055310504 100644 --- a/src/main/java/com/gmail/nossr50/chat/SamePartyPredicate.java +++ b/src/main/java/com/gmail/nossr50/chat/SamePartyPredicate.java @@ -3,12 +3,11 @@ package com.gmail.nossr50.chat; import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.util.player.UserManager; +import java.util.function.Predicate; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; -import java.util.function.Predicate; - public class SamePartyPredicate implements Predicate { final Party party; @@ -21,12 +20,14 @@ public class SamePartyPredicate implements Predicate public boolean test(T t) { //Include the console in the audience if (t instanceof ConsoleCommandSender) { - return false; //Party audiences are special, we exclude console from them to avoid double messaging since we send a more verbose version to consoles + //Party audiences are special, we exclude console from them to avoid double + // messaging since we send a more verbose version to consoles + return false; } else { if (t instanceof Player player) { - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if (mcMMOPlayer != null) { - return mcMMOPlayer.getParty() == party; + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + if (mmoPlayer != null) { + return mmoPlayer.getParty() == party; } } } diff --git a/src/main/java/com/gmail/nossr50/chat/author/AbstractPlayerAuthor.java b/src/main/java/com/gmail/nossr50/chat/author/AbstractPlayerAuthor.java index 2b9344f51..d1b4299c1 100644 --- a/src/main/java/com/gmail/nossr50/chat/author/AbstractPlayerAuthor.java +++ b/src/main/java/com/gmail/nossr50/chat/author/AbstractPlayerAuthor.java @@ -3,17 +3,17 @@ package com.gmail.nossr50.chat.author; import com.gmail.nossr50.datatypes.chat.ChatChannel; import com.gmail.nossr50.util.text.TextUtils; import com.google.common.base.Objects; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; import org.bukkit.entity.Player; import org.checkerframework.checker.nullness.qual.NonNull; import org.jetbrains.annotations.NotNull; -import java.util.HashMap; -import java.util.UUID; - public abstract class AbstractPlayerAuthor implements Author { private final @NotNull Player player; + private final @NotNull Map sanitizedNameCache; private @NotNull String lastKnownDisplayName; - private final @NotNull HashMap sanitizedNameCache; public AbstractPlayerAuthor(@NotNull Player player) { this.player = player; @@ -31,22 +31,24 @@ public abstract class AbstractPlayerAuthor implements Author { } /** - * Player display names can change and this method will update the last known display name of this player + * Player display names can change and this method will update the last known display name of + * this player */ private void updateLastKnownDisplayName() { lastKnownDisplayName = player.getDisplayName(); } /** - * Gets a sanitized name for a channel - * Sanitized names are names that are friendly to the {@link net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer} - * Sanitized names for authors are cached by channel and are only created as needed - * Sanitized names will update if a players display name has updated + * Gets a sanitized name for a channel Sanitized names are names that are friendly to the + * {@link net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer} Sanitized names + * for authors are cached by channel and are only created as needed Sanitized names will update + * if a players display name has updated * * @param chatChannel target chat channel * @return the sanitized name for a player */ - protected @NotNull String getSanitizedName(@NotNull ChatChannel chatChannel, boolean useDisplayName) { + protected @NotNull String getSanitizedName(@NotNull ChatChannel chatChannel, + boolean useDisplayName) { //Already in cache if (sanitizedNameCache.containsKey(chatChannel)) { //Update cache @@ -68,16 +70,18 @@ public abstract class AbstractPlayerAuthor implements Author { } /** - * Update the sanitized name cache - * This will add entries if one didn't exit - * Sanitized names are associated with a {@link ChatChannel} as different chat channels have different chat name settings + * Update the sanitized name cache This will add entries if one didn't exit Sanitized names are + * associated with a {@link ChatChannel} as different chat channels have different chat name + * settings * * @param chatChannel target chat channel * @param useDisplayName whether to use this authors display name */ - private void updateSanitizedNameCache(@NotNull ChatChannel chatChannel, boolean useDisplayName) { + private void updateSanitizedNameCache(@NotNull ChatChannel chatChannel, + boolean useDisplayName) { if (useDisplayName) { - sanitizedNameCache.put(chatChannel, TextUtils.sanitizeForSerializer(player.getDisplayName())); + sanitizedNameCache.put(chatChannel, + TextUtils.sanitizeForSerializer(player.getDisplayName())); } else { //No need to sanitize a basic String sanitizedNameCache.put(chatChannel, player.getName()); @@ -105,12 +109,17 @@ public abstract class AbstractPlayerAuthor implements Author { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } AbstractPlayerAuthor that = (AbstractPlayerAuthor) o; - return Objects.equal(player, that.player) && - Objects.equal(lastKnownDisplayName, that.lastKnownDisplayName) && - Objects.equal(sanitizedNameCache, that.sanitizedNameCache); + return Objects.equal(player, that.player) && Objects.equal( + lastKnownDisplayName, + that.lastKnownDisplayName) && Objects.equal( + sanitizedNameCache, that.sanitizedNameCache); } @Override diff --git a/src/main/java/com/gmail/nossr50/chat/author/Author.java b/src/main/java/com/gmail/nossr50/chat/author/Author.java index c7c35b7e2..feec3d257 100644 --- a/src/main/java/com/gmail/nossr50/chat/author/Author.java +++ b/src/main/java/com/gmail/nossr50/chat/author/Author.java @@ -7,9 +7,9 @@ import org.jetbrains.annotations.NotNull; public interface Author extends Identity { /** - * The name of this author as used in mcMMO chat - * This is the {@link String} representation of the users current chat username - * This can either be the player's display name or the player's official registered nickname with Mojang it depends on the servers chat settings for mcMMO + * The name of this author as used in mcMMO chat This is the {@link String} representation of + * the users current chat username This can either be the player's display name or the player's + * official registered nickname with Mojang it depends on the servers chat settings for mcMMO * * @param chatChannel which chat channel this is going to * @return The name of this author as used in mcMMO chat @@ -25,6 +25,7 @@ public interface Author extends Identity { /** * Whether this author is a {@link org.bukkit.entity.Player} + * * @return true if this author is a player */ boolean isPlayer(); diff --git a/src/main/java/com/gmail/nossr50/chat/author/ConsoleAuthor.java b/src/main/java/com/gmail/nossr50/chat/author/ConsoleAuthor.java index 3c6452d32..24bb0cd6e 100644 --- a/src/main/java/com/gmail/nossr50/chat/author/ConsoleAuthor.java +++ b/src/main/java/com/gmail/nossr50/chat/author/ConsoleAuthor.java @@ -2,11 +2,10 @@ package com.gmail.nossr50.chat.author; import com.gmail.nossr50.datatypes.chat.ChatChannel; import com.gmail.nossr50.util.text.TextUtils; +import java.util.UUID; import org.checkerframework.checker.nullness.qual.NonNull; import org.jetbrains.annotations.NotNull; -import java.util.UUID; - public class ConsoleAuthor implements Author { private final UUID uuid; private final @NotNull String name; diff --git a/src/main/java/com/gmail/nossr50/chat/mailer/AdminChatMailer.java b/src/main/java/com/gmail/nossr50/chat/mailer/AdminChatMailer.java index 96c7ad1a6..a9bc7dc9d 100644 --- a/src/main/java/com/gmail/nossr50/chat/mailer/AdminChatMailer.java +++ b/src/main/java/com/gmail/nossr50/chat/mailer/AdminChatMailer.java @@ -10,6 +10,7 @@ import com.gmail.nossr50.events.chat.McMMOChatEvent; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.text.TextUtils; +import java.util.function.Predicate; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.text.TextComponent; import org.bukkit.Bukkit; @@ -18,16 +19,14 @@ import org.bukkit.command.ConsoleCommandSender; import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; -import java.util.function.Predicate; - public class AdminChatMailer extends AbstractChatMailer { + public static final @NotNull String MCMMO_CHAT_ADMINCHAT_PERMISSION = "mcmmo.chat.adminchat"; + public AdminChatMailer(Plugin pluginRef) { super(pluginRef); } - public static final @NotNull String MCMMO_CHAT_ADMINCHAT_PERMISSION = "mcmmo.chat.adminchat"; - /** * Constructs an audience of admins * @@ -43,9 +42,10 @@ public class AdminChatMailer extends AbstractChatMailer { * @return admin chat audience predicate */ public @NotNull Predicate predicate() { - return (commandSender) -> commandSender.isOp() - || commandSender.hasPermission(MCMMO_CHAT_ADMINCHAT_PERMISSION) - || (ChatConfig.getInstance().isConsoleIncludedInAudience(ChatChannel.ADMIN) && commandSender instanceof ConsoleCommandSender); + return (commandSender) -> commandSender.isOp() || commandSender.hasPermission( + MCMMO_CHAT_ADMINCHAT_PERMISSION) || ( + ChatConfig.getInstance().isConsoleIncludedInAudience( + ChatChannel.ADMIN) && commandSender instanceof ConsoleCommandSender); } /** @@ -56,11 +56,16 @@ public class AdminChatMailer extends AbstractChatMailer { * @param canColor whether to replace colors codes with colors in the raw message * @return the styled string, based on a locale entry */ - public @NotNull TextComponent addStyle(@NotNull Author author, @NotNull String message, boolean canColor) { + public @NotNull TextComponent addStyle(@NotNull Author author, @NotNull String message, + boolean canColor) { if (canColor) { - return LocaleLoader.getTextComponent("Chat.Style.Admin", author.getAuthoredName(ChatChannel.ADMIN), message); + return LocaleLoader.getTextComponent( + "Chat.Style.Admin", author.getAuthoredName(ChatChannel.ADMIN), + message); } else { - return TextUtils.ofLegacyTextRaw(LocaleLoader.getString("Chat.Style.Admin", author.getAuthoredName(ChatChannel.ADMIN), message)); + return TextUtils.ofLegacyTextRaw( + LocaleLoader.getString("Chat.Style.Admin", + author.getAuthoredName(ChatChannel.ADMIN), message)); } } @@ -77,8 +82,12 @@ public class AdminChatMailer extends AbstractChatMailer { * @param isAsync whether this is being processed asynchronously * @param canColor whether the author can use colors in chat */ - public void processChatMessage(@NotNull Author author, @NotNull String rawString, boolean isAsync, boolean canColor) { - AdminChatMessage chatMessage = new AdminChatMessage(pluginRef, author, constructAudience(), rawString, addStyle(author, rawString, canColor)); + public void processChatMessage(@NotNull Author author, @NotNull String rawString, + boolean isAsync, + boolean canColor) { + AdminChatMessage chatMessage = new AdminChatMessage( + pluginRef, author, constructAudience(), rawString, + addStyle(author, rawString, canColor)); McMMOChatEvent chatEvent = new McMMOAdminChatEvent(pluginRef, chatMessage, isAsync); Bukkit.getPluginManager().callEvent(chatEvent); diff --git a/src/main/java/com/gmail/nossr50/chat/mailer/ChatMailer.java b/src/main/java/com/gmail/nossr50/chat/mailer/ChatMailer.java index 77d456b6f..bbd3d9e0c 100644 --- a/src/main/java/com/gmail/nossr50/chat/mailer/ChatMailer.java +++ b/src/main/java/com/gmail/nossr50/chat/mailer/ChatMailer.java @@ -6,6 +6,7 @@ import org.jetbrains.annotations.NotNull; public interface ChatMailer { /** * Send out a chat message + * * @param chatMessage the {@link ChatMessage} */ void sendMail(@NotNull ChatMessage chatMessage); diff --git a/src/main/java/com/gmail/nossr50/chat/mailer/PartyChatMailer.java b/src/main/java/com/gmail/nossr50/chat/mailer/PartyChatMailer.java index e4edb0320..34bc560f1 100644 --- a/src/main/java/com/gmail/nossr50/chat/mailer/PartyChatMailer.java +++ b/src/main/java/com/gmail/nossr50/chat/mailer/PartyChatMailer.java @@ -30,8 +30,12 @@ public class PartyChatMailer extends AbstractChatMailer { * @param isAsync whether this is being processed asynchronously * @param canColor whether the author can use colors in chat */ - public void processChatMessage(@NotNull Author author, @NotNull String rawString, @NotNull Party party, boolean isAsync, boolean canColor, boolean isLeader) { - PartyChatMessage chatMessage = new PartyChatMessage(pluginRef, author, constructPartyAudience(party), rawString, addStyle(author, rawString, canColor, isLeader), party); + public void processChatMessage(@NotNull Author author, @NotNull String rawString, + @NotNull Party party, + boolean isAsync, boolean canColor, boolean isLeader) { + PartyChatMessage chatMessage = new PartyChatMessage( + pluginRef, author, constructPartyAudience(party), rawString, + addStyle(author, rawString, canColor, isLeader), party); McMMOChatEvent chatEvent = new McMMOPartyChatEvent(pluginRef, chatMessage, party, isAsync); Bukkit.getPluginManager().callEvent(chatEvent); @@ -59,18 +63,29 @@ public class PartyChatMailer extends AbstractChatMailer { * @param canColor whether to replace colors codes with colors in the raw message * @return the styled string, based on a locale entry */ - public @NotNull TextComponent addStyle(@NotNull Author author, @NotNull String message, boolean canColor, boolean isLeader) { + public @NotNull TextComponent addStyle(@NotNull Author author, @NotNull String message, + boolean canColor, + boolean isLeader) { if (canColor) { if (isLeader) { - return LocaleLoader.getTextComponent("Chat.Style.Party.Leader", author.getAuthoredName(ChatChannel.PARTY), message); + return LocaleLoader.getTextComponent( + "Chat.Style.Party.Leader", + author.getAuthoredName(ChatChannel.PARTY), message); } else { - return LocaleLoader.getTextComponent("Chat.Style.Party", author.getAuthoredName(ChatChannel.PARTY), message); + return LocaleLoader.getTextComponent( + "Chat.Style.Party", author.getAuthoredName(ChatChannel.PARTY), + message); } } else { if (isLeader) { - return TextUtils.ofLegacyTextRaw(LocaleLoader.getString("Chat.Style.Party.Leader", author.getAuthoredName(ChatChannel.PARTY), message)); + return TextUtils.ofLegacyTextRaw( + LocaleLoader.getString( + "Chat.Style.Party.Leader", + author.getAuthoredName(ChatChannel.PARTY), message)); } else { - return TextUtils.ofLegacyTextRaw(LocaleLoader.getString("Chat.Style.Party", author.getAuthoredName(ChatChannel.PARTY), message)); + return TextUtils.ofLegacyTextRaw( + LocaleLoader.getString("Chat.Style.Party", + author.getAuthoredName(ChatChannel.PARTY), message)); } } } diff --git a/src/main/java/com/gmail/nossr50/chat/message/AbstractChatMessage.java b/src/main/java/com/gmail/nossr50/chat/message/AbstractChatMessage.java index 5eeb889e4..a1269c334 100644 --- a/src/main/java/com/gmail/nossr50/chat/message/AbstractChatMessage.java +++ b/src/main/java/com/gmail/nossr50/chat/message/AbstractChatMessage.java @@ -15,7 +15,9 @@ public abstract class AbstractChatMessage implements ChatMessage { protected @NotNull TextComponent componentMessage; protected @NotNull Audience audience; - public AbstractChatMessage(@NotNull Plugin pluginRef, @NotNull Author author, @NotNull Audience audience, @NotNull String rawMessage, @NotNull TextComponent componentMessage) { + public AbstractChatMessage(@NotNull Plugin pluginRef, @NotNull Author author, + @NotNull Audience audience, + @NotNull String rawMessage, @NotNull TextComponent componentMessage) { this.pluginRef = pluginRef; this.author = author; this.audience = audience; @@ -38,6 +40,11 @@ public abstract class AbstractChatMessage implements ChatMessage { return audience; } + @Override + public void setAudience(@NotNull Audience newAudience) { + audience = newAudience; + } + @Override public @NotNull TextComponent getChatMessage() { return componentMessage; @@ -48,21 +55,20 @@ public abstract class AbstractChatMessage implements ChatMessage { this.componentMessage = textComponent; } - @Override - public void setAudience(@NotNull Audience newAudience) { - audience = newAudience; - } - @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } AbstractChatMessage that = (AbstractChatMessage) o; - return Objects.equal(pluginRef, that.pluginRef) && - Objects.equal(author, that.author) && - Objects.equal(rawMessage, that.rawMessage) && - Objects.equal(componentMessage, that.componentMessage) && - Objects.equal(audience, that.audience); + return Objects.equal(pluginRef, that.pluginRef) && Objects.equal(author, that.author) + && Objects.equal( + rawMessage, that.rawMessage) && Objects.equal(componentMessage, + that.componentMessage) && Objects.equal( + audience, that.audience); } @Override diff --git a/src/main/java/com/gmail/nossr50/chat/message/AdminChatMessage.java b/src/main/java/com/gmail/nossr50/chat/message/AdminChatMessage.java index 973c0f0c7..1daca02f0 100644 --- a/src/main/java/com/gmail/nossr50/chat/message/AdminChatMessage.java +++ b/src/main/java/com/gmail/nossr50/chat/message/AdminChatMessage.java @@ -8,7 +8,9 @@ import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; public class AdminChatMessage extends AbstractChatMessage { - public AdminChatMessage(@NotNull Plugin pluginRef, @NotNull Author author, @NotNull Audience audience, @NotNull String rawMessage, @NotNull TextComponent componentMessage) { + public AdminChatMessage(@NotNull Plugin pluginRef, @NotNull Author author, + @NotNull Audience audience, + @NotNull String rawMessage, @NotNull TextComponent componentMessage) { super(pluginRef, author, audience, rawMessage, componentMessage); } diff --git a/src/main/java/com/gmail/nossr50/chat/message/ChatMessage.java b/src/main/java/com/gmail/nossr50/chat/message/ChatMessage.java index 45bc1ac18..3bcabdd3c 100644 --- a/src/main/java/com/gmail/nossr50/chat/message/ChatMessage.java +++ b/src/main/java/com/gmail/nossr50/chat/message/ChatMessage.java @@ -7,8 +7,8 @@ import org.jetbrains.annotations.NotNull; public interface ChatMessage { /** - * The original message from the {@link Author} - * This is formatted and styled before being sent out to players by mcMMO + * The original message from the {@link Author} This is formatted and styled before being sent + * out to players by mcMMO * * @return the original message without any formatting or alterations * @see #getChatMessage() @@ -18,33 +18,42 @@ public interface ChatMessage { /** * The {@link Author} from which this payload originated * - * @see #getChatMessage() * @return the source of the chat message + * @see #getChatMessage() */ @NotNull Author getAuthor(); /** - * The authors display name which is used in the initial creation of the message payload, it is provided for convenience. - * + * The authors display name which is used in the initial creation of the message payload, it is + * provided for convenience. + *

* This is a name generated by mcMMO during the creation of the {@link ChatMessage} - * + *

* This is used by mcMMO when generating the message payload + *

+ * This method provides the display name for the convenience of plugins constructing their own + * {@link TextComponent payloads} * - * This method provides the display name for the convenience of plugins constructing their own {@link TextComponent payloads} - * - * @see #getChatMessage() * @return the author display name as generated by mcMMO + * @see #getChatMessage() */ @NotNull String getAuthorDisplayName(); /** - * The target audience of this chat message - * Unless modified, this will include the {@link Author} + * The target audience of this chat message Unless modified, this will include the + * {@link Author} * * @return target audience */ @NotNull Audience getAudience(); + /** + * Changes the audience + * + * @param newAudience the replacement audience + */ + void setAudience(@NotNull Audience newAudience); + /** * The {@link TextComponent message} being sent to the audience * @@ -59,13 +68,6 @@ public interface ChatMessage { */ void setChatMessage(@NotNull TextComponent textComponent); - /** - * Changes the audience - * - * @param newAudience the replacement audience - */ - void setAudience(@NotNull Audience newAudience); - /** * Deliver the message to the audience */ diff --git a/src/main/java/com/gmail/nossr50/chat/message/PartyChatMessage.java b/src/main/java/com/gmail/nossr50/chat/message/PartyChatMessage.java index 02b2499ea..5bbee66d1 100644 --- a/src/main/java/com/gmail/nossr50/chat/message/PartyChatMessage.java +++ b/src/main/java/com/gmail/nossr50/chat/message/PartyChatMessage.java @@ -19,13 +19,17 @@ public class PartyChatMessage extends AbstractChatMessage { private final @NotNull Party party; - public PartyChatMessage(@NotNull Plugin pluginRef, @NotNull Author author, @NotNull Audience audience, @NotNull String rawMessage, @NotNull TextComponent componentMessage, @NotNull Party party) { + public PartyChatMessage(@NotNull Plugin pluginRef, @NotNull Author author, + @NotNull Audience audience, + @NotNull String rawMessage, @NotNull TextComponent componentMessage, + @NotNull Party party) { super(pluginRef, author, audience, rawMessage, componentMessage); this.party = party; } /** * The party that this chat message was intended for + * * @return the party that this message was intended for */ public @NotNull Party getParty() { @@ -46,29 +50,33 @@ public class PartyChatMessage extends AbstractChatMessage { //Sends to everyone but console audience.sendMessage(author, componentMessage); - TextComponent spyMessage = LocaleLoader.getTextComponent("Chat.Spy.Party", author.getAuthoredName(ChatChannel.PARTY), rawMessage, party.getName()); + final TextComponent spyMessage = LocaleLoader.getTextComponent( + "Chat.Spy.Party", + author.getAuthoredName(ChatChannel.PARTY), rawMessage, party.getName()); //Relay to spies messagePartyChatSpies(spyMessage); //Console message - if (ChatConfig.getInstance().isConsoleIncludedInAudience(ChatChannel.PARTY)) + if (ChatConfig.getInstance().isConsoleIncludedInAudience(ChatChannel.PARTY)) { mcMMO.p.getChatManager().sendConsoleMessage(author, spyMessage); + } } /** - * Console and Party Chat Spies get a more verbose version of the message - * Party Chat Spies will get a copy of the message as well + * Console and Party Chat Spies get a more verbose version of the message Party Chat Spies will + * get a copy of the message as well + * * @param spyMessage the message to copy to spies */ private void messagePartyChatSpies(@NotNull TextComponent spyMessage) { //Find the people with permissions - for(McMMOPlayer mcMMOPlayer : UserManager.getPlayers()) { - Player player = mcMMOPlayer.getPlayer(); + for (McMMOPlayer mmoPlayer : UserManager.getPlayers()) { + final Player player = mmoPlayer.getPlayer(); //Check for toggled players - if (mcMMOPlayer.isPartyChatSpying()) { - Party adminParty = mcMMOPlayer.getParty(); + if (mmoPlayer.isPartyChatSpying()) { + Party adminParty = mmoPlayer.getParty(); //Only message admins not part of this party if (adminParty == null || adminParty != getParty()) { @@ -82,10 +90,16 @@ public class PartyChatMessage extends AbstractChatMessage { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - if (!super.equals(o)) return false; - PartyChatMessage that = (PartyChatMessage) o; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + if (!super.equals(o)) { + return false; + } + final PartyChatMessage that = (PartyChatMessage) o; return Objects.equal(party, that.party); } diff --git a/src/main/java/com/gmail/nossr50/commands/CommandManager.java b/src/main/java/com/gmail/nossr50/commands/CommandManager.java index d870baed0..fbb7cf445 100644 --- a/src/main/java/com/gmail/nossr50/commands/CommandManager.java +++ b/src/main/java/com/gmail/nossr50/commands/CommandManager.java @@ -60,7 +60,8 @@ public class CommandManager { if (ChatConfig.getInstance().isChatChannelEnabled(ChatChannel.ADMIN)) { bukkitCommandManager.registerCommand(new AdminChatCommand(pluginRef)); } - if (pluginRef.getPartyConfig().isPartyEnabled() && ChatConfig.getInstance().isChatChannelEnabled(ChatChannel.PARTY)) { + if (pluginRef.getPartyConfig().isPartyEnabled() && ChatConfig.getInstance() + .isChatChannelEnabled(ChatChannel.PARTY)) { bukkitCommandManager.registerCommand(new PartyChatCommand(pluginRef)); } } @@ -72,15 +73,17 @@ public class CommandManager { } private void registerSkillConditions() { - bukkitCommandManager.getCommandConditions().addCondition(POWER_LEVEL_CONDITION, (context) -> { - BukkitCommandIssuer issuer = context.getIssuer(); + bukkitCommandManager.getCommandConditions() + .addCondition(POWER_LEVEL_CONDITION, (context) -> { + BukkitCommandIssuer issuer = context.getIssuer(); - if (issuer.getIssuer() instanceof Player) { - validateLoadedData(issuer.getPlayer()); - } else { - throw new ConditionFailedException(LocaleLoader.getString("Commands.NoConsole")); - } - }); + if (issuer.getIssuer() instanceof Player) { + validateLoadedData(issuer.getPlayer()); + } else { + throw new ConditionFailedException( + LocaleLoader.getString("Commands.NoConsole")); + } + }); } private void registerChatCommandConditions() { @@ -114,7 +117,8 @@ public class CommandManager { }); } - private void validatePermission(@NotNull String permissionNode, @NotNull Permissible permissible) { + private void validatePermission(@NotNull String permissionNode, + @NotNull Permissible permissible) { if (!permissible.hasPermission(permissionNode)) { throw new ConditionFailedException(LocaleLoader.getString("mcMMO.NoPermission")); } @@ -123,7 +127,8 @@ public class CommandManager { public void validateAdmin(@NotNull Player player) { if (!player.isOp() && !Permissions.adminChat(player)) { - throw new ConditionFailedException("You are lacking the correct permissions to use this command."); + throw new ConditionFailedException( + "You are lacking the correct permissions to use this command."); } } @@ -134,7 +139,7 @@ public class CommandManager { } public void validatePlayerParty(@NotNull Player player) { - McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); if (!pluginRef.getPartyConfig().isPartyEnabled() || mmoPlayer.getParty() == null) { throw new ConditionFailedException(LocaleLoader.getString("Commands.Party.None")); diff --git a/src/main/java/com/gmail/nossr50/commands/McabilityCommand.java b/src/main/java/com/gmail/nossr50/commands/McabilityCommand.java index 0628b9364..c391dc9ff 100644 --- a/src/main/java/com/gmail/nossr50/commands/McabilityCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/McabilityCommand.java @@ -17,9 +17,10 @@ public class McabilityCommand extends ToggleCommand { } @Override - protected void applyCommandAction(McMMOPlayer mcMMOPlayer) { - mcMMOPlayer.getPlayer().sendMessage(LocaleLoader.getString("Commands.Ability." + (mcMMOPlayer.getAbilityUse() ? "Off" : "On"))); - mcMMOPlayer.toggleAbilityUse(); + protected void applyCommandAction(McMMOPlayer mmoPlayer) { + mmoPlayer.getPlayer().sendMessage(LocaleLoader.getString( + "Commands.Ability." + (mmoPlayer.getAbilityUse() ? "Off" : "On"))); + mmoPlayer.toggleAbilityUse(); } @Override diff --git a/src/main/java/com/gmail/nossr50/commands/McconvertCommand.java b/src/main/java/com/gmail/nossr50/commands/McconvertCommand.java index e00510078..5b07e15c2 100644 --- a/src/main/java/com/gmail/nossr50/commands/McconvertCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/McconvertCommand.java @@ -7,6 +7,9 @@ import com.gmail.nossr50.datatypes.database.DatabaseType; import com.gmail.nossr50.datatypes.experience.FormulaType; import com.gmail.nossr50.mcMMO; import com.google.common.collect.ImmutableList; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; @@ -14,10 +17,6 @@ import org.bukkit.command.TabExecutor; import org.bukkit.util.StringUtil; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - public class McconvertCommand implements TabExecutor { private static final List FORMULA_TYPES; private static final List DATABASE_TYPES; @@ -54,11 +53,13 @@ public class McconvertCommand implements TabExecutor { } @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (args.length == 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); } @@ -68,17 +69,22 @@ public class McconvertCommand implements TabExecutor { } @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, String[] args) { switch (args.length) { case 1: - return StringUtil.copyPartialMatches(args[0], SUBCOMMANDS, new ArrayList<>(SUBCOMMANDS.size())); + return StringUtil.copyPartialMatches(args[0], SUBCOMMANDS, + new ArrayList<>(SUBCOMMANDS.size())); case 2: if (args[0].equalsIgnoreCase("database") || args[0].equalsIgnoreCase("db")) { - return StringUtil.copyPartialMatches(args[0], DATABASE_TYPES, new ArrayList<>(DATABASE_TYPES.size())); + return StringUtil.copyPartialMatches(args[0], DATABASE_TYPES, + new ArrayList<>(DATABASE_TYPES.size())); } - if (args[0].equalsIgnoreCase("experience") || args[0].equalsIgnoreCase("xp") || args[0].equalsIgnoreCase("exp")) { - return StringUtil.copyPartialMatches(args[0], FORMULA_TYPES, new ArrayList<>(FORMULA_TYPES.size())); + if (args[0].equalsIgnoreCase("experience") || args[0].equalsIgnoreCase("xp") + || args[0].equalsIgnoreCase("exp")) { + return StringUtil.copyPartialMatches(args[0], FORMULA_TYPES, + new ArrayList<>(FORMULA_TYPES.size())); } return ImmutableList.of(); diff --git a/src/main/java/com/gmail/nossr50/commands/McgodCommand.java b/src/main/java/com/gmail/nossr50/commands/McgodCommand.java index 1867c4672..00fb1c6a1 100644 --- a/src/main/java/com/gmail/nossr50/commands/McgodCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/McgodCommand.java @@ -17,9 +17,10 @@ public class McgodCommand extends ToggleCommand { } @Override - protected void applyCommandAction(McMMOPlayer mcMMOPlayer) { - mcMMOPlayer.getPlayer().sendMessage(LocaleLoader.getString("Commands.GodMode." + (mcMMOPlayer.getGodMode() ? "Disabled" : "Enabled"))); - mcMMOPlayer.toggleGodMode(); + protected void applyCommandAction(McMMOPlayer mmoPlayer) { + mmoPlayer.getPlayer().sendMessage(LocaleLoader.getString( + "Commands.GodMode." + (mmoPlayer.getGodMode() ? "Disabled" : "Enabled"))); + mmoPlayer.toggleGodMode(); } @Override diff --git a/src/main/java/com/gmail/nossr50/commands/McmmoCommand.java b/src/main/java/com/gmail/nossr50/commands/McmmoCommand.java index 6660e2fbc..dc3a4a9f5 100644 --- a/src/main/java/com/gmail/nossr50/commands/McmmoCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/McmmoCommand.java @@ -12,7 +12,8 @@ import org.jetbrains.annotations.NotNull; public class McmmoCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { switch (args.length) { case 0: if (!Permissions.mcmmoDescription(sender)) { @@ -27,18 +28,22 @@ public class McmmoCommand implements CommandExecutor { if (mcMMO.p.getGeneralConfig().getDonateMessageEnabled()) { sender.sendMessage(LocaleLoader.getString("MOTD.Donate")); - sender.sendMessage(ChatColor.GOLD + " - " + ChatColor.GREEN + "nossr50@gmail.com" + ChatColor.GOLD + " Paypal"); + sender.sendMessage( + ChatColor.GOLD + " - " + ChatColor.GREEN + "nossr50@gmail.com" + + ChatColor.GOLD + " Paypal"); } if (Permissions.showversion(sender)) { - sender.sendMessage(LocaleLoader.getString("MOTD.Version", mcMMO.p.getDescription().getVersion())); + sender.sendMessage(LocaleLoader.getString("MOTD.Version", + mcMMO.p.getDescription().getVersion())); } // mcMMO.getHolidayManager().anniversaryCheck(sender); return true; case 1: - if (args[0].equalsIgnoreCase("?") || args[0].equalsIgnoreCase("help") || args[0].equalsIgnoreCase("commands")) { + if (args[0].equalsIgnoreCase("?") || args[0].equalsIgnoreCase("help") + || args[0].equalsIgnoreCase("commands")) { if (!Permissions.mcmmoHelp(sender)) { sender.sendMessage(command.getPermissionMessage()); return true; @@ -72,8 +77,10 @@ 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 d693a99c7..289fc8d80 100644 --- a/src/main/java/com/gmail/nossr50/commands/McnotifyCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/McnotifyCommand.java @@ -5,39 +5,41 @@ import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.player.UserManager; import com.google.common.collect.ImmutableList; +import java.util.List; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabExecutor; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.List; - public class McnotifyCommand implements TabExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (CommandUtils.noConsoleUsage(sender)) { return true; } if (args.length == 0) { - McMMOPlayer mcMMOPlayer = UserManager.getPlayer((Player) sender); + final McMMOPlayer mmoPlayer = UserManager.getPlayer((Player) sender); //Not Loaded yet - if (mcMMOPlayer == null) { + if (mmoPlayer == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } - sender.sendMessage(LocaleLoader.getString("Commands.Notifications." + (mcMMOPlayer.useChatNotifications() ? "Off" : "On"))); - mcMMOPlayer.toggleChatNotifications(); + sender.sendMessage(LocaleLoader.getString( + "Commands.Notifications." + (mmoPlayer.useChatNotifications() ? "Off" : "On"))); + mmoPlayer.toggleChatNotifications(); return true; } return false; } @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, String[] args) { return ImmutableList.of(); } } diff --git a/src/main/java/com/gmail/nossr50/commands/McrefreshCommand.java b/src/main/java/com/gmail/nossr50/commands/McrefreshCommand.java index 9cc0ed3c1..8d38ac90c 100644 --- a/src/main/java/com/gmail/nossr50/commands/McrefreshCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/McrefreshCommand.java @@ -17,13 +17,13 @@ public class McrefreshCommand extends ToggleCommand { } @Override - protected void applyCommandAction(McMMOPlayer mcMMOPlayer) { - mcMMOPlayer.setRecentlyHurt(0); - mcMMOPlayer.resetCooldowns(); - mcMMOPlayer.resetToolPrepMode(); - mcMMOPlayer.resetAbilityMode(); + protected void applyCommandAction(McMMOPlayer mmoPlayer) { + mmoPlayer.setRecentlyHurt(0); + mmoPlayer.resetCooldowns(); + mmoPlayer.resetToolPrepMode(); + mmoPlayer.resetAbilityMode(); - mcMMOPlayer.getPlayer().sendMessage(LocaleLoader.getString("Ability.Generic.Refresh")); + mmoPlayer.getPlayer().sendMessage(LocaleLoader.getString("Ability.Generic.Refresh")); } @Override diff --git a/src/main/java/com/gmail/nossr50/commands/McscoreboardCommand.java b/src/main/java/com/gmail/nossr50/commands/McscoreboardCommand.java index 8bcdde1ad..074780438 100644 --- a/src/main/java/com/gmail/nossr50/commands/McscoreboardCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/McscoreboardCommand.java @@ -5,20 +5,20 @@ import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.scoreboards.ScoreboardManager; import com.google.common.collect.ImmutableList; +import java.util.ArrayList; +import java.util.List; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabExecutor; import org.bukkit.util.StringUtil; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.List; - public class McscoreboardCommand implements TabExecutor { private static final List FIRST_ARGS = ImmutableList.of("keep", "time", "clear"); @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (CommandUtils.noConsoleUsage(sender)) { return true; } @@ -42,7 +42,8 @@ public class McscoreboardCommand implements TabExecutor { } if (args[0].equalsIgnoreCase("keep")) { - if (!mcMMO.p.getGeneralConfig().getAllowKeepBoard() || !mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) { + if (!mcMMO.p.getGeneralConfig().getAllowKeepBoard() + || !mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) { sender.sendMessage(LocaleLoader.getString("Commands.Disabled")); return true; } @@ -80,9 +81,11 @@ public class McscoreboardCommand implements TabExecutor { } @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, String[] args) { if (args.length == 1) { - return StringUtil.copyPartialMatches(args[0], FIRST_ARGS, new ArrayList<>(FIRST_ARGS.size())); + return StringUtil.copyPartialMatches(args[0], FIRST_ARGS, + new ArrayList<>(FIRST_ARGS.size())); } return ImmutableList.of(); } diff --git a/src/main/java/com/gmail/nossr50/commands/ToggleCommand.java b/src/main/java/com/gmail/nossr50/commands/ToggleCommand.java index fea470d0e..d73bc0c8a 100644 --- a/src/main/java/com/gmail/nossr50/commands/ToggleCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/ToggleCommand.java @@ -4,18 +4,18 @@ import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.player.UserManager; import com.google.common.collect.ImmutableList; +import java.util.ArrayList; +import java.util.List; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabExecutor; import org.bukkit.util.StringUtil; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.List; - public abstract class ToggleCommand implements TabExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { switch (args.length) { case 0: if (CommandUtils.noConsoleUsage(sender)) { @@ -41,17 +41,17 @@ public abstract class ToggleCommand implements TabExecutor { } String playerName = CommandUtils.getMatchedPlayerName(args[0]); - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(playerName); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(playerName); - if (!CommandUtils.checkPlayerExistence(sender, playerName, mcMMOPlayer)) { + if (!CommandUtils.checkPlayerExistence(sender, playerName, mmoPlayer)) { return true; } - if (CommandUtils.isOffline(sender, mcMMOPlayer.getPlayer())) { + if (CommandUtils.isOffline(sender, mmoPlayer.getPlayer())) { return true; } - applyCommandAction(mcMMOPlayer); + applyCommandAction(mmoPlayer); sendSuccessMessage(sender, playerName); return true; @@ -61,16 +61,21 @@ public abstract class ToggleCommand implements TabExecutor { } @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, String[] args) { if (args.length == 1) { List playerNames = CommandUtils.getOnlinePlayerNames(sender); - return StringUtil.copyPartialMatches(args[0], playerNames, new ArrayList<>(playerNames.size())); + return StringUtil.copyPartialMatches(args[0], playerNames, + new ArrayList<>(playerNames.size())); } return ImmutableList.of(); } protected abstract boolean hasOtherPermission(CommandSender sender); + protected abstract boolean hasSelfPermission(CommandSender sender); - protected abstract void applyCommandAction(McMMOPlayer mcMMOPlayer); + + protected abstract void applyCommandAction(McMMOPlayer mmoPlayer); + 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 2eb487826..d42be646a 100644 --- a/src/main/java/com/gmail/nossr50/commands/XprateCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/XprateCommand.java @@ -9,6 +9,8 @@ import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.player.NotificationManager; import com.gmail.nossr50.util.text.StringUtils; import com.google.common.collect.ImmutableList; +import java.util.ArrayList; +import java.util.List; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; @@ -16,17 +18,16 @@ import org.bukkit.command.TabExecutor; import org.bukkit.util.StringUtil; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.List; - public class XprateCommand implements TabExecutor { - private final double ORIGINAL_XP_RATE = ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier(); + private final double ORIGINAL_XP_RATE = ExperienceConfig.getInstance() + .getExperienceGainsGlobalMultiplier(); @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull 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; } @@ -41,16 +42,19 @@ public class XprateCommand implements TabExecutor { NotificationManager.broadcastTitle(mcMMO.p.getServer(), LocaleLoader.getString("Commands.Event.Stop"), LocaleLoader.getString("Commands.Event.Stop.Subtitle"), - 10, 10*20, 20); + 10, 10 * 20, 20); } if (mcMMO.p.getGeneralConfig().broadcastEventMessages()) { - mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.Stop")); - mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.Stop.Subtitle")); + mcMMO.p.getServer() + .broadcastMessage(LocaleLoader.getString("Commands.Event.Stop")); + mcMMO.p.getServer().broadcastMessage( + LocaleLoader.getString("Commands.Event.Stop.Subtitle")); } //Admin notification - NotificationManager.processSensitiveCommandNotification(sender, SensitiveCommandType.XPRATE_END); + NotificationManager.processSensitiveCommandNotification(sender, + SensitiveCommandType.XPRATE_END); mcMMO.p.toggleXpEventEnabled(); } @@ -79,7 +83,8 @@ public class XprateCommand implements TabExecutor { int newXpRate = Integer.parseInt(args[0]); if (newXpRate < 0) { - sender.sendMessage(ChatColor.RED+LocaleLoader.getString("Commands.NegativeNumberWarn")); + sender.sendMessage( + ChatColor.RED + LocaleLoader.getString("Commands.NegativeNumberWarn")); return true; } @@ -89,16 +94,19 @@ public class XprateCommand implements TabExecutor { NotificationManager.broadcastTitle(mcMMO.p.getServer(), LocaleLoader.getString("Commands.Event.Start"), LocaleLoader.getString("Commands.Event.XP", newXpRate), - 10, 10*20, 20); + 10, 10 * 20, 20); } if (mcMMO.p.getGeneralConfig().broadcastEventMessages()) { - mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.Start")); - mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.XP", newXpRate)); + mcMMO.p.getServer() + .broadcastMessage(LocaleLoader.getString("Commands.Event.Start")); + mcMMO.p.getServer().broadcastMessage( + LocaleLoader.getString("Commands.Event.XP", newXpRate)); } //Admin notification - NotificationManager.processSensitiveCommandNotification(sender, SensitiveCommandType.XPRATE_MODIFY, String.valueOf(newXpRate)); + NotificationManager.processSensitiveCommandNotification(sender, + SensitiveCommandType.XPRATE_MODIFY, String.valueOf(newXpRate)); return true; @@ -108,16 +116,19 @@ public class XprateCommand implements TabExecutor { } @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, String[] args) { switch (args.length) { case 1: if (StringUtils.isInt(args[0])) { return ImmutableList.of(); } - return StringUtil.copyPartialMatches(args[0], CommandUtils.RESET_OPTIONS, new ArrayList<>(CommandUtils.RESET_OPTIONS.size())); + return StringUtil.copyPartialMatches(args[0], CommandUtils.RESET_OPTIONS, + new ArrayList<>(CommandUtils.RESET_OPTIONS.size())); case 2: - return StringUtil.copyPartialMatches(args[1], CommandUtils.TRUE_FALSE_OPTIONS, new ArrayList<>(CommandUtils.TRUE_FALSE_OPTIONS.size())); + return StringUtil.copyPartialMatches(args[1], CommandUtils.TRUE_FALSE_OPTIONS, + new ArrayList<>(CommandUtils.TRUE_FALSE_OPTIONS.size())); default: return ImmutableList.of(); } diff --git a/src/main/java/com/gmail/nossr50/commands/admin/CompatibilityCommand.java b/src/main/java/com/gmail/nossr50/commands/admin/CompatibilityCommand.java index 89a0f1061..9f153859c 100644 --- a/src/main/java/com/gmail/nossr50/commands/admin/CompatibilityCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/admin/CompatibilityCommand.java @@ -11,8 +11,8 @@ public class CompatibilityCommand implements CommandExecutor { /** * Executes the given command, returning its success. *
- * If false is returned, then the "usage" plugin.yml entry for this command - * (if defined) will be sent to the player. + * If false is returned, then the "usage" plugin.yml entry for this command (if defined) will be + * sent to the player. * * @param commandSender Source of the command * @param command Command which was executed @@ -21,7 +21,9 @@ public class CompatibilityCommand implements CommandExecutor { * @return true if a valid command, otherwise false */ @Override - public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String s, @NotNull String[] strings) { + public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, + @NotNull String s, + @NotNull String[] strings) { mcMMO.getCompatibilityManager().reportCompatibilityStatus(commandSender); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/admin/DropTreasureCommand.java b/src/main/java/com/gmail/nossr50/commands/admin/DropTreasureCommand.java deleted file mode 100644 index e793a60f8..000000000 --- a/src/main/java/com/gmail/nossr50/commands/admin/DropTreasureCommand.java +++ /dev/null @@ -1,57 +0,0 @@ -//package com.gmail.nossr50.commands.admin; -// -//import com.gmail.nossr50.config.treasure.FishingTreasureConfig; -//import com.gmail.nossr50.datatypes.player.McMMOPlayer; -//import com.gmail.nossr50.datatypes.treasure.FishingTreasure; -//import com.gmail.nossr50.datatypes.treasure.Rarity; -//import com.gmail.nossr50.mcMMO; -//import com.gmail.nossr50.skills.fishing.FishingManager; -//import com.gmail.nossr50.util.player.UserManager; -//import org.bukkit.Location; -//import org.bukkit.command.Command; -//import org.bukkit.command.CommandExecutor; -//import org.bukkit.command.CommandSender; -//import org.bukkit.entity.Player; -//import org.jetbrains.annotations.NotNull; -// -//public class DropTreasureCommand implements CommandExecutor { -// @Override -// public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { -// if (sender instanceof Player) { -// if (!sender.isOp()) { -// sender.sendMessage("This command is for Operators only"); -// return false; -// } -// -// Player player = (Player) sender; -// Location location = player.getLocation(); -// McMMOPlayer mmoPlayer = UserManager.getPlayer(player); -// -// if (mmoPlayer == null) { -// //TODO: Localize -// player.sendMessage("Your player data is not loaded yet"); -// return false; -// } -// -// if (args.length == 0) { -// mcMMO.p.getLogger().info(player.toString() +" is dropping all mcMMO treasures via admin command at location "+location.toString()); -// for(Rarity rarity : FishingTreasureConfig.getInstance().fishingRewards.keySet()) { -// for(FishingTreasure fishingTreasure : FishingTreasureConfig.getInstance().fishingRewards.get(rarity)) { -// FishingManager fishingManager = mmoPlayer.getFishingManager(); -// } -// } -// //TODO: impl -// } else { -// String targetTreasure = args[1]; -// -// //Drop all treasures matching the name -// //TODO: impl -// } -// -// return true; -// } else { -// sender.sendMessage("No console support for this command"); -// return false; -// } -// } -//} diff --git a/src/main/java/com/gmail/nossr50/commands/admin/McmmoReloadLocaleCommand.java b/src/main/java/com/gmail/nossr50/commands/admin/McmmoReloadLocaleCommand.java index b5a5e22a8..20fb60674 100644 --- a/src/main/java/com/gmail/nossr50/commands/admin/McmmoReloadLocaleCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/admin/McmmoReloadLocaleCommand.java @@ -12,7 +12,9 @@ import org.jetbrains.annotations.NotNull; */ public final class McmmoReloadLocaleCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, + String[] args) { if (args.length == 0) { if (!Permissions.reloadlocale(sender)) { sender.sendMessage(command.getPermissionMessage()); diff --git a/src/main/java/com/gmail/nossr50/commands/admin/PlayerDebugCommand.java b/src/main/java/com/gmail/nossr50/commands/admin/PlayerDebugCommand.java index 767d544f6..5f6c3b63c 100644 --- a/src/main/java/com/gmail/nossr50/commands/admin/PlayerDebugCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/admin/PlayerDebugCommand.java @@ -12,11 +12,14 @@ import org.jetbrains.annotations.NotNull; public class PlayerDebugCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, + String[] args) { if (sender instanceof Player) { - McMMOPlayer mcMMOPlayer = UserManager.getPlayer((Player) sender); - mcMMOPlayer.toggleDebugMode(); //Toggle debug mode - NotificationManager.sendPlayerInformationChatOnlyPrefixed(mcMMOPlayer.getPlayer(), "Commands.Mmodebug.Toggle", String.valueOf(mcMMOPlayer.isDebugMode())); + final McMMOPlayer mmoPlayer = UserManager.getPlayer((Player) sender); + mmoPlayer.toggleDebugMode(); //Toggle debug mode + NotificationManager.sendPlayerInformationChatOnlyPrefixed(mmoPlayer.getPlayer(), + "Commands.Mmodebug.Toggle", String.valueOf(mmoPlayer.isDebugMode())); return true; } else { return false; diff --git a/src/main/java/com/gmail/nossr50/commands/chat/AdminChatCommand.java b/src/main/java/com/gmail/nossr50/commands/chat/AdminChatCommand.java index 2e71b238d..3feeeacad 100644 --- a/src/main/java/com/gmail/nossr50/commands/chat/AdminChatCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/chat/AdminChatCommand.java @@ -22,24 +22,29 @@ public class AdminChatCommand extends BaseCommand { this.pluginRef = pluginRef; } - @Default @Conditions(CommandManager.ADMIN_CONDITION) + @Default + @Conditions(CommandManager.ADMIN_CONDITION) public void processCommand(String[] args) { - BukkitCommandIssuer bukkitCommandIssuer = (BukkitCommandIssuer) getCurrentCommandIssuer(); + final BukkitCommandIssuer bukkitCommandIssuer = (BukkitCommandIssuer) getCurrentCommandIssuer(); if (args == null || args.length == 0) { //Process with no arguments if (bukkitCommandIssuer.isPlayer()) { - McMMOPlayer mmoPlayer = UserManager.getPlayer(bukkitCommandIssuer.getPlayer()); + final McMMOPlayer mmoPlayer = UserManager.getPlayer( + bukkitCommandIssuer.getPlayer()); pluginRef.getChatManager().setOrToggleChatChannel(mmoPlayer, ChatChannel.ADMIN); } else { //Not support for console - mcMMO.p.getLogger().info("You cannot switch chat channels as console, please provide full arguments."); + mcMMO.p.getLogger() + .info("You cannot switch chat channels as console, please provide full arguments."); } } else { if (bukkitCommandIssuer.isPlayer()) { - McMMOPlayer mmoPlayer = UserManager.getPlayer(bukkitCommandIssuer.getPlayer()); + final McMMOPlayer mmoPlayer = UserManager.getPlayer( + bukkitCommandIssuer.getPlayer()); - if (mmoPlayer == null) + if (mmoPlayer == null) { return; + } //Message contains the original command so it needs to be passed to this method to trim it pluginRef.getChatManager().processPlayerMessage(mmoPlayer, args, ChatChannel.ADMIN); diff --git a/src/main/java/com/gmail/nossr50/commands/chat/McChatSpy.java b/src/main/java/com/gmail/nossr50/commands/chat/McChatSpy.java index 87ef2285f..f6e861707 100644 --- a/src/main/java/com/gmail/nossr50/commands/chat/McChatSpy.java +++ b/src/main/java/com/gmail/nossr50/commands/chat/McChatSpy.java @@ -18,9 +18,11 @@ public class McChatSpy extends ToggleCommand { } @Override - protected void applyCommandAction(McMMOPlayer mcMMOPlayer) { - mcMMOPlayer.getPlayer().sendMessage(LocaleLoader.getString("Commands.AdminChatSpy." + (mcMMOPlayer.isPartyChatSpying() ? "Disabled" : "Enabled"))); - mcMMOPlayer.togglePartyChatSpying(); + protected void applyCommandAction(McMMOPlayer mmoPlayer) { + mmoPlayer.getPlayer().sendMessage(LocaleLoader.getString( + "Commands.AdminChatSpy." + (mmoPlayer.isPartyChatSpying() ? "Disabled" + : "Enabled"))); + mmoPlayer.togglePartyChatSpying(); } @Override 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 369b4a58b..4e174b114 100644 --- a/src/main/java/com/gmail/nossr50/commands/chat/PartyChatCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/chat/PartyChatCommand.java @@ -33,11 +33,13 @@ public class PartyChatCommand extends BaseCommand { if (args == null || args.length == 0) { //Process with no arguments if (bukkitCommandIssuer.isPlayer()) { - McMMOPlayer mmoPlayer = UserManager.getPlayer(bukkitCommandIssuer.getPlayer()); + final McMMOPlayer mmoPlayer = UserManager.getPlayer( + bukkitCommandIssuer.getPlayer()); pluginRef.getChatManager().setOrToggleChatChannel(mmoPlayer, ChatChannel.PARTY); } else { //Not support for console - mcMMO.p.getLogger().info("You cannot switch chat channels as console, please provide full arguments."); + mcMMO.p.getLogger() + .info("You cannot switch chat channels as console, please provide full arguments."); } } else { //Here we split the logic, consoles need to target a party name and players do not @@ -46,11 +48,12 @@ public class PartyChatCommand extends BaseCommand { * Player Logic */ if (bukkitCommandIssuer.getIssuer() instanceof Player) { - McMMOPlayer mmoPlayer = UserManager.getPlayer(bukkitCommandIssuer.getPlayer()); + final McMMOPlayer mmoPlayer = UserManager.getPlayer( + bukkitCommandIssuer.getPlayer()); processCommandArgsPlayer(mmoPlayer, args); - /* - * Console Logic - */ + /* + * Console Logic + */ } else { processCommandArgsConsole(args); } @@ -59,6 +62,7 @@ public class PartyChatCommand extends BaseCommand { /** * Processes the command with arguments for a {@link McMMOPlayer} + * * @param mmoPlayer target player * @param args command arguments */ @@ -68,19 +72,24 @@ public class PartyChatCommand extends BaseCommand { } /** - * Processes the command with arguments for a {@link com.gmail.nossr50.chat.author.ConsoleAuthor} + * Processes the command with arguments for a + * {@link com.gmail.nossr50.chat.author.ConsoleAuthor} + * * @param args command arguments */ private void processCommandArgsConsole(@NotNull String[] args) { if (args.length <= 1) { //Only specific a party and not the message - mcMMO.p.getLogger().severe("You need to specify a party name and then write a message afterwards."); + mcMMO.p.getLogger() + .severe("You need to specify a party name and then write a message afterwards."); } else { //Grab party Party targetParty = mcMMO.p.getPartyManager().getParty(args[0]); if (targetParty != null) { - pluginRef.getChatManager().processConsoleMessage(StringUtils.buildStringAfterNthElement(args, 1), targetParty); + pluginRef.getChatManager() + .processConsoleMessage(StringUtils.buildStringAfterNthElement(args, 1), + targetParty); } else { mcMMO.p.getLogger().severe("A party with that name doesn't exist!"); } 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 0c69d9f27..e2027bc56 100644 --- a/src/main/java/com/gmail/nossr50/commands/database/ConvertDatabaseCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/database/ConvertDatabaseCommand.java @@ -17,17 +17,25 @@ import org.jetbrains.annotations.NotNull; public class ConvertDatabaseCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, + String[] args) { if (args.length == 2) { DatabaseType previousType = DatabaseType.getDatabaseType(args[1]); DatabaseType newType = mcMMO.getDatabaseManager().getDatabaseType(); - if (previousType == newType || (newType == DatabaseType.CUSTOM && DatabaseManagerFactory.getCustomDatabaseManagerClass().getSimpleName().equalsIgnoreCase(args[1]))) { - sender.sendMessage(LocaleLoader.getString("Commands.mcconvert.Database.Same", newType.toString())); + if (previousType == newType || (newType == DatabaseType.CUSTOM + && DatabaseManagerFactory.getCustomDatabaseManagerClass() + .getSimpleName() + .equalsIgnoreCase(args[1]))) { + sender.sendMessage(LocaleLoader.getString("Commands.mcconvert.Database.Same", + newType.toString())); return true; } - DatabaseManager oldDatabase = DatabaseManagerFactory.createDatabaseManager(previousType, mcMMO.getUsersFilePath(), mcMMO.p.getLogger(), mcMMO.p.getPurgeTime(), mcMMO.p.getAdvancedConfig().getStartingLevel()); + DatabaseManager oldDatabase = DatabaseManagerFactory.createDatabaseManager(previousType, + mcMMO.getUsersFilePath(), mcMMO.p.getLogger(), mcMMO.p.getPurgeTime(), + mcMMO.p.getAdvancedConfig().getStartingLevel()); if (oldDatabase == null) { sender.sendMessage("Unable to load the old database! Check your log for errors."); return true; @@ -40,19 +48,26 @@ public class ConvertDatabaseCommand implements CommandExecutor { clazz = Class.forName(args[1]); if (!DatabaseManager.class.isAssignableFrom(clazz)) { - sender.sendMessage(LocaleLoader.getString("Commands.mcconvert.Database.InvalidType", args[1])); + sender.sendMessage( + LocaleLoader.getString("Commands.mcconvert.Database.InvalidType", + args[1])); return true; } - oldDatabase = DatabaseManagerFactory.createCustomDatabaseManager((Class) clazz); + oldDatabase = DatabaseManagerFactory.createCustomDatabaseManager( + (Class) clazz); } catch (Throwable e) { e.printStackTrace(); - sender.sendMessage(LocaleLoader.getString("Commands.mcconvert.Database.InvalidType", args[1])); + sender.sendMessage( + LocaleLoader.getString("Commands.mcconvert.Database.InvalidType", + args[1])); return true; } } - sender.sendMessage(LocaleLoader.getString("Commands.mcconvert.Database.Start", previousType.toString(), newType.toString())); + sender.sendMessage(LocaleLoader.getString("Commands.mcconvert.Database.Start", + previousType.toString(), + newType.toString())); UserManager.saveAll(); UserManager.clearAll(); @@ -64,10 +79,14 @@ public class ConvertDatabaseCommand implements CommandExecutor { mcMMO.getDatabaseManager().saveUser(profile); } - mcMMO.p.getFoliaLib().getScheduler().runLaterAsync(new PlayerProfileLoadingTask(player), 1); // 1 Tick delay to ensure the player is marked as online before we begin loading + mcMMO.p.getFoliaLib().getScheduler() + .runLaterAsync(new PlayerProfileLoadingTask(player), + 1); // 1 Tick delay to ensure the player is marked as online before we begin loading } - mcMMO.p.getFoliaLib().getScheduler().runAsync(new DatabaseConversionTask(oldDatabase, sender, previousType.toString(), newType.toString())); + mcMMO.p.getFoliaLib().getScheduler().runAsync( + new DatabaseConversionTask(oldDatabase, sender, previousType.toString(), + newType.toString())); return true; } return false; diff --git a/src/main/java/com/gmail/nossr50/commands/database/McpurgeCommand.java b/src/main/java/com/gmail/nossr50/commands/database/McpurgeCommand.java index 6f192510f..366ed0c1b 100644 --- a/src/main/java/com/gmail/nossr50/commands/database/McpurgeCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/database/McpurgeCommand.java @@ -3,16 +3,16 @@ package com.gmail.nossr50.commands.database; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; import com.google.common.collect.ImmutableList; +import java.util.List; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabExecutor; import org.jetbrains.annotations.NotNull; -import java.util.List; - public class McpurgeCommand implements TabExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (args.length == 0) { mcMMO.getDatabaseManager().purgePowerlessUsers(); @@ -27,7 +27,8 @@ public class McpurgeCommand implements TabExecutor { } @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, String[] args) { return ImmutableList.of(); } } 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 56b817337..c81e88bc9 100644 --- a/src/main/java/com/gmail/nossr50/commands/database/McremoveCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/database/McremoveCommand.java @@ -5,6 +5,9 @@ import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.player.UserManager; import com.google.common.collect.ImmutableList; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; @@ -12,17 +15,15 @@ import org.bukkit.command.TabExecutor; import org.bukkit.util.StringUtil; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - public class McremoveCommand implements TabExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (args.length == 1) { String playerName = CommandUtils.getMatchedPlayerName(args[0]); - if (UserManager.getOfflinePlayer(playerName) == null && CommandUtils.unloadedProfile(sender, mcMMO.getDatabaseManager().loadPlayerProfile(playerName))) { + if (UserManager.getOfflinePlayer(playerName) == null && CommandUtils.unloadedProfile( + sender, mcMMO.getDatabaseManager().loadPlayerProfile(playerName))) { return true; } @@ -35,7 +36,8 @@ public class McremoveCommand implements TabExecutor { if (mcMMO.getDatabaseManager().removeUser(playerName, uuid)) { sender.sendMessage(LocaleLoader.getString("Commands.mcremove.Success", playerName)); } else { - sender.sendMessage(playerName + " could not be removed from the database."); // Pretty sure this should NEVER happen. + sender.sendMessage(playerName + + " could not be removed from the database."); // Pretty sure this should NEVER happen. } return true; @@ -44,10 +46,12 @@ public class McremoveCommand implements TabExecutor { } @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, String[] args) { if (args.length == 1) { List playerNames = CommandUtils.getOnlinePlayerNames(sender); - return StringUtil.copyPartialMatches(args[0], playerNames, new ArrayList<>(playerNames.size())); + return StringUtil.copyPartialMatches(args[0], playerNames, + new ArrayList<>(playerNames.size())); } return ImmutableList.of(); } diff --git a/src/main/java/com/gmail/nossr50/commands/database/MmoshowdbCommand.java b/src/main/java/com/gmail/nossr50/commands/database/MmoshowdbCommand.java index bcb07312d..f314b89f8 100644 --- a/src/main/java/com/gmail/nossr50/commands/database/MmoshowdbCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/database/MmoshowdbCommand.java @@ -4,16 +4,16 @@ import com.gmail.nossr50.database.DatabaseManagerFactory; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; import com.google.common.collect.ImmutableList; +import java.util.List; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabExecutor; import org.jetbrains.annotations.NotNull; -import java.util.List; - public class MmoshowdbCommand implements TabExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (args.length == 0) { Class clazz = DatabaseManagerFactory.getCustomDatabaseManagerClass(); @@ -22,14 +22,16 @@ public class MmoshowdbCommand implements TabExecutor { return true; } - sender.sendMessage(LocaleLoader.getString("Commands.mmoshowdb", (mcMMO.p.getGeneralConfig().getUseMySQL() ? "sql" : "flatfile"))); + sender.sendMessage(LocaleLoader.getString("Commands.mmoshowdb", + (mcMMO.p.getGeneralConfig().getUseMySQL() ? "sql" : "flatfile"))); return true; } return false; } @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, String[] args) { return ImmutableList.of(); } } diff --git a/src/main/java/com/gmail/nossr50/commands/experience/AddlevelsCommand.java b/src/main/java/com/gmail/nossr50/commands/experience/AddlevelsCommand.java index b9fb64d25..bfa855e85 100644 --- a/src/main/java/com/gmail/nossr50/commands/experience/AddlevelsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/experience/AddlevelsCommand.java @@ -24,7 +24,8 @@ public class AddlevelsCommand extends ExperienceCommand { } @Override - protected void handleCommand(Player player, PlayerProfile profile, PrimarySkillType skill, int value) { + protected void handleCommand(Player player, PlayerProfile profile, PrimarySkillType skill, + int value) { float xpRemoved = profile.getSkillXpLevelRaw(skill); profile.addLevels(skill, value); @@ -33,29 +34,35 @@ public class AddlevelsCommand extends ExperienceCommand { return; } - McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); if (mmoPlayer == null) { - EventUtils.tryLevelChangeEvent(player, skill, value, xpRemoved, true, XPGainReason.COMMAND); + EventUtils.tryLevelChangeEvent(player, skill, value, xpRemoved, true, + XPGainReason.COMMAND); } else { - EventUtils.tryLevelChangeEvent(mmoPlayer, skill, value, xpRemoved, true, XPGainReason.COMMAND); + EventUtils.tryLevelChangeEvent(mmoPlayer, skill, value, xpRemoved, true, + XPGainReason.COMMAND); } } @Override protected void handlePlayerMessageAll(Player player, int value, boolean isSilent) { - if (isSilent) + if (isSilent) { return; + } player.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.1", value)); } @Override - protected void handlePlayerMessageSkill(Player player, int value, PrimarySkillType skill, boolean isSilent) { - if (isSilent) + protected void handlePlayerMessageSkill(Player player, int value, PrimarySkillType skill, + boolean isSilent) { + if (isSilent) { return; + } - player.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.1", value, mcMMO.p.getSkillTools().getLocalizedSkillName(skill))); + player.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.1", value, + mcMMO.p.getSkillTools().getLocalizedSkillName(skill))); } } 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 953ad7436..d5583a1e1 100644 --- a/src/main/java/com/gmail/nossr50/commands/experience/AddxpCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/experience/AddxpCommand.java @@ -23,13 +23,16 @@ public class AddxpCommand extends ExperienceCommand { } @Override - protected void handleCommand(Player player, PlayerProfile profile, PrimarySkillType skill, int value) { + 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); + UserManager.getPlayer(player) + .applyXpGain(skill, value, XPGainReason.COMMAND, XPGainSource.COMMAND); } else { profile.addXp(skill, value); profile.scheduleAsyncSave(); @@ -38,17 +41,21 @@ public class AddxpCommand extends ExperienceCommand { @Override protected void handlePlayerMessageAll(Player player, int value, boolean isSilent) { - if (isSilent) + if (isSilent) { return; + } player.sendMessage(LocaleLoader.getString("Commands.addxp.AwardAll", value)); } @Override - protected void handlePlayerMessageSkill(Player player, int value, PrimarySkillType skill, boolean isSilent) { - if (isSilent) + protected void handlePlayerMessageSkill(Player player, int value, PrimarySkillType skill, + boolean isSilent) { + if (isSilent) { return; + } - player.sendMessage(LocaleLoader.getString("Commands.addxp.AwardSkill", value, mcMMO.p.getSkillTools().getLocalizedSkillName(skill))); + player.sendMessage(LocaleLoader.getString("Commands.addxp.AwardSkill", value, + mcMMO.p.getSkillTools().getLocalizedSkillName(skill))); } } diff --git a/src/main/java/com/gmail/nossr50/commands/experience/ConvertExperienceCommand.java b/src/main/java/com/gmail/nossr50/commands/experience/ConvertExperienceCommand.java index ee9c90998..361f9fe0f 100644 --- a/src/main/java/com/gmail/nossr50/commands/experience/ConvertExperienceCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/experience/ConvertExperienceCommand.java @@ -6,17 +6,17 @@ import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.runnables.database.FormulaConversionTask; import com.gmail.nossr50.runnables.player.PlayerProfileLoadingTask; import com.gmail.nossr50.util.player.UserManager; +import java.util.Locale; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.Locale; - public class ConvertExperienceCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (args.length == 2) { FormulaType previousType = mcMMO.getFormulaManager().getPreviousFormulaType(); FormulaType newType = FormulaType.getFormulaType(args[1].toUpperCase(Locale.ENGLISH)); @@ -27,19 +27,24 @@ public class ConvertExperienceCommand implements CommandExecutor { } if (previousType == newType) { - sender.sendMessage(LocaleLoader.getString("Commands.mcconvert.Experience.Same", newType.toString())); + sender.sendMessage(LocaleLoader.getString("Commands.mcconvert.Experience.Same", + newType.toString())); return true; } - sender.sendMessage(LocaleLoader.getString("Commands.mcconvert.Experience.Start", previousType.toString(), newType.toString())); + sender.sendMessage(LocaleLoader.getString("Commands.mcconvert.Experience.Start", + previousType.toString(), newType.toString())); UserManager.saveAll(); UserManager.clearAll(); - mcMMO.p.getFoliaLib().getScheduler().runLater(new FormulaConversionTask(sender, newType), 1); + mcMMO.p.getFoliaLib().getScheduler() + .runLater(new FormulaConversionTask(sender, newType), 1); for (Player player : mcMMO.p.getServer().getOnlinePlayers()) { - mcMMO.p.getFoliaLib().getScheduler().runLaterAsync(new PlayerProfileLoadingTask(player), 1); // 1 Tick delay to ensure the player is marked as online before we begin loading + mcMMO.p.getFoliaLib().getScheduler() + .runLaterAsync(new PlayerProfileLoadingTask(player), + 1); // 1 Tick delay to ensure the player is marked as online before we begin loading } return true; 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 37e1d6c17..8d65254a5 100644 --- a/src/main/java/com/gmail/nossr50/commands/experience/ExperienceCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/experience/ExperienceCommand.java @@ -9,6 +9,8 @@ import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.SkillTools; import com.google.common.collect.ImmutableList; +import java.util.ArrayList; +import java.util.List; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabExecutor; @@ -16,12 +18,10 @@ import org.bukkit.entity.Player; import org.bukkit.util.StringUtil; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.List; - public abstract class ExperienceCommand implements TabExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { PrimarySkillType skill; if (args.length < 2) { @@ -33,8 +33,9 @@ public abstract class ExperienceCommand implements TabExecutor { } if (!permissionsCheckSelf(sender)) { - if (command.getPermissionMessage() != null) + if (command.getPermissionMessage() != null) { sender.sendMessage(command.getPermissionMessage()); + } sender.sendMessage("(mcMMO) No permission!"); return true; } @@ -60,8 +61,8 @@ public abstract class ExperienceCommand implements TabExecutor { return true; } - - editValues((Player) sender, UserManager.getPlayer(sender.getName()).getProfile(), skill, Integer.parseInt(args[1]), isSilent(args)); + editValues((Player) sender, UserManager.getPlayer(sender.getName()).getProfile(), + skill, Integer.parseInt(args[1]), isSilent(args)); return true; } else if ((args.length == 3 && !isSilent(args)) || (args.length == 4 && isSilent(args))) { @@ -88,10 +89,10 @@ public abstract class ExperienceCommand implements TabExecutor { int value = Integer.parseInt(args[2]); String playerName = CommandUtils.getMatchedPlayerName(args[0]); - McMMOPlayer mcMMOPlayer = UserManager.getOfflinePlayer(playerName); + final McMMOPlayer mmoPlayer = UserManager.getOfflinePlayer(playerName); - // If the mcMMOPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process. - if (mcMMOPlayer == null) { + // If the mmoPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process. + if (mmoPlayer == null) { PlayerProfile profile; profile = mcMMO.getDatabaseManager().loadPlayerProfile(playerName); @@ -108,7 +109,8 @@ public abstract class ExperienceCommand implements TabExecutor { editValues(null, profile, skill, value, isSilent(args)); } else { - editValues(mcMMOPlayer.getPlayer(), mcMMOPlayer.getProfile(), skill, value, isSilent(args)); + editValues(mmoPlayer.getPlayer(), mmoPlayer.getProfile(), skill, value, + isSilent(args)); } handleSenderMessage(sender, playerName, skill); @@ -122,45 +124,60 @@ public abstract class ExperienceCommand implements TabExecutor { private boolean isSilent(String[] args) { int length = args.length; - if (length == 0) + if (length == 0) { return false; + } - return args[length-1].equalsIgnoreCase("-s"); + return args[length - 1].equalsIgnoreCase("-s"); } @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, String[] args) { switch (args.length) { case 1: List playerNames = CommandUtils.getOnlinePlayerNames(sender); - return StringUtil.copyPartialMatches(args[0], playerNames, new ArrayList<>(playerNames.size())); + return StringUtil.copyPartialMatches(args[0], playerNames, + new ArrayList<>(playerNames.size())); case 2: - return StringUtil.copyPartialMatches(args[1], mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES, new ArrayList<>(mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES.size())); + return StringUtil.copyPartialMatches(args[1], + mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES, + new ArrayList<>(mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES.size())); default: return ImmutableList.of(); } } 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 handleCommand(Player player, PlayerProfile profile, + PrimarySkillType skill, int value); + protected abstract void handlePlayerMessageAll(Player player, int value, boolean isSilent); - protected abstract void handlePlayerMessageSkill(Player player, int value, PrimarySkillType skill, boolean isSilent); + + protected abstract void handlePlayerMessageSkill(Player player, int value, + PrimarySkillType skill, boolean isSilent); private boolean validateArguments(CommandSender sender, String skillName, String value) { - return !(CommandUtils.isInvalidInteger(sender, value) || (!skillName.equalsIgnoreCase("all") && CommandUtils.isInvalidSkill(sender, skillName))); + return !(CommandUtils.isInvalidInteger(sender, value) || (!skillName.equalsIgnoreCase("all") + && CommandUtils.isInvalidSkill(sender, skillName))); } - protected static void handleSenderMessage(CommandSender sender, String playerName, PrimarySkillType skill) { + 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", mcMMO.p.getSkillTools().getLocalizedSkillName(skill), playerName)); + sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.2", + mcMMO.p.getSkillTools().getLocalizedSkillName(skill), playerName)); } } - protected void editValues(Player player, PlayerProfile profile, PrimarySkillType skill, int value, boolean isSilent) { + protected void editValues(Player player, PlayerProfile profile, PrimarySkillType skill, + int value, boolean isSilent) { if (skill == null) { for (PrimarySkillType primarySkillType : SkillTools.NON_CHILD_SKILLS) { handleCommand(player, profile, primarySkillType, value); diff --git a/src/main/java/com/gmail/nossr50/commands/experience/MmoeditCommand.java b/src/main/java/com/gmail/nossr50/commands/experience/MmoeditCommand.java index 737d7f40a..954e83edd 100644 --- a/src/main/java/com/gmail/nossr50/commands/experience/MmoeditCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/experience/MmoeditCommand.java @@ -24,7 +24,8 @@ public class MmoeditCommand extends ExperienceCommand { } @Override - protected void handleCommand(Player player, PlayerProfile profile, PrimarySkillType skill, int value) { + protected void handleCommand(Player player, PlayerProfile profile, PrimarySkillType skill, + int value) { int skillLevel = profile.getSkillLevel(skill); float xpRemoved = profile.getSkillXpLevelRaw(skill); @@ -39,29 +40,35 @@ public class MmoeditCommand extends ExperienceCommand { return; } - McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); if (mmoPlayer != null) { - EventUtils.tryLevelEditEvent(mmoPlayer, skill, value, xpRemoved, value > skillLevel, XPGainReason.COMMAND, skillLevel); + EventUtils.tryLevelEditEvent(mmoPlayer, skill, value, xpRemoved, value > skillLevel, + XPGainReason.COMMAND, skillLevel); } else { - EventUtils.tryLevelEditEvent(player, skill, value, xpRemoved, value > skillLevel, XPGainReason.COMMAND, skillLevel); + EventUtils.tryLevelEditEvent(player, skill, value, xpRemoved, value > skillLevel, + XPGainReason.COMMAND, skillLevel); } } @Override protected void handlePlayerMessageAll(Player player, int value, boolean isSilent) { - if (isSilent) + if (isSilent) { return; + } player.sendMessage(LocaleLoader.getString("Commands.mmoedit.AllSkills.1", value)); } @Override - protected void handlePlayerMessageSkill(Player player, int value, PrimarySkillType skill, boolean isSilent) { - if (isSilent) + protected void handlePlayerMessageSkill(Player player, int value, PrimarySkillType skill, + boolean isSilent) { + if (isSilent) { return; + } - player.sendMessage(LocaleLoader.getString("Commands.mmoedit.Modified.1", mcMMO.p.getSkillTools().getLocalizedSkillName(skill), value)); + player.sendMessage(LocaleLoader.getString("Commands.mmoedit.Modified.1", + mcMMO.p.getSkillTools().getLocalizedSkillName(skill), value)); } } 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 e2fcd38ec..8364f7bfd 100644 --- a/src/main/java/com/gmail/nossr50/commands/experience/SkillresetCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/experience/SkillresetCommand.java @@ -12,6 +12,8 @@ import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.SkillTools; import com.google.common.collect.ImmutableList; +import java.util.ArrayList; +import java.util.List; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; @@ -20,16 +22,14 @@ import org.bukkit.entity.Player; import org.bukkit.util.StringUtil; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.List; - /** - * This class mirrors the structure of ExperienceCommand, except the - * value/quantity argument is removed. + * This class mirrors the structure of ExperienceCommand, except the value/quantity argument is + * removed. */ public class SkillresetCommand implements TabExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { PrimarySkillType skill; switch (args.length) { case 1: @@ -52,7 +52,8 @@ public class SkillresetCommand implements TabExecutor { skill = mcMMO.p.getSkillTools().matchSkill(args[0]); } - editValues((Player) sender, UserManager.getPlayer(sender.getName()).getProfile(), skill); + editValues((Player) sender, UserManager.getPlayer(sender.getName()).getProfile(), + skill); return true; case 2: @@ -72,12 +73,13 @@ public class SkillresetCommand implements TabExecutor { } String playerName = CommandUtils.getMatchedPlayerName(args[0]); - McMMOPlayer mcMMOPlayer = UserManager.getOfflinePlayer(playerName); + final McMMOPlayer mmoPlayer = UserManager.getOfflinePlayer(playerName); - // If the mcMMOPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process. - if (mcMMOPlayer == null) { + // If the mmoPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process. + if (mmoPlayer == null) { OfflinePlayer offlinePlayer = mcMMO.p.getServer().getOfflinePlayer(playerName); - PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(offlinePlayer); + PlayerProfile profile = mcMMO.getDatabaseManager() + .loadPlayerProfile(offlinePlayer); //Check loading by UUID if (CommandUtils.unloadedProfile(sender, profile)) { @@ -92,7 +94,7 @@ public class SkillresetCommand implements TabExecutor { editValues(null, profile, skill); } else { - editValues(mcMMOPlayer.getPlayer(), mcMMOPlayer.getProfile(), skill); + editValues(mmoPlayer.getPlayer(), mmoPlayer.getProfile(), skill); } handleSenderMessage(sender, playerName, skill); @@ -104,13 +106,17 @@ public class SkillresetCommand implements TabExecutor { } @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, String[] args) { switch (args.length) { case 1: List playerNames = CommandUtils.getOnlinePlayerNames(sender); - return StringUtil.copyPartialMatches(args[0], playerNames, new ArrayList<>(playerNames.size())); + return StringUtil.copyPartialMatches(args[0], playerNames, + new ArrayList<>(playerNames.size())); case 2: - return StringUtil.copyPartialMatches(args[1], mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES, new ArrayList<>(mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES.size())); + return StringUtil.copyPartialMatches(args[1], + mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES, + new ArrayList<>(mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES.size())); default: return ImmutableList.of(); } @@ -127,7 +133,8 @@ public class SkillresetCommand implements TabExecutor { return; } - EventUtils.tryLevelChangeEvent(player, skill, levelsRemoved, xpRemoved, false, XPGainReason.COMMAND); + EventUtils.tryLevelChangeEvent(player, skill, levelsRemoved, xpRemoved, false, + XPGainReason.COMMAND); } protected boolean permissionsCheckSelf(CommandSender sender) { @@ -143,18 +150,21 @@ public class SkillresetCommand implements TabExecutor { } protected void handlePlayerMessageSkill(Player player, PrimarySkillType skill) { - player.sendMessage(LocaleLoader.getString("Commands.Reset.Single", mcMMO.p.getSkillTools().getLocalizedSkillName(skill))); + player.sendMessage(LocaleLoader.getString("Commands.Reset.Single", + mcMMO.p.getSkillTools().getLocalizedSkillName(skill))); } private boolean validateArguments(CommandSender sender, String skillName) { return skillName.equalsIgnoreCase("all") || !CommandUtils.isInvalidSkill(sender, skillName); } - protected static void handleSenderMessage(CommandSender sender, String playerName, PrimarySkillType skill) { + 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", mcMMO.p.getSkillTools().getLocalizedSkillName(skill), playerName)); + sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.2", + mcMMO.p.getSkillTools().getLocalizedSkillName(skill), playerName)); } } 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 3b9d07f62..248a72c08 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyAcceptCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyAcceptCommand.java @@ -12,9 +12,10 @@ import org.jetbrains.annotations.NotNull; public class PartyAcceptCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (args.length == 1) { - Player player = (Player) sender; + final Player player = (Player) sender; //Check if player profile is loaded if (UserManager.getPlayer(player) == null) { @@ -22,20 +23,20 @@ public class PartyAcceptCommand implements CommandExecutor { return true; } - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - - if (!mcMMOPlayer.hasPartyInvite()) { + if (!mmoPlayer.hasPartyInvite()) { sender.sendMessage(LocaleLoader.getString("mcMMO.NoInvites")); return true; } // Changing parties - if (!mcMMO.p.getPartyManager().changeOrJoinParty(mcMMOPlayer, mcMMOPlayer.getPartyInvite().getName())) { + if (!mcMMO.p.getPartyManager() + .changeOrJoinParty(mmoPlayer, mmoPlayer.getPartyInvite().getName())) { return true; } - mcMMO.p.getPartyManager().joinInvitedParty(mcMMOPlayer); + mcMMO.p.getPartyManager().joinInvitedParty(mmoPlayer); return true; } sender.sendMessage(LocaleLoader.getString("Commands.Usage.1", "party", "accept")); 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 29b3d64d1..03a35b382 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyChangeOwnerCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyChangeOwnerCommand.java @@ -14,7 +14,8 @@ import org.jetbrains.annotations.NotNull; public class PartyChangeOwnerCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (args.length == 2) {//Check if player profile is loaded if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); @@ -33,7 +34,8 @@ public class PartyChangeOwnerCommand implements CommandExecutor { mcMMO.p.getPartyManager().setPartyLeader(target.getUniqueId(), playerParty); return true; } - sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "owner", "<" + LocaleLoader.getString("Commands.Usage.Player") + ">")); + sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "owner", + "<" + LocaleLoader.getString("Commands.Usage.Player") + ">")); 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 7ef2dc560..706342142 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyChangePasswordCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyChangePasswordCommand.java @@ -11,7 +11,8 @@ import org.jetbrains.annotations.NotNull; public class PartyChangePasswordCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; @@ -34,8 +35,10 @@ public class PartyChangePasswordCommand implements CommandExecutor { return true; default: - sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "password", "[clear|reset]")); - sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "password", "<" + LocaleLoader.getString("Commands.Usage.Password") + ">")); + sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "password", + "[clear|reset]")); + sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "password", + "<" + LocaleLoader.getString("Commands.Usage.Password") + ">")); 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 06691c171..27b1030e6 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyCommand.java @@ -9,6 +9,10 @@ import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.player.UserManager; import com.google.common.collect.ImmutableList; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; @@ -17,15 +21,11 @@ import org.bukkit.entity.Player; import org.bukkit.util.StringUtil; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - public class PartyCommand implements TabExecutor { private final List PARTY_SUBCOMMANDS; private final List XPSHARE_COMPLETIONS = ImmutableList.of("none", "equal"); - private final List ITEMSHARE_COMPLETIONS = ImmutableList.of("none", "equal", "random", "loot", "mining", "herbalism", "woodcutting", "misc"); + private final List ITEMSHARE_COMPLETIONS = ImmutableList.of("none", "equal", "random", + "loot", "mining", "herbalism", "woodcutting", "misc"); private final CommandExecutor partyJoinCommand; private final CommandExecutor partyAcceptCommand; private final CommandExecutor partyCreateCommand; @@ -43,24 +43,25 @@ public class PartyCommand implements TabExecutor { private final CommandExecutor partyHelpCommand; private final CommandExecutor partyTeleportCommand; private final CommandExecutor partyAllianceCommand; + public PartyCommand() { - partyJoinCommand = new PartyJoinCommand(); - partyAcceptCommand = new PartyAcceptCommand(); - partyCreateCommand = new PartyCreateCommand(); - partyQuitCommand = new PartyQuitCommand(); - partyXpShareCommand = new PartyXpShareCommand(); - partyItemShareCommand = new PartyItemShareCommand(); - partyInviteCommand = new PartyInviteCommand(); - partyKickCommand = new PartyKickCommand(); - partyDisbandCommand = new PartyDisbandCommand(); - partyChangeOwnerCommand = new PartyChangeOwnerCommand(); - partyLockCommand = new PartyLockCommand(); + partyJoinCommand = new PartyJoinCommand(); + partyAcceptCommand = new PartyAcceptCommand(); + partyCreateCommand = new PartyCreateCommand(); + partyQuitCommand = new PartyQuitCommand(); + partyXpShareCommand = new PartyXpShareCommand(); + partyItemShareCommand = new PartyItemShareCommand(); + partyInviteCommand = new PartyInviteCommand(); + partyKickCommand = new PartyKickCommand(); + partyDisbandCommand = new PartyDisbandCommand(); + partyChangeOwnerCommand = new PartyChangeOwnerCommand(); + partyLockCommand = new PartyLockCommand(); partyChangePasswordCommand = new PartyChangePasswordCommand(); - partyRenameCommand = new PartyRenameCommand(); - partyInfoCommand = new PartyInfoCommand(); - partyHelpCommand = new PartyHelpCommand(); - partyTeleportCommand = new PtpCommand(); - partyAllianceCommand = new PartyAllianceCommand(); + partyRenameCommand = new PartyRenameCommand(); + partyInfoCommand = new PartyInfoCommand(); + partyHelpCommand = new PartyHelpCommand(); + partyTeleportCommand = new PtpCommand(); + partyAllianceCommand = new PartyAllianceCommand(); ArrayList subcommands = new ArrayList<>(); @@ -73,7 +74,8 @@ public class PartyCommand implements TabExecutor { } @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (CommandUtils.noConsoleUsage(sender)) { return true; } @@ -83,21 +85,20 @@ public class PartyCommand implements TabExecutor { return true; } - Player player = (Player) sender; + final Player player = (Player) sender; if (!UserManager.hasPlayerDataKey(player)) { return true; } - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if (mcMMOPlayer == null) { + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + if (mmoPlayer == null) { player.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } - if (args.length < 1) { - if (!mcMMOPlayer.inParty()) { + if (!mmoPlayer.inParty()) { sender.sendMessage(LocaleLoader.getString("Commands.Party.None")); return printUsage(player); } @@ -112,7 +113,8 @@ public class PartyCommand implements TabExecutor { } // Can't use this for lock/unlock since they're handled by the same command - if (subcommand != PartySubcommandType.LOCK && subcommand != PartySubcommandType.UNLOCK && !Permissions.partySubcommand(sender, subcommand)) { + if (subcommand != PartySubcommandType.LOCK && subcommand != PartySubcommandType.UNLOCK + && !Permissions.partySubcommand(sender, subcommand)) { sender.sendMessage(command.getPermissionMessage()); return true; } @@ -131,7 +133,7 @@ public class PartyCommand implements TabExecutor { } // Party member commands - if (!mcMMOPlayer.inParty()) { + if (!mmoPlayer.inParty()) { sender.sendMessage(LocaleLoader.getString("Commands.Party.None")); return printUsage(player); } @@ -150,7 +152,7 @@ public class PartyCommand implements TabExecutor { } // Party leader commands - if (!mcMMOPlayer.getParty().getLeader().getUniqueId().equals(player.getUniqueId())) { + if (!mmoPlayer.getParty().getLeader().getUniqueId().equals(player.getUniqueId())) { sender.sendMessage(LocaleLoader.getString("Party.NotOwner")); return true; } @@ -170,10 +172,12 @@ public class PartyCommand implements TabExecutor { } @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, String[] args) { switch (args.length) { case 1: - return StringUtil.copyPartialMatches(args[0], PARTY_SUBCOMMANDS, new ArrayList<>(PARTY_SUBCOMMANDS.size())); + return StringUtil.copyPartialMatches(args[0], PARTY_SUBCOMMANDS, + new ArrayList<>(PARTY_SUBCOMMANDS.size())); case 2: PartySubcommandType subcommand = PartySubcommandType.getSubcommand(args[0]); @@ -188,36 +192,46 @@ public class PartyCommand implements TabExecutor { case INVITE: case KICK: case OWNER: - return StringUtil.copyPartialMatches(args[1], playerNames, new ArrayList<>(playerNames.size())); + return StringUtil.copyPartialMatches(args[1], playerNames, + new ArrayList<>(playerNames.size())); case XPSHARE: - return StringUtil.copyPartialMatches(args[1], XPSHARE_COMPLETIONS, new ArrayList<>(XPSHARE_COMPLETIONS.size())); + return StringUtil.copyPartialMatches(args[1], XPSHARE_COMPLETIONS, + new ArrayList<>(XPSHARE_COMPLETIONS.size())); case ITEMSHARE: - return StringUtil.copyPartialMatches(args[1], ITEMSHARE_COMPLETIONS, new ArrayList<>(ITEMSHARE_COMPLETIONS.size())); + return StringUtil.copyPartialMatches(args[1], ITEMSHARE_COMPLETIONS, + new ArrayList<>(ITEMSHARE_COMPLETIONS.size())); case LOCK: case CHAT: - return StringUtil.copyPartialMatches(args[1], CommandUtils.TRUE_FALSE_OPTIONS, new ArrayList<>(CommandUtils.TRUE_FALSE_OPTIONS.size())); + return StringUtil.copyPartialMatches(args[1], + CommandUtils.TRUE_FALSE_OPTIONS, + new ArrayList<>(CommandUtils.TRUE_FALSE_OPTIONS.size())); case PASSWORD: - return StringUtil.copyPartialMatches(args[1], CommandUtils.RESET_OPTIONS, new ArrayList<>(CommandUtils.RESET_OPTIONS.size())); + return StringUtil.copyPartialMatches(args[1], CommandUtils.RESET_OPTIONS, + new ArrayList<>(CommandUtils.RESET_OPTIONS.size())); case TELEPORT: - List matches = StringUtil.copyPartialMatches(args[1], PtpCommand.TELEPORT_SUBCOMMANDS, new ArrayList<>(PtpCommand.TELEPORT_SUBCOMMANDS.size())); + List matches = StringUtil.copyPartialMatches(args[1], + PtpCommand.TELEPORT_SUBCOMMANDS, + new ArrayList<>(PtpCommand.TELEPORT_SUBCOMMANDS.size())); if (matches.isEmpty()) { - Player player = (Player) sender; - final McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final Player player = (Player) sender; + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); //Not Loaded - if (mcMMOPlayer == null) { + if (mmoPlayer == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return ImmutableList.of(); } - if (mcMMOPlayer.getParty() == null) + if (mmoPlayer.getParty() == null) { return ImmutableList.of(); + } - final Party party = mcMMOPlayer.getParty(); + final Party party = mmoPlayer.getParty(); playerNames = party.getOnlinePlayerNames(player); - return StringUtil.copyPartialMatches(args[1], playerNames, new ArrayList<>(playerNames.size())); + return StringUtil.copyPartialMatches(args[1], playerNames, + new ArrayList<>(playerNames.size())); } return matches; @@ -225,8 +239,10 @@ public class PartyCommand implements TabExecutor { return ImmutableList.of(); } case 3: - if (PartySubcommandType.getSubcommand(args[0]) == PartySubcommandType.ITEMSHARE && isItemShareCategory(args[1])) { - return StringUtil.copyPartialMatches(args[2], CommandUtils.TRUE_FALSE_OPTIONS, new ArrayList<>(CommandUtils.TRUE_FALSE_OPTIONS.size())); + if (PartySubcommandType.getSubcommand(args[0]) == PartySubcommandType.ITEMSHARE + && isItemShareCategory(args[1])) { + return StringUtil.copyPartialMatches(args[2], CommandUtils.TRUE_FALSE_OPTIONS, + new ArrayList<>(CommandUtils.TRUE_FALSE_OPTIONS.size())); } return ImmutableList.of(); @@ -247,7 +263,9 @@ public class PartyCommand implements TabExecutor { } private boolean isItemShareCategory(String category) { - return category.equalsIgnoreCase("loot") || category.equalsIgnoreCase("mining") || category.equalsIgnoreCase("herbalism") || category.equalsIgnoreCase("woodcutting") || category.equalsIgnoreCase("misc"); + return category.equalsIgnoreCase("loot") || category.equalsIgnoreCase("mining") + || category.equalsIgnoreCase("herbalism") || category.equalsIgnoreCase( + "woodcutting") || category.equalsIgnoreCase("misc"); } } 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 b11ac69ff..72dcb5094 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyCreateCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyCreateCommand.java @@ -12,12 +12,13 @@ import org.jetbrains.annotations.NotNull; public class PartyCreateCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { switch (args.length) { case 2: case 3: - Player player = (Player) sender; - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final Player player = (Player) sender; + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); if (UserManager.getPlayer(player) == null) { player.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); @@ -30,15 +31,17 @@ public class PartyCreateCommand implements CommandExecutor { } // Changing parties - if (!mcMMO.p.getPartyManager().changeOrJoinParty(mcMMOPlayer, args[1])) { + if (!mcMMO.p.getPartyManager().changeOrJoinParty(mmoPlayer, args[1])) { return true; } - mcMMO.p.getPartyManager().createParty(mcMMOPlayer, args[1], getPassword(args)); + mcMMO.p.getPartyManager().createParty(mmoPlayer, args[1], getPassword(args)); return true; default: - sender.sendMessage(LocaleLoader.getString("Commands.Usage.3", "party", "create", "<" + LocaleLoader.getString("Commands.Usage.PartyName") + ">", "[" + LocaleLoader.getString("Commands.Usage.Password") + "]")); + sender.sendMessage(LocaleLoader.getString("Commands.Usage.3", "party", "create", + "<" + LocaleLoader.getString("Commands.Usage.PartyName") + ">", + "[" + LocaleLoader.getString("Commands.Usage.Password") + "]")); 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 ac16d357b..5016a24bc 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyDisbandCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyDisbandCommand.java @@ -14,26 +14,28 @@ import org.jetbrains.annotations.NotNull; public class PartyDisbandCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (args.length == 1) { - final McMMOPlayer mcMMOPlayer = UserManager.getPlayer((Player) sender); - if (mcMMOPlayer == null) { + final McMMOPlayer mmoPlayer = UserManager.getPlayer((Player) sender); + if (mmoPlayer == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } - final Party playerParty = mcMMOPlayer.getParty(); + final Party playerParty = mmoPlayer.getParty(); final String partyName = playerParty.getName(); for (Player member : playerParty.getOnlineMembers()) { - if (!mcMMO.p.getPartyManager().handlePartyChangeEvent(member, partyName, null, EventReason.KICKED_FROM_PARTY)) { + if (!mcMMO.p.getPartyManager().handlePartyChangeEvent(member, partyName, null, + EventReason.KICKED_FROM_PARTY)) { return true; } member.sendMessage(LocaleLoader.getString("Party.Disband")); } - mcMMO.p.getPartyManager().disbandParty(mcMMOPlayer, playerParty); + mcMMO.p.getPartyManager().disbandParty(mmoPlayer, playerParty); return true; } sender.sendMessage(LocaleLoader.getString("Commands.Usage.1", "party", "disband")); diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyHelpCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyHelpCommand.java index bbf906a06..1365a6c72 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyHelpCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyHelpCommand.java @@ -9,9 +9,11 @@ import org.jetbrains.annotations.NotNull; public class PartyHelpCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (args.length == 1) { - sender.sendMessage(LocaleLoader.getString("Party.Help.3", "/party join", "/party quit")); + sender.sendMessage( + LocaleLoader.getString("Party.Help.3", "/party join", "/party quit")); sender.sendMessage(LocaleLoader.getString("Party.Help.1", "/party create")); sender.sendMessage(LocaleLoader.getString("Party.Help.4", "/party ")); sender.sendMessage(LocaleLoader.getString("Party.Help.5", "/party password")); 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 892256cdb..52787f628 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyInfoCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyInfoCommand.java @@ -7,6 +7,8 @@ import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.player.UserManager; +import java.util.ArrayList; +import java.util.List; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; @@ -14,12 +16,10 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.List; - public class PartyInfoCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { switch (args.length) { case 0: case 1: @@ -27,14 +27,14 @@ public class PartyInfoCommand implements CommandExecutor { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } - Player player = (Player) sender; - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - Party party = mcMMOPlayer.getParty(); + final Player player = (Player) sender; + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + Party party = mmoPlayer.getParty(); displayPartyHeader(player, party); displayShareModeInfo(player, party); displayPartyFeatures(player, party); - displayMemberInfo(player, mcMMOPlayer, party); + displayMemberInfo(player, mmoPlayer, party); return true; default: @@ -47,7 +47,10 @@ public class PartyInfoCommand implements CommandExecutor { player.sendMessage(LocaleLoader.getString("Commands.Party.Header")); StringBuilder status = new StringBuilder(); - status.append(LocaleLoader.getString("Commands.Party.Status", party.getName(), LocaleLoader.getString("Party.Status." + (party.isLocked() ? "Locked" : "Unlocked")), party.getLevel())); + status.append(LocaleLoader.getString("Commands.Party.Status", party.getName(), + LocaleLoader.getString( + "Party.Status." + (party.isLocked() ? "Locked" : "Unlocked")), + party.getLevel())); if (!party.hasReachedLevelCap()) { status.append(" (").append(party.getXpToLevelPercentage()).append(")"); @@ -74,7 +77,8 @@ public class PartyInfoCommand implements CommandExecutor { } } - player.sendMessage(LocaleLoader.getString("Commands.Party.UnlockedFeatures", unlockedPartyFeatures.isEmpty() ? "None" : unlockedPartyFeatures)); + player.sendMessage(LocaleLoader.getString("Commands.Party.UnlockedFeatures", + unlockedPartyFeatures.isEmpty() ? "None" : unlockedPartyFeatures)); for (String message : lockedPartyFeatures) { player.sendMessage(message); @@ -82,7 +86,8 @@ public class PartyInfoCommand implements CommandExecutor { } private boolean isUnlockedFeature(Party party, PartyFeature partyFeature) { - return party.getLevel() >= mcMMO.p.getGeneralConfig().getPartyFeatureUnlockLevel(partyFeature); + return party.getLevel() >= mcMMO.p.getGeneralConfig() + .getPartyFeatureUnlockLevel(partyFeature); } private void displayShareModeInfo(Player player, Party party) { @@ -99,34 +104,41 @@ public class PartyInfoCommand implements CommandExecutor { String separator = ""; if (xpShareEnabled) { - expShareInfo = LocaleLoader.getString("Commands.Party.ExpShare", party.getXpShareMode().toString()); + expShareInfo = LocaleLoader.getString("Commands.Party.ExpShare", + party.getXpShareMode().toString()); } if (itemShareEnabled) { - itemShareInfo = LocaleLoader.getString("Commands.Party.ItemShare", party.getItemShareMode().toString()); + itemShareInfo = LocaleLoader.getString("Commands.Party.ItemShare", + party.getItemShareMode().toString()); } if (xpShareEnabled && itemShareEnabled) { separator = ChatColor.DARK_GRAY + " || "; } - player.sendMessage(LocaleLoader.getString("Commands.Party.ShareMode") + expShareInfo + separator + itemShareInfo); + player.sendMessage( + LocaleLoader.getString("Commands.Party.ShareMode") + expShareInfo + separator + + itemShareInfo); if (itemSharingActive) { - player.sendMessage(LocaleLoader.getString("Commands.Party.ItemShareCategories", party.getItemShareCategories())); + player.sendMessage(LocaleLoader.getString("Commands.Party.ItemShareCategories", + party.getItemShareCategories())); } } - private void displayMemberInfo(Player player, McMMOPlayer mcMMOPlayer, Party party) { + private void displayMemberInfo(Player player, McMMOPlayer mmoPlayer, Party party) { /* * Only show members of the party that this member can see */ - List nearMembers = mcMMO.p.getPartyManager().getNearVisibleMembers(mcMMOPlayer); + List nearMembers = mcMMO.p.getPartyManager().getNearVisibleMembers(mmoPlayer); 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 91d6b39be..24fdc9c6d 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyInviteCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyInviteCommand.java @@ -14,7 +14,8 @@ import org.jetbrains.annotations.NotNull; public class PartyInviteCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (args.length == 2) { String targetName = CommandUtils.getMatchedPlayerName(args[1]); McMMOPlayer mcMMOTarget = UserManager.getOfflinePlayer(targetName); @@ -30,8 +31,8 @@ public class PartyInviteCommand implements CommandExecutor { return true; } - Player player = (Player) sender; - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final Player player = (Player) sender; + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); String playerName = player.getName(); if (player.equals(target)) { @@ -44,26 +45,32 @@ public class PartyInviteCommand implements CommandExecutor { return true; } - if (!mcMMO.p.getPartyManager().canInvite(mcMMOPlayer)) { + if (!mcMMO.p.getPartyManager().canInvite(mmoPlayer)) { player.sendMessage(LocaleLoader.getString("Party.Locked")); return true; } - Party playerParty = mcMMOPlayer.getParty(); + Party playerParty = mmoPlayer.getParty(); if (mcMMO.p.getPartyManager().isPartyFull(target, playerParty)) { - player.sendMessage(LocaleLoader.getString("Commands.Party.PartyFull.Invite", target.getName(), playerParty.toString(), mcMMO.p.getGeneralConfig().getPartyMaxSize())); + player.sendMessage( + LocaleLoader.getString("Commands.Party.PartyFull.Invite", target.getName(), + playerParty.toString(), + mcMMO.p.getGeneralConfig().getPartyMaxSize())); return true; } mcMMOTarget.setPartyInvite(playerParty); sender.sendMessage(LocaleLoader.getString("Commands.Invite.Success")); - target.sendMessage(LocaleLoader.getString("Commands.Party.Invite.0", playerParty.getName(), playerName)); + target.sendMessage( + LocaleLoader.getString("Commands.Party.Invite.0", playerParty.getName(), + playerName)); target.sendMessage(LocaleLoader.getString("Commands.Party.Invite.1")); return true; } - sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "invite", "<" + LocaleLoader.getString("Commands.Usage.Player") + ">")); + sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "invite", + "<" + LocaleLoader.getString("Commands.Usage.Player") + ">")); 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 38a3e3a24..9187abc81 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyItemShareCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyItemShareCommand.java @@ -9,17 +9,17 @@ import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.text.StringUtils; +import java.util.Locale; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.Locale; - public class PartyItemShareCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; @@ -27,7 +27,8 @@ public class PartyItemShareCommand implements CommandExecutor { Party party = UserManager.getPlayer((Player) sender).getParty(); - if (party.getLevel() < mcMMO.p.getGeneralConfig().getPartyFeatureUnlockLevel(PartyFeature.ITEM_SHARE)) { + if (party.getLevel() < mcMMO.p.getGeneralConfig() + .getPartyFeatureUnlockLevel(PartyFeature.ITEM_SHARE)) { sender.sendMessage(LocaleLoader.getString("Party.Feature.Disabled.4")); return true; } @@ -37,7 +38,9 @@ public class PartyItemShareCommand implements CommandExecutor { ShareMode mode = ShareMode.getShareMode(args[1].toUpperCase(Locale.ENGLISH)); if (mode == null) { - sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", "")); + sender.sendMessage( + LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", + "")); return true; } @@ -52,22 +55,28 @@ public class PartyItemShareCommand implements CommandExecutor { } else if (CommandUtils.shouldDisableToggle(args[2])) { toggle = false; } else { - sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", " ")); + sender.sendMessage( + LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", + " ")); return true; } try { - handleToggleItemShareCategory(party, ItemShareType.valueOf(args[1].toUpperCase(Locale.ENGLISH)), toggle); - } - catch (IllegalArgumentException ex) { - sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", " ")); + handleToggleItemShareCategory(party, + ItemShareType.valueOf(args[1].toUpperCase(Locale.ENGLISH)), toggle); + } catch (IllegalArgumentException ex) { + sender.sendMessage( + LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", + " ")); } return true; default: - sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", "")); - sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", " ")); + sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", + "")); + sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", + " ")); return true; } } @@ -75,7 +84,9 @@ public class PartyItemShareCommand implements CommandExecutor { private void handleChangingShareMode(Party party, ShareMode mode) { party.setItemShareMode(mode); - String changeModeMessage = LocaleLoader.getString("Commands.Party.SetSharing", LocaleLoader.getString("Party.ShareType.Item"), LocaleLoader.getString("Party.ShareMode." + StringUtils.getCapitalized(mode.toString()))); + String changeModeMessage = LocaleLoader.getString("Commands.Party.SetSharing", + LocaleLoader.getString("Party.ShareType.Item"), LocaleLoader.getString( + "Party.ShareMode." + StringUtils.getCapitalized(mode.toString()))); for (Player member : party.getOnlineMembers()) { member.sendMessage(changeModeMessage); @@ -85,7 +96,8 @@ public class PartyItemShareCommand implements CommandExecutor { private void handleToggleItemShareCategory(Party party, ItemShareType type, boolean toggle) { party.setSharingDrops(type, toggle); - String toggleMessage = LocaleLoader.getString("Commands.Party.ToggleShareCategory", StringUtils.getCapitalized(type.toString()), toggle ? "enabled" : "disabled"); + String toggleMessage = LocaleLoader.getString("Commands.Party.ToggleShareCategory", + StringUtils.getCapitalized(type.toString()), toggle ? "enabled" : "disabled"); for (Player member : party.getOnlineMembers()) { member.sendMessage(toggleMessage); 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 79b14b915..60c2d4515 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyJoinCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyJoinCommand.java @@ -14,7 +14,8 @@ import org.jetbrains.annotations.NotNull; public class PartyJoinCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { switch (args.length) { case 2: case 3: @@ -28,21 +29,23 @@ public class PartyJoinCommand implements CommandExecutor { Player target = mcMMOTarget.getPlayer(); if (!mcMMOTarget.inParty()) { - sender.sendMessage(LocaleLoader.getString("Party.PlayerNotInParty", targetName)); + sender.sendMessage( + LocaleLoader.getString("Party.PlayerNotInParty", targetName)); return true; } - Player player = (Player) sender; + final Player player = (Player) sender; if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); Party targetParty = mcMMOTarget.getParty(); - if (player.equals(target) || (mcMMOPlayer.inParty() && mcMMOPlayer.getParty().equals(targetParty))) { + if (player.equals(target) || (mmoPlayer.inParty() && mmoPlayer.getParty() + .equals(targetParty))) { sender.sendMessage(LocaleLoader.getString("Party.Join.Self")); return true; } @@ -57,21 +60,24 @@ public class PartyJoinCommand implements CommandExecutor { String partyName = targetParty.getName(); // Changing parties - if (!mcMMO.p.getPartyManager().changeOrJoinParty(mcMMOPlayer, partyName)) { + if (!mcMMO.p.getPartyManager().changeOrJoinParty(mmoPlayer, partyName)) { return true; } if (mcMMO.p.getPartyManager().isPartyFull(player, targetParty)) { - player.sendMessage(LocaleLoader.getString("Commands.Party.PartyFull", targetParty.toString())); + player.sendMessage(LocaleLoader.getString("Commands.Party.PartyFull", + targetParty.toString())); return true; } player.sendMessage(LocaleLoader.getString("Commands.Party.Join", partyName)); - mcMMO.p.getPartyManager().addToParty(mcMMOPlayer, targetParty); + mcMMO.p.getPartyManager().addToParty(mmoPlayer, targetParty); return true; default: - sender.sendMessage(LocaleLoader.getString("Commands.Usage.3", "party", "join", "<" + LocaleLoader.getString("Commands.Usage.Player") + ">", "[" + LocaleLoader.getString("Commands.Usage.Password") + "]")); + sender.sendMessage(LocaleLoader.getString("Commands.Usage.3", "party", "join", + "<" + LocaleLoader.getString("Commands.Usage.Player") + ">", + "[" + LocaleLoader.getString("Commands.Usage.Password") + "]")); 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 9ee2de089..b864f61d7 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyKickCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyKickCommand.java @@ -15,7 +15,8 @@ import org.jetbrains.annotations.NotNull; public class PartyKickCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (args.length == 2) { if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); @@ -36,7 +37,8 @@ public class PartyKickCommand implements CommandExecutor { Player onlineTarget = target.getPlayer(); String partyName = playerParty.getName(); - if (!mcMMO.p.getPartyManager().handlePartyChangeEvent(onlineTarget, partyName, null, EventReason.KICKED_FROM_PARTY)) { + if (!mcMMO.p.getPartyManager().handlePartyChangeEvent(onlineTarget, partyName, null, + EventReason.KICKED_FROM_PARTY)) { return true; } @@ -47,7 +49,8 @@ public class PartyKickCommand implements CommandExecutor { mcMMO.p.getPartyManager().removeFromParty(target, playerParty); return true; } - sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "kick", "<" + LocaleLoader.getString("Commands.Usage.Player") + ">")); + sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "kick", + "<" + LocaleLoader.getString("Commands.Usage.Player") + ">")); 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 745fba90f..18ac5da15 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyLockCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyLockCommand.java @@ -13,7 +13,8 @@ import org.jetbrains.annotations.NotNull; public class PartyLockCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { switch (args.length) { case 1: if (args[0].equalsIgnoreCase("lock")) { @@ -59,13 +60,15 @@ public class PartyLockCommand implements CommandExecutor { Party party = UserManager.getPlayer((Player) sender).getParty(); - if (!Permissions.partySubcommand(sender, lock ? PartySubcommandType.LOCK : PartySubcommandType.UNLOCK)) { + if (!Permissions.partySubcommand(sender, + lock ? PartySubcommandType.LOCK : PartySubcommandType.UNLOCK)) { sender.sendMessage(LocaleLoader.getString("mcMMO.NoPermission")); return; } if (lock == party.isLocked()) { - sender.sendMessage(LocaleLoader.getString("Party." + (lock ? "IsLocked" : "IsntLocked"))); + sender.sendMessage( + LocaleLoader.getString("Party." + (lock ? "IsLocked" : "IsntLocked"))); 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 880541add..10685c666 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyQuitCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyQuitCommand.java @@ -14,23 +14,26 @@ import org.jetbrains.annotations.NotNull; public class PartyQuitCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (args.length == 1) { - Player player = (Player) sender; + final Player player = (Player) sender; if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - Party playerParty = mcMMOPlayer.getParty(); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + Party playerParty = mmoPlayer.getParty(); - if (!mcMMO.p.getPartyManager().handlePartyChangeEvent(player, playerParty.getName(), null, EventReason.LEFT_PARTY)) { + if (!mcMMO.p.getPartyManager() + .handlePartyChangeEvent(player, playerParty.getName(), null, + EventReason.LEFT_PARTY)) { return true; } - mcMMO.p.getPartyManager().removeFromParty(mcMMOPlayer); + mcMMO.p.getPartyManager().removeFromParty(mmoPlayer); sender.sendMessage(LocaleLoader.getString("Commands.Party.Leave")); 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 7d2954ad0..c109696d4 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyRenameCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyRenameCommand.java @@ -14,15 +14,16 @@ import org.jetbrains.annotations.NotNull; public class PartyRenameCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (args.length == 2) { if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } - McMMOPlayer mcMMOPlayer = UserManager.getPlayer((Player) sender); - Party playerParty = mcMMOPlayer.getParty(); + final McMMOPlayer mmoPlayer = UserManager.getPlayer((Player) sender); + Party playerParty = mmoPlayer.getParty(); String oldPartyName = playerParty.getName(); String newPartyName = args[1].replace(".", ""); @@ -33,7 +34,7 @@ public class PartyRenameCommand implements CommandExecutor { return true; } - Player player = mcMMOPlayer.getPlayer(); + Player player = mmoPlayer.getPlayer(); // Check to see if the party exists, and if it does cancel renaming the party if (mcMMO.p.getPartyManager().checkPartyExistence(player, newPartyName)) { @@ -43,12 +44,16 @@ public class PartyRenameCommand implements CommandExecutor { String leaderName = playerParty.getLeader().getPlayerName(); for (Player member : playerParty.getOnlineMembers()) { - if (!mcMMO.p.getPartyManager().handlePartyChangeEvent(member, oldPartyName, newPartyName, EventReason.CHANGED_PARTIES)) { + if (!mcMMO.p.getPartyManager() + .handlePartyChangeEvent(member, oldPartyName, newPartyName, + EventReason.CHANGED_PARTIES)) { return true; } if (!member.getName().equalsIgnoreCase(leaderName)) { - member.sendMessage(LocaleLoader.getString("Party.InformedOnNameChange", leaderName, newPartyName)); + member.sendMessage( + LocaleLoader.getString("Party.InformedOnNameChange", leaderName, + newPartyName)); } } @@ -57,7 +62,8 @@ public class PartyRenameCommand implements CommandExecutor { sender.sendMessage(LocaleLoader.getString("Commands.Party.Rename", newPartyName)); return true; } - sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "rename", "<" + LocaleLoader.getString("Commands.Usage.PartyName") + ">")); + sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "rename", + "<" + LocaleLoader.getString("Commands.Usage.PartyName") + ">")); 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 c9c45453d..5dfb68504 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartySubcommandType.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartySubcommandType.java @@ -34,9 +34,11 @@ public enum PartySubcommandType { return QUIT; } 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")) { 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 098cdc3a2..66e346ef9 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyXpShareCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyXpShareCommand.java @@ -16,7 +16,8 @@ import org.jetbrains.annotations.NotNull; public class PartyXpShareCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; @@ -24,7 +25,8 @@ public class PartyXpShareCommand implements CommandExecutor { Party party = UserManager.getPlayer((Player) sender).getParty(); - if (party.getLevel() < mcMMO.p.getGeneralConfig().getPartyFeatureUnlockLevel(PartyFeature.XP_SHARE)) { + if (party.getLevel() < mcMMO.p.getGeneralConfig() + .getPartyFeatureUnlockLevel(PartyFeature.XP_SHARE)) { sender.sendMessage(LocaleLoader.getString("Party.Feature.Disabled.5")); return true; } @@ -32,22 +34,27 @@ public class PartyXpShareCommand implements CommandExecutor { if (args.length == 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 { - sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "xpshare", "")); + sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "xpshare", + "")); } return true; } - sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "xpshare", "")); + sender.sendMessage( + LocaleLoader.getString("Commands.Usage.2", "party", "xpshare", "")); return true; } private void handleChangingShareMode(Party party, ShareMode mode) { party.setXpShareMode(mode); - String changeModeMessage = LocaleLoader.getString("Commands.Party.SetSharing", LocaleLoader.getString("Party.ShareType.Xp"), LocaleLoader.getString("Party.ShareMode." + StringUtils.getCapitalized(mode.toString()))); + String changeModeMessage = LocaleLoader.getString("Commands.Party.SetSharing", + LocaleLoader.getString("Party.ShareType.Xp"), LocaleLoader.getString( + "Party.ShareMode." + StringUtils.getCapitalized(mode.toString()))); for (Player member : party.getOnlineMembers()) { member.sendMessage(changeModeMessage); 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 b4bb002ab..277defb55 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 @@ -12,29 +12,31 @@ import org.jetbrains.annotations.NotNull; public class PartyAllianceAcceptCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (args.length == 2) { if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } - Player player = (Player) sender; - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final Player player = (Player) sender; + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if (!mcMMOPlayer.hasPartyAllianceInvite()) { + if (!mmoPlayer.hasPartyAllianceInvite()) { sender.sendMessage(LocaleLoader.getString("mcMMO.NoInvites")); return true; } - if (mcMMOPlayer.getParty().getAlly() != null) { + if (mmoPlayer.getParty().getAlly() != null) { player.sendMessage(LocaleLoader.getString("Commands.Party.Alliance.AlreadyAllies")); return true; } - mcMMO.p.getPartyManager().acceptAllianceInvite(mcMMOPlayer); + mcMMO.p.getPartyManager().acceptAllianceInvite(mmoPlayer); return true; } - sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "alliance", "accept")); + sender.sendMessage( + LocaleLoader.getString("Commands.Usage.2", "party", "alliance", "accept")); 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 231f85456..84faf86e5 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 @@ -8,6 +8,8 @@ import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.player.UserManager; import com.google.common.collect.ImmutableList; +import java.util.ArrayList; +import java.util.List; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; @@ -17,22 +19,21 @@ import org.bukkit.entity.Player; import org.bukkit.util.StringUtil; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.List; - public class PartyAllianceCommand implements TabExecutor { private Player player; private Party playerParty; private Party targetParty; - public static final List ALLIANCE_SUBCOMMANDS = ImmutableList.of("invite", "accept", "disband"); + public static final List ALLIANCE_SUBCOMMANDS = ImmutableList.of("invite", "accept", + "disband"); private final CommandExecutor partyAllianceInviteCommand = new PartyAllianceInviteCommand(); private final CommandExecutor partyAllianceAcceptCommand = new PartyAllianceAcceptCommand(); private final CommandExecutor partyAllianceDisbandCommand = new PartyAllianceDisbandCommand(); @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (CommandUtils.noConsoleUsage(sender)) { return true; } @@ -43,13 +44,14 @@ public class PartyAllianceCommand implements TabExecutor { } player = (Player) sender; - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - playerParty = mcMMOPlayer.getParty(); + playerParty = mmoPlayer.getParty(); switch (args.length) { case 1: - if (playerParty.getLevel() < mcMMO.p.getGeneralConfig().getPartyFeatureUnlockLevel(PartyFeature.ALLIANCE)) { + if (playerParty.getLevel() < mcMMO.p.getGeneralConfig() + .getPartyFeatureUnlockLevel(PartyFeature.ALLIANCE)) { sender.sendMessage(LocaleLoader.getString("Party.Feature.Disabled.3")); return true; } @@ -62,12 +64,13 @@ public class PartyAllianceCommand implements TabExecutor { targetParty = playerParty.getAlly(); displayPartyHeader(); - displayMemberInfo(mcMMOPlayer); + displayMemberInfo(mmoPlayer); return true; case 2: case 3: - if (playerParty.getLevel() < mcMMO.p.getGeneralConfig().getPartyFeatureUnlockLevel(PartyFeature.ALLIANCE)) { + if (playerParty.getLevel() < mcMMO.p.getGeneralConfig() + .getPartyFeatureUnlockLevel(PartyFeature.ALLIANCE)) { sender.sendMessage(LocaleLoader.getString("Party.Feature.Disabled.3")); return true; } @@ -92,7 +95,7 @@ public class PartyAllianceCommand implements TabExecutor { targetParty = playerParty.getAlly(); displayPartyHeader(); - displayMemberInfo(mcMMOPlayer); + displayMemberInfo(mmoPlayer); return true; default: @@ -107,13 +110,16 @@ public class PartyAllianceCommand implements TabExecutor { } @Override - public List onTabComplete(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String label, String[] args) { + public List onTabComplete(@NotNull CommandSender commandSender, + @NotNull Command command, @NotNull String label, String[] args) { if (args.length == 1) { - List matches = StringUtil.copyPartialMatches(args[0], ALLIANCE_SUBCOMMANDS, new ArrayList<>(ALLIANCE_SUBCOMMANDS.size())); + List matches = StringUtil.copyPartialMatches(args[0], ALLIANCE_SUBCOMMANDS, + new ArrayList<>(ALLIANCE_SUBCOMMANDS.size())); if (matches.size() == 0) { List playerNames = CommandUtils.getOnlinePlayerNames(commandSender); - return StringUtil.copyPartialMatches(args[0], playerNames, new ArrayList<>(playerNames.size())); + return StringUtil.copyPartialMatches(args[0], playerNames, + new ArrayList<>(playerNames.size())); } return matches; @@ -123,11 +129,13 @@ public class PartyAllianceCommand implements TabExecutor { private void displayPartyHeader() { player.sendMessage(LocaleLoader.getString("Commands.Party.Alliance.Header")); - player.sendMessage(LocaleLoader.getString("Commands.Party.Alliance.Ally", playerParty.getName(), targetParty.getName())); + player.sendMessage( + LocaleLoader.getString("Commands.Party.Alliance.Ally", playerParty.getName(), + targetParty.getName())); } - private void displayMemberInfo(McMMOPlayer mcMMOPlayer) { - List nearMembers = mcMMO.p.getPartyManager().getNearMembers(mcMMOPlayer); + private void displayMemberInfo(McMMOPlayer mmoPlayer) { + List nearMembers = mcMMO.p.getPartyManager().getNearMembers(mmoPlayer); player.sendMessage(LocaleLoader.getString("Commands.Party.Alliance.Members.Header")); player.sendMessage(playerParty.createMembersList(player)); player.sendMessage(ChatColor.DARK_GRAY + "----------------------------"); 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 6b5e2dcea..bf8f40f96 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 @@ -13,15 +13,16 @@ import org.jetbrains.annotations.NotNull; public class PartyAllianceDisbandCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (args.length == 2) { if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } - Player player = (Player) sender; - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - Party party = mcMMOPlayer.getParty(); + final Player player = (Player) sender; + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + Party party = mmoPlayer.getParty(); if (party.getAlly() == null) { sender.sendMessage(LocaleLoader.getString("Commands.Party.Alliance.None")); @@ -31,7 +32,8 @@ public class PartyAllianceDisbandCommand implements CommandExecutor { mcMMO.p.getPartyManager().disbandAlliance(player, party, party.getAlly()); return true; } - sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "alliance", "disband")); + sender.sendMessage( + LocaleLoader.getString("Commands.Usage.2", "party", "alliance", "disband")); 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 04d12b649..4ce9a6242 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 @@ -14,7 +14,8 @@ import org.jetbrains.annotations.NotNull; public class PartyAllianceInviteCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (args.length == 3) { String targetName = CommandUtils.getMatchedPlayerName(args[2]); McMMOPlayer mcMMOTarget = UserManager.getOfflinePlayer(targetName); @@ -30,8 +31,8 @@ public class PartyAllianceInviteCommand implements CommandExecutor { return true; } - Player player = (Player) sender; - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final Player player = (Player) sender; + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); String playerName = player.getName(); if (player.equals(target)) { @@ -54,7 +55,7 @@ public class PartyAllianceInviteCommand implements CommandExecutor { return true; } - Party playerParty = mcMMOPlayer.getParty(); + Party playerParty = mmoPlayer.getParty(); if (playerParty.getAlly() != null) { player.sendMessage(LocaleLoader.getString("Commands.Party.Alliance.AlreadyAllies")); @@ -64,11 +65,13 @@ public class PartyAllianceInviteCommand implements CommandExecutor { mcMMOTarget.setPartyAllianceInvite(playerParty); sender.sendMessage(LocaleLoader.getString("Commands.Invite.Success")); - target.sendMessage(LocaleLoader.getString("Commands.Party.Alliance.Invite.0", playerParty.getName(), playerName)); + target.sendMessage(LocaleLoader.getString("Commands.Party.Alliance.Invite.0", + playerParty.getName(), playerName)); target.sendMessage(LocaleLoader.getString("Commands.Party.Alliance.Invite.1")); return true; } - sender.sendMessage(LocaleLoader.getString("Commands.Usage.3", "party", "alliance", "invite", "<" + LocaleLoader.getString("Commands.Usage.Player") + ">")); + sender.sendMessage(LocaleLoader.getString("Commands.Usage.3", "party", "alliance", "invite", + "<" + LocaleLoader.getString("Commands.Usage.Player") + ">")); 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 3b589ad0b..445e31fe3 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 @@ -11,13 +11,15 @@ import org.jetbrains.annotations.NotNull; public class PtpAcceptAnyCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (!Permissions.partyTeleportAcceptAll(sender)) { sender.sendMessage(command.getPermissionMessage()); return true; } - PartyTeleportRecord ptpRecord = UserManager.getPlayer(sender.getName()).getPartyTeleportRecord(); + PartyTeleportRecord ptpRecord = UserManager.getPlayer(sender.getName()) + .getPartyTeleportRecord(); if (ptpRecord.isConfirmRequired()) { sender.sendMessage(LocaleLoader.getString("Commands.ptp.AcceptAny.Disabled")); 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 c5c22aad3..58141563b 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 @@ -15,7 +15,8 @@ import org.jetbrains.annotations.NotNull; public class PtpAcceptCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (!Permissions.partyTeleportAccept(sender)) { sender.sendMessage(command.getPermissionMessage()); return true; @@ -26,7 +27,7 @@ public class PtpAcceptCommand implements CommandExecutor { return true; } - Player player = (Player) sender; + final Player player = (Player) sender; PartyTeleportRecord ptpRecord = UserManager.getPlayer(player).getPartyTeleportRecord(); if (!ptpRecord.hasRequest()) { @@ -34,7 +35,8 @@ public class PtpAcceptCommand implements CommandExecutor { return true; } - if (SkillUtils.cooldownExpired(ptpRecord.getTimeout(), mcMMO.p.getGeneralConfig().getPTPCommandTimeout())) { + if (SkillUtils.cooldownExpired(ptpRecord.getTimeout(), + mcMMO.p.getGeneralConfig().getPTPCommandTimeout())) { ptpRecord.removeRequest(); player.sendMessage(LocaleLoader.getString("Commands.ptp.RequestExpired")); return true; @@ -53,10 +55,13 @@ public class PtpAcceptCommand implements CommandExecutor { if (!Permissions.partyTeleportAllWorlds(target)) { if (!Permissions.partyTeleportWorld(target, targetWorld)) { - target.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", targetWorld.getName())); + target.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", + targetWorld.getName())); return true; - } else if (targetWorld != playerWorld && !Permissions.partyTeleportWorld(target, playerWorld)) { - target.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", playerWorld.getName())); + } 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 e33fda508..8f80f482f 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 @@ -17,6 +17,8 @@ import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.worldguard.WorldGuardManager; import com.gmail.nossr50.worldguard.WorldGuardUtils; import com.google.common.collect.ImmutableList; +import java.util.ArrayList; +import java.util.List; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; @@ -26,172 +28,15 @@ import org.bukkit.entity.Player; import org.bukkit.util.StringUtil; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.List; - public class PtpCommand implements TabExecutor { - public static final List TELEPORT_SUBCOMMANDS = ImmutableList.of("toggle", "accept", "acceptany", "acceptall"); + public static final List TELEPORT_SUBCOMMANDS = ImmutableList.of("toggle", "accept", + "acceptany", + "acceptall"); private final CommandExecutor ptpToggleCommand = new PtpToggleCommand(); private final CommandExecutor ptpAcceptAnyCommand = new PtpAcceptAnyCommand(); private final CommandExecutor ptpAcceptCommand = new PtpAcceptCommand(); - @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { - if (CommandUtils.noConsoleUsage(sender)) { - return true; - } - - Player player = (Player) sender; - - /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) { - if (!WorldGuardManager.getInstance().hasMainFlag(player)) - return true; - } - - /* WORLD BLACKLIST CHECK */ - if (WorldBlacklist.isWorldBlacklisted(player.getWorld())) - return true; - - if (!UserManager.hasPlayerDataKey(player)) { - return true; - } - - if (UserManager.getPlayer((Player) sender) == null) { - sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); - return true; - } - - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - - if (!mcMMOPlayer.inParty()) { - sender.sendMessage(LocaleLoader.getString("Commands.Party.None")); - return true; - } - - Party party = mcMMOPlayer.getParty(); - - if (party.getLevel() < mcMMO.p.getGeneralConfig().getPartyFeatureUnlockLevel(PartyFeature.TELEPORT)) { - sender.sendMessage(LocaleLoader.getString("Party.Feature.Disabled.2")); - return true; - } - - if (args.length == 1) { - if (args[0].equalsIgnoreCase("toggle")) { - return ptpToggleCommand.onCommand(sender, command, label, args); - } - - if (args[0].equalsIgnoreCase("acceptany") || args[0].equalsIgnoreCase("acceptall")) { - return ptpAcceptAnyCommand.onCommand(sender, command, label, args); - } - - long recentlyHurt = mcMMOPlayer.getRecentlyHurt(); - int hurtCooldown = mcMMO.p.getGeneralConfig().getPTPCommandRecentlyHurtCooldown(); - - if (hurtCooldown > 0) { - int timeRemaining = SkillUtils.calculateTimeLeft(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, hurtCooldown, player); - - if (timeRemaining > 0) { - player.sendMessage(LocaleLoader.getString("Item.Injured.Wait", timeRemaining)); - return true; - } - } - - if (args[0].equalsIgnoreCase("accept")) { - return ptpAcceptCommand.onCommand(sender, command, label, args); - } - - if (!Permissions.partyTeleportSend(sender)) { - sender.sendMessage(command.getPermissionMessage()); - return true; - } - - int ptpCooldown = mcMMO.p.getGeneralConfig().getPTPCommandCooldown(); - long ptpLastUse = mcMMOPlayer.getPartyTeleportRecord().getLastUse(); - - if (ptpCooldown > 0) { - int timeRemaining = SkillUtils.calculateTimeLeft(ptpLastUse * Misc.TIME_CONVERSION_FACTOR, ptpCooldown, player); - - if (timeRemaining > 0) { - player.sendMessage(LocaleLoader.getString("Item.Generic.Wait", timeRemaining)); - return true; - } - } - - sendTeleportRequest(sender, player, CommandUtils.getMatchedPlayerName(args[0])); - return true; - } - return false; - } - - @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { - if (args.length == 1) { - List matches = StringUtil.copyPartialMatches(args[0], TELEPORT_SUBCOMMANDS, new ArrayList<>(TELEPORT_SUBCOMMANDS.size())); - - if (matches.size() == 0) { - if (UserManager.getPlayer((Player) sender) == null) { - sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); - return ImmutableList.of(); - } - - Player player = (Player) sender; - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - - if (!mcMMOPlayer.inParty()) { - return ImmutableList.of(); - } - - List playerNames = mcMMOPlayer.getParty().getOnlinePlayerNames(player); - return StringUtil.copyPartialMatches(args[0], playerNames, new ArrayList<>(playerNames.size())); - } - - return matches; - } - return ImmutableList.of(); - } - - private void sendTeleportRequest(CommandSender sender, Player player, String targetName) { - if (!canTeleport(sender, player, targetName)) { - return; - } - - McMMOPlayer mcMMOTarget = UserManager.getPlayer(targetName); - Player target = mcMMOTarget.getPlayer(); - - - if (mcMMO.p.getGeneralConfig().getPTPCommandWorldPermissions()) { - World targetWorld = target.getWorld(); - World playerWorld = player.getWorld(); - - if (!Permissions.partyTeleportAllWorlds(player)) { - if (!Permissions.partyTeleportWorld(target, targetWorld)) { - player.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", targetWorld.getName())); - return; - } else if (targetWorld != playerWorld && !Permissions.partyTeleportWorld(player, targetWorld)) { - player.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", targetWorld.getName())); - return; - } - } - } - - PartyTeleportRecord ptpRecord = mcMMOTarget.getPartyTeleportRecord(); - - if (!ptpRecord.isConfirmRequired()) { - handleTeleportWarmup(player, target); - return; - } - - ptpRecord.setRequestor(player); - ptpRecord.actualizeTimeout(); - - player.sendMessage(LocaleLoader.getString("Commands.Invite.Success")); - - target.sendMessage(LocaleLoader.getString("Commands.ptp.Request1", player.getName())); - target.sendMessage(LocaleLoader.getString("Commands.ptp.Request2", mcMMO.p.getGeneralConfig().getPTPCommandTimeout())); - } - protected static boolean canTeleport(CommandSender sender, Player player, String targetName) { McMMOPlayer mcMMOTarget = UserManager.getPlayer(targetName); @@ -244,9 +89,185 @@ public class PtpCommand implements TabExecutor { if (warmup > 0) { teleportingPlayer.sendMessage(LocaleLoader.getString("Teleport.Commencing", warmup)); - mcMMO.p.getFoliaLib().getScheduler().runAtEntityLater(teleportingPlayer, new TeleportationWarmup(mcMMOPlayer, mcMMOTarget), 20 * warmup); + mcMMO.p.getFoliaLib().getScheduler().runAtEntityLater(teleportingPlayer, + new TeleportationWarmup(mcMMOPlayer, mcMMOTarget), 20 * warmup); } else { EventUtils.handlePartyTeleportEvent(teleportingPlayer, targetPlayer); } } + + @Override + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, + String[] args) { + if (CommandUtils.noConsoleUsage(sender)) { + return true; + } + + Player player = (Player) sender; + + /* WORLD GUARD MAIN FLAG CHECK */ + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) { + return true; + } + } + + /* WORLD BLACKLIST CHECK */ + if (WorldBlacklist.isWorldBlacklisted(player.getWorld())) { + return true; + } + + if (!UserManager.hasPlayerDataKey(player)) { + return true; + } + + if (UserManager.getPlayer((Player) sender) == null) { + sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); + return true; + } + + McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + + if (!mcMMOPlayer.inParty()) { + sender.sendMessage(LocaleLoader.getString("Commands.Party.None")); + return true; + } + + Party party = mcMMOPlayer.getParty(); + + if (party.getLevel() < mcMMO.p.getGeneralConfig() + .getPartyFeatureUnlockLevel(PartyFeature.TELEPORT)) { + sender.sendMessage(LocaleLoader.getString("Party.Feature.Disabled.2")); + return true; + } + + if (args.length == 1) { + if (args[0].equalsIgnoreCase("toggle")) { + return ptpToggleCommand.onCommand(sender, command, label, args); + } + + if (args[0].equalsIgnoreCase("acceptany") || args[0].equalsIgnoreCase("acceptall")) { + return ptpAcceptAnyCommand.onCommand(sender, command, label, args); + } + + long recentlyHurt = mcMMOPlayer.getRecentlyHurt(); + int hurtCooldown = mcMMO.p.getGeneralConfig().getPTPCommandRecentlyHurtCooldown(); + + if (hurtCooldown > 0) { + int timeRemaining = SkillUtils.calculateTimeLeft( + recentlyHurt * Misc.TIME_CONVERSION_FACTOR, + hurtCooldown, player); + + if (timeRemaining > 0) { + player.sendMessage(LocaleLoader.getString("Item.Injured.Wait", timeRemaining)); + return true; + } + } + + if (args[0].equalsIgnoreCase("accept")) { + return ptpAcceptCommand.onCommand(sender, command, label, args); + } + + if (!Permissions.partyTeleportSend(sender)) { + sender.sendMessage(command.getPermissionMessage()); + return true; + } + + int ptpCooldown = mcMMO.p.getGeneralConfig().getPTPCommandCooldown(); + long ptpLastUse = mcMMOPlayer.getPartyTeleportRecord().getLastUse(); + + if (ptpCooldown > 0) { + int timeRemaining = SkillUtils.calculateTimeLeft( + ptpLastUse * Misc.TIME_CONVERSION_FACTOR, ptpCooldown, + player); + + if (timeRemaining > 0) { + player.sendMessage(LocaleLoader.getString("Item.Generic.Wait", timeRemaining)); + return true; + } + } + + sendTeleportRequest(sender, player, CommandUtils.getMatchedPlayerName(args[0])); + return true; + } + return false; + } + + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, + String[] args) { + if (args.length == 1) { + List matches = StringUtil.copyPartialMatches(args[0], TELEPORT_SUBCOMMANDS, + new ArrayList<>(TELEPORT_SUBCOMMANDS.size())); + + if (matches.size() == 0) { + if (UserManager.getPlayer((Player) sender) == null) { + sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); + return ImmutableList.of(); + } + + Player player = (Player) sender; + McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + + if (!mcMMOPlayer.inParty()) { + return ImmutableList.of(); + } + + List playerNames = mcMMOPlayer.getParty().getOnlinePlayerNames(player); + return StringUtil.copyPartialMatches(args[0], playerNames, + new ArrayList<>(playerNames.size())); + } + + return matches; + } + return ImmutableList.of(); + } + + private void sendTeleportRequest(CommandSender sender, Player player, String targetName) { + if (!canTeleport(sender, player, targetName)) { + return; + } + + McMMOPlayer mcMMOTarget = UserManager.getPlayer(targetName); + Player target = mcMMOTarget.getPlayer(); + + if (mcMMO.p.getGeneralConfig().getPTPCommandWorldPermissions()) { + World targetWorld = target.getWorld(); + World playerWorld = player.getWorld(); + + if (!Permissions.partyTeleportAllWorlds(player)) { + if (!Permissions.partyTeleportWorld(target, targetWorld)) { + player.sendMessage( + LocaleLoader.getString("Commands.ptp.NoWorldPermissions", + targetWorld.getName())); + return; + } else if (targetWorld != playerWorld && !Permissions.partyTeleportWorld(player, + targetWorld)) { + player.sendMessage( + LocaleLoader.getString("Commands.ptp.NoWorldPermissions", + targetWorld.getName())); + return; + } + } + } + + PartyTeleportRecord ptpRecord = mcMMOTarget.getPartyTeleportRecord(); + + if (!ptpRecord.isConfirmRequired()) { + handleTeleportWarmup(player, target); + return; + } + + ptpRecord.setRequestor(player); + ptpRecord.actualizeTimeout(); + + player.sendMessage(LocaleLoader.getString("Commands.Invite.Success")); + + target.sendMessage(LocaleLoader.getString("Commands.ptp.Request1", player.getName())); + target.sendMessage( + LocaleLoader.getString("Commands.ptp.Request2", + mcMMO.p.getGeneralConfig().getPTPCommandTimeout())); + } } 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 e3ef50491..ec1a1d6cc 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 @@ -11,13 +11,15 @@ import org.jetbrains.annotations.NotNull; public class PtpToggleCommand implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (!Permissions.partyTeleportToggle(sender)) { sender.sendMessage(command.getPermissionMessage()); return true; } - PartyTeleportRecord ptpRecord = UserManager.getPlayer(sender.getName()).getPartyTeleportRecord(); + PartyTeleportRecord ptpRecord = UserManager.getPlayer(sender.getName()) + .getPartyTeleportRecord(); if (ptpRecord.isEnabled()) { sender.sendMessage(LocaleLoader.getString("Commands.ptp.Disabled")); 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 ab1047387..2af5265f6 100644 --- a/src/main/java/com/gmail/nossr50/commands/player/InspectCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/player/InspectCommand.java @@ -11,6 +11,8 @@ import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.scoreboards.ScoreboardManager; import com.gmail.nossr50.util.skills.SkillTools; import com.google.common.collect.ImmutableList; +import java.util.ArrayList; +import java.util.List; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabExecutor; @@ -18,19 +20,18 @@ import org.bukkit.entity.Player; import org.bukkit.util.StringUtil; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.List; - public class InspectCommand implements TabExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (args.length == 1) { String playerName = CommandUtils.getMatchedPlayerName(args[0]); - McMMOPlayer mcMMOPlayer = UserManager.getOfflinePlayer(playerName); + final McMMOPlayer mmoPlayer = UserManager.getOfflinePlayer(playerName); - // If the mcMMOPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process. - if (mcMMOPlayer == null) { - PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(playerName); // Temporary Profile + // If the mmoPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process. + if (mmoPlayer == null) { + PlayerProfile profile = mcMMO.getDatabaseManager() + .loadPlayerProfile(playerName); // Temporary Profile if (!CommandUtils.isLoaded(sender, profile)) { return true; @@ -65,27 +66,26 @@ public class InspectCommand implements TabExecutor { // Sum power level int powerLevel = 0; - for (PrimarySkillType skill : SkillTools.NON_CHILD_SKILLS) + for (PrimarySkillType skill : SkillTools.NON_CHILD_SKILLS) { powerLevel += profile.getSkillLevel(skill); + } sender.sendMessage(LocaleLoader.getString("Commands.PowerLevel", powerLevel)); } else { - Player target = mcMMOPlayer.getPlayer(); - boolean isVanished = false; - - if (CommandUtils.hidden(sender, target, Permissions.inspectHidden(sender))) { - isVanished = true; - } + Player target = mmoPlayer.getPlayer(); + boolean isVanished = CommandUtils.hidden(sender, target, + Permissions.inspectHidden(sender)); //Only distance check players who are online and not vanished - if (!isVanished && CommandUtils.tooFar(sender, target, Permissions.inspectFar(sender))) { + if (!isVanished && CommandUtils.tooFar(sender, target, + Permissions.inspectFar(sender))) { return true; } if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled() && sender instanceof Player && mcMMO.p.getGeneralConfig().getInspectUseBoard()) { - ScoreboardManager.enablePlayerInspectScoreboard((Player) sender, mcMMOPlayer); + ScoreboardManager.enablePlayerInspectScoreboard((Player) sender, mmoPlayer); if (!mcMMO.p.getGeneralConfig().getInspectUseChat()) { return true; @@ -102,7 +102,8 @@ public class InspectCommand implements TabExecutor { CommandUtils.printCombatSkills(target, sender); CommandUtils.printMiscSkills(target, sender); - sender.sendMessage(LocaleLoader.getString("Commands.PowerLevel", mcMMOPlayer.getPowerLevel())); + sender.sendMessage( + LocaleLoader.getString("Commands.PowerLevel", mmoPlayer.getPowerLevel())); } return true; @@ -111,10 +112,12 @@ public class InspectCommand implements TabExecutor { } @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, String[] args) { if (args.length == 1) { List playerNames = CommandUtils.getOnlinePlayerNames(sender); - return StringUtil.copyPartialMatches(args[0], playerNames, new ArrayList<>(playerNames.size())); + return StringUtil.copyPartialMatches(args[0], playerNames, + new ArrayList<>(playerNames.size())); } return ImmutableList.of(); } 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 e4b0c24db..d7124996c 100644 --- a/src/main/java/com/gmail/nossr50/commands/player/McRankCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/player/McRankCommand.java @@ -9,6 +9,8 @@ import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.player.UserManager; import com.google.common.collect.ImmutableList; +import java.util.ArrayList; +import java.util.List; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabExecutor; @@ -17,12 +19,10 @@ import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.util.StringUtil; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.List; - public class McRankCommand implements TabExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { switch (args.length) { case 0: if (CommandUtils.noConsoleUsage(sender)) { @@ -53,10 +53,10 @@ public class McRankCommand implements TabExecutor { } String playerName = CommandUtils.getMatchedPlayerName(args[0]); - McMMOPlayer mcMMOPlayer = UserManager.getOfflinePlayer(playerName); + final McMMOPlayer mmoPlayer = UserManager.getOfflinePlayer(playerName); - if (mcMMOPlayer != null) { - Player player = mcMMOPlayer.getPlayer(); + if (mmoPlayer != null) { + Player player = mmoPlayer.getPlayer(); playerName = player.getName(); if (CommandUtils.tooFar(sender, player, Permissions.mcrankFar(sender))) { @@ -73,27 +73,31 @@ public class McRankCommand implements TabExecutor { } @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, String[] args) { if (args.length == 1) { List playerNames = CommandUtils.getOnlinePlayerNames(sender); - return StringUtil.copyPartialMatches(args[0], playerNames, new ArrayList<>(playerNames.size())); + return StringUtil.copyPartialMatches(args[0], playerNames, + new ArrayList<>(playerNames.size())); } return ImmutableList.of(); } private void display(CommandSender sender, String playerName) { if (sender instanceof Player) { - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName()); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(sender.getName()); - if (mcMMOPlayer == null) { + if (mmoPlayer == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return; } - long cooldownMillis = Math.min(mcMMO.p.getGeneralConfig().getDatabasePlayerCooldown(), 1750); + long cooldownMillis = Math.min(mcMMO.p.getGeneralConfig().getDatabasePlayerCooldown(), + 1750); - if (mcMMOPlayer.getDatabaseATS() + cooldownMillis > System.currentTimeMillis()) { - sender.sendMessage(LocaleLoader.getString("Commands.Database.CooldownMS", getCDSeconds(mcMMOPlayer, cooldownMillis))); + if (mmoPlayer.getDatabaseATS() + cooldownMillis > System.currentTimeMillis()) { + sender.sendMessage(LocaleLoader.getString("Commands.Database.CooldownMS", + getCDSeconds(mmoPlayer, cooldownMillis))); return; } @@ -101,19 +105,23 @@ public class McRankCommand implements TabExecutor { sender.sendMessage(LocaleLoader.getString("Commands.Database.Processing")); return; } else { - ((Player) sender).setMetadata(MetadataConstants.METADATA_KEY_DATABASE_COMMAND, new FixedMetadataValue(mcMMO.p, null)); + ((Player) sender).setMetadata(MetadataConstants.METADATA_KEY_DATABASE_COMMAND, + new FixedMetadataValue(mcMMO.p, null)); } - mcMMOPlayer.actualizeDatabaseATS(); + mmoPlayer.actualizeDatabaseATS(); } - boolean useBoard = mcMMO.p.getGeneralConfig().getScoreboardsEnabled() && (sender instanceof Player) && (mcMMO.p.getGeneralConfig().getRankUseBoard()); + boolean useBoard = + mcMMO.p.getGeneralConfig().getScoreboardsEnabled() && (sender instanceof Player) + && (mcMMO.p.getGeneralConfig().getRankUseBoard()); boolean useChat = !useBoard || mcMMO.p.getGeneralConfig().getRankUseChat(); - mcMMO.p.getFoliaLib().getScheduler().runAsync(new McRankCommandAsyncTask(playerName, sender, useBoard, useChat)); + mcMMO.p.getFoliaLib().getScheduler() + .runAsync(new McRankCommandAsyncTask(playerName, sender, useBoard, useChat)); } - private long getCDSeconds(McMMOPlayer mcMMOPlayer, long cooldownMillis) { - return ((mcMMOPlayer.getDatabaseATS() + cooldownMillis) - System.currentTimeMillis()); + private long getCDSeconds(McMMOPlayer mmoPlayer, long cooldownMillis) { + return ((mmoPlayer.getDatabaseATS() + cooldownMillis) - System.currentTimeMillis()); } } diff --git a/src/main/java/com/gmail/nossr50/commands/player/McTopCommand.java b/src/main/java/com/gmail/nossr50/commands/player/McTopCommand.java index 9f347d32a..c54e4836e 100644 --- a/src/main/java/com/gmail/nossr50/commands/player/McTopCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/player/McTopCommand.java @@ -11,6 +11,8 @@ import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.text.StringUtils; import com.google.common.collect.ImmutableList; +import java.util.ArrayList; +import java.util.List; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabExecutor; @@ -19,12 +21,10 @@ import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.util.StringUtil; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.List; - public class McTopCommand implements TabExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { PrimarySkillType skill = null; switch (args.length) { @@ -46,7 +46,8 @@ public class McTopCommand implements TabExecutor { // Check if the command is for Maces but the MC version is not correct if (skill == PrimarySkillType.MACES - && !mcMMO.getCompatibilityManager().getMinecraftGameVersion().isAtLeast(1, 21, 0)) { + && !mcMMO.getCompatibilityManager().getMinecraftGameVersion() + .isAtLeast(1, 21, 0)) { return true; } @@ -66,7 +67,8 @@ public class McTopCommand implements TabExecutor { // Check if the command is for Maces but the MC version is not correct if (skill == PrimarySkillType.MACES - && !mcMMO.getCompatibilityManager().getMinecraftGameVersion().isAtLeast(1, 21, 0)) { + && !mcMMO.getCompatibilityManager().getMinecraftGameVersion() + .isAtLeast(1, 21, 0)) { return true; } @@ -79,9 +81,12 @@ public class McTopCommand implements TabExecutor { } @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, String[] args) { if (args.length == 1) { - return StringUtil.copyPartialMatches(args[0], mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES, new ArrayList<>(mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES.size())); + return StringUtil.copyPartialMatches(args[0], + mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES, + new ArrayList<>(mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES.size())); } return ImmutableList.of(); } @@ -97,16 +102,20 @@ public class McTopCommand implements TabExecutor { return; } - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName()); - long cooldownMillis = Math.max(mcMMO.p.getGeneralConfig().getDatabasePlayerCooldown(), 1750); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(sender.getName()); + long cooldownMillis = Math.max(mcMMO.p.getGeneralConfig().getDatabasePlayerCooldown(), + 1750); - if (mcMMOPlayer.getDatabaseATS() + cooldownMillis > System.currentTimeMillis()) { - double seconds = ((mcMMOPlayer.getDatabaseATS() + cooldownMillis) - System.currentTimeMillis()) / 1000.0D; + if (mmoPlayer.getDatabaseATS() + cooldownMillis > System.currentTimeMillis()) { + double seconds = + ((mmoPlayer.getDatabaseATS() + cooldownMillis) - System.currentTimeMillis()) + / 1000.0D; if (seconds < 1) { seconds = 1; } - sender.sendMessage(LocaleLoader.formatString(LocaleLoader.getString("Commands.Database.Cooldown"), seconds)); + sender.sendMessage(LocaleLoader.formatString( + LocaleLoader.getString("Commands.Database.Cooldown"), seconds)); return; } @@ -114,20 +123,23 @@ public class McTopCommand implements TabExecutor { sender.sendMessage(LocaleLoader.getString("Commands.Database.Processing")); return; } else { - ((Player) sender).setMetadata(MetadataConstants.METADATA_KEY_DATABASE_COMMAND, new FixedMetadataValue(mcMMO.p, null)); + ((Player) sender).setMetadata(MetadataConstants.METADATA_KEY_DATABASE_COMMAND, + new FixedMetadataValue(mcMMO.p, null)); } - mcMMOPlayer.actualizeDatabaseATS(); + mmoPlayer.actualizeDatabaseATS(); } display(page, skill, sender); } private void display(int page, PrimarySkillType skill, CommandSender sender) { - boolean useBoard = (sender instanceof Player) && (mcMMO.p.getGeneralConfig().getTopUseBoard()); + boolean useBoard = + (sender instanceof Player) && (mcMMO.p.getGeneralConfig().getTopUseBoard()); boolean useChat = !useBoard || mcMMO.p.getGeneralConfig().getTopUseChat(); - mcMMO.p.getFoliaLib().getScheduler().runAsync(new McTopCommandAsyncTask(page, skill, sender, useBoard, useChat)); + mcMMO.p.getFoliaLib().getScheduler() + .runAsync(new McTopCommandAsyncTask(page, skill, sender, useBoard, useChat)); } private PrimarySkillType extractSkill(CommandSender sender, String skillName) { 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 4475c984a..255f76c1f 100644 --- a/src/main/java/com/gmail/nossr50/commands/player/MccooldownCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/player/MccooldownCommand.java @@ -8,17 +8,17 @@ import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.scoreboards.ScoreboardManager; import com.google.common.collect.ImmutableList; +import java.util.List; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabExecutor; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.List; - public class MccooldownCommand implements TabExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (CommandUtils.noConsoleUsage(sender)) { return true; } @@ -28,9 +28,10 @@ public class MccooldownCommand implements TabExecutor { } if (args.length == 0) { - Player player = (Player) sender; + final Player player = (Player) sender; - if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled() && mcMMO.p.getGeneralConfig().getCooldownUseBoard()) { + if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled() && mcMMO.p.getGeneralConfig() + .getCooldownUseBoard()) { ScoreboardManager.enablePlayerCooldownScoreboard(player); if (!mcMMO.p.getGeneralConfig().getCooldownUseChat()) { @@ -43,7 +44,7 @@ public class MccooldownCommand implements TabExecutor { return true; } - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); player.sendMessage(LocaleLoader.getString("Commands.Cooldowns.Header")); player.sendMessage(LocaleLoader.getString("mcMMO.NoSkillNote")); @@ -53,12 +54,14 @@ public class MccooldownCommand implements TabExecutor { continue; } - int seconds = mcMMOPlayer.calculateTimeRemaining(ability); + int seconds = mmoPlayer.calculateTimeRemaining(ability); if (seconds <= 0) { - player.sendMessage(LocaleLoader.getString("Commands.Cooldowns.Row.Y", ability.getLocalizedName())); + player.sendMessage(LocaleLoader.getString("Commands.Cooldowns.Row.Y", + ability.getLocalizedName())); } else { - player.sendMessage(LocaleLoader.getString("Commands.Cooldowns.Row.N", ability.getLocalizedName(), seconds)); + player.sendMessage(LocaleLoader.getString("Commands.Cooldowns.Row.N", + ability.getLocalizedName(), seconds)); } } @@ -68,7 +71,8 @@ public class MccooldownCommand implements TabExecutor { } @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, String[] args) { return ImmutableList.of(); } } 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 a9e8cf6e1..3ae8e5fd0 100644 --- a/src/main/java/com/gmail/nossr50/commands/player/McstatsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/player/McstatsCommand.java @@ -6,17 +6,17 @@ import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.scoreboards.ScoreboardManager; import com.google.common.collect.ImmutableList; +import java.util.List; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabExecutor; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.List; - public class McstatsCommand implements TabExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (CommandUtils.noConsoleUsage(sender)) { return true; } @@ -31,9 +31,10 @@ public class McstatsCommand implements TabExecutor { return true; } - Player player = (Player) sender; + final Player player = (Player) sender; - if (mcMMO.p.getGeneralConfig().getStatsUseBoard() && mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) { + if (mcMMO.p.getGeneralConfig().getStatsUseBoard() && mcMMO.p.getGeneralConfig() + .getScoreboardsEnabled()) { ScoreboardManager.enablePlayerStatsScoreboard(player); if (!mcMMO.p.getGeneralConfig().getStatsUseChat()) { @@ -51,9 +52,11 @@ public class McstatsCommand implements TabExecutor { int powerLevelCap = mcMMO.p.getGeneralConfig().getPowerLevelCap(); if (powerLevelCap != Integer.MAX_VALUE) { - player.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Capped", UserManager.getPlayer(player).getPowerLevel(), powerLevelCap)); + player.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Capped", + UserManager.getPlayer(player).getPowerLevel(), powerLevelCap)); } else { - player.sendMessage(LocaleLoader.getString("Commands.PowerLevel", UserManager.getPlayer(player).getPowerLevel())); + player.sendMessage(LocaleLoader.getString("Commands.PowerLevel", + UserManager.getPlayer(player).getPowerLevel())); } return true; @@ -62,7 +65,8 @@ public class McstatsCommand implements TabExecutor { } @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, String[] args) { return ImmutableList.of(); } } diff --git a/src/main/java/com/gmail/nossr50/commands/player/XPBarCommand.java b/src/main/java/com/gmail/nossr50/commands/player/XPBarCommand.java index 7fa7d04ff..371716aac 100644 --- a/src/main/java/com/gmail/nossr50/commands/player/XPBarCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/player/XPBarCommand.java @@ -9,6 +9,8 @@ import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.text.StringUtils; import com.google.common.collect.ImmutableList; +import java.util.ArrayList; +import java.util.List; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabExecutor; @@ -17,36 +19,39 @@ import org.bukkit.util.StringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; -import java.util.List; - public class XPBarCommand implements TabExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, @NotNull String[] args) { if (sender instanceof Player) { - McMMOPlayer mmoPlayer = UserManager.getPlayer((Player) sender); + final McMMOPlayer mmoPlayer = UserManager.getPlayer((Player) sender); if (mmoPlayer == null) { - NotificationManager.sendPlayerInformationChatOnlyPrefixed(mmoPlayer.getPlayer(), "Profile.PendingLoad"); + NotificationManager.sendPlayerInformationChatOnlyPrefixed(mmoPlayer.getPlayer(), + "Profile.PendingLoad"); return false; } if (args.length == 0) { return false; } else if (args.length < 2) { - String option = args[0]; + String option = args[0]; - if (option.equalsIgnoreCase(ExperienceBarManager.XPBarSettingTarget.RESET.toString())) { - mmoPlayer.getExperienceBarManager().xpBarSettingToggle(ExperienceBarManager.XPBarSettingTarget.RESET, null); - return true; - } else if (option.equalsIgnoreCase(ExperienceBarManager.XPBarSettingTarget.DISABLE.toString())) { - mmoPlayer.getExperienceBarManager().disableAllBars(); - return true; - } else { - return false; - } + if (option.equalsIgnoreCase( + ExperienceBarManager.XPBarSettingTarget.RESET.toString())) { + mmoPlayer.getExperienceBarManager() + .xpBarSettingToggle(ExperienceBarManager.XPBarSettingTarget.RESET, + null); + return true; + } else if (option.equalsIgnoreCase( + ExperienceBarManager.XPBarSettingTarget.DISABLE.toString())) { + mmoPlayer.getExperienceBarManager().disableAllBars(); + return true; + } else { + return false; + } - //Per skill Settings path + //Per skill Settings path } else if (args.length == 2) { String skillName = args[1]; @@ -57,10 +62,13 @@ public class XPBarCommand implements TabExecutor { //Target setting String option = args[0].toLowerCase(); - ExperienceBarManager.XPBarSettingTarget settingTarget = getSettingTarget(option); - if (settingTarget != null && settingTarget != ExperienceBarManager.XPBarSettingTarget.RESET) { + ExperienceBarManager.XPBarSettingTarget settingTarget = getSettingTarget( + option); + if (settingTarget != null + && settingTarget != ExperienceBarManager.XPBarSettingTarget.RESET) { //Change setting - mmoPlayer.getExperienceBarManager().xpBarSettingToggle(settingTarget, targetSkill); + mmoPlayer.getExperienceBarManager() + .xpBarSettingToggle(settingTarget, targetSkill); return true; } else { return false; @@ -92,19 +100,25 @@ public class XPBarCommand implements TabExecutor { } @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, String[] args) { switch (args.length) { case 1: List options = new ArrayList<>(); - for(ExperienceBarManager.XPBarSettingTarget settingTarget : ExperienceBarManager.XPBarSettingTarget.values()) { + for (ExperienceBarManager.XPBarSettingTarget settingTarget : ExperienceBarManager.XPBarSettingTarget.values()) { options.add(StringUtils.getCapitalized(settingTarget.toString())); } - return StringUtil.copyPartialMatches(args[0], options, new ArrayList<>(ExperienceBarManager.XPBarSettingTarget.values().length)); + return StringUtil.copyPartialMatches(args[0], options, + new ArrayList<>(ExperienceBarManager.XPBarSettingTarget.values().length)); case 2: - if (!args[0].equalsIgnoreCase(ExperienceBarManager.XPBarSettingTarget.RESET.toString())) - return StringUtil.copyPartialMatches(args[1], mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES, new ArrayList<>(mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES.size())); + if (!args[0].equalsIgnoreCase( + ExperienceBarManager.XPBarSettingTarget.RESET.toString())) { + return StringUtil.copyPartialMatches(args[1], + mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES, + new ArrayList<>(mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES.size())); + } default: return ImmutableList.of(); } diff --git a/src/main/java/com/gmail/nossr50/commands/server/Mcmmoupgrade.java b/src/main/java/com/gmail/nossr50/commands/server/Mcmmoupgrade.java index 77b181e2a..f8469fb63 100644 --- a/src/main/java/com/gmail/nossr50/commands/server/Mcmmoupgrade.java +++ b/src/main/java/com/gmail/nossr50/commands/server/Mcmmoupgrade.java @@ -10,7 +10,8 @@ import org.jetbrains.annotations.NotNull; */ public class Mcmmoupgrade implements CommandExecutor { @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { return false; } } 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 94751a95b..3ce1db82e 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/AcrobaticsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/AcrobaticsCommand.java @@ -8,11 +8,10 @@ import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.text.TextComponentFactory; -import net.kyori.adventure.text.Component; -import org.bukkit.entity.Player; - import java.util.ArrayList; import java.util.List; +import net.kyori.adventure.text.Component; +import org.bukkit.entity.Player; public class AcrobaticsCommand extends SkillCommand { private String dodgeChance; @@ -29,7 +28,8 @@ public class AcrobaticsCommand extends SkillCommand { protected void dataCalculations(Player player, float skillValue) { // ACROBATICS_DODGE if (canDodge) { - final String[] dodgeStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.ACROBATICS_DODGE); + final String[] dodgeStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + SubSkillType.ACROBATICS_DODGE); dodgeChance = dodgeStrings[0]; dodgeChanceLucky = dodgeStrings[1]; } @@ -42,23 +42,27 @@ public class AcrobaticsCommand extends SkillCommand { } @Override - protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { + protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, + boolean isLucky) { List messages = new ArrayList<>(); if (canDodge) { messages.add(getStatMessage(SubSkillType.ACROBATICS_DODGE, dodgeChance) - + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", dodgeChanceLucky) : "")); + + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", dodgeChanceLucky) + : "")); } - + if (canRoll) { AbstractSubSkill abstractSubSkill = InteractionManager.getAbstractByName("Roll"); if (abstractSubSkill != null) { - String[] rollStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.ACROBATICS_ROLL); + String[] rollStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + SubSkillType.ACROBATICS_ROLL); messages.add(getStatMessage(SubSkillType.ACROBATICS_ROLL, rollStrings[0]) - + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", rollStrings[1]) : "")); + + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", rollStrings[1]) + : "")); } } @@ -69,7 +73,8 @@ public class AcrobaticsCommand extends SkillCommand { protected List getTextComponents(Player player) { List textComponents = new ArrayList<>(); - TextComponentFactory.getSubSkillTextComponents(player, textComponents, PrimarySkillType.ACROBATICS); + TextComponentFactory.getSubSkillTextComponents(player, textComponents, + PrimarySkillType.ACROBATICS); return textComponents; } 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 9fa9281a7..cd5570ba8 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/AlchemyCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/AlchemyCommand.java @@ -7,18 +7,17 @@ import com.gmail.nossr50.skills.alchemy.AlchemyManager; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; -import net.kyori.adventure.text.Component; -import org.bukkit.entity.Player; - import java.util.ArrayList; import java.util.List; +import net.kyori.adventure.text.Component; +import org.bukkit.entity.Player; 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; @@ -35,7 +34,8 @@ public class AlchemyCommand extends SkillCommand { boolean isLucky = Permissions.lucky(player, PrimarySkillType.ALCHEMY); displayValues[0] = decimal.format(alchemyManager.calculateBrewSpeed(false)) + "x"; - displayValues[1] = isLucky ? decimal.format(alchemyManager.calculateBrewSpeed(true)) + "x" : null; + displayValues[1] = + isLucky ? decimal.format(alchemyManager.calculateBrewSpeed(true)) + "x" : null; return displayValues; } @@ -65,7 +65,8 @@ public class AlchemyCommand extends SkillCommand { } @Override - protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { + protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, + boolean isLucky) { List messages = new ArrayList<>(); if (canCatalysis) { @@ -74,8 +75,11 @@ public class AlchemyCommand extends SkillCommand { } if (canConcoctions) { - messages.add(getStatMessage(false, true, SubSkillType.ALCHEMY_CONCOCTIONS, String.valueOf(tier), String.valueOf(RankUtils.getHighestRank(SubSkillType.ALCHEMY_CONCOCTIONS)))); - messages.add(getStatMessage(true, true, SubSkillType.ALCHEMY_CONCOCTIONS, String.valueOf(ingredientCount), ingredientList)); + messages.add(getStatMessage(false, true, SubSkillType.ALCHEMY_CONCOCTIONS, + String.valueOf(tier), + String.valueOf(RankUtils.getHighestRank(SubSkillType.ALCHEMY_CONCOCTIONS)))); + messages.add(getStatMessage(true, true, SubSkillType.ALCHEMY_CONCOCTIONS, + String.valueOf(ingredientCount), ingredientList)); //messages.add(LocaleLoader.getString("Alchemy.Concoctions.Rank", tier, RankUtils.getHighestRank(SubSkillType.ALCHEMY_CONCOCTIONS))); //messages.add(LocaleLoader.getString("Alchemy.Concoctions.Ingredients", ingredientCount, ingredientList)); @@ -88,7 +92,8 @@ public class AlchemyCommand extends SkillCommand { protected List getTextComponents(Player player) { List textComponents = new ArrayList<>(); - TextComponentFactory.getSubSkillTextComponents(player, textComponents, PrimarySkillType.ALCHEMY); + TextComponentFactory.getSubSkillTextComponents(player, textComponents, + PrimarySkillType.ALCHEMY); return textComponents; } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/AprilCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/AprilCommand.java index 5364918ff..cfab931cd 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/AprilCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/AprilCommand.java @@ -31,7 +31,7 @@ // skillName = StringUtils.getCapitalized(label); // // if (args.length == 0) { -// Player player = (Player) sender; +// final Player player = (Player) sender; // FakeSkillType fakeSkillType = FakeSkillType.getByName(skillName); // // float skillValue = Misc.getRandom().nextInt(99); 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 d916f458a..77eb6706e 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/ArcheryCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/ArcheryCommand.java @@ -8,11 +8,10 @@ import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.text.TextComponentFactory; -import net.kyori.adventure.text.Component; -import org.bukkit.entity.Player; - import java.util.ArrayList; import java.util.List; +import net.kyori.adventure.text.Component; +import org.bukkit.entity.Player; public class ArcheryCommand extends SkillCommand { private String skillShotBonus; @@ -33,18 +32,20 @@ public class ArcheryCommand extends SkillCommand { protected void dataCalculations(Player player, float skillValue) { // ARCHERY_ARROW_RETRIEVAL if (canRetrieve) { - String[] retrieveStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.ARCHERY_ARROW_RETRIEVAL); + String[] retrieveStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + SubSkillType.ARCHERY_ARROW_RETRIEVAL); retrieveChance = retrieveStrings[0]; retrieveChanceLucky = retrieveStrings[1]; } - + // ARCHERY_DAZE if (canDaze) { - String[] dazeStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.ARCHERY_DAZE); + String[] dazeStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + SubSkillType.ARCHERY_DAZE); dazeChance = dazeStrings[0]; dazeChanceLucky = dazeStrings[1]; } - + // SKILL SHOT if (canSkillShot) { skillShotBonus = percent.format(Archery.getDamageBonusPercent(player)); @@ -59,26 +60,30 @@ public class ArcheryCommand extends SkillCommand { } @Override - protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { + protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, + boolean isLucky) { List messages = new ArrayList<>(); if (canRetrieve) { messages.add(getStatMessage(SubSkillType.ARCHERY_ARROW_RETRIEVAL, retrieveChance) - + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", retrieveChanceLucky) : "")); + + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", retrieveChanceLucky) + : "")); } - + if (canDaze) { messages.add(getStatMessage(SubSkillType.ARCHERY_DAZE, dazeChance) - + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", dazeChanceLucky) : "")); + + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", dazeChanceLucky) + : "")); } - + if (canSkillShot) { messages.add(getStatMessage(SubSkillType.ARCHERY_SKILL_SHOT, skillShotBonus)); } if (Permissions.canUseSubSkill(player, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK)) { messages.add(getStatMessage(SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK, - String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK, 1000)))); + String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, + SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK, 1000)))); } return messages; @@ -88,7 +93,8 @@ public class ArcheryCommand extends SkillCommand { protected List getTextComponents(Player player) { List textComponents = new ArrayList<>(); - TextComponentFactory.getSubSkillTextComponents(player, textComponents, PrimarySkillType.ARCHERY); + TextComponentFactory.getSubSkillTextComponents(player, textComponents, + PrimarySkillType.ARCHERY); return textComponents; } 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 ce1907c39..620fd6e17 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/AxesCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/AxesCommand.java @@ -9,11 +9,10 @@ import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; -import net.kyori.adventure.text.Component; -import org.bukkit.entity.Player; - import java.util.ArrayList; import java.util.List; +import net.kyori.adventure.text.Component; +import org.bukkit.entity.Player; public class AxesCommand extends SkillCommand { private String critChance; @@ -44,14 +43,15 @@ public class AxesCommand extends SkillCommand { if (canAxeMastery) { axeMasteryDamage = Axes.getAxeMasteryBonusDamage(player); } - + // CRITICAL HIT if (canCritical) { - String[] criticalHitStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.AXES_CRITICAL_STRIKES); + String[] criticalHitStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + SubSkillType.AXES_CRITICAL_STRIKES); critChance = criticalHitStrings[0]; critChanceLucky = criticalHitStrings[1]; } - + // SKULL SPLITTER if (canSkullSplitter) { String[] skullSplitterStrings = calculateLengthDisplayValues(player, skillValue); @@ -62,7 +62,9 @@ public class AxesCommand extends SkillCommand { @Override protected void permissionsCheck(Player player) { - canSkullSplitter = Permissions.skullSplitter(player) && RankUtils.hasUnlockedSubskill(player, SubSkillType.AXES_SKULL_SPLITTER); + canSkullSplitter = + Permissions.skullSplitter(player) && RankUtils.hasUnlockedSubskill(player, + SubSkillType.AXES_SKULL_SPLITTER); canCritical = Permissions.canUseSubSkill(player, SubSkillType.AXES_CRITICAL_STRIKES); canAxeMastery = Permissions.canUseSubSkill(player, SubSkillType.AXES_AXE_MASTERY); canImpact = Permissions.canUseSubSkill(player, SubSkillType.AXES_ARMOR_IMPACT); @@ -70,34 +72,44 @@ public class AxesCommand extends SkillCommand { } @Override - protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { + protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, + boolean isLucky) { List messages = new ArrayList<>(); if (canImpact) { - messages.add(LocaleLoader.getString("Ability.Generic.Template", LocaleLoader.getString("Axes.Ability.Bonus.2"), LocaleLoader.getString("Axes.Ability.Bonus.3", impactDamage))); + 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))); + messages.add(LocaleLoader.getString("Ability.Generic.Template", + LocaleLoader.getString("Axes.Ability.Bonus.0"), + LocaleLoader.getString("Axes.Ability.Bonus.1", axeMasteryDamage))); } if (canCritical) { messages.add(getStatMessage(SubSkillType.AXES_CRITICAL_STRIKES, critChance) - + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", critChanceLucky) : "")); + + (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))); + messages.add(LocaleLoader.getString("Ability.Generic.Template", + LocaleLoader.getString("Axes.Ability.Bonus.4"), + LocaleLoader.getString("Axes.Ability.Bonus.5", Axes.greaterImpactBonusDamage))); } if (canSkullSplitter) { messages.add(getStatMessage(SubSkillType.AXES_SKULL_SPLITTER, skullSplitterLength) - + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", skullSplitterLengthEndurance) : "")); + + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", + skullSplitterLengthEndurance) : "")); } if (Permissions.canUseSubSkill(player, SubSkillType.AXES_AXES_LIMIT_BREAK)) { messages.add(getStatMessage(SubSkillType.AXES_AXES_LIMIT_BREAK, - String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, SubSkillType.AXES_AXES_LIMIT_BREAK, 1000)))); + String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, + SubSkillType.AXES_AXES_LIMIT_BREAK, 1000)))); } return messages; @@ -107,7 +119,8 @@ public class AxesCommand extends SkillCommand { protected List getTextComponents(Player player) { final List textComponents = new ArrayList<>(); - TextComponentFactory.getSubSkillTextComponents(player, textComponents, PrimarySkillType.AXES); + TextComponentFactory.getSubSkillTextComponents(player, textComponents, + PrimarySkillType.AXES); return textComponents; } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/CrossbowsCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/CrossbowsCommand.java index 309b5de27..fe2a87ec7 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/CrossbowsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/CrossbowsCommand.java @@ -1,17 +1,18 @@ package com.gmail.nossr50.commands.skills; +import static com.gmail.nossr50.datatypes.skills.SubSkillType.CROSSBOWS_CROSSBOWS_LIMIT_BREAK; +import static com.gmail.nossr50.datatypes.skills.SubSkillType.CROSSBOWS_POWERED_SHOT; +import static com.gmail.nossr50.datatypes.skills.SubSkillType.CROSSBOWS_TRICK_SHOT; + import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; -import net.kyori.adventure.text.Component; -import org.bukkit.entity.Player; - import java.util.ArrayList; import java.util.List; - -import static com.gmail.nossr50.datatypes.skills.SubSkillType.*; +import net.kyori.adventure.text.Component; +import org.bukkit.entity.Player; public class CrossbowsCommand extends SkillCommand { private boolean canTrickShot; @@ -36,7 +37,8 @@ public class CrossbowsCommand extends SkillCommand { } @Override - protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { + protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, + boolean isLucky) { List messages = new ArrayList<>(); if (mmoPlayer == null) { @@ -55,7 +57,8 @@ public class CrossbowsCommand extends SkillCommand { if (Permissions.canUseSubSkill(player, CROSSBOWS_CROSSBOWS_LIMIT_BREAK)) { messages.add(getStatMessage(CROSSBOWS_CROSSBOWS_LIMIT_BREAK, - String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, CROSSBOWS_CROSSBOWS_LIMIT_BREAK, 1000)))); + String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, + CROSSBOWS_CROSSBOWS_LIMIT_BREAK, 1000)))); } return messages; @@ -65,7 +68,8 @@ public class CrossbowsCommand extends SkillCommand { protected List getTextComponents(Player player) { List textComponents = new ArrayList<>(); - TextComponentFactory.getSubSkillTextComponents(player, textComponents, PrimarySkillType.CROSSBOWS); + TextComponentFactory.getSubSkillTextComponents(player, textComponents, + PrimarySkillType.CROSSBOWS); return textComponents; } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/ExcavationCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/ExcavationCommand.java index 829e4644f..d5068bd34 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/ExcavationCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/ExcavationCommand.java @@ -7,11 +7,10 @@ import com.gmail.nossr50.skills.excavation.ExcavationManager; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; -import net.kyori.adventure.text.Component; -import org.bukkit.entity.Player; - import java.util.ArrayList; import java.util.List; +import net.kyori.adventure.text.Component; +import org.bukkit.entity.Player; public class ExcavationCommand extends SkillCommand { private String gigaDrillBreakerLength; @@ -36,19 +35,23 @@ public class ExcavationCommand extends SkillCommand { @Override protected void permissionsCheck(Player player) { - canGigaDrill = Permissions.gigaDrillBreaker(player) && RankUtils.hasUnlockedSubskill(player, SubSkillType.EXCAVATION_GIGA_DRILL_BREAKER); + canGigaDrill = Permissions.gigaDrillBreaker(player) && RankUtils.hasUnlockedSubskill(player, + SubSkillType.EXCAVATION_GIGA_DRILL_BREAKER); canTreasureHunt = Permissions.canUseSubSkill(player, SubSkillType.EXCAVATION_ARCHAEOLOGY); } @Override - protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { + protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, + boolean isLucky) { List messages = new ArrayList<>(); ExcavationManager excavationManager = mmoPlayer.getExcavationManager(); if (canGigaDrill) { - messages.add(getStatMessage(SubSkillType.EXCAVATION_GIGA_DRILL_BREAKER, gigaDrillBreakerLength) - + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", gigaDrillBreakerLengthEndurance) : "")); + messages.add(getStatMessage(SubSkillType.EXCAVATION_GIGA_DRILL_BREAKER, + gigaDrillBreakerLength) + + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", + gigaDrillBreakerLengthEndurance) : "")); //messages.add(LocaleLoader.getString("Excavation.Effect.Length", gigaDrillBreakerLength) + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", gigaDrillBreakerLengthEndurance) : "")); } @@ -68,7 +71,8 @@ public class ExcavationCommand extends SkillCommand { protected List getTextComponents(Player player) { List textComponents = new ArrayList<>(); - TextComponentFactory.getSubSkillTextComponents(player, textComponents, PrimarySkillType.EXCAVATION); + TextComponentFactory.getSubSkillTextComponents(player, textComponents, + PrimarySkillType.EXCAVATION); return textComponents; } 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 c955fdf18..d96066c39 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/FishingCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/FishingCommand.java @@ -13,11 +13,10 @@ import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.StringUtils; import com.gmail.nossr50.util.text.TextComponentFactory; -import net.kyori.adventure.text.Component; -import org.bukkit.entity.Player; - import java.util.ArrayList; import java.util.List; +import net.kyori.adventure.text.Component; +import org.bukkit.entity.Player; public class FishingCommand extends SkillCommand { private int lootTier; @@ -56,26 +55,40 @@ public class FishingCommand extends SkillCommand { lootTier = fishingManager.getLootTier(); // Item drop rates - commonTreasure = percent.format(FishingTreasureConfig.getInstance().getItemDropRate(lootTier, Rarity.COMMON) / 100.0); - uncommonTreasure = percent.format(FishingTreasureConfig.getInstance().getItemDropRate(lootTier, Rarity.UNCOMMON) / 100.0); - rareTreasure = percent.format(FishingTreasureConfig.getInstance().getItemDropRate(lootTier, Rarity.RARE) / 100.0); - epicTreasure = percent.format(FishingTreasureConfig.getInstance().getItemDropRate(lootTier, Rarity.EPIC) / 100.0); - legendaryTreasure = percent.format(FishingTreasureConfig.getInstance().getItemDropRate(lootTier, Rarity.LEGENDARY) / 100.0); - mythicTreasure = percent.format(FishingTreasureConfig.getInstance().getItemDropRate(lootTier, Rarity.MYTHIC) / 100.0); + commonTreasure = percent.format( + FishingTreasureConfig.getInstance().getItemDropRate(lootTier, Rarity.COMMON) + / 100.0); + uncommonTreasure = percent.format( + FishingTreasureConfig.getInstance().getItemDropRate(lootTier, Rarity.UNCOMMON) + / 100.0); + rareTreasure = percent.format( + FishingTreasureConfig.getInstance().getItemDropRate(lootTier, Rarity.RARE) + / 100.0); + epicTreasure = percent.format( + FishingTreasureConfig.getInstance().getItemDropRate(lootTier, Rarity.EPIC) + / 100.0); + legendaryTreasure = percent.format( + FishingTreasureConfig.getInstance().getItemDropRate(lootTier, Rarity.LEGENDARY) + / 100.0); + mythicTreasure = percent.format( + FishingTreasureConfig.getInstance().getItemDropRate(lootTier, Rarity.MYTHIC) + / 100.0); // Magic hunter drop rates double totalEnchantChance = 0; for (Rarity rarity : Rarity.values()) { if (rarity != Rarity.MYTHIC) { - totalEnchantChance += FishingTreasureConfig.getInstance().getEnchantmentDropRate(lootTier, rarity); + totalEnchantChance += FishingTreasureConfig.getInstance() + .getEnchantmentDropRate(lootTier, rarity); } } - if (totalEnchantChance >= 1) + if (totalEnchantChance >= 1) { magicChance = percent.format(totalEnchantChance / 100.0); - else + } else { magicChance = percent.format(0); + } } // FISHING_SHAKE @@ -93,54 +106,69 @@ public class FishingCommand extends SkillCommand { // MASTER ANGLER if (canMasterAngler) { - maMinWaitTime = StringUtils.ticksToSeconds(fishingManager.getMasterAnglerTickMinWaitReduction(RankUtils.getRank(player, SubSkillType.FISHING_MASTER_ANGLER), false)); - maMaxWaitTime = StringUtils.ticksToSeconds(fishingManager.getMasterAnglerTickMaxWaitReduction(RankUtils.getRank(player, SubSkillType.FISHING_MASTER_ANGLER), false, 0)); + maMinWaitTime = StringUtils.ticksToSeconds( + fishingManager.getMasterAnglerTickMinWaitReduction( + RankUtils.getRank(player, SubSkillType.FISHING_MASTER_ANGLER), false)); + maMaxWaitTime = StringUtils.ticksToSeconds( + fishingManager.getMasterAnglerTickMaxWaitReduction( + RankUtils.getRank(player, SubSkillType.FISHING_MASTER_ANGLER), false, + 0)); } } @Override protected void permissionsCheck(Player player) { canTreasureHunt = Permissions.canUseSubSkill(player, SubSkillType.FISHING_TREASURE_HUNTER); - canMagicHunt = Permissions.canUseSubSkill(player, SubSkillType.FISHING_MAGIC_HUNTER) && Permissions.canUseSubSkill(player, SubSkillType.FISHING_TREASURE_HUNTER); + canMagicHunt = Permissions.canUseSubSkill(player, SubSkillType.FISHING_MAGIC_HUNTER) + && Permissions.canUseSubSkill(player, SubSkillType.FISHING_TREASURE_HUNTER); canShake = Permissions.canUseSubSkill(player, SubSkillType.FISHING_SHAKE); - canFishermansDiet = Permissions.canUseSubSkill(player, SubSkillType.FISHING_FISHERMANS_DIET); - canMasterAngler = mcMMO.getCompatibilityManager().getMasterAnglerCompatibilityLayer() != null && Permissions.canUseSubSkill(player, SubSkillType.FISHING_MASTER_ANGLER); + canFishermansDiet = Permissions.canUseSubSkill(player, + SubSkillType.FISHING_FISHERMANS_DIET); + canMasterAngler = + mcMMO.getCompatibilityManager().getMasterAnglerCompatibilityLayer() != null + && Permissions.canUseSubSkill(player, SubSkillType.FISHING_MASTER_ANGLER); canIceFish = Permissions.canUseSubSkill(player, SubSkillType.FISHING_ICE_FISHING); } @Override - protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { + 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))); + 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())); + messages.add(getStatMessage(SubSkillType.FISHING_ICE_FISHING, + SubSkillType.FISHING_ICE_FISHING.getLocaleStatDescription())); } - + if (canMagicHunt) { messages.add(getStatMessage(SubSkillType.FISHING_MAGIC_HUNTER, magicChance)); } if (canMasterAngler) { - messages.add(getStatMessage(false,true, + messages.add(getStatMessage(false, true, SubSkillType.FISHING_MASTER_ANGLER, maMinWaitTime)); - messages.add(getStatMessage(true,true, + messages.add(getStatMessage(true, true, SubSkillType.FISHING_MASTER_ANGLER, maMaxWaitTime)); } - + 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(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, String.valueOf(commonTreasure), String.valueOf(uncommonTreasure), @@ -157,7 +185,8 @@ public class FishingCommand extends SkillCommand { protected List getTextComponents(Player player) { List textComponents = new ArrayList<>(); - TextComponentFactory.getSubSkillTextComponents(player, textComponents, PrimarySkillType.FISHING); + TextComponentFactory.getSubSkillTextComponents(player, textComponents, + PrimarySkillType.FISHING); return textComponents; } 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 5c9028897..4a95874af 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/HerbalismCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/HerbalismCommand.java @@ -8,13 +8,12 @@ import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; +import java.util.ArrayList; +import java.util.List; import net.kyori.adventure.text.Component; import org.bukkit.Material; import org.bukkit.entity.Player; -import java.util.ArrayList; -import java.util.List; - public class HerbalismCommand extends SkillCommand { private String greenTerraLength; private String greenTerraLengthEndurance; @@ -46,25 +45,27 @@ public class HerbalismCommand extends SkillCommand { @Override protected void dataCalculations(Player player, float skillValue) { - + // DOUBLE DROPS if (canDoubleDrop) { - String[] doubleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.HERBALISM_DOUBLE_DROPS); + String[] doubleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + SubSkillType.HERBALISM_DOUBLE_DROPS); doubleDropChance = doubleDropStrings[0]; doubleDropChanceLucky = doubleDropStrings[1]; } if (canTripleDrop) { - String[] tripleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.HERBALISM_VERDANT_BOUNTY); + String[] tripleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + SubSkillType.HERBALISM_VERDANT_BOUNTY); tripleDropChance = tripleDropStrings[0]; tripleDropChanceLucky = tripleDropStrings[1]; } - + // FARMERS DIET if (canFarmersDiet) { farmersDietRank = RankUtils.getRank(player, SubSkillType.HERBALISM_FARMERS_DIET); } - + // GREEN TERRA if (canGreenTerra) { String[] greenTerraStrings = calculateLengthDisplayValues(player, skillValue); @@ -76,21 +77,24 @@ public class HerbalismCommand extends SkillCommand { if (canGreenThumbBlocks || canGreenThumbPlants) { greenThumbStage = RankUtils.getRank(player, SubSkillType.HERBALISM_GREEN_THUMB); - String[] greenThumbStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.HERBALISM_GREEN_THUMB); + String[] greenThumbStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + SubSkillType.HERBALISM_GREEN_THUMB); greenThumbChance = greenThumbStrings[0]; greenThumbChanceLucky = greenThumbStrings[1]; } // HYLIAN LUCK if (hasHylianLuck) { - String[] hylianLuckStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.HERBALISM_HYLIAN_LUCK); + String[] hylianLuckStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + SubSkillType.HERBALISM_HYLIAN_LUCK); hylianLuckChance = hylianLuckStrings[0]; hylianLuckChanceLucky = hylianLuckStrings[1]; } // SHROOM THUMB if (canShroomThumb) { - String[] shroomThumbStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.HERBALISM_SHROOM_THUMB); + String[] shroomThumbStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + SubSkillType.HERBALISM_SHROOM_THUMB); shroomThumbChance = shroomThumbStrings[0]; shroomThumbChanceLucky = shroomThumbStrings[1]; } @@ -100,57 +104,80 @@ public class HerbalismCommand extends SkillCommand { protected void permissionsCheck(Player player) { hasHylianLuck = Permissions.canUseSubSkill(player, SubSkillType.HERBALISM_HYLIAN_LUCK); canGreenTerra = Permissions.greenTerra(player); - canGreenThumbPlants = RankUtils.hasUnlockedSubskill(player, SubSkillType.HERBALISM_GREEN_THUMB) && (Permissions.greenThumbPlant(player, Material.WHEAT) || Permissions.greenThumbPlant(player, Material.CARROT) || Permissions.greenThumbPlant(player, Material.POTATO) || Permissions.greenThumbPlant(player, Material.BEETROOTS) || Permissions.greenThumbPlant(player, Material.NETHER_WART) || Permissions.greenThumbPlant(player, Material.COCOA)); - canGreenThumbBlocks = RankUtils.hasUnlockedSubskill(player, SubSkillType.HERBALISM_GREEN_THUMB) && (Permissions.greenThumbBlock(player, Material.DIRT) || Permissions.greenThumbBlock(player, Material.COBBLESTONE) || Permissions.greenThumbBlock(player, Material.COBBLESTONE_WALL) || Permissions.greenThumbBlock(player, Material.STONE_BRICKS)); + canGreenThumbPlants = + RankUtils.hasUnlockedSubskill(player, SubSkillType.HERBALISM_GREEN_THUMB) && ( + Permissions.greenThumbPlant(player, Material.WHEAT) + || Permissions.greenThumbPlant(player, Material.CARROT) + || Permissions.greenThumbPlant(player, Material.POTATO) + || Permissions.greenThumbPlant(player, Material.BEETROOTS) + || Permissions.greenThumbPlant(player, Material.NETHER_WART) + || Permissions.greenThumbPlant(player, Material.COCOA)); + canGreenThumbBlocks = + RankUtils.hasUnlockedSubskill(player, SubSkillType.HERBALISM_GREEN_THUMB) && ( + Permissions.greenThumbBlock(player, Material.DIRT) + || Permissions.greenThumbBlock(player, Material.COBBLESTONE) + || Permissions.greenThumbBlock(player, Material.COBBLESTONE_WALL) + || Permissions.greenThumbBlock(player, Material.STONE_BRICKS)); canFarmersDiet = Permissions.canUseSubSkill(player, SubSkillType.HERBALISM_FARMERS_DIET); - canDoubleDrop = Permissions.canUseSubSkill(player, SubSkillType.HERBALISM_DOUBLE_DROPS) && !mcMMO.p.getGeneralConfig().getDoubleDropsDisabled(skill); - canTripleDrop = Permissions.canUseSubSkill(player, SubSkillType.HERBALISM_VERDANT_BOUNTY) && !mcMMO.p.getGeneralConfig().getDoubleDropsDisabled(skill); + canDoubleDrop = Permissions.canUseSubSkill(player, SubSkillType.HERBALISM_DOUBLE_DROPS) + && !mcMMO.p.getGeneralConfig().getDoubleDropsDisabled(skill); + canTripleDrop = Permissions.canUseSubSkill(player, SubSkillType.HERBALISM_VERDANT_BOUNTY) + && !mcMMO.p.getGeneralConfig().getDoubleDropsDisabled(skill); canShroomThumb = Permissions.canUseSubSkill(player, SubSkillType.HERBALISM_SHROOM_THUMB); } @Override - protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { + protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, + boolean isLucky) { List messages = new ArrayList<>(); if (canDoubleDrop) { messages.add(getStatMessage(SubSkillType.HERBALISM_DOUBLE_DROPS, doubleDropChance) - + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", doubleDropChanceLucky) : "")); + + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", doubleDropChanceLucky) + : "")); } if (canTripleDrop) { messages.add(getStatMessage(SubSkillType.HERBALISM_VERDANT_BOUNTY, tripleDropChance) - + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", tripleDropChanceLucky) : "")); + + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", tripleDropChanceLucky) + : "")); } if (canFarmersDiet) { - messages.add(getStatMessage(false, true, SubSkillType.HERBALISM_FARMERS_DIET, String.valueOf(farmersDietRank))); + 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) : "")); + + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", + greenTerraLengthEndurance) : "")); //messages.add(LocaleLoader.getString("Herbalism.Ability.GTe.Length", greenTerraLength) + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", greenTerraLengthEndurance) : "")); } if (canGreenThumbBlocks || canGreenThumbPlants) { messages.add(getStatMessage(SubSkillType.HERBALISM_GREEN_THUMB, greenThumbChance) - + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", greenThumbChanceLucky) : "")); + + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", greenThumbChanceLucky) + : "")); //messages.add(LocaleLoader.getString("Herbalism.Ability.GTh.Chance", greenThumbChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", greenThumbChanceLucky) : "")); } 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) { messages.add(getStatMessage(SubSkillType.HERBALISM_HYLIAN_LUCK, hylianLuckChance) - + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", hylianLuckChanceLucky) : "")); + + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", hylianLuckChanceLucky) + : "")); } if (canShroomThumb) { messages.add(getStatMessage(SubSkillType.HERBALISM_SHROOM_THUMB, shroomThumbChance) - + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", shroomThumbChanceLucky) : "")); + + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", shroomThumbChanceLucky) + : "")); } return messages; @@ -160,7 +187,8 @@ public class HerbalismCommand extends SkillCommand { protected List getTextComponents(Player player) { List textComponents = new ArrayList<>(); - TextComponentFactory.getSubSkillTextComponents(player, textComponents, PrimarySkillType.HERBALISM); + TextComponentFactory.getSubSkillTextComponents(player, textComponents, + PrimarySkillType.HERBALISM); return textComponents; } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/MacesCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/MacesCommand.java index 7898fabe8..e2c6e3108 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/MacesCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/MacesCommand.java @@ -1,5 +1,8 @@ package com.gmail.nossr50.commands.skills; +import static com.gmail.nossr50.datatypes.skills.SubSkillType.MACES_CRIPPLE; +import static com.gmail.nossr50.datatypes.skills.SubSkillType.MACES_MACES_LIMIT_BREAK; + import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.locale.LocaleLoader; @@ -9,14 +12,10 @@ import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.text.TextComponentFactory; -import net.kyori.adventure.text.Component; -import org.bukkit.entity.Player; - import java.util.ArrayList; import java.util.List; - -import static com.gmail.nossr50.datatypes.skills.SubSkillType.MACES_CRIPPLE; -import static com.gmail.nossr50.datatypes.skills.SubSkillType.MACES_MACES_LIMIT_BREAK; +import net.kyori.adventure.text.Component; +import org.bukkit.entity.Player; public class MacesCommand extends SkillCommand { @@ -30,19 +29,25 @@ public class MacesCommand extends SkillCommand { protected void dataCalculations(Player player, float skillValue) { if (SkillUtils.canUseSubskill(player, MACES_CRIPPLE)) { int crippleRank = RankUtils.getRank(player, MACES_CRIPPLE); - crippleLengthAgainstPlayers = String.valueOf(MacesManager.getCrippleTickDuration(true) / 20.0D); - crippleLengthAgainstMobs = String.valueOf(MacesManager.getCrippleTickDuration(false) / 20.0D); + crippleLengthAgainstPlayers = String.valueOf( + MacesManager.getCrippleTickDuration(true) / 20.0D); + crippleLengthAgainstMobs = String.valueOf( + MacesManager.getCrippleTickDuration(false) / 20.0D); - crippleChanceToApply = String.valueOf(mcMMO.p.getAdvancedConfig().getCrippleChanceToApplyOnHit(crippleRank) + "%"); - crippleChanceToApplyLucky = String.valueOf(mcMMO.p.getAdvancedConfig().getCrippleChanceToApplyOnHit(crippleRank) * 1.33); + crippleChanceToApply = + mcMMO.p.getAdvancedConfig().getCrippleChanceToApplyOnHit(crippleRank) + "%"; + crippleChanceToApplyLucky = String.valueOf( + mcMMO.p.getAdvancedConfig().getCrippleChanceToApplyOnHit(crippleRank) * 1.33); } } @Override - protected void permissionsCheck(Player player) {} + protected void permissionsCheck(Player player) { + } @Override - protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { + protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, + boolean isLucky) { final List messages = new ArrayList<>(); if (SkillUtils.canUseSubskill(player, MACES_MACES_LIMIT_BREAK)) { @@ -53,7 +58,8 @@ public class MacesCommand extends SkillCommand { if (SkillUtils.canUseSubskill(player, MACES_CRIPPLE)) { messages.add(getStatMessage(MACES_CRIPPLE, crippleChanceToApply) - + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", crippleChanceToApplyLucky) : "")); + + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", + crippleChanceToApplyLucky) : "")); messages.add(getStatMessage(true, true, MACES_CRIPPLE, crippleLengthAgainstPlayers, crippleLengthAgainstMobs)); @@ -71,7 +77,8 @@ public class MacesCommand extends SkillCommand { protected List getTextComponents(Player player) { List textComponents = new ArrayList<>(); - TextComponentFactory.getSubSkillTextComponents(player, textComponents, PrimarySkillType.MACES); + TextComponentFactory.getSubSkillTextComponents(player, textComponents, + PrimarySkillType.MACES); return textComponents; } 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 b92107e91..05af220ea 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/MiningCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/MiningCommand.java @@ -8,11 +8,10 @@ import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; -import net.kyori.adventure.text.Component; -import org.bukkit.entity.Player; - import java.util.ArrayList; import java.util.List; +import net.kyori.adventure.text.Component; +import org.bukkit.entity.Player; public class MiningCommand extends SkillCommand { private String doubleDropChance; @@ -26,7 +25,7 @@ public class MiningCommand extends SkillCommand { private int bonusTNTDrops; private double blastRadiusIncrease; private String oreBonus; -// private String debrisReduction; + // private String debrisReduction; private String blastDamageDecrease; private boolean canSuperBreaker; @@ -56,18 +55,20 @@ public class MiningCommand extends SkillCommand { // Mastery TRIPLE DROPS if (canTripleDrop) { - String[] masteryTripleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.MINING_MOTHER_LODE); + String[] masteryTripleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + SubSkillType.MINING_MOTHER_LODE); tripleDropChance = masteryTripleDropStrings[0]; tripleDropChanceLucky = masteryTripleDropStrings[1]; } - + // DOUBLE DROPS if (canDoubleDrop) { - String[] doubleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.MINING_DOUBLE_DROPS); + String[] doubleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + SubSkillType.MINING_DOUBLE_DROPS); doubleDropChance = doubleDropStrings[0]; doubleDropChanceLucky = doubleDropStrings[1]; } - + // SUPER BREAKER if (canSuperBreaker) { String[] superBreakerStrings = calculateLengthDisplayValues(player, skillValue); @@ -78,47 +79,61 @@ public class MiningCommand extends SkillCommand { @Override protected void permissionsCheck(Player player) { - canBiggerBombs = RankUtils.hasUnlockedSubskill(player, SubSkillType.MINING_BIGGER_BOMBS) && Permissions.biggerBombs(player); - canBlast = RankUtils.hasUnlockedSubskill(player, SubSkillType.MINING_BLAST_MINING) && Permissions.remoteDetonation(player); - canDemoExpert = RankUtils.hasUnlockedSubskill(player, SubSkillType.MINING_DEMOLITIONS_EXPERTISE) && Permissions.demolitionsExpertise(player); + canBiggerBombs = RankUtils.hasUnlockedSubskill(player, SubSkillType.MINING_BIGGER_BOMBS) + && Permissions.biggerBombs(player); + canBlast = RankUtils.hasUnlockedSubskill(player, SubSkillType.MINING_BLAST_MINING) + && Permissions.remoteDetonation(player); + canDemoExpert = + RankUtils.hasUnlockedSubskill(player, SubSkillType.MINING_DEMOLITIONS_EXPERTISE) + && Permissions.demolitionsExpertise(player); canDoubleDrop = Permissions.canUseSubSkill(player, SubSkillType.MINING_DOUBLE_DROPS); canTripleDrop = Permissions.canUseSubSkill(player, SubSkillType.MINING_MOTHER_LODE); - canSuperBreaker = RankUtils.hasUnlockedSubskill(player, SubSkillType.MINING_SUPER_BREAKER) && Permissions.superBreaker(player); + canSuperBreaker = RankUtils.hasUnlockedSubskill(player, SubSkillType.MINING_SUPER_BREAKER) + && Permissions.superBreaker(player); } @Override - protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { + protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, + boolean isLucky) { List messages = new ArrayList<>(); if (canBiggerBombs) { - messages.add(getStatMessage(true, true, SubSkillType.MINING_BLAST_MINING, String.valueOf(blastRadiusIncrease))); + 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, bonusTNTDrops))); + 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, 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) { - messages.add(getStatMessage(SubSkillType.MINING_DEMOLITIONS_EXPERTISE, blastDamageDecrease)); + + if (canDemoExpert) { + messages.add( + getStatMessage(SubSkillType.MINING_DEMOLITIONS_EXPERTISE, blastDamageDecrease)); //messages.add(LocaleLoader.getString("Mining.Effect.Decrease", blastDamageDecrease)); } if (canDoubleDrop) { messages.add(getStatMessage(SubSkillType.MINING_DOUBLE_DROPS, doubleDropChance) - + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", doubleDropChanceLucky) : "")); + + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", doubleDropChanceLucky) + : "")); //messages.add(LocaleLoader.getString("Mining.Effect.DropChance", doubleDropChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", doubleDropChanceLucky) : "")); } if (canTripleDrop) { messages.add(getStatMessage(SubSkillType.MINING_MOTHER_LODE, tripleDropChance) - + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", tripleDropChanceLucky) : "")); + + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", tripleDropChanceLucky) + : "")); } if (canSuperBreaker) { messages.add(getStatMessage(SubSkillType.MINING_SUPER_BREAKER, superBreakerLength) - + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", superBreakerLengthEndurance) : "")); + + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", + superBreakerLengthEndurance) : "")); //messages.add(LocaleLoader.getString("Mining.Ability.Length", superBreakerLength) + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", superBreakerLengthEndurance) : "")); } @@ -129,7 +144,8 @@ public class MiningCommand extends SkillCommand { protected List getTextComponents(Player player) { List textComponents = new ArrayList<>(); - TextComponentFactory.getSubSkillTextComponents(player, textComponents, PrimarySkillType.MINING); + TextComponentFactory.getSubSkillTextComponents(player, textComponents, + PrimarySkillType.MINING); return textComponents; } 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 795f4005c..6300ee0b5 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/MmoInfoCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/MmoInfoCommand.java @@ -6,6 +6,8 @@ import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.text.TextComponentFactory; import com.google.common.collect.ImmutableList; +import java.util.ArrayList; +import java.util.List; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabExecutor; @@ -13,34 +15,34 @@ import org.bukkit.entity.Player; import org.bukkit.util.StringUtil; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.List; - /** * This is the command that retrieves data about skills from in-game sources */ public class MmoInfoCommand implements TabExecutor { @Override - public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String s, String[] args) { + public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, + @NotNull String s, String[] args) { /* * Only allow players to use this command */ if (commandSender instanceof Player player) { - if (args == null || args.length < 1 || args[0] == null || args[0].isEmpty()) + if (args == null || args.length < 1 || args[0] == null || args[0].isEmpty()) { return false; + } if (Permissions.mmoinfo(player)) { - 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.SubSkillHeader", "???")); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.DetailsHeader")); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.Mystery")); return true; } final SubSkillType subSkillType = matchSubSkill(args[0]); - if (subSkillType != null) { + if (subSkillType != null) { displayInfo(player, subSkillType); } else { //Not a real skill @@ -54,28 +56,34 @@ public class MmoInfoCommand implements TabExecutor { } public SubSkillType matchSubSkill(String name) { - for(SubSkillType subSkillType : SubSkillType.values()) { + for (SubSkillType subSkillType : SubSkillType.values()) { if (subSkillType.getNiceNameNoSpaces(subSkillType).equalsIgnoreCase(name) - || subSkillType.name().equalsIgnoreCase(name)) + || subSkillType.name().equalsIgnoreCase(name)) { return subSkillType; + } } return null; } @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, String[] args) { if (args.length == 1) { - return StringUtil.copyPartialMatches(args[0], mcMMO.p.getSkillTools().EXACT_SUBSKILL_NAMES, new ArrayList<>(mcMMO.p.getSkillTools().EXACT_SUBSKILL_NAMES.size())); + return StringUtil.copyPartialMatches(args[0], + mcMMO.p.getSkillTools().EXACT_SUBSKILL_NAMES, + new ArrayList<>(mcMMO.p.getSkillTools().EXACT_SUBSKILL_NAMES.size())); } return ImmutableList.of(); } private void displayInfo(Player player, SubSkillType subSkillType) { player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.Header")); - player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.SubSkillHeader", subSkillType.getLocaleName())); + player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.SubSkillHeader", + subSkillType.getLocaleName())); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.DetailsHeader")); //Send Player Wiki Link - TextComponentFactory.sendPlayerSubSkillWikiLink(player, subSkillType.getLocaleName(), subSkillType); + TextComponentFactory.sendPlayerSubSkillWikiLink(player, subSkillType.getLocaleName(), + subSkillType); } } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/PowerLevelCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/PowerLevelCommand.java index 639275b55..579b1e419 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/PowerLevelCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/PowerLevelCommand.java @@ -28,13 +28,16 @@ public class PowerLevelCommand extends BaseCommand { public void processCommand(String[] args) { BukkitCommandIssuer bukkitCommandIssuer = (BukkitCommandIssuer) getCurrentCommandIssuer(); Player player = bukkitCommandIssuer.getPlayer(); - McMMOPlayer mmoPlayer = UserManager.getPlayer(player); //Should never be null at this point because its caught in an ACF validation + final McMMOPlayer mmoPlayer = UserManager.getPlayer( + player); //Should never be null at this point because its caught in an ACF validation if (mmoPlayer == null) { return; } int powerLevel = mmoPlayer.getPowerLevel(); - mmoPlayer.getPlayer().sendMessage(ChatColor.DARK_AQUA + "Your " + ChatColor.GOLD + "[mcMMO]" + ChatColor.DARK_AQUA + " power level is: " + ChatColor.GREEN + powerLevel); + mmoPlayer.getPlayer().sendMessage( + ChatColor.DARK_AQUA + "Your " + ChatColor.GOLD + "[mcMMO]" + ChatColor.DARK_AQUA + + " power level is: " + ChatColor.GREEN + powerLevel); } } 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 af23a880d..e56a5e879 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/RepairCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/RepairCommand.java @@ -13,13 +13,12 @@ import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; +import java.util.ArrayList; +import java.util.List; import net.kyori.adventure.text.Component; import org.bukkit.Material; import org.bukkit.entity.Player; -import java.util.ArrayList; -import java.util.List; - public class RepairCommand extends SkillCommand { private String repairMasteryBonus; private String superRepairChance; @@ -49,10 +48,14 @@ public class RepairCommand extends SkillCommand { @Override protected void dataCalculations(Player player, float skillValue) { // We're using pickaxes here, not the best but it works - Repairable diamondRepairable = mcMMO.getRepairableManager().getRepairable(Material.DIAMOND_PICKAXE); - Repairable goldRepairable = mcMMO.getRepairableManager().getRepairable(Material.GOLDEN_PICKAXE); - Repairable ironRepairable = mcMMO.getRepairableManager().getRepairable(Material.IRON_PICKAXE); - Repairable stoneRepairable = mcMMO.getRepairableManager().getRepairable(Material.STONE_PICKAXE); + Repairable diamondRepairable = mcMMO.getRepairableManager() + .getRepairable(Material.DIAMOND_PICKAXE); + Repairable goldRepairable = mcMMO.getRepairableManager() + .getRepairable(Material.GOLDEN_PICKAXE); + Repairable ironRepairable = mcMMO.getRepairableManager() + .getRepairable(Material.IRON_PICKAXE); + Repairable stoneRepairable = mcMMO.getRepairableManager() + .getRepairable(Material.STONE_PICKAXE); // TODO: This isn't really accurate - if they don't have pickaxes loaded it doesn't always mean the repair level is 0 diamondLevel = (diamondRepairable == null) ? 0 : diamondRepairable.getMinimumLevel(); @@ -62,12 +65,15 @@ public class RepairCommand extends SkillCommand { // REPAIR MASTERY if (canMasterRepair) { - repairMasteryBonus = percent.format(Math.min(((Repair.repairMasteryMaxBonus / Repair.repairMasteryMaxBonusLevel) * skillValue), Repair.repairMasteryMaxBonus) / 100D); + repairMasteryBonus = percent.format(Math.min( + ((Repair.repairMasteryMaxBonus / Repair.repairMasteryMaxBonusLevel) + * skillValue), Repair.repairMasteryMaxBonus) / 100D); } // SUPER REPAIR if (canSuperRepair) { - String[] superRepairStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.REPAIR_SUPER_REPAIR); + String[] superRepairStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + SubSkillType.REPAIR_SUPER_REPAIR); superRepairChance = superRepairStrings[0]; superRepairChanceLucky = superRepairStrings[1]; } @@ -85,11 +91,13 @@ public class RepairCommand extends SkillCommand { canRepairString = Permissions.repairMaterialType(player, MaterialType.STRING); canRepairLeather = Permissions.repairMaterialType(player, MaterialType.LEATHER); canRepairWood = Permissions.repairMaterialType(player, MaterialType.WOOD); - arcaneBypass = (Permissions.arcaneBypass(player) || Permissions.hasRepairEnchantBypassPerk(player)); + arcaneBypass = (Permissions.arcaneBypass(player) || Permissions.hasRepairEnchantBypassPerk( + player)); } @Override - protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { + protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, + boolean isLucky) { List messages = new ArrayList<>(); if (canArcaneForge) { @@ -103,17 +111,20 @@ public class RepairCommand extends SkillCommand { if (ArcaneForging.arcaneForgingEnchantLoss || ArcaneForging.arcaneForgingDowngrades) { messages.add(getStatMessage(true, true, SubSkillType.REPAIR_ARCANE_FORGING, String.valueOf(arcaneBypass ? 100 : repairManager.getKeepEnchantChance()), - String.valueOf(arcaneBypass ? 0 : repairManager.getDowngradeEnchantChance()))); //Jesus those parentheses + String.valueOf(arcaneBypass ? 0 + : repairManager.getDowngradeEnchantChance()))); //Jesus those parentheses } } - + if (canMasterRepair) { - messages.add(getStatMessage(false, true, SubSkillType.REPAIR_REPAIR_MASTERY, repairMasteryBonus)); + messages.add(getStatMessage(false, true, SubSkillType.REPAIR_REPAIR_MASTERY, + repairMasteryBonus)); } if (canSuperRepair) { messages.add(getStatMessage(SubSkillType.REPAIR_SUPER_REPAIR, superRepairChance) - + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", superRepairChanceLucky) : "")); + + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", superRepairChanceLucky) + : "")); } return messages; @@ -123,7 +134,8 @@ public class RepairCommand extends SkillCommand { protected List getTextComponents(Player player) { List textComponents = new ArrayList<>(); - TextComponentFactory.getSubSkillTextComponents(player, textComponents, PrimarySkillType.REPAIR); + TextComponentFactory.getSubSkillTextComponents(player, textComponents, + PrimarySkillType.REPAIR); return textComponents; } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/SalvageCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/SalvageCommand.java index 646510334..29a8cd6c0 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/SalvageCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/SalvageCommand.java @@ -8,11 +8,10 @@ import com.gmail.nossr50.skills.salvage.SalvageManager; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; -import net.kyori.adventure.text.Component; -import org.bukkit.entity.Player; - import java.util.ArrayList; import java.util.List; +import net.kyori.adventure.text.Component; +import org.bukkit.entity.Player; public class SalvageCommand extends SkillCommand { private boolean canScrapCollector; @@ -30,12 +29,14 @@ public class SalvageCommand extends SkillCommand { @Override protected void permissionsCheck(Player player) { - canScrapCollector = Permissions.canUseSubSkill(player, SubSkillType.SALVAGE_SCRAP_COLLECTOR); + canScrapCollector = Permissions.canUseSubSkill(player, + SubSkillType.SALVAGE_SCRAP_COLLECTOR); canArcaneSalvage = Permissions.canUseSubSkill(player, SubSkillType.SALVAGE_ARCANE_SALVAGE); } @Override - protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { + protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, + boolean isLucky) { List messages = new ArrayList<>(); SalvageManager salvageManager = mmoPlayer.getSalvageManager(); @@ -52,11 +53,15 @@ public class SalvageCommand extends SkillCommand { String.valueOf(RankUtils.getHighestRank(SubSkillType.SALVAGE_ARCANE_SALVAGE)))); if (Salvage.arcaneSalvageEnchantLoss) { - messages.add(LocaleLoader.getString("Ability.Generic.Template", LocaleLoader.getString("Salvage.Arcane.ExtractFull"), percent.format(salvageManager.getExtractFullEnchantChance() / 100))); + messages.add(LocaleLoader.getString("Ability.Generic.Template", + LocaleLoader.getString("Salvage.Arcane.ExtractFull"), + percent.format(salvageManager.getExtractFullEnchantChance() / 100))); } if (Salvage.arcaneSalvageDowngrades) { - messages.add(LocaleLoader.getString("Ability.Generic.Template", LocaleLoader.getString("Salvage.Arcane.ExtractPartial"), percent.format(salvageManager.getExtractPartialEnchantChance() / 100))); + messages.add(LocaleLoader.getString("Ability.Generic.Template", + LocaleLoader.getString("Salvage.Arcane.ExtractPartial"), + percent.format(salvageManager.getExtractPartialEnchantChance() / 100))); } } @@ -67,7 +72,8 @@ public class SalvageCommand extends SkillCommand { protected List getTextComponents(Player player) { List textComponents = new ArrayList<>(); - TextComponentFactory.getSubSkillTextComponents(player, textComponents, PrimarySkillType.SALVAGE); + TextComponentFactory.getSubSkillTextComponents(player, textComponents, + PrimarySkillType.SALVAGE); return textComponents; } 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 de0fe1035..87ef5a4a9 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/SkillCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/SkillCommand.java @@ -15,6 +15,11 @@ import com.gmail.nossr50.util.skills.SkillTools; import com.gmail.nossr50.util.text.StringUtils; import com.gmail.nossr50.util.text.TextComponentFactory; import com.google.common.collect.ImmutableList; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; import net.kyori.adventure.text.Component; import net.md_5.bungee.api.ChatColor; import org.bukkit.command.Command; @@ -24,19 +29,15 @@ import org.bukkit.command.TabExecutor; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - public abstract class SkillCommand implements TabExecutor { public static final String ABILITY_GENERIC_TEMPLATE_CUSTOM = "Ability.Generic.Template.Custom"; public static final String ABILITY_GENERIC_TEMPLATE = "Ability.Generic.Template"; protected PrimarySkillType skill; - protected DecimalFormat percent = new DecimalFormat("##0.00%", DecimalFormatSymbols.getInstance(Locale.US)); - protected DecimalFormat decimal = new DecimalFormat("##0.00", DecimalFormatSymbols.getInstance(Locale.US)); + protected DecimalFormat percent = new DecimalFormat("##0.00%", + DecimalFormatSymbols.getInstance(Locale.US)); + protected DecimalFormat decimal = new DecimalFormat("##0.00", + DecimalFormatSymbols.getInstance(Locale.US)); protected McMMOPlayer mmoPlayer; private final CommandExecutor skillGuideCommand; @@ -47,7 +48,8 @@ public abstract class SkillCommand implements TabExecutor { } @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { if (CommandUtils.noConsoleUsage(sender)) { return true; } @@ -56,7 +58,7 @@ public abstract class SkillCommand implements TabExecutor { return true; } - Player player = (Player) sender; + final Player player = (Player) sender; mmoPlayer = UserManager.getPlayer(player); if (mmoPlayer == null) { @@ -70,10 +72,11 @@ public abstract class SkillCommand implements TabExecutor { float skillValue = mmoPlayer.getSkillLevel(skill); //Send the players a few blank lines to make finding the top of the skill command easier - if (mcMMO.p.getAdvancedConfig().doesSkillCommandSendBlankLines()) + if (mcMMO.p.getAdvancedConfig().doesSkillCommandSendBlankLines()) { for (int i = 0; i < 2; i++) { player.sendMessage(""); } + } permissionsCheck(player); dataCalculations(player, skillValue); @@ -85,7 +88,8 @@ public abstract class SkillCommand implements TabExecutor { List subskillTextComponents = getTextComponents(player); //Subskills Header - player.sendMessage(LocaleLoader.getString("Skills.Overhaul.Header", LocaleLoader.getString("Effects.SubSkills.Overhaul"))); + player.sendMessage(LocaleLoader.getString("Skills.Overhaul.Header", + LocaleLoader.getString("Effects.SubSkills.Overhaul"))); //Send JSON text components @@ -100,20 +104,19 @@ public abstract class SkillCommand implements TabExecutor { //Header - //Link Header if (mcMMO.p.getGeneralConfig().getUrlLinksEnabled()) { player.sendMessage(LocaleLoader.getString("Overhaul.mcMMO.Header")); TextComponentFactory.sendPlayerUrlHeader(player); } - - if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled() && mcMMO.p.getGeneralConfig().getSkillUseBoard()) { + if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled() && mcMMO.p.getGeneralConfig() + .getSkillUseBoard()) { ScoreboardManager.enablePlayerSkillScoreboard(player, skill); } return true; - } else if ("keep".equals(args[0].toLowerCase())) { + } else if ("keep".equalsIgnoreCase(args[0])) { if (!mcMMO.p.getGeneralConfig().getAllowKeepBoard() || !mcMMO.p.getGeneralConfig().getScoreboardsEnabled() || !mcMMO.p.getGeneralConfig().getSkillUseBoard()) { @@ -130,11 +133,13 @@ public abstract class SkillCommand implements TabExecutor { return skillGuideCommand.onCommand(sender, command, label, args); } - private void getStatMessages(Player player, boolean isLucky, boolean hasEndurance, float skillValue) { + private void getStatMessages(Player player, boolean isLucky, boolean hasEndurance, + float skillValue) { List statsMessages = statsDisplay(player, skillValue, hasEndurance, isLucky); if (!statsMessages.isEmpty()) { - player.sendMessage(LocaleLoader.getString("Skills.Overhaul.Header", LocaleLoader.getString("Commands.Stats.Self.Overhaul"))); + player.sendMessage(LocaleLoader.getString("Skills.Overhaul.Header", + LocaleLoader.getString("Commands.Stats.Self.Overhaul"))); for (String message : statsMessages) { player.sendMessage(message); @@ -147,7 +152,8 @@ public abstract class SkillCommand implements TabExecutor { skillName.toLowerCase(Locale.ENGLISH))); } - private void sendSkillCommandHeader(String skillName, Player player, McMMOPlayer mcMMOPlayer, int skillValue) { + private void sendSkillCommandHeader(String skillName, Player player, McMMOPlayer mmoPlayer, + int skillValue) { // send header player.sendMessage(LocaleLoader.getString("Skills.Overhaul.Header", skillName)); @@ -157,10 +163,13 @@ public abstract class SkillCommand implements TabExecutor { */ //XP GAIN METHOD - player.sendMessage(LocaleLoader.getString("Commands.XPGain.Overhaul", LocaleLoader.getString("Commands.XPGain." + StringUtils.getCapitalized(skill.toString())))); + player.sendMessage(LocaleLoader.getString("Commands.XPGain.Overhaul", + LocaleLoader.getString( + "Commands.XPGain." + StringUtils.getCapitalized(skill.toString())))); //LEVEL - player.sendMessage(LocaleLoader.getString("Effects.Level.Overhaul", skillValue, mcMMOPlayer.getSkillXpLevel(skill), mcMMOPlayer.getXpToLevel(skill))); + player.sendMessage(LocaleLoader.getString("Effects.Level.Overhaul", skillValue, + mmoPlayer.getSkillXpLevel(skill), mmoPlayer.getXpToLevel(skill))); } else { /* @@ -169,29 +178,36 @@ public abstract class SkillCommand implements TabExecutor { var parents = mcMMO.p.getSkillTools().getChildSkillParents(skill); //TODO: Add JSON here - /*player.sendMessage(parent.getName() + " - " + LocaleLoader.getString("Effects.Level.Overhaul", mcMMOPlayer.getSkillLevel(parent), mcMMOPlayer.getSkillXpLevel(parent), mcMMOPlayer.getXpToLevel(parent)))*/ + /*player.sendMessage(parent.getName() + " - " + LocaleLoader.getString("Effects.Level.Overhaul", mmoPlayer.getSkillLevel(parent), mmoPlayer.getSkillXpLevel(parent), mmoPlayer.getXpToLevel(parent)))*/ ArrayList parentList = new ArrayList<>(parents); StringBuilder parentMessage = new StringBuilder(); - for(int i = 0; i < parentList.size(); i++) { - if (i+1 < parentList.size()) { - parentMessage.append(LocaleLoader.getString("Effects.Child.ParentList", mcMMO.p.getSkillTools().getLocalizedSkillName(parentList.get(i)), mcMMOPlayer.getSkillLevel(parentList.get(i)))); + for (int i = 0; i < parentList.size(); i++) { + if (i + 1 < parentList.size()) { + parentMessage.append(LocaleLoader.getString("Effects.Child.ParentList", + mcMMO.p.getSkillTools().getLocalizedSkillName(parentList.get(i)), + mmoPlayer.getSkillLevel(parentList.get(i)))); parentMessage.append(ChatColor.GRAY).append(", "); } else { - parentMessage.append(LocaleLoader.getString("Effects.Child.ParentList", mcMMO.p.getSkillTools().getLocalizedSkillName(parentList.get(i)), mcMMOPlayer.getSkillLevel(parentList.get(i)))); + parentMessage.append(LocaleLoader.getString("Effects.Child.ParentList", + mcMMO.p.getSkillTools().getLocalizedSkillName(parentList.get(i)), + mmoPlayer.getSkillLevel(parentList.get(i)))); } } //XP GAIN METHOD - player.sendMessage(LocaleLoader.getString("Commands.XPGain.Overhaul", LocaleLoader.getString("Commands.XPGain.Child"))); + player.sendMessage(LocaleLoader.getString("Commands.XPGain.Overhaul", + LocaleLoader.getString("Commands.XPGain.Child"))); - player.sendMessage(LocaleLoader.getString("Effects.Child.Overhaul", skillValue, parentMessage.toString())); + player.sendMessage(LocaleLoader.getString("Effects.Child.Overhaul", skillValue, + parentMessage.toString())); } } @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, String[] args) { if (args.length == 1) { return ImmutableList.of("?", "keep"); } @@ -203,7 +219,8 @@ public abstract class SkillCommand implements TabExecutor { } protected String[] calculateLengthDisplayValues(Player player, float skillValue) { - int maxLength = mcMMO.p.getSkillTools().getSuperAbilityMaxLength(mcMMO.p.getSkillTools().getSuperAbility(skill)); + int maxLength = mcMMO.p.getSkillTools() + .getSuperAbilityMaxLength(mcMMO.p.getSkillTools().getSuperAbility(skill)); int abilityLengthVar = mcMMO.p.getAdvancedConfig().getAbilityLength(); int abilityLengthCap = mcMMO.p.getAdvancedConfig().getAbilityLengthCap(); @@ -221,7 +238,7 @@ 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) { @@ -229,18 +246,20 @@ public abstract class SkillCommand implements TabExecutor { } protected String getStatMessage(boolean isExtra, boolean isCustom, - @NotNull SubSkillType subSkillType, String... vars) { - final String templateKey = isCustom ? ABILITY_GENERIC_TEMPLATE_CUSTOM : ABILITY_GENERIC_TEMPLATE; + @NotNull SubSkillType subSkillType, String... vars) { + final String templateKey = + isCustom ? ABILITY_GENERIC_TEMPLATE_CUSTOM : ABILITY_GENERIC_TEMPLATE; final String statDescriptionKey = !isExtra ? subSkillType.getLocaleKeyStatDescription() : subSkillType.getLocaleKeyStatExtraDescription(); if (isCustom) { - return LocaleLoader.getString(templateKey, LocaleLoader.getString(statDescriptionKey, vars)); + return LocaleLoader.getString(templateKey, + LocaleLoader.getString(statDescriptionKey, vars)); } else { final String[] mergedList = NotificationManager.addItemToFirstPositionOfArray( - LocaleLoader.getString(statDescriptionKey), vars); + LocaleLoader.getString(statDescriptionKey), vars); return LocaleLoader.getString(templateKey, mergedList); } } @@ -257,7 +276,8 @@ public abstract class SkillCommand implements TabExecutor { protected abstract void permissionsCheck(Player player); - protected abstract List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky); + protected abstract List statsDisplay(Player player, float skillValue, + boolean hasEndurance, boolean isLucky); protected abstract List getTextComponents(Player player); 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 6b9342598..13f372061 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/SkillGuideCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/SkillGuideCommand.java @@ -4,14 +4,13 @@ import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.text.StringUtils; +import java.util.ArrayList; +import java.util.Arrays; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.Arrays; - public class SkillGuideCommand implements CommandExecutor { private final String header; private final ArrayList guide; @@ -19,12 +18,14 @@ public class SkillGuideCommand implements CommandExecutor { private final String invalidPage = LocaleLoader.getString("Guides.Page.Invalid"); public SkillGuideCommand(PrimarySkillType skill) { - header = LocaleLoader.getString("Guides.Header", mcMMO.p.getSkillTools().getLocalizedSkillName(skill)); + header = LocaleLoader.getString("Guides.Header", + mcMMO.p.getSkillTools().getLocalizedSkillName(skill)); guide = getGuide(skill); } @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String label, String[] args) { switch (args.length) { case 1: if (!args[0].equals("?")) { @@ -45,7 +46,8 @@ public class SkillGuideCommand implements CommandExecutor { int pageNumber = Integer.parseInt(args[1]); if (pageNumber > totalPages || pageNumber <= 0) { - sender.sendMessage(LocaleLoader.getString("Guides.Page.OutOfRange", totalPages)); + sender.sendMessage( + LocaleLoader.getString("Guides.Page.OutOfRange", totalPages)); return true; } @@ -90,7 +92,9 @@ public class SkillGuideCommand implements CommandExecutor { ArrayList guide = new ArrayList<>(); for (int i = 0; i < 10; i++) { - String[] section = LocaleLoader.getString("Guides." + StringUtils.getCapitalized(skill.toString()) + ".Section." + i).split("\n"); + String[] section = LocaleLoader.getString( + "Guides." + StringUtils.getCapitalized(skill.toString()) + ".Section." + i) + .split("\n"); if (section[0].startsWith("!")) { break; 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 0ca68a964..5b2eec7a1 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/SmeltingCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/SmeltingCommand.java @@ -7,11 +7,10 @@ import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; -import net.kyori.adventure.text.Component; -import org.bukkit.entity.Player; - import java.util.ArrayList; import java.util.List; +import net.kyori.adventure.text.Component; +import org.bukkit.entity.Player; public class SmeltingCommand extends SkillCommand { private String burnTimeModifier; @@ -33,7 +32,8 @@ public class SmeltingCommand extends SkillCommand { protected void dataCalculations(Player player, float skillValue) { // FUEL EFFICIENCY if (canFuelEfficiency) { - burnTimeModifier = String.valueOf(mmoPlayer.getSmeltingManager().getFuelEfficiencyMultiplier()); + burnTimeModifier = String.valueOf( + mmoPlayer.getSmeltingManager().getFuelEfficiencyMultiplier()); } // FLUX MINING @@ -42,10 +42,11 @@ public class SmeltingCommand extends SkillCommand { str_fluxMiningChance = fluxMiningStrings[0]; str_fluxMiningChanceLucky = fluxMiningStrings[1]; }*/ - + // SECOND SMELT if (canSecondSmelt) { - String[] secondSmeltStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.SMELTING_SECOND_SMELT); + String[] secondSmeltStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + SubSkillType.SMELTING_SECOND_SMELT); str_secondSmeltChance = secondSmeltStrings[0]; str_secondSmeltChanceLucky = secondSmeltStrings[1]; } @@ -53,14 +54,18 @@ public class SmeltingCommand extends SkillCommand { @Override protected void permissionsCheck(Player player) { - canFuelEfficiency = Permissions.canUseSubSkill(player, SubSkillType.SMELTING_FUEL_EFFICIENCY); + canFuelEfficiency = Permissions.canUseSubSkill(player, + SubSkillType.SMELTING_FUEL_EFFICIENCY); canSecondSmelt = Permissions.canUseSubSkill(player, SubSkillType.SMELTING_SECOND_SMELT); //canFluxMine = canUseSubskill(player, SubSkillType.SMELTING_FLUX_MINING); - canUnderstandTheArt = Permissions.vanillaXpBoost(player, skill) && RankUtils.hasUnlockedSubskill(player, SubSkillType.SMELTING_UNDERSTANDING_THE_ART); + canUnderstandTheArt = + Permissions.vanillaXpBoost(player, skill) && RankUtils.hasUnlockedSubskill(player, + SubSkillType.SMELTING_UNDERSTANDING_THE_ART); } @Override - protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { + protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, + boolean isLucky) { List messages = new ArrayList<>(); /*if (canFluxMine) { @@ -68,14 +73,16 @@ 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)); + messages.add(getStatMessage(false, true, SubSkillType.SMELTING_FUEL_EFFICIENCY, + burnTimeModifier)); } if (canSecondSmelt) { messages.add(getStatMessage(SubSkillType.SMELTING_SECOND_SMELT, str_secondSmeltChance) - + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", str_secondSmeltChanceLucky) : "")); + + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", + str_secondSmeltChanceLucky) : "")); } if (canUnderstandTheArt) { @@ -90,7 +97,8 @@ public class SmeltingCommand extends SkillCommand { protected List getTextComponents(Player player) { List textComponents = new ArrayList<>(); - TextComponentFactory.getSubSkillTextComponents(player, textComponents, PrimarySkillType.SMELTING); + TextComponentFactory.getSubSkillTextComponents(player, textComponents, + PrimarySkillType.SMELTING); return textComponents; } 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 c44af71ef..54359c9df 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/SwordsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/SwordsCommand.java @@ -10,11 +10,10 @@ import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.text.TextComponentFactory; -import net.kyori.adventure.text.Component; -import org.bukkit.entity.Player; - import java.util.ArrayList; import java.util.List; +import net.kyori.adventure.text.Component; +import org.bukkit.entity.Player; public class SwordsCommand extends SkillCommand { private String counterChance; @@ -38,7 +37,8 @@ public class SwordsCommand extends SkillCommand { protected void dataCalculations(Player player, float skillValue) { // SWORDS_COUNTER_ATTACK if (canCounter) { - String[] counterStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.SWORDS_COUNTER_ATTACK); + String[] counterStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + SubSkillType.SWORDS_COUNTER_ATTACK); counterChance = counterStrings[0]; counterChanceLucky = counterStrings[1]; } @@ -46,19 +46,27 @@ public class SwordsCommand extends SkillCommand { // SWORDS_RUPTURE if (canRupture) { int ruptureRank = RankUtils.getRank(player, SubSkillType.SWORDS_RUPTURE); - ruptureLengthSecondsAgainstPlayers = String.valueOf(mcMMO.p.getAdvancedConfig().getRuptureDurationSeconds(true)); - ruptureLengthSecondsAgainstMobs = String.valueOf(mcMMO.p.getAdvancedConfig().getRuptureDurationSeconds(false)); + ruptureLengthSecondsAgainstPlayers = String.valueOf( + mcMMO.p.getAdvancedConfig().getRuptureDurationSeconds(true)); + ruptureLengthSecondsAgainstMobs = String.valueOf( + mcMMO.p.getAdvancedConfig().getRuptureDurationSeconds(false)); - rupturePureTickDamageAgainstPlayers = String.valueOf(mcMMO.p.getAdvancedConfig().getRuptureTickDamage(true, ruptureRank)); - rupturePureTickDamageAgainstMobs = String.valueOf(mcMMO.p.getAdvancedConfig().getRuptureTickDamage(false, ruptureRank)); + rupturePureTickDamageAgainstPlayers = String.valueOf( + mcMMO.p.getAdvancedConfig().getRuptureTickDamage(true, ruptureRank)); + rupturePureTickDamageAgainstMobs = String.valueOf( + mcMMO.p.getAdvancedConfig().getRuptureTickDamage(false, ruptureRank)); - ruptureExplosionDamageAgainstPlayers = String.valueOf(mcMMO.p.getAdvancedConfig().getRuptureExplosionDamage(true, ruptureRank)); - ruptureExplosionDamageAgainstMobs = String.valueOf(mcMMO.p.getAdvancedConfig().getRuptureExplosionDamage(false, ruptureRank)); + ruptureExplosionDamageAgainstPlayers = String.valueOf( + mcMMO.p.getAdvancedConfig().getRuptureExplosionDamage(true, ruptureRank)); + ruptureExplosionDamageAgainstMobs = String.valueOf( + mcMMO.p.getAdvancedConfig().getRuptureExplosionDamage(false, ruptureRank)); - ruptureChanceToApply = String.valueOf(mcMMO.p.getAdvancedConfig().getRuptureChanceToApplyOnHit(ruptureRank) + "%"); - ruptureChanceToApplyLucky = String.valueOf(mcMMO.p.getAdvancedConfig().getRuptureChanceToApplyOnHit(ruptureRank) * 1.33); + ruptureChanceToApply = + mcMMO.p.getAdvancedConfig().getRuptureChanceToApplyOnHit(ruptureRank) + "%"; + ruptureChanceToApplyLucky = String.valueOf( + mcMMO.p.getAdvancedConfig().getRuptureChanceToApplyOnHit(ruptureRank) * 1.33); } - + // SERRATED STRIKES if (canSerratedStrike) { String[] serratedStrikesStrings = calculateLengthDisplayValues(player, skillValue); @@ -71,26 +79,32 @@ public class SwordsCommand extends SkillCommand { protected void permissionsCheck(Player player) { canRupture = SkillUtils.canUseSubskill(player, SubSkillType.SWORDS_RUPTURE); canCounter = SkillUtils.canUseSubskill(player, SubSkillType.SWORDS_COUNTER_ATTACK); - canSerratedStrike = RankUtils.hasUnlockedSubskill(player, SubSkillType.SWORDS_SERRATED_STRIKES) && Permissions.serratedStrikes(player); + canSerratedStrike = + RankUtils.hasUnlockedSubskill(player, SubSkillType.SWORDS_SERRATED_STRIKES) + && Permissions.serratedStrikes(player); } @Override - protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { + protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, + boolean isLucky) { List messages = new ArrayList<>(); if (canCounter) { messages.add(getStatMessage(SubSkillType.SWORDS_COUNTER_ATTACK, counterChance) - + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", counterChanceLucky) : "")); + + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", counterChanceLucky) + : "")); } if (canRupture) { messages.add(getStatMessage(SubSkillType.SWORDS_RUPTURE, ruptureChanceToApply) - + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", ruptureChanceToApplyLucky) : "")); + + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", + ruptureChanceToApplyLucky) : "")); messages.add(getStatMessage(true, true, SubSkillType.SWORDS_RUPTURE, ruptureLengthSecondsAgainstPlayers, ruptureLengthSecondsAgainstMobs)); - messages.add(LocaleLoader.getString("Swords.SubSkill.Rupture.Stat.TickDamage", rupturePureTickDamageAgainstPlayers, rupturePureTickDamageAgainstMobs)); + messages.add(LocaleLoader.getString("Swords.SubSkill.Rupture.Stat.TickDamage", + rupturePureTickDamageAgainstPlayers, rupturePureTickDamageAgainstMobs)); // messages.add(LocaleLoader.getString("Swords.SubSkill.Rupture.Stat.ExplosionDamage", ruptureExplosionDamageAgainstPlayers, ruptureExplosionDamageAgainstMobs)); messages.add(LocaleLoader.getString("Swords.Combat.Rupture.Note.Update.One")); @@ -98,7 +112,8 @@ public class SwordsCommand extends SkillCommand { if (canSerratedStrike) { messages.add(getStatMessage(SubSkillType.SWORDS_SERRATED_STRIKES, serratedStrikesLength) - + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", serratedStrikesLengthEndurance) : "")); + + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", + serratedStrikesLengthEndurance) : "")); } if (SkillUtils.canUseSubskill(player, SubSkillType.SWORDS_STAB)) { @@ -108,7 +123,8 @@ public class SwordsCommand extends SkillCommand { if (SkillUtils.canUseSubskill(player, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK)) { messages.add(getStatMessage(SubSkillType.SWORDS_SWORDS_LIMIT_BREAK, - String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK, 1000)))); + String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, + SubSkillType.SWORDS_SWORDS_LIMIT_BREAK, 1000)))); } return messages; @@ -118,7 +134,8 @@ public class SwordsCommand extends SkillCommand { protected List getTextComponents(Player player) { List textComponents = new ArrayList<>(); - TextComponentFactory.getSubSkillTextComponents(player, textComponents, PrimarySkillType.SWORDS); + TextComponentFactory.getSubSkillTextComponents(player, textComponents, + PrimarySkillType.SWORDS); return textComponents; } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/TamingCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/TamingCommand.java index 12430fc02..a7db4d82c 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/TamingCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/TamingCommand.java @@ -7,13 +7,12 @@ import com.gmail.nossr50.skills.taming.Taming; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.text.TextComponentFactory; +import java.util.ArrayList; +import java.util.List; import net.kyori.adventure.text.Component; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; -import java.util.ArrayList; -import java.util.List; - public class TamingCommand extends SkillCommand { private String goreChance; private String goreChanceLucky; @@ -35,7 +34,8 @@ public class TamingCommand extends SkillCommand { @Override protected void dataCalculations(Player player, float skillValue) { if (canGore) { - String[] goreStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.TAMING_GORE); + String[] goreStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + SubSkillType.TAMING_GORE); goreChance = goreStrings[0]; goreChanceLucky = goreStrings[1]; } @@ -44,8 +44,12 @@ public class TamingCommand extends SkillCommand { @Override protected void permissionsCheck(Player player) { canBeastLore = Permissions.canUseSubSkill(player, SubSkillType.TAMING_BEAST_LORE); - canCallWild = Permissions.callOfTheWild(player, EntityType.HORSE) || Permissions.callOfTheWild(player, EntityType.WOLF) || Permissions.callOfTheWild(player, EntityType.OCELOT); - canEnvironmentallyAware = Permissions.canUseSubSkill(player, SubSkillType.TAMING_ENVIRONMENTALLY_AWARE); + canCallWild = + Permissions.callOfTheWild(player, EntityType.HORSE) || Permissions.callOfTheWild( + player, EntityType.WOLF) || Permissions.callOfTheWild(player, + EntityType.OCELOT); + canEnvironmentallyAware = Permissions.canUseSubSkill(player, + SubSkillType.TAMING_ENVIRONMENTALLY_AWARE); canFastFood = Permissions.canUseSubSkill(player, SubSkillType.TAMING_FAST_FOOD_SERVICE); canGore = Permissions.canUseSubSkill(player, SubSkillType.TAMING_GORE); canSharpenedClaws = Permissions.canUseSubSkill(player, SubSkillType.TAMING_SHARPENED_CLAWS); @@ -55,37 +59,53 @@ public class TamingCommand extends SkillCommand { } @Override - protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { + protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, + boolean isLucky) { List messages = new ArrayList<>(); if (canEnvironmentallyAware) { - messages.add(LocaleLoader.getString("Ability.Generic.Template", LocaleLoader.getString("Taming.Ability.Bonus.0"), LocaleLoader.getString("Taming.Ability.Bonus.1"))); + messages.add(LocaleLoader.getString("Ability.Generic.Template", + LocaleLoader.getString("Taming.Ability.Bonus.0"), + LocaleLoader.getString("Taming.Ability.Bonus.1"))); } - + if (canFastFood) { - messages.add(LocaleLoader.getString("Ability.Generic.Template", LocaleLoader.getString("Taming.Ability.Bonus.8"), LocaleLoader.getString("Taming.Ability.Bonus.9", percent.format(Taming.fastFoodServiceActivationChance / 100D)))); + messages.add(LocaleLoader.getString("Ability.Generic.Template", + LocaleLoader.getString("Taming.Ability.Bonus.8"), + LocaleLoader.getString("Taming.Ability.Bonus.9", + percent.format(Taming.fastFoodServiceActivationChance / 100D)))); } - + if (canGore) { messages.add(LocaleLoader.getString("Ability.Generic.Template", LocaleLoader.getString("Taming.Combat.Chance.Gore"), - goreChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", goreChanceLucky) : "")); + goreChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", + goreChanceLucky) : "")); } - + if (canHolyHound) { - messages.add(LocaleLoader.getString("Ability.Generic.Template", LocaleLoader.getString("Taming.Ability.Bonus.10"), LocaleLoader.getString("Taming.Ability.Bonus.11"))); + messages.add(LocaleLoader.getString("Ability.Generic.Template", + LocaleLoader.getString("Taming.Ability.Bonus.10"), + LocaleLoader.getString("Taming.Ability.Bonus.11"))); } if (canSharpenedClaws) { - messages.add(LocaleLoader.getString("Ability.Generic.Template", LocaleLoader.getString("Taming.Ability.Bonus.6"), LocaleLoader.getString("Taming.Ability.Bonus.7", Taming.sharpenedClawsBonusDamage))); + messages.add(LocaleLoader.getString("Ability.Generic.Template", + LocaleLoader.getString("Taming.Ability.Bonus.6"), + LocaleLoader.getString("Taming.Ability.Bonus.7", + Taming.sharpenedClawsBonusDamage))); } - + if (canShockProof) { - messages.add(LocaleLoader.getString("Ability.Generic.Template", LocaleLoader.getString("Taming.Ability.Bonus.4"), LocaleLoader.getString("Taming.Ability.Bonus.5", Taming.shockProofModifier))); + messages.add(LocaleLoader.getString("Ability.Generic.Template", + LocaleLoader.getString("Taming.Ability.Bonus.4"), + LocaleLoader.getString("Taming.Ability.Bonus.5", Taming.shockProofModifier))); } - + if (canThickFur) { - messages.add(LocaleLoader.getString("Ability.Generic.Template", LocaleLoader.getString("Taming.Ability.Bonus.2"), LocaleLoader.getString("Taming.Ability.Bonus.3", Taming.thickFurModifier))); + messages.add(LocaleLoader.getString("Ability.Generic.Template", + LocaleLoader.getString("Taming.Ability.Bonus.2"), + LocaleLoader.getString("Taming.Ability.Bonus.3", Taming.thickFurModifier))); } return messages; diff --git a/src/main/java/com/gmail/nossr50/commands/skills/TridentsCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/TridentsCommand.java index da49fdccb..b01dfdb36 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/TridentsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/TridentsCommand.java @@ -1,17 +1,16 @@ package com.gmail.nossr50.commands.skills; +import static com.gmail.nossr50.datatypes.skills.SubSkillType.TRIDENTS_IMPALE; +import static com.gmail.nossr50.datatypes.skills.SubSkillType.TRIDENTS_TRIDENTS_LIMIT_BREAK; + import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.text.TextComponentFactory; -import net.kyori.adventure.text.Component; -import org.bukkit.entity.Player; - import java.util.ArrayList; import java.util.List; - -import static com.gmail.nossr50.datatypes.skills.SubSkillType.TRIDENTS_IMPALE; -import static com.gmail.nossr50.datatypes.skills.SubSkillType.TRIDENTS_TRIDENTS_LIMIT_BREAK; +import net.kyori.adventure.text.Component; +import org.bukkit.entity.Player; public class TridentsCommand extends SkillCommand { @@ -21,18 +20,22 @@ public class TridentsCommand extends SkillCommand { } @Override - protected void dataCalculations(Player player, float skillValue) {} + protected void dataCalculations(Player player, float skillValue) { + } @Override - protected void permissionsCheck(Player player) {} + protected void permissionsCheck(Player player) { + } @Override - protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { + protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, + boolean isLucky) { List messages = new ArrayList<>(); if (SkillUtils.canUseSubskill(player, TRIDENTS_TRIDENTS_LIMIT_BREAK)) { messages.add(getStatMessage(TRIDENTS_TRIDENTS_LIMIT_BREAK, - String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, TRIDENTS_TRIDENTS_LIMIT_BREAK, 1000)))); + String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, + TRIDENTS_TRIDENTS_LIMIT_BREAK, 1000)))); } if (SkillUtils.canUseSubskill(player, TRIDENTS_IMPALE)) { @@ -47,7 +50,8 @@ public class TridentsCommand extends SkillCommand { protected List getTextComponents(Player player) { List textComponents = new ArrayList<>(); - TextComponentFactory.getSubSkillTextComponents(player, textComponents, PrimarySkillType.TRIDENTS); + TextComponentFactory.getSubSkillTextComponents(player, textComponents, + PrimarySkillType.TRIDENTS); return textComponents; } 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 6a85468c8..7ae5c1a7f 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/UnarmedCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/UnarmedCommand.java @@ -8,11 +8,10 @@ import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; -import net.kyori.adventure.text.Component; -import org.bukkit.entity.Player; - import java.util.ArrayList; import java.util.List; +import net.kyori.adventure.text.Component; +import org.bukkit.entity.Player; public class UnarmedCommand extends SkillCommand { private String berserkLength; @@ -39,11 +38,12 @@ public class UnarmedCommand extends SkillCommand { protected void dataCalculations(Player player, float skillValue) { // UNARMED_ARROW_DEFLECT if (canDeflect) { - String[] deflectStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.UNARMED_ARROW_DEFLECT); + String[] deflectStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + SubSkillType.UNARMED_ARROW_DEFLECT); deflectChance = deflectStrings[0]; deflectChanceLucky = deflectStrings[1]; } - + // BERSERK if (canBerserk) { String[] berserkStrings = calculateLengthDisplayValues(player, skillValue); @@ -53,7 +53,8 @@ public class UnarmedCommand extends SkillCommand { // UNARMED_DISARM if (canDisarm) { - String[] disarmStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.UNARMED_DISARM); + String[] disarmStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + SubSkillType.UNARMED_DISARM); disarmChance = disarmStrings[0]; disarmChanceLucky = disarmStrings[1]; } @@ -65,7 +66,8 @@ public class UnarmedCommand extends SkillCommand { // IRON GRIP if (canIronGrip) { - String[] ironGripStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.UNARMED_IRON_GRIP); + String[] ironGripStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + SubSkillType.UNARMED_IRON_GRIP); ironGripChance = ironGripStrings[0]; ironGripChanceLucky = ironGripStrings[1]; } @@ -73,7 +75,8 @@ public class UnarmedCommand extends SkillCommand { @Override protected void permissionsCheck(Player player) { - canBerserk = RankUtils.hasUnlockedSubskill(player, SubSkillType.UNARMED_BERSERK) && Permissions.berserk(player); + canBerserk = RankUtils.hasUnlockedSubskill(player, SubSkillType.UNARMED_BERSERK) + && Permissions.berserk(player); canIronArm = Permissions.canUseSubSkill(player, SubSkillType.UNARMED_STEEL_ARM_STYLE); canDeflect = Permissions.canUseSubSkill(player, SubSkillType.UNARMED_ARROW_DEFLECT); canDisarm = Permissions.canUseSubSkill(player, SubSkillType.UNARMED_DISARM); @@ -82,40 +85,48 @@ public class UnarmedCommand extends SkillCommand { } @Override - protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { + protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, + boolean isLucky) { List messages = new ArrayList<>(); if (canDeflect) { messages.add(getStatMessage(SubSkillType.UNARMED_ARROW_DEFLECT, deflectChance) - + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", deflectChanceLucky) : "")); + + (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) : "")); + + (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) : "")); + + (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))); + messages.add(LocaleLoader.getString("Ability.Generic.Template", + LocaleLoader.getString("Unarmed.Ability.Bonus.0"), + LocaleLoader.getString("Unarmed.Ability.Bonus.1", ironArmBonus))); } if (canIronGrip) { messages.add(getStatMessage(SubSkillType.UNARMED_IRON_GRIP, ironGripChance) - + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", ironGripChanceLucky) : "")); + + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", ironGripChanceLucky) + : "")); //messages.add(LocaleLoader.getString("Unarmed.Ability.Chance.IronGrip", ironGripChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", ironGripChanceLucky) : "")); } if (Permissions.canUseSubSkill(player, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK)) { messages.add(getStatMessage(SubSkillType.UNARMED_UNARMED_LIMIT_BREAK, - String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK, 1000)))); + String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, + SubSkillType.UNARMED_UNARMED_LIMIT_BREAK, 1000)))); } return messages; @@ -125,7 +136,8 @@ public class UnarmedCommand extends SkillCommand { protected List getTextComponents(Player player) { List textComponents = new ArrayList<>(); - TextComponentFactory.getSubSkillTextComponents(player, textComponents, PrimarySkillType.UNARMED); + TextComponentFactory.getSubSkillTextComponents(player, textComponents, + PrimarySkillType.UNARMED); return textComponents; } 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 33dd0f071..9b7f9ed30 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/WoodcuttingCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/WoodcuttingCommand.java @@ -8,11 +8,10 @@ import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; -import net.kyori.adventure.text.Component; -import org.bukkit.entity.Player; - import java.util.ArrayList; import java.util.List; +import net.kyori.adventure.text.Component; +import org.bukkit.entity.Player; public class WoodcuttingCommand extends SkillCommand { private String treeFellerLength; @@ -41,7 +40,8 @@ public class WoodcuttingCommand extends SkillCommand { //Clean Cuts if (canTripleDrop) { - String[] tripleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.WOODCUTTING_CLEAN_CUTS); + String[] tripleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + SubSkillType.WOODCUTTING_CLEAN_CUTS); tripleDropChance = tripleDropStrings[0]; tripleDropChanceLucky = tripleDropStrings[1]; } @@ -55,37 +55,43 @@ public class WoodcuttingCommand extends SkillCommand { } private void setDoubleDropClassicChanceStrings(Player player) { - String[] doubleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.WOODCUTTING_HARVEST_LUMBER); + String[] doubleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + SubSkillType.WOODCUTTING_HARVEST_LUMBER); doubleDropChance = doubleDropStrings[0]; doubleDropChanceLucky = doubleDropStrings[1]; } @Override protected void permissionsCheck(Player player) { - canTreeFell = RankUtils.hasUnlockedSubskill(player, SubSkillType.WOODCUTTING_TREE_FELLER) && Permissions.treeFeller(player); + canTreeFell = RankUtils.hasUnlockedSubskill(player, SubSkillType.WOODCUTTING_TREE_FELLER) + && Permissions.treeFeller(player); canDoubleDrop = !mcMMO.p.getGeneralConfig().getDoubleDropsDisabled(skill) && Permissions.canUseSubSkill(player, SubSkillType.WOODCUTTING_HARVEST_LUMBER) && RankUtils.getRank(player, SubSkillType.WOODCUTTING_HARVEST_LUMBER) >= 1; - canTripleDrop = !mcMMO.p.getGeneralConfig().getDoubleDropsDisabled(skill) && Permissions.canUseSubSkill(player, SubSkillType.WOODCUTTING_CLEAN_CUTS); + canTripleDrop = !mcMMO.p.getGeneralConfig().getDoubleDropsDisabled(skill) + && Permissions.canUseSubSkill(player, SubSkillType.WOODCUTTING_CLEAN_CUTS); canLeafBlow = Permissions.canUseSubSkill(player, SubSkillType.WOODCUTTING_LEAF_BLOWER); - canKnockOnWood = canTreeFell && Permissions.canUseSubSkill(player, SubSkillType.WOODCUTTING_KNOCK_ON_WOOD); + canKnockOnWood = canTreeFell && Permissions.canUseSubSkill(player, + SubSkillType.WOODCUTTING_KNOCK_ON_WOOD); } @Override - protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { + protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, + boolean isLucky) { List messages = new ArrayList<>(); if (canDoubleDrop) { messages.add(getStatMessage(SubSkillType.WOODCUTTING_HARVEST_LUMBER, doubleDropChance) - + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", doubleDropChanceLucky) : "")); + + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", doubleDropChanceLucky) + : "")); } if (canTripleDrop) { messages.add(getStatMessage(SubSkillType.WOODCUTTING_CLEAN_CUTS, tripleDropChance) - + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", tripleDropChanceLucky) : "")); + + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", tripleDropChanceLucky) + : "")); } - if (canKnockOnWood) { String lootNote; @@ -97,14 +103,17 @@ public class WoodcuttingCommand extends SkillCommand { messages.add(getStatMessage(SubSkillType.WOODCUTTING_KNOCK_ON_WOOD, lootNote)); } - + if (canLeafBlow) { - messages.add(LocaleLoader.getString("Ability.Generic.Template", LocaleLoader.getString("Woodcutting.Ability.0"), LocaleLoader.getString("Woodcutting.Ability.1"))); + messages.add(LocaleLoader.getString("Ability.Generic.Template", + LocaleLoader.getString("Woodcutting.Ability.0"), + LocaleLoader.getString("Woodcutting.Ability.1"))); } if (canTreeFell) { messages.add(getStatMessage(SubSkillType.WOODCUTTING_TREE_FELLER, treeFellerLength) - + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", treeFellerLengthEndurance) : "")); + + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", + treeFellerLengthEndurance) : "")); } return messages; @@ -114,7 +123,8 @@ public class WoodcuttingCommand extends SkillCommand { protected List getTextComponents(Player player) { List textComponents = new ArrayList<>(); - TextComponentFactory.getSubSkillTextComponents(player, textComponents, PrimarySkillType.WOODCUTTING); + TextComponentFactory.getSubSkillTextComponents(player, textComponents, + PrimarySkillType.WOODCUTTING); return textComponents; } diff --git a/src/main/java/com/gmail/nossr50/config/AdvancedConfig.java b/src/main/java/com/gmail/nossr50/config/AdvancedConfig.java index 414f0331a..1f44ac78b 100644 --- a/src/main/java/com/gmail/nossr50/config/AdvancedConfig.java +++ b/src/main/java/com/gmail/nossr50/config/AdvancedConfig.java @@ -4,11 +4,10 @@ import com.gmail.nossr50.datatypes.interactions.NotificationType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.subskills.AbstractSubSkill; import com.gmail.nossr50.mcMMO; -import net.md_5.bungee.api.ChatColor; - import java.io.File; import java.util.ArrayList; import java.util.List; +import net.md_5.bungee.api.ChatColor; public class AdvancedConfig extends BukkitConfig { int[] defaultCrippleValues = new int[]{10, 15, 20, 25}; @@ -66,7 +65,8 @@ public class AdvancedConfig extends BukkitConfig { } if (getCatalysisMaxSpeed() < getCatalysisMinSpeed()) { - reason.add("Skills.Alchemy.Catalysis.MaxSpeed should be at least Skills.Alchemy.Catalysis.MinSpeed!"); + reason.add( + "Skills.Alchemy.Catalysis.MaxSpeed should be at least Skills.Alchemy.Catalysis.MinSpeed!"); } /* ARCHERY */ @@ -358,7 +358,8 @@ public class AdvancedConfig extends BukkitConfig { } if (getMaxHorseJumpStrength() < 0 || getMaxHorseJumpStrength() > 2) { - reason.add("Skills.Taming.CallOfTheWild.MaxHorseJumpStrength should be between 0 and 2!"); + reason.add( + "Skills.Taming.CallOfTheWild.MaxHorseJumpStrength should be between 0 and 2!"); } /* UNARMED */ @@ -410,7 +411,8 @@ public class AdvancedConfig extends BukkitConfig { /* GENERAL */ public boolean useAttackCooldown() { - return config.getBoolean("Skills.General.Attack_Cooldown.Adjust_Skills_For_Attack_Cooldown", true); + return config.getBoolean("Skills.General.Attack_Cooldown.Adjust_Skills_For_Attack_Cooldown", + true); } public boolean canApplyLimitBreakPVE() { @@ -426,29 +428,32 @@ public class AdvancedConfig extends BukkitConfig { } /** - * This returns the maximum level at which superabilities will stop lengthening from scaling alongside skill level. - * It returns a different value depending on whether the server is in retro mode + * This returns the maximum level at which superabilities will stop lengthening from scaling + * alongside skill level. It returns a different value depending on whether 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 config.getInt("Skills.General.Ability.Length.Standard.CapLevel", 50); - else + } else { return config.getInt("Skills.General.Ability.Length.RetroMode.CapLevel", 500); + } } /** - * This returns the frequency at which abilities will increase in length - * It returns a different value depending on whether the server is in retro mode + * This returns the frequency at which abilities will increase in length It returns a different + * value depending on whether 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 config.getInt("Skills.General.Ability.Length.Standard.IncreaseLevel", 5); - else + } else { return config.getInt("Skills.General.Ability.Length.RetroMode.IncreaseLevel", 50); + } } public int getEnchantBuff() { @@ -456,17 +461,19 @@ public class AdvancedConfig extends BukkitConfig { } /** - * 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 + * 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 keyPath = subSkillType.getAdvConfigAddress() + ".MaxBonusLevel."; - return mcMMO.isRetroModeEnabled() ? config.getInt(keyPath + "RetroMode", 1000) : config.getInt(keyPath + "Standard", 100); + return mcMMO.isRetroModeEnabled() ? config.getInt(keyPath + "RetroMode", 1000) + : config.getInt( + keyPath + "Standard", 100); } public int getMaxBonusLevel(AbstractSubSkill abstractSubSkill) { @@ -489,11 +496,15 @@ public class AdvancedConfig extends BukkitConfig { } public boolean doesNotificationUseActionBar(NotificationType notificationType) { - return config.getBoolean("Feedback.ActionBarNotifications." + notificationType.toString() + ".Enabled", true); + return config.getBoolean( + "Feedback.ActionBarNotifications." + notificationType.toString() + ".Enabled", + true); } public boolean doesNotificationSendCopyToChat(NotificationType notificationType) { - return config.getBoolean("Feedback.ActionBarNotifications." + notificationType.toString() + ".SendCopyOfMessageToChat", false); + return config.getBoolean( + "Feedback.ActionBarNotifications." + notificationType.toString() + + ".SendCopyOfMessageToChat", false); } public boolean useTitlesForXPEvent() { @@ -501,63 +512,10 @@ public class AdvancedConfig extends BukkitConfig { } public boolean sendAbilityNotificationToOtherPlayers() { - return config.getBoolean("Feedback.Events.AbilityActivation.SendNotificationToOtherPlayers", true); + return config.getBoolean("Feedback.Events.AbilityActivation.SendNotificationToOtherPlayers", + true); } - /* - * JSON Style Settings - */ - - - /*public ChatColor getJSONStatHoverElementColor(StatType statType, boolean isPrefix) { - String keyAddress = isPrefix ? "Prefix" : "Value"; - String keyLocation = "Style.JSON.Hover.Details." + StringUtils.getCapitalized(statType.toString()) +"."+keyAddress+".Color"; - - return getChatColorFromKey(keyLocation); - }*/ - - /** - * Used to color our details header in our JSON Hover Object tooltips - * - * @return the ChatColor for this element - */ - /*public ChatColor getJSONStatHoverDetailsColor() { - String keyLocation = "Style.JSON.Hover.Details.Header.Color"; - return getChatColorFromKey(keyLocation); - } - - public boolean isJSONDetailsHeaderBold() { - return config.getBoolean("Style.JSON.Hover.Details.Header.Bold"); - } - - public boolean isJSONDetailsHeaderItalic() { - return config.getBoolean("Style.JSON.Hover.Details.Header.Italics"); - } - - public boolean isJSONDetailsHeaderUnderlined() { - return config.getBoolean("Style.JSON.Hover.Details.Header.Underlined"); - } - - public ChatColor getJSONStatHoverDescriptionColor() { - String keyLocation = "Style.JSON.Hover.Details.Description.Color"; - return getChatColorFromKey(keyLocation); - } - - public boolean isJSONDetailsDescriptionBold() { - return config.getBoolean("Style.JSON.Hover.Details.Description.Bold"); - } - - public boolean isJSONDetailsDescriptionItalic() { - return config.getBoolean("Style.JSON.Hover.Details.Description.Italics"); - } - - public boolean isJSONDetailsDescriptionUnderlined() { - return config.getBoolean("Style.JSON.Hover.Details.Description.Underlined"); - } - - public ChatColor getJSONActionBarColor(NotificationType notificationType) { - return getChatColor(config.getString("Style.JSON.Notification."+notificationType.toString()+".Color")); - }*/ private ChatColor getChatColorFromKey(String keyLocation) { String colorName = config.getString(keyLocation); @@ -566,8 +524,9 @@ public class AdvancedConfig extends BukkitConfig { private ChatColor getChatColor(String configColor) { for (ChatColor chatColor : ChatColor.values()) { - if (configColor.equalsIgnoreCase(chatColor.getName())) + if (configColor.equalsIgnoreCase(chatColor.getName())) { return chatColor; + } } //Invalid Color @@ -811,10 +770,11 @@ public class AdvancedConfig extends BukkitConfig { /* SMELTING */ public int getBurnModifierMaxLevel() { - if (mcMMO.isRetroModeEnabled()) + if (mcMMO.isRetroModeEnabled()) { return config.getInt("Skills.Smelting.FuelEfficiency.RetroMode.MaxBonusLevel", 1000); - else + } else { return config.getInt("Skills.Smelting.FuelEfficiency.Standard.MaxBonusLevel", 100); + } } public double getFluxMiningChance() { @@ -903,7 +863,6 @@ public class AdvancedConfig extends BukkitConfig { } /* UNARMED */ - public boolean isSteelArmDamageCustom() { return config.getBoolean("Skills.Unarmed.SteelArmStyle.Damage_Override", false); } @@ -919,12 +878,13 @@ public class AdvancedConfig extends BukkitConfig { /* WOODCUTTING */ public boolean isKnockOnWoodXPOrbEnabled() { - return config.getBoolean("Skills.Woodcutting.TreeFeller.Knock_On_Wood.Add_XP_Orbs_To_Drops", true); + return config.getBoolean("Skills.Woodcutting.TreeFeller.Knock_On_Wood.Add_XP_Orbs_To_Drops", + true); } /* MACES */ public double getCrippleChanceToApplyOnHit(int rank) { String root = "Skills.Maces.Cripple.Chance_To_Apply_On_Hit.Rank_"; - return config.getDouble(root + rank, defaultCrippleValues[rank-1]); + return config.getDouble(root + rank, defaultCrippleValues[rank - 1]); } } diff --git a/src/main/java/com/gmail/nossr50/config/AutoUpdateLegacyConfigLoader.java b/src/main/java/com/gmail/nossr50/config/AutoUpdateLegacyConfigLoader.java index 600e7f984..d3cd6f1a6 100644 --- a/src/main/java/com/gmail/nossr50/config/AutoUpdateLegacyConfigLoader.java +++ b/src/main/java/com/gmail/nossr50/config/AutoUpdateLegacyConfigLoader.java @@ -2,14 +2,13 @@ package com.gmail.nossr50.config; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.LogUtils; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.jetbrains.annotations.NotNull; - import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Set; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.jetbrains.annotations.NotNull; public abstract class AutoUpdateLegacyConfigLoader extends LegacyConfigLoader { public AutoUpdateLegacyConfigLoader(String relativePath, String fileName, File dataFolder) { @@ -47,7 +46,8 @@ public abstract class AutoUpdateLegacyConfigLoader extends LegacyConfigLoader { @Override protected void loadFile() { super.loadFile(); - FileConfiguration internalConfig = YamlConfiguration.loadConfiguration(mcMMO.p.getResourceAsReader(fileName)); + FileConfiguration internalConfig = YamlConfiguration.loadConfiguration( + mcMMO.p.getResourceAsReader(fileName)); Set configKeys = config.getKeys(true); Set internalConfigKeys = internalConfig.getKeys(true); @@ -74,7 +74,8 @@ public abstract class AutoUpdateLegacyConfigLoader extends LegacyConfigLoader { } for (String key : newKeys) { - LogUtils.debug(mcMMO.p.getLogger(), "Adding new key: " + key + " = " + internalConfig.get(key)); + LogUtils.debug(mcMMO.p.getLogger(), + "Adding new key: " + key + " = " + internalConfig.get(key)); config.set(key, internalConfig.get(key)); } diff --git a/src/main/java/com/gmail/nossr50/config/BukkitConfig.java b/src/main/java/com/gmail/nossr50/config/BukkitConfig.java index 028a3e3bc..d3b431551 100644 --- a/src/main/java/com/gmail/nossr50/config/BukkitConfig.java +++ b/src/main/java/com/gmail/nossr50/config/BukkitConfig.java @@ -2,16 +2,15 @@ package com.gmail.nossr50.config; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.LogUtils; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.YamlConfiguration; -import org.jetbrains.annotations.NotNull; - import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; +import org.jetbrains.annotations.NotNull; public abstract class BukkitConfig { boolean copyDefaults = true; @@ -19,7 +18,8 @@ public abstract class BukkitConfig { protected final File configFile; protected YamlConfiguration defaultYamlConfig; protected YamlConfiguration config; - protected @NotNull final File dataFolder; + protected @NotNull + final File dataFolder; private boolean savedDefaults = false; public BukkitConfig(@NotNull String fileName, @NotNull File dataFolder, boolean copyDefaults) { @@ -41,6 +41,7 @@ public abstract class BukkitConfig { public BukkitConfig(@NotNull String fileName) { this(fileName, mcMMO.p.getDataFolder()); } + public BukkitConfig(@NotNull String fileName, boolean copyDefaults) { this(fileName, mcMMO.p.getDataFolder(), copyDefaults); } @@ -82,8 +83,9 @@ public abstract class BukkitConfig { * Copies the config from the JAR to defaults/ */ YamlConfiguration saveDefaultConfigToDisk() { - LogUtils.debug(mcMMO.p.getLogger(), "Copying default config to disk: " + fileName + " to defaults/" + fileName); - try(InputStream inputStream = mcMMO.p.getResource(fileName)) { + LogUtils.debug(mcMMO.p.getLogger(), + "Copying default config to disk: " + fileName + " to defaults/" + fileName); + try (InputStream inputStream = mcMMO.p.getResource(fileName)) { if (inputStream == null) { mcMMO.p.getLogger().severe("Unable to copy default config: " + fileName); return null; @@ -110,7 +112,9 @@ public abstract class BukkitConfig { YamlConfiguration initConfig() { if (!configFile.exists()) { - LogUtils.debug(mcMMO.p.getLogger(), "User config file not found, copying a default config to disk: " + fileName); + LogUtils.debug( + mcMMO.p.getLogger(), + "User config file not found, copying a default config to disk: " + fileName); mcMMO.p.saveResource(fileName, false); } @@ -154,15 +158,20 @@ public abstract class BukkitConfig { if (validateKeys()) { LogUtils.debug(mcMMO.p.getLogger(), "No errors found in " + fileName + "!"); } else { - mcMMO.p.getLogger().warning("Errors were found in " + fileName + "! mcMMO was disabled!"); + mcMMO.p.getLogger() + .warning("Errors were found in " + fileName + "! mcMMO was disabled!"); mcMMO.p.getServer().getPluginManager().disablePlugin(mcMMO.p); mcMMO.p.noErrorsInConfigFiles = false; } } public void backup() { - LogUtils.debug(mcMMO.p.getLogger(), "You are using an old version of the " + fileName + " file."); - LogUtils.debug(mcMMO.p.getLogger(), "Your old file has been renamed to " + fileName + ".old and has been replaced by an updated version."); + LogUtils.debug(mcMMO.p.getLogger(), + "You are using an old version of the " + fileName + " file."); + LogUtils.debug( + mcMMO.p.getLogger(), + "Your old file has been renamed to " + fileName + + ".old and has been replaced by an updated version."); configFile.renameTo(new File(configFile.getPath() + ".old")); diff --git a/src/main/java/com/gmail/nossr50/config/ChatConfig.java b/src/main/java/com/gmail/nossr50/config/ChatConfig.java index 627686efb..caff26c03 100644 --- a/src/main/java/com/gmail/nossr50/config/ChatConfig.java +++ b/src/main/java/com/gmail/nossr50/config/ChatConfig.java @@ -35,7 +35,8 @@ public class ChatConfig extends BukkitConfig { } public boolean isChatChannelEnabled(@NotNull ChatChannel chatChannel) { - String key = "Chat.Channels." + StringUtils.getCapitalized(chatChannel.toString()) + ".Enable"; + String key = + "Chat.Channels." + StringUtils.getCapitalized(chatChannel.toString()) + ".Enable"; return config.getBoolean(key, true); } @@ -43,16 +44,17 @@ public class ChatConfig extends BukkitConfig { * Whether to use display names for players in target {@link ChatChannel} * * @param chatChannel target chat channel - * * @return true if display names should be used */ public boolean useDisplayNames(@NotNull ChatChannel chatChannel) { - String key = "Chat.Channels." + StringUtils.getCapitalized(chatChannel.toString()) + ".Use_Display_Names"; + String key = "Chat.Channels." + StringUtils.getCapitalized(chatChannel.toString()) + + ".Use_Display_Names"; return config.getBoolean(key, true); } public boolean isConsoleIncludedInAudience(@NotNull ChatChannel chatChannel) { - String key = "Chat.Channels." + StringUtils.getCapitalized(chatChannel.toString()) + ".Send_To_Console"; + String key = "Chat.Channels." + StringUtils.getCapitalized(chatChannel.toString()) + + ".Send_To_Console"; return config.getBoolean(key, true); } diff --git a/src/main/java/com/gmail/nossr50/config/CoreSkillsConfig.java b/src/main/java/com/gmail/nossr50/config/CoreSkillsConfig.java index d172e4551..61db52fc6 100644 --- a/src/main/java/com/gmail/nossr50/config/CoreSkillsConfig.java +++ b/src/main/java/com/gmail/nossr50/config/CoreSkillsConfig.java @@ -13,8 +13,9 @@ public class CoreSkillsConfig extends BukkitConfig { } public static CoreSkillsConfig getInstance() { - if (instance == null) + if (instance == null) { instance = new CoreSkillsConfig(); + } return instance; } @@ -35,25 +36,26 @@ public class CoreSkillsConfig extends BukkitConfig { */ /** - * Whether a skill is enabled - * Defaults true + * Whether a skill is enabled Defaults true * * @param abstractSubSkill SubSkill definition to check - * * @return true if subskill is enabled */ public boolean isSkillEnabled(AbstractSubSkill abstractSubSkill) { - return config.getBoolean(StringUtils.getCapitalized(abstractSubSkill.getPrimarySkill().toString()) + "." + abstractSubSkill.getConfigKeyName() + ".Enabled", true); + return config.getBoolean( + StringUtils.getCapitalized(abstractSubSkill.getPrimarySkill() + .toString()) + "." + abstractSubSkill.getConfigKeyName() + ".Enabled", + true); } /** * Whether this primary skill is enabled * * @param primarySkillType target primary skill - * * @return true if enabled */ public boolean isPrimarySkillEnabled(PrimarySkillType primarySkillType) { - return config.getBoolean(StringUtils.getCapitalized(primarySkillType.toString()) + ".Enabled", true); + return config.getBoolean( + StringUtils.getCapitalized(primarySkillType.toString()) + ".Enabled", true); } } diff --git a/src/main/java/com/gmail/nossr50/config/CustomItemSupportConfig.java b/src/main/java/com/gmail/nossr50/config/CustomItemSupportConfig.java index 51731d367..2c996ec87 100644 --- a/src/main/java/com/gmail/nossr50/config/CustomItemSupportConfig.java +++ b/src/main/java/com/gmail/nossr50/config/CustomItemSupportConfig.java @@ -14,10 +14,12 @@ public class CustomItemSupportConfig extends BukkitConfig { } public boolean isCustomRepairAllowed() { - return config.getBoolean("Custom_Item_Support.Repair.Allow_Repair_On_Items_With_Custom_Model_Data", true); + return config.getBoolean( + "Custom_Item_Support.Repair.Allow_Repair_On_Items_With_Custom_Model_Data", true); } public boolean isCustomSalvageAllowed() { - return config.getBoolean("Custom_Item_Support.Salvage.Allow_Salvage_On_Items_With_Custom_Model_Data", true); + return config.getBoolean( + "Custom_Item_Support.Salvage.Allow_Salvage_On_Items_With_Custom_Model_Data", true); } } diff --git a/src/main/java/com/gmail/nossr50/config/GeneralConfig.java b/src/main/java/com/gmail/nossr50/config/GeneralConfig.java index 83806a4d0..7b44b52aa 100644 --- a/src/main/java/com/gmail/nossr50/config/GeneralConfig.java +++ b/src/main/java/com/gmail/nossr50/config/GeneralConfig.java @@ -1,25 +1,24 @@ package com.gmail.nossr50.config; +import static com.gmail.nossr50.util.text.ConfigStringUtils.getConfigPartyFeatureString; +import static com.gmail.nossr50.util.text.ConfigStringUtils.getMaterialConfigString; + import com.gmail.nossr50.database.SQLDatabaseManager.PoolIdentifier; import com.gmail.nossr50.datatypes.MobHealthbarType; import com.gmail.nossr50.datatypes.party.PartyFeature; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SuperAbilityType; import com.gmail.nossr50.util.text.StringUtils; -import org.bukkit.Material; -import org.bukkit.block.data.BlockData; -import org.bukkit.configuration.ConfigurationSection; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Set; - -import static com.gmail.nossr50.util.text.ConfigStringUtils.getConfigPartyFeatureString; -import static com.gmail.nossr50.util.text.ConfigStringUtils.getMaterialConfigString; +import org.bukkit.Material; +import org.bukkit.block.data.BlockData; +import org.bukkit.configuration.ConfigurationSection; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class GeneralConfig extends BukkitConfig { @@ -46,16 +45,19 @@ public class GeneralConfig extends BukkitConfig { /* MySQL Settings */ for (PoolIdentifier identifier : PoolIdentifier.values()) { if (getMySQLMaxConnections(identifier) <= 0) { - reason.add("MySQL.Database.MaxConnections." + StringUtils.getCapitalized(identifier.toString()) + " should be greater than 0!"); + reason.add("MySQL.Database.MaxConnections." + StringUtils.getCapitalized( + identifier.toString()) + " should be greater than 0!"); } if (getMySQLMaxPoolSize(identifier) <= 0) { - reason.add("MySQL.Database.MaxPoolSize." + StringUtils.getCapitalized(identifier.toString()) + " should be greater than 0!"); + reason.add("MySQL.Database.MaxPoolSize." + StringUtils.getCapitalized( + identifier.toString()) + " should be greater than 0!"); } } /* Mob Healthbar */ if (getMobHealthbarTime() == 0) { - reason.add("Mob_Healthbar.Display_Time cannot be 0! Set to -1 to disable or set a valid value."); + reason.add( + "Mob_Healthbar.Display_Time cannot be 0! Set to -1 to disable or set a valid value."); } /* Database Purging */ @@ -68,11 +70,14 @@ public class GeneralConfig extends BukkitConfig { } /* Hardcore Mode */ - if (getHardcoreDeathStatPenaltyPercentage() < 0.01 || getHardcoreDeathStatPenaltyPercentage() > 100) { - reason.add("Hardcore.Death_Stat_Loss.Penalty_Percentage only accepts values from 0.01 to 100!"); + if (getHardcoreDeathStatPenaltyPercentage() < 0.01 + || getHardcoreDeathStatPenaltyPercentage() > 100) { + reason.add( + "Hardcore.Death_Stat_Loss.Penalty_Percentage only accepts values from 0.01 to 100!"); } - if (getHardcoreVampirismStatLeechPercentage() < 0.01 || getHardcoreVampirismStatLeechPercentage() > 100) { + if (getHardcoreVampirismStatLeechPercentage() < 0.01 + || getHardcoreVampirismStatLeechPercentage() > 100) { reason.add("Hardcore.Vampirism.Leech_Percentage only accepts values from 0.01 to 100!"); } @@ -125,7 +130,8 @@ public class GeneralConfig extends BukkitConfig { for (PartyFeature partyFeature : PartyFeature.values()) { if (getPartyFeatureUnlockLevel(partyFeature) < 0) { - reason.add("Party.Leveling." + getConfigPartyFeatureString(partyFeature) + "_UnlockLevel should be at least 0!"); + reason.add("Party.Leveling." + getConfigPartyFeatureString( + partyFeature) + "_UnlockLevel should be at least 0!"); } } @@ -231,7 +237,9 @@ public class GeneralConfig extends BukkitConfig { /* Mob Healthbar */ public MobHealthbarType getMobHealthbarDefault() { try { - return MobHealthbarType.valueOf(config.getString("Mob_Healthbar.Display_Type", "HEARTS").toUpperCase(Locale.ENGLISH).trim()); + return MobHealthbarType.valueOf(config.getString("Mob_Healthbar.Display_Type", "HEARTS") + .toUpperCase(Locale.ENGLISH) + .trim()); } catch (IllegalArgumentException ex) { return MobHealthbarType.HEARTS; } @@ -402,11 +410,14 @@ public class GeneralConfig extends BukkitConfig { } public int getMySQLMaxConnections(PoolIdentifier identifier) { - return config.getInt("MySQL.Database.MaxConnections." + StringUtils.getCapitalized(identifier.toString()), 30); + return config.getInt("MySQL.Database.MaxConnections." + StringUtils.getCapitalized( + identifier.toString()), 30); } public int getMySQLMaxPoolSize(PoolIdentifier identifier) { - return config.getInt("MySQL.Database.MaxPoolSize." + StringUtils.getCapitalized(identifier.toString()), 10); + return config.getInt( + "MySQL.Database.MaxPoolSize." + StringUtils.getCapitalized(identifier.toString()), + 10); } public boolean getMySQLSSL() { @@ -436,11 +447,16 @@ public class GeneralConfig extends BukkitConfig { /* Hardcore Mode */ public boolean getHardcoreStatLossEnabled(PrimarySkillType primarySkillType) { - return config.getBoolean("Hardcore.Death_Stat_Loss.Enabled." + StringUtils.getCapitalized(primarySkillType.toString()), false); + return config.getBoolean( + "Hardcore.Death_Stat_Loss.Enabled." + StringUtils.getCapitalized( + primarySkillType.toString()), false); } public void setHardcoreStatLossEnabled(PrimarySkillType primarySkillType, boolean enabled) { - config.set("Hardcore.Death_Stat_Loss.Enabled." + StringUtils.getCapitalized(primarySkillType.toString()), enabled); + config.set( + "Hardcore.Death_Stat_Loss.Enabled." + StringUtils.getCapitalized( + primarySkillType.toString()), + enabled); } public double getHardcoreDeathStatPenaltyPercentage() { @@ -456,11 +472,14 @@ public class GeneralConfig extends BukkitConfig { } public boolean getHardcoreVampirismEnabled(PrimarySkillType primarySkillType) { - return config.getBoolean("Hardcore.Vampirism.Enabled." + StringUtils.getCapitalized(primarySkillType.toString()), false); + return config.getBoolean( + "Hardcore.Vampirism.Enabled." + StringUtils.getCapitalized( + primarySkillType.toString()), false); } public void setHardcoreVampirismEnabled(PrimarySkillType primarySkillType, boolean enabled) { - config.set("Hardcore.Vampirism.Enabled." + StringUtils.getCapitalized(primarySkillType.toString()), enabled); + config.set("Hardcore.Vampirism.Enabled." + StringUtils.getCapitalized( + primarySkillType.toString()), enabled); } public double getHardcoreVampirismStatLeechPercentage() { @@ -577,7 +596,7 @@ public class GeneralConfig extends BukkitConfig { public int getLevelUpEffectsTier() { return config.getInt("Particles.LevelUp_Tier", 100); } -// public boolean getLargeFireworks() { return config.getBoolean("Particles.LargeFireworks", true); } + // public boolean getLargeFireworks() { return config.getBoolean("Particles.LargeFireworks", true); } /* PARTY SETTINGS */ public boolean getPartyFriendlyFire() { @@ -630,7 +649,8 @@ public class GeneralConfig extends BukkitConfig { } public int getPartyFeatureUnlockLevel(PartyFeature partyFeature) { - return config.getInt("Party.Leveling." + getConfigPartyFeatureString(partyFeature) + "_UnlockLevel", 0); + return config.getInt( + "Party.Leveling." + getConfigPartyFeatureString(partyFeature) + "_UnlockLevel", 0); } /* Party Teleport Settings */ @@ -711,17 +731,22 @@ public class GeneralConfig extends BukkitConfig { */ public boolean getDoubleDropsEnabled(PrimarySkillType skill, Material material) { //TODO: Temporary measure to fix an exploit caused by a yet to be fixed Spigot bug (as of 7/3/2020) - if (material.toString().equalsIgnoreCase("LILY_PAD")) + if (material.toString().equalsIgnoreCase("LILY_PAD")) { return false; + } - return config.getBoolean("Bonus_Drops." + StringUtils.getCapitalized(skill.toString()) + "." + getMaterialConfigString(material).replace(" ", "_")); + return config.getBoolean( + "Bonus_Drops." + StringUtils.getCapitalized(skill.toString()) + "." + + getMaterialConfigString( + material).replace(" ", "_")); } public boolean getDoubleDropsDisabled(PrimarySkillType skill) { String skillName = StringUtils.getCapitalized(skill.toString()); ConfigurationSection section = config.getConfigurationSection("Bonus_Drops." + skillName); - if (section == null) + if (section == null) { return false; + } Set keys = section.getKeys(false); boolean disabled = true; @@ -781,7 +806,8 @@ public class GeneralConfig extends BukkitConfig { /* Mining */ public Material getDetonatorItem() { - return Material.matchMaterial(config.getString("Skills.Mining.Detonator_Name", "FLINT_AND_STEEL")); + return Material.matchMaterial( + config.getString("Skills.Mining.Detonator_Name", "FLINT_AND_STEEL")); } /* Excavation */ @@ -803,7 +829,8 @@ public class GeneralConfig extends BukkitConfig { } public @Nullable Material getRepairAnvilMaterial() { - return Material.matchMaterial(config.getString("Skills.Repair.Anvil_Material", "IRON_BLOCK")); + return Material.matchMaterial( + config.getString("Skills.Repair.Anvil_Material", "IRON_BLOCK")); } public boolean getRepairConfirmRequired() { @@ -836,7 +863,8 @@ public class GeneralConfig extends BukkitConfig { } public @Nullable Material getSalvageAnvilMaterial() { - return Material.matchMaterial(config.getString("Skills.Salvage.Anvil_Material", "GOLD_BLOCK")); + return Material.matchMaterial( + config.getString("Skills.Salvage.Anvil_Material", "GOLD_BLOCK")); } public boolean getSalvageConfirmRequired() { @@ -866,14 +894,16 @@ public class GeneralConfig extends BukkitConfig { } /* Taming */ -// public Material getTamingCOTWMaterial(EntityType type) { return Material.matchMaterial(config.getString("Skills.Taming.Call_Of_The_Wild." + StringUtils.getPrettyEntityTypeString(type) + ".Item_Material")); } -// public int getTamingCOTWCost(EntityType type) { return config.getInt("Skills.Taming.Call_Of_The_Wild." + StringUtils.getPrettyEntityTypeString(type) + ".Item_Amount"); } -// public int getTamingCOTWAmount(EntityType type) { return config.getInt("Skills.Taming.Call_Of_The_Wild." + StringUtils.getPrettyEntityTypeString(type) + ".Summon_Amount"); } -// public int getTamingCOTWLength(EntityType type) { return config.getInt("Skills.Taming.Call_Of_The_Wild." + StringUtils.getPrettyEntityTypeString(type)+ ".Summon_Length"); } -// public int getTamingCOTWMaxAmount(EntityType type) { return config.getInt("Skills.Taming.Call_Of_The_Wild." + StringUtils.getPrettyEntityTypeString(type)+ ".Summon_Max_Amount"); } + // public Material getTamingCOTWMaterial(EntityType type) { return Material.matchMaterial(config.getString("Skills.Taming.Call_Of_The_Wild." + StringUtils.getPrettyEntityTypeString(type) + ".Item_Material")); } + // public int getTamingCOTWCost(EntityType type) { return config.getInt("Skills.Taming.Call_Of_The_Wild." + StringUtils.getPrettyEntityTypeString(type) + ".Item_Amount"); } + // public int getTamingCOTWAmount(EntityType type) { return config.getInt("Skills.Taming.Call_Of_The_Wild." + StringUtils.getPrettyEntityTypeString(type) + ".Summon_Amount"); } + // public int getTamingCOTWLength(EntityType type) { return config.getInt("Skills.Taming.Call_Of_The_Wild." + StringUtils.getPrettyEntityTypeString(type)+ ".Summon_Length"); } + // public int getTamingCOTWMaxAmount(EntityType type) { return config.getInt("Skills.Taming.Call_Of_The_Wild." + StringUtils.getPrettyEntityTypeString(type)+ ".Summon_Max_Amount"); } public Material getTamingCOTWMaterial(String cotwEntity) { - return Material.matchMaterial(config.getString("Skills.Taming.Call_Of_The_Wild." + cotwEntity + ".Item_Material")); + return Material.matchMaterial( + config.getString( + "Skills.Taming.Call_Of_The_Wild." + cotwEntity + ".Item_Material")); } public int getTamingCOTWCost(String cotwEntity) { @@ -889,13 +919,14 @@ public class GeneralConfig extends BukkitConfig { } public int getTamingCOTWMaxAmount(String cotwEntity) { - return config.getInt("Skills.Taming.Call_Of_The_Wild." + cotwEntity + ".Per_Player_Limit", 1); + return config.getInt("Skills.Taming.Call_Of_The_Wild." + cotwEntity + ".Per_Player_Limit", + 1); } /* Woodcutting */ public boolean getWoodcuttingDoubleDropsEnabled(BlockData blockData) { - return config.getBoolean("Bonus_Drops.Woodcutting." - + getMaterialConfigString(blockData.getMaterial())); + return config.getBoolean( + "Bonus_Drops.Woodcutting." + getMaterialConfigString(blockData.getMaterial())); } public boolean getTreeFellerSoundsEnabled() { @@ -918,7 +949,8 @@ public class GeneralConfig extends BukkitConfig { } public int getLevelCap(PrimarySkillType skill) { - int cap = config.getInt("Skills." + StringUtils.getCapitalized(skill.toString()) + ".Level_Cap"); + int cap = config.getInt( + "Skills." + StringUtils.getCapitalized(skill.toString()) + ".Level_Cap"); return (cap <= 0) ? Integer.MAX_VALUE : cap; } @@ -933,11 +965,15 @@ public class GeneralConfig extends BukkitConfig { /* PVP & PVE Settings */ public boolean getPVPEnabled(PrimarySkillType skill) { - return config.getBoolean("Skills." + StringUtils.getCapitalized(skill.toString()) + ".Enabled_For_PVP", true); + return config.getBoolean( + "Skills." + StringUtils.getCapitalized(skill.toString()) + ".Enabled_For_PVP", + true); } public boolean getPVEEnabled(PrimarySkillType skill) { - return config.getBoolean("Skills." + StringUtils.getCapitalized(skill.toString()) + ".Enabled_For_PVE", true); + return config.getBoolean( + "Skills." + StringUtils.getCapitalized(skill.toString()) + ".Enabled_For_PVE", + true); } //public float getMasterVolume() { return (float) config.getDouble("Sounds.MasterVolume", 1.0); } @@ -959,23 +995,30 @@ public class GeneralConfig extends BukkitConfig { } public boolean shouldLevelUpBroadcastToConsole() { - return config.getBoolean("General.Level_Up_Chat_Broadcasts.Broadcast_Targets.Send_To_Console", true); + return config.getBoolean( + "General.Level_Up_Chat_Broadcasts.Broadcast_Targets.Send_To_Console", true); } public boolean isLevelUpBroadcastsPartyMembersOnly() { - return config.getBoolean("General.Level_Up_Chat_Broadcasts.Broadcast_Targets.Only_Party_Members", false); + return config.getBoolean( + "General.Level_Up_Chat_Broadcasts.Broadcast_Targets.Only_Party_Members", false); } public boolean isLevelUpBroadcastsSameWorldOnly() { - return config.getBoolean("General.Level_Up_Chat_Broadcasts.Broadcast_Targets.Only_Same_World", false); + return config.getBoolean( + "General.Level_Up_Chat_Broadcasts.Broadcast_Targets.Only_Same_World", false); } public boolean shouldLevelUpBroadcastsRestrictDistance() { - return config.getBoolean("General.Level_Up_Chat_Broadcasts.Broadcast_Targets.Distance_Restrictions.Restrict_Distance", false); + return config.getBoolean( + "General.Level_Up_Chat_Broadcasts.Broadcast_Targets.Distance_Restrictions.Restrict_Distance", + false); } public int getLevelUpBroadcastRadius() { - return config.getInt("General.Level_Up_Chat_Broadcasts.Broadcast_Targets.Distance_Restrictions.Restricted_Radius", 100); + return config.getInt( + "General.Level_Up_Chat_Broadcasts.Broadcast_Targets.Distance_Restrictions.Restricted_Radius", + 100); } public int getLevelUpBroadcastInterval() { @@ -983,40 +1026,56 @@ public class GeneralConfig extends BukkitConfig { } public boolean shouldPowerLevelUpBroadcasts() { - return config.getBoolean("General.Level_Up_Chat_Broadcasts.Broadcast_Powerlevels.Enabled", true); + return config.getBoolean("General.Level_Up_Chat_Broadcasts.Broadcast_Powerlevels.Enabled", + true); } public boolean shouldPowerLevelUpBroadcastToConsole() { - return config.getBoolean("General.Level_Up_Chat_Broadcasts.Broadcast_Powerlevels.Broadcast_Targets.Send_To_Console", true); + return config.getBoolean( + "General.Level_Up_Chat_Broadcasts.Broadcast_Powerlevels.Broadcast_Targets.Send_To_Console", + true); } public boolean isPowerLevelUpBroadcastsPartyMembersOnly() { - return config.getBoolean("General.Level_Up_Chat_Broadcasts.Broadcast_Powerlevels.Broadcast_Targets.Only_Party_Members", false); + return config.getBoolean( + "General.Level_Up_Chat_Broadcasts.Broadcast_Powerlevels.Broadcast_Targets.Only_Party_Members", + false); } public boolean isPowerLevelUpBroadcastsSameWorldOnly() { - return config.getBoolean("General.Level_Up_Chat_Broadcasts.Broadcast_Powerlevels.Broadcast_Targets.Only_Same_World", false); + return config.getBoolean( + "General.Level_Up_Chat_Broadcasts.Broadcast_Powerlevels.Broadcast_Targets.Only_Same_World", + false); } public boolean shouldPowerLevelUpBroadcastsRestrictDistance() { - return config.getBoolean("General.Level_Up_Chat_Broadcasts.Broadcast_Powerlevels.Broadcast_Targets.Distance_Restrictions.Restrict_Distance", false); + return config.getBoolean( + "General.Level_Up_Chat_Broadcasts.Broadcast_Powerlevels.Broadcast_Targets.Distance_Restrictions.Restrict_Distance", + false); } public int getPowerLevelUpBroadcastRadius() { - return config.getInt("General.Level_Up_Chat_Broadcasts.Broadcast_Powerlevels.Broadcast_Targets.Distance_Restrictions.Restricted_Radius", 100); + return config.getInt( + "General.Level_Up_Chat_Broadcasts.Broadcast_Powerlevels.Broadcast_Targets.Distance_Restrictions.Restricted_Radius", + 100); } public int getPowerLevelUpBroadcastInterval() { - return config.getInt("General.Level_Up_Chat_Broadcasts.Broadcast_Powerlevels.Milestone_Interval", 100); + return config.getInt( + "General.Level_Up_Chat_Broadcasts.Broadcast_Powerlevels.Milestone_Interval", 100); } public boolean isGreenThumbReplantableCrop(@NotNull Material material) { - return config.getBoolean("Green_Thumb_Replanting_Crops." + StringUtils.getCapitalized(material.toString()), true); + return config.getBoolean( + "Green_Thumb_Replanting_Crops." + StringUtils.getCapitalized(material.toString()), + true); } public boolean useVerboseLogging() { return config.getBoolean("General.Verbose_Logging", false); } - public boolean isMasterySystemEnabled() { return config.getBoolean( "General.PowerLevel.Skill_Mastery.Enabled"); } + public boolean isMasterySystemEnabled() { + return config.getBoolean("General.PowerLevel.Skill_Mastery.Enabled"); + } } diff --git a/src/main/java/com/gmail/nossr50/config/HiddenConfig.java b/src/main/java/com/gmail/nossr50/config/HiddenConfig.java index 54cdf0ff0..9fbe00811 100644 --- a/src/main/java/com/gmail/nossr50/config/HiddenConfig.java +++ b/src/main/java/com/gmail/nossr50/config/HiddenConfig.java @@ -1,9 +1,8 @@ package com.gmail.nossr50.config; import com.gmail.nossr50.mcMMO; -import org.bukkit.configuration.file.YamlConfiguration; - import java.io.InputStreamReader; +import org.bukkit.configuration.file.YamlConfiguration; public class HiddenConfig { private static HiddenConfig instance; diff --git a/src/main/java/com/gmail/nossr50/config/LegacyConfigLoader.java b/src/main/java/com/gmail/nossr50/config/LegacyConfigLoader.java index c9d808e01..4bd380f96 100644 --- a/src/main/java/com/gmail/nossr50/config/LegacyConfigLoader.java +++ b/src/main/java/com/gmail/nossr50/config/LegacyConfigLoader.java @@ -2,13 +2,12 @@ package com.gmail.nossr50.config; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.LogUtils; +import java.io.File; +import java.util.List; import org.bukkit.configuration.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.VisibleForTesting; -import java.io.File; -import java.util.List; - @Deprecated public abstract class LegacyConfigLoader { protected final @NotNull File configFile; @@ -16,7 +15,8 @@ public abstract class LegacyConfigLoader { protected @NotNull String fileName; protected YamlConfiguration config; - public LegacyConfigLoader(@NotNull String relativePath, @NotNull String fileName, @NotNull File dataFolder) { + public LegacyConfigLoader(@NotNull String relativePath, @NotNull String fileName, + @NotNull File dataFolder) { this.fileName = fileName; this.dataFolder = dataFolder; configFile = new File(dataFolder, relativePath + File.separator + fileName); @@ -61,7 +61,9 @@ public abstract class LegacyConfigLoader { try { mcMMO.p.saveResource(fileName, false); // Normal files } catch (IllegalArgumentException ex) { - mcMMO.p.saveResource(configFile.getParentFile().getName() + File.separator + fileName, false); // Mod files + mcMMO.p.saveResource( + configFile.getParentFile().getName() + File.separator + fileName, + false); // Mod files } } else { LogUtils.debug(mcMMO.p.getLogger(), "Loading mcMMO " + fileName + " File..."); @@ -88,7 +90,8 @@ public abstract class LegacyConfigLoader { if (validateKeys()) { LogUtils.debug(mcMMO.p.getLogger(), "No errors found in " + fileName + "!"); } else { - mcMMO.p.getLogger().warning("Errors were found in " + fileName + "! mcMMO was disabled!"); + mcMMO.p.getLogger() + .warning("Errors were found in " + fileName + "! mcMMO was disabled!"); mcMMO.p.getServer().getPluginManager().disablePlugin(mcMMO.p); mcMMO.p.noErrorsInConfigFiles = false; } @@ -100,7 +103,9 @@ public abstract class LegacyConfigLoader { public void backup() { mcMMO.p.getLogger().warning("You are using an old version of the " + fileName + " file."); - mcMMO.p.getLogger().warning("Your old file has been renamed to " + fileName + ".old and has been replaced by an updated version."); + mcMMO.p.getLogger().warning( + "Your old file has been renamed to " + fileName + + ".old and has been replaced by an updated version."); configFile.renameTo(new File(configFile.getPath() + ".old")); diff --git a/src/main/java/com/gmail/nossr50/config/RankConfig.java b/src/main/java/com/gmail/nossr50/config/RankConfig.java index d892ecda4..f7a2e3000 100644 --- a/src/main/java/com/gmail/nossr50/config/RankConfig.java +++ b/src/main/java/com/gmail/nossr50/config/RankConfig.java @@ -4,11 +4,10 @@ import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.subskills.AbstractSubSkill; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.LogUtils; -import org.jetbrains.annotations.NotNull; - import java.util.ArrayList; import java.util.HashSet; import java.util.List; +import org.jetbrains.annotations.NotNull; public class RankConfig extends BukkitConfig { private static RankConfig instance; @@ -20,8 +19,9 @@ public class RankConfig extends BukkitConfig { } public static RankConfig getInstance() { - if (instance == null) + if (instance == null) { return new RankConfig(); + } return instance; } @@ -47,8 +47,7 @@ public class RankConfig extends BukkitConfig { * Returns the unlock level for a subskill depending on the gamemode * * @param subSkillType target subskill - * @param rank the rank we are checking - * + * @param rank the rank we are checking * @return the level requirement for a subskill at this particular rank */ public int getSubSkillUnlockLevel(SubSkillType subSkillType, int rank) { @@ -61,8 +60,7 @@ public class RankConfig extends BukkitConfig { * Returns the unlock level for a subskill depending on the gamemode * * @param subSkillType target subskill - * @param rank the rank we are checking - * + * @param rank the rank we are checking * @return the level requirement for a subskill at this particular rank */ public int getSubSkillUnlockLevel(SubSkillType subSkillType, int rank, boolean retroMode) { @@ -74,12 +72,12 @@ public class RankConfig extends BukkitConfig { * Returns the unlock level for a subskill depending on the gamemode * * @param abstractSubSkill target subskill - * @param rank the rank we are checking - * + * @param rank the rank we are checking * @return the level requirement for a subskill at this particular rank */ public int getSubSkillUnlockLevel(AbstractSubSkill abstractSubSkill, int rank) { - String key = abstractSubSkill.getPrimaryKeyName() + "." + abstractSubSkill.getConfigKeyName(); + String key = + abstractSubSkill.getPrimaryKeyName() + "." + abstractSubSkill.getConfigKeyName(); return findRankByRootAddress(rank, key); } @@ -87,13 +85,13 @@ public class RankConfig extends BukkitConfig { /** * Returns the unlock level for a subskill depending on the gamemode * - * @param key root address of the subskill in the rankskills.yml file + * @param key root address of the subskill in the rankskills.yml file * @param rank the rank we are checking - * * @return the level requirement for a subskill at this particular rank */ private int findRankByRootAddress(int rank, String key) { - String scalingKey = mcMMO.p.getGeneralConfig().getIsRetroMode() ? ".RetroMode." : ".Standard."; + String scalingKey = + mcMMO.p.getGeneralConfig().getIsRetroMode() ? ".RetroMode." : ".Standard."; String targetRank = "Rank_" + rank; @@ -145,18 +143,26 @@ public class RankConfig extends BukkitConfig { checkConfig(reasons, badSkillSetup, false); //Fix bad entries - if (badSkillSetup.isEmpty()) + if (badSkillSetup.isEmpty()) { return; + } - LogUtils.debug(mcMMO.p.getLogger(), "(FIXING CONFIG) mcMMO is correcting a few mistakes found in your skill rank config setup"); + LogUtils.debug( + mcMMO.p.getLogger(), + "(FIXING CONFIG) mcMMO is correcting a few mistakes found in your skill rank config setup"); for (SubSkillType subSkillType : badSkillSetup) { - LogUtils.debug(mcMMO.p.getLogger(), "(FIXING CONFIG) Resetting rank config settings for skill named - " + subSkillType.toString()); + LogUtils.debug( + mcMMO.p.getLogger(), + "(FIXING CONFIG) Resetting rank config settings for skill named - " + + subSkillType.toString()); fixBadEntries(subSkillType); } } - private void checkConfig(@NotNull List reasons, @NotNull HashSet badSkillSetup, boolean retroMode) { + private void checkConfig(@NotNull List reasons, + @NotNull HashSet badSkillSetup, + boolean retroMode) { for (SubSkillType subSkillType : SubSkillType.values()) { //Keeping track of the rank requirements and making sure there are no logical errors int curRank = 0; @@ -165,21 +171,27 @@ public class RankConfig extends BukkitConfig { for (int x = 0; x < subSkillType.getNumRanks(); x++) { int index = x + 1; - if (curRank > 0) + if (curRank > 0) { prevRank = curRank; + } curRank = getSubSkillUnlockLevel(subSkillType, index, retroMode); //Do we really care if its below 0? Probably not if (curRank < 0) { - reasons.add("(CONFIG ISSUE) " + subSkillType + " should not have any ranks that require a negative level!"); + reasons.add( + "(CONFIG ISSUE) " + subSkillType + + " should not have any ranks that require a negative level!"); badSkillSetup.add(subSkillType); continue; } if (prevRank > curRank) { //We're going to allow this but we're going to warn them - LogUtils.debug(mcMMO.p.getLogger(), "(CONFIG ISSUE) You have the ranks for the subskill " + subSkillType + " set up poorly, sequential ranks should have ascending requirements"); + LogUtils.debug( + mcMMO.p.getLogger(), + "(CONFIG ISSUE) You have the ranks for the subskill " + subSkillType + + " set up poorly, sequential ranks should have ascending requirements"); badSkillSetup.add(subSkillType); } } diff --git a/src/main/java/com/gmail/nossr50/config/SoundConfig.java b/src/main/java/com/gmail/nossr50/config/SoundConfig.java index 4b80352b6..3ad71fa98 100644 --- a/src/main/java/com/gmail/nossr50/config/SoundConfig.java +++ b/src/main/java/com/gmail/nossr50/config/SoundConfig.java @@ -14,8 +14,9 @@ public class SoundConfig extends BukkitConfig { } public static SoundConfig getInstance() { - if (instance == null) + if (instance == null) { return new SoundConfig(); + } return instance; } @@ -29,14 +30,16 @@ public class SoundConfig extends BukkitConfig { protected boolean validateKeys() { for (SoundType soundType : SoundType.values()) { if (config.getDouble("Sounds." + soundType.toString() + ".Volume") < 0) { - LogUtils.debug(mcMMO.p.getLogger(), "[mcMMO] Sound volume cannot be below 0 for " + soundType); + LogUtils.debug(mcMMO.p.getLogger(), + "[mcMMO] Sound volume cannot be below 0 for " + soundType); return false; } //Sounds with custom pitching don't use pitch values if (!soundType.usesCustomPitch()) { if (config.getDouble("Sounds." + soundType + ".Pitch") < 0) { - LogUtils.debug(mcMMO.p.getLogger(), "[mcMMO] Sound pitch cannot be below 0 for " + soundType); + LogUtils.debug(mcMMO.p.getLogger(), + "[mcMMO] Sound pitch cannot be below 0 for " + soundType); return false; } } diff --git a/src/main/java/com/gmail/nossr50/config/WorldBlacklist.java b/src/main/java/com/gmail/nossr50/config/WorldBlacklist.java index d92d2778f..8899e6964 100644 --- a/src/main/java/com/gmail/nossr50/config/WorldBlacklist.java +++ b/src/main/java/com/gmail/nossr50/config/WorldBlacklist.java @@ -1,10 +1,13 @@ package com.gmail.nossr50.config; import com.gmail.nossr50.mcMMO; -import org.bukkit.World; - -import java.io.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Reader; import java.util.ArrayList; +import org.bukkit.World; /** * Blacklist certain features in certain worlds @@ -24,8 +27,9 @@ public class WorldBlacklist { public static boolean isWorldBlacklisted(World world) { for (String s : blacklist) { - if (world.getName().equalsIgnoreCase(s)) + if (world.getName().equalsIgnoreCase(s)) { return true; + } } return false; @@ -36,8 +40,9 @@ public class WorldBlacklist { File blackListFile = new File(plugin.getDataFolder() + File.separator + blackListFileName); try { - if (!blackListFile.exists()) + if (!blackListFile.exists()) { blackListFile.createNewFile(); + } } catch (IOException e) { e.printStackTrace(); } @@ -57,11 +62,13 @@ public class WorldBlacklist { String currentLine; while ((currentLine = bufferedReader.readLine()) != null) { - if (currentLine.length() == 0) + if (currentLine.length() == 0) { continue; + } - if (!blacklist.contains(currentLine)) + if (!blacklist.contains(currentLine)) { blacklist.add(currentLine); + } } @@ -73,8 +80,9 @@ public class WorldBlacklist { closeRead(fileReader); } - if (blacklist.size() > 0) + if (blacklist.size() > 0) { plugin.getLogger().info(blacklist.size() + " entries in mcMMO World Blacklist"); + } } private void closeRead(Reader reader) { 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 5b38cdef0..eb9d6dd11 100644 --- a/src/main/java/com/gmail/nossr50/config/experience/ExperienceConfig.java +++ b/src/main/java/com/gmail/nossr50/config/experience/ExperienceConfig.java @@ -1,11 +1,18 @@ package com.gmail.nossr50.config.experience; +import static com.gmail.nossr50.util.text.ConfigStringUtils.getConfigEntityTypeString; +import static com.gmail.nossr50.util.text.ConfigStringUtils.getMaterialConfigString; + import com.gmail.nossr50.config.BukkitConfig; import com.gmail.nossr50.datatypes.experience.FormulaType; import com.gmail.nossr50.datatypes.skills.MaterialType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.alchemy.PotionStage; import com.gmail.nossr50.util.text.StringUtils; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockState; @@ -14,14 +21,6 @@ import org.bukkit.boss.BarColor; import org.bukkit.boss.BarStyle; import org.bukkit.entity.EntityType; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static com.gmail.nossr50.util.text.ConfigStringUtils.getConfigEntityTypeString; -import static com.gmail.nossr50.util.text.ConfigStringUtils.getMaterialConfigString; - public class ExperienceConfig extends BukkitConfig { private static ExperienceConfig instance; final private Map> blockExperienceMap = new HashMap<>(); @@ -65,7 +64,8 @@ public class ExperienceConfig extends BukkitConfig { /* Curve values */ if (getMultiplier(FormulaType.EXPONENTIAL) <= 0) { - reason.add("Experience_Formula.Exponential_Values.multiplier should be greater than 0!"); + reason.add( + "Experience_Formula.Exponential_Values.multiplier should be greater than 0!"); } if (getMultiplier(FormulaType.LINEAR) <= 0) { @@ -108,7 +108,9 @@ public class ExperienceConfig extends BukkitConfig { /* Alchemy */ for (PotionStage potionStage : PotionStage.values()) { if (getPotionXP(potionStage) < 0) { - reason.add("Experience_Values.Alchemy.Potion_Stage_" + potionStage.toNumerical() + " should be at least 0!"); + reason.add( + "Experience_Values.Alchemy.Potion_Stage_" + potionStage.toNumerical() + + " should be at least 0!"); } } @@ -230,15 +232,20 @@ public class ExperienceConfig extends BukkitConfig { /* Curve values */ public double getMultiplier(FormulaType type) { - return config.getDouble("Experience_Formula." + StringUtils.getCapitalized(type.toString()) + "_Values.multiplier"); + return config.getDouble( + "Experience_Formula." + StringUtils.getCapitalized(type.toString()) + + "_Values.multiplier"); } public int getBase(FormulaType type) { - return config.getInt("Experience_Formula." + StringUtils.getCapitalized(type.toString()) + "_Values.base"); + return config.getInt("Experience_Formula." + StringUtils.getCapitalized(type.toString()) + + "_Values.base"); } public double getExponent(FormulaType type) { - return config.getDouble("Experience_Formula." + StringUtils.getCapitalized(type.toString()) + "_Values.exponent"); + return config.getDouble( + "Experience_Formula." + StringUtils.getCapitalized(type.toString()) + + "_Values.exponent"); } /* Global modifier */ @@ -278,7 +285,10 @@ public class ExperienceConfig extends BukkitConfig { /* Skill modifiers */ public double getFormulaSkillModifier(PrimarySkillType skill) { - return config.getDouble("Experience_Formula.Skill_Multiplier." + StringUtils.getCapitalized(skill.toString()), 1); + return config.getDouble( + "Experience_Formula.Skill_Multiplier." + StringUtils.getCapitalized( + skill.toString()), + 1); } /* Custom XP perk */ @@ -296,7 +306,9 @@ public class ExperienceConfig extends BukkitConfig { } public int getDiminishedReturnsThreshold(PrimarySkillType skill) { - return config.getInt("Diminished_Returns.Threshold." + StringUtils.getCapitalized(skill.toString()), 20000); + return config.getInt( + "Diminished_Returns.Threshold." + StringUtils.getCapitalized(skill.toString()), + 20000); } public int getDiminishedReturnsTimeInterval() { @@ -323,11 +335,16 @@ public class ExperienceConfig extends BukkitConfig { } public double getCombatXP(EntityType entity) { - return config.getDouble("Experience_Values.Combat.Multiplier." + getConfigEntityTypeString(entity).replace(" ", "_")); + return config.getDouble( + "Experience_Values.Combat.Multiplier." + getConfigEntityTypeString(entity).replace( + " ", "_")); } public double getAnimalsXP(EntityType entity) { - return config.getDouble("Experience_Values.Combat.Multiplier." + getConfigEntityTypeString(entity).replace(" ", "_"), getAnimalsXP()); + return config.getDouble( + "Experience_Values.Combat.Multiplier." + getConfigEntityTypeString(entity).replace( + " ", "_"), + getAnimalsXP()); } public double getAnimalsXP() { @@ -335,16 +352,20 @@ public class ExperienceConfig extends BukkitConfig { } public boolean hasCombatXP(EntityType entity) { - return config.contains("Experience_Values.Combat.Multiplier." + getConfigEntityTypeString(entity).replace(" ", "_")); + return config.contains( + "Experience_Values.Combat.Multiplier." + getConfigEntityTypeString(entity).replace( + " ", "_")); } /* Materials */ private int getConfigXp(PrimarySkillType skill, Material material) { // prevents exploit - if (material == Material.LILY_PAD) + if (material == Material.LILY_PAD) { return 0; + } - final String baseString = "Experience_Values." + StringUtils.getCapitalized(skill.toString()) + "."; + final String baseString = + "Experience_Values." + StringUtils.getCapitalized(skill.toString()) + "."; final String configPath = baseString + getMaterialConfigString(material); return config.getInt(configPath, 0); } @@ -388,12 +409,17 @@ public class ExperienceConfig extends BukkitConfig { } public boolean getDoExperienceBarsAlwaysUpdateTitle() { - return config.getBoolean("Experience_Bars.ThisMayCauseLag.AlwaysUpdateTitlesWhenXPIsGained.Enable", false) || getAddExtraDetails(); + return config.getBoolean( + "Experience_Bars.ThisMayCauseLag.AlwaysUpdateTitlesWhenXPIsGained.Enable", + false) || getAddExtraDetails(); } public boolean getAddExtraDetails() { - return config.getBoolean("Experience_Bars.ThisMayCauseLag.AlwaysUpdateTitlesWhenXPIsGained.ExtraDetails", false); + return config.getBoolean( + "Experience_Bars.ThisMayCauseLag.AlwaysUpdateTitlesWhenXPIsGained.ExtraDetails", + false); } + public boolean useCombatHPCeiling() { return config.getBoolean("ExploitFix.Combat.XPCeiling.Enabled", true); } @@ -407,15 +433,20 @@ public class ExperienceConfig extends BukkitConfig { } public boolean isExperienceBarEnabled(PrimarySkillType primarySkillType) { - return config.getBoolean("Experience_Bars." + StringUtils.getCapitalized(primarySkillType.toString()) + ".Enable", true); + return config.getBoolean( + "Experience_Bars." + StringUtils.getCapitalized(primarySkillType.toString()) + + ".Enable", true); } public BarColor getExperienceBarColor(PrimarySkillType primarySkillType) { - String colorValueFromConfig = config.getString("Experience_Bars." + StringUtils.getCapitalized(primarySkillType.toString()) + ".Color"); + String colorValueFromConfig = config.getString( + "Experience_Bars." + StringUtils.getCapitalized(primarySkillType.toString()) + + ".Color"); for (BarColor barColor : BarColor.values()) { - if (barColor.toString().equalsIgnoreCase(colorValueFromConfig)) + if (barColor.toString().equalsIgnoreCase(colorValueFromConfig)) { return barColor; + } } //In case the value is invalid @@ -423,11 +454,14 @@ public class ExperienceConfig extends BukkitConfig { } public BarStyle getExperienceBarStyle(PrimarySkillType primarySkillType) { - String colorValueFromConfig = config.getString("Experience_Bars." + StringUtils.getCapitalized(primarySkillType.toString()) + ".BarStyle"); + String colorValueFromConfig = config.getString( + "Experience_Bars." + StringUtils.getCapitalized(primarySkillType.toString()) + + ".BarStyle"); for (BarStyle barStyle : BarStyle.values()) { - if (barStyle.toString().equalsIgnoreCase(colorValueFromConfig)) + if (barStyle.toString().equalsIgnoreCase(colorValueFromConfig)) { return barStyle; + } } //In case the value is invalid @@ -453,7 +487,8 @@ public class ExperienceConfig extends BukkitConfig { /* Alchemy */ public double getPotionXP(PotionStage stage) { - return config.getDouble("Experience_Values.Alchemy.Potion_Brewing.Stage_" + stage.toNumerical(), 10D); + return config.getDouble( + "Experience_Values.Alchemy.Potion_Brewing.Stage_" + stage.toNumerical(), 10D); } /* Archery */ @@ -471,12 +506,15 @@ public class ExperienceConfig extends BukkitConfig { } public double getRepairXP(MaterialType repairMaterialType) { - return config.getDouble("Experience_Values.Repair." + StringUtils.getCapitalized(repairMaterialType.toString())); + return config.getDouble( + "Experience_Values.Repair." + StringUtils.getCapitalized( + repairMaterialType.toString())); } /* Taming */ public int getTamingXP(EntityType type) { - return config.getInt("Experience_Values.Taming.Animal_Taming." + getConfigEntityTypeString(type)); + return config.getInt( + "Experience_Values.Taming.Animal_Taming." + getConfigEntityTypeString(type)); } public boolean preventStoneLavaFarming() { diff --git a/src/main/java/com/gmail/nossr50/config/party/ItemWeightConfig.java b/src/main/java/com/gmail/nossr50/config/party/ItemWeightConfig.java index 0d23230de..ad5b183f9 100644 --- a/src/main/java/com/gmail/nossr50/config/party/ItemWeightConfig.java +++ b/src/main/java/com/gmail/nossr50/config/party/ItemWeightConfig.java @@ -1,12 +1,11 @@ package com.gmail.nossr50.config.party; -import com.gmail.nossr50.config.BukkitConfig; -import org.bukkit.Material; +import static com.gmail.nossr50.util.text.ConfigStringUtils.getMaterialConfigString; +import com.gmail.nossr50.config.BukkitConfig; import java.util.HashSet; import java.util.Locale; - -import static com.gmail.nossr50.util.text.ConfigStringUtils.getMaterialConfigString; +import org.bukkit.Material; public class ItemWeightConfig extends BukkitConfig { private static ItemWeightConfig instance; @@ -24,7 +23,9 @@ public class ItemWeightConfig extends BukkitConfig { } public int getItemWeight(Material material) { - return config.getInt("Item_Weights." + getMaterialConfigString(material).replace(" ", "_"), config.getInt("Item_Weights.Default")); + return config.getInt( + "Item_Weights." + getMaterialConfigString(material).replace(" ", "_"), + config.getInt("Item_Weights.Default")); } public HashSet getMiscItems() { diff --git a/src/main/java/com/gmail/nossr50/config/party/PartyConfig.java b/src/main/java/com/gmail/nossr50/config/party/PartyConfig.java index cf4ce277d..3d10851e2 100644 --- a/src/main/java/com/gmail/nossr50/config/party/PartyConfig.java +++ b/src/main/java/com/gmail/nossr50/config/party/PartyConfig.java @@ -1,7 +1,6 @@ package com.gmail.nossr50.config.party; import com.gmail.nossr50.config.BukkitConfig; - import java.io.File; public class PartyConfig extends BukkitConfig { 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 39fb5adba..de202e5e3 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 @@ -1,10 +1,20 @@ package com.gmail.nossr50.config.skills.alchemy; +import static com.gmail.nossr50.util.ItemUtils.setItemName; +import static com.gmail.nossr50.util.PotionUtil.matchPotionType; +import static com.gmail.nossr50.util.PotionUtil.setBasePotionType; +import static com.gmail.nossr50.util.PotionUtil.setUpgradedAndExtendedProperties; + import com.gmail.nossr50.config.LegacyConfigLoader; import com.gmail.nossr50.datatypes.skills.alchemy.AlchemyPotion; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.ItemUtils; import com.gmail.nossr50.util.LogUtils; +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.Material; @@ -18,15 +28,6 @@ import org.bukkit.potion.PotionType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.VisibleForTesting; -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static com.gmail.nossr50.util.ItemUtils.setItemName; -import static com.gmail.nossr50.util.PotionUtil.*; - public class PotionConfig extends LegacyConfigLoader { private static final String BREEZE_ROD_STR = "BREEZE_ROD"; private static final String INFESTED_EFFECT_STR = "INFESTED"; @@ -45,16 +46,19 @@ public class PotionConfig extends LegacyConfigLoader { private final List concoctionsIngredientsTierSix = new ArrayList<>(); private final List concoctionsIngredientsTierSeven = new ArrayList<>(); private final List concoctionsIngredientsTierEight = new ArrayList<>(); - private final AlchemyPotionConfigResult INCOMPATIBLE_POTION_RESULT = new AlchemyPotionConfigResult(null, + private final AlchemyPotionConfigResult INCOMPATIBLE_POTION_RESULT = new AlchemyPotionConfigResult( + null, AlchemyPotionConfigResultType.INCOMPATIBLE); - private final AlchemyPotionConfigResult ERROR_POTION_RESULT = new AlchemyPotionConfigResult(null, + private final AlchemyPotionConfigResult ERROR_POTION_RESULT = new AlchemyPotionConfigResult( + null, AlchemyPotionConfigResultType.ERROR); - record AlchemyPotionConfigResult(AlchemyPotion alchemyPotion, AlchemyPotionConfigResultType resultType) {} + record AlchemyPotionConfigResult(AlchemyPotion alchemyPotion, + AlchemyPotionConfigResultType resultType) { + } + enum AlchemyPotionConfigResultType { - LOADED, - INCOMPATIBLE, - ERROR; + LOADED, INCOMPATIBLE, ERROR } /** @@ -82,17 +86,26 @@ public class PotionConfig extends LegacyConfigLoader { @VisibleForTesting void loadConcoctions() { - final ConfigurationSection concoctionSection = config.getConfigurationSection("Concoctions"); + final ConfigurationSection concoctionSection = config.getConfigurationSection( + "Concoctions"); // Load the ingredients for each tier - loadConcoctionsTier(concoctionsIngredientsTierOne, concoctionSection.getStringList("Tier_One_Ingredients")); - loadConcoctionsTier(concoctionsIngredientsTierTwo, concoctionSection.getStringList("Tier_Two_Ingredients")); - loadConcoctionsTier(concoctionsIngredientsTierThree, concoctionSection.getStringList("Tier_Three_Ingredients")); - loadConcoctionsTier(concoctionsIngredientsTierFour, concoctionSection.getStringList("Tier_Four_Ingredients")); - loadConcoctionsTier(concoctionsIngredientsTierFive, concoctionSection.getStringList("Tier_Five_Ingredients")); - loadConcoctionsTier(concoctionsIngredientsTierSix, concoctionSection.getStringList("Tier_Six_Ingredients")); - loadConcoctionsTier(concoctionsIngredientsTierSeven, concoctionSection.getStringList("Tier_Seven_Ingredients")); - loadConcoctionsTier(concoctionsIngredientsTierEight, concoctionSection.getStringList("Tier_Eight_Ingredients")); + loadConcoctionsTier(concoctionsIngredientsTierOne, + concoctionSection.getStringList("Tier_One_Ingredients")); + loadConcoctionsTier(concoctionsIngredientsTierTwo, + concoctionSection.getStringList("Tier_Two_Ingredients")); + loadConcoctionsTier(concoctionsIngredientsTierThree, + concoctionSection.getStringList("Tier_Three_Ingredients")); + loadConcoctionsTier(concoctionsIngredientsTierFour, + concoctionSection.getStringList("Tier_Four_Ingredients")); + loadConcoctionsTier(concoctionsIngredientsTierFive, + concoctionSection.getStringList("Tier_Five_Ingredients")); + loadConcoctionsTier(concoctionsIngredientsTierSix, + concoctionSection.getStringList("Tier_Six_Ingredients")); + loadConcoctionsTier(concoctionsIngredientsTierSeven, + concoctionSection.getStringList("Tier_Seven_Ingredients")); + loadConcoctionsTier(concoctionsIngredientsTierEight, + concoctionSection.getStringList("Tier_Eight_Ingredients")); concoctionsIngredientsTierTwo.addAll(concoctionsIngredientsTierOne); concoctionsIngredientsTierThree.addAll(concoctionsIngredientsTierTwo); @@ -103,7 +116,8 @@ public class PotionConfig extends LegacyConfigLoader { concoctionsIngredientsTierEight.addAll(concoctionsIngredientsTierSeven); } - private void loadConcoctionsTier(List ingredientList, List ingredientStrings) { + private void loadConcoctionsTier(List ingredientList, + List ingredientStrings) { if (ingredientStrings != null && !ingredientStrings.isEmpty()) { for (String ingredientString : ingredientStrings) { ItemStack ingredient = loadIngredient(ingredientString); @@ -114,6 +128,7 @@ public class PotionConfig extends LegacyConfigLoader { } } } + /** * Find the Potions configuration section and load all defined potions. */ @@ -124,14 +139,16 @@ public class PotionConfig extends LegacyConfigLoader { int failures = 0; for (String potionName : potionSection.getKeys(false)) { - AlchemyPotionConfigResult alchemyPotionConfigResult = loadPotion(potionSection.getConfigurationSection(potionName)); + AlchemyPotionConfigResult alchemyPotionConfigResult = loadPotion( + potionSection.getConfigurationSection(potionName)); AlchemyPotion potion = alchemyPotionConfigResult.alchemyPotion; if (potion != null) { alchemyPotions.put(potionName, potion); potionsLoaded++; } else { - if (alchemyPotionConfigResult.resultType == AlchemyPotionConfigResultType.INCOMPATIBLE) { + if (alchemyPotionConfigResult.resultType + == AlchemyPotionConfigResultType.INCOMPATIBLE) { incompatible++; } else { failures++; @@ -141,14 +158,18 @@ public class PotionConfig extends LegacyConfigLoader { int totalPotions = potionsLoaded + incompatible + failures; - mcMMO.p.getLogger().info("Loaded " + potionsLoaded + " of " + totalPotions + " Alchemy potions."); + mcMMO.p.getLogger() + .info("Loaded " + potionsLoaded + " of " + totalPotions + " Alchemy potions."); if (incompatible > 0) { - mcMMO.p.getLogger().info("Skipped " + incompatible + " Alchemy potions that require a newer" + - " Minecraft game version."); + mcMMO.p.getLogger().info( + "Skipped " + incompatible + " Alchemy potions that require a newer" + + " Minecraft game version."); } if (failures > 0) { - mcMMO.p.getLogger().info("Failed to load " + failures + " Alchemy potions that encountered errors while loading."); + mcMMO.p.getLogger().info( + "Failed to load " + failures + + " Alchemy potions that encountered errors while loading."); } return potionsLoaded; } @@ -157,7 +178,8 @@ public class PotionConfig extends LegacyConfigLoader { try { final String key = potion_section.getName(); - final ConfigurationSection potionData = potion_section.getConfigurationSection("PotionData"); + final ConfigurationSection potionData = potion_section.getConfigurationSection( + "PotionData"); boolean extended = false; boolean upgraded = false; @@ -171,13 +193,17 @@ public class PotionConfig extends LegacyConfigLoader { if (materialString != null) { material = ItemUtils.exhaustiveMaterialLookup(materialString); if (material == null) { - mcMMO.p.getLogger().warning("PotionConfig: Failed to parse material for potion " + key + ": " + materialString); + mcMMO.p.getLogger().warning( + "PotionConfig: Failed to parse material for potion " + key + ": " + + materialString); mcMMO.p.getLogger().warning("PotionConfig: Defaulting to POTION"); material = Material.POTION; } } else { - mcMMO.p.getLogger().warning("PotionConfig: Missing Material config entry for potion " + key + "," + - " from configuration section: " + potion_section + ", defaulting to POTION"); + mcMMO.p.getLogger().warning( + "PotionConfig: Missing Material config entry for potion " + key + "," + + " from configuration section: " + potion_section + + ", defaulting to POTION"); material = Material.POTION; } @@ -185,29 +211,34 @@ public class PotionConfig extends LegacyConfigLoader { final PotionMeta potionMeta = (PotionMeta) itemStack.getItemMeta(); if (potionMeta == null) { - mcMMO.p.getLogger().severe("PotionConfig: Failed to get PotionMeta for " + key + ", from configuration section:" + - " " + potion_section); + mcMMO.p.getLogger().severe( + "PotionConfig: Failed to get PotionMeta for " + key + + ", from configuration section:" + " " + potion_section); return ERROR_POTION_RESULT; } // extended and upgraded seem to be mutually exclusive if (extended && upgraded) { - mcMMO.p.getLogger().warning("Potion " + key + " has both Extended and Upgraded set to true," + - " defaulting to Extended."); + mcMMO.p.getLogger().warning( + "Potion " + key + " has both Extended and Upgraded set to true," + + " defaulting to Extended."); upgraded = false; } String potionTypeStr = potionData.getString("PotionType", null); if (potionTypeStr == null) { - mcMMO.p.getLogger().severe("PotionConfig: Missing PotionType for " + key + ", from configuration section:" + - " " + potion_section); + mcMMO.p.getLogger().severe( + "PotionConfig: Missing PotionType for " + key + + ", from configuration section:" + " " + potion_section); return ERROR_POTION_RESULT; } // This works via side effects // TODO: Redesign later, side effects are stupid - if(!setPotionType(potionMeta, potionTypeStr, upgraded, extended)) { - mcMMO.p.getLogger().severe("PotionConfig: Failed to set parameters of potion for " + key + ": " + potionTypeStr); + if (!setPotionType(potionMeta, potionTypeStr, upgraded, extended)) { + mcMMO.p.getLogger().severe( + "PotionConfig: Failed to set parameters of potion for " + key + ": " + + potionTypeStr); return ERROR_POTION_RESULT; } @@ -222,21 +253,28 @@ public class PotionConfig extends LegacyConfigLoader { if (potion_section.contains("Effects")) { for (String effect : potion_section.getStringList("Effects")) { String[] parts = effect.split(" "); - if (isTrickyTrialsPotionEffect(parts[0]) - && !mcMMO.getCompatibilityManager().getMinecraftGameVersion().isAtLeast(1, 21, 0)) { - LogUtils.debug(mcMMO.p.getLogger(), "Skipping potion effect " + effect +" because it is not" + - " compatible with the current Minecraft game version."); + if (isTrickyTrialsPotionEffect(parts[0]) && !mcMMO.getCompatibilityManager() + .getMinecraftGameVersion() + .isAtLeast(1, 21, 0)) { + LogUtils.debug( + mcMMO.p.getLogger(), + "Skipping potion effect " + effect + " because it is not" + + " compatible with the current Minecraft game version."); return INCOMPATIBLE_POTION_RESULT; } - PotionEffectType type = parts.length > 0 ? PotionEffectType.getByName(parts[0]) : null; + PotionEffectType type = + parts.length > 0 ? PotionEffectType.getByName(parts[0]) : null; int amplifier = parts.length > 1 ? Integer.parseInt(parts[1]) : 0; int duration = parts.length > 2 ? Integer.parseInt(parts[2]) : 0; if (type != null) { - potionMeta.addCustomEffect(new PotionEffect(type, duration, amplifier), true); + potionMeta.addCustomEffect(new PotionEffect(type, duration, amplifier), + true); } else { - mcMMO.p.getLogger().severe("PotionConfig: Failed to parse effect for potion " + key + ": " + effect); + mcMMO.p.getLogger().severe( + "PotionConfig: Failed to parse effect for potion " + key + ": " + + effect); } } } @@ -251,19 +289,25 @@ public class PotionConfig extends LegacyConfigLoader { final Map children = new HashMap<>(); if (potion_section.contains("Children")) { - for (String childIngredient : potion_section.getConfigurationSection("Children").getKeys(false)) { + for (String childIngredient : potion_section.getConfigurationSection("Children") + .getKeys(false)) { // Breeze Rod was only for potions after 1.21.0 if (isTrickyTrialsIngredient(childIngredient) - && !mcMMO.getCompatibilityManager().getMinecraftGameVersion().isAtLeast(1, 21, 0)) { + && !mcMMO.getCompatibilityManager() + .getMinecraftGameVersion() + .isAtLeast(1, 21, 0)) { continue; } ItemStack ingredient = loadIngredient(childIngredient); if (ingredient != null) { - children.put(ingredient, - potion_section.getConfigurationSection("Children").getString(childIngredient)); + children.put( + ingredient, + potion_section.getConfigurationSection("Children") + .getString(childIngredient)); } else { mcMMO.p.getLogger().severe( - "PotionConfig: Failed to parse child for potion " + key + ": " + childIngredient); + "PotionConfig: Failed to parse child for potion " + key + ": " + + childIngredient); } } } @@ -272,30 +316,38 @@ public class PotionConfig extends LegacyConfigLoader { // TODO: Might not need to .setItemMeta itemStack.setItemMeta(potionMeta); - return new AlchemyPotionConfigResult(new AlchemyPotion(potion_section.getName(), itemStack, children), + return new AlchemyPotionConfigResult( + new AlchemyPotion(potion_section.getName(), itemStack, children), AlchemyPotionConfigResultType.LOADED); } catch (Exception e) { - mcMMO.p.getLogger().warning("PotionConfig: Failed to load Alchemy potion: " + potion_section.getName()); + mcMMO.p.getLogger().warning( + "PotionConfig: Failed to load Alchemy potion: " + potion_section.getName()); e.printStackTrace(); return ERROR_POTION_RESULT; } } private static boolean isTrickyTrialsIngredient(String ingredientStr) { - return ingredientStr.equalsIgnoreCase(BREEZE_ROD_STR) || ingredientStr.equalsIgnoreCase(SLIME_BLOCK_STR) - || ingredientStr.equalsIgnoreCase(COBWEB_STR) || ingredientStr.equalsIgnoreCase(STONE_STR); + return ingredientStr.equalsIgnoreCase(BREEZE_ROD_STR) || ingredientStr.equalsIgnoreCase( + SLIME_BLOCK_STR) || ingredientStr.equalsIgnoreCase(COBWEB_STR) + || ingredientStr.equalsIgnoreCase( + STONE_STR); } private static boolean isTrickyTrialsPotionEffect(String effectStr) { - return effectStr.equalsIgnoreCase(INFESTED_EFFECT_STR) || effectStr.equalsIgnoreCase(WEAVING_EFFECT_STR) - || effectStr.equalsIgnoreCase(OOZING_EFFECT_STR) || effectStr.equalsIgnoreCase(WIND_CHARGED_EFFECT_STR); + return effectStr.equalsIgnoreCase(INFESTED_EFFECT_STR) || effectStr.equalsIgnoreCase( + WEAVING_EFFECT_STR) || effectStr.equalsIgnoreCase(OOZING_EFFECT_STR) + || effectStr.equalsIgnoreCase( + WIND_CHARGED_EFFECT_STR); } - private boolean setPotionType(PotionMeta potionMeta, String potionTypeStr, boolean upgraded, boolean extended) { + private boolean setPotionType(PotionMeta potionMeta, String potionTypeStr, boolean upgraded, + boolean extended) { final PotionType potionType = matchPotionType(potionTypeStr, upgraded, extended); if (potionType == null) { - mcMMO.p.getLogger().severe("PotionConfig: Failed to parse potion type for: " + potionTypeStr); + mcMMO.p.getLogger() + .severe("PotionConfig: Failed to parse potion type for: " + potionTypeStr); return false; } @@ -320,12 +372,10 @@ public class PotionConfig extends LegacyConfigLoader { } /** - * Parse a string representation of an ingredient. - * Format: '<MATERIAL>[:data]' - * Returns null if input cannot be parsed. + * Parse a string representation of an ingredient. Format: '<MATERIAL>[:data]' Returns + * null if input cannot be parsed. * * @param ingredient String representing an ingredient. - * * @return Parsed ingredient. */ private ItemStack loadIngredient(String ingredient) { @@ -344,6 +394,7 @@ public class PotionConfig extends LegacyConfigLoader { /** * Get the ingredients for the given tier. + * * @param tier Tier to get ingredients for. * @return List of ingredients for the given tier. */ @@ -362,6 +413,7 @@ public class PotionConfig extends LegacyConfigLoader { /** * Check if the given ItemStack is a valid potion. + * * @param item ItemStack to be checked. * @return True if the given ItemStack is a valid potion, false otherwise. */ @@ -371,6 +423,7 @@ public class PotionConfig extends LegacyConfigLoader { /** * Get the AlchemyPotion that corresponds to the given name. + * * @param name Name of the potion to be checked. * @return AlchemyPotion that corresponds to the given name. */ @@ -382,19 +435,17 @@ public class PotionConfig extends LegacyConfigLoader { * Get the AlchemyPotion that corresponds to the given ItemStack. * * @param item ItemStack to be checked. - * * @return AlchemyPotion that corresponds to the given ItemStack. */ public AlchemyPotion getPotion(ItemStack item) { // Fast return if the item does not have any item meta to avoid initializing an unnecessary ItemMeta instance - if (!item.hasItemMeta()) + if (!item.hasItemMeta()) { return null; + } ItemMeta itemMeta = item.getItemMeta(); - final List potionList = alchemyPotions.values() - .stream() - .filter(potion -> potion.isSimilarPotion(item, itemMeta)) - .toList(); + final List potionList = alchemyPotions.values().stream().filter( + potion -> potion.isSimilarPotion(item, itemMeta)).toList(); return potionList.isEmpty() ? null : potionList.get(0); } diff --git a/src/main/java/com/gmail/nossr50/config/skills/repair/RepairConfig.java b/src/main/java/com/gmail/nossr50/config/skills/repair/RepairConfig.java index 1df5de82c..e85e369d5 100644 --- a/src/main/java/com/gmail/nossr50/config/skills/repair/RepairConfig.java +++ b/src/main/java/com/gmail/nossr50/config/skills/repair/RepairConfig.java @@ -8,12 +8,15 @@ import com.gmail.nossr50.skills.repair.repairables.Repairable; import com.gmail.nossr50.skills.repair.repairables.RepairableFactory; import com.gmail.nossr50.util.ItemUtils; import com.gmail.nossr50.util.LogUtils; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.inventory.ItemStack; -import java.util.*; - public class RepairConfig extends BukkitConfig { private final HashSet notSupported; private List repairables; @@ -56,7 +59,8 @@ public class RepairConfig extends BukkitConfig { // Repair Material Type MaterialType repairMaterialType = MaterialType.OTHER; - String repairMaterialTypeString = config.getString("Repairables." + key + ".MaterialType", "OTHER"); + String repairMaterialTypeString = config.getString( + "Repairables." + key + ".MaterialType", "OTHER"); if (!config.contains("Repairables." + key + ".MaterialType") && itemMaterial != null) { ItemStack repairItem = new ItemStack(itemMaterial); @@ -73,9 +77,11 @@ public class RepairConfig extends BukkitConfig { repairMaterialType = MaterialType.IRON; } else if (ItemUtils.isGoldArmor(repairItem) || ItemUtils.isGoldTool(repairItem)) { repairMaterialType = MaterialType.GOLD; - } else if (ItemUtils.isDiamondArmor(repairItem) || ItemUtils.isDiamondTool(repairItem)) { + } else if (ItemUtils.isDiamondArmor(repairItem) || ItemUtils.isDiamondTool( + repairItem)) { repairMaterialType = MaterialType.DIAMOND; - } else if (ItemUtils.isNetheriteArmor(repairItem) || ItemUtils.isNetheriteTool(repairItem)) { + } else if (ItemUtils.isNetheriteArmor(repairItem) || ItemUtils.isNetheriteTool( + repairItem)) { repairMaterialType = MaterialType.NETHERITE; } } else { @@ -88,7 +94,9 @@ public class RepairConfig extends BukkitConfig { // Repair Material String repairMaterialName = config.getString("Repairables." + key + ".RepairMaterial"); - Material repairMaterial = (repairMaterialName == null ? repairMaterialType.getDefaultMaterial() : Material.matchMaterial(repairMaterialName)); + Material repairMaterial = (repairMaterialName == null + ? repairMaterialType.getDefaultMaterial() + : Material.matchMaterial(repairMaterialName)); if (repairMaterial == null) { notSupported.add(key); //Collect names of unsupported items @@ -96,10 +104,13 @@ public class RepairConfig extends BukkitConfig { } // Maximum Durability - short maximumDurability = (itemMaterial != null ? itemMaterial.getMaxDurability() : (short) config.getInt("Repairables." + key + ".MaximumDurability")); + short maximumDurability = (itemMaterial != null ? itemMaterial.getMaxDurability() + : (short) config.getInt( + "Repairables." + key + ".MaximumDurability")); if (maximumDurability <= 0) { - maximumDurability = (short) config.getInt("Repairables." + key + ".MaximumDurability"); + maximumDurability = (short) config.getInt( + "Repairables." + key + ".MaximumDurability"); } if (maximumDurability <= 0) { @@ -108,7 +119,8 @@ public class RepairConfig extends BukkitConfig { // Item Type ItemType repairItemType = ItemType.OTHER; - String repairItemTypeString = config.getString("Repairables." + key + ".ItemType", "OTHER"); + String repairItemTypeString = config.getString("Repairables." + key + ".ItemType", + "OTHER"); if (!config.contains("Repairables." + key + ".ItemType") && itemMaterial != null) { ItemStack repairItem = new ItemStack(itemMaterial); @@ -141,7 +153,10 @@ public class RepairConfig extends BukkitConfig { } if (noErrorsInRepairable(reason)) { - Repairable repairable = RepairableFactory.getRepairable(itemMaterial, repairMaterial, null, minimumLevel, maximumDurability, repairItemType, repairMaterialType, xpMultiplier, minimumQuantity); + Repairable repairable = RepairableFactory.getRepairable( + itemMaterial, repairMaterial, null, minimumLevel, maximumDurability, + repairItemType, + repairMaterialType, xpMultiplier, minimumQuantity); repairables.add(repairable); } } @@ -149,7 +164,8 @@ public class RepairConfig extends BukkitConfig { StringBuilder stringBuilder = new StringBuilder(); if (notSupported.size() > 0) { - stringBuilder.append("mcMMO found the following materials in the Repair config that are not supported by the version of Minecraft running on this server: "); + stringBuilder.append( + "mcMMO found the following materials in the Repair config that are not supported by the version of Minecraft running on this server: "); for (Iterator iterator = notSupported.iterator(); iterator.hasNext(); ) { String unsupportedMaterial = iterator.next(); @@ -162,7 +178,8 @@ public class RepairConfig extends BukkitConfig { } LogUtils.debug(mcMMO.p.getLogger(), stringBuilder.toString()); - LogUtils.debug(mcMMO.p.getLogger(), "Items using materials that are not supported will simply be skipped."); + LogUtils.debug(mcMMO.p.getLogger(), + "Items using materials that are not supported will simply be skipped."); } } diff --git a/src/main/java/com/gmail/nossr50/config/skills/repair/RepairConfigManager.java b/src/main/java/com/gmail/nossr50/config/skills/repair/RepairConfigManager.java index 491a511ed..bab50ce38 100644 --- a/src/main/java/com/gmail/nossr50/config/skills/repair/RepairConfigManager.java +++ b/src/main/java/com/gmail/nossr50/config/skills/repair/RepairConfigManager.java @@ -2,7 +2,6 @@ package com.gmail.nossr50.config.skills.repair; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.skills.repair.repairables.Repairable; - import java.io.File; import java.util.Collection; import java.util.HashSet; @@ -20,8 +19,9 @@ public class RepairConfigManager { repairables.addAll(mainRepairConfig.getLoadedRepairables()); for (String fileName : dataFolder.list()) { - if (fileName.equals(REPAIR_VANILLA_YML)) + if (fileName.equals(REPAIR_VANILLA_YML)) { continue; + } if (!pattern.matcher(fileName).matches()) { continue; diff --git a/src/main/java/com/gmail/nossr50/config/skills/salvage/SalvageConfig.java b/src/main/java/com/gmail/nossr50/config/skills/salvage/SalvageConfig.java index 7d7ba2964..1a91ab504 100644 --- a/src/main/java/com/gmail/nossr50/config/skills/salvage/SalvageConfig.java +++ b/src/main/java/com/gmail/nossr50/config/skills/salvage/SalvageConfig.java @@ -10,14 +10,19 @@ import com.gmail.nossr50.skills.salvage.salvageables.SalvageableFactory; import com.gmail.nossr50.util.ItemUtils; import com.gmail.nossr50.util.LogUtils; import com.gmail.nossr50.util.skills.SkillUtils; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.logging.Level; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.inventory.ItemStack; -import java.io.IOException; -import java.util.*; -import java.util.logging.Level; - public class SalvageConfig extends BukkitConfig { private final HashSet notSupported; private Set salvageables; @@ -42,17 +47,26 @@ public class SalvageConfig extends BukkitConfig { //Original version of 1.16 support had maximum quantities that were bad, this fixes it if (mcMMO.getUpgradeManager().shouldUpgrade(UpgradeType.FIX_NETHERITE_SALVAGE_QUANTITIES)) { - mcMMO.p.getLogger().log(Level.INFO, "Fixing incorrect Salvage quantities on Netherite gear, this will only run once..."); + mcMMO.p.getLogger().log( + Level.INFO, + "Fixing incorrect Salvage quantities on Netherite gear, this will only run once..."); for (String namespacedkey : mcMMO.getMaterialMapStore().getNetheriteArmor()) { - config.set("Salvageables." + namespacedkey.toUpperCase(Locale.ENGLISH) + ".MaximumQuantity", 4); //TODO: Doesn't make sense to default to 4 for everything + config.set( + "Salvageables." + namespacedkey.toUpperCase(Locale.ENGLISH) + + ".MaximumQuantity", + 4); //TODO: Doesn't make sense to default to 4 for everything } try { config.save(getFile()); - mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.FIX_NETHERITE_SALVAGE_QUANTITIES); - LogUtils.debug(mcMMO.p.getLogger(), "Fixed incorrect Salvage quantities for Netherite gear!"); + mcMMO.getUpgradeManager() + .setUpgradeCompleted(UpgradeType.FIX_NETHERITE_SALVAGE_QUANTITIES); + LogUtils.debug(mcMMO.p.getLogger(), + "Fixed incorrect Salvage quantities for Netherite gear!"); } catch (IOException e) { - LogUtils.debug(mcMMO.p.getLogger(), "Unable to fix Salvage config, please delete the salvage yml file to generate a new one."); + LogUtils.debug( + mcMMO.p.getLogger(), + "Unable to fix Salvage config, please delete the salvage yml file to generate a new one."); e.printStackTrace(); } } @@ -71,7 +85,8 @@ public class SalvageConfig extends BukkitConfig { // Salvage Material Type MaterialType salvageMaterialType = MaterialType.OTHER; - String salvageMaterialTypeString = config.getString("Salvageables." + key + ".MaterialType", "OTHER"); + String salvageMaterialTypeString = config.getString( + "Salvageables." + key + ".MaterialType", "OTHER"); if (!config.contains("Salvageables." + key + ".MaterialType") && itemMaterial != null) { ItemStack salvageItem = new ItemStack(itemMaterial); @@ -86,26 +101,36 @@ public class SalvageConfig extends BukkitConfig { salvageMaterialType = MaterialType.PRISMARINE; } else if (ItemUtils.isLeatherArmor(salvageItem)) { salvageMaterialType = MaterialType.LEATHER; - } else if (ItemUtils.isIronArmor(salvageItem) || ItemUtils.isIronTool(salvageItem)) { + } else if (ItemUtils.isIronArmor(salvageItem) || ItemUtils.isIronTool( + salvageItem)) { salvageMaterialType = MaterialType.IRON; - } else if (ItemUtils.isGoldArmor(salvageItem) || ItemUtils.isGoldTool(salvageItem)) { + } else if (ItemUtils.isGoldArmor(salvageItem) || ItemUtils.isGoldTool( + salvageItem)) { salvageMaterialType = MaterialType.GOLD; - } else if (ItemUtils.isDiamondArmor(salvageItem) || ItemUtils.isDiamondTool(salvageItem)) { + } else if (ItemUtils.isDiamondArmor(salvageItem) || ItemUtils.isDiamondTool( + salvageItem)) { salvageMaterialType = MaterialType.DIAMOND; - } else if (ItemUtils.isNetheriteTool(salvageItem) || ItemUtils.isNetheriteArmor(salvageItem)) { + } else if (ItemUtils.isNetheriteTool(salvageItem) || ItemUtils.isNetheriteArmor( + salvageItem)) { salvageMaterialType = MaterialType.NETHERITE; } } else { try { - salvageMaterialType = MaterialType.valueOf(salvageMaterialTypeString.replace(" ", "_").toUpperCase(Locale.ENGLISH)); + salvageMaterialType = MaterialType.valueOf( + salvageMaterialTypeString.replace(" ", "_") + .toUpperCase(Locale.ENGLISH)); } catch (IllegalArgumentException ex) { - reason.add(key + " has an invalid MaterialType of " + salvageMaterialTypeString); + reason.add( + key + " has an invalid MaterialType of " + salvageMaterialTypeString); } } // Salvage Material - String salvageMaterialName = config.getString("Salvageables." + key + ".SalvageMaterial"); - Material salvageMaterial = (salvageMaterialName == null ? salvageMaterialType.getDefaultMaterial() : Material.matchMaterial(salvageMaterialName)); + String salvageMaterialName = config.getString( + "Salvageables." + key + ".SalvageMaterial"); + Material salvageMaterial = (salvageMaterialName == null + ? salvageMaterialType.getDefaultMaterial() + : Material.matchMaterial(salvageMaterialName)); if (salvageMaterial == null) { notSupported.add(key); @@ -113,11 +138,14 @@ public class SalvageConfig extends BukkitConfig { } // Maximum Durability - short maximumDurability = (itemMaterial != null ? itemMaterial.getMaxDurability() : (short) config.getInt("Salvageables." + key + ".MaximumDurability")); + short maximumDurability = (itemMaterial != null ? itemMaterial.getMaxDurability() + : (short) config.getInt( + "Salvageables." + key + ".MaximumDurability")); // Item Type ItemType salvageItemType = ItemType.OTHER; - String salvageItemTypeString = config.getString("Salvageables." + key + ".ItemType", "OTHER"); + String salvageItemTypeString = config.getString("Salvageables." + key + ".ItemType", + "OTHER"); if (!config.contains("Salvageables." + key + ".ItemType") && itemMaterial != null) { ItemStack salvageItem = new ItemStack(itemMaterial); @@ -129,7 +157,8 @@ public class SalvageConfig extends BukkitConfig { } } else { try { - salvageItemType = ItemType.valueOf(salvageItemTypeString.replace(" ", "_").toUpperCase(Locale.ENGLISH)); + salvageItemType = ItemType.valueOf( + salvageItemTypeString.replace(" ", "_").toUpperCase(Locale.ENGLISH)); } catch (IllegalArgumentException ex) { reason.add(key + " has an invalid ItemType of " + salvageItemTypeString); } @@ -143,15 +172,16 @@ public class SalvageConfig extends BukkitConfig { } // Maximum Quantity - int maximumQuantity = itemMaterial != null - ? SkillUtils.getRepairAndSalvageQuantities(itemMaterial, salvageMaterial) - : config.getInt("Salvageables." + key + ".MaximumQuantity", 1); + int maximumQuantity = itemMaterial != null ? SkillUtils.getRepairAndSalvageQuantities( + itemMaterial, + salvageMaterial) : config.getInt("Salvageables." + key + ".MaximumQuantity", 1); if (maximumQuantity <= 0 && itemMaterial != null) { maximumQuantity = config.getInt("Salvageables." + key + ".MaximumQuantity", 1); } - int configMaximumQuantity = config.getInt("Salvageables." + key + ".MaximumQuantity", -1); + int configMaximumQuantity = config.getInt("Salvageables." + key + ".MaximumQuantity", + -1); if (configMaximumQuantity > 0) { maximumQuantity = configMaximumQuantity; @@ -162,7 +192,10 @@ public class SalvageConfig extends BukkitConfig { } if (noErrorsInSalvageable(reason)) { - Salvageable salvageable = SalvageableFactory.getSalvageable(itemMaterial, salvageMaterial, minimumLevel, maximumQuantity, maximumDurability, salvageItemType, salvageMaterialType, xpMultiplier); + Salvageable salvageable = SalvageableFactory.getSalvageable( + itemMaterial, salvageMaterial, minimumLevel, + maximumQuantity, maximumDurability, salvageItemType, salvageMaterialType, + xpMultiplier); salvageables.add(salvageable); } } @@ -170,7 +203,8 @@ public class SalvageConfig extends BukkitConfig { StringBuilder stringBuilder = new StringBuilder(); if (notSupported.size() > 0) { - stringBuilder.append("mcMMO found the following materials in the Salvage config that are not supported by the version of Minecraft running on this server: "); + stringBuilder.append( + "mcMMO found the following materials in the Salvage config that are not supported by the version of Minecraft running on this server: "); for (Iterator iterator = notSupported.iterator(); iterator.hasNext(); ) { String unsupportedMaterial = iterator.next(); @@ -183,7 +217,8 @@ public class SalvageConfig extends BukkitConfig { } LogUtils.debug(mcMMO.p.getLogger(), stringBuilder.toString()); - LogUtils.debug(mcMMO.p.getLogger(), "Items using materials that are not supported will simply be skipped."); + LogUtils.debug(mcMMO.p.getLogger(), + "Items using materials that are not supported will simply be skipped."); } } diff --git a/src/main/java/com/gmail/nossr50/config/skills/salvage/SalvageConfigManager.java b/src/main/java/com/gmail/nossr50/config/skills/salvage/SalvageConfigManager.java index 1832da789..08477658a 100644 --- a/src/main/java/com/gmail/nossr50/config/skills/salvage/SalvageConfigManager.java +++ b/src/main/java/com/gmail/nossr50/config/skills/salvage/SalvageConfigManager.java @@ -2,7 +2,6 @@ package com.gmail.nossr50.config.skills.salvage; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.skills.salvage.salvageables.Salvageable; - import java.io.File; import java.util.ArrayList; import java.util.List; @@ -21,8 +20,9 @@ public class SalvageConfigManager { salvageables.addAll(mainSalvageConfig.getLoadedSalvageables()); for (String fileName : dataFolder.list()) { - if (fileName.equals(SALVAGE_VANILLA_YML)) + if (fileName.equals(SALVAGE_VANILLA_YML)) { continue; + } if (!pattern.matcher(fileName).matches()) { continue; 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 95788896c..2b0261b67 100755 --- a/src/main/java/com/gmail/nossr50/config/treasure/FishingTreasureConfig.java +++ b/src/main/java/com/gmail/nossr50/config/treasure/FishingTreasureConfig.java @@ -1,11 +1,22 @@ package com.gmail.nossr50.config.treasure; +import static com.gmail.nossr50.util.PotionUtil.matchPotionType; + import com.gmail.nossr50.config.BukkitConfig; -import com.gmail.nossr50.datatypes.treasure.*; +import com.gmail.nossr50.datatypes.treasure.EnchantmentTreasure; +import com.gmail.nossr50.datatypes.treasure.FishingTreasure; +import com.gmail.nossr50.datatypes.treasure.FishingTreasureBook; +import com.gmail.nossr50.datatypes.treasure.Rarity; +import com.gmail.nossr50.datatypes.treasure.ShakeTreasure; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.EnchantmentUtils; import com.gmail.nossr50.util.LogUtils; import com.gmail.nossr50.util.PotionUtil; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; @@ -17,10 +28,6 @@ import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionType; import org.jetbrains.annotations.NotNull; -import java.util.*; - -import static com.gmail.nossr50.util.PotionUtil.matchPotionType; - public class FishingTreasureConfig extends BukkitConfig { public static final String FILENAME = "fishing_treasures.yml"; @@ -48,7 +55,8 @@ public class FishingTreasureConfig extends BukkitConfig { protected boolean validateKeys() { // Validate all the settings! List reason = new ArrayList<>(); - ConfigurationSection enchantment_drop_rates = config.getConfigurationSection("Enchantment_Drop_Rates"); + ConfigurationSection enchantment_drop_rates = config.getConfigurationSection( + "Enchantment_Drop_Rates"); if (enchantment_drop_rates != null) { for (String tier : enchantment_drop_rates.getKeys(false)) { @@ -56,15 +64,21 @@ public class FishingTreasureConfig extends BukkitConfig { double totalItemDropRate = 0; for (Rarity rarity : Rarity.values()) { - double enchantDropRate = config.getDouble("Enchantment_Drop_Rates." + tier + "." + rarity.toString()); - double itemDropRate = config.getDouble("Item_Drop_Rates." + tier + "." + rarity); + double enchantDropRate = config.getDouble( + "Enchantment_Drop_Rates." + tier + "." + rarity.toString()); + double itemDropRate = config.getDouble( + "Item_Drop_Rates." + tier + "." + rarity); if ((enchantDropRate < 0.0 || enchantDropRate > 100.0)) { - reason.add("The enchant drop rate for " + tier + " items that are " + rarity + "should be between 0.0 and 100.0!"); + reason.add( + "The enchant drop rate for " + tier + " items that are " + rarity + + "should be between 0.0 and 100.0!"); } if (itemDropRate < 0.0 || itemDropRate > 100.0) { - reason.add("The item drop rate for " + tier + " items that are " + rarity + "should be between 0.0 and 100.0!"); + reason.add( + "The item drop rate for " + tier + " items that are " + rarity + + "should be between 0.0 and 100.0!"); } totalEnchantDropRate += enchantDropRate; @@ -72,15 +86,18 @@ public class FishingTreasureConfig extends BukkitConfig { } if (totalEnchantDropRate < 0 || totalEnchantDropRate > 100.0) { - reason.add("The total enchant drop rate for " + tier + " should be between 0.0 and 100.0!"); + reason.add("The total enchant drop rate for " + tier + + " should be between 0.0 and 100.0!"); } if (totalItemDropRate < 0 || totalItemDropRate > 100.0) { - reason.add("The total item drop rate for " + tier + " should be between 0.0 and 100.0!"); + reason.add("The total item drop rate for " + tier + + " should be between 0.0 and 100.0!"); } } } else { - mcMMO.p.getLogger().warning("Your fishing treasures config is empty, is this intentional? Delete it to regenerate."); + mcMMO.p.getLogger().warning( + "Your fishing treasures config is empty, is this intentional? Delete it to regenerate."); } return noErrorsInConfig(reason); @@ -134,17 +151,24 @@ public class FishingTreasureConfig extends BukkitConfig { if (materialName.contains("INVENTORY")) { // Use magic material BEDROCK to know that we're grabbing something from the inventory and not a normal treasure - addShakeTreasure(new ShakeTreasure(new ItemStack(Material.BEDROCK, 1, (byte) 0), 1, getInventoryStealDropChance(), getInventoryStealDropLevel()), EntityType.PLAYER); + addShakeTreasure( + new ShakeTreasure( + new ItemStack(Material.BEDROCK, 1, (byte) 0), 1, + getInventoryStealDropChance(), getInventoryStealDropLevel()), + EntityType.PLAYER); continue; } else { material = Material.matchMaterial(materialName); } int amount = config.getInt(type + "." + treasureName + ".Amount"); - short data = (treasureInfo.length == 2) ? Short.parseShort(treasureInfo[1]) : (short) config.getInt(type + "." + treasureName + ".Data"); + short data = (treasureInfo.length == 2) ? Short.parseShort(treasureInfo[1]) + : (short) config.getInt( + type + "." + treasureName + ".Data"); if (material == null) { - reason.add("Cannot find matching item type in this version of MC, skipping - " + materialName); + reason.add("Cannot find matching item type in this version of MC, skipping - " + + materialName); continue; } @@ -173,7 +197,8 @@ public class FishingTreasureConfig extends BukkitConfig { } if (dropLevel < 0) { - reason.add("Fishing Config: " + treasureName + " has an invalid Drop_Level: " + dropLevel); + reason.add("Fishing Config: " + treasureName + " has an invalid Drop_Level: " + + dropLevel); } /* @@ -187,8 +212,11 @@ public class FishingTreasureConfig extends BukkitConfig { if (rarityStr != null) { rarity = Rarity.getRarity(rarityStr); } else { - mcMMO.p.getLogger().severe("Please edit your config and add a Rarity definition for - " + treasureName); - mcMMO.p.getLogger().severe("Skipping this treasure until rarity is defined - " + treasureName); + mcMMO.p.getLogger().severe( + "Please edit your config and add a Rarity definition for - " + + treasureName); + mcMMO.p.getLogger().severe("Skipping this treasure until rarity is defined - " + + treasureName); continue; } } @@ -198,7 +226,6 @@ public class FishingTreasureConfig extends BukkitConfig { */ ItemStack item = null; - String customName = null; if (hasCustomName(type, treasureName)) { @@ -217,20 +244,28 @@ public class FishingTreasureConfig extends BukkitConfig { PotionMeta potionMeta = (PotionMeta) item.getItemMeta(); if (potionMeta == null) { - mcMMO.p.getLogger().severe("FishingConfig: Item meta when adding potion to fishing treasure was null," + - " contact the mcMMO devs!"); - reason.add("FishingConfig: Item meta when adding potion to fishing treasure was null"); + mcMMO.p.getLogger().severe( + "FishingConfig: Item meta when adding potion to fishing treasure was null," + + " contact the mcMMO devs!"); + reason.add( + "FishingConfig: Item meta when adding potion to fishing treasure was null"); continue; } String potionTypeStr; - potionTypeStr = config.getString(type + "." + treasureName + ".PotionData.PotionType", "WATER"); - boolean extended = config.getBoolean(type + "." + treasureName + ".PotionData.Extended", false); - boolean upgraded = config.getBoolean(type + "." + treasureName + ".PotionData.Upgraded", false); - final PotionType potionType = matchPotionType(potionTypeStr, extended, upgraded); + potionTypeStr = config.getString( + type + "." + treasureName + ".PotionData.PotionType", "WATER"); + boolean extended = config.getBoolean( + type + "." + treasureName + ".PotionData.Extended", false); + boolean upgraded = config.getBoolean( + type + "." + treasureName + ".PotionData.Upgraded", false); + final PotionType potionType = matchPotionType(potionTypeStr, extended, + upgraded); if (potionType == null) { - reason.add("FishingConfig: Could not derive potion type from: " + potionTypeStr +", " + extended + ", " + upgraded); + reason.add( + "FishingConfig: Could not derive potion type from: " + potionTypeStr + + ", " + extended + ", " + upgraded); continue; } @@ -239,7 +274,8 @@ public class FishingTreasureConfig extends BukkitConfig { PotionUtil.setBasePotionType(potionMeta, potionType, upgraded, extended); if (customName != null) { - potionMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', customName)); + potionMeta.setDisplayName( + ChatColor.translateAlternateColorCodes('&', customName)); } if (config.contains(type + "." + treasureName + ".Lore")) { @@ -256,8 +292,10 @@ public class FishingTreasureConfig extends BukkitConfig { item = new ItemStack(material, 1); ItemMeta itemMeta = item.getItemMeta(); - List allowedEnchantsList = config.getStringList(type + "." + treasureName + ".Enchantments_Whitelist"); - List disallowedEnchantsList = config.getStringList(type + "." + treasureName + ".Enchantments_Blacklist"); + List allowedEnchantsList = config.getStringList( + type + "." + treasureName + ".Enchantments_Whitelist"); + List disallowedEnchantsList = config.getStringList( + type + "." + treasureName + ".Enchantments_Blacklist"); Set blackListedEnchants = new HashSet<>(); Set whiteListedEnchants = new HashSet<>(); @@ -266,11 +304,14 @@ public class FishingTreasureConfig extends BukkitConfig { matchAndFillSet(allowedEnchantsList, whiteListedEnchants); if (customName != null && itemMeta != null) { - itemMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', customName)); + itemMeta.setDisplayName( + ChatColor.translateAlternateColorCodes('&', customName)); item.setItemMeta(itemMeta); } - FishingTreasureBook fishingTreasureBook = new FishingTreasureBook(item, xp, blackListedEnchants, whiteListedEnchants); + FishingTreasureBook fishingTreasureBook = new FishingTreasureBook( + item, xp, blackListedEnchants, + whiteListedEnchants); addFishingTreasure(rarity, fishingTreasureBook); //TODO: Add book support for shake continue; //The code in this whole file is a disaster, ignore this hacky solution :P @@ -279,7 +320,8 @@ public class FishingTreasureConfig extends BukkitConfig { if (customName != null) { ItemMeta itemMeta = item.getItemMeta(); - itemMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', customName)); + itemMeta.setDisplayName( + ChatColor.translateAlternateColorCodes('&', customName)); item.setItemMeta(itemMeta); } @@ -294,12 +336,12 @@ public class FishingTreasureConfig extends BukkitConfig { } } - if (noErrorsInConfig(reason)) { if (isFishing) { addFishingTreasure(rarity, new FishingTreasure(item, xp)); } else if (isShake) { - ShakeTreasure shakeTreasure = new ShakeTreasure(item, xp, dropChance, dropLevel); + ShakeTreasure shakeTreasure = new ShakeTreasure(item, xp, dropChance, + dropLevel); EntityType entityType = EntityType.valueOf(type.substring(6)); addShakeTreasure(shakeTreasure, entityType); @@ -308,13 +350,16 @@ public class FishingTreasureConfig extends BukkitConfig { } } - private void addShakeTreasure(@NotNull ShakeTreasure shakeTreasure, @NotNull EntityType entityType) { - if (!shakeMap.containsKey(entityType)) + private void addShakeTreasure(@NotNull ShakeTreasure shakeTreasure, + @NotNull EntityType entityType) { + if (!shakeMap.containsKey(entityType)) { shakeMap.put(entityType, new ArrayList<>()); + } shakeMap.get(entityType).add(shakeTreasure); } - private void addFishingTreasure(@NotNull Rarity rarity, @NotNull FishingTreasure fishingTreasure) { + private void addFishingTreasure(@NotNull Rarity rarity, + @NotNull FishingTreasure fishingTreasure) { fishingRewards.get(rarity).add(fishingTreasure); } @@ -329,7 +374,8 @@ public class FishingTreasureConfig extends BukkitConfig { * @param enchantListStr the users string list of enchantments * @param permissiveList the permissive list of enchantments */ - private void matchAndFillSet(@NotNull List enchantListStr, @NotNull Set permissiveList) { + private void matchAndFillSet(@NotNull List enchantListStr, + @NotNull Set permissiveList) { if (enchantListStr.isEmpty()) { return; } @@ -345,7 +391,10 @@ public class FishingTreasureConfig extends BukkitConfig { } if (!foundMatch) { - LogUtils.debug(mcMMO.p.getLogger(), "[Fishing Treasure Init] Could not find any enchantments which matched the user defined enchantment named: " + str); + LogUtils.debug( + mcMMO.p.getLogger(), + "[Fishing Treasure Init] Could not find any enchantments which matched the user defined enchantment named: " + + str); } } } @@ -356,7 +405,8 @@ public class FishingTreasureConfig extends BukkitConfig { fishingEnchantments.put(rarity, (new ArrayList<>())); } - ConfigurationSection enchantmentSection = config.getConfigurationSection("Enchantments_Rarity." + rarity.toString()); + ConfigurationSection enchantmentSection = config.getConfigurationSection( + "Enchantments_Rarity." + rarity.toString()); if (enchantmentSection == null) { return; @@ -367,8 +417,9 @@ public class FishingTreasureConfig extends BukkitConfig { Enchantment enchantment = EnchantmentUtils.getByName(enchantmentName); if (enchantment == null) { - mcMMO.p.getLogger().info("Skipping invalid enchantment in '" + FILENAME + "', named:" - + enchantmentName); + mcMMO.p.getLogger().info( + "Skipping invalid enchantment in '" + FILENAME + "', named:" + + enchantmentName); continue; } diff --git a/src/main/java/com/gmail/nossr50/config/treasure/TreasureConfig.java b/src/main/java/com/gmail/nossr50/config/treasure/TreasureConfig.java index 72d402f81..be7fdc6dd 100755 --- a/src/main/java/com/gmail/nossr50/config/treasure/TreasureConfig.java +++ b/src/main/java/com/gmail/nossr50/config/treasure/TreasureConfig.java @@ -1,5 +1,7 @@ package com.gmail.nossr50.config.treasure; +import static com.gmail.nossr50.util.text.ConfigStringUtils.getMaterialConfigString; + import com.gmail.nossr50.config.BukkitConfig; import com.gmail.nossr50.datatypes.treasure.ExcavationTreasure; import com.gmail.nossr50.datatypes.treasure.HylianTreasure; @@ -7,6 +9,10 @@ import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.BlockUtils; import com.gmail.nossr50.util.LogUtils; import com.gmail.nossr50.util.PotionUtil; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.Tag; @@ -16,13 +22,6 @@ import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionType; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import static com.gmail.nossr50.util.text.ConfigStringUtils.getMaterialConfigString; - public class TreasureConfig extends BukkitConfig { public static final String FILENAME = "treasures.yml"; @@ -95,7 +94,9 @@ public class TreasureConfig extends BukkitConfig { material = Material.matchMaterial(materialName); int amount = config.getInt(type + "." + treasureName + ".Amount"); - short data = (treasureInfo.length == 2) ? Short.parseShort(treasureInfo[1]) : (short) config.getInt(type + "." + treasureName + ".Data"); + short data = (treasureInfo.length == 2) ? Short.parseShort(treasureInfo[1]) + : (short) config.getInt( + type + "." + treasureName + ".Data"); if (material == null) { reason.add("Invalid material: " + materialName); @@ -120,31 +121,42 @@ public class TreasureConfig extends BukkitConfig { //Check for legacy drop level values and convert if (getWrongKeyValue(type, treasureName, DropLevelKeyConversionType.LEGACY) != -1) { //Legacy Drop level, needs to be converted - shouldWeUpdateFile = processAutomaticKeyConversion(type, shouldWeUpdateFile, treasureName, DropLevelKeyConversionType.LEGACY); + shouldWeUpdateFile = processAutomaticKeyConversion( + type, shouldWeUpdateFile, treasureName, + DropLevelKeyConversionType.LEGACY); } //Check for a bad key that was accidentally shipped out to some users - if (getWrongKeyValue(type, treasureName, DropLevelKeyConversionType.WRONG_KEY_STANDARD) != -1) { + if (getWrongKeyValue(type, treasureName, DropLevelKeyConversionType.WRONG_KEY_STANDARD) + != -1) { //Partially converted to the new system, I had a dyslexic moment so some configs have this - shouldWeUpdateFile = processAutomaticKeyConversion(type, shouldWeUpdateFile, treasureName, DropLevelKeyConversionType.WRONG_KEY_STANDARD); + shouldWeUpdateFile = processAutomaticKeyConversion( + type, shouldWeUpdateFile, treasureName, + DropLevelKeyConversionType.WRONG_KEY_STANDARD); } //Check for a bad key that was accidentally shipped out to some users - if (getWrongKeyValue(type, treasureName, DropLevelKeyConversionType.WRONG_KEY_RETRO) != -1) { + if (getWrongKeyValue(type, treasureName, DropLevelKeyConversionType.WRONG_KEY_RETRO) + != -1) { //Partially converted to the new system, I had a dyslexic moment so some configs have this - shouldWeUpdateFile = processAutomaticKeyConversion(type, shouldWeUpdateFile, treasureName, DropLevelKeyConversionType.WRONG_KEY_RETRO); + shouldWeUpdateFile = processAutomaticKeyConversion( + type, shouldWeUpdateFile, treasureName, + DropLevelKeyConversionType.WRONG_KEY_RETRO); } int dropLevel = -1; if (mcMMO.isRetroModeEnabled()) { - dropLevel = config.getInt(type + "." + treasureName + LEVEL_REQUIREMENT_RETRO_MODE, -1); + dropLevel = config.getInt(type + "." + treasureName + LEVEL_REQUIREMENT_RETRO_MODE, + -1); } else { - dropLevel = config.getInt(type + "." + treasureName + LEVEL_REQUIREMENT_STANDARD_MODE, -1); + dropLevel = config.getInt( + type + "." + treasureName + LEVEL_REQUIREMENT_STANDARD_MODE, -1); } if (dropLevel == -1) { - mcMMO.p.getLogger().severe("Could not find a Level_Requirement entry for treasure " + treasureName); + mcMMO.p.getLogger().severe("Could not find a Level_Requirement entry for treasure " + + treasureName); mcMMO.p.getLogger().severe("Skipping treasure"); continue; } @@ -171,19 +183,27 @@ public class TreasureConfig extends BukkitConfig { item = new ItemStack(mat, amount, data); PotionMeta potionMeta = (PotionMeta) item.getItemMeta(); if (potionMeta == null) { - mcMMO.p.getLogger().severe("Item meta when adding potion to treasure was null, contact the mcMMO devs!"); - reason.add("Item meta when adding potion to treasure was null, contact the mcMMO devs!"); + mcMMO.p.getLogger().severe( + "Item meta when adding potion to treasure was null, contact the mcMMO devs!"); + reason.add( + "Item meta when adding potion to treasure was null, contact the mcMMO devs!"); continue; } String potionTypeStr; - potionTypeStr = config.getString(type + "." + treasureName + ".PotionData.PotionType", "WATER"); - boolean extended = config.getBoolean(type + "." + treasureName + ".PotionData.Extended", false); - boolean upgraded = config.getBoolean(type + "." + treasureName + ".PotionData.Upgraded", false); - PotionType potionType = PotionUtil.matchPotionType(potionTypeStr, extended, upgraded); + potionTypeStr = config.getString( + type + "." + treasureName + ".PotionData.PotionType", "WATER"); + boolean extended = config.getBoolean( + type + "." + treasureName + ".PotionData.Extended", false); + boolean upgraded = config.getBoolean( + type + "." + treasureName + ".PotionData.Upgraded", false); + PotionType potionType = PotionUtil.matchPotionType(potionTypeStr, extended, + upgraded); if (potionType == null) { - reason.add("Could not derive potion type from: " + potionTypeStr +", " + extended + ", " + upgraded); + reason.add( + "Could not derive potion type from: " + potionTypeStr + ", " + + extended + ", " + upgraded); continue; } @@ -192,7 +212,9 @@ public class TreasureConfig extends BukkitConfig { PotionUtil.setBasePotionType(potionMeta, potionType, extended, upgraded); if (config.contains(type + "." + treasureName + ".Custom_Name")) { - potionMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', config.getString(type + "." + treasureName + ".Custom_Name"))); + potionMeta.setDisplayName(ChatColor.translateAlternateColorCodes( + '&', + config.getString(type + "." + treasureName + ".Custom_Name"))); } if (config.contains(type + "." + treasureName + ".Lore")) { @@ -209,7 +231,9 @@ public class TreasureConfig extends BukkitConfig { if (config.contains(type + "." + treasureName + ".Custom_Name")) { ItemMeta itemMeta = item.getItemMeta(); - itemMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', config.getString(type + "." + treasureName + ".Custom_Name"))); + itemMeta.setDisplayName(ChatColor.translateAlternateColorCodes( + '&', + config.getString(type + "." + treasureName + ".Custom_Name"))); item.setItemMeta(itemMeta); } @@ -226,43 +250,62 @@ public class TreasureConfig extends BukkitConfig { if (noErrorsInConfig(reason)) { if (isExcavation) { - ExcavationTreasure excavationTreasure = new ExcavationTreasure(item, xp, dropChance, dropLevel); - List dropList = config.getStringList(type + "." + treasureName + ".Drops_From"); + ExcavationTreasure excavationTreasure = new ExcavationTreasure(item, xp, + dropChance, dropLevel); + List dropList = config.getStringList( + type + "." + treasureName + ".Drops_From"); for (String blockType : dropList) { - if (!excavationMap.containsKey(blockType)) + if (!excavationMap.containsKey(blockType)) { excavationMap.put(blockType, new ArrayList<>()); + } excavationMap.get(blockType).add(excavationTreasure); } } else if (isHylian) { - HylianTreasure hylianTreasure = new HylianTreasure(item, xp, dropChance, dropLevel); - List dropList = config.getStringList(type + "." + treasureName + ".Drops_From"); + HylianTreasure hylianTreasure = new HylianTreasure(item, xp, dropChance, + dropLevel); + List dropList = config.getStringList( + type + "." + treasureName + ".Drops_From"); for (String dropper : dropList) { if (dropper.equals("Bushes")) { - AddHylianTreasure(getMaterialConfigString(Material.FERN), hylianTreasure); - AddHylianTreasure(getMaterialConfigString(BlockUtils.getShortGrass()), hylianTreasure); - for (Material species : Tag.SAPLINGS.getValues()) + AddHylianTreasure(getMaterialConfigString(Material.FERN), + hylianTreasure); + AddHylianTreasure(getMaterialConfigString(BlockUtils.getShortGrass()), + hylianTreasure); + for (Material species : Tag.SAPLINGS.getValues()) { AddHylianTreasure(getMaterialConfigString(species), hylianTreasure); + } - AddHylianTreasure(getMaterialConfigString(Material.DEAD_BUSH), hylianTreasure); + AddHylianTreasure(getMaterialConfigString(Material.DEAD_BUSH), + hylianTreasure); continue; } if (dropper.equals("Flowers")) { - AddHylianTreasure(getMaterialConfigString(Material.POPPY), hylianTreasure); - AddHylianTreasure(getMaterialConfigString(Material.DANDELION), hylianTreasure); - AddHylianTreasure(getMaterialConfigString(Material.BLUE_ORCHID), hylianTreasure); - AddHylianTreasure(getMaterialConfigString(Material.ALLIUM), hylianTreasure); - AddHylianTreasure(getMaterialConfigString(Material.AZURE_BLUET), hylianTreasure); - AddHylianTreasure(getMaterialConfigString(Material.ORANGE_TULIP), hylianTreasure); - AddHylianTreasure(getMaterialConfigString(Material.PINK_TULIP), hylianTreasure); - AddHylianTreasure(getMaterialConfigString(Material.RED_TULIP), hylianTreasure); - AddHylianTreasure(getMaterialConfigString(Material.WHITE_TULIP), hylianTreasure); + AddHylianTreasure(getMaterialConfigString(Material.POPPY), + hylianTreasure); + AddHylianTreasure(getMaterialConfigString(Material.DANDELION), + hylianTreasure); + AddHylianTreasure(getMaterialConfigString(Material.BLUE_ORCHID), + hylianTreasure); + AddHylianTreasure(getMaterialConfigString(Material.ALLIUM), + hylianTreasure); + AddHylianTreasure(getMaterialConfigString(Material.AZURE_BLUET), + hylianTreasure); + AddHylianTreasure(getMaterialConfigString(Material.ORANGE_TULIP), + hylianTreasure); + AddHylianTreasure(getMaterialConfigString(Material.PINK_TULIP), + hylianTreasure); + AddHylianTreasure(getMaterialConfigString(Material.RED_TULIP), + hylianTreasure); + AddHylianTreasure(getMaterialConfigString(Material.WHITE_TULIP), + hylianTreasure); continue; } if (dropper.equals("Pots")) { - for (Material species : Tag.FLOWER_POTS.getValues()) + for (Material species : Tag.FLOWER_POTS.getValues()) { AddHylianTreasure(getMaterialConfigString(species), hylianTreasure); + } continue; } AddHylianTreasure(dropper, hylianTreasure); @@ -281,36 +324,61 @@ public class TreasureConfig extends BukkitConfig { } } - private boolean processAutomaticKeyConversion(String type, boolean shouldWeUpdateTheFile, String treasureName, DropLevelKeyConversionType conversionType) { + private boolean processAutomaticKeyConversion(String type, boolean shouldWeUpdateTheFile, + String treasureName, + DropLevelKeyConversionType conversionType) { switch (conversionType) { case LEGACY: - int legacyDropLevel = getWrongKeyValue(type, treasureName, conversionType); //Legacy only had one value, Retro Mode didn't have a setting + int legacyDropLevel = getWrongKeyValue( + type, treasureName, + conversionType); //Legacy only had one value, Retro Mode didn't have a setting //Config needs to be updated to be more specific - LogUtils.debug(mcMMO.p.getLogger(), "(" + treasureName + ") [Fixing bad address: Legacy] Converting Drop_Level to Level_Requirement in treasures.yml for treasure to match new expected format"); - config.set(type + "." + treasureName + LEGACY_DROP_LEVEL, null); //Remove legacy entry - config.set(type + "." + treasureName + LEVEL_REQUIREMENT_RETRO_MODE, legacyDropLevel * 10); //Multiply by 10 for Retro - config.set(type + "." + treasureName + LEVEL_REQUIREMENT_STANDARD_MODE, legacyDropLevel); + LogUtils.debug( + mcMMO.p.getLogger(), + "(" + treasureName + + ") [Fixing bad address: Legacy] Converting Drop_Level to Level_Requirement in treasures.yml for treasure to match new expected format"); + config.set(type + "." + treasureName + LEGACY_DROP_LEVEL, + null); //Remove legacy entry + config.set( + type + "." + treasureName + LEVEL_REQUIREMENT_RETRO_MODE, + legacyDropLevel * 10); //Multiply by 10 for Retro + config.set(type + "." + treasureName + LEVEL_REQUIREMENT_STANDARD_MODE, + legacyDropLevel); shouldWeUpdateTheFile = true; break; case WRONG_KEY_STANDARD: - LogUtils.debug(mcMMO.p.getLogger(), "(" + treasureName + ") [Fixing bad address: STANDARD] Converting Drop_Level to Level_Requirement in treasures.yml for treasure to match new expected format"); + LogUtils.debug( + mcMMO.p.getLogger(), + "(" + treasureName + + ") [Fixing bad address: STANDARD] Converting Drop_Level to Level_Requirement in treasures.yml for treasure to match new expected format"); int wrongKeyValueStandard = getWrongKeyValue(type, treasureName, conversionType); - config.set(type + "." + treasureName + WRONG_KEY_ROOT, null); //We also kill the Retro key here as we have enough information for setting in values if needed + config.set( + type + "." + treasureName + WRONG_KEY_ROOT, + null); //We also kill the Retro key here as we have enough information for setting in values if needed if (wrongKeyValueStandard != -1) { - config.set(type + "." + treasureName + LEVEL_REQUIREMENT_STANDARD_MODE, wrongKeyValueStandard); - config.set(type + "." + treasureName + LEVEL_REQUIREMENT_RETRO_MODE, wrongKeyValueStandard * 10); //Multiply by 10 for Retro + config.set(type + "." + treasureName + LEVEL_REQUIREMENT_STANDARD_MODE, + wrongKeyValueStandard); + config.set( + type + "." + treasureName + LEVEL_REQUIREMENT_RETRO_MODE, + wrongKeyValueStandard * 10); //Multiply by 10 for Retro } shouldWeUpdateTheFile = true; break; case WRONG_KEY_RETRO: - LogUtils.debug(mcMMO.p.getLogger(), "(" + treasureName + ") [Fixing bad address: RETRO] Converting Drop_Level to Level_Requirement in treasures.yml for treasure to match new expected format"); + LogUtils.debug( + mcMMO.p.getLogger(), + "(" + treasureName + + ") [Fixing bad address: RETRO] Converting Drop_Level to Level_Requirement in treasures.yml for treasure to match new expected format"); int wrongKeyValueRetro = getWrongKeyValue(type, treasureName, conversionType); - config.set(type + "." + treasureName + WRONG_KEY_ROOT, null); //We also kill the Retro key here as we have enough information for setting in values if needed + config.set( + type + "." + treasureName + WRONG_KEY_ROOT, + null); //We also kill the Retro key here as we have enough information for setting in values if needed if (wrongKeyValueRetro != -1) { - config.set(type + "." + treasureName + LEVEL_REQUIREMENT_RETRO_MODE, wrongKeyValueRetro); + config.set(type + "." + treasureName + LEVEL_REQUIREMENT_RETRO_MODE, + wrongKeyValueRetro); } shouldWeUpdateTheFile = true; @@ -319,24 +387,26 @@ public class TreasureConfig extends BukkitConfig { return shouldWeUpdateTheFile; } - private int getWrongKeyValue(String type, String treasureName, DropLevelKeyConversionType dropLevelKeyConversionType) { + private int getWrongKeyValue(String type, String treasureName, + DropLevelKeyConversionType dropLevelKeyConversionType) { return switch (dropLevelKeyConversionType) { case LEGACY -> config.getInt(type + "." + treasureName + LEGACY_DROP_LEVEL, -1); - case WRONG_KEY_STANDARD -> config.getInt(type + "." + treasureName + WRONG_KEY_VALUE_STANDARD, -1); - case WRONG_KEY_RETRO -> config.getInt(type + "." + treasureName + WRONG_KEY_VALUE_RETRO, -1); + case WRONG_KEY_STANDARD -> + config.getInt(type + "." + treasureName + WRONG_KEY_VALUE_STANDARD, -1); + case WRONG_KEY_RETRO -> + config.getInt(type + "." + treasureName + WRONG_KEY_VALUE_RETRO, -1); }; } private void AddHylianTreasure(String dropper, HylianTreasure treasure) { - if (!hylianMap.containsKey(dropper)) + if (!hylianMap.containsKey(dropper)) { hylianMap.put(dropper, new ArrayList<>()); + } hylianMap.get(dropper).add(treasure); } private enum DropLevelKeyConversionType { - LEGACY, - WRONG_KEY_STANDARD, - WRONG_KEY_RETRO + LEGACY, WRONG_KEY_STANDARD, WRONG_KEY_RETRO } } diff --git a/src/main/java/com/gmail/nossr50/database/DatabaseManager.java b/src/main/java/com/gmail/nossr50/database/DatabaseManager.java index 586c8c0b6..a666739e7 100644 --- a/src/main/java/com/gmail/nossr50/database/DatabaseManager.java +++ b/src/main/java/com/gmail/nossr50/database/DatabaseManager.java @@ -5,15 +5,14 @@ import com.gmail.nossr50.datatypes.database.DatabaseType; import com.gmail.nossr50.datatypes.database.PlayerStat; import com.gmail.nossr50.datatypes.player.PlayerProfile; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; +import java.util.List; +import java.util.Map; +import java.util.UUID; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.List; -import java.util.Map; -import java.util.UUID; - public interface DatabaseManager { // During convertUsers, how often to output a status int progressInterval = 200; @@ -38,8 +37,8 @@ public interface DatabaseManager { boolean removeUser(String playerName, UUID uuid); /** - * Removes any cache used for faster lookups - * Currently only used for SQL + * Removes any cache used for faster lookups Currently only used for SQL + * * @param uuid target UUID to cleanup */ void cleanupUser(UUID uuid); @@ -53,21 +52,21 @@ public interface DatabaseManager { boolean saveUser(PlayerProfile profile); /** - * Retrieve leaderboard info. - * Will never be null but it may be empty - * - * @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 - */ - @NotNull List readLeaderboard(@Nullable PrimarySkillType skill, int pageNumber, int statsPerPage) throws InvalidSkillException; + * Retrieve leaderboard info. Will never be null but it may be empty + * + * @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 + */ + @NotNull List readLeaderboard(@Nullable PrimarySkillType skill, int pageNumber, + int statsPerPage) throws InvalidSkillException; /** * Retrieve rank info into a HashMap from PrimarySkillType to the rank. *

- * The special value null is used to represent the Power - * Level rank (the combination of all skill levels). + * The special value null is used to represent the Power Level rank (the + * combination of all skill levels). * * @param playerName The name of the user to retrieve the rankings for * @return the requested rank information @@ -76,7 +75,8 @@ public interface DatabaseManager { /** * Add a new user to the database. - * @param playerName The name of the player to be added 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 * @return */ @@ -88,8 +88,7 @@ public interface DatabaseManager { * Load a player from the database. * * @param playerName The name of the player to load from the database - * @return The player's data, or an unloaded PlayerProfile if not found - * and createNew is false + * @return The player's data, or an unloaded PlayerProfile if not found and createNew is false */ @NotNull PlayerProfile loadPlayerProfile(@NotNull String playerName); diff --git a/src/main/java/com/gmail/nossr50/database/DatabaseManagerFactory.java b/src/main/java/com/gmail/nossr50/database/DatabaseManagerFactory.java index df6c5a158..d75952890 100644 --- a/src/main/java/com/gmail/nossr50/database/DatabaseManagerFactory.java +++ b/src/main/java/com/gmail/nossr50/database/DatabaseManagerFactory.java @@ -3,57 +3,55 @@ package com.gmail.nossr50.database; import com.gmail.nossr50.datatypes.database.DatabaseType; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.LogUtils; +import java.util.logging.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.logging.Logger; - public class DatabaseManagerFactory { private static Class customManager = null; public static final String MYSQL_DRIVER = "com.mysql.cj.jdbc.Driver"; - public static DatabaseManager getDatabaseManager(@NotNull String userFilePath, @NotNull Logger logger, long purgeTime, int startingLevel) { + public static DatabaseManager getDatabaseManager(@NotNull String userFilePath, + @NotNull Logger logger, long purgeTime, int startingLevel) { if (customManager != null) { try { return createDefaultCustomDatabaseManager(); - } - catch (Exception e) { + } catch (Exception e) { LogUtils.debug(mcMMO.p.getLogger(), "Could not create custom database manager"); e.printStackTrace(); - } - catch (Throwable e) { + } catch (Throwable e) { LogUtils.debug(mcMMO.p.getLogger(), "Failed to create custom database manager"); e.printStackTrace(); } - LogUtils.debug(mcMMO.p.getLogger(), "Falling back on " + (mcMMO.p.getGeneralConfig().getUseMySQL() ? "SQL" : "Flatfile") + " database"); + LogUtils.debug(mcMMO.p.getLogger(), + "Falling back on " + (mcMMO.p.getGeneralConfig().getUseMySQL() ? "SQL" + : "Flatfile") + " database"); } - return mcMMO.p.getGeneralConfig().getUseMySQL() ? new SQLDatabaseManager(logger, MYSQL_DRIVER) : new FlatFileDatabaseManager(userFilePath, logger, purgeTime, startingLevel); + return mcMMO.p.getGeneralConfig().getUseMySQL() ? new SQLDatabaseManager(logger, + MYSQL_DRIVER) + : new FlatFileDatabaseManager(userFilePath, logger, purgeTime, startingLevel); } /** - * Sets the custom DatabaseManager class for mcMMO to use. This should be - * called prior to mcMMO enabling. + * Sets the custom DatabaseManager class for mcMMO to use. This should be called prior to mcMMO + * enabling. *

- * The provided class must have an empty constructor, which is the one - * that will be used. + * The provided class must have an empty constructor, which is the one that will be used. *

- * This method is intended for API use, but it should not be considered - * stable. This method is subject to change and/or removal in future - * versions. + * This method is intended for API use, but it should not be considered stable. This method is + * subject to change and/or removal in future versions. * * @param clazz the DatabaseManager class to use - * - * @throws IllegalArgumentException if the provided class does not have - * an empty constructor + * @throws IllegalArgumentException if the provided class does not have an empty constructor */ public static void setCustomDatabaseManagerClass(Class clazz) { try { clazz.getConstructor(); customManager = clazz; - } - catch (Throwable e) { - throw new IllegalArgumentException("Provided database manager class must have an empty constructor", e); + } catch (Throwable e) { + throw new IllegalArgumentException( + "Provided database manager class must have an empty constructor", e); } } @@ -61,7 +59,9 @@ public class DatabaseManagerFactory { return customManager; } - public static @Nullable DatabaseManager createDatabaseManager(@NotNull DatabaseType type, @NotNull String userFilePath, @NotNull Logger logger, long purgeTime, int startingLevel) { + public static @Nullable DatabaseManager createDatabaseManager(@NotNull DatabaseType type, + @NotNull String userFilePath, @NotNull Logger logger, long purgeTime, + int startingLevel) { switch (type) { case FLATFILE: LogUtils.debug(mcMMO.p.getLogger(), "Using FlatFile Database"); @@ -75,8 +75,7 @@ public class DatabaseManagerFactory { try { LogUtils.debug(mcMMO.p.getLogger(), "Attempting to use Custom Database"); return createDefaultCustomDatabaseManager(); - } - catch (Throwable e) { + } catch (Throwable e) { e.printStackTrace(); } @@ -89,7 +88,8 @@ public class DatabaseManagerFactory { return customManager.getConstructor().newInstance(); } - public static DatabaseManager createCustomDatabaseManager(Class clazz) throws Throwable { + public static DatabaseManager createCustomDatabaseManager( + Class clazz) throws Throwable { return clazz.getConstructor().newInstance(); } } diff --git a/src/main/java/com/gmail/nossr50/database/FlatFileDataProcessor.java b/src/main/java/com/gmail/nossr50/database/FlatFileDataProcessor.java index 8f68b7bcf..2331809af 100644 --- a/src/main/java/com/gmail/nossr50/database/FlatFileDataProcessor.java +++ b/src/main/java/com/gmail/nossr50/database/FlatFileDataProcessor.java @@ -1,16 +1,70 @@ package com.gmail.nossr50.database; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_ARCHERY; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_BERSERK; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_BLAST_MINING; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_CHIMAERA_WING; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_GIGA_DRILL_BREAKER; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_GREEN_TERRA; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_MACES; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_SERRATED_STRIKES; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_SKULL_SPLITTER; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_SUPER_BREAKER; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_SUPER_SHOTGUN; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_TREE_FELLER; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_TRIDENTS; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.DATA_ENTRY_COUNT; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_ACROBATICS; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_ALCHEMY; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_ARCHERY; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_AXES; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_CROSSBOWS; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_EXCAVATION; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_FISHING; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_HERBALISM; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_MACES; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_MINING; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_REPAIR; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_SWORDS; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_TAMING; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_TRIDENTS; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_UNARMED; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_WOODCUTTING; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.HEALTHBAR; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.LEGACY_LAST_LOGIN; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.OVERHAUL_LAST_LOGIN; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SCOREBOARD_TIPS; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_ACROBATICS; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_ALCHEMY; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_ARCHERY; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_AXES; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_CROSSBOWS; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_EXCAVATION; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_FISHING; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_HERBALISM; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_MACES; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_MINING; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_REPAIR; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_SWORDS; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_TAMING; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_TRIDENTS; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_UNARMED; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_WOODCUTTING; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.USERNAME_INDEX; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.UUID_INDEX; + import com.gmail.nossr50.database.flatfile.FlatFileDataBuilder; import com.gmail.nossr50.database.flatfile.FlatFileDataContainer; import com.gmail.nossr50.database.flatfile.FlatFileDataUtil; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.UUID; +import java.util.logging.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; -import java.util.logging.Logger; - -import static com.gmail.nossr50.database.FlatFileDatabaseManager.*; - public class FlatFileDataProcessor { private final @NotNull List flatFileDataContainers; private final @NotNull List flatFileDataFlags; @@ -51,7 +105,8 @@ public class FlatFileDataProcessor { if (splitDataLine.length < getMinimumSplitDataLength()) { //Data is considered junk if (!corruptDataFound) { - logger.severe("Some corrupt data was found in mcmmo.users and has been repaired, it is possible that some player data has been lost in this process."); + logger.severe( + "Some corrupt data was found in mcmmo.users and has been repaired, it is possible that some player data has been lost in this process."); corruptDataFound = true; } @@ -59,10 +114,13 @@ public class FlatFileDataProcessor { builder.appendFlag(FlatFileDataFlag.CORRUPTED_OR_UNRECOGNIZABLE); //TODO: This block here is probably pointless - if (splitDataLine.length >= 10 //The value here is kind of arbitrary, it shouldn't be too low to avoid false positives, but also we aren't really going to correctly identify when player data has been corrupted or not with 100% accuracy ever + if (splitDataLine.length >= 10 + //The value here is kind of arbitrary, it shouldn't be too low to avoid false positives, but also we aren't really going to correctly identify when player data has been corrupted or not with 100% accuracy ever && splitDataLine[0] != null && !splitDataLine[0].isEmpty()) { if (splitDataLine[0].length() <= 16 && splitDataLine[0].length() >= 3) { - logger.severe("Not enough data found to recover corrupted player data for user: "+splitDataLine[0]); + logger.severe( + "Not enough data found to recover corrupted player data for user: " + + splitDataLine[0]); registerData(builder.appendFlag(FlatFileDataFlag.TOO_INCOMPLETE)); return; } @@ -123,8 +181,9 @@ public class FlatFileDataProcessor { badDataValues[USERNAME_INDEX] = true; } - if (!name.isEmpty()) + if (!name.isEmpty()) { names.add(name); + } //Make sure the data is up to date schema wise, if it isn't we adjust it to the correct size and flag it for repair splitDataLine = isDataSchemaUpToDate(splitDataLine, builder, badDataValues); @@ -135,7 +194,7 @@ public class FlatFileDataProcessor { */ //Check each data for bad values - for(int i = 0; i < DATA_ENTRY_COUNT; i++) { + for (int i = 0; i < DATA_ENTRY_COUNT; i++) { if (shouldNotBeEmpty(splitDataLine[i], i)) { if (i == OVERHAUL_LAST_LOGIN) { @@ -163,7 +222,8 @@ public class FlatFileDataProcessor { registerData(builder); } - public @NotNull String[] isDataSchemaUpToDate(@NotNull String[] splitDataLine, @NotNull FlatFileDataBuilder builder, boolean[] badDataValues) { + public @NotNull String[] isDataSchemaUpToDate(@NotNull String[] splitDataLine, + @NotNull FlatFileDataBuilder builder, boolean[] badDataValues) { assert splitDataLine.length <= DATA_ENTRY_COUNT; //should NEVER be higher if (splitDataLine.length < DATA_ENTRY_COUNT) { @@ -172,7 +232,7 @@ public class FlatFileDataProcessor { int newLength = splitDataLine.length; //TODO: Test this - for(int i = oldLength; i < (newLength - 1); i++){ + for (int i = oldLength; i < (newLength - 1); i++) { badDataValues[i] = true; } @@ -192,7 +252,7 @@ public class FlatFileDataProcessor { } public boolean isOfExpectedType(@NotNull String data, @NotNull ExpectedType expectedType) { - switch(expectedType) { + switch (expectedType) { case STRING: return true; case INTEGER: @@ -226,7 +286,8 @@ public class FlatFileDataProcessor { return false; } case OUT_OF_RANGE: - throw new ArrayIndexOutOfBoundsException("Value matched type OUT_OF_RANGE, this should never happen."); + throw new ArrayIndexOutOfBoundsException( + "Value matched type OUT_OF_RANGE, this should never happen."); case IGNORED: default: return true; @@ -248,26 +309,35 @@ public class FlatFileDataProcessor { FlatFileDataContainer flatFileDataContainer = builder.build(); flatFileDataContainers.add(flatFileDataContainer); - if (flatFileDataContainer.getDataFlags() != null) + if (flatFileDataContainer.getDataFlags() != null) { flatFileDataFlags.addAll(flatFileDataContainer.getDataFlags()); + } } - public static @NotNull ExpectedType getExpectedValueType(int dataIndex) throws IndexOutOfBoundsException { + public static @NotNull ExpectedType getExpectedValueType(int dataIndex) + throws IndexOutOfBoundsException { return switch (dataIndex) { - case USERNAME_INDEX -> ExpectedType.STRING; //Assumption: Used to be for something, no longer used + case USERNAME_INDEX -> + ExpectedType.STRING; //Assumption: Used to be for something, no longer used //Assumption: Used to be for something, no longer used //Assumption: Used to be used for something, no longer used //Assumption: Used to be used for something, no longer used case 2, 3, 23, 33, HEALTHBAR, LEGACY_LAST_LOGIN -> ExpectedType.IGNORED; - case SKILLS_MINING, SKILLS_REPAIR, SKILLS_UNARMED, SKILLS_HERBALISM, SKILLS_EXCAVATION, SKILLS_ARCHERY, - SKILLS_SWORDS, SKILLS_AXES, SKILLS_WOODCUTTING, SKILLS_ACROBATICS, SKILLS_TAMING, SKILLS_FISHING, + case SKILLS_MINING, SKILLS_REPAIR, SKILLS_UNARMED, SKILLS_HERBALISM, SKILLS_EXCAVATION, + SKILLS_ARCHERY, + SKILLS_SWORDS, SKILLS_AXES, SKILLS_WOODCUTTING, SKILLS_ACROBATICS, SKILLS_TAMING, + SKILLS_FISHING, SKILLS_ALCHEMY, SKILLS_CROSSBOWS, SKILLS_TRIDENTS, SKILLS_MACES, COOLDOWN_BERSERK, - COOLDOWN_GIGA_DRILL_BREAKER, COOLDOWN_TREE_FELLER, COOLDOWN_GREEN_TERRA, COOLDOWN_SERRATED_STRIKES, - COOLDOWN_SKULL_SPLITTER, COOLDOWN_SUPER_BREAKER, COOLDOWN_BLAST_MINING, SCOREBOARD_TIPS, - COOLDOWN_CHIMAERA_WING, COOLDOWN_SUPER_SHOTGUN, COOLDOWN_TRIDENTS, COOLDOWN_ARCHERY, COOLDOWN_MACES -> - ExpectedType.INTEGER; - case EXP_MINING, EXP_WOODCUTTING, EXP_REPAIR, EXP_UNARMED, EXP_HERBALISM, EXP_EXCAVATION, EXP_ARCHERY, - EXP_SWORDS, EXP_AXES, EXP_ACROBATICS, EXP_TAMING, EXP_FISHING, EXP_ALCHEMY, EXP_CROSSBOWS, + COOLDOWN_GIGA_DRILL_BREAKER, COOLDOWN_TREE_FELLER, COOLDOWN_GREEN_TERRA, + COOLDOWN_SERRATED_STRIKES, + COOLDOWN_SKULL_SPLITTER, COOLDOWN_SUPER_BREAKER, COOLDOWN_BLAST_MINING, + SCOREBOARD_TIPS, + COOLDOWN_CHIMAERA_WING, COOLDOWN_SUPER_SHOTGUN, COOLDOWN_TRIDENTS, + COOLDOWN_ARCHERY, COOLDOWN_MACES -> ExpectedType.INTEGER; + case EXP_MINING, EXP_WOODCUTTING, EXP_REPAIR, EXP_UNARMED, EXP_HERBALISM, + EXP_EXCAVATION, EXP_ARCHERY, + EXP_SWORDS, EXP_AXES, EXP_ACROBATICS, EXP_TAMING, EXP_FISHING, EXP_ALCHEMY, + EXP_CROSSBOWS, EXP_TRIDENTS, EXP_MACES -> ExpectedType.FLOAT; case UUID_INDEX -> ExpectedType.UUID; case OVERHAUL_LAST_LOGIN -> ExpectedType.LONG; @@ -292,11 +362,12 @@ public class FlatFileDataProcessor { //Fix our data if needed and prepare it to be saved - for(FlatFileDataContainer dataContainer : flatFileDataContainers) { + for (FlatFileDataContainer dataContainer : flatFileDataContainers) { String[] splitData = FlatFileDataUtil.getPreparedSaveDataLine(dataContainer); - if (splitData == null) + if (splitData == null) { continue; + } //We add a trailing : as it is needed for some reason (is it?) //TODO: Is the trailing ":" actually necessary? diff --git a/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java b/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java index a73be51ad..efc337e53 100644 --- a/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java +++ b/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java @@ -12,21 +12,32 @@ import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.LogUtils; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.skills.SkillTools; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.logging.Logger; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.*; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.*; -import java.util.logging.Logger; - public final class FlatFileDatabaseManager implements DatabaseManager { public static final String IGNORED = "IGNORED"; public static final String LEGACY_INVALID_OLD_USERNAME = "_INVALID_OLD_USERNAME_'"; - private final @NotNull EnumMap> playerStatHash = new EnumMap<>(PrimarySkillType.class); + private final @NotNull EnumMap> playerStatHash = new EnumMap<>( + PrimarySkillType.class); private final @NotNull List powerLevels = new ArrayList<>(); private long lastUpdate = 0; private final @NotNull String usersFilePath; @@ -93,7 +104,8 @@ public final class FlatFileDatabaseManager implements DatabaseManager { //Update this everytime new data is added public static final int DATA_ENTRY_COUNT = COOLDOWN_MACES + 1; - FlatFileDatabaseManager(@NotNull File usersFile, @NotNull Logger logger, long purgeTime, int startingLevel, boolean testing) { + FlatFileDatabaseManager(@NotNull File usersFile, @NotNull Logger logger, long purgeTime, + int startingLevel, boolean testing) { this.usersFile = usersFile; this.usersFilePath = usersFile.getPath(); this.logger = logger; @@ -110,7 +122,8 @@ public final class FlatFileDatabaseManager implements DatabaseManager { if (flatFileDataFlags != null) { if (!flatFileDataFlags.isEmpty()) { - logger.info("Detected "+flatFileDataFlags.size() + " data entries which need correction."); + logger.info("Detected " + flatFileDataFlags.size() + + " data entries which need correction."); } } @@ -118,7 +131,8 @@ public final class FlatFileDatabaseManager implements DatabaseManager { } } - FlatFileDatabaseManager(@NotNull String usersFilePath, @NotNull Logger logger, long purgeTime, int startingLevel) { + FlatFileDatabaseManager(@NotNull String usersFilePath, @NotNull Logger logger, long purgeTime, + int startingLevel) { this(new File(usersFilePath), logger, purgeTime, startingLevel, false); } @@ -160,24 +174,21 @@ public final class FlatFileDatabaseManager implements DatabaseManager { // Write the new file out = new FileWriter(usersFilePath); out.write(writer.toString()); - } - catch (IOException e) { - logger.severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e); - } - finally { + } catch (IOException e) { + logger.severe("Exception while reading " + usersFilePath + + " (Are you sure you formatted it correctly?)" + e); + } 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 } } @@ -233,7 +244,8 @@ public final class FlatFileDatabaseManager implements DatabaseManager { if (rewrite) { // Rewrite their data with a valid time character[OVERHAUL_LAST_LOGIN] = Long.toString(lastPlayed); - String newLine = org.apache.commons.lang3.StringUtils.join(character, ":"); + String newLine = org.apache.commons.lang3.StringUtils.join(character, + ":"); writer.append(newLine).append("\r\n"); } else { writer.append(line).append("\r\n"); @@ -248,24 +260,21 @@ public final class FlatFileDatabaseManager implements DatabaseManager { if (testing) { System.out.println(writer); } - } - catch (IOException e) { - logger.severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e); - } - finally { + } catch (IOException e) { + logger.severe("Exception while reading " + usersFilePath + + " (Are you sure you formatted it correctly?)" + e); + } 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 } } @@ -301,24 +310,21 @@ public final class FlatFileDatabaseManager implements DatabaseManager { out = new FileWriter(usersFilePath); // Write out the new file out.write(writer.toString()); - } - catch (Exception e) { - logger.severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e); - } - finally { + } catch (Exception e) { + logger.severe("Exception while reading " + usersFilePath + + " (Are you sure you formatted it correctly?)" + e); + } 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 } } @@ -362,7 +368,8 @@ public final class FlatFileDatabaseManager implements DatabaseManager { if (!line.contains(":")) { if (!corruptDataFound) { - logger.severe("mcMMO found some unexpected or corrupted data in mcmmo.users and is removing it, it is possible some data has been lost."); + logger.severe( + "mcMMO found some unexpected or corrupted data in mcmmo.users and is removing it, it is possible some data has been lost."); corruptDataFound = true; } @@ -372,10 +379,12 @@ public final class FlatFileDatabaseManager implements DatabaseManager { String[] splitData = line.split(":"); //This would be rare, but check the splitData for having enough entries to contain a UUID - if (splitData.length < UUID_INDEX) { //UUID have been in mcMMO DB for a very long time so any user without + if (splitData.length + < UUID_INDEX) { //UUID have been in mcMMO DB for a very long time so any user without if (!corruptDataFound) { - logger.severe("mcMMO found some unexpected or corrupted data in mcmmo.users and is removing it, it is possible some data has been lost."); + logger.severe( + "mcMMO found some unexpected or corrupted data in mcmmo.users and is removing it, it is possible some data has been lost."); corruptDataFound = true; } @@ -383,9 +392,10 @@ public final class FlatFileDatabaseManager implements DatabaseManager { } if (!(uuid != null - && splitData[UUID_INDEX].equalsIgnoreCase(uuid.toString())) - && !splitData[USERNAME_INDEX].equalsIgnoreCase(playerName)) { - writer.append(line).append("\r\n"); //Not the user so write it to file and move on + && splitData[UUID_INDEX].equalsIgnoreCase(uuid.toString())) + && !splitData[USERNAME_INDEX].equalsIgnoreCase(playerName)) { + writer.append(line) + .append("\r\n"); //Not the user so write it to file and move on } else { //User found writeUserToLine(profile, writer); @@ -404,25 +414,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 } } @@ -430,83 +436,137 @@ public final class FlatFileDatabaseManager implements DatabaseManager { } } - public void writeUserToLine(@NotNull PlayerProfile profile, @NotNull Appendable appendable) throws IOException { + public void writeUserToLine(@NotNull PlayerProfile profile, @NotNull Appendable appendable) + throws IOException { appendable.append(profile.getPlayerName()).append(":"); - appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.MINING))).append(":"); + appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.MINING))) + .append(":"); appendable.append(IGNORED).append(":"); appendable.append(IGNORED).append(":"); - appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.MINING))).append(":"); - appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.WOODCUTTING))).append(":"); - appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.WOODCUTTING))).append(":"); - appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.REPAIR))).append(":"); - appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.UNARMED))).append(":"); - appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.HERBALISM))).append(":"); - appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.EXCAVATION))).append(":"); - appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.ARCHERY))).append(":"); - appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.SWORDS))).append(":"); + appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.MINING))) + .append(":"); + appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.WOODCUTTING))) + .append(":"); + appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.WOODCUTTING))) + .append(":"); + appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.REPAIR))) + .append(":"); + appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.UNARMED))) + .append(":"); + appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.HERBALISM))) + .append(":"); + appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.EXCAVATION))) + .append(":"); + appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.ARCHERY))) + .append(":"); + appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.SWORDS))) + .append(":"); appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.AXES))).append(":"); - appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.ACROBATICS))).append(":"); - appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.REPAIR))).append(":"); - appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.UNARMED))).append(":"); - appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.HERBALISM))).append(":"); - appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.EXCAVATION))).append(":"); - appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.ARCHERY))).append(":"); - appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.SWORDS))).append(":"); - appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.AXES))).append(":"); - appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.ACROBATICS))).append(":"); + appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.ACROBATICS))) + .append(":"); + appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.REPAIR))) + .append(":"); + appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.UNARMED))) + .append(":"); + appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.HERBALISM))) + .append(":"); + appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.EXCAVATION))) + .append(":"); + appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.ARCHERY))) + .append(":"); + appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.SWORDS))) + .append(":"); + appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.AXES))) + .append(":"); + appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.ACROBATICS))) + .append(":"); appendable.append(IGNORED).append(":"); - appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.TAMING))).append(":"); - appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.TAMING))).append(":"); - appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.BERSERK))).append(":"); - appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.GIGA_DRILL_BREAKER))).append(":"); - appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.TREE_FELLER))).append(":"); - appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.GREEN_TERRA))).append(":"); - appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.SERRATED_STRIKES))).append(":"); - appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.SKULL_SPLITTER))).append(":"); - appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.SUPER_BREAKER))).append(":"); + appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.TAMING))) + .append(":"); + appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.TAMING))) + .append(":"); + appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.BERSERK))) + .append(":"); + appendable.append( + String.valueOf(profile.getAbilityDATS(SuperAbilityType.GIGA_DRILL_BREAKER))) + .append(":"); + appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.TREE_FELLER))) + .append(":"); + appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.GREEN_TERRA))) + .append(":"); + appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.SERRATED_STRIKES))) + .append(":"); + appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.SKULL_SPLITTER))) + .append(":"); + appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.SUPER_BREAKER))) + .append(":"); appendable.append(IGNORED).append(":"); - appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.FISHING))).append(":"); - appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.FISHING))).append(":"); - appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.BLAST_MINING))).append(":"); + appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.FISHING))) + .append(":"); + appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.FISHING))) + .append(":"); + appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.BLAST_MINING))) + .append(":"); appendable.append(IGNORED).append(":"); //Legacy last login appendable.append(IGNORED).append(":"); //mob health bar - appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.ALCHEMY))).append(":"); - appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.ALCHEMY))).append(":"); - appendable.append(profile.getUniqueId() != null ? profile.getUniqueId().toString() : "NULL").append(":"); + appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.ALCHEMY))) + .append(":"); + appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.ALCHEMY))) + .append(":"); + appendable.append(profile.getUniqueId() != null ? profile.getUniqueId().toString() : "NULL") + .append(":"); appendable.append(String.valueOf(profile.getScoreboardTipsShown())).append(":"); - appendable.append(String.valueOf(profile.getUniqueData(UniqueDataType.CHIMAERA_WING_DATS))).append(":"); + appendable.append(String.valueOf(profile.getUniqueData(UniqueDataType.CHIMAERA_WING_DATS))) + .append(":"); appendable.append(String.valueOf(profile.getLastLogin())).append(":"); //overhaul last login - appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.CROSSBOWS))).append(":"); - appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.CROSSBOWS))).append(":"); - appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.TRIDENTS))).append(":"); - appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.TRIDENTS))).append(":"); + appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.CROSSBOWS))) + .append(":"); + appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.CROSSBOWS))) + .append(":"); + appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.TRIDENTS))) + .append(":"); + appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.TRIDENTS))) + .append(":"); // public static final int COOLDOWN_SUPER_SHOTGUN = 49; - appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.SUPER_SHOTGUN))).append(":"); + appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.SUPER_SHOTGUN))) + .append(":"); // public static final int COOLDOWN_TRIDENTS = 50; - appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.TRIDENTS_SUPER_ABILITY))).append(":"); + appendable.append( + String.valueOf(profile.getAbilityDATS(SuperAbilityType.TRIDENTS_SUPER_ABILITY))) + .append(":"); // public static final int COOLDOWN_ARCHERY = 51; - appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.EXPLOSIVE_SHOT))).append(":"); + appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.EXPLOSIVE_SHOT))) + .append(":"); // public static final int EXP_MACES = 52; - appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.MACES))).append(":"); + appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.MACES))) + .append(":"); // public static final int SKILLS_MACES = 53; - appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.MACES))).append(":"); + appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.MACES))) + .append(":"); // public static final int COOLDOWN_MACES = 54; - appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.MACES_SUPER_ABILITY))).append(":"); + appendable.append( + String.valueOf(profile.getAbilityDATS(SuperAbilityType.MACES_SUPER_ABILITY))) + .append(":"); appendable.append("\r\n"); } - public @NotNull List readLeaderboard(@Nullable PrimarySkillType primarySkillType, int pageNumber, int statsPerPage) throws InvalidSkillException { + public @NotNull List readLeaderboard(@Nullable PrimarySkillType primarySkillType, + int pageNumber, int statsPerPage) throws InvalidSkillException { //Fix for a plugin that people are using that is throwing SQL errors if (primarySkillType != null && SkillTools.isChildSkill(primarySkillType)) { - logger.severe("A plugin hooking into mcMMO is being naughty with our database commands, update all plugins that hook into mcMMO and contact their devs!"); - throw new InvalidSkillException("A plugin hooking into mcMMO that you are using is attempting to read leaderboard skills for child skills, child skills do not have leaderboards! This is NOT an mcMMO error!"); + logger.severe( + "A plugin hooking into mcMMO is being naughty with our database commands, update all plugins that hook into mcMMO and contact their devs!"); + throw new InvalidSkillException( + "A plugin hooking into mcMMO that you are using is attempting to read leaderboard skills for child skills, child skills do not have leaderboards! This is NOT an mcMMO error!"); } updateLeaderboards(); - List statsList = primarySkillType == null ? powerLevels : playerStatHash.get(primarySkillType); + List statsList = + primarySkillType == null ? powerLevels : playerStatHash.get(primarySkillType); int fromIndex = (Math.max(pageNumber, 1) - 1) * statsPerPage; - return statsList.subList(Math.min(fromIndex, statsList.size()), Math.min(fromIndex + statsPerPage, statsList.size())); + return statsList.subList(Math.min(fromIndex, statsList.size()), + Math.min(fromIndex + statsPerPage, statsList.size())); } public @NotNull HashMap readRank(String playerName) { @@ -532,13 +592,14 @@ public final class FlatFileDatabaseManager implements DatabaseManager { PlayerProfile playerProfile = new PlayerProfile(playerName, uuid, true, startingLevel); synchronized (fileWritingLock) { - try(BufferedReader bufferedReader = new BufferedReader(new FileReader(usersFilePath))) { + try (BufferedReader bufferedReader = new BufferedReader( + new FileReader(usersFilePath))) { StringBuilder stringBuilder = new StringBuilder(); String line; //Build up the file - while((line = bufferedReader.readLine()) != null) { + while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line).append("\r\n"); } @@ -568,7 +629,8 @@ public final class FlatFileDatabaseManager implements DatabaseManager { return processUserQuery(getUserQuery(uuid, null)); } - private @NotNull UserQuery getUserQuery(@Nullable UUID uuid, @Nullable String playerName) throws NullPointerException { + private @NotNull UserQuery getUserQuery(@Nullable UUID uuid, @Nullable String playerName) + throws NullPointerException { boolean hasName = playerName != null && !playerName.equalsIgnoreCase("null"); if (hasName && uuid != null) { @@ -578,18 +640,20 @@ public final class FlatFileDatabaseManager implements DatabaseManager { } else if (hasName) { return new UserQueryNameImpl(playerName); } else { - throw new NullPointerException("Both name and UUID cannot be null, at least one must be non-null!"); + throw new NullPointerException( + "Both name and UUID cannot be null, at least one must be non-null!"); } } /** - * Find and load a player by UUID/Name - * If the name isn't null and doesn't match the name in the DB, the players name is then replaced/updated + * Find and load a player by UUID/Name If the name isn't null and doesn't match the name in the + * DB, the players name is then replaced/updated * * @param userQuery the query * @return a profile with the targets data or an unloaded profile if no data was found */ - private @NotNull PlayerProfile processUserQuery(@NotNull UserQuery userQuery) throws RuntimeException { + private @NotNull PlayerProfile processUserQuery(@NotNull UserQuery userQuery) + throws RuntimeException { return switch (userQuery.getType()) { case UUID_AND_NAME -> queryByUUIDAndName((UserQueryFull) userQuery); case UUID -> queryByUUID((UserQueryUUID) userQuery); @@ -607,13 +671,11 @@ public final class FlatFileDatabaseManager implements DatabaseManager { in = new BufferedReader(new FileReader(usersFilePath)); String line; - while ((line = in.readLine()) != null) { if (line.startsWith("#")) { continue; } - // Find if the line contains the player we want. String[] rawSplitData = line.split(":"); @@ -643,7 +705,6 @@ public final class FlatFileDatabaseManager implements DatabaseManager { } } - //Return a new blank profile return new PlayerProfile(playerName, new UUID(0, 0), startingLevel); } @@ -700,7 +761,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { * No match was found in the file */ - return grabUnloadedProfile(uuid, "Player-Not-Found="+ uuid); + return grabUnloadedProfile(uuid, "Player-Not-Found=" + uuid); } private @NotNull PlayerProfile queryByUUIDAndName(@NotNull UserQueryFull userQuery) { @@ -735,8 +796,11 @@ public final class FlatFileDatabaseManager implements DatabaseManager { boolean matchingName = dbPlayerName.equalsIgnoreCase(playerName); if (!matchingName) { - logger.warning("When loading user: "+playerName +" with UUID of (" + uuid - +") we found a mismatched name, the name in the DB will be replaced (DB name: "+dbPlayerName+")"); + logger.warning( + "When loading user: " + playerName + " with UUID of (" + + uuid + + ") we found a mismatched name, the name in the DB will be replaced (DB name: " + + dbPlayerName + ")"); //logger.info("Name updated for player: " + rawSplitData[USERNAME_INDEX] + " => " + playerName); rawSplitData[USERNAME_INDEX] = playerName; } @@ -772,7 +836,8 @@ public final class FlatFileDatabaseManager implements DatabaseManager { return grabUnloadedProfile(uuid, playerName); //Create an empty new profile and return } - private @NotNull PlayerProfile grabUnloadedProfile(@NotNull UUID uuid, @Nullable String playerName) { + private @NotNull PlayerProfile grabUnloadedProfile(@NotNull UUID uuid, + @Nullable String playerName) { if (playerName == null) { playerName = ""; //No name for you boy! } @@ -806,16 +871,13 @@ public final class FlatFileDatabaseManager implements DatabaseManager { 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 } } @@ -855,25 +917,22 @@ public final class FlatFileDatabaseManager implements DatabaseManager { out = new FileWriter(usersFilePath); // Write out the new file out.write(writer.toString()); - } - catch (Exception e) { - logger.severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e); - } - finally { + } catch (Exception e) { + logger.severe("Exception while reading " + usersFilePath + + " (Are you sure you formatted it correctly?)" + e); + } finally { LogUtils.debug(logger, 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 } } @@ -896,14 +955,17 @@ public final class FlatFileDatabaseManager implements DatabaseManager { while (((line = in.readLine()) != null)) { String[] character = line.split(":"); - if (!fetchedUUIDs.isEmpty() && fetchedUUIDs.containsKey(character[USERNAME_INDEX])) { + if (!fetchedUUIDs.isEmpty() && fetchedUUIDs.containsKey( + character[USERNAME_INDEX])) { if (character.length < 42) { - logger.severe("Could not update UUID for " + character[USERNAME_INDEX] + "!"); + logger.severe( + "Could not update UUID for " + character[USERNAME_INDEX] + "!"); logger.severe("Database entry is invalid."); continue; } - character[UUID_INDEX] = fetchedUUIDs.remove(character[USERNAME_INDEX]).toString(); + character[UUID_INDEX] = fetchedUUIDs.remove(character[USERNAME_INDEX]) + .toString(); line = org.apache.commons.lang3.StringUtils.join(character, ":") + ":"; } @@ -913,25 +975,22 @@ public final class FlatFileDatabaseManager implements DatabaseManager { out = new FileWriter(usersFilePath); // Write out the new file out.write(writer.toString()); - } - catch (Exception e) { - logger.severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e); - } - finally { + } catch (Exception e) { + logger.severe("Exception while reading " + usersFilePath + + " (Are you sure you formatted it correctly?)" + e); + } finally { LogUtils.debug(logger, 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 } } @@ -955,16 +1014,13 @@ public final class FlatFileDatabaseManager implements DatabaseManager { String[] character = line.split(":"); users.add(character[USERNAME_INDEX]); } - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); - } - finally { + } finally { if (in != null) { try { in.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } @@ -1013,8 +1069,9 @@ public final class FlatFileDatabaseManager implements DatabaseManager { while ((line = in.readLine()) != null) { - if (line.startsWith("#")) + if (line.startsWith("#")) { continue; + } String[] data = line.split(":"); playerName = data[USERNAME_INDEX]; @@ -1022,35 +1079,45 @@ public final class FlatFileDatabaseManager implements DatabaseManager { Map skills = getSkillMapFromLine(data); - powerLevel += putStat(acrobatics, playerName, skills.get(PrimarySkillType.ACROBATICS)); - powerLevel += putStat(alchemy, playerName, skills.get(PrimarySkillType.ALCHEMY)); - powerLevel += putStat(archery, playerName, skills.get(PrimarySkillType.ARCHERY)); + powerLevel += putStat(acrobatics, playerName, + skills.get(PrimarySkillType.ACROBATICS)); + powerLevel += putStat(alchemy, playerName, + skills.get(PrimarySkillType.ALCHEMY)); + powerLevel += putStat(archery, playerName, + skills.get(PrimarySkillType.ARCHERY)); powerLevel += putStat(axes, playerName, skills.get(PrimarySkillType.AXES)); - powerLevel += putStat(excavation, playerName, skills.get(PrimarySkillType.EXCAVATION)); - powerLevel += putStat(fishing, playerName, skills.get(PrimarySkillType.FISHING)); - powerLevel += putStat(herbalism, playerName, skills.get(PrimarySkillType.HERBALISM)); + powerLevel += putStat(excavation, playerName, + skills.get(PrimarySkillType.EXCAVATION)); + powerLevel += putStat(fishing, playerName, + skills.get(PrimarySkillType.FISHING)); + powerLevel += putStat(herbalism, playerName, + skills.get(PrimarySkillType.HERBALISM)); powerLevel += putStat(mining, playerName, skills.get(PrimarySkillType.MINING)); powerLevel += putStat(repair, playerName, skills.get(PrimarySkillType.REPAIR)); powerLevel += putStat(swords, playerName, skills.get(PrimarySkillType.SWORDS)); powerLevel += putStat(taming, playerName, skills.get(PrimarySkillType.TAMING)); - powerLevel += putStat(unarmed, playerName, skills.get(PrimarySkillType.UNARMED)); - powerLevel += putStat(woodcutting, playerName, skills.get(PrimarySkillType.WOODCUTTING)); - powerLevel += putStat(crossbows, playerName, skills.get(PrimarySkillType.CROSSBOWS)); - powerLevel += putStat(tridents, playerName, skills.get(PrimarySkillType.TRIDENTS)); + powerLevel += putStat(unarmed, playerName, + skills.get(PrimarySkillType.UNARMED)); + powerLevel += putStat(woodcutting, playerName, + skills.get(PrimarySkillType.WOODCUTTING)); + powerLevel += putStat(crossbows, playerName, + skills.get(PrimarySkillType.CROSSBOWS)); + powerLevel += putStat(tridents, playerName, + skills.get(PrimarySkillType.TRIDENTS)); powerLevel += putStat(maces, playerName, skills.get(PrimarySkillType.MACES)); putStat(powerLevels, playerName, powerLevel); } - } - catch (Exception e) { - logger.severe("Exception while reading " + usersFilePath + " during user " + playerName + " (Are you sure you formatted it correctly?) " + e); + } catch (Exception e) { + logger.severe( + "Exception while reading " + usersFilePath + " during user " + playerName + + " (Are you sure you formatted it correctly?) " + e); return LeaderboardStatus.FAILED; } finally { if (in != null) { try { in.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } @@ -1104,17 +1171,19 @@ public final class FlatFileDatabaseManager implements DatabaseManager { try { // Open the file to write the player bufferedWriter = new BufferedWriter(new FileWriter(usersFilePath, true)); - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm"); + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern( + "MM/dd/yyyy HH:mm"); LocalDateTime localDateTime = LocalDateTime.now(); - bufferedWriter.append("# mcMMO Database created on ").append(localDateTime.format(dateTimeFormatter)).append("\r\n"); //Empty file + bufferedWriter.append("# mcMMO Database created on ") + .append(localDateTime.format(dateTimeFormatter)) + .append("\r\n"); //Empty file } catch (Exception e) { e.printStackTrace(); } finally { if (bufferedWriter != null) { try { bufferedWriter.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } @@ -1144,13 +1213,15 @@ public final class FlatFileDatabaseManager implements DatabaseManager { //Analyze the data while ((currentLine = bufferedReader.readLine()) != null) { //Commented lines - if (currentLine.startsWith("#") && dbCommentDate == null) { //The first commented line in the file is likely to be our note about when the file was created + if (currentLine.startsWith("#") && dbCommentDate + == null) { //The first commented line in the file is likely to be our note about when the file was created dbCommentDate = currentLine; continue; } - if (currentLine.isEmpty()) + if (currentLine.isEmpty()) { continue; + } //TODO: We are never passing empty lines, should we remove the flag for them? dataProcessor.processData(currentLine); @@ -1162,8 +1233,9 @@ public final class FlatFileDatabaseManager implements DatabaseManager { logger.info("Updating FlatFile Database..."); fileWriter = new FileWriter(usersFilePath); //Write data to file - if (dbCommentDate != null) + if (dbCommentDate != null) { fileWriter.write(dbCommentDate + "\r\n"); + } fileWriter.write(dataProcessor.processDataForSave().toString()); } @@ -1186,8 +1258,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { if (bufferedReader != null) { try { bufferedReader.close(); - } - catch (IOException e) { + } catch (IOException e) { e.printStackTrace(); } } @@ -1195,8 +1266,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { if (fileWriter != null) { try { fileWriter.close(); - } - catch (IOException e) { + } catch (IOException e) { e.printStackTrace(); } } @@ -1233,67 +1303,95 @@ public final class FlatFileDatabaseManager implements DatabaseManager { } private PlayerProfile loadFromLine(@NotNull String[] character) { - Map skills = getSkillMapFromLine(character); // Skill levels - Map skillsXp = new EnumMap<>(PrimarySkillType.class); // Skill & XP - Map skillsDATS = new EnumMap<>(SuperAbilityType.class); // Ability & Cooldown + 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); int scoreboardTipsShown; long lastLogin; String username = character[USERNAME_INDEX]; - tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.TAMING, EXP_TAMING, username); - tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.MINING, EXP_MINING, username); - tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.REPAIR, EXP_REPAIR, username); - tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.WOODCUTTING, EXP_WOODCUTTING, username); - tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.UNARMED, EXP_UNARMED, username); - tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.HERBALISM, EXP_HERBALISM, username); - tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.EXCAVATION, EXP_EXCAVATION, username); - tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.ARCHERY, EXP_ARCHERY, username); - tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.SWORDS, EXP_SWORDS, username); - tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.AXES, EXP_AXES, username); - tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.ACROBATICS, EXP_ACROBATICS, username); - tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.FISHING, EXP_FISHING, username); - tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.ALCHEMY, EXP_ALCHEMY, username); - tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.CROSSBOWS, EXP_CROSSBOWS, username); - tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.TRIDENTS, EXP_TRIDENTS, username); - tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.MACES, EXP_MACES, username); + tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.TAMING, EXP_TAMING, + username); + tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.MINING, EXP_MINING, + username); + tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.REPAIR, EXP_REPAIR, + username); + tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.WOODCUTTING, + EXP_WOODCUTTING, username); + tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.UNARMED, + EXP_UNARMED, username); + tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.HERBALISM, + EXP_HERBALISM, username); + tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.EXCAVATION, + EXP_EXCAVATION, username); + tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.ARCHERY, + EXP_ARCHERY, username); + tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.SWORDS, EXP_SWORDS, + username); + tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.AXES, EXP_AXES, + username); + tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.ACROBATICS, + EXP_ACROBATICS, username); + tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.FISHING, + EXP_FISHING, username); + tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.ALCHEMY, + EXP_ALCHEMY, username); + tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.CROSSBOWS, + EXP_CROSSBOWS, username); + tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.TRIDENTS, + EXP_TRIDENTS, username); + tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.MACES, EXP_MACES, + username); // Taming - Unused - tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.SUPER_BREAKER, COOLDOWN_SUPER_BREAKER, username); + tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.SUPER_BREAKER, + COOLDOWN_SUPER_BREAKER, username); // Repair - Unused - tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.TREE_FELLER, COOLDOWN_TREE_FELLER, username); - tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.BERSERK, COOLDOWN_BERSERK, username); - tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.GREEN_TERRA, COOLDOWN_GREEN_TERRA, username); - tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.GIGA_DRILL_BREAKER, COOLDOWN_GIGA_DRILL_BREAKER, username); - tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.EXPLOSIVE_SHOT, COOLDOWN_ARCHERY, username); - tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.SERRATED_STRIKES, COOLDOWN_SERRATED_STRIKES, username); - tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.SKULL_SPLITTER, COOLDOWN_SKULL_SPLITTER, username); + tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.TREE_FELLER, + COOLDOWN_TREE_FELLER, username); + tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.BERSERK, + COOLDOWN_BERSERK, username); + tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.GREEN_TERRA, + COOLDOWN_GREEN_TERRA, username); + tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.GIGA_DRILL_BREAKER, + COOLDOWN_GIGA_DRILL_BREAKER, username); + tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.EXPLOSIVE_SHOT, + COOLDOWN_ARCHERY, username); + tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.SERRATED_STRIKES, + COOLDOWN_SERRATED_STRIKES, username); + tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.SKULL_SPLITTER, + COOLDOWN_SKULL_SPLITTER, username); // Acrobatics - Unused - tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.BLAST_MINING, COOLDOWN_BLAST_MINING, username); - tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.SUPER_SHOTGUN, COOLDOWN_SUPER_SHOTGUN, username); - tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.TRIDENTS_SUPER_ABILITY, COOLDOWN_TRIDENTS, username); - tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.MACES_SUPER_ABILITY, COOLDOWN_MACES, username); + tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.BLAST_MINING, + COOLDOWN_BLAST_MINING, username); + tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.SUPER_SHOTGUN, + COOLDOWN_SUPER_SHOTGUN, username); + tryLoadSkillCooldownFromRawData(skillsDATS, character, + SuperAbilityType.TRIDENTS_SUPER_ABILITY, COOLDOWN_TRIDENTS, username); + tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.MACES_SUPER_ABILITY, + COOLDOWN_MACES, username); UUID uuid; try { uuid = UUID.fromString(character[UUID_INDEX]); - } - catch (Exception e) { + } catch (Exception e) { uuid = null; } try { scoreboardTipsShown = Integer.parseInt(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) { + uniquePlayerDataMap.put(UniqueDataType.CHIMAERA_WING_DATS, + Integer.valueOf(character[COOLDOWN_CHIMAERA_WING])); + } catch (Exception e) { uniquePlayerDataMap.put(UniqueDataType.CHIMAERA_WING_DATS, 0); } @@ -1303,10 +1401,13 @@ public final class FlatFileDatabaseManager implements DatabaseManager { lastLogin = -1; } - return new PlayerProfile(username, uuid, skills, skillsXp, skillsDATS, scoreboardTipsShown, uniquePlayerDataMap, lastLogin); + return new PlayerProfile(username, uuid, skills, skillsXp, skillsDATS, scoreboardTipsShown, + uniquePlayerDataMap, lastLogin); } - private void tryLoadSkillCooldownFromRawData(@NotNull Map cooldownMap, @NotNull String[] splitData, @NotNull SuperAbilityType superAbilityType, int index, @NotNull String userName) { + private void tryLoadSkillCooldownFromRawData( + @NotNull Map cooldownMap, @NotNull String[] splitData, + @NotNull SuperAbilityType superAbilityType, int index, @NotNull String userName) { try { cooldownMap.put(superAbilityType, Integer.valueOf(splitData[index])); } catch (IndexOutOfBoundsException e) { @@ -1314,56 +1415,84 @@ public final class FlatFileDatabaseManager implements DatabaseManager { // set to 0 when data not found cooldownMap.put(superAbilityType, 0); } catch (NumberFormatException e) { - throw new NumberFormatException("Data corruption when trying to load the cooldown for skill "+superAbilityType+" for player named " + userName); + throw new NumberFormatException( + "Data corruption when trying to load the cooldown for skill " + superAbilityType + + " for player named " + userName); } } - private void tryLoadSkillFloatValuesFromRawData(@NotNull Map skillMap, @NotNull String[] character, @NotNull PrimarySkillType primarySkillType, int index, @NotNull String userName) { + private void tryLoadSkillFloatValuesFromRawData(@NotNull Map skillMap, + @NotNull String[] character, @NotNull PrimarySkillType primarySkillType, int index, + @NotNull String userName) { try { float valueFromString = Integer.parseInt(character[index]); skillMap.put(primarySkillType, valueFromString); } catch (NumberFormatException e) { skillMap.put(primarySkillType, 0F); - logger.severe("Data corruption when trying to load the value for skill "+primarySkillType+" for player named " + userName+ " setting value to zero"); + logger.severe( + "Data corruption when trying to load the value for skill " + primarySkillType + + " for player named " + userName + " setting value to zero"); e.printStackTrace(); } } - private void tryLoadSkillIntValuesFromRawData(@NotNull Map skillMap, @NotNull String[] character, @NotNull PrimarySkillType primarySkillType, int index, @NotNull String userName) { + private void tryLoadSkillIntValuesFromRawData(@NotNull Map skillMap, + @NotNull String[] character, @NotNull PrimarySkillType primarySkillType, int index, + @NotNull String userName) { try { int valueFromString = Integer.parseInt(character[index]); skillMap.put(primarySkillType, valueFromString); - } catch (ArrayIndexOutOfBoundsException e ) { + } catch (ArrayIndexOutOfBoundsException e) { // TODO: Add debug message // set to 0 when data not found skillMap.put(primarySkillType, 0); } catch (NumberFormatException e) { skillMap.put(primarySkillType, 0); - logger.severe("Data corruption when trying to load the value for skill "+primarySkillType+" for player named " + userName+ " setting value to zero"); + logger.severe( + "Data corruption when trying to load the value for skill " + primarySkillType + + " for player named " + userName + " setting value to zero"); e.printStackTrace(); } } - private @NotNull Map getSkillMapFromLine(@NotNull String[] character) { - EnumMap skills = new EnumMap<>(PrimarySkillType.class); // Skill & Level + private @NotNull Map getSkillMapFromLine( + @NotNull String[] character) { + EnumMap skills = new EnumMap<>( + PrimarySkillType.class); // Skill & Level String username = character[USERNAME_INDEX]; - tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.ACROBATICS, SKILLS_ACROBATICS, username); - tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.TAMING, SKILLS_TAMING, username); - tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.MINING, SKILLS_MINING, username); - tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.REPAIR, SKILLS_REPAIR, username); - tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.WOODCUTTING, SKILLS_WOODCUTTING, username); - tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.UNARMED, SKILLS_UNARMED, username); - tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.HERBALISM, SKILLS_HERBALISM, username); - tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.EXCAVATION, SKILLS_EXCAVATION, username); - tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.ARCHERY, SKILLS_ARCHERY, username); - tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.SWORDS, SKILLS_SWORDS, username); - tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.AXES, SKILLS_AXES, username); - tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.FISHING, SKILLS_FISHING, username); - tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.ALCHEMY, SKILLS_ALCHEMY, username); - tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.CROSSBOWS, SKILLS_CROSSBOWS, username); - tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.TRIDENTS, SKILLS_TRIDENTS, username); - tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.MACES, SKILLS_MACES, username); + tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.ACROBATICS, + SKILLS_ACROBATICS, username); + tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.TAMING, SKILLS_TAMING, + username); + tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.MINING, SKILLS_MINING, + username); + tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.REPAIR, SKILLS_REPAIR, + username); + tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.WOODCUTTING, + SKILLS_WOODCUTTING, username); + tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.UNARMED, + SKILLS_UNARMED, username); + tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.HERBALISM, + SKILLS_HERBALISM, username); + tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.EXCAVATION, + SKILLS_EXCAVATION, username); + tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.ARCHERY, + SKILLS_ARCHERY, username); + tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.SWORDS, SKILLS_SWORDS, + username); + tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.AXES, SKILLS_AXES, + username); + tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.FISHING, + SKILLS_FISHING, username); + tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.ALCHEMY, + SKILLS_ALCHEMY, username); + tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.CROSSBOWS, + SKILLS_CROSSBOWS, username); + tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.TRIDENTS, + SKILLS_TRIDENTS, username); + tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.MACES, SKILLS_MACES, + username); return skills; } @@ -1377,5 +1506,6 @@ public final class FlatFileDatabaseManager implements DatabaseManager { } @Override - public void onDisable() { } + public void onDisable() { + } } diff --git a/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java b/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java index 70dafbf9c..50866edb1 100644 --- a/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java +++ b/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java @@ -14,6 +14,22 @@ import com.gmail.nossr50.runnables.database.UUIDUpdateAsyncTask; import com.gmail.nossr50.util.LogUtils; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.skills.SkillTools; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.locks.ReentrantLock; +import java.util.logging.Logger; import org.apache.tomcat.jdbc.pool.DataSource; import org.apache.tomcat.jdbc.pool.PoolProperties; import org.bukkit.OfflinePlayer; @@ -21,11 +37,6 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.sql.*; -import java.util.*; -import java.util.concurrent.locks.ReentrantLock; -import java.util.logging.Logger; - public final class SQLDatabaseManager implements DatabaseManager { private static final String ALL_QUERY_VERSION = "total"; public static final String MOBHEALTHBAR_VARCHAR = "VARCHAR(50)"; @@ -60,7 +71,7 @@ public final class SQLDatabaseManager implements DatabaseManager { String connectionString = getConnectionString(h2); if (!h2 && mcMMO.p.getGeneralConfig().getMySQLPublicKeyRetrieval()) { - connectionString+= + connectionString += "&allowPublicKeyRetrieval=true"; } @@ -87,8 +98,10 @@ public final class SQLDatabaseManager implements DatabaseManager { poolProperties.setUrl(connectionString); poolProperties.setUsername(mcMMO.p.getGeneralConfig().getMySQLUserName()); poolProperties.setPassword(mcMMO.p.getGeneralConfig().getMySQLUserPassword()); - poolProperties.setMaxIdle(mcMMO.p.getGeneralConfig().getMySQLMaxPoolSize(PoolIdentifier.MISC)); - poolProperties.setMaxActive(mcMMO.p.getGeneralConfig().getMySQLMaxConnections(PoolIdentifier.MISC)); + poolProperties.setMaxIdle( + mcMMO.p.getGeneralConfig().getMySQLMaxPoolSize(PoolIdentifier.MISC)); + poolProperties.setMaxActive( + mcMMO.p.getGeneralConfig().getMySQLMaxConnections(PoolIdentifier.MISC)); poolProperties.setInitialSize(0); poolProperties.setMaxWait(-1); poolProperties.setRemoveAbandoned(true); @@ -103,8 +116,10 @@ public final class SQLDatabaseManager implements DatabaseManager { poolProperties.setUsername(mcMMO.p.getGeneralConfig().getMySQLUserName()); poolProperties.setPassword(mcMMO.p.getGeneralConfig().getMySQLUserPassword()); poolProperties.setInitialSize(0); - poolProperties.setMaxIdle(mcMMO.p.getGeneralConfig().getMySQLMaxPoolSize(PoolIdentifier.SAVE)); - poolProperties.setMaxActive(mcMMO.p.getGeneralConfig().getMySQLMaxConnections(PoolIdentifier.SAVE)); + poolProperties.setMaxIdle( + mcMMO.p.getGeneralConfig().getMySQLMaxPoolSize(PoolIdentifier.SAVE)); + poolProperties.setMaxActive( + mcMMO.p.getGeneralConfig().getMySQLMaxConnections(PoolIdentifier.SAVE)); poolProperties.setMaxWait(-1); poolProperties.setRemoveAbandoned(true); poolProperties.setRemoveAbandonedTimeout(60); @@ -118,8 +133,10 @@ public final class SQLDatabaseManager implements DatabaseManager { poolProperties.setUsername(mcMMO.p.getGeneralConfig().getMySQLUserName()); poolProperties.setPassword(mcMMO.p.getGeneralConfig().getMySQLUserPassword()); poolProperties.setInitialSize(0); - poolProperties.setMaxIdle(mcMMO.p.getGeneralConfig().getMySQLMaxPoolSize(PoolIdentifier.LOAD)); - poolProperties.setMaxActive(mcMMO.p.getGeneralConfig().getMySQLMaxConnections(PoolIdentifier.LOAD)); + poolProperties.setMaxIdle( + mcMMO.p.getGeneralConfig().getMySQLMaxPoolSize(PoolIdentifier.LOAD)); + poolProperties.setMaxActive( + mcMMO.p.getGeneralConfig().getMySQLMaxConnections(PoolIdentifier.LOAD)); poolProperties.setMaxWait(-1); poolProperties.setRemoveAbandoned(true); poolProperties.setRemoveAbandonedTimeout(60); @@ -138,17 +155,20 @@ public final class SQLDatabaseManager implements DatabaseManager { } String connectionString = "jdbc:mysql://" + mcMMO.p.getGeneralConfig().getMySQLServerName() - + ":" + mcMMO.p.getGeneralConfig().getMySQLServerPort() + "/" + mcMMO.p.getGeneralConfig().getMySQLDatabaseName(); + + ":" + mcMMO.p.getGeneralConfig().getMySQLServerPort() + "/" + + mcMMO.p.getGeneralConfig().getMySQLDatabaseName(); - if (!mcMMO.getCompatibilityManager().getMinecraftGameVersion().isAtLeast(1, 17, 0) //Temporary hack for SQL and 1.17 support - && mcMMO.p.getGeneralConfig().getMySQLSSL()) + if (!mcMMO.getCompatibilityManager().getMinecraftGameVersion().isAtLeast(1, 17, 0) + //Temporary hack for SQL and 1.17 support + && mcMMO.p.getGeneralConfig().getMySQLSSL()) { + connectionString += + "?verifyServerCertificate=false" + + "&useSSL=true" + + "&requireSSL=true"; + } else { connectionString += - "?verifyServerCertificate=false"+ - "&useSSL=true"+ - "&requireSSL=true"; - else - connectionString+= "?useSSL=false"; + } return connectionString; } @@ -171,15 +191,25 @@ public final class SQLDatabaseManager implements DatabaseManager { + "archery = 0 AND swords = 0 AND axes = 0 AND acrobatics = 0 " + "AND fishing = 0 AND alchemy = 0 AND crossbows = 0 AND tridents = 0 AND maces = 0;"); - statement.executeUpdate("DELETE FROM `" + tablePrefix + "experience` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "skills` `s` WHERE `" + tablePrefix + "experience`.`user_id` = `s`.`user_id`)"); - 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) { + statement.executeUpdate( + "DELETE FROM `" + tablePrefix + "experience` WHERE NOT EXISTS (SELECT * FROM `" + + tablePrefix + "skills` `s` WHERE `" + tablePrefix + + "experience`.`user_id` = `s`.`user_id`)"); + 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) { printErrors(ex); - } - finally { + } finally { tryClose(statement); tryClose(connection); massUpdateLock.unlock(); @@ -191,7 +221,8 @@ public final class SQLDatabaseManager implements DatabaseManager { public void purgeOldUsers() { massUpdateLock.lock(); - logger.info("Purging inactive users older than " + (mcMMO.p.getPurgeTime() / 2630000000L) + " months..."); + logger.info("Purging inactive users older than " + (mcMMO.p.getPurgeTime() / 2630000000L) + + " months..."); Connection connection = null; Statement statement = null; @@ -201,14 +232,15 @@ public final class SQLDatabaseManager implements DatabaseManager { connection = getConnection(PoolIdentifier.MISC); statement = connection.createStatement(); - purged = statement.executeUpdate("DELETE FROM u, e, h, s, c USING " + tablePrefix + "users u " + - "JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) " + - "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) " + - "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " + - "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " + - "WHERE ((UNIX_TIMESTAMP() - lastlogin) > " + mcMMO.p.getPurgeTime() + ")"); - } - catch (SQLException ex) { + purged = statement.executeUpdate( + "DELETE FROM u, e, h, s, c USING " + tablePrefix + "users u " + + "JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) " + + "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) " + + "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " + + "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " + + "WHERE ((UNIX_TIMESTAMP() - lastlogin) > " + mcMMO.p.getPurgeTime() + + ")"); + } catch (SQLException ex) { printErrors(ex); } finally { tryClose(statement); @@ -237,18 +269,17 @@ 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); } if (success) { - if (uuid != null) + if (uuid != null) { cleanupUser(uuid); + } Misc.profileCleanup(playerName); } @@ -278,7 +309,8 @@ public final class SQLDatabaseManager implements DatabaseManager { } } - statement = connection.prepareStatement("UPDATE " + tablePrefix + "users SET lastlogin = UNIX_TIMESTAMP() WHERE id = ?"); + statement = connection.prepareStatement("UPDATE " + tablePrefix + + "users SET lastlogin = UNIX_TIMESTAMP() WHERE id = ?"); statement.setInt(1, id); success &= (statement.executeUpdate() != 0); statement.close(); @@ -309,8 +341,9 @@ public final class SQLDatabaseManager implements DatabaseManager { statement.setInt(15, profile.getSkillLevel(PrimarySkillType.TRIDENTS)); statement.setInt(16, profile.getSkillLevel(PrimarySkillType.MACES)); int total = 0; - for (PrimarySkillType primarySkillType : SkillTools.NON_CHILD_SKILLS) + for (PrimarySkillType primarySkillType : SkillTools.NON_CHILD_SKILLS) { total += profile.getSkillLevel(primarySkillType); + } statement.setInt(17, total); statement.setInt(18, id); success &= (statement.executeUpdate() != 0); @@ -374,7 +407,8 @@ public final class SQLDatabaseManager implements DatabaseManager { return false; } - statement = connection.prepareStatement("UPDATE " + tablePrefix + "huds SET mobhealthbar = ?, scoreboardtips = ? WHERE user_id = ?"); + statement = connection.prepareStatement("UPDATE " + tablePrefix + + "huds SET mobhealthbar = ?, scoreboardtips = ? WHERE user_id = ?"); statement.setString(1, MobHealthbarType.HEARTS.name()); statement.setInt(2, profile.getScoreboardTipsShown()); statement.setInt(3, id); @@ -384,11 +418,9 @@ public final class SQLDatabaseManager implements DatabaseManager { logger.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); } @@ -396,13 +428,16 @@ public final class SQLDatabaseManager implements DatabaseManager { return success; } - public @NotNull List readLeaderboard(@Nullable PrimarySkillType skill, int pageNumber, int statsPerPage) throws InvalidSkillException { + public @NotNull List readLeaderboard(@Nullable PrimarySkillType skill, + int pageNumber, int statsPerPage) throws InvalidSkillException { List stats = new ArrayList<>(); //Fix for a plugin that people are using that is throwing SQL errors if (skill != null && SkillTools.isChildSkill(skill)) { - logger.severe("A plugin hooking into mcMMO is being naughty with our database commands, update all plugins that hook into mcMMO and contact their devs!"); - throw new InvalidSkillException("A plugin hooking into mcMMO that you are using is attempting to read leaderboard skills for child skills, child skills do not have leaderboards! This is NOT an mcMMO error!"); + logger.severe( + "A plugin hooking into mcMMO is being naughty with our database commands, update all plugins that hook into mcMMO and contact their devs!"); + throw new InvalidSkillException( + "A plugin hooking into mcMMO that you are using is attempting to read leaderboard skills for child skills, child skills do not have leaderboards! This is NOT an mcMMO error!"); } String query = skill == null ? ALL_QUERY_VERSION : skill.name().toLowerCase(Locale.ENGLISH); @@ -412,7 +447,11 @@ public final class SQLDatabaseManager implements DatabaseManager { try { connection = getConnection(PoolIdentifier.MISC); - statement = connection.prepareStatement("SELECT " + query + ", `user` FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON (user_id = id) WHERE " + query + " > 0 AND NOT `user` = '\\_INVALID\\_OLD\\_USERNAME\\_' ORDER BY " + query + " DESC, `user` LIMIT ?, ?"); + statement = connection.prepareStatement( + "SELECT " + query + ", `user` FROM " + tablePrefix + "users JOIN " + tablePrefix + + "skills ON (user_id = id) WHERE " + query + + " > 0 AND NOT `user` = '\\_INVALID\\_OLD\\_USERNAME\\_' ORDER BY " + + query + " DESC, `user` LIMIT ?, ?"); statement.setInt(1, (pageNumber * statsPerPage) - statsPerPage); statement.setInt(2, statsPerPage); resultSet = statement.executeQuery(); @@ -426,11 +465,9 @@ public final class SQLDatabaseManager implements DatabaseManager { stats.add(new PlayerStat(column.get(1), Integer.parseInt(column.get(0)))); } - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(resultSet); tryClose(statement); tryClose(connection); @@ -451,8 +488,10 @@ public final class SQLDatabaseManager implements DatabaseManager { for (PrimarySkillType primarySkillType : SkillTools.NON_CHILD_SKILLS) { String skillName = primarySkillType.name().toLowerCase(Locale.ENGLISH); // Get count of all users with higher skill level than player - String sql = "SELECT COUNT(*) AS 'rank' FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE " + skillName + " > 0 " + - "AND " + skillName + " > (SELECT " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " + + String sql = "SELECT COUNT(*) AS 'rank' FROM " + tablePrefix + "users JOIN " + + tablePrefix + "skills ON user_id = id WHERE " + skillName + " > 0 " + + "AND " + skillName + " > (SELECT " + skillName + " FROM " + tablePrefix + + "users JOIN " + tablePrefix + "skills ON user_id = id " + "WHERE `user` = ?)"; statement = connection.prepareStatement(sql); @@ -464,8 +503,10 @@ public final class SQLDatabaseManager implements DatabaseManager { int rank = resultSet.getInt("rank"); // Ties are settled by alphabetical order - sql = "SELECT user, " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE " + skillName + " > 0 " + - "AND " + skillName + " = (SELECT " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " + + sql = "SELECT user, " + skillName + " FROM " + tablePrefix + "users JOIN " + + tablePrefix + "skills ON user_id = id WHERE " + skillName + " > 0 " + + "AND " + skillName + " = (SELECT " + skillName + " FROM " + tablePrefix + + "users JOIN " + tablePrefix + "skills ON user_id = id " + "WHERE `user` = '" + playerName + "') ORDER BY user"; resultSet.close(); @@ -485,11 +526,14 @@ public final class SQLDatabaseManager implements DatabaseManager { statement.close(); } - String sql = "SELECT COUNT(*) AS 'rank' FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " + - "WHERE " + ALL_QUERY_VERSION + " > 0 " + - "AND " + ALL_QUERY_VERSION + " > " + - "(SELECT " + ALL_QUERY_VERSION + " " + - "FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE `user` = ?)"; + String sql = + "SELECT COUNT(*) AS 'rank' FROM " + tablePrefix + "users JOIN " + tablePrefix + + "skills ON user_id = id " + + "WHERE " + ALL_QUERY_VERSION + " > 0 " + + "AND " + ALL_QUERY_VERSION + " > " + + "(SELECT " + ALL_QUERY_VERSION + " " + + "FROM " + tablePrefix + "users JOIN " + tablePrefix + + "skills ON user_id = id WHERE `user` = ?)"; statement = connection.prepareStatement(sql); statement.setString(1, playerName); @@ -503,11 +547,13 @@ public final class SQLDatabaseManager implements DatabaseManager { statement.close(); sql = "SELECT user, " + ALL_QUERY_VERSION + " " + - "FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " + + "FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " + + "WHERE " + ALL_QUERY_VERSION + " > 0 " + "AND " + ALL_QUERY_VERSION + " = " + "(SELECT " + ALL_QUERY_VERSION + " " + - "FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE `user` = ?) ORDER BY user"; + "FROM " + tablePrefix + "users JOIN " + tablePrefix + + "skills ON user_id = id WHERE `user` = ?) ORDER BY user"; statement = connection.prepareStatement(sql); statement.setString(1, playerName); @@ -522,11 +568,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); @@ -547,7 +591,8 @@ public final class SQLDatabaseManager implements DatabaseManager { tryClose(connection); } - return new PlayerProfile(playerName, uuid, true, mcMMO.p.getAdvancedConfig().getStartingLevel()); + return new PlayerProfile(playerName, uuid, true, + mcMMO.p.getAdvancedConfig().getStartingLevel()); } @Override @@ -557,7 +602,8 @@ public final class SQLDatabaseManager implements DatabaseManager { int id = newUser(connection, player.getName(), player.getUniqueId()); if (id == -1) { - return new PlayerProfile(player.getName(), player.getUniqueId(), false, mcMMO.p.getAdvancedConfig().getStartingLevel()); + return new PlayerProfile(player.getName(), player.getUniqueId(), false, + mcMMO.p.getAdvancedConfig().getStartingLevel()); } else { return loadPlayerProfile(player); } @@ -565,7 +611,8 @@ public final class SQLDatabaseManager implements DatabaseManager { e.printStackTrace(); } - return new PlayerProfile(player.getName(), player.getUniqueId(), false, mcMMO.p.getAdvancedConfig().getStartingLevel()); + return new PlayerProfile(player.getName(), player.getUniqueId(), false, + mcMMO.p.getAdvancedConfig().getStartingLevel()); } private int newUser(Connection connection, String playerName, UUID uuid) { @@ -582,7 +629,9 @@ public final class SQLDatabaseManager implements DatabaseManager { statement.executeUpdate(); statement.close(); - statement = connection.prepareStatement("INSERT INTO " + tablePrefix + "users (user, uuid, lastlogin) VALUES (?, ?, UNIX_TIMESTAMP())", Statement.RETURN_GENERATED_KEYS); + statement = connection.prepareStatement("INSERT INTO " + tablePrefix + + "users (user, uuid, lastlogin) VALUES (?, ?, UNIX_TIMESTAMP())", + Statement.RETURN_GENERATED_KEYS); statement.setString(1, playerName); statement.setString(2, uuid != null ? uuid.toString() : null); statement.executeUpdate(); @@ -596,11 +645,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); } @@ -612,7 +659,8 @@ public final class SQLDatabaseManager implements DatabaseManager { return loadPlayerFromDB(null, playerName); } catch (RuntimeException e) { e.printStackTrace(); - return new PlayerProfile(playerName, false, mcMMO.p.getAdvancedConfig().getStartingLevel()); + return new PlayerProfile(playerName, false, + mcMMO.p.getAdvancedConfig().getStartingLevel()); } } @@ -621,7 +669,8 @@ public final class SQLDatabaseManager implements DatabaseManager { return loadPlayerFromDB(offlinePlayer.getUniqueId(), offlinePlayer.getName()); } - public @NotNull PlayerProfile loadPlayerProfile(@NotNull UUID uuid, @Nullable String playerName) { + public @NotNull PlayerProfile loadPlayerProfile(@NotNull UUID uuid, + @Nullable String playerName) { return loadPlayerFromDB(uuid, playerName); } @@ -630,9 +679,11 @@ public final class SQLDatabaseManager implements DatabaseManager { return loadPlayerFromDB(uuid, null); } - private PlayerProfile loadPlayerFromDB(@Nullable UUID uuid, @Nullable String playerName) throws RuntimeException { + private PlayerProfile loadPlayerFromDB(@Nullable UUID uuid, @Nullable String playerName) + throws RuntimeException { if (uuid == null && playerName == null) { - throw new RuntimeException("Error looking up player, both UUID and playerName are null and one must not be."); + throw new RuntimeException( + "Error looking up player, both UUID and playerName are null and one must not be."); } PreparedStatement statement = null; @@ -644,17 +695,21 @@ public final class SQLDatabaseManager implements DatabaseManager { int id = getUserID(connection, playerName, uuid); if (id == -1) { - // There is no such user - return new PlayerProfile(playerName, mcMMO.p.getAdvancedConfig().getStartingLevel()); + // There is no such user + return new PlayerProfile(playerName, + mcMMO.p.getAdvancedConfig().getStartingLevel()); } // There is such a user writeMissingRows(connection, id); statement = connection.prepareStatement( "SELECT " + - "s.taming, s.mining, s.repair, s.woodcutting, s.unarmed, s.herbalism, s.excavation, s.archery, s.swords, s.axes, s.acrobatics, s.fishing, s.alchemy, s.crossbows, s.tridents, s.maces, " + - "e.taming, e.mining, e.repair, e.woodcutting, e.unarmed, e.herbalism, e.excavation, e.archery, e.swords, e.axes, e.acrobatics, e.fishing, e.alchemy, e.crossbows, e.tridents, e.maces, " + - "c.taming, c.mining, c.repair, c.woodcutting, c.unarmed, c.herbalism, c.excavation, c.archery, c.swords, c.axes, c.acrobatics, c.blast_mining, c.chimaera_wing, c.crossbows, c.tridents, c.maces, " + + "s.taming, s.mining, s.repair, s.woodcutting, s.unarmed, s.herbalism, s.excavation, s.archery, s.swords, s.axes, s.acrobatics, s.fishing, s.alchemy, s.crossbows, s.tridents, s.maces, " + + + "e.taming, e.mining, e.repair, e.woodcutting, e.unarmed, e.herbalism, e.excavation, e.archery, e.swords, e.axes, e.acrobatics, e.fishing, e.alchemy, e.crossbows, e.tridents, e.maces, " + + + "c.taming, c.mining, c.repair, c.woodcutting, c.unarmed, c.herbalism, c.excavation, c.archery, c.swords, c.axes, c.acrobatics, c.blast_mining, c.chimaera_wing, c.crossbows, c.tridents, c.maces, " + + "h.mobhealthbar, h.scoreboardtips, u.uuid, u.`user` " + "FROM " + tablePrefix + "users u " + "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " @@ -670,7 +725,8 @@ public final class SQLDatabaseManager implements DatabaseManager { if (resultSet.next()) { try { PlayerProfile profile = loadFromResult(playerName, resultSet); - String name = resultSet.getString(MAGIC_NUMBER); // TODO: Magic Number, make sure it stays updated + String name = resultSet.getString( + MAGIC_NUMBER); // TODO: Magic Number, make sure it stays updated resultSet.close(); statement.close(); @@ -698,17 +754,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); @@ -747,19 +800,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); @@ -780,12 +830,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); } @@ -799,7 +847,8 @@ public final class SQLDatabaseManager implements DatabaseManager { try { connection = getConnection(PoolIdentifier.MISC); - statement = connection.prepareStatement("UPDATE " + tablePrefix + "users SET uuid = ? WHERE `user` = ?"); + statement = connection.prepareStatement( + "UPDATE " + tablePrefix + "users SET uuid = ? WHERE `user` = ?"); for (Map.Entry entry : fetchedUUIDs.entrySet()) { statement.setString(1, entry.getValue().toString()); @@ -820,12 +869,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); } @@ -845,11 +892,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); @@ -869,7 +914,8 @@ public final class SQLDatabaseManager implements DatabaseManager { try { connection = getConnection(PoolIdentifier.MISC); - String schemaQuery = this.h2 ? "SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_name = ?" + String schemaQuery = this.h2 + ? "SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_name = ?" : "SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = ? AND table_name = ?"; statement = connection.prepareStatement(schemaQuery); @@ -896,12 +942,14 @@ public final class SQLDatabaseManager implements DatabaseManager { resultSet = statement.executeQuery(); if (!resultSet.next()) { createStatement = connection.createStatement(); - createStatement.executeUpdate("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "huds` (" - + "`user_id` int(10) unsigned NOT NULL," - + "`mobhealthbar` varchar(50) NOT NULL DEFAULT '" + mcMMO.p.getGeneralConfig().getMobHealthbarDefault() + "'," - + "`scoreboardtips` int(10) NOT NULL DEFAULT '0'," - + "PRIMARY KEY (`user_id`)) " - + "DEFAULT CHARSET=" + CHARSET_SQL + ";"); + createStatement.executeUpdate( + "CREATE TABLE IF NOT EXISTS `" + tablePrefix + "huds` (" + + "`user_id` int(10) unsigned NOT NULL," + + "`mobhealthbar` varchar(50) NOT NULL DEFAULT '" + + mcMMO.p.getGeneralConfig().getMobHealthbarDefault() + "'," + + "`scoreboardtips` int(10) NOT NULL DEFAULT '0'," + + "PRIMARY KEY (`user_id`)) " + + "DEFAULT CHARSET=" + CHARSET_SQL + ";"); tryClose(createStatement); } tryClose(resultSet); @@ -909,26 +957,27 @@ public final class SQLDatabaseManager implements DatabaseManager { resultSet = statement.executeQuery(); if (!resultSet.next()) { createStatement = connection.createStatement(); - createStatement.executeUpdate("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "cooldowns` (" - + "`user_id` int(10) unsigned NOT NULL," - + "`taming` int(32) unsigned NOT NULL DEFAULT '0'," - + "`mining` int(32) unsigned NOT NULL DEFAULT '0'," - + "`woodcutting` int(32) unsigned NOT NULL DEFAULT '0'," - + "`repair` int(32) unsigned NOT NULL DEFAULT '0'," - + "`unarmed` int(32) unsigned NOT NULL DEFAULT '0'," - + "`herbalism` int(32) unsigned NOT NULL DEFAULT '0'," - + "`excavation` int(32) unsigned NOT NULL DEFAULT '0'," - + "`archery` int(32) unsigned NOT NULL DEFAULT '0'," - + "`swords` int(32) unsigned NOT NULL DEFAULT '0'," - + "`axes` int(32) unsigned NOT NULL DEFAULT '0'," - + "`acrobatics` int(32) unsigned NOT NULL DEFAULT '0'," - + "`blast_mining` int(32) unsigned NOT NULL DEFAULT '0'," - + "`chimaera_wing` int(32) unsigned NOT NULL DEFAULT '0'," - + "`crossbows` int(32) unsigned NOT NULL DEFAULT '0'," - + "`tridents` int(32) unsigned NOT NULL DEFAULT '0'," - + "`maces` int(32) unsigned NOT NULL DEFAULT '0'," - + "PRIMARY KEY (`user_id`)) " - + "DEFAULT CHARSET=" + CHARSET_SQL + ";"); + createStatement.executeUpdate( + "CREATE TABLE IF NOT EXISTS `" + tablePrefix + "cooldowns` (" + + "`user_id` int(10) unsigned NOT NULL," + + "`taming` int(32) unsigned NOT NULL DEFAULT '0'," + + "`mining` int(32) unsigned NOT NULL DEFAULT '0'," + + "`woodcutting` int(32) unsigned NOT NULL DEFAULT '0'," + + "`repair` int(32) unsigned NOT NULL DEFAULT '0'," + + "`unarmed` int(32) unsigned NOT NULL DEFAULT '0'," + + "`herbalism` int(32) unsigned NOT NULL DEFAULT '0'," + + "`excavation` int(32) unsigned NOT NULL DEFAULT '0'," + + "`archery` int(32) unsigned NOT NULL DEFAULT '0'," + + "`swords` int(32) unsigned NOT NULL DEFAULT '0'," + + "`axes` int(32) unsigned NOT NULL DEFAULT '0'," + + "`acrobatics` int(32) unsigned NOT NULL DEFAULT '0'," + + "`blast_mining` int(32) unsigned NOT NULL DEFAULT '0'," + + "`chimaera_wing` int(32) unsigned NOT NULL DEFAULT '0'," + + "`crossbows` int(32) unsigned NOT NULL DEFAULT '0'," + + "`tridents` int(32) unsigned NOT NULL DEFAULT '0'," + + "`maces` int(32) unsigned NOT NULL DEFAULT '0'," + + "PRIMARY KEY (`user_id`)) " + + "DEFAULT CHARSET=" + CHARSET_SQL + ";"); tryClose(createStatement); } tryClose(resultSet); @@ -936,29 +985,45 @@ public final class SQLDatabaseManager implements DatabaseManager { resultSet = statement.executeQuery(); if (!resultSet.next()) { String startingLevel = "'" + mcMMO.p.getAdvancedConfig().getStartingLevel() + "'"; - String totalLevel = "'" + (mcMMO.p.getAdvancedConfig().getStartingLevel() * (PrimarySkillType.values().length - CHILD_SKILLS_SIZE)) + "'"; + String totalLevel = "'" + (mcMMO.p.getAdvancedConfig().getStartingLevel() * ( + PrimarySkillType.values().length - CHILD_SKILLS_SIZE)) + "'"; 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+"," - + "`crossbows` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," - + "`tridents` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," - + "`maces` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," - + "`total` int(10) unsigned NOT NULL DEFAULT "+totalLevel+"," - + "PRIMARY KEY (`user_id`)) " - + "DEFAULT CHARSET=" + CHARSET_SQL + ";"); + 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 + + "," + + "`crossbows` int(10) unsigned NOT NULL DEFAULT " + startingLevel + + "," + + "`tridents` int(10) unsigned NOT NULL DEFAULT " + startingLevel + + "," + + "`maces` int(10) unsigned NOT NULL DEFAULT " + startingLevel + "," + + "`total` int(10) unsigned NOT NULL DEFAULT " + totalLevel + "," + + "PRIMARY KEY (`user_id`)) " + + "DEFAULT CHARSET=" + CHARSET_SQL + ";"); tryClose(createStatement); } tryClose(resultSet); @@ -966,25 +1031,26 @@ public final class SQLDatabaseManager implements DatabaseManager { resultSet = statement.executeQuery(); if (!resultSet.next()) { createStatement = connection.createStatement(); - createStatement.executeUpdate("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "experience` (" - + "`user_id` int(10) unsigned NOT NULL," - + "`taming` int(10) unsigned NOT NULL DEFAULT '0'," - + "`mining` int(10) unsigned NOT NULL DEFAULT '0'," - + "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0'," - + "`repair` int(10) unsigned NOT NULL DEFAULT '0'," - + "`unarmed` int(10) unsigned NOT NULL DEFAULT '0'," - + "`herbalism` int(10) unsigned NOT NULL DEFAULT '0'," - + "`excavation` int(10) unsigned NOT NULL DEFAULT '0'," - + "`archery` int(10) unsigned NOT NULL DEFAULT '0'," - + "`swords` int(10) unsigned NOT NULL DEFAULT '0'," - + "`axes` int(10) unsigned NOT NULL DEFAULT '0'," - + "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0'," - + "`fishing` int(10) unsigned NOT NULL DEFAULT '0'," - + "`alchemy` int(10) unsigned NOT NULL DEFAULT '0'," - + "`crossbows` int(10) unsigned NOT NULL DEFAULT '0'," - + "`tridents` int(10) unsigned NOT NULL DEFAULT '0'," - + "PRIMARY KEY (`user_id`)) " - + "DEFAULT CHARSET=" + CHARSET_SQL + ";"); + createStatement.executeUpdate( + "CREATE TABLE IF NOT EXISTS `" + tablePrefix + "experience` (" + + "`user_id` int(10) unsigned NOT NULL," + + "`taming` int(10) unsigned NOT NULL DEFAULT '0'," + + "`mining` int(10) unsigned NOT NULL DEFAULT '0'," + + "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0'," + + "`repair` int(10) unsigned NOT NULL DEFAULT '0'," + + "`unarmed` int(10) unsigned NOT NULL DEFAULT '0'," + + "`herbalism` int(10) unsigned NOT NULL DEFAULT '0'," + + "`excavation` int(10) unsigned NOT NULL DEFAULT '0'," + + "`archery` int(10) unsigned NOT NULL DEFAULT '0'," + + "`swords` int(10) unsigned NOT NULL DEFAULT '0'," + + "`axes` int(10) unsigned NOT NULL DEFAULT '0'," + + "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0'," + + "`fishing` int(10) unsigned NOT NULL DEFAULT '0'," + + "`alchemy` int(10) unsigned NOT NULL DEFAULT '0'," + + "`crossbows` int(10) unsigned NOT NULL DEFAULT '0'," + + "`tridents` int(10) unsigned NOT NULL DEFAULT '0'," + + "PRIMARY KEY (`user_id`)) " + + "DEFAULT CHARSET=" + CHARSET_SQL + ";"); tryClose(createStatement); } tryClose(resultSet); @@ -998,7 +1064,10 @@ public final class SQLDatabaseManager implements DatabaseManager { for (PrimarySkillType skill : SkillTools.NON_CHILD_SKILLS) { int cap = mcMMO.p.getSkillTools().getLevelCap(skill); if (cap != Integer.MAX_VALUE) { - statement = connection.prepareStatement("UPDATE `" + tablePrefix + "skills` SET `" + skill.name().toLowerCase(Locale.ENGLISH) + "` = " + cap + " WHERE `" + skill.name().toLowerCase(Locale.ENGLISH) + "` > " + cap); + statement = connection.prepareStatement( + "UPDATE `" + tablePrefix + "skills` SET `" + skill.name() + .toLowerCase(Locale.ENGLISH) + "` = " + cap + " WHERE `" + + skill.name().toLowerCase(Locale.ENGLISH) + "` > " + cap); statement.executeUpdate(); tryClose(statement); } @@ -1008,15 +1077,25 @@ public final class SQLDatabaseManager implements DatabaseManager { // TODO: refactor LogUtils.debug(logger, "Killing orphans"); createStatement = connection.createStatement(); - createStatement.executeUpdate("DELETE FROM `" + tablePrefix + "experience` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "users` `u` WHERE `" + tablePrefix + "experience`.`user_id` = `u`.`id`)"); - 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) { + createStatement.executeUpdate( + "DELETE FROM `" + tablePrefix + "experience` WHERE NOT EXISTS (SELECT * FROM `" + + tablePrefix + "users` `u` WHERE `" + tablePrefix + + "experience`.`user_id` = `u`.`id`)"); + 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) { printErrors(ex); - } - finally { + } finally { tryClose(resultSet); tryClose(statement); tryClose(createStatement); @@ -1045,12 +1124,15 @@ public final class SQLDatabaseManager implements DatabaseManager { private void updateStructure(String tableName, String columnName, String columnSize) { try (Connection connection = getConnection(PoolIdentifier.MISC)) { - if (!columnExists(connection, mcMMO.p.getGeneralConfig().getMySQLDatabaseName(), tablePrefix+tableName, columnName)) { + if (!columnExists(connection, mcMMO.p.getGeneralConfig().getMySQLDatabaseName(), + tablePrefix + tableName, columnName)) { try (Statement createStatement = connection.createStatement()) { // logger.info("[SQLDB Check] Adding column '" + columnName + "' to table '" + tablePrefix + tableName + "'..."); - String startingLevel = "'" + mcMMO.p.getAdvancedConfig().getStartingLevel() + "'"; + String startingLevel = + "'" + mcMMO.p.getAdvancedConfig().getStartingLevel() + "'"; createStatement.executeUpdate("ALTER TABLE `" + tablePrefix + tableName + "` " - + "ADD COLUMN `" + columnName + "` int(" + columnSize + ") unsigned NOT NULL DEFAULT " + startingLevel); + + "ADD COLUMN `" + columnName + "` int(" + columnSize + + ") unsigned NOT NULL DEFAULT " + startingLevel); } } else { // logger.info("[SQLDB Check] Column '" + columnName + "' already exists in table '" + tablePrefix + tableName + "', looks good!"); @@ -1061,7 +1143,8 @@ public final class SQLDatabaseManager implements DatabaseManager { } } - private boolean columnExists(Connection connection, String database, String tableName, String columnName) throws SQLException { + private boolean columnExists(Connection connection, String database, String tableName, + String columnName) throws SQLException { // logger.info("[SQLDB Check] Checking if column '" + columnName + "' exists in table '" + tableName + "'"); try (Statement createStatement = connection.createStatement()) { String sql = "SELECT `COLUMN_NAME`\n" + @@ -1072,14 +1155,16 @@ public final class SQLDatabaseManager implements DatabaseManager { var resultSet = createStatement.executeQuery(sql); return resultSet.next(); } catch (SQLException e) { - logger.info("Failed to check if column exists in table " + tableName + " for column " + columnName); + logger.info("Failed to check if column exists in table " + tableName + " for column " + + columnName); e.printStackTrace(); throw e; } } - private void setStatementQuery(PreparedStatement statement, String tableName) throws SQLException { + private void setStatementQuery(PreparedStatement statement, String tableName) + throws SQLException { if (!this.h2) { // Set schema name for MySQL statement.setString(1, mcMMO.p.getGeneralConfig().getMySQLDatabaseName()); @@ -1097,7 +1182,9 @@ public final class SQLDatabaseManager implements DatabaseManager { case SAVE -> savePool.getConnection(); }; if (connection == null) { - throw new RuntimeException("getConnection() for " + identifier.name().toLowerCase(Locale.ENGLISH) + " pool timed out. Increase max connections settings."); + throw new RuntimeException( + "getConnection() for " + identifier.name().toLowerCase(Locale.ENGLISH) + + " pool timed out. Increase max connections settings."); } return connection; } @@ -1175,11 +1262,9 @@ public final class SQLDatabaseManager implements DatabaseManager { break; } - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(statement); } } @@ -1188,41 +1273,47 @@ public final class SQLDatabaseManager implements DatabaseManager { PreparedStatement statement = null; try { - statement = connection.prepareStatement("INSERT IGNORE INTO " + tablePrefix + "experience (user_id) VALUES (?)"); + statement = connection.prepareStatement( + "INSERT IGNORE INTO " + tablePrefix + "experience (user_id) VALUES (?)"); statement.setInt(1, id); statement.execute(); statement.close(); - statement = connection.prepareStatement("INSERT IGNORE INTO " + tablePrefix + "skills (user_id) VALUES (?)"); + statement = connection.prepareStatement( + "INSERT IGNORE INTO " + tablePrefix + "skills (user_id) VALUES (?)"); statement.setInt(1, id); statement.execute(); statement.close(); - statement = connection.prepareStatement("INSERT IGNORE INTO " + tablePrefix + "cooldowns (user_id) VALUES (?)"); + statement = connection.prepareStatement( + "INSERT IGNORE INTO " + tablePrefix + "cooldowns (user_id) VALUES (?)"); statement.setInt(1, id); statement.execute(); statement.close(); - statement = connection.prepareStatement("INSERT IGNORE INTO " + tablePrefix + "huds (user_id, mobhealthbar, scoreboardtips) VALUES (?, ?, ?)"); + statement = connection.prepareStatement("INSERT IGNORE INTO " + tablePrefix + + "huds (user_id, mobhealthbar, scoreboardtips) VALUES (?, ?, ?)"); statement.setInt(1, id); statement.setString(2, mcMMO.p.getGeneralConfig().getMobHealthbarDefault().name()); statement.setInt(3, 0); statement.execute(); statement.close(); - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(statement); } } private PlayerProfile loadFromResult(String playerName, ResultSet result) throws SQLException { - final Map skills = new EnumMap<>(PrimarySkillType.class); // Skill & Level - final Map skillsXp = new EnumMap<>(PrimarySkillType.class); // Skill & XP - final Map skillsDATS = new EnumMap<>(SuperAbilityType.class); // Ability & Cooldown - final Map uniqueData = new EnumMap<>(UniqueDataType.class); //Chimaera wing cooldown and other misc info + final Map skills = new EnumMap<>( + PrimarySkillType.class); // Skill & Level + final Map skillsXp = new EnumMap<>( + PrimarySkillType.class); // Skill & XP + final Map skillsDATS = new EnumMap<>( + SuperAbilityType.class); // Ability & Cooldown + final Map uniqueData = new EnumMap<>( + UniqueDataType.class); //Chimaera wing cooldown and other misc info UUID uuid; int scoreboardTipsShown; @@ -1305,7 +1396,8 @@ public final class SQLDatabaseManager implements DatabaseManager { uuid = null; } - return new PlayerProfile(playerName, uuid, skills, skillsXp, skillsDATS, scoreboardTipsShown, uniqueData, null); + return new PlayerProfile(playerName, uuid, skills, skillsXp, skillsDATS, + scoreboardTipsShown, uniqueData, null); } private void printErrors(SQLException ex) { @@ -1340,7 +1432,7 @@ public final class SQLDatabaseManager implements DatabaseManager { } resultSet.close(); logger.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)"); mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.DROP_NAME_UNIQUENESS); @@ -1355,33 +1447,36 @@ public final class SQLDatabaseManager implements DatabaseManager { try { statement.executeQuery("SELECT `alchemy` FROM `" + tablePrefix + "skills` LIMIT 1"); mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.ADD_ALCHEMY); - } - catch (SQLException ex) { + } catch (SQLException ex) { logger.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'"); + 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'"); } } private void checkUpgradeAddBlastMiningCooldown(final Statement statement) throws SQLException { try { - statement.executeQuery("SELECT `blast_mining` FROM `" + tablePrefix + "cooldowns` LIMIT 1"); + statement.executeQuery( + "SELECT `blast_mining` FROM `" + tablePrefix + "cooldowns` LIMIT 1"); mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.ADD_BLAST_MINING_COOLDOWN); - } - catch (SQLException ex) { + } catch (SQLException ex) { logger.info("Updating mcMMO MySQL tables for Blast Mining..."); - statement.executeUpdate("ALTER TABLE `" + tablePrefix + "cooldowns` ADD `blast_mining` int(32) NOT NULL DEFAULT '0'"); + statement.executeUpdate("ALTER TABLE `" + tablePrefix + + "cooldowns` ADD `blast_mining` int(32) NOT NULL DEFAULT '0'"); } } private void checkUpgradeAddUniqueChimaeraWing(final Statement statement) throws SQLException { try { - statement.executeQuery("SELECT `chimaera_wing` FROM `" + tablePrefix + "cooldowns` LIMIT 1"); + statement.executeQuery( + "SELECT `chimaera_wing` FROM `" + tablePrefix + "cooldowns` LIMIT 1"); mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.ADD_UNIQUE_PLAYER_DATA); - } - catch (SQLException ex) { + } catch (SQLException ex) { logger.info("Updating mcMMO MySQL tables for Chimaera Wing..."); - statement.executeUpdate("ALTER TABLE `" + tablePrefix + "cooldowns` ADD `chimaera_wing` int(32) NOT NULL DEFAULT '0'"); + statement.executeUpdate("ALTER TABLE `" + tablePrefix + + "cooldowns` ADD `chimaera_wing` int(32) NOT NULL DEFAULT '0'"); } } @@ -1389,11 +1484,12 @@ public final class SQLDatabaseManager implements DatabaseManager { try { statement.executeQuery("SELECT `fishing` FROM `" + tablePrefix + "skills` LIMIT 1"); mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.ADD_FISHING); - } - catch (SQLException ex) { + } catch (SQLException ex) { logger.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'"); + 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'"); } } @@ -1401,21 +1497,23 @@ public final class SQLDatabaseManager implements DatabaseManager { try { statement.executeQuery("SELECT `mobhealthbar` FROM `" + tablePrefix + "huds` LIMIT 1"); mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.ADD_MOB_HEALTHBARS); - } - catch (SQLException ex) { + } catch (SQLException ex) { logger.info("Updating mcMMO MySQL tables for mob healthbars..."); - statement.executeUpdate("ALTER TABLE `" + tablePrefix + "huds` ADD `mobhealthbar` varchar(50) NOT NULL DEFAULT '" + mcMMO.p.getGeneralConfig().getMobHealthbarDefault() + "'"); + statement.executeUpdate("ALTER TABLE `" + tablePrefix + + "huds` ADD `mobhealthbar` varchar(50) NOT NULL DEFAULT '" + + mcMMO.p.getGeneralConfig().getMobHealthbarDefault() + "'"); } } private void checkUpgradeAddScoreboardTips(final Statement statement) throws SQLException { try { - statement.executeQuery("SELECT `scoreboardtips` FROM `" + tablePrefix + "huds` LIMIT 1"); + statement.executeQuery( + "SELECT `scoreboardtips` FROM `" + tablePrefix + "huds` LIMIT 1"); mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.ADD_SCOREBOARD_TIPS); - } - catch (SQLException ex) { + } catch (SQLException ex) { logger.info("Updating mcMMO MySQL tables for scoreboard tips..."); - statement.executeUpdate("ALTER TABLE `" + tablePrefix + "huds` ADD `scoreboardtips` int(10) NOT NULL DEFAULT '0' ;"); + statement.executeUpdate("ALTER TABLE `" + tablePrefix + + "huds` ADD `scoreboardtips` int(10) NOT NULL DEFAULT '0' ;"); } } @@ -1423,7 +1521,8 @@ public final class SQLDatabaseManager implements DatabaseManager { ResultSet resultSet = null; try { - resultSet = statement.executeQuery("SHOW INDEX FROM `" + tablePrefix + "skills` WHERE `Key_name` LIKE 'idx\\_%'"); + resultSet = statement.executeQuery( + "SHOW INDEX FROM `" + tablePrefix + "skills` WHERE `Key_name` LIKE 'idx\\_%'"); resultSet.last(); if (resultSet.getRow() != SkillTools.NON_CHILD_SKILLS.size()) { @@ -1433,20 +1532,19 @@ public final class SQLDatabaseManager implements DatabaseManager { String skill_name = skill.name().toLowerCase(Locale.ENGLISH); try { - statement.executeUpdate("ALTER TABLE `" + tablePrefix + "skills` ADD INDEX `idx_" + skill_name + "` (`" + skill_name + "`) USING BTREE"); - } - catch (SQLException ex) { + statement.executeUpdate( + "ALTER TABLE `" + tablePrefix + "skills` ADD INDEX `idx_" + + skill_name + "` (`" + skill_name + "`) USING BTREE"); + } catch (SQLException ex) { // Ignore } } } mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.ADD_SQL_INDEXES); - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(resultSet); } } @@ -1469,18 +1567,19 @@ public final class SQLDatabaseManager implements DatabaseManager { if (!column_exists) { logger.info("Adding UUIDs to mcMMO MySQL user table..."); - 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"); + 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"); - mcMMO.p.getFoliaLib().getScheduler().runLaterAsync(new GetUUIDUpdatesRequired(), 100); // wait until after first purge + mcMMO.p.getFoliaLib().getScheduler().runLaterAsync(new GetUUIDUpdatesRequired(), + 100); // wait until after first purge } mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.ADD_UUIDS); - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(resultSet); } } @@ -1496,7 +1595,8 @@ public final class SQLDatabaseManager implements DatabaseManager { try { connection = miscPool.getConnection(); statement = connection.createStatement(); - resultSet = statement.executeQuery("SELECT `user` FROM `" + tablePrefix + "users` WHERE `uuid` IS NULL"); + resultSet = statement.executeQuery( + "SELECT `user` FROM `" + tablePrefix + "users` WHERE `uuid` IS NULL"); while (resultSet.next()) { names.add(resultSet.getString("user")); @@ -1538,15 +1638,14 @@ public final class SQLDatabaseManager implements DatabaseManager { if (column_exists) { logger.info("Removing party name from users table..."); - statement.executeUpdate("ALTER TABLE `" + tablePrefix + "users` DROP COLUMN `party`"); + statement.executeUpdate( + "ALTER TABLE `" + tablePrefix + "users` DROP COLUMN `party`"); } mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.DROP_SQL_PARTY_NAMES); - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(resultSet); } } @@ -1572,18 +1671,19 @@ public final class SQLDatabaseManager implements DatabaseManager { if (!column_exists) { logger.info("Adding skill total column to skills table..."); - statement.executeUpdate("ALTER TABLE `" + tablePrefix + "skills` ADD COLUMN `total` int NOT NULL DEFAULT '0'"); - statement.executeUpdate("UPDATE `" + tablePrefix + "skills` SET `total` = (taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing+alchemy)"); - statement.executeUpdate("ALTER TABLE `" + tablePrefix + "skills` ADD INDEX `idx_total` (`total`) USING BTREE"); + statement.executeUpdate("ALTER TABLE `" + tablePrefix + + "skills` ADD COLUMN `total` int NOT NULL DEFAULT '0'"); + statement.executeUpdate("UPDATE `" + tablePrefix + + "skills` SET `total` = (taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing+alchemy)"); + statement.executeUpdate("ALTER TABLE `" + tablePrefix + + "skills` ADD INDEX `idx_total` (`total`) USING BTREE"); connection.commit(); } mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.ADD_SKILL_TOTAL); - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { connection.setAutoCommit(true); tryClose(resultSet); tryClose(statement); @@ -1608,31 +1708,33 @@ public final class SQLDatabaseManager implements DatabaseManager { if (column_exists) { logger.info("Removing Spout HUD type from huds table..."); - statement.executeUpdate("ALTER TABLE `" + tablePrefix + "huds` DROP COLUMN `hudtype`"); + statement.executeUpdate( + "ALTER TABLE `" + tablePrefix + "huds` DROP COLUMN `hudtype`"); } mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.DROP_SPOUT); - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(resultSet); } } private int getUserID(final Connection connection, final String playerName, final UUID uuid) { - if (uuid == null) + if (uuid == null) { return getUserIDByName(connection, playerName); + } - if (cachedUserIDs.containsKey(uuid)) + if (cachedUserIDs.containsKey(uuid)) { return cachedUserIDs.get(uuid); + } ResultSet resultSet = null; PreparedStatement statement = null; try { - statement = connection.prepareStatement("SELECT id, `user` FROM " + tablePrefix + "users WHERE uuid = ? OR (uuid IS NULL AND `user` = ?)"); + statement = connection.prepareStatement("SELECT id, `user` FROM " + tablePrefix + + "users WHERE uuid = ? OR (uuid IS NULL AND `user` = ?)"); statement.setString(1, uuid.toString()); statement.setString(2, playerName); resultSet = statement.executeQuery(); @@ -1644,11 +1746,9 @@ public final class SQLDatabaseManager implements DatabaseManager { return id; } - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(resultSet); tryClose(statement); } @@ -1661,7 +1761,8 @@ public final class SQLDatabaseManager implements DatabaseManager { PreparedStatement statement = null; try { - statement = connection.prepareStatement("SELECT id, `user` FROM " + tablePrefix + "users WHERE `user` = ?"); + statement = connection.prepareStatement( + "SELECT id, `user` FROM " + tablePrefix + "users WHERE `user` = ?"); statement.setString(1, playerName); resultSet = statement.executeQuery(); @@ -1669,24 +1770,21 @@ public final class SQLDatabaseManager implements DatabaseManager { return resultSet.getInt("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 } } @@ -1712,14 +1810,13 @@ public final class SQLDatabaseManager implements DatabaseManager { try { connection = getConnection(PoolIdentifier.MISC); - statement = connection.prepareStatement("UPDATE " + tablePrefix + "huds SET mobhealthbar = ?"); + statement = connection.prepareStatement( + "UPDATE " + tablePrefix + "huds SET mobhealthbar = ?"); statement.setString(1, mcMMO.p.getGeneralConfig().getMobHealthbarDefault().toString()); statement.executeUpdate(); - } - catch (SQLException ex) { + } catch (SQLException ex) { printErrors(ex); - } - finally { + } finally { tryClose(statement); tryClose(connection); } @@ -1740,18 +1837,18 @@ public final class SQLDatabaseManager implements DatabaseManager { //Update "user" column try { - logger.info("Updating user column to new encoding"); - statement.executeUpdate(getUpdateUserInUsersTableSQLQuery()); + logger.info("Updating user column to new encoding"); + statement.executeUpdate(getUpdateUserInUsersTableSQLQuery()); - //Update "uuid" column - logger.info("Updating user column to new encoding"); - statement.executeUpdate(getUpdateUUIDInUsersTableSQLQuery()); + //Update "uuid" column + logger.info("Updating user column to new encoding"); + statement.executeUpdate(getUpdateUUIDInUsersTableSQLQuery()); - //Update "mobhealthbar" column - logger.info("Updating mobhealthbar column to new encoding"); - statement.executeUpdate(getUpdateMobHealthBarInHudsTableSQLQuery()); + //Update "mobhealthbar" column + logger.info("Updating mobhealthbar column to new encoding"); + statement.executeUpdate(getUpdateMobHealthBarInHudsTableSQLQuery()); - mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.SQL_CHARSET_UTF8MB4); + mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.SQL_CHARSET_UTF8MB4); } catch (SQLException e) { e.printStackTrace(); diff --git a/src/main/java/com/gmail/nossr50/database/UserQueryFull.java b/src/main/java/com/gmail/nossr50/database/UserQueryFull.java index 47a3e965a..d104d3cc0 100644 --- a/src/main/java/com/gmail/nossr50/database/UserQueryFull.java +++ b/src/main/java/com/gmail/nossr50/database/UserQueryFull.java @@ -1,8 +1,7 @@ package com.gmail.nossr50.database; -import org.jetbrains.annotations.NotNull; - import java.util.UUID; +import org.jetbrains.annotations.NotNull; public class UserQueryFull implements UserQueryUUID, UserQueryName { diff --git a/src/main/java/com/gmail/nossr50/database/UserQueryUUID.java b/src/main/java/com/gmail/nossr50/database/UserQueryUUID.java index 192997f90..785c34875 100644 --- a/src/main/java/com/gmail/nossr50/database/UserQueryUUID.java +++ b/src/main/java/com/gmail/nossr50/database/UserQueryUUID.java @@ -1,8 +1,7 @@ package com.gmail.nossr50.database; -import org.jetbrains.annotations.NotNull; - import java.util.UUID; +import org.jetbrains.annotations.NotNull; public interface UserQueryUUID extends UserQuery { diff --git a/src/main/java/com/gmail/nossr50/database/UserQueryUUIDImpl.java b/src/main/java/com/gmail/nossr50/database/UserQueryUUIDImpl.java index 49ad038f5..70a207d8a 100644 --- a/src/main/java/com/gmail/nossr50/database/UserQueryUUIDImpl.java +++ b/src/main/java/com/gmail/nossr50/database/UserQueryUUIDImpl.java @@ -1,8 +1,7 @@ package com.gmail.nossr50.database; -import org.jetbrains.annotations.NotNull; - import java.util.UUID; +import org.jetbrains.annotations.NotNull; public class UserQueryUUIDImpl implements UserQueryUUID { private final @NotNull UUID uuid; diff --git a/src/main/java/com/gmail/nossr50/database/flatfile/BadCategorizedFlatFileData.java b/src/main/java/com/gmail/nossr50/database/flatfile/BadCategorizedFlatFileData.java index fbeaf9c2d..dbc8301e8 100644 --- a/src/main/java/com/gmail/nossr50/database/flatfile/BadCategorizedFlatFileData.java +++ b/src/main/java/com/gmail/nossr50/database/flatfile/BadCategorizedFlatFileData.java @@ -2,15 +2,16 @@ package com.gmail.nossr50.database.flatfile; import com.gmail.nossr50.database.FlatFileDataFlag; import com.google.common.base.Objects; -import org.jetbrains.annotations.NotNull; - import java.util.Arrays; import java.util.HashSet; +import org.jetbrains.annotations.NotNull; public class BadCategorizedFlatFileData extends CategorizedFlatFileData { private final boolean[] badDataIndexes; - protected BadCategorizedFlatFileData(int uniqueProcessingId, @NotNull HashSet dataFlags, @NotNull String[] splitData, boolean[] badDataIndexes) { + protected BadCategorizedFlatFileData(int uniqueProcessingId, + @NotNull HashSet dataFlags, @NotNull String[] splitData, + boolean[] badDataIndexes) { super(uniqueProcessingId, dataFlags, splitData); this.badDataIndexes = badDataIndexes; } @@ -21,9 +22,15 @@ public class BadCategorizedFlatFileData extends CategorizedFlatFileData { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - if (!super.equals(o)) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + if (!super.equals(o)) { + return false; + } BadCategorizedFlatFileData that = (BadCategorizedFlatFileData) o; return Objects.equal(badDataIndexes, that.badDataIndexes); } diff --git a/src/main/java/com/gmail/nossr50/database/flatfile/CategorizedFlatFileData.java b/src/main/java/com/gmail/nossr50/database/flatfile/CategorizedFlatFileData.java index 500be9c4f..ceabbb4f1 100644 --- a/src/main/java/com/gmail/nossr50/database/flatfile/CategorizedFlatFileData.java +++ b/src/main/java/com/gmail/nossr50/database/flatfile/CategorizedFlatFileData.java @@ -2,17 +2,17 @@ package com.gmail.nossr50.database.flatfile; import com.gmail.nossr50.database.FlatFileDataFlag; import com.google.common.base.Objects; -import org.jetbrains.annotations.NotNull; - import java.util.HashSet; import java.util.Set; +import org.jetbrains.annotations.NotNull; public class CategorizedFlatFileData implements FlatFileDataContainer { private final @NotNull Set dataFlags; private final @NotNull String[] splitData; private final int uniqueProcessingId; - public CategorizedFlatFileData(int uniqueProcessingId, @NotNull HashSet dataFlags, @NotNull String[] splitData) { + public CategorizedFlatFileData(int uniqueProcessingId, + @NotNull HashSet dataFlags, @NotNull String[] splitData) { this.uniqueProcessingId = uniqueProcessingId; this.dataFlags = dataFlags; this.splitData = splitData; @@ -36,10 +36,15 @@ public class CategorizedFlatFileData implements FlatFileDataContainer { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } CategorizedFlatFileData that = (CategorizedFlatFileData) o; - return uniqueProcessingId == that.uniqueProcessingId && Objects.equal(dataFlags, that.dataFlags) && Objects.equal(splitData, that.splitData); + return uniqueProcessingId == that.uniqueProcessingId && Objects.equal(dataFlags, + that.dataFlags) && Objects.equal(splitData, that.splitData); } @Override diff --git a/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataBuilder.java b/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataBuilder.java index eb6e3dd2a..12fa7c834 100644 --- a/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataBuilder.java +++ b/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataBuilder.java @@ -1,9 +1,8 @@ package com.gmail.nossr50.database.flatfile; import com.gmail.nossr50.database.FlatFileDataFlag; -import org.jetbrains.annotations.NotNull; - import java.util.HashSet; +import org.jetbrains.annotations.NotNull; public class FlatFileDataBuilder { private final @NotNull HashSet dataFlags; @@ -29,7 +28,8 @@ public class FlatFileDataBuilder { public @NotNull FlatFileDataContainer build() { if (dataFlags.contains(FlatFileDataFlag.BAD_VALUES)) { - return new BadCategorizedFlatFileData(uniqueProcessingId, dataFlags, splitStringData, badDataValues); + return new BadCategorizedFlatFileData(uniqueProcessingId, dataFlags, splitStringData, + badDataValues); } return new CategorizedFlatFileData(uniqueProcessingId, dataFlags, splitStringData); diff --git a/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataContainer.java b/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataContainer.java index e2fb2336c..461dbbf94 100644 --- a/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataContainer.java +++ b/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataContainer.java @@ -1,11 +1,10 @@ package com.gmail.nossr50.database.flatfile; import com.gmail.nossr50.database.FlatFileDataFlag; +import java.util.Set; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Set; - public interface FlatFileDataContainer { default @Nullable Set getDataFlags() { return null; diff --git a/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataUtil.java b/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataUtil.java index a3c78685f..d6d1750c1 100644 --- a/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataUtil.java +++ b/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataUtil.java @@ -1,15 +1,67 @@ package com.gmail.nossr50.database.flatfile; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_ARCHERY; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_BERSERK; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_BLAST_MINING; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_CHIMAERA_WING; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_GIGA_DRILL_BREAKER; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_GREEN_TERRA; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_MACES; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_SERRATED_STRIKES; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_SKULL_SPLITTER; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_SUPER_BREAKER; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_SUPER_SHOTGUN; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_TREE_FELLER; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.COOLDOWN_TRIDENTS; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_ACROBATICS; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_ALCHEMY; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_ARCHERY; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_AXES; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_CROSSBOWS; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_EXCAVATION; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_FISHING; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_HERBALISM; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_MACES; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_MINING; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_REPAIR; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_SWORDS; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_TAMING; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_TRIDENTS; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_UNARMED; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.EXP_WOODCUTTING; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.HEALTHBAR; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.LEGACY_INVALID_OLD_USERNAME; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.LEGACY_LAST_LOGIN; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.OVERHAUL_LAST_LOGIN; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SCOREBOARD_TIPS; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_ACROBATICS; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_ALCHEMY; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_ARCHERY; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_AXES; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_CROSSBOWS; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_EXCAVATION; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_FISHING; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_HERBALISM; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_MACES; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_MINING; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_REPAIR; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_SWORDS; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_TAMING; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_TRIDENTS; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_UNARMED; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.SKILLS_WOODCUTTING; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.USERNAME_INDEX; +import static com.gmail.nossr50.database.FlatFileDatabaseManager.UUID_INDEX; + import com.gmail.nossr50.database.FlatFileDataFlag; import com.gmail.nossr50.database.FlatFileDatabaseManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import static com.gmail.nossr50.database.FlatFileDatabaseManager.*; - public class FlatFileDataUtil { - public static @Nullable String[] getPreparedSaveDataLine(@NotNull FlatFileDataContainer dataContainer) { + public static @Nullable String[] getPreparedSaveDataLine( + @NotNull FlatFileDataContainer dataContainer) { if (dataContainer.getDataFlags() == null) { return dataContainer.getSplitData(); } @@ -18,8 +70,10 @@ public class FlatFileDataUtil { //TODO: Test that we ignore the things we are supposed to ignore //TODO: Should we even keep track of the bad data or just not even build data containers for it? Making containers for it is only really useful for debugging.. well I suppose operations are typically async so it shouldn't matter if (dataContainer.getDataFlags().contains(FlatFileDataFlag.CORRUPTED_OR_UNRECOGNIZABLE) - || dataContainer.getDataFlags().contains(FlatFileDataFlag.DUPLICATE_UUID) //For now we will not try to fix any issues with UUIDs - || dataContainer.getDataFlags().contains(FlatFileDataFlag.BAD_UUID_DATA) //For now we will not try to fix any issues with UUIDs + || dataContainer.getDataFlags().contains(FlatFileDataFlag.DUPLICATE_UUID) + //For now we will not try to fix any issues with UUIDs + || dataContainer.getDataFlags().contains(FlatFileDataFlag.BAD_UUID_DATA) + //For now we will not try to fix any issues with UUIDs || dataContainer.getDataFlags().contains(FlatFileDataFlag.TOO_INCOMPLETE)) { return null; } @@ -40,8 +94,9 @@ public class FlatFileDataUtil { return splitData; } - public static @NotNull String[] repairBadData(@NotNull String[] splitData, boolean[] badDataValues) { - for(int i = 0; i < FlatFileDatabaseManager.DATA_ENTRY_COUNT; i++) { + public static @NotNull String[] repairBadData(@NotNull String[] splitData, + boolean[] badDataValues) { + for (int i = 0; i < FlatFileDatabaseManager.DATA_ENTRY_COUNT; i++) { if (badDataValues[i]) { //This data value was marked as bad so we zero initialize it splitData[i] = getZeroInitialisedData(i, 0); @@ -55,7 +110,8 @@ public class FlatFileDataUtil { * @param index "zero" Initialization will depend on what the index is for * @return the "zero" initialized data corresponding to the index */ - public static @NotNull String getZeroInitialisedData(int index, int startingLevel) throws IndexOutOfBoundsException { + public static @NotNull String getZeroInitialisedData(int index, int startingLevel) + throws IndexOutOfBoundsException { //TODO: Add UUID recovery? Might not even be worth it. return switch (index) { case USERNAME_INDEX -> @@ -65,15 +121,23 @@ public class FlatFileDataUtil { //Assumption: Used to be used for something, no longer used //Assumption: Used to be used for something, no longer used case 2, 3, 23, 33, LEGACY_LAST_LOGIN, HEALTHBAR -> "IGNORED"; - case SKILLS_MINING, SKILLS_REPAIR, SKILLS_UNARMED, SKILLS_HERBALISM, SKILLS_EXCAVATION, SKILLS_ARCHERY, - SKILLS_SWORDS, SKILLS_AXES, SKILLS_WOODCUTTING, SKILLS_ACROBATICS, SKILLS_TAMING, SKILLS_FISHING, - SKILLS_ALCHEMY, SKILLS_CROSSBOWS, SKILLS_TRIDENTS, SKILLS_MACES -> String.valueOf(startingLevel); + case SKILLS_MINING, SKILLS_REPAIR, SKILLS_UNARMED, SKILLS_HERBALISM, SKILLS_EXCAVATION, + SKILLS_ARCHERY, + SKILLS_SWORDS, SKILLS_AXES, SKILLS_WOODCUTTING, SKILLS_ACROBATICS, SKILLS_TAMING, + SKILLS_FISHING, + SKILLS_ALCHEMY, SKILLS_CROSSBOWS, SKILLS_TRIDENTS, SKILLS_MACES -> + String.valueOf(startingLevel); case OVERHAUL_LAST_LOGIN -> String.valueOf(-1L); - case COOLDOWN_BERSERK, COOLDOWN_GIGA_DRILL_BREAKER, COOLDOWN_TREE_FELLER, COOLDOWN_GREEN_TERRA, - COOLDOWN_SERRATED_STRIKES, COOLDOWN_SKULL_SPLITTER, COOLDOWN_SUPER_BREAKER, COOLDOWN_BLAST_MINING, - COOLDOWN_SUPER_SHOTGUN, COOLDOWN_TRIDENTS, COOLDOWN_ARCHERY, COOLDOWN_MACES, SCOREBOARD_TIPS, COOLDOWN_CHIMAERA_WING, - EXP_MINING, EXP_WOODCUTTING, EXP_REPAIR, EXP_UNARMED, EXP_HERBALISM, EXP_EXCAVATION, EXP_ARCHERY, - EXP_SWORDS, EXP_AXES, EXP_ACROBATICS, EXP_TAMING, EXP_FISHING, EXP_ALCHEMY, EXP_CROSSBOWS, + case COOLDOWN_BERSERK, COOLDOWN_GIGA_DRILL_BREAKER, COOLDOWN_TREE_FELLER, + COOLDOWN_GREEN_TERRA, + COOLDOWN_SERRATED_STRIKES, COOLDOWN_SKULL_SPLITTER, COOLDOWN_SUPER_BREAKER, + COOLDOWN_BLAST_MINING, + COOLDOWN_SUPER_SHOTGUN, COOLDOWN_TRIDENTS, COOLDOWN_ARCHERY, COOLDOWN_MACES, + SCOREBOARD_TIPS, COOLDOWN_CHIMAERA_WING, + EXP_MINING, EXP_WOODCUTTING, EXP_REPAIR, EXP_UNARMED, EXP_HERBALISM, + EXP_EXCAVATION, EXP_ARCHERY, + EXP_SWORDS, EXP_AXES, EXP_ACROBATICS, EXP_TAMING, EXP_FISHING, EXP_ALCHEMY, + EXP_CROSSBOWS, EXP_TRIDENTS, EXP_MACES -> "0"; case UUID_INDEX -> throw new IndexOutOfBoundsException(); //TODO: Add UUID recovery? Might not even be worth it. diff --git a/src/main/java/com/gmail/nossr50/datatypes/BlockLocationHistory.java b/src/main/java/com/gmail/nossr50/datatypes/BlockLocationHistory.java index 6674cd020..3ccf154fb 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/BlockLocationHistory.java +++ b/src/main/java/com/gmail/nossr50/datatypes/BlockLocationHistory.java @@ -1,12 +1,12 @@ package com.gmail.nossr50.datatypes; import com.google.common.collect.HashMultiset; +import java.util.LinkedList; import org.bukkit.Location; -import java.util.LinkedList; - /** - * This class works with the assumption that you only pass in Block Locations. If locations have differing pitch/yaw, the logic breaks + * This class works with the assumption that you only pass in Block Locations. If locations have + * differing pitch/yaw, the logic breaks */ public class BlockLocationHistory { private final LinkedList limitedSizeOrderedList = new LinkedList<>(); @@ -18,15 +18,17 @@ public class BlockLocationHistory { } /** - * Adds a block location to the history. If the history memory would exceed the max size, it will remove the least recently added block location + * Adds a block location to the history. If the history memory would exceed the max size, it + * will remove the least recently added block location * * @param newItem */ public void add(Location newItem) { limitedSizeOrderedList.addFirst(newItem); lookup.add(newItem); - if (limitedSizeOrderedList.size() > maxSize) + if (limitedSizeOrderedList.size() > maxSize) { lookup.remove(limitedSizeOrderedList.removeLast()); + } } /** diff --git a/src/main/java/com/gmail/nossr50/datatypes/BlockSnapshot.java b/src/main/java/com/gmail/nossr50/datatypes/BlockSnapshot.java index ca60cc4a8..28173a6a5 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/BlockSnapshot.java +++ b/src/main/java/com/gmail/nossr50/datatypes/BlockSnapshot.java @@ -4,8 +4,8 @@ import org.bukkit.Material; import org.bukkit.block.Block; /** - * Contains a snapshot of a block at a specific moment in time - * Used to check before/after type stuff + * Contains a snapshot of a block at a specific moment in time Used to check before/after type + * stuff */ public class BlockSnapshot { private final Material oldType; diff --git a/src/main/java/com/gmail/nossr50/datatypes/LevelUpBroadcastPredicate.java b/src/main/java/com/gmail/nossr50/datatypes/LevelUpBroadcastPredicate.java index 32109deac..f9aa65277 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/LevelUpBroadcastPredicate.java +++ b/src/main/java/com/gmail/nossr50/datatypes/LevelUpBroadcastPredicate.java @@ -5,12 +5,11 @@ import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.player.UserManager; +import java.util.function.Predicate; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.function.Predicate; - //TODO: Allow for offline players to broadcast public class LevelUpBroadcastPredicate implements Predicate { @@ -33,7 +32,8 @@ public class LevelUpBroadcastPredicate implements Predi if (mmoBroadcastingPlayer == null) { //This should never be null, but just in case... - mcMMO.p.getLogger().severe("McMMOPlayer was null for broadcaster in LevelUpBroadcastPredicate when it should never be null!"); + mcMMO.p.getLogger() + .severe("McMMOPlayer was null for broadcaster in LevelUpBroadcastPredicate when it should never be null!"); return false; } @@ -61,24 +61,25 @@ public class LevelUpBroadcastPredicate implements Predi //Same world check if (isLevelUpBroadcastsSameWorldOnly()) { - if (!mmoBroadcastingPlayer.getPlayer().getWorld().equals(listeningPlayer.getWorld())) { + if (!mmoBroadcastingPlayer.getPlayer().getWorld() + .equals(listeningPlayer.getWorld())) { return false; //Not in the same world when its required } //Distance checks if (mcMMO.p.getGeneralConfig().shouldLevelUpBroadcastsRestrictDistance()) { - if (!Misc.isNear(mmoBroadcastingPlayer.getPlayer().getLocation(), listeningPlayer.getLocation(), mcMMO.p.getGeneralConfig().getLevelUpBroadcastRadius())) { + if (!Misc.isNear(mmoBroadcastingPlayer.getPlayer().getLocation(), + listeningPlayer.getLocation(), + mcMMO.p.getGeneralConfig().getLevelUpBroadcastRadius())) { return false; } } } //Visibility checks - if (!listeningPlayer.canSee(mmoBroadcastingPlayer.getPlayer()) && listeningPlayer != mmoBroadcastingPlayer.getPlayer()) { - return false; //Player who leveled should be invisible to this player so don't send the message - } - - return true; + return listeningPlayer.canSee(mmoBroadcastingPlayer.getPlayer()) + || listeningPlayer + == mmoBroadcastingPlayer.getPlayer(); //Player who leveled should be invisible to this player so don't send the message } else { //Send out to console return mcMMO.p.getGeneralConfig().shouldLevelUpBroadcastToConsole(); diff --git a/src/main/java/com/gmail/nossr50/datatypes/PowerLevelUpBroadcastPredicate.java b/src/main/java/com/gmail/nossr50/datatypes/PowerLevelUpBroadcastPredicate.java index 1e6b278a8..cd472d869 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/PowerLevelUpBroadcastPredicate.java +++ b/src/main/java/com/gmail/nossr50/datatypes/PowerLevelUpBroadcastPredicate.java @@ -5,12 +5,11 @@ import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.player.UserManager; +import java.util.function.Predicate; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.function.Predicate; - //TODO: Allow for offline players to broadcast public class PowerLevelUpBroadcastPredicate implements Predicate { @@ -33,7 +32,8 @@ public class PowerLevelUpBroadcastPredicate implements if (mmoBroadcastingPlayer == null) { //This should never be null, but just in case... - mcMMO.p.getLogger().severe("McMMOPlayer was null for broadcaster in LevelUpBroadcastPredicate when it should never be null!"); + mcMMO.p.getLogger() + .severe("McMMOPlayer was null for broadcaster in LevelUpBroadcastPredicate when it should never be null!"); return false; } @@ -61,24 +61,25 @@ public class PowerLevelUpBroadcastPredicate implements //Same world check if (isPowerLevelUpBroadcastsSameWorldOnly()) { - if (!mmoBroadcastingPlayer.getPlayer().getWorld().equals(listeningPlayer.getWorld())) { + if (!mmoBroadcastingPlayer.getPlayer().getWorld() + .equals(listeningPlayer.getWorld())) { return false; //Not in the same world when its required } //Distance checks if (mcMMO.p.getGeneralConfig().shouldPowerLevelUpBroadcastsRestrictDistance()) { - if (!Misc.isNear(mmoBroadcastingPlayer.getPlayer().getLocation(), listeningPlayer.getLocation(), mcMMO.p.getGeneralConfig().getPowerLevelUpBroadcastRadius())) { + if (!Misc.isNear(mmoBroadcastingPlayer.getPlayer().getLocation(), + listeningPlayer.getLocation(), + mcMMO.p.getGeneralConfig().getPowerLevelUpBroadcastRadius())) { return false; } } } //Visibility checks - if (!listeningPlayer.canSee(mmoBroadcastingPlayer.getPlayer()) && listeningPlayer != mmoBroadcastingPlayer.getPlayer()) { - return false; //Player who leveled should be invisible to this player so don't send the message - } - - return true; + return listeningPlayer.canSee(mmoBroadcastingPlayer.getPlayer()) + || listeningPlayer + == mmoBroadcastingPlayer.getPlayer(); //Player who leveled should be invisible to this player so don't send the message } else { //Send out to console return mcMMO.p.getGeneralConfig().shouldPowerLevelUpBroadcastToConsole(); diff --git a/src/main/java/com/gmail/nossr50/datatypes/chat/ChatChannel.java b/src/main/java/com/gmail/nossr50/datatypes/chat/ChatChannel.java index f6edfa5f0..5d1bc29f5 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/chat/ChatChannel.java +++ b/src/main/java/com/gmail/nossr50/datatypes/chat/ChatChannel.java @@ -4,8 +4,10 @@ import com.gmail.nossr50.locale.LocaleLoader; import org.jetbrains.annotations.Nullable; public enum ChatChannel { - ADMIN(LocaleLoader.getString("Commands.AdminChat.On"), LocaleLoader.getString("Commands.AdminChat.Off")), - PARTY(LocaleLoader.getString("Commands.Party.Chat.On"), LocaleLoader.getString("Commands.Party.Chat.Off")), + ADMIN(LocaleLoader.getString("Commands.AdminChat.On"), + LocaleLoader.getString("Commands.AdminChat.Off")), + PARTY(LocaleLoader.getString("Commands.Party.Chat.On"), + LocaleLoader.getString("Commands.Party.Chat.Off")), PARTY_OFFICER(null, null), NONE(null, null); @@ -13,7 +15,7 @@ public enum ChatChannel { private final String disabledMessage; ChatChannel(@Nullable String enabledMessage, @Nullable String disabledMessage) { - this.enabledMessage = enabledMessage; + this.enabledMessage = enabledMessage; this.disabledMessage = disabledMessage; } 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 2725daafe..c166ae10a 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/experience/SkillXpGain.java +++ b/src/main/java/com/gmail/nossr50/datatypes/experience/SkillXpGain.java @@ -2,10 +2,9 @@ package com.gmail.nossr50.datatypes.experience; import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; -import org.jetbrains.annotations.NotNull; - import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; +import org.jetbrains.annotations.NotNull; public class SkillXpGain implements Delayed { private final long expiryTime; @@ -27,7 +26,8 @@ public class SkillXpGain implements Delayed { } private static long getDuration() { - return TimeUnit.MINUTES.toMillis(ExperienceConfig.getInstance().getDiminishedReturnsTimeInterval()); + return TimeUnit.MINUTES.toMillis( + ExperienceConfig.getInstance().getDiminishedReturnsTimeInterval()); } public int compareTo(SkillXpGain other) { 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 252644820..f8120730a 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/json/McMMOUrl.java +++ b/src/main/java/com/gmail/nossr50/datatypes/json/McMMOUrl.java @@ -1,15 +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://wiki.mcmmo.org/"; - public static final String urlSpigot = "https://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://wiki.mcmmo.org/"; + public static final String urlSpigot = "https://spigot.mcmmo.org"; public static final String urlTranslate = "https://translate.mcmmo.org/"; public static String getUrl(McMMOWebLinks webLinks) { - switch(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 2e7eb887b..e27aac8eb 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/json/McMMOWebLinks.java +++ b/src/main/java/com/gmail/nossr50/datatypes/json/McMMOWebLinks.java @@ -22,13 +22,13 @@ public enum McMMOWebLinks { 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/RuptureTaskMeta.java b/src/main/java/com/gmail/nossr50/datatypes/meta/RuptureTaskMeta.java index b484ce8cd..9563449af 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/meta/RuptureTaskMeta.java +++ b/src/main/java/com/gmail/nossr50/datatypes/meta/RuptureTaskMeta.java @@ -8,11 +8,12 @@ import org.jetbrains.annotations.NotNull; public class RuptureTaskMeta extends FixedMetadataValue { private final @NotNull RuptureTask ruptureTask; + /** * Initializes a FixedMetadataValue with an Object * * @param owningPlugin the {@link Plugin} that created this metadata value - * @param ruptureTask the value assigned to this metadata value + * @param ruptureTask the value assigned to this metadata value */ public RuptureTaskMeta(@NotNull Plugin owningPlugin, @NotNull RuptureTask ruptureTask) { super(owningPlugin, ruptureTask); diff --git a/src/main/java/com/gmail/nossr50/datatypes/meta/UUIDMeta.java b/src/main/java/com/gmail/nossr50/datatypes/meta/UUIDMeta.java index 3ba795def..4174a8d68 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/meta/UUIDMeta.java +++ b/src/main/java/com/gmail/nossr50/datatypes/meta/UUIDMeta.java @@ -1,18 +1,17 @@ package com.gmail.nossr50.datatypes.meta; +import java.util.UUID; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.UUID; - public class UUIDMeta extends FixedMetadataValue { /** * Initializes a FixedMetadataValue with an Object * * @param owningPlugin the {@link Plugin} that created this metadata value - * @param value the value assigned to this metadata value + * @param value the value assigned to this metadata value */ public UUIDMeta(@NotNull Plugin owningPlugin, @Nullable UUID value) { super(owningPlugin, value); diff --git a/src/main/java/com/gmail/nossr50/datatypes/mods/CustomEntity.java b/src/main/java/com/gmail/nossr50/datatypes/mods/CustomEntity.java index c1b8fc118..88846f364 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/mods/CustomEntity.java +++ b/src/main/java/com/gmail/nossr50/datatypes/mods/CustomEntity.java @@ -10,7 +10,8 @@ public class CustomEntity { private final ItemStack callOfTheWildItem; private final int callOfTheWildAmount; - public CustomEntity(double xpMultiplier, boolean canBeTamed, int tamingXP, boolean canBeSummoned, ItemStack callOfTheWildItem, int callOfTheWildAmount) { + public CustomEntity(double xpMultiplier, boolean canBeTamed, int tamingXP, + boolean canBeSummoned, ItemStack callOfTheWildItem, int callOfTheWildAmount) { this.xpMultiplier = xpMultiplier; this.canBeTamed = canBeTamed; this.tamingXP = tamingXP; 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 8089e025e..5f744c093 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/party/ItemShareType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/party/ItemShareType.java @@ -29,6 +29,7 @@ public enum ItemShareType { } public String getLocaleString() { - return LocaleLoader.getString("Party.ItemShare.Category." + StringUtils.getCapitalized(this.toString())); + return LocaleLoader.getString( + "Party.ItemShare.Category." + StringUtils.getCapitalized(this.toString())); } } 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 f0f1d110e..e62ce449c 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/party/Party.java +++ b/src/main/java/com/gmail/nossr50/datatypes/party/Party.java @@ -10,6 +10,14 @@ import com.gmail.nossr50.util.EventUtils; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.sounds.SoundManager; import com.gmail.nossr50.util.sounds.SoundType; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import java.util.function.Predicate; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; @@ -17,14 +25,10 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.util.*; -import java.util.function.Predicate; - public class Party { - private static final DecimalFormat percent = new DecimalFormat("##0.00%", DecimalFormatSymbols.getInstance(Locale.US)); + private static final DecimalFormat percent = new DecimalFormat("##0.00%", + DecimalFormatSymbols.getInstance(Locale.US)); private final @NotNull Predicate samePartyPredicate; private final LinkedHashMap members = new LinkedHashMap<>(); @@ -38,14 +42,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; @@ -89,9 +93,10 @@ public class Party { 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); + } } return visibleMembers; @@ -201,7 +206,8 @@ public class Party { public int getXpToLevel() { FormulaType formulaType = ExperienceConfig.getInstance().getFormulaType(); - return (mcMMO.getFormulaManager().getXPtoNextLevel(level, formulaType)) * (getOnlineMembers().size() + mcMMO.p.getGeneralConfig().getPartyXpCurveMultiplier()); + return (mcMMO.getFormulaManager().getXPtoNextLevel(level, formulaType)) * ( + getOnlineMembers().size() + mcMMO.p.getGeneralConfig().getPartyXpCurveMultiplier()); } public String getXpToLevelPercentage() { @@ -243,7 +249,8 @@ public class Party { Player leader = mcMMO.p.getServer().getPlayer(this.leader.getUniqueId()); if (leader != null) { - leader.sendMessage(LocaleLoader.getString("Party.LevelUp", levelsGained, getLevel())); + leader.sendMessage( + LocaleLoader.getString("Party.LevelUp", levelsGained, getLevel())); if (mcMMO.p.getGeneralConfig().getLevelUpSoundsEnabled()) { SoundManager.sendSound(leader, leader.getLocation(), SoundType.LEVEL_UP); @@ -332,9 +339,10 @@ 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 + * 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 */ @@ -342,11 +350,12 @@ public class Party { StringBuilder memberList = new StringBuilder(); List coloredNames = new ArrayList<>(); - for(UUID playerUUID : members.keySet()) { + for (UUID playerUUID : members.keySet()) { OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(playerUUID); if (offlinePlayer.isOnline() && player.canSee((Player) offlinePlayer)) { - ChatColor onlineColor = leader.getUniqueId().equals(playerUUID) ? ChatColor.GOLD : ChatColor.GREEN; + ChatColor onlineColor = + leader.getUniqueId().equals(playerUUID) ? ChatColor.GOLD : ChatColor.GREEN; coloredNames.add(onlineColor + offlinePlayer.getName()); } else { coloredNames.add(ChatColor.DARK_GRAY + members.get(playerUUID)); @@ -358,7 +367,7 @@ public class Party { } private void buildChatMessage(@NotNull StringBuilder stringBuilder, String @NotNull [] names) { - for(int i = 0; i < names.length; i++) { + for (int i = 0; i < names.length; i++) { if (i + 1 >= names.length) { stringBuilder .append(names[i]); @@ -373,19 +382,20 @@ public class Party { /** * Get the near party members. * - * @param mcMMOPlayer The player to check + * @param mmoPlayer The player to check * @return the near party members */ - public List getNearMembers(McMMOPlayer mcMMOPlayer) { + public List getNearMembers(McMMOPlayer mmoPlayer) { List nearMembers = new ArrayList<>(); - Party party = mcMMOPlayer.getParty(); + Party party = mmoPlayer.getParty(); if (party != null) { - Player player = mcMMOPlayer.getPlayer(); + Player player = mmoPlayer.getPlayer(); double range = mcMMO.p.getGeneralConfig().getPartyShareRange(); for (Player member : party.getOnlineMembers()) { - if (!player.equals(member) && member.isValid() && Misc.isNear(player.getLocation(), member.getLocation(), range)) { + if (!player.equals(member) && member.isValid() && Misc.isNear(player.getLocation(), + member.getLocation(), range)) { nearMembers.add(member); } } 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 c01f17f75..8acc68306 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/party/PartyFeature.java +++ b/src/main/java/com/gmail/nossr50/datatypes/party/PartyFeature.java @@ -1,13 +1,13 @@ package com.gmail.nossr50.datatypes.party; +import static com.gmail.nossr50.util.text.ConfigStringUtils.getConfigPartyFeatureString; + import com.gmail.nossr50.commands.party.PartySubcommandType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.Permissions; import org.bukkit.entity.Player; -import static com.gmail.nossr50.util.text.ConfigStringUtils.getConfigPartyFeatureString; - public enum PartyFeature { CHAT, TELEPORT, @@ -20,7 +20,9 @@ public enum PartyFeature { } public String getFeatureLockedLocaleString() { - return LocaleLoader.getString("Ability.Generic.Template.Lock", LocaleLoader.getString("Party.Feature.Locked." + getConfigPartyFeatureString(this), mcMMO.p.getGeneralConfig().getPartyFeatureUnlockLevel(this))); + return LocaleLoader.getString("Ability.Generic.Template.Lock", + LocaleLoader.getString("Party.Feature.Locked." + getConfigPartyFeatureString(this), + mcMMO.p.getGeneralConfig().getPartyFeatureUnlockLevel(this))); } public boolean hasPermission(Player player) { @@ -45,7 +47,6 @@ public enum PartyFeature { return false; } - return Permissions.partySubcommand(player, partySubCommandType); } } 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 17d815a6b..7c79d9cec 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 3c136711b..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,8 +10,7 @@ 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)) { 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 6ff677993..aa12b55f3 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java +++ b/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java @@ -1,5 +1,8 @@ package com.gmail.nossr50.datatypes.player; +import static com.gmail.nossr50.util.EventUtils.callPlayerAbilityActivateEvent; +import static java.util.Objects.requireNonNull; + import com.gmail.nossr50.api.exceptions.InvalidSkillException; import com.gmail.nossr50.chat.author.PlayerAuthor; import com.gmail.nossr50.config.ChatConfig; @@ -42,7 +45,11 @@ import com.gmail.nossr50.skills.taming.TamingManager; import com.gmail.nossr50.skills.tridents.TridentsManager; import com.gmail.nossr50.skills.unarmed.UnarmedManager; import com.gmail.nossr50.skills.woodcutting.WoodcuttingManager; -import com.gmail.nossr50.util.*; +import com.gmail.nossr50.util.BlockUtils; +import com.gmail.nossr50.util.EventUtils; +import com.gmail.nossr50.util.MetadataConstants; +import com.gmail.nossr50.util.Misc; +import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.experience.ExperienceBarManager; import com.gmail.nossr50.util.player.NotificationManager; import com.gmail.nossr50.util.player.UserManager; @@ -53,6 +60,9 @@ import com.gmail.nossr50.util.skills.SkillTools; import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.sounds.SoundManager; import com.gmail.nossr50.util.sounds.SoundType; +import java.util.EnumMap; +import java.util.Map; +import java.util.UUID; import net.kyori.adventure.identity.Identified; import net.kyori.adventure.identity.Identity; import org.bukkit.Bukkit; @@ -68,29 +78,23 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.VisibleForTesting; -import java.util.EnumMap; -import java.util.Map; -import java.util.UUID; - -import static com.gmail.nossr50.util.EventUtils.callPlayerAbilityActivateEvent; -import static java.util.Objects.requireNonNull; - public class McMMOPlayer implements Identified { private final @NotNull Identity identity; //Hacky fix for now, redesign later private final @NotNull PlayerAuthor playerAuthor; - private final Player player; + private final Player player; private final PlayerProfile profile; - private final Map skillManagers = new EnumMap<>(PrimarySkillType.class); + private final Map skillManagers = new EnumMap<>( + PrimarySkillType.class); private final 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; @@ -103,8 +107,10 @@ public class McMMOPlayer implements Identified { private ChatChannel chatChannel; - private final Map abilityMode = new EnumMap<>(SuperAbilityType.class); - private final Map abilityInformed = new EnumMap<>(SuperAbilityType.class); + private final Map abilityMode = new EnumMap<>( + SuperAbilityType.class); + private final Map abilityInformed = new EnumMap<>( + SuperAbilityType.class); private final Map toolMode = new EnumMap<>(ToolType.class); @@ -161,7 +167,7 @@ public class McMMOPlayer implements Identified { } private void initSkillManagers() { - for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { + for (PrimarySkillType primarySkillType : PrimarySkillType.values()) { try { initManager(primarySkillType); } catch (InvalidSkillException e) { @@ -172,7 +178,7 @@ public class McMMOPlayer implements Identified { //TODO: Add test private void initManager(PrimarySkillType primarySkillType) throws InvalidSkillException { - switch(primarySkillType) { + switch (primarySkillType) { case ACROBATICS: skillManagers.put(primarySkillType, new AcrobaticsManager(this)); break; @@ -230,7 +236,8 @@ public class McMMOPlayer implements Identified { } break; default: - throw new InvalidSkillException("The skill named has no manager! Contact the devs!"); + throw new InvalidSkillException( + "The skill named has no manager! Contact the devs!"); } } @@ -254,10 +261,12 @@ public class McMMOPlayer implements Identified { this.lastSkillShownScoreboard = primarySkillType; } - public void processPostXpEvent(PrimarySkillType primarySkillType, Plugin plugin, XPGainSource xpGainSource) { + public void processPostXpEvent(PrimarySkillType primarySkillType, Plugin plugin, + XPGainSource xpGainSource) { //Check if they've reached the power level cap just now if (hasReachedPowerLevelCap()) { - NotificationManager.sendPlayerInformationChatOnly(player, "LevelCap.PowerLevel", String.valueOf(mcMMO.p.getGeneralConfig().getPowerLevelCap())); + NotificationManager.sendPlayerInformationChatOnly(player, "LevelCap.PowerLevel", + String.valueOf(mcMMO.p.getGeneralConfig().getPowerLevelCap())); } else if (hasReachedLevelCap(primarySkillType)) { NotificationManager.sendPlayerInformationChatOnly(player, "LevelCap.Skill", String.valueOf(mcMMO.p.getSkillTools().getLevelCap(primarySkillType)), @@ -265,17 +274,22 @@ public class McMMOPlayer implements Identified { } //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); } @@ -314,6 +328,7 @@ public class McMMOPlayer implements Identified { public AxesManager getAxesManager() { return (AxesManager) skillManagers.get(PrimarySkillType.AXES); } + public CrossbowsManager getCrossbowsManager() { return (CrossbowsManager) skillManagers.get(PrimarySkillType.CROSSBOWS); } @@ -492,7 +507,8 @@ public class McMMOPlayer implements Identified { } public void actualizeChimeraWingLastUse() { - profile.setChimaeraWingDATS((int) (System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR)); + profile.setChimaeraWingDATS( + (int) (System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR)); } public Location getTeleportCommenceLocation() { @@ -551,9 +567,13 @@ public class McMMOPlayer implements Identified { * Party Chat Spy */ - public boolean isPartyChatSpying() { return chatSpy; } + public boolean isPartyChatSpying() { + return chatSpy; + } - public void togglePartyChatSpying() { chatSpy = !chatSpy;} + public void togglePartyChatSpying() { + chatSpy = !chatSpy; + } /* * Debug Mode Flags @@ -597,21 +617,25 @@ public class McMMOPlayer implements Identified { } /** - * Whether a player is level capped - * If they are at the power level cap, this will return true, otherwise it checks their skill level + * Whether a player is level capped If they are at the power level cap, this will return true, + * otherwise it checks their skill level + * * @param primarySkillType * @return */ public boolean hasReachedLevelCap(PrimarySkillType primarySkillType) { - if (hasReachedPowerLevelCap()) + if (hasReachedPowerLevelCap()) { return true; + } - return getSkillLevel(primarySkillType) >= mcMMO.p.getSkillTools().getLevelCap(primarySkillType); + return getSkillLevel(primarySkillType) >= mcMMO.p.getSkillTools() + .getLevelCap(primarySkillType); } /** - * Whether a player is power level capped - * Compares their power level total to the current set limit + * Whether a player is power level capped Compares their power level total to the current set + * limit + * * @return true if they have reached the power level cap */ public boolean hasReachedPowerLevelCap() { @@ -619,12 +643,14 @@ public class McMMOPlayer implements Identified { } /** - * Begins an experience gain. The amount will be affected by skill modifiers, global rate, perks, and may be shared with the party + * 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 */ - public void beginXpGain(PrimarySkillType skill, float xp, XPGainReason xpGainReason, XPGainSource xpGainSource) { + public void beginXpGain(PrimarySkillType skill, float xp, XPGainReason xpGainReason, + XPGainSource xpGainSource) { if (xp <= 0) { return; } @@ -643,7 +669,8 @@ public class McMMOPlayer implements Identified { } // Return if the experience has been shared - if (party != null && ShareHandler.handleXpShare(xp, this, skill, ShareHandler.getSharedXpGainReason(xpGainReason))) { + if (party != null && ShareHandler.handleXpShare(xp, this, skill, + ShareHandler.getSharedXpGainReason(xpGainReason))) { return; } @@ -651,22 +678,27 @@ public class McMMOPlayer implements Identified { } /** - * Begins an experience gain. The amount will be affected by skill modifiers, global rate and perks + * 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 */ - public void beginUnsharedXpGain(PrimarySkillType skill, float xp, XPGainReason xpGainReason, XPGainSource xpGainSource) { - if (player.getGameMode() == GameMode.CREATIVE) - return; - - applyXpGain(skill, modifyXpGain(skill, xp), xpGainReason, xpGainSource); - - if (!mcMMO.p.getPartyConfig().isPartyEnabled() || party == null || party.hasReachedLevelCap()) { + public void beginUnsharedXpGain(PrimarySkillType skill, float xp, XPGainReason xpGainReason, + XPGainSource xpGainSource) { + if (player.getGameMode() == GameMode.CREATIVE) { return; } - if (!mcMMO.p.getGeneralConfig().getPartyXpNearMembersNeeded() || !mcMMO.p.getPartyManager().getNearMembers(this).isEmpty()) { + applyXpGain(skill, modifyXpGain(skill, xp), xpGainReason, xpGainSource); + + if (!mcMMO.p.getPartyConfig().isPartyEnabled() || party == null + || party.hasReachedLevelCap()) { + return; + } + + if (!mcMMO.p.getGeneralConfig().getPartyXpNearMembersNeeded() || !mcMMO.p.getPartyManager() + .getNearMembers(this).isEmpty()) { party.applyXpGain(modifyXpGain(skill, xp)); } } @@ -677,14 +709,16 @@ public class McMMOPlayer implements Identified { * @param primarySkillType Skill being used * @param xp Experience amount to add */ - public void applyXpGain(PrimarySkillType primarySkillType, float xp, XPGainReason xpGainReason, XPGainSource xpGainSource) { + public void applyXpGain(PrimarySkillType primarySkillType, float xp, XPGainReason xpGainReason, + XPGainSource xpGainSource) { if (!mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, primarySkillType)) { return; } - final McMMOPlayerPreXpGainEvent mcMMOPlayerPreXpGainEvent = new McMMOPlayerPreXpGainEvent(player, primarySkillType, xp, xpGainReason); - Bukkit.getPluginManager().callEvent(mcMMOPlayerPreXpGainEvent); - xp = mcMMOPlayerPreXpGainEvent.getXpGained(); + final McMMOPlayerPreXpGainEvent mmoPlayerPreXpGainEvent = new McMMOPlayerPreXpGainEvent( + player, primarySkillType, xp, xpGainReason); + Bukkit.getPluginManager().callEvent(mmoPlayerPreXpGainEvent); + xp = mmoPlayerPreXpGainEvent.getXpGained(); if (SkillTools.isChildSkill(primarySkillType)) { var parentSkills = mcMMO.p.getSkillTools().getChildSkillParents(primarySkillType); @@ -709,9 +743,11 @@ public class McMMOPlayer implements Identified { * * @param primarySkillType The skill to check */ - private void checkXp(PrimarySkillType primarySkillType, XPGainReason xpGainReason, XPGainSource xpGainSource) { - if (hasReachedLevelCap(primarySkillType)) + private void checkXp(PrimarySkillType primarySkillType, XPGainReason xpGainReason, + XPGainSource xpGainSource) { + if (hasReachedLevelCap(primarySkillType)) { return; + } if (getSkillXpLevelRaw(primarySkillType) < getXpToLevel(primarySkillType)) { processPostXpEvent(primarySkillType, mcMMO.p, xpGainSource); @@ -731,7 +767,8 @@ public class McMMOPlayer implements Identified { levelsGained++; } - if (EventUtils.tryLevelChangeEvent(this, primarySkillType, levelsGained, xpRemoved, true, xpGainReason)) { + if (EventUtils.tryLevelChangeEvent(this, primarySkillType, levelsGained, xpRemoved, true, + xpGainReason)) { return; } @@ -743,7 +780,8 @@ public class McMMOPlayer implements Identified { * Check to see if the player unlocked any new skills */ - NotificationManager.sendPlayerLevelUpNotification(this, primarySkillType, levelsGained, profile.getSkillLevel(primarySkillType)); + NotificationManager.sendPlayerLevelUpNotification(this, primarySkillType, levelsGained, + profile.getSkillLevel(primarySkillType)); //UPDATE XP BARS processPostXpEvent(primarySkillType, mcMMO.p, xpGainSource); @@ -767,7 +805,8 @@ public class McMMOPlayer implements Identified { public void setupPartyData() { if (mcMMO.p.isPartySystemEnabled()) { - party = mcMMO.p.getPartyManager().getPlayerParty(player.getName(), player.getUniqueId()); + party = mcMMO.p.getPartyManager() + .getPlayerParty(player.getName(), player.getUniqueId()); ptpRecord = new PartyTeleportRecord(); if (inParty()) { @@ -858,19 +897,22 @@ public class McMMOPlayer implements Identified { @VisibleForTesting float modifyXpGain(PrimarySkillType primarySkillType, float xp) { //TODO: A rare situation can occur where the default Power Level cap can prevent a player with one skill edited to something silly like Integer.MAX_VALUE from gaining XP in any skill, we may need to represent power level with another data type - if ((mcMMO.p.getSkillTools().getLevelCap(primarySkillType) <= getSkillLevel(primarySkillType)) + if ((mcMMO.p.getSkillTools().getLevelCap(primarySkillType) <= getSkillLevel( + primarySkillType)) || (mcMMO.p.getGeneralConfig().getPowerLevelCap() <= getPowerLevel())) { return 0; } - xp = (float) ((xp * ExperienceConfig.getInstance().getFormulaSkillModifier(primarySkillType)) * ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier()); + xp = (float) ( + (xp * ExperienceConfig.getInstance().getFormulaSkillModifier(primarySkillType)) + * ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier()); return PerksUtils.handleXpPerks(player, xp, primarySkillType); } 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")); } @@ -890,7 +932,8 @@ public class McMMOPlayer implements Identified { */ public void checkAbilityActivation(PrimarySkillType primarySkillType) { ToolType tool = mcMMO.p.getSkillTools().getPrimarySkillToolType(primarySkillType); - SuperAbilityType superAbilityType = mcMMO.p.getSkillTools().getSuperAbility(primarySkillType); + SuperAbilityType superAbilityType = mcMMO.p.getSkillTools() + .getSuperAbility(primarySkillType); SubSkillType subSkillType = superAbilityType.getSubSkillTypeDefinition(); if (getAbilityMode(superAbilityType) || !superAbilityType.getPermissions(player)) { @@ -900,10 +943,13 @@ public class McMMOPlayer implements Identified { //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 (!RankUtils.hasUnlockedSubskill(player, subSkillType)) { - int diff = RankUtils.getSuperAbilityUnlockRequirement(superAbilityType) - getSkillLevel(primarySkillType); + int diff = RankUtils.getSuperAbilityUnlockRequirement(superAbilityType) - getSkillLevel( + primarySkillType); //Inform the player they are not yet skilled enough - NotificationManager.sendPlayerInformation(player, NotificationType.ABILITY_COOLDOWN, "Skills.AbilityGateRequirementFail", String.valueOf(diff), mcMMO.p.getSkillTools().getLocalizedSkillName(primarySkillType)); + NotificationManager.sendPlayerInformation(player, NotificationType.ABILITY_COOLDOWN, + "Skills.AbilityGateRequirementFail", String.valueOf(diff), + mcMMO.p.getSkillTools().getLocalizedSkillName(primarySkillType)); return; } @@ -914,8 +960,10 @@ public class McMMOPlayer implements Identified { * Axes and Woodcutting are odd because they share the same tool. * We show them the too tired message when they take action. */ - if (primarySkillType == PrimarySkillType.WOODCUTTING || primarySkillType == PrimarySkillType.AXES) { - NotificationManager.sendPlayerInformation(player, NotificationType.ABILITY_COOLDOWN, "Skills.TooTired", String.valueOf(timeRemaining)); + if (primarySkillType == PrimarySkillType.WOODCUTTING + || primarySkillType == PrimarySkillType.AXES) { + NotificationManager.sendPlayerInformation(player, NotificationType.ABILITY_COOLDOWN, + "Skills.TooTired", String.valueOf(timeRemaining)); //SoundManager.sendSound(player, player.getLocation(), SoundType.TIRED); } @@ -934,37 +982,50 @@ public class McMMOPlayer implements Identified { //Ability cap of 0 or below means no cap if (abilityLengthCap > 0) { - ticks = PerksUtils.handleActivationPerks(player, 2 + (Math.min(abilityLengthCap, getSkillLevel(primarySkillType)) / abilityLengthVar), superAbilityType.getMaxLength()); + ticks = PerksUtils.handleActivationPerks(player, + 2 + (Math.min(abilityLengthCap, getSkillLevel(primarySkillType)) + / abilityLengthVar), superAbilityType.getMaxLength()); } else { - ticks = PerksUtils.handleActivationPerks(player, 2 + (getSkillLevel(primarySkillType) / abilityLengthVar), superAbilityType.getMaxLength()); + ticks = PerksUtils.handleActivationPerks(player, + 2 + (getSkillLevel(primarySkillType) / abilityLengthVar), + superAbilityType.getMaxLength()); } if (useChatNotifications()) { - NotificationManager.sendPlayerInformation(player, NotificationType.SUPER_ABILITY, superAbilityType.getAbilityOn()); + NotificationManager.sendPlayerInformation(player, NotificationType.SUPER_ABILITY, + superAbilityType.getAbilityOn()); //player.sendMessage(ability.getAbilityOn()); } if (mcMMO.p.getAdvancedConfig().sendAbilityNotificationToOtherPlayers()) { - SkillUtils.sendSkillMessage(player, NotificationType.SUPER_ABILITY_ALERT_OTHERS, superAbilityType.getAbilityPlayer()); + SkillUtils.sendSkillMessage(player, NotificationType.SUPER_ABILITY_ALERT_OTHERS, + superAbilityType.getAbilityPlayer()); } //Sounds - SoundManager.worldSendSound(player.getWorld(), player.getLocation(), SoundType.ABILITY_ACTIVATED_GENERIC); + SoundManager.worldSendSound(player.getWorld(), player.getLocation(), + SoundType.ABILITY_ACTIVATED_GENERIC); //If the current item is still buffed somehow, remove it to prevent enchantments from stacking. - if (superAbilityType == SuperAbilityType.SUPER_BREAKER || superAbilityType == SuperAbilityType.GIGA_DRILL_BREAKER) + if (superAbilityType == SuperAbilityType.SUPER_BREAKER + || superAbilityType == SuperAbilityType.GIGA_DRILL_BREAKER) { SkillUtils.removeAbilityBuff(player.getInventory().getItemInMainHand()); + } // Enable the ability - profile.setAbilityDATS(superAbilityType, System.currentTimeMillis() + ((long) ticks * Misc.TIME_CONVERSION_FACTOR)); + profile.setAbilityDATS(superAbilityType, + System.currentTimeMillis() + ((long) ticks * Misc.TIME_CONVERSION_FACTOR)); setAbilityMode(superAbilityType, true); - if (superAbilityType == SuperAbilityType.SUPER_BREAKER || superAbilityType == SuperAbilityType.GIGA_DRILL_BREAKER) { + if (superAbilityType == SuperAbilityType.SUPER_BREAKER + || superAbilityType == SuperAbilityType.GIGA_DRILL_BREAKER) { SkillUtils.handleAbilitySpeedIncrease(player); } setToolPreparationMode(tool, false); - mcMMO.p.getFoliaLib().getScheduler().runAtEntityLater(player, new AbilityDisableTask(this, superAbilityType), (long) ticks * Misc.TICK_CONVERSION_FACTOR); + mcMMO.p.getFoliaLib().getScheduler() + .runAtEntityLater(player, new AbilityDisableTask(this, superAbilityType), + (long) ticks * Misc.TICK_CONVERSION_FACTOR); } public void processAbilityActivation(@NotNull PrimarySkillType primarySkillType) { @@ -972,7 +1033,8 @@ public class McMMOPlayer implements Identified { return; } - if (mcMMO.p.getGeneralConfig().getAbilitiesOnlyActivateWhenSneaking() && !player.isSneaking()) { + if (mcMMO.p.getGeneralConfig().getAbilitiesOnlyActivateWhenSneaking() + && !player.isSneaking()) { return; } @@ -996,11 +1058,14 @@ public class McMMOPlayer implements Identified { * Basically the tool always needs to ready and we check to see if the cooldown is over when the user takes action */ if (tool.inHand(inHand) && !getToolPreparationMode(tool)) { - if (primarySkillType != PrimarySkillType.WOODCUTTING && primarySkillType != PrimarySkillType.AXES) { + if (primarySkillType != PrimarySkillType.WOODCUTTING + && primarySkillType != PrimarySkillType.AXES) { int timeRemaining = calculateTimeRemaining(ability); if (isAbilityOnCooldown(ability)) { - NotificationManager.sendPlayerInformation(player, NotificationType.ABILITY_COOLDOWN, "Skills.TooTired", String.valueOf(timeRemaining)); + NotificationManager.sendPlayerInformation(player, + NotificationType.ABILITY_COOLDOWN, "Skills.TooTired", + String.valueOf(timeRemaining)); return; } } @@ -1014,7 +1079,8 @@ public class McMMOPlayer implements Identified { if (tool == ToolType.AXE) { processAxeToolMessages(); } else { - NotificationManager.sendPlayerInformation(player, NotificationType.TOOL, tool.getRaiseTool()); + NotificationManager.sendPlayerInformation(player, NotificationType.TOOL, + tool.getRaiseTool()); } //Send Sound @@ -1022,7 +1088,9 @@ public class McMMOPlayer implements Identified { } setToolPreparationMode(tool, true); - mcMMO.p.getFoliaLib().getScheduler().runAtEntityLater(player, new ToolLowerTask(this, tool), 4 * Misc.TICK_CONVERSION_FACTOR); + mcMMO.p.getFoliaLib().getScheduler() + .runAtEntityLater(player, new ToolLowerTask(this, tool), + 4 * Misc.TICK_CONVERSION_FACTOR); } } @@ -1032,40 +1100,51 @@ public class McMMOPlayer implements Identified { /* * IF BOTH TREE FELLER & SKULL SPLITTER ARE ON CD */ - if (isAbilityOnCooldown(SuperAbilityType.TREE_FELLER) && isAbilityOnCooldown(SuperAbilityType.SKULL_SPLITTER)) { - tooTiredMultiple(PrimarySkillType.WOODCUTTING, SubSkillType.WOODCUTTING_TREE_FELLER, SuperAbilityType.TREE_FELLER, SubSkillType.AXES_SKULL_SPLITTER, SuperAbilityType.SKULL_SPLITTER); - /* - * IF TREE FELLER IS ON CD - * AND PLAYER IS LOOKING AT TREE - */ + if (isAbilityOnCooldown(SuperAbilityType.TREE_FELLER) && isAbilityOnCooldown( + SuperAbilityType.SKULL_SPLITTER)) { + tooTiredMultiple(PrimarySkillType.WOODCUTTING, SubSkillType.WOODCUTTING_TREE_FELLER, + SuperAbilityType.TREE_FELLER, SubSkillType.AXES_SKULL_SPLITTER, + SuperAbilityType.SKULL_SPLITTER); + /* + * IF TREE FELLER IS ON CD + * AND PLAYER IS LOOKING AT TREE + */ } else if (isAbilityOnCooldown(SuperAbilityType.TREE_FELLER) && BlockUtils.isPartOfTree(rayCast)) { - raiseToolWithCooldowns(SubSkillType.WOODCUTTING_TREE_FELLER, SuperAbilityType.TREE_FELLER); + raiseToolWithCooldowns(SubSkillType.WOODCUTTING_TREE_FELLER, + SuperAbilityType.TREE_FELLER); - /* - * IF SKULL SPLITTER IS ON CD - */ + /* + * IF SKULL SPLITTER IS ON CD + */ } else if (isAbilityOnCooldown(SuperAbilityType.SKULL_SPLITTER)) { - raiseToolWithCooldowns(SubSkillType.AXES_SKULL_SPLITTER, SuperAbilityType.SKULL_SPLITTER); + raiseToolWithCooldowns(SubSkillType.AXES_SKULL_SPLITTER, + SuperAbilityType.SKULL_SPLITTER); } else { - NotificationManager.sendPlayerInformation(player, NotificationType.TOOL, ToolType.AXE.getRaiseTool()); + NotificationManager.sendPlayerInformation(player, NotificationType.TOOL, + ToolType.AXE.getRaiseTool()); } } private void tooTiredMultiple(PrimarySkillType primarySkillType, SubSkillType aSubSkill, - SuperAbilityType aSuperAbility, SubSkillType bSubSkill, SuperAbilityType bSuperAbility) { - String aSuperAbilityCD = LocaleLoader.getString("Skills.TooTired.Named", aSubSkill.getLocaleName(), + SuperAbilityType aSuperAbility, SubSkillType bSubSkill, + SuperAbilityType bSuperAbility) { + String aSuperAbilityCD = LocaleLoader.getString("Skills.TooTired.Named", + aSubSkill.getLocaleName(), String.valueOf(calculateTimeRemaining(aSuperAbility))); - String bSuperAbilityCD = LocaleLoader.getString("Skills.TooTired.Named", bSubSkill.getLocaleName(), + String bSuperAbilityCD = LocaleLoader.getString("Skills.TooTired.Named", + bSubSkill.getLocaleName(), String.valueOf(calculateTimeRemaining(bSuperAbility))); String allCDStr = aSuperAbilityCD + ", " + bSuperAbilityCD; - NotificationManager.sendPlayerInformation(player, NotificationType.TOOL, "Skills.TooTired.Extra", + NotificationManager.sendPlayerInformation(player, NotificationType.TOOL, + "Skills.TooTired.Extra", mcMMO.p.getSkillTools().getLocalizedSkillName(primarySkillType), allCDStr); } - private void raiseToolWithCooldowns(SubSkillType subSkillType, SuperAbilityType superAbilityType) { + private void raiseToolWithCooldowns(SubSkillType subSkillType, + SuperAbilityType superAbilityType) { NotificationManager.sendPlayerInformation(player, NotificationType.TOOL, "Axes.Ability.Ready.Extra", subSkillType.getLocaleName(), @@ -1080,12 +1159,14 @@ public class McMMOPlayer implements Identified { * 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) { long deactivatedTimestamp = profile.getAbilityDATS(ability) * Misc.TIME_CONVERSION_FACTOR; - return (int) (((deactivatedTimestamp + (PerksUtils.handleCooldownPerks(player, ability.getCooldown()) * Misc.TIME_CONVERSION_FACTOR)) - System.currentTimeMillis()) / Misc.TIME_CONVERSION_FACTOR); + return (int) (((deactivatedTimestamp + ( + PerksUtils.handleCooldownPerks(player, ability.getCooldown()) + * Misc.TIME_CONVERSION_FACTOR)) - System.currentTimeMillis()) + / Misc.TIME_CONVERSION_FACTOR); } /* @@ -1140,18 +1221,20 @@ public class McMMOPlayer implements Identified { } /** - * This method is called by PlayerQuitEvent to tear down the mcMMOPlayer. + * This method is called by PlayerQuitEvent to tear down the mmoPlayer. * * @param syncSave if true, data is saved synchronously */ public void logout(boolean syncSave) { final Player thisPlayer = getPlayer(); - if (getPlayer() != null && getPlayer().hasMetadata(MetadataConstants.METADATA_KEY_RUPTURE)) { + if (getPlayer() != null && getPlayer().hasMetadata( + MetadataConstants.METADATA_KEY_RUPTURE)) { final RuptureTaskMeta ruptureTaskMeta - = (RuptureTaskMeta) getPlayer().getMetadata(MetadataConstants.METADATA_KEY_RUPTURE).get(0); + = (RuptureTaskMeta) getPlayer().getMetadata( + MetadataConstants.METADATA_KEY_RUPTURE).get(0); if (ruptureTaskMeta != null) { final RuptureTask ruptureTimerTask = ruptureTaskMeta.getRuptureTimerTask(); - if(ruptureTimerTask != null) { + if (ruptureTimerTask != null) { ruptureTimerTask.cancel(); } getPlayer().removeMetadata(MetadataConstants.METADATA_KEY_RUPTURE, mcMMO.p); @@ -1168,8 +1251,9 @@ public class McMMOPlayer implements Identified { UserManager.remove(thisPlayer); - if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) + if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) { ScoreboardManager.teardownPlayer(thisPlayer); + } if (inParty()) { party.removeOnlineMember(thisPlayer); @@ -1180,10 +1264,8 @@ public class McMMOPlayer implements Identified { } /** - * Cleanup various things related to this player - * Such as temporary summons.. - * Turning off abilities... - * Etc... + * Cleanup various things related to this player Such as temporary summons.. Turning off + * abilities... Etc... */ public void cleanup() { resetAbilityMode(); @@ -1192,6 +1274,7 @@ public class McMMOPlayer implements Identified { /** * For use with Adventure API (Kyori lib) + * * @return this players identity */ @Override @@ -1202,6 +1285,7 @@ public class McMMOPlayer implements Identified { /** * The {@link com.gmail.nossr50.chat.author.Author} for this player, used by mcMMO chat + * * @return the {@link com.gmail.nossr50.chat.author.Author} for this player */ public @NotNull PlayerAuthor getPlayerAuthor() { @@ -1213,8 +1297,8 @@ public class McMMOPlayer implements Identified { } /** - * Change the chat channel for a player - * This does not inform the player + * Change the chat channel for a player This does not inform the player + * * @param chatChannel new chat channel */ public void setChatMode(@NotNull ChatChannel chatChannel) { 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 bbcfd8bda..c9c2e9d83 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/player/PlayerProfile.java +++ b/src/main/java/com/gmail/nossr50/datatypes/player/PlayerProfile.java @@ -11,14 +11,13 @@ import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.SkillTools; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.util.EnumMap; import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.concurrent.DelayQueue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class PlayerProfile { private final String playerName; @@ -33,14 +32,19 @@ public class PlayerProfile { private @Nullable Long lastLogin; /* Skill Data */ - private final Map skills = new EnumMap<>(PrimarySkillType.class); // Skill & Level - private final Map skillsXp = new EnumMap<>(PrimarySkillType.class); // Skill & XP - private final Map abilityDATS = new EnumMap<>(SuperAbilityType.class); // Ability & Cooldown - private final Map uniquePlayerData = new EnumMap<>(UniqueDataType.class); //Misc data that doesn't fit into other categories (chimaera wing, etc..) + private final Map skills = new EnumMap<>( + PrimarySkillType.class); // Skill & Level + private final Map skillsXp = new EnumMap<>( + PrimarySkillType.class); // Skill & XP + private final Map abilityDATS = new EnumMap<>( + SuperAbilityType.class); // Ability & Cooldown + private final Map uniquePlayerData = new EnumMap<>( + UniqueDataType.class); //Misc data that doesn't fit into other categories (chimaera wing, etc..) // Store previous XP gains for diminished returns private final DelayQueue gainedSkillsXp = new DelayQueue<>(); - private final Map rollingSkillsXp = new EnumMap<>(PrimarySkillType.class); + private final Map rollingSkillsXp = new EnumMap<>( + PrimarySkillType.class); @Deprecated public PlayerProfile(String playerName) { @@ -89,9 +93,9 @@ public class PlayerProfile { } public PlayerProfile(@NotNull String playerName, @Nullable UUID uuid, - Map levelData, Map xpData, - Map cooldownData, int scoreboardTipsShown, - Map uniqueProfileData, @Nullable Long lastLogin) { + Map levelData, Map xpData, + Map cooldownData, int scoreboardTipsShown, + Map uniqueProfileData, @Nullable Long lastLogin) { this.playerName = playerName; this.uuid = uuid; this.scoreboardTipsShown = scoreboardTipsShown; @@ -103,8 +107,9 @@ public class PlayerProfile { loaded = true; - if (lastLogin != null) + if (lastLogin != null) { this.lastLogin = lastLogin; + } } public void scheduleAsyncSave() { @@ -112,7 +117,8 @@ public class PlayerProfile { } public void scheduleAsyncSaveDelay() { - mcMMO.p.getFoliaLib().getScheduler().runLaterAsync(new PlayerProfileSaveTask(this, false), 20); + mcMMO.p.getFoliaLib().getScheduler() + .runLaterAsync(new PlayerProfileSaveTask(this, false), 20); } @Deprecated @@ -127,29 +133,34 @@ public class PlayerProfile { } // TODO should this part be synchronized? - PlayerProfile profileCopy = new PlayerProfile(playerName, uuid, ImmutableMap.copyOf(skills), ImmutableMap.copyOf(skillsXp), ImmutableMap.copyOf(abilityDATS), scoreboardTipsShown, ImmutableMap.copyOf(uniquePlayerData), lastLogin); + PlayerProfile profileCopy = new PlayerProfile(playerName, uuid, ImmutableMap.copyOf(skills), + ImmutableMap.copyOf(skillsXp), ImmutableMap.copyOf(abilityDATS), + scoreboardTipsShown, ImmutableMap.copyOf(uniquePlayerData), lastLogin); changed = !mcMMO.getDatabaseManager().saveUser(profileCopy); if (changed) { - mcMMO.p.getLogger().severe("PlayerProfile saving failed for player: " + playerName + " " + uuid); + 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."); + mcMMO.p.getLogger().severe("Attempted to save profile for player " + getPlayerName() + + " resulted in failure. " + saveAttempts + " have been made so far."); } if (saveAttempts < 10) { saveAttempts++; //Back out of async saving if we detect a server shutdown, this is not always going to be caught - if (mcMMO.isServerShutdownExecuted() || useSync) - mcMMO.p.getFoliaLib().getScheduler().runNextTick(new PlayerProfileSaveTask(this, true)); - else + if (mcMMO.isServerShutdownExecuted() || useSync) { + mcMMO.p.getFoliaLib().getScheduler() + .runNextTick(new PlayerProfileSaveTask(this, true)); + } else { scheduleAsyncSave(); + } } 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."); } @@ -160,9 +171,12 @@ public class PlayerProfile { } /** - * Get this users last login, will return current java.lang.System#currentTimeMillis() if it doesn't exist + * Get this users last login, will return current java.lang.System#currentTimeMillis() if it + * doesn't exist + * * @return the last login - * @deprecated This is only function for FlatFileDB atm, and it's only here for unit testing right now + * @deprecated This is only function for FlatFileDB atm, and it's only here for unit testing + * right now */ public @NotNull Long getLastLogin() { return Objects.requireNonNullElse(lastLogin, -1L); @@ -215,7 +229,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) { markProfileDirty(); @@ -227,7 +243,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. @@ -341,8 +359,9 @@ public class PlayerProfile { markProfileDirty(); //Don't allow levels to be negative - if (level < 0) + if (level < 0) { level = 0; + } skills.put(skill, level); skillsXp.put(skill, 0F); @@ -380,8 +399,7 @@ public class PlayerProfile { } /** - * Get the registered amount of experience gained - * This is used for diminished XP returns + * Get the registered amount of experience gained This is used for diminished XP returns * * @return xp Experience amount registered */ @@ -396,8 +414,7 @@ public class PlayerProfile { } /** - * Register an experience gain - * This is used for diminished XP returns + * Register an experience gain This is used for diminished XP returns * * @param primarySkillType Skill being used * @param xp Experience amount to add @@ -408,13 +425,13 @@ public class PlayerProfile { } /** - * Remove experience gains older than a given time - * This is used for diminished XP returns + * Remove experience gains older than a given time This is used for diminished XP returns */ public void purgeExpiredXpGains() { SkillXpGain gain; while ((gain = gainedSkillsXp.poll()) != null) { - rollingSkillsXp.put(gain.getSkill(), getRegisteredXpGain(gain.getSkill()) - gain.getXp()); + rollingSkillsXp.put(gain.getSkill(), + getRegisteredXpGain(gain.getSkill()) - gain.getXp()); } } @@ -429,18 +446,21 @@ public class PlayerProfile { return 0; } - int level = (ExperienceConfig.getInstance().getCumulativeCurveEnabled()) ? UserManager.getPlayer(playerName).getPowerLevel() : skills.get(primarySkillType); + int level = (ExperienceConfig.getInstance().getCumulativeCurveEnabled()) + ? UserManager.getPlayer(playerName).getPowerLevel() : skills.get(primarySkillType); FormulaType formulaType = ExperienceConfig.getInstance().getFormulaType(); return mcMMO.getFormulaManager().getXPtoNextLevel(level, formulaType); } - private int getChildSkillLevel(@NotNull PrimarySkillType primarySkillType) throws IllegalArgumentException { + private int getChildSkillLevel(@NotNull PrimarySkillType primarySkillType) + throws IllegalArgumentException { if (!SkillTools.isChildSkill(primarySkillType)) { throw new IllegalArgumentException(primarySkillType + " is not a child skill!"); } - ImmutableList parents = mcMMO.p.getSkillTools().getChildSkillParents(primarySkillType); + ImmutableList parents = mcMMO.p.getSkillTools() + .getChildSkillParents(primarySkillType); int sum = 0; for (PrimarySkillType parent : parents) { diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/MaterialType.java b/src/main/java/com/gmail/nossr50/datatypes/skills/MaterialType.java index 6b00c688e..f66798be9 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/MaterialType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/MaterialType.java @@ -38,10 +38,11 @@ public enum MaterialType { return Material.DIAMOND; case NETHERITE: - if (Material.getMaterial("NETHERITE_SCRAP") != null) + if (Material.getMaterial("NETHERITE_SCRAP") != null) { return Material.getMaterial("NETHERITE_SCRAP"); - else + } else { return Material.DIAMOND; + } case PRISMARINE: return Material.PRISMARINE_CRYSTALS; 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 31f315c1f..a6073fec9 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/PrimarySkillType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/PrimarySkillType.java @@ -4,13 +4,12 @@ import com.gmail.nossr50.config.GeneralConfig; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.skills.SkillTools; +import java.util.ArrayList; +import java.util.List; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.List; - public enum PrimarySkillType { ACROBATICS, ALCHEMY, @@ -32,10 +31,13 @@ public enum PrimarySkillType { WOODCUTTING; /** - * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() + * instead + * * @return the max level of this skill * @see SkillTools#getLevelCap(com.gmail.nossr50.datatypes.skills.PrimarySkillType) - * @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * @deprecated this is being removed in an upcoming update, you should be using + * mcMMO.getSkillTools() instead */ @Deprecated public int getMaxLevel() { @@ -43,10 +45,14 @@ public enum PrimarySkillType { } /** - * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() + * instead + * * @return the max level of this skill - * @see SkillTools#isSuperAbilityUnlocked(com.gmail.nossr50.datatypes.skills.PrimarySkillType, org.bukkit.entity.Player) - * @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * @see SkillTools#isSuperAbilityUnlocked(com.gmail.nossr50.datatypes.skills.PrimarySkillType, + * org.bukkit.entity.Player) + * @deprecated this is being removed in an upcoming update, you should be using + * mcMMO.getSkillTools() instead */ @Deprecated public boolean isSuperAbilityUnlocked(@NotNull Player player) { @@ -54,10 +60,13 @@ public enum PrimarySkillType { } /** - * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() + * instead + * * @return the max level of this skill * @see SkillTools#getPVPEnabled(com.gmail.nossr50.datatypes.skills.PrimarySkillType) - * @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * @deprecated this is being removed in an upcoming update, you should be using + * mcMMO.getSkillTools() instead */ @Deprecated public boolean getPVPEnabled() { @@ -65,10 +74,13 @@ public enum PrimarySkillType { } /** - * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() + * instead + * * @return the max level of this skill * @see SkillTools#getPVEEnabled(com.gmail.nossr50.datatypes.skills.PrimarySkillType) - * @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * @deprecated this is being removed in an upcoming update, you should be using + * mcMMO.getSkillTools() instead */ @Deprecated public boolean getPVEEnabled() { @@ -76,10 +88,13 @@ public enum PrimarySkillType { } /** - * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() + * instead + * * @return the max level of this skill * @see GeneralConfig#getDoubleDropsDisabled(com.gmail.nossr50.datatypes.skills.PrimarySkillType) - * @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * @deprecated this is being removed in an upcoming update, you should be using + * mcMMO.getSkillTools() instead */ @Deprecated public boolean getDoubleDropsDisabled() { @@ -87,10 +102,13 @@ public enum PrimarySkillType { } /** - * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() + * instead + * * @return the max level of this skill * @see SkillTools#getHardcoreStatLossEnabled(com.gmail.nossr50.datatypes.skills.PrimarySkillType) - * @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * @deprecated this is being removed in an upcoming update, you should be using + * mcMMO.getSkillTools() instead */ @Deprecated public boolean getHardcoreStatLossEnabled() { @@ -98,10 +116,13 @@ public enum PrimarySkillType { } /** - * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() + * instead + * * @return the max level of this skill * @see SkillTools#getHardcoreVampirismEnabled(com.gmail.nossr50.datatypes.skills.PrimarySkillType) - * @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * @deprecated this is being removed in an upcoming update, you should be using + * mcMMO.getSkillTools() instead */ @Deprecated public boolean getHardcoreVampirismEnabled() { @@ -109,10 +130,13 @@ public enum PrimarySkillType { } /** - * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() + * instead + * * @return the max level of this skill * @see SkillTools#getPrimarySkillToolType(com.gmail.nossr50.datatypes.skills.PrimarySkillType) - * @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * @deprecated this is being removed in an upcoming update, you should be using + * mcMMO.getSkillTools() instead */ @Deprecated public ToolType getTool() { @@ -120,10 +144,13 @@ public enum PrimarySkillType { } /** - * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() + * instead + * * @return the max level of this skill * @see SkillTools#getSubSkills(com.gmail.nossr50.datatypes.skills.PrimarySkillType) - * @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * @deprecated this is being removed in an upcoming update, you should be using + * mcMMO.getSkillTools() instead */ @Deprecated public List getSkillAbilities() { @@ -131,10 +158,13 @@ public enum PrimarySkillType { } /** - * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() + * instead + * * @return the max level of this skill * @see SkillTools#getXpMultiplier(com.gmail.nossr50.datatypes.skills.PrimarySkillType) - * @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * @deprecated this is being removed in an upcoming update, you should be using + * mcMMO.getSkillTools() instead */ @Deprecated public double getXpModifier() { @@ -142,10 +172,13 @@ public enum PrimarySkillType { } /** - * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() + * instead + * * @return the max level of this skill * @see SkillTools#matchSkill(java.lang.String) - * @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * @deprecated this is being removed in an upcoming update, you should be using + * mcMMO.getSkillTools() instead */ @Deprecated public static PrimarySkillType getSkill(String skillName) { @@ -153,10 +186,13 @@ public enum PrimarySkillType { } /** - * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() + * instead + * * @return the max level of this skill * @see SkillTools#isChildSkill(com.gmail.nossr50.datatypes.skills.PrimarySkillType) - * @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * @deprecated this is being removed in an upcoming update, you should be using + * mcMMO.getSkillTools() instead */ @Deprecated public boolean isChildSkill() { @@ -164,10 +200,13 @@ public enum PrimarySkillType { } /** - * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() + * instead + * * @return the max level of this skill * @see SkillTools#getPrimarySkillBySubSkill(com.gmail.nossr50.datatypes.skills.SubSkillType) - * @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * @deprecated this is being removed in an upcoming update, you should be using + * mcMMO.getSkillTools() instead */ @Deprecated public static PrimarySkillType bySecondaryAbility(SubSkillType subSkillType) { @@ -175,10 +214,13 @@ public enum PrimarySkillType { } /** - * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() + * instead + * * @return the max level of this skill * @see SkillTools#getPrimarySkillBySuperAbility(com.gmail.nossr50.datatypes.skills.SuperAbilityType) - * @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * @deprecated this is being removed in an upcoming update, you should be using + * mcMMO.getSkillTools() instead */ @Deprecated public static PrimarySkillType byAbility(SuperAbilityType superAbilityType) { @@ -186,10 +228,13 @@ public enum PrimarySkillType { } /** - * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() + * instead + * * @return the max level of this skill * @see SkillTools#getLocalizedSkillName(com.gmail.nossr50.datatypes.skills.PrimarySkillType) - * @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * @deprecated this is being removed in an upcoming update, you should be using + * mcMMO.getSkillTools() instead */ @Deprecated public String getName() { @@ -197,9 +242,12 @@ public enum PrimarySkillType { } /** - * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() + * instead + * * @return the max level of this skill - * @see Permissions#skillEnabled(org.bukkit.permissions.Permissible, com.gmail.nossr50.datatypes.skills.PrimarySkillType) + * @see Permissions#skillEnabled(org.bukkit.permissions.Permissible, + * com.gmail.nossr50.datatypes.skills.PrimarySkillType) * @deprecated this is being removed in an upcoming update */ @Deprecated @@ -208,10 +256,14 @@ public enum PrimarySkillType { } /** - * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() + * instead + * * @return the max level of this skill - * @see SkillTools#canCombatSkillsTrigger(com.gmail.nossr50.datatypes.skills.PrimarySkillType, org.bukkit.entity.Entity) - * @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead + * @see SkillTools#canCombatSkillsTrigger(com.gmail.nossr50.datatypes.skills.PrimarySkillType, + * org.bukkit.entity.Entity) + * @deprecated this is being removed in an upcoming update, you should be using + * mcMMO.getSkillTools() instead */ @Deprecated public boolean shouldProcess(Entity target) { diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillFlags.java b/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillFlags.java index ed4626935..47a5edcca 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillFlags.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillFlags.java @@ -6,14 +6,14 @@ public class SubSkillFlags { * These are so I can flag properties for subskills * Flags are in the power of 2 because binary is a base-2 system */ - public static final int ACTIVE = 1; //Active subskills are ones that aren't passive - public static final int SUPERABILITY = 2; // Super abilities are redundantly active - public static final int RNG = 4; //If the subskill makes use of RNG - public static final int PVP = 8; //If the subskill has properties that change in PVP conditions - public static final int TIMED = 16; //If the subskill has a duration or time component - public static final int TARGET_COLLECTION = 32; //If the subskill has multiple target types - public static final int REWARD_COLLECTION = 64; //If the subskill has multiple reward types - public static final int CHARGES = 128; - public static final int LIMITED = 256; + public static final int ACTIVE = 1; //Active subskills are ones that aren't passive + public static final int SUPERABILITY = 2; // Super abilities are redundantly active + public static final int RNG = 4; //If the subskill makes use of RNG + public static final int PVP = 8; //If the subskill has properties that change in PVP conditions + public static final int TIMED = 16; //If the subskill has a duration or time component + public static final int TARGET_COLLECTION = 32; //If the subskill has multiple target types + public static final int REWARD_COLLECTION = 64; //If the subskill has multiple reward types + public static final int CHARGES = 128; + public static final int LIMITED = 256; //public static final int RANDOM_ACTIVATION = 128; //If the subskill has random activation } 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 3af58f56d..210653077 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillType.java @@ -3,7 +3,6 @@ package com.gmail.nossr50.datatypes.skills; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.text.StringUtils; - import java.util.Locale; public enum SubSkillType { @@ -128,6 +127,7 @@ 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) { @@ -143,39 +143,49 @@ public enum SubSkillType { } /** - * !!! This relies on the immutable lists in PrimarySkillType being populated !!! - * If we add skills, those immutable lists need to be updated + * !!! This relies on the immutable lists in PrimarySkillType being populated !!! If we add + * skills, those immutable lists need to be updated + * * @return the parent skill of this subskill */ - public PrimarySkillType getParentSkill() { return mcMMO.p.getSkillTools().getPrimarySkillBySubSkill(this); } + public PrimarySkillType getParentSkill() { + return mcMMO.p.getSkillTools().getPrimarySkillBySubSkill(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() { - return "Skills." + StringUtils.getCapitalized(getParentSkill().toString()) + "." + getConfigName(toString()); + return "Skills." + StringUtils.getCapitalized(getParentSkill().toString()) + "." + + getConfigName(toString()); } /** * 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() { - return StringUtils.getCapitalized(getParentSkill().toString()) + "." + getConfigName(toString()); + return StringUtils.getCapitalized(getParentSkill().toString()) + "." + getConfigName( + toString()); } /** * Get the string representation of the permission node for this subskill + * * @return the permission node for this subskill */ public String getPermissionNodeAddress() { //TODO: This could be optimized - return "mcmmo.ability." + getParentSkill().toString().toLowerCase(Locale.ENGLISH) + "." + getConfigName(toString()).toLowerCase(Locale.ENGLISH); + return "mcmmo.ability." + getParentSkill().toString().toLowerCase(Locale.ENGLISH) + "." + + getConfigName(toString()).toLowerCase(Locale.ENGLISH); } /** * 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) { @@ -202,7 +212,7 @@ public enum SubSkillType { if (subskillNameWithoutPrefix.contains("_")) { String[] splitStrings = subskillNameWithoutPrefix.split("_"); - for(String string : splitStrings) { + for (String string : splitStrings) { endResult.append(StringUtils.getCapitalized(string)); } } else { @@ -222,14 +232,17 @@ 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"); + 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 */ @@ -239,6 +252,7 @@ public enum SubSkillType { /** * 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 */ @@ -258,7 +272,8 @@ public enum SubSkillType { } public String getLocaleKeyRoot() { - return StringUtils.getCapitalized(getParentSkill().toString())+".SubSkill."+getConfigName(toString()); + return StringUtils.getCapitalized(getParentSkill().toString()) + ".SubSkill." + + getConfigName(toString()); } public String getLocaleName() { @@ -269,11 +284,21 @@ public enum SubSkillType { 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 getLocaleStatExtraDescription() { + return getFromLocaleSubAddress(".Stat.Extra"); + } + + public String getLocaleKeyStatExtraDescription() { + return getLocaleKeyFromSubAddress(".Stat.Extra"); + } public String getLocaleStat(String... vars) { return LocaleLoader.getString("Ability.Generic.Template", (Object[]) vars); 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 e7cd4a5d0..04dd1baea 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/SuperAbilityType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/SuperAbilityType.java @@ -112,14 +112,14 @@ public enum SuperAbilityType { */ // TODO: This is stupid 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 final String abilityOn; @@ -130,7 +130,8 @@ public enum SuperAbilityType { private SubSkillType subSkillTypeDefinition; private final String localizedName; - SuperAbilityType(String abilityOn, String abilityOff, String abilityPlayer, String abilityRefresh, String abilityPlayerOff, String localizedName) { + SuperAbilityType(String abilityOn, String abilityOff, String abilityPlayer, + String abilityRefresh, String abilityPlayerOff, String localizedName) { this.abilityOn = abilityOn; this.abilityOff = abilityOff; this.abilityPlayer = abilityPlayer; @@ -215,16 +216,16 @@ public enum SuperAbilityType { case SUPER_BREAKER -> Permissions.superBreaker(player); case TREE_FELLER -> Permissions.treeFeller(player); // TODO: once implemented, return permissions for the following abilities - case EXPLOSIVE_SHOT, TRIDENTS_SUPER_ABILITY, SUPER_SHOTGUN, MACES_SUPER_ABILITY -> false; + case EXPLOSIVE_SHOT, TRIDENTS_SUPER_ABILITY, SUPER_SHOTGUN, MACES_SUPER_ABILITY -> + false; }; } public boolean blockCheck(@NotNull Block block) { return switch (this) { - case BERSERK -> - (BlockUtils.affectedByGigaDrillBreaker(block) - || block.getType() == Material.SNOW - || mcMMO.getMaterialMapStore().isGlass(block.getType())); + case BERSERK -> (BlockUtils.affectedByGigaDrillBreaker(block) + || block.getType() == Material.SNOW + || mcMMO.getMaterialMapStore().isGlass(block.getType())); case GIGA_DRILL_BREAKER -> BlockUtils.affectedByGigaDrillBreaker(block); case GREEN_TERRA -> BlockUtils.canMakeMossy(block); case SUPER_BREAKER -> BlockUtils.affectedBySuperBreaker(block); @@ -235,6 +236,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 214bd703b..9ab8411ba 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 @@ -1,7 +1,13 @@ package com.gmail.nossr50.datatypes.skills.alchemy; +import static com.gmail.nossr50.util.PotionUtil.samePotionType; +import static java.util.Objects.requireNonNull; + import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.PotionUtil; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Objects; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; @@ -9,13 +15,6 @@ import org.bukkit.inventory.meta.PotionMeta; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Objects; - -import static com.gmail.nossr50.util.PotionUtil.samePotionType; -import static java.util.Objects.requireNonNull; - public class AlchemyPotion { private final @NotNull String potionConfigName; private final @NotNull ItemStack potionItemStack; @@ -23,11 +22,13 @@ public class AlchemyPotion { private final @NotNull Map alchemyPotionChildren; public AlchemyPotion(@NotNull String potionConfigName, @NotNull ItemStack potionItemStack, - @NotNull Map alchemyPotionChildren) { + @NotNull Map alchemyPotionChildren) { this.potionConfigName = requireNonNull(potionConfigName, "potionConfigName cannot be null"); this.potionItemStack = requireNonNull(potionItemStack, "potionItemStack cannot be null"); - this.alchemyPotionChildren = requireNonNull(alchemyPotionChildren, "alchemyPotionChildren cannot be null"); - this.potionItemMeta = requireNonNull(potionItemStack.getItemMeta(), "potionItemMeta cannot be null"); // The potion item meta should never be null because it is a potion, but if it is null, then something went terribly wrong + this.alchemyPotionChildren = requireNonNull(alchemyPotionChildren, + "alchemyPotionChildren cannot be null"); + this.potionItemMeta = requireNonNull(potionItemStack.getItemMeta(), + "potionItemMeta cannot be null"); // The potion item meta should never be null because it is a potion, but if it is null, then something went terribly wrong } public @NotNull ItemStack toItemStack(int amount) { @@ -135,10 +136,16 @@ public class AlchemyPotion { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } AlchemyPotion that = (AlchemyPotion) o; - return Objects.equals(potionConfigName, that.potionConfigName) && Objects.equals(potionItemStack, that.potionItemStack) && Objects.equals(alchemyPotionChildren, that.alchemyPotionChildren); + return Objects.equals(potionConfigName, that.potionConfigName) && Objects.equals( + potionItemStack, that.potionItemStack) && Objects.equals(alchemyPotionChildren, + that.alchemyPotionChildren); } @Override 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 7825c717f..471320190 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 @@ -1,11 +1,13 @@ package com.gmail.nossr50.datatypes.skills.alchemy; +import static com.gmail.nossr50.util.PotionUtil.isLong; +import static com.gmail.nossr50.util.PotionUtil.isPotionTypeWater; +import static com.gmail.nossr50.util.PotionUtil.isStrong; + import com.gmail.nossr50.util.PotionUtil; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionEffect; -import static com.gmail.nossr50.util.PotionUtil.*; - public enum PotionStage { FIVE(5), FOUR(4), @@ -63,8 +65,8 @@ public enum PotionStage { if (isStrong(potionMeta)) { stage++; } else if (!potionMeta.getCustomEffects().isEmpty()) { - for (PotionEffect effect : potionMeta.getCustomEffects()){ - if (effect.getAmplifier() > 0){ + for (PotionEffect effect : potionMeta.getCustomEffects()) { + if (effect.getAmplifier() > 0) { stage++; break; } 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..dff03f7da 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 @@ -3,14 +3,15 @@ package com.gmail.nossr50.datatypes.skills.interfaces; import com.gmail.nossr50.datatypes.skills.SubSkillType; /** - * This interface is mostly here to maintain backwards compatibility with other mcMMO plugins - * Only Core Skills will make use of this - * Previously in mcMMO subskills were basically defined by the SecondaryAbility ENUM - * In the new system which I'm gradually converting all the existing skills to, skills instead are unique instances of AbstractSubSkill + * This interface is mostly here to maintain backwards compatibility with other mcMMO plugins Only + * Core Skills will make use of this Previously in mcMMO subskills were basically defined by the + * SecondaryAbility ENUM In the new system which I'm gradually converting all the existing skills + * to, skills instead are unique instances of AbstractSubSkill */ 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..8498a9c79 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 @@ -1,18 +1,20 @@ package com.gmail.nossr50.datatypes.skills.interfaces; /** - * Localized interface represents skills which have localizations - * Skills with localizations will use their localization names/descriptions when being printed + * Localized interface represents skills which have localizations Skills with localizations will use + * their localization names/descriptions when being printed */ 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 e3a448eb0..37cc115a6 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 @@ -1,19 +1,19 @@ package com.gmail.nossr50.datatypes.skills.interfaces; -import org.bukkit.inventory.ItemStack; - import java.util.Collection; +import org.bukkit.inventory.ItemStack; public interface Toolable { /** - * Whether this Skill requires a tool - * Not all skills will require a tool + * Whether 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/subskills/AbstractSubSkill.java b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/AbstractSubSkill.java index 7a933f010..a4c277824 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 @@ -18,7 +18,8 @@ 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 +32,8 @@ 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 +41,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); @@ -56,7 +59,8 @@ public abstract class AbstractSubSkill implements SubSkill, Interaction, Rank, S final Player player = mmoPlayer.getPlayer(); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.Header")); - player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.SubSkillHeader", getConfigKeyName())); + player.sendMessage( + LocaleLoader.getString("Commands.MmoInfo.SubSkillHeader", getConfigKeyName())); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.DetailsHeader")); } 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 df479bb53..7d1848c02 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 @@ -14,21 +14,22 @@ public abstract class AcrobaticsSubSkill extends AbstractSubSkill { protected EventPriority interactionPriority; - public AcrobaticsSubSkill(String configKeySub, EventPriority interactionPriority, SubSkillType subSkillType) { + public AcrobaticsSubSkill(String configKeySub, EventPriority interactionPriority, + SubSkillType subSkillType) { super(configKeySub, "Acrobatics", subSkillType); this.interactionPriority = interactionPriority; } /** - * The name of this subskill - * Core mcMMO skills will pull the name from Locale with this method + * The name of this subskill Core mcMMO skills will pull the name from Locale with this method * * @return the subskill name */ @Override public String getNiceName() { - return LocaleLoader.getString(getPrimaryKeyName()+".SubSkill."+getConfigKeyName()+".Name"); + return LocaleLoader.getString( + getPrimaryKeyName() + ".SubSkill." + getConfigKeyName() + ".Name"); } /** @@ -48,7 +49,9 @@ 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"); } /** @@ -84,7 +87,7 @@ public abstract class AcrobaticsSubSkill extends AbstractSubSkill { /** * 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 */ 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 b4cc9ba74..4b64a8ad1 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 @@ -1,5 +1,10 @@ package com.gmail.nossr50.datatypes.skills.subskills.acrobatics; +import static com.gmail.nossr50.util.player.NotificationManager.sendPlayerInformation; +import static com.gmail.nossr50.util.random.ProbabilityUtil.getSubSkillProbability; +import static com.gmail.nossr50.util.skills.SkillUtils.applyXpGain; +import static com.gmail.nossr50.util.sounds.SoundManager.sendCategorizedSound; + import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.datatypes.experience.XPGainReason; import com.gmail.nossr50.datatypes.interactions.NotificationType; @@ -15,6 +20,7 @@ import com.gmail.nossr50.util.random.Probability; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.sounds.SoundType; +import java.util.Locale; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextComponent; import org.bukkit.Location; @@ -28,13 +34,6 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.VisibleForTesting; -import java.util.Locale; - -import static com.gmail.nossr50.util.player.NotificationManager.sendPlayerInformation; -import static com.gmail.nossr50.util.random.ProbabilityUtil.getSubSkillProbability; -import static com.gmail.nossr50.util.skills.SkillUtils.applyXpGain; -import static com.gmail.nossr50.util.sounds.SoundManager.sendCategorizedSound; - public class Roll extends AcrobaticsSubSkill { @@ -57,19 +56,21 @@ public class Roll extends AcrobaticsSubSkill { //Make sure a real player was damaged in this event if (!EventUtils.isRealPlayerDamaged(entityDamageEvent) - || !entityDamageEvent.isApplicable(EntityDamageEvent.DamageModifier.MAGIC)) + || !entityDamageEvent.isApplicable(EntityDamageEvent.DamageModifier.MAGIC)) { return false; + } if (entityDamageEvent.getCause() == EntityDamageEvent.DamageCause.FALL) { final McMMOPlayer mmoPlayer = EventUtils.getMcMMOPlayer(entityDamageEvent.getEntity()); - if (mmoPlayer == null) + if (mmoPlayer == null) { return false; + } /* * Check for success */ - + if (canRoll(mmoPlayer)) { final RollResult rollResult = rollCheck(mmoPlayer, entityDamageEvent); @@ -84,30 +85,37 @@ public class Roll extends AcrobaticsSubSkill { entityDamageEvent.setDamage(0); // Send the damage is MAGIC so that it cuts through all resistances // This is fine because we considered protection/featherfalling in the rollCheck method - entityDamageEvent.setDamage(EntityDamageEvent.DamageModifier.MAGIC, rollResult.getModifiedDamage()); + entityDamageEvent.setDamage(EntityDamageEvent.DamageModifier.MAGIC, + rollResult.getModifiedDamage()); if (entityDamageEvent.getFinalDamage() == 0) { entityDamageEvent.setCancelled(true); } final String key - = rollResult.isGraceful() ? GRACEFUL_ROLL_ACTIVATED_LOCALE_STR_KEY : ROLL_ACTIVATED_LOCALE_KEY; - sendPlayerInformation(mmoPlayer.getPlayer(), NotificationType.SUBSKILL_MESSAGE, key); + = rollResult.isGraceful() ? GRACEFUL_ROLL_ACTIVATED_LOCALE_STR_KEY + : ROLL_ACTIVATED_LOCALE_KEY; + sendPlayerInformation(mmoPlayer.getPlayer(), NotificationType.SUBSKILL_MESSAGE, + key); sendCategorizedSound(mmoPlayer.getPlayer(), mmoPlayer.getPlayer().getLocation(), - SoundType.ROLL_ACTIVATED, SoundCategory.PLAYERS,0.5F); + SoundType.ROLL_ACTIVATED, SoundCategory.PLAYERS, 0.5F); } if (!rollResult.isExploiting() && rollResult.getXpGain() > 0) { - applyXpGain(mmoPlayer, getPrimarySkill(), rollResult.getXpGain(), XPGainReason.PVE); + applyXpGain(mmoPlayer, getPrimarySkill(), rollResult.getXpGain(), + XPGainReason.PVE); } // Player didn't die, so add the location to the list addFallLocation(mmoPlayer); return true; - // We give Acrobatics XP for fall damage even if they haven't unlocked roll - } else if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(mmoPlayer.getPlayer(), PrimarySkillType.ACROBATICS)) { + // We give Acrobatics XP for fall damage even if they haven't unlocked roll + } else if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(mmoPlayer.getPlayer(), + PrimarySkillType.ACROBATICS)) { //Give XP - applyXpGain(mmoPlayer, getPrimarySkill(), calculateRollXP(mmoPlayer, ((EntityDamageEvent) event).getFinalDamage(), false), XPGainReason.PVE); + applyXpGain(mmoPlayer, getPrimarySkill(), + calculateRollXP(mmoPlayer, ((EntityDamageEvent) event).getFinalDamage(), + false), XPGainReason.PVE); } } @@ -121,7 +129,8 @@ public class Roll extends AcrobaticsSubSkill { */ @Override public String getPermissionNode() { - return ("mcmmo.ability."+getPrimaryKeyName()+"."+getConfigKeyName()).toLowerCase(Locale.ENGLISH); + return ("mcmmo.ability." + getPrimaryKeyName() + "." + getConfigKeyName()).toLowerCase( + Locale.ENGLISH); } /** @@ -149,7 +158,8 @@ public class Roll extends AcrobaticsSubSkill { float skillValue = mmoPlayer.getSkillLevel(getPrimarySkill()); boolean isLucky = Permissions.lucky(mmoPlayer.getPlayer(), getPrimarySkill()); - String[] rollStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.ACROBATICS_ROLL); + String[] rollStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + SubSkillType.ACROBATICS_ROLL); rollChance = rollStrings[0]; rollChanceLucky = rollStrings[1]; @@ -170,20 +180,29 @@ public class Roll extends AcrobaticsSubSkill { componentBuilder.append("\n");*/ //Acrobatics.SubSkill.Roll.Chance - componentBuilder.append(Component.text(LocaleLoader.getString("Acrobatics.SubSkill.Roll.Chance", rollChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", rollChanceLucky) : ""))); + componentBuilder.append(Component.text( + LocaleLoader.getString("Acrobatics.SubSkill.Roll.Chance", rollChance) + (isLucky + ? LocaleLoader.getString("Perks.Lucky.Bonus", rollChanceLucky) : ""))); componentBuilder.append(Component.newline()); - componentBuilder.append(Component.text(LocaleLoader.getString("Acrobatics.SubSkill.Roll.GraceChance", gracefulRollChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", gracefulRollChanceLucky) : ""))); + componentBuilder.append(Component.text( + LocaleLoader.getString("Acrobatics.SubSkill.Roll.GraceChance", gracefulRollChance) + + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", + gracefulRollChanceLucky) : ""))); //Activation Tips - componentBuilder.append(Component.newline()).append(Component.text(LocaleLoader.getString("JSON.Hover.Tips"))).append(Component.newline()); + componentBuilder.append(Component.newline()) + .append(Component.text(LocaleLoader.getString("JSON.Hover.Tips"))) + .append(Component.newline()); componentBuilder.append(Component.text(getTips())); componentBuilder.append(Component.newline()); //Advanced //Lucky Notice if (isLucky) { - componentBuilder.append(Component.text(LocaleLoader.getString("JSON.JWrapper.Perks.Header"))); + componentBuilder.append( + Component.text(LocaleLoader.getString("JSON.JWrapper.Perks.Header"))); componentBuilder.append(Component.newline()); - componentBuilder.append(Component.text(LocaleLoader.getString("JSON.JWrapper.Perks.Lucky", "33"))); + componentBuilder.append( + Component.text(LocaleLoader.getString("JSON.JWrapper.Perks.Lucky", "33"))); } } @@ -211,14 +230,16 @@ public class Roll extends AcrobaticsSubSkill { @VisibleForTesting public boolean canRoll(McMMOPlayer mmoPlayer) { return RankUtils.hasUnlockedSubskill(mmoPlayer.getPlayer(), SubSkillType.ACROBATICS_ROLL) - && Permissions.isSubSkillEnabled(mmoPlayer.getPlayer(), SubSkillType.ACROBATICS_ROLL); + && Permissions.isSubSkillEnabled(mmoPlayer.getPlayer(), + SubSkillType.ACROBATICS_ROLL); } /** * Handle the damage reduction and XP gain from the Roll / Graceful Roll ability * * @param entityDamageEvent the event to modify in the event of roll success - * @return the modified event damage if the ability was successful, the original event damage otherwise + * @return the modified event damage if the ability was successful, the original event damage + * otherwise */ @VisibleForTesting public RollResult rollCheck(McMMOPlayer mmoPlayer, EntityDamageEvent entityDamageEvent) { @@ -227,7 +248,8 @@ public class Roll extends AcrobaticsSubSkill { final RollResult.Builder rollResultBuilder = new RollResult.Builder(entityDamageEvent, isGraceful); final Probability probability - = isGraceful ? getGracefulProbability(mmoPlayer) : getNonGracefulProbability(mmoPlayer); + = isGraceful ? getGracefulProbability(mmoPlayer) + : getNonGracefulProbability(mmoPlayer); double modifiedDamage = calculateModifiedRollDamage(baseDamage, mcMMO.p.getAdvancedConfig().getRollDamageThreshold() * 2); @@ -237,7 +259,8 @@ public class Roll extends AcrobaticsSubSkill { rollResultBuilder.exploiting(isExploiting); // They Rolled if (!isFatal(mmoPlayer, modifiedDamage) - && ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.ACROBATICS, mmoPlayer, probability)) { + && ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.ACROBATICS, + mmoPlayer, probability)) { rollResultBuilder.rollSuccess(true); rollResultBuilder.exploiting(isExploiting); final boolean canGainXp = mmoPlayer.getAcrobaticsManager().canGainRollXP(); @@ -247,7 +270,7 @@ public class Roll extends AcrobaticsSubSkill { } return rollResultBuilder.build(); - // They did not roll, but they also did not die so reward XP as appropriate + // They did not roll, but they also did not die so reward XP as appropriate } else if (!isFatal(mmoPlayer, baseDamage)) { rollResultBuilder.rollSuccess(false); final boolean canGainXp = mmoPlayer.getAcrobaticsManager().canGainRollXP(); @@ -263,18 +286,19 @@ public class Roll extends AcrobaticsSubSkill { @NotNull public static Probability getGracefulProbability(McMMOPlayer mmoPlayer) { - double gracefulOdds = getSubSkillProbability(SubSkillType.ACROBATICS_ROLL, mmoPlayer).getValue() * 2; + double gracefulOdds = + getSubSkillProbability(SubSkillType.ACROBATICS_ROLL, mmoPlayer).getValue() * 2; return Probability.ofValue(gracefulOdds); } public static Probability getNonGracefulProbability(McMMOPlayer mmoPlayer) { - double gracefulOdds = getSubSkillProbability(SubSkillType.ACROBATICS_ROLL, mmoPlayer).getValue(); + double gracefulOdds = getSubSkillProbability(SubSkillType.ACROBATICS_ROLL, + mmoPlayer).getValue(); return Probability.ofValue(gracefulOdds); } /** - * Check if the player is "farming" Acrobatics XP using - * exploits in the game. + * Check if the player is "farming" Acrobatics XP using exploits in the game. * * @return true if exploits are detected, false otherwise */ @@ -283,16 +307,20 @@ public class Roll extends AcrobaticsSubSkill { return false; } - if (ItemUtils.hasItemInEitherHand(mmoPlayer.getPlayer(), Material.ENDER_PEARL) || mmoPlayer.getPlayer().isInsideVehicle()) { + if (ItemUtils.hasItemInEitherHand(mmoPlayer.getPlayer(), Material.ENDER_PEARL) + || mmoPlayer.getPlayer().isInsideVehicle()) { if (mmoPlayer.isDebugMode()) { - mmoPlayer.getPlayer().sendMessage("Acrobatics XP Prevented: Ender Pearl or Inside Vehicle"); + mmoPlayer.getPlayer() + .sendMessage("Acrobatics XP Prevented: Ender Pearl or Inside Vehicle"); } return true; } - if (mmoPlayer.getAcrobaticsManager().hasFallenInLocationBefore(getBlockLocation(mmoPlayer))) { + if (mmoPlayer.getAcrobaticsManager() + .hasFallenInLocationBefore(getBlockLocation(mmoPlayer))) { if (mmoPlayer.isDebugMode()) { - mmoPlayer.getPlayer().sendMessage("Acrobatics XP Prevented: Fallen in location before"); + mmoPlayer.getPlayer() + .sendMessage("Acrobatics XP Prevented: Fallen in location before"); } return true; @@ -306,9 +334,11 @@ public class Roll extends AcrobaticsSubSkill { damage = Math.min(20, damage); ItemStack boots = mmoPlayer.getPlayer().getInventory().getBoots(); - float xp = (float) (damage * (isRoll ? ExperienceConfig.getInstance().getRollXPModifier() : ExperienceConfig.getInstance().getFallXPModifier())); + float xp = (float) (damage * (isRoll ? ExperienceConfig.getInstance().getRollXPModifier() + : ExperienceConfig.getInstance().getFallXPModifier())); - if (boots != null && boots.containsEnchantment(mcMMO.p.getEnchantmentMapper().getFeatherFalling())) { + if (boots != null && boots.containsEnchantment( + mcMMO.p.getEnchantmentMapper().getFeatherFalling())) { xp *= ExperienceConfig.getInstance().getFeatherFallXPModifier(); } @@ -347,7 +377,7 @@ public class Roll extends AcrobaticsSubSkill { //player.sendMessage(getDescription()); //Player stats mmoPlayer.getPlayer().sendMessage(LocaleLoader.getString("Commands.MmoInfo.Stats", - LocaleLoader.getString("Acrobatics.SubSkill.Roll.Stats", getStats(mmoPlayer)))); + LocaleLoader.getString("Acrobatics.SubSkill.Roll.Stats", getStats(mmoPlayer)))); //Mechanics mmoPlayer.getPlayer().sendMessage(LocaleLoader.getString("Commands.MmoInfo.Mechanics")); @@ -370,7 +400,7 @@ public class Roll extends AcrobaticsSubSkill { double playerChanceRoll = getSubSkillProbability(subSkillType, mmoPlayer).getValue(); double playerChanceGrace = playerChanceRoll * 2; - return new Double[]{ playerChanceRoll, playerChanceGrace }; + return new Double[]{playerChanceRoll, playerChanceGrace}; } public void addFallLocation(@NotNull McMMOPlayer mmoPlayer) { diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/RollResult.java b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/RollResult.java index e2ee88578..b1742d35f 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/RollResult.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/RollResult.java @@ -1,9 +1,9 @@ package com.gmail.nossr50.datatypes.skills.subskills.acrobatics; -import org.bukkit.event.entity.EntityDamageEvent; - import static java.util.Objects.requireNonNull; +import org.bukkit.event.entity.EntityDamageEvent; + /** * Immutable class representing the result of a roll action in acrobatics. */ @@ -70,7 +70,7 @@ public class RollResult { * Constructs a new {@code Builder} with required parameters. * * @param entityDamageEvent the damage event, must not be null - * @param isGracefulRoll whether the roll is graceful + * @param isGracefulRoll whether the roll is graceful */ public Builder(EntityDamageEvent entityDamageEvent, boolean isGracefulRoll) { requireNonNull(entityDamageEvent, "EntityDamageEvent cannot be null"); 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..fed55dca4 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,12 +7,14 @@ 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 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 4729ae454..4bb0c6d33 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 9a3c49e30..2da1dda84 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 @@ -8,18 +8,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 mmoPlayer target player * @return stat array for target player for this skill */ @@ -27,38 +30,43 @@ 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 */ boolean hasPermission(Player player); /** - * The name of this subskill - * It's a good idea for this to return the localized name + * 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 mmoPlayer owner of this skill */ @@ -66,12 +74,14 @@ public interface SubSkill extends Skill { /** * Whether this subskill is enabled + * * @return true if enabled */ boolean isEnabled(); /** * Prints detailed info about this subskill to the player + * * @param mmoPlayer the target player */ void printInfo(McMMOPlayer mmoPlayer); diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/taming/CallOfTheWildType.java b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/taming/CallOfTheWildType.java index 9e1749adc..4794fd0ac 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/taming/CallOfTheWildType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/taming/CallOfTheWildType.java @@ -11,9 +11,10 @@ public enum CallOfTheWildType { //TODO: This is a hacky fix to make the COTW code in 2.1 more bearable, this will be removed upon the rework planned for COTW public String getConfigEntityTypeEntry() { - switch(this) { + switch (this) { case CAT: - return StringUtils.getPrettyEntityTypeString(EntityType.OCELOT); //Even though cats will be summoned in 1.14, we specify Ocelot here. This will be gone in 2.2 + return StringUtils.getPrettyEntityTypeString( + EntityType.OCELOT); //Even though cats will be summoned in 1.14, we specify Ocelot here. This will be gone in 2.2 case WOLF: return StringUtils.getPrettyEntityTypeString(EntityType.WOLF); case HORSE: diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/taming/TamingSummon.java b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/taming/TamingSummon.java index 1c39fed2f..fb0cfc159 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/taming/TamingSummon.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/taming/TamingSummon.java @@ -16,7 +16,8 @@ public class TamingSummon { private final CallOfTheWildType callOfTheWildType; private EntityType entityType; - public TamingSummon(CallOfTheWildType callOfTheWildType, Material itemType, int itemAmountRequired, int entitiesSummoned, int summonLifespan, int summonCap) { + public TamingSummon(CallOfTheWildType callOfTheWildType, Material itemType, + int itemAmountRequired, int entitiesSummoned, int summonLifespan, int summonCap) { this.callOfTheWildType = callOfTheWildType; this.itemType = itemType; this.itemAmountRequired = Math.max(itemAmountRequired, 1); @@ -28,7 +29,7 @@ public class TamingSummon { } private void initEntityType() { - switch(callOfTheWildType) { + switch (callOfTheWildType) { case WOLF: entityType = EntityType.WOLF; break; diff --git a/src/main/java/com/gmail/nossr50/datatypes/treasure/EnchantmentWrapper.java b/src/main/java/com/gmail/nossr50/datatypes/treasure/EnchantmentWrapper.java index c442b4179..f283f2b61 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/treasure/EnchantmentWrapper.java +++ b/src/main/java/com/gmail/nossr50/datatypes/treasure/EnchantmentWrapper.java @@ -31,10 +31,15 @@ public class EnchantmentWrapper { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } EnchantmentWrapper that = (EnchantmentWrapper) o; - return enchantmentLevel == that.enchantmentLevel && Objects.equal(enchantment, that.enchantment); + return enchantmentLevel == that.enchantmentLevel && Objects.equal(enchantment, + that.enchantment); } @Override diff --git a/src/main/java/com/gmail/nossr50/datatypes/treasure/FishingTreasureBook.java b/src/main/java/com/gmail/nossr50/datatypes/treasure/FishingTreasureBook.java index efe7d1f9c..c797a9815 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/treasure/FishingTreasureBook.java +++ b/src/main/java/com/gmail/nossr50/datatypes/treasure/FishingTreasureBook.java @@ -2,21 +2,22 @@ package com.gmail.nossr50.datatypes.treasure; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.LogUtils; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - public class FishingTreasureBook extends FishingTreasure { private final @Nullable Set blackListedEnchantments; private final @Nullable Set whiteListedEnchantments; private final @NotNull List legalEnchantments; //TODO: Make immutable - public FishingTreasureBook(@NotNull ItemStack enchantedBook, int xp, @Nullable Set blackListedEnchantments, @Nullable Set whiteListedEnchantments) { + public FishingTreasureBook(@NotNull ItemStack enchantedBook, int xp, + @Nullable Set blackListedEnchantments, + @Nullable Set whiteListedEnchantments) { super(enchantedBook, xp); this.blackListedEnchantments = blackListedEnchantments; @@ -29,7 +30,7 @@ public class FishingTreasureBook extends FishingTreasure { private void initLegalEnchantments() { LogUtils.debug(mcMMO.p.getLogger(), "Registering enchantments for Fishing Book..."); - for(Enchantment enchantment : Enchantment.values()) { + for (Enchantment enchantment : Enchantment.values()) { if (isEnchantAllowed(enchantment)) { addAllLegalEnchants(enchantment); } @@ -37,8 +38,8 @@ public class FishingTreasureBook extends FishingTreasure { } /** - * Get all the enchantments which can drop for this book - * This list can be empty, but should in practice never be empty... + * Get all the enchantments which can drop for this book This list can be empty, but should in + * practice never be empty... * * @return all the enchantments that can drop for this book */ @@ -57,9 +58,10 @@ public class FishingTreasureBook extends FishingTreasure { private void addAllLegalEnchants(@NotNull Enchantment enchantment) { int legalEnchantCap = enchantment.getMaxLevel(); - for(int i = 0; i < legalEnchantCap; i++) { - int enchantLevel = i+1; - EnchantmentWrapper enchantmentWrapper = new EnchantmentWrapper(enchantment, enchantLevel); + for (int i = 0; i < legalEnchantCap; i++) { + int enchantLevel = i + 1; + EnchantmentWrapper enchantmentWrapper = new EnchantmentWrapper(enchantment, + enchantLevel); legalEnchantments.add(enchantmentWrapper); // mcMMO.p.getLogger().info("Fishing treasure book enchantment added: " + enchantmentWrapper); } 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 0ff04bdbd..f21cda3b8 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/treasure/Rarity.java +++ b/src/main/java/com/gmail/nossr50/datatypes/treasure/Rarity.java @@ -13,13 +13,13 @@ public enum Rarity { public static @NotNull Rarity getRarity(@NotNull String string) { if (string.equalsIgnoreCase("Records")) { - mcMMO.p.getLogger().severe("Entries in fishing treasures have Records set as rarity, however Records was renamed to Mythic. Please update your treasures to read MYTHIC instead of RECORDS for rarity, or delete the config file to regenerate a new one."); + mcMMO.p.getLogger() + .severe("Entries in fishing treasures have Records set as rarity, however Records was renamed to Mythic. Please update your treasures to read MYTHIC instead of RECORDS for rarity, or delete the config file to regenerate a new one."); return Rarity.MYTHIC; //People that copy paste their configs will have Records interpretted as Mythic } 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 659a94fc1..cc1660548 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/treasure/Treasure.java +++ b/src/main/java/com/gmail/nossr50/datatypes/treasure/Treasure.java @@ -70,10 +70,16 @@ public abstract class Treasure { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } Treasure treasure = (Treasure) o; - return xp == treasure.xp && Double.compare(treasure.dropChance, dropChance) == 0 && dropLevel == treasure.dropLevel && Objects.equal(dropProbability, treasure.dropProbability) && Objects.equal(drop, treasure.drop); + return xp == treasure.xp && Double.compare(treasure.dropChance, dropChance) == 0 + && dropLevel == treasure.dropLevel && Objects.equal(dropProbability, + treasure.dropProbability) && Objects.equal(drop, treasure.drop); } @Override diff --git a/src/main/java/com/gmail/nossr50/events/McMMOReplaceVanillaTreasureEvent.java b/src/main/java/com/gmail/nossr50/events/McMMOReplaceVanillaTreasureEvent.java index dfbbe7348..80aa0a2f2 100644 --- a/src/main/java/com/gmail/nossr50/events/McMMOReplaceVanillaTreasureEvent.java +++ b/src/main/java/com/gmail/nossr50/events/McMMOReplaceVanillaTreasureEvent.java @@ -13,17 +13,21 @@ public class McMMOReplaceVanillaTreasureEvent extends Event { private final @NotNull Item originalItem; private final @Nullable Player causingPlayer; - public McMMOReplaceVanillaTreasureEvent(@NotNull Item originalItem, @NotNull ItemStack replacementItemStack) { + public McMMOReplaceVanillaTreasureEvent(@NotNull Item originalItem, + @NotNull ItemStack replacementItemStack) { this(originalItem, replacementItemStack, null); } - public McMMOReplaceVanillaTreasureEvent(@NotNull Item originalItem, @NotNull ItemStack replacementItemStack, @Nullable Player causingPlayer) { + public McMMOReplaceVanillaTreasureEvent(@NotNull Item originalItem, + @NotNull ItemStack replacementItemStack, @Nullable Player causingPlayer) { this.originalItem = originalItem; this.replacementItemStack = replacementItemStack; this.causingPlayer = causingPlayer; } - /** Rest of file is required boilerplate for custom events **/ + /** + * Rest of file is required boilerplate for custom events + **/ private static final @NotNull HandlerList handlers = new HandlerList(); @Override diff --git a/src/main/java/com/gmail/nossr50/events/chat/McMMOAdminChatEvent.java b/src/main/java/com/gmail/nossr50/events/chat/McMMOAdminChatEvent.java index 921fdd7fa..190df18ee 100644 --- a/src/main/java/com/gmail/nossr50/events/chat/McMMOAdminChatEvent.java +++ b/src/main/java/com/gmail/nossr50/events/chat/McMMOAdminChatEvent.java @@ -8,7 +8,8 @@ import org.jetbrains.annotations.NotNull; * Called when a chat is sent to the admin chat channel */ public class McMMOAdminChatEvent extends McMMOChatEvent { - public McMMOAdminChatEvent(@NotNull Plugin plugin, @NotNull AbstractChatMessage chatMessage, boolean isAsync) { + public McMMOAdminChatEvent(@NotNull Plugin plugin, @NotNull AbstractChatMessage chatMessage, + boolean isAsync) { super(plugin, chatMessage, isAsync); } } 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 5f9980398..85b8e677d 100644 --- a/src/main/java/com/gmail/nossr50/events/chat/McMMOChatEvent.java +++ b/src/main/java/com/gmail/nossr50/events/chat/McMMOChatEvent.java @@ -18,7 +18,8 @@ public abstract class McMMOChatEvent extends Event implements Cancellable { protected final @NotNull Plugin plugin; protected final @NotNull AbstractChatMessage chatMessage; - protected McMMOChatEvent(@NotNull Plugin plugin, @NotNull AbstractChatMessage chatMessage, boolean isAsync) { + protected McMMOChatEvent(@NotNull Plugin plugin, @NotNull AbstractChatMessage chatMessage, + boolean isAsync) { super(isAsync); this.plugin = plugin; this.chatMessage = chatMessage; @@ -59,8 +60,9 @@ public abstract class McMMOChatEvent extends Event implements Cancellable { } /** - * The name of the author - * Will return the display name if mcMMO chat config is set to, otherwise returns the players Mojang registered nickname + * The name of the author Will return the display name if mcMMO chat config is set to, otherwise + * returns the players Mojang registered nickname + * * @return the author's name */ public @NotNull String getDisplayName(ChatChannel chatChannel) { @@ -79,8 +81,7 @@ public abstract class McMMOChatEvent extends Event implements Cancellable { } /** - * The original message typed by the player before any formatting - * The raw message is immutable + * The original message typed by the player before any formatting The raw message is immutable * * @return the message as it was typed by the player, this is before any formatting */ @@ -89,7 +90,8 @@ public abstract class McMMOChatEvent extends Event implements Cancellable { } /** - * The {@link TextComponent} as it will be sent to all players which should include formatting such as adding chat prefixes, player names, etc + * The {@link TextComponent} as it will be sent to all players which should include formatting + * such as adding chat prefixes, player names, etc * * @return the message that will be sent to the {@link Audience} */ @@ -98,7 +100,8 @@ public abstract class McMMOChatEvent extends Event implements Cancellable { } /** - * This will be the final message sent to the audience, this should be the message after its been formatted and has had player names added to it etc + * This will be the final message sent to the audience, this should be the message after its + * been formatted and has had player names added to it etc * * @param chatMessage the new chat message */ @@ -108,7 +111,6 @@ public abstract class McMMOChatEvent extends Event implements Cancellable { /** * @param message Adjusts the final message sent to players in the party - * * @deprecated use {{@link #setMessagePayload(TextComponent)}} */ @Deprecated @@ -116,7 +118,9 @@ public abstract class McMMOChatEvent extends Event implements Cancellable { chatMessage.setChatMessage(Component.text(message)); } - /** Following are required for Cancellable **/ + /** + * Following are required for Cancellable + **/ @Override public boolean isCancelled() { return cancelled; @@ -127,7 +131,9 @@ public abstract class McMMOChatEvent extends Event implements Cancellable { this.cancelled = cancelled; } - /** Rest of file is required boilerplate for custom events **/ + /** + * Rest of file is required boilerplate for custom events + **/ private static final @NotNull HandlerList handlers = new HandlerList(); @Override @@ -141,6 +147,7 @@ public abstract class McMMOChatEvent extends Event implements Cancellable { /** * The {@link ChatMessage} + * * @return the chat message */ public @NotNull ChatMessage getChatMessage() { diff --git a/src/main/java/com/gmail/nossr50/events/chat/McMMOPartyChatEvent.java b/src/main/java/com/gmail/nossr50/events/chat/McMMOPartyChatEvent.java index 1f00c6763..46d897014 100644 --- a/src/main/java/com/gmail/nossr50/events/chat/McMMOPartyChatEvent.java +++ b/src/main/java/com/gmail/nossr50/events/chat/McMMOPartyChatEvent.java @@ -12,7 +12,8 @@ public class McMMOPartyChatEvent extends McMMOChatEvent { private final @NotNull String party; //Not going to break the API to rename this for now private final @NotNull Party targetParty; - public McMMOPartyChatEvent(@NotNull Plugin pluginRef, @NotNull PartyChatMessage chatMessage, @NotNull Party party, boolean isAsync) { + public McMMOPartyChatEvent(@NotNull Plugin pluginRef, @NotNull PartyChatMessage chatMessage, + @NotNull Party party, boolean isAsync) { super(pluginRef, chatMessage, isAsync); this.party = party.getName(); this.targetParty = party; @@ -20,7 +21,6 @@ public class McMMOPartyChatEvent extends McMMOChatEvent { /** * @return String name of the party the message will be sent to - * * @deprecated this will be removed in the future */ @Deprecated 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 f278143cd..fc84e7884 100644 --- a/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerExperienceEvent.java +++ b/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerExperienceEvent.java @@ -26,7 +26,8 @@ public abstract class McMMOPlayerExperienceEvent extends PlayerEvent implements this.xpGainReason = XPGainReason.UNKNOWN; } - protected McMMOPlayerExperienceEvent(Player player, PrimarySkillType skill, XPGainReason xpGainReason) { + protected McMMOPlayerExperienceEvent(Player player, PrimarySkillType skill, + XPGainReason xpGainReason) { super(player); this.skill = skill; @@ -60,7 +61,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; @@ -70,7 +73,7 @@ public abstract class McMMOPlayerExperienceEvent extends PlayerEvent implements public void setCancelled(boolean cancelled) { this.cancelled = cancelled; } - + private static final HandlerList handlers = new HandlerList(); @Override diff --git a/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerLevelChangeEvent.java b/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerLevelChangeEvent.java index bf23d4443..8b0dc62da 100644 --- a/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerLevelChangeEvent.java +++ b/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerLevelChangeEvent.java @@ -13,7 +13,8 @@ public abstract class McMMOPlayerLevelChangeEvent extends McMMOPlayerExperienceE super(player, skill, XPGainReason.UNKNOWN); } - public McMMOPlayerLevelChangeEvent(Player player, PrimarySkillType skill, XPGainReason xpGainReason) { + public McMMOPlayerLevelChangeEvent(Player player, PrimarySkillType skill, + XPGainReason xpGainReason) { super(player, skill, xpGainReason); } } 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 6e512b338..01a5530aa 100644 --- a/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerLevelDownEvent.java +++ b/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerLevelDownEvent.java @@ -24,12 +24,14 @@ public class McMMOPlayerLevelDownEvent extends McMMOPlayerLevelChangeEvent { this.levelsLost = levelsLost; } - public McMMOPlayerLevelDownEvent(Player player, PrimarySkillType skill, XPGainReason xpGainReason) { + public McMMOPlayerLevelDownEvent(Player player, PrimarySkillType skill, + XPGainReason xpGainReason) { super(player, skill, xpGainReason); this.levelsLost = 1; } - public McMMOPlayerLevelDownEvent(Player player, PrimarySkillType skill, int levelsLost, XPGainReason xpGainReason) { + public McMMOPlayerLevelDownEvent(Player player, PrimarySkillType skill, int levelsLost, + XPGainReason xpGainReason) { super(player, skill, xpGainReason); this.levelsLost = levelsLost; } 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 20badcf7c..ed269e41c 100644 --- a/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerLevelUpEvent.java +++ b/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerLevelUpEvent.java @@ -24,12 +24,14 @@ public class McMMOPlayerLevelUpEvent extends McMMOPlayerLevelChangeEvent { this.levelsGained = levelsGained; } - public McMMOPlayerLevelUpEvent(Player player, PrimarySkillType skill, XPGainReason xpGainReason) { + public McMMOPlayerLevelUpEvent(Player player, PrimarySkillType skill, + XPGainReason xpGainReason) { super(player, skill, xpGainReason); this.levelsGained = 1; } - public McMMOPlayerLevelUpEvent(Player player, PrimarySkillType skill, int levelsGained, XPGainReason xpGainReason) { + public McMMOPlayerLevelUpEvent(Player player, PrimarySkillType skill, int levelsGained, + XPGainReason xpGainReason) { super(player, skill, xpGainReason); this.levelsGained = levelsGained; } diff --git a/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerPreXpGainEvent.java b/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerPreXpGainEvent.java index 849d7ab48..a9eb3505b 100644 --- a/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerPreXpGainEvent.java +++ b/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerPreXpGainEvent.java @@ -18,7 +18,8 @@ public class McMMOPlayerPreXpGainEvent extends McMMOPlayerExperienceEvent { this.xpGained = xpGained; } - public McMMOPlayerPreXpGainEvent(Player player, PrimarySkillType skill, float xpGained, XPGainReason xpGainReason) { + public McMMOPlayerPreXpGainEvent(Player player, PrimarySkillType skill, float xpGained, + XPGainReason xpGainReason) { super(player, skill, xpGainReason); this.xpGained = xpGained; } 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 5cd0c73fa..1cfcef292 100644 --- a/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerXpGainEvent.java +++ b/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerXpGainEvent.java @@ -18,7 +18,8 @@ public class McMMOPlayerXpGainEvent extends McMMOPlayerExperienceEvent { this.xpGained = xpGained; } - public McMMOPlayerXpGainEvent(Player player, PrimarySkillType skill, float xpGained, XPGainReason xpGainReason) { + public McMMOPlayerXpGainEvent(Player player, PrimarySkillType skill, float xpGained, + XPGainReason xpGainReason) { super(player, skill, xpGainReason); this.xpGained = xpGained; } diff --git a/src/main/java/com/gmail/nossr50/events/fake/FakeBlockDamageEvent.java b/src/main/java/com/gmail/nossr50/events/fake/FakeBlockDamageEvent.java index 0e32ce00c..d756a5653 100644 --- a/src/main/java/com/gmail/nossr50/events/fake/FakeBlockDamageEvent.java +++ b/src/main/java/com/gmail/nossr50/events/fake/FakeBlockDamageEvent.java @@ -9,7 +9,8 @@ import org.bukkit.inventory.ItemStack; * Called when mcMMO damages a block due to a special ability. */ public class FakeBlockDamageEvent extends BlockDamageEvent implements FakeEvent { - public FakeBlockDamageEvent(Player player, Block block, ItemStack itemInHand, boolean instaBreak) { + public FakeBlockDamageEvent(Player player, Block block, ItemStack itemInHand, + boolean instaBreak) { super(player, block, itemInHand, instaBreak); } } diff --git a/src/main/java/com/gmail/nossr50/events/fake/FakeBrewEvent.java b/src/main/java/com/gmail/nossr50/events/fake/FakeBrewEvent.java index ea44f355a..4ba86c465 100644 --- a/src/main/java/com/gmail/nossr50/events/fake/FakeBrewEvent.java +++ b/src/main/java/com/gmail/nossr50/events/fake/FakeBrewEvent.java @@ -1,14 +1,14 @@ package com.gmail.nossr50.events.fake; +import java.util.List; import org.bukkit.block.Block; import org.bukkit.event.inventory.BrewEvent; import org.bukkit.inventory.BrewerInventory; import org.bukkit.inventory.ItemStack; -import java.util.List; - public class FakeBrewEvent extends BrewEvent implements FakeEvent { - public FakeBrewEvent(Block brewer, BrewerInventory contents, List results, int fuelLevel) { + public FakeBrewEvent(Block brewer, BrewerInventory contents, List results, + int fuelLevel) { super(brewer, contents, results, fuelLevel); } } diff --git a/src/main/java/com/gmail/nossr50/events/fake/FakeEvent.java b/src/main/java/com/gmail/nossr50/events/fake/FakeEvent.java index 62e989326..b15fed073 100644 --- a/src/main/java/com/gmail/nossr50/events/fake/FakeEvent.java +++ b/src/main/java/com/gmail/nossr50/events/fake/FakeEvent.java @@ -3,9 +3,8 @@ package com.gmail.nossr50.events.fake; import org.bukkit.event.Event; /** - * This interface marks an {@link Event} as "fake". - * This is just a handy way of checking if an {@link Event} is fake or not, maybe there - * will be methods suitable for this in the future. - * + * This interface marks an {@link Event} as "fake". This is just a handy way of checking if an + * {@link Event} is fake or not, maybe there will be methods suitable for this in the future. */ -public interface FakeEvent {} +public interface FakeEvent { +} diff --git a/src/main/java/com/gmail/nossr50/events/fake/FakePlayerAnimationEvent.java b/src/main/java/com/gmail/nossr50/events/fake/FakePlayerAnimationEvent.java index e4eb1ec88..ce89f20e1 100644 --- a/src/main/java/com/gmail/nossr50/events/fake/FakePlayerAnimationEvent.java +++ b/src/main/java/com/gmail/nossr50/events/fake/FakePlayerAnimationEvent.java @@ -4,7 +4,7 @@ //import org.bukkit.event.player.PlayerAnimationEvent; //import org.bukkit.event.player.PlayerAnimationType; // -///** +/// ** // * Called when handling extra drops to avoid issues with NoCheat. // */ //public class FakePlayerAnimationEvent extends PlayerAnimationEvent implements FakeEvent { 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 7c4d3f08a..77814aa37 100644 --- a/src/main/java/com/gmail/nossr50/events/hardcore/McMMOPlayerDeathPenaltyEvent.java +++ b/src/main/java/com/gmail/nossr50/events/hardcore/McMMOPlayerDeathPenaltyEvent.java @@ -1,20 +1,20 @@ package com.gmail.nossr50.events.hardcore; +import java.util.HashMap; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; import org.jetbrains.annotations.NotNull; -import java.util.HashMap; - public class McMMOPlayerDeathPenaltyEvent extends PlayerEvent implements Cancellable { private HashMap levelChanged; private HashMap experienceChanged; private boolean cancelled; - public McMMOPlayerDeathPenaltyEvent(Player player, HashMap levelChanged, HashMap experienceChanged) { + public McMMOPlayerDeathPenaltyEvent(Player player, HashMap levelChanged, + HashMap experienceChanged) { super(player); this.levelChanged = levelChanged; this.experienceChanged = experienceChanged; @@ -43,7 +43,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; @@ -54,7 +56,9 @@ public class McMMOPlayerDeathPenaltyEvent extends PlayerEvent implements Cancell this.cancelled = cancelled; } - /** Rest of file is required boilerplate for custom events **/ + /** + * Rest of file is required boilerplate for custom events + **/ private static final HandlerList handlers = new HandlerList(); @Override 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 7bf355da0..5c7301cba 100644 --- a/src/main/java/com/gmail/nossr50/events/hardcore/McMMOPlayerPreDeathPenaltyEvent.java +++ b/src/main/java/com/gmail/nossr50/events/hardcore/McMMOPlayerPreDeathPenaltyEvent.java @@ -14,7 +14,9 @@ public class McMMOPlayerPreDeathPenaltyEvent extends PlayerEvent implements Canc this.cancelled = false; } - /** Following are required for Cancellable **/ + /** + * Following are required for Cancellable + **/ @Override public boolean isCancelled() { return cancelled; @@ -25,7 +27,9 @@ public class McMMOPlayerPreDeathPenaltyEvent extends PlayerEvent implements Canc this.cancelled = cancelled; } - /** Rest of file is required boilerplate for custom events **/ + /** + * Rest of file is required boilerplate for custom events + **/ private static final HandlerList handlers = new HandlerList(); @Override diff --git a/src/main/java/com/gmail/nossr50/events/hardcore/McMMOPlayerStatLossEvent.java b/src/main/java/com/gmail/nossr50/events/hardcore/McMMOPlayerStatLossEvent.java index 414ffdac5..e204b1014 100644 --- a/src/main/java/com/gmail/nossr50/events/hardcore/McMMOPlayerStatLossEvent.java +++ b/src/main/java/com/gmail/nossr50/events/hardcore/McMMOPlayerStatLossEvent.java @@ -1,12 +1,12 @@ package com.gmail.nossr50.events.hardcore; -import org.bukkit.entity.Player; - import java.util.HashMap; +import org.bukkit.entity.Player; public class McMMOPlayerStatLossEvent extends McMMOPlayerDeathPenaltyEvent { - public McMMOPlayerStatLossEvent(Player player, HashMap levelChanged, HashMap experienceChanged) { + public McMMOPlayerStatLossEvent(Player player, HashMap levelChanged, + HashMap experienceChanged) { super(player, levelChanged, experienceChanged); } } diff --git a/src/main/java/com/gmail/nossr50/events/hardcore/McMMOPlayerVampirismEvent.java b/src/main/java/com/gmail/nossr50/events/hardcore/McMMOPlayerVampirismEvent.java index 8aa59d521..3f42a7148 100644 --- a/src/main/java/com/gmail/nossr50/events/hardcore/McMMOPlayerVampirismEvent.java +++ b/src/main/java/com/gmail/nossr50/events/hardcore/McMMOPlayerVampirismEvent.java @@ -1,13 +1,13 @@ package com.gmail.nossr50.events.hardcore; -import org.bukkit.entity.Player; - import java.util.HashMap; +import org.bukkit.entity.Player; public class McMMOPlayerVampirismEvent extends McMMOPlayerDeathPenaltyEvent { private final boolean isVictim; - public McMMOPlayerVampirismEvent(Player player, boolean isVictim, HashMap levelChanged, HashMap experienceChanged) { + public McMMOPlayerVampirismEvent(Player player, boolean isVictim, + HashMap levelChanged, HashMap experienceChanged) { super(player, levelChanged, experienceChanged); this.isVictim = isVictim; } 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 1249476d4..f333da5b0 100644 --- a/src/main/java/com/gmail/nossr50/events/items/McMMOItemSpawnEvent.java +++ b/src/main/java/com/gmail/nossr50/events/items/McMMOItemSpawnEvent.java @@ -20,7 +20,8 @@ public class McMMOItemSpawnEvent extends Event implements Cancellable { private final ItemSpawnReason itemSpawnReason; private final Player player; - public McMMOItemSpawnEvent(@NotNull Location location, @NotNull ItemStack itemStack, @NotNull ItemSpawnReason itemSpawnReason, @Nullable Player player) { + public McMMOItemSpawnEvent(@NotNull Location location, @NotNull ItemStack itemStack, + @NotNull ItemSpawnReason itemSpawnReason, @Nullable Player player) { this.location = location; this.itemStack = itemStack; this.itemSpawnReason = itemSpawnReason; @@ -29,8 +30,8 @@ public class McMMOItemSpawnEvent extends Event implements Cancellable { } /** - * Get the associated player - * This can be null + * Get the associated player This can be null + * * @return the associated player if one exists null otherwise */ public @Nullable Player getPlayer() { @@ -39,8 +40,9 @@ public class McMMOItemSpawnEvent extends Event implements Cancellable { /** * The reason an item is being spawned by mcMMO - * @see ItemSpawnReason + * * @return the item drop reason + * @see ItemSpawnReason */ public ItemSpawnReason getItemSpawnReason() { return itemSpawnReason; @@ -74,7 +76,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; @@ -85,7 +89,9 @@ public class McMMOItemSpawnEvent extends Event implements Cancellable { this.cancelled = cancelled; } - /** Rest of file is required boilerplate for custom events **/ + /** + * Rest of file is required boilerplate for custom events + **/ private static final @NotNull HandlerList handlers = new HandlerList(); @Override 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 68fc2db6f..1d8fdd7d9 100644 --- a/src/main/java/com/gmail/nossr50/events/party/McMMOPartyAllianceChangeEvent.java +++ b/src/main/java/com/gmail/nossr50/events/party/McMMOPartyAllianceChangeEvent.java @@ -12,7 +12,8 @@ public class McMMOPartyAllianceChangeEvent extends PlayerEvent implements Cancel private final EventReason reason; private boolean cancelled; - public McMMOPartyAllianceChangeEvent(Player player, String oldAlly, String newAlly, EventReason reason) { + public McMMOPartyAllianceChangeEvent(Player player, String oldAlly, String newAlly, + EventReason reason) { super(player); if (newAlly != null) { @@ -66,7 +67,9 @@ public class McMMOPartyAllianceChangeEvent extends PlayerEvent implements Cancel CUSTOM } - /** Following are required for Cancellable **/ + /** + * Following are required for Cancellable + **/ @Override public boolean isCancelled() { return cancelled; @@ -77,7 +80,9 @@ public class McMMOPartyAllianceChangeEvent extends PlayerEvent implements Cancel this.cancelled = cancelled; } - /** Rest of file is required boilerplate for custom events **/ + /** + * Rest of file is required boilerplate for custom events + **/ private static final HandlerList handlers = new HandlerList(); @Override 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 1f9b30696..46f0e6365 100644 --- a/src/main/java/com/gmail/nossr50/events/party/McMMOPartyChangeEvent.java +++ b/src/main/java/com/gmail/nossr50/events/party/McMMOPartyChangeEvent.java @@ -15,7 +15,8 @@ public class McMMOPartyChangeEvent extends PlayerEvent implements Cancellable { private final EventReason reason; private boolean cancelled; - public McMMOPartyChangeEvent(Player player, String oldParty, String newParty, EventReason reason) { + public McMMOPartyChangeEvent(Player player, String oldParty, String newParty, + EventReason reason) { super(player); if (newParty != null) { @@ -89,7 +90,9 @@ public class McMMOPartyChangeEvent extends PlayerEvent implements Cancellable { CUSTOM } - /** Following are required for Cancellable **/ + /** + * Following are required for Cancellable + **/ @Override public boolean isCancelled() { return cancelled; @@ -100,7 +103,9 @@ public class McMMOPartyChangeEvent extends PlayerEvent implements Cancellable { this.cancelled = cancelled; } - /** Rest of file is required boilerplate for custom events **/ + /** + * Rest of file is required boilerplate for custom events + **/ private static final HandlerList handlers = new HandlerList(); @Override 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 ed42bf028..e676d18aa 100644 --- a/src/main/java/com/gmail/nossr50/events/party/McMMOPartyLevelUpEvent.java +++ b/src/main/java/com/gmail/nossr50/events/party/McMMOPartyLevelUpEvent.java @@ -29,7 +29,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; @@ -40,7 +42,9 @@ public class McMMOPartyLevelUpEvent extends Event implements Cancellable { this.cancelled = cancelled; } - /** Rest of file is required boilerplate for custom events **/ + /** + * Rest of file is required boilerplate for custom events + **/ private static final HandlerList handlers = new HandlerList(); @Override 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 322833de1..0e2e108b2 100644 --- a/src/main/java/com/gmail/nossr50/events/party/McMMOPartyTeleportEvent.java +++ b/src/main/java/com/gmail/nossr50/events/party/McMMOPartyTeleportEvent.java @@ -32,7 +32,9 @@ public class McMMOPartyTeleportEvent extends PlayerTeleportEvent { return target; } - /** Rest of file is required boilerplate for custom events **/ + /** + * Rest of file is required boilerplate for custom events + **/ private static final HandlerList handlers = new HandlerList(); @Override 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 926588dcc..1d6b7cce7 100644 --- a/src/main/java/com/gmail/nossr50/events/party/McMMOPartyXpGainEvent.java +++ b/src/main/java/com/gmail/nossr50/events/party/McMMOPartyXpGainEvent.java @@ -51,7 +51,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; @@ -62,7 +64,9 @@ public class McMMOPartyXpGainEvent extends Event implements Cancellable { this.cancelled = cancelled; } - /** Rest of file is required boilerplate for custom events **/ + /** + * Rest of file is required boilerplate for custom events + **/ private static final HandlerList handlers = new HandlerList(); @Override diff --git a/src/main/java/com/gmail/nossr50/events/players/McMMOPlayerProfileLoadEvent.java b/src/main/java/com/gmail/nossr50/events/players/McMMOPlayerProfileLoadEvent.java index c16a520a8..84347fb66 100644 --- a/src/main/java/com/gmail/nossr50/events/players/McMMOPlayerProfileLoadEvent.java +++ b/src/main/java/com/gmail/nossr50/events/players/McMMOPlayerProfileLoadEvent.java @@ -12,13 +12,15 @@ public class McMMOPlayerProfileLoadEvent extends Event implements Cancellable { private boolean cancelled; private final PlayerProfile profile; private final Player player; - public McMMOPlayerProfileLoadEvent(Player player, PlayerProfile profile){ + + public McMMOPlayerProfileLoadEvent(Player player, PlayerProfile profile) { super(!Bukkit.isPrimaryThread()); this.cancelled = false; this.profile = profile; this.player = player; } + @Override public boolean isCancelled() { return this.cancelled; @@ -29,7 +31,10 @@ public class McMMOPlayerProfileLoadEvent extends Event implements Cancellable { this.cancelled = cancelled; } - public PlayerProfile getProfile(){return this.profile;} + public PlayerProfile getProfile() { + return this.profile; + } + private static final HandlerList handlers = new HandlerList(); @Override @@ -41,5 +46,7 @@ public class McMMOPlayerProfileLoadEvent extends Event implements Cancellable { return handlers; } - public Player getPlayer() {return player;} + public Player getPlayer() { + return player; + } } 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 a3f31598b..249edd304 100644 --- a/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardEvent.java +++ b/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardEvent.java @@ -7,8 +7,7 @@ import org.bukkit.scoreboard.Scoreboard; import org.jetbrains.annotations.NotNull; /** - * The parent class of all mcMMO scoreboard events - * All scoreboard events will extend from this + * The parent class of all mcMMO scoreboard events All scoreboard events will extend from this */ abstract public class McMMOScoreboardEvent extends Event { @@ -18,7 +17,8 @@ abstract public class McMMOScoreboardEvent extends Event { private final ScoreboardEventReason scoreboardEventReason; - 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; @@ -29,6 +29,7 @@ abstract public class McMMOScoreboardEvent extends Event { /** * 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 +38,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,6 +47,7 @@ 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() { @@ -54,6 +57,7 @@ abstract public class McMMOScoreboardEvent extends Event { /** * 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,6 +66,7 @@ abstract public class McMMOScoreboardEvent extends Event { /** * The ENUM defining the reason for this event + * * @return the reason for this event */ public ScoreboardEventReason getScoreboardEventReason() { @@ -70,13 +75,16 @@ abstract public class McMMOScoreboardEvent extends Event { /** * 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 **/ + /** + * Rest of file is required boilerplate for custom events + **/ private static final HandlerList handlers = new HandlerList(); @Override diff --git a/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardMakeboardEvent.java b/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardMakeboardEvent.java index 8418e0ad8..63f3a4e83 100644 --- a/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardMakeboardEvent.java +++ b/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardMakeboardEvent.java @@ -4,12 +4,13 @@ import org.bukkit.entity.Player; import org.bukkit.scoreboard.Scoreboard; /** - * This event is called when mcMMO creates its custom boards - * You should not interfere with this event unless you understand our board code thoroughly - * mcMMO relies on using new scoreboards to show players individually catered boards with stats specific to them + * This event is called when mcMMO creates its custom boards You should not interfere with this + * event unless you understand our board code thoroughly mcMMO relies on using new scoreboards to + * show players individually catered boards with stats specific to them */ public class McMMOScoreboardMakeboardEvent extends McMMOScoreboardEvent { - public McMMOScoreboardMakeboardEvent(Scoreboard targetBoard, Scoreboard currentBoard, Player targetPlayer, ScoreboardEventReason scoreboardEventReason) { + public McMMOScoreboardMakeboardEvent(Scoreboard targetBoard, Scoreboard currentBoard, + Player targetPlayer, ScoreboardEventReason scoreboardEventReason) { super(targetBoard, currentBoard, targetPlayer, scoreboardEventReason); } } 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..bfa6d2478 100644 --- a/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardObjectiveEvent.java +++ b/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardObjectiveEvent.java @@ -11,7 +11,9 @@ public class McMMOScoreboardObjectiveEvent extends McMMOScoreboardEvent implemen protected Objective targetObjective; protected final ScoreboardObjectiveEventReason objectiveEventReason; - public McMMOScoreboardObjectiveEvent(Objective targetObjective, ScoreboardObjectiveEventReason objectiveEventReason, Scoreboard scoreboard, Scoreboard oldboard, Player targetPlayer, ScoreboardEventReason scoreboardEventReason) { + public McMMOScoreboardObjectiveEvent(Objective targetObjective, + ScoreboardObjectiveEventReason objectiveEventReason, Scoreboard scoreboard, + Scoreboard oldboard, Player targetPlayer, ScoreboardEventReason scoreboardEventReason) { super(scoreboard, oldboard, targetPlayer, scoreboardEventReason); this.objectiveEventReason = objectiveEventReason; this.targetObjective = targetObjective; @@ -20,6 +22,7 @@ public class McMMOScoreboardObjectiveEvent extends McMMOScoreboardEvent implemen /** * The objective that will be modified by this event + * * @return */ public Objective getTargetObjective() { @@ -28,6 +31,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/scoreboard/McMMOScoreboardRevertEvent.java b/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardRevertEvent.java index 000a19a54..0d4f0c738 100644 --- a/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardRevertEvent.java +++ b/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardRevertEvent.java @@ -4,11 +4,14 @@ import org.bukkit.entity.Player; import org.bukkit.scoreboard.Scoreboard; /** - * This event is called when mcMMO is attempting to change a players targetBoard back to their previous board - * This is used when an mcMMO board is cleared (removed from the screen), changing back from a temporary board (usually from a delayed scheduled task or our mcscoreboard time command) + * This event is called when mcMMO is attempting to change a players targetBoard back to their + * previous board This is used when an mcMMO board is cleared (removed from the screen), changing + * back from a temporary board (usually from a delayed scheduled task or our mcscoreboard time + * command) */ public class McMMOScoreboardRevertEvent extends McMMOScoreboardEvent { - public McMMOScoreboardRevertEvent(Scoreboard targetBoard, Scoreboard currentBoard, Player targetPlayer, ScoreboardEventReason scoreboardEventReason) { + public McMMOScoreboardRevertEvent(Scoreboard targetBoard, Scoreboard currentBoard, + Player targetPlayer, ScoreboardEventReason scoreboardEventReason) { super(targetBoard, currentBoard, targetPlayer, scoreboardEventReason); } } 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 75d8eae83..5d7261d48 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/McMMOPlayerNotificationEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/McMMOPlayerNotificationEvent.java @@ -30,8 +30,8 @@ public class McMMOPlayerNotificationEvent extends Event implements Cancellable { protected final Player player; public McMMOPlayerNotificationEvent(Player player, NotificationType notificationType, - Component notificationTextComponent, McMMOMessageType chatMessageType, - boolean isMessageAlsoBeingSentToChat) { + Component notificationTextComponent, McMMOMessageType chatMessageType, + boolean isMessageAlsoBeingSentToChat) { super(false); this.player = player; this.notificationType = notificationType; @@ -75,6 +75,7 @@ public class McMMOPlayerNotificationEvent extends Event implements Cancellable { /** * The notification type for this event + * * @return this event's notification type */ public NotificationType getEventNotificationType() { 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 99059ff19..c44765b7a 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/McMMOPlayerSkillEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/McMMOPlayerSkillEvent.java @@ -1,5 +1,7 @@ package com.gmail.nossr50.events.skills; +import static java.util.Objects.requireNonNull; + import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.util.player.UserManager; @@ -8,8 +10,6 @@ import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; import org.jetbrains.annotations.NotNull; -import static java.util.Objects.requireNonNull; - /** * Generic event for mcMMO skill handling. */ @@ -21,7 +21,7 @@ public abstract class McMMOPlayerSkillEvent extends PlayerEvent { @Deprecated(forRemoval = true, since = "2.2.010") protected McMMOPlayerSkillEvent(@NotNull Player player, @NotNull PrimarySkillType skill) { super(player); - McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); requireNonNull(mmoPlayer, "Player not found in UserManager," + "contact the dev and tell them to use the constructor for" + " McMMOPlayerSkillEvent(McMMOPlayer, PrimarySkillType) instead"); @@ -29,7 +29,8 @@ public abstract class McMMOPlayerSkillEvent extends PlayerEvent { this.skillLevel = UserManager.getPlayer(player).getSkillLevel(skill); } - protected McMMOPlayerSkillEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull PrimarySkillType primarySkillType) { + protected McMMOPlayerSkillEvent(@NotNull McMMOPlayer mmoPlayer, + @NotNull PrimarySkillType primarySkillType) { super(mmoPlayer.getPlayer()); requireNonNull(mmoPlayer, "mmoPlayer cannot be null"); requireNonNull(primarySkillType, "primarySkillType cannot be null"); @@ -51,7 +52,9 @@ public abstract class McMMOPlayerSkillEvent extends PlayerEvent { return skillLevel; } - /** Rest of file is required boilerplate for custom events **/ + /** + * Rest of file is required boilerplate for custom events + **/ private static final HandlerList handlers = new HandlerList(); /** diff --git a/src/main/java/com/gmail/nossr50/events/skills/SkillActivationPerkEvent.java b/src/main/java/com/gmail/nossr50/events/skills/SkillActivationPerkEvent.java index 36848e6fa..8e88147ef 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/SkillActivationPerkEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/SkillActivationPerkEvent.java @@ -9,8 +9,6 @@ import org.jetbrains.annotations.NotNull; public class SkillActivationPerkEvent extends Event { - - private static final HandlerList handlers = new HandlerList(); private final Player player; private int ticks; diff --git a/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityActivateEvent.java b/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityActivateEvent.java index 707981c9c..c8f8cbb86 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityActivateEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityActivateEvent.java @@ -3,12 +3,12 @@ package com.gmail.nossr50.events.skills.abilities; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.util.player.UserManager; +import java.util.Objects; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; -import java.util.Objects; - -public class McMMOPlayerAbilityActivateEvent extends McMMOPlayerAbilityEvent implements Cancellable { +public class McMMOPlayerAbilityActivateEvent extends McMMOPlayerAbilityEvent implements + Cancellable { private boolean cancelled; @Deprecated(forRemoval = true, since = "2.2.010") diff --git a/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityDeactivateEvent.java b/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityDeactivateEvent.java index bf55a43ab..7883d19c0 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityDeactivateEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityDeactivateEvent.java @@ -1,20 +1,22 @@ package com.gmail.nossr50.events.skills.abilities; +import static java.util.Objects.requireNonNull; + import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.util.player.UserManager; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import static java.util.Objects.requireNonNull; - public class McMMOPlayerAbilityDeactivateEvent extends McMMOPlayerAbilityEvent { @Deprecated(forRemoval = true, since = "2.2.010") - public McMMOPlayerAbilityDeactivateEvent(@NotNull Player player, @NotNull PrimarySkillType skill) { + public McMMOPlayerAbilityDeactivateEvent(@NotNull Player player, + @NotNull PrimarySkillType skill) { this(requireNonNull(UserManager.getPlayer(player)), skill); } - public McMMOPlayerAbilityDeactivateEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull PrimarySkillType skill) { + public McMMOPlayerAbilityDeactivateEvent(@NotNull McMMOPlayer mmoPlayer, + @NotNull PrimarySkillType skill) { super(mmoPlayer, skill); } } diff --git a/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityEvent.java b/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityEvent.java index 42e5fd9a5..183af3540 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityEvent.java @@ -6,9 +6,8 @@ import com.gmail.nossr50.datatypes.skills.SuperAbilityType; import com.gmail.nossr50.events.skills.McMMOPlayerSkillEvent; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.player.UserManager; -import org.bukkit.entity.Player; - import java.util.Objects; +import org.bukkit.entity.Player; public class McMMOPlayerAbilityEvent extends McMMOPlayerSkillEvent { private final SuperAbilityType ability; @@ -28,6 +27,7 @@ public class McMMOPlayerAbilityEvent extends McMMOPlayerSkillEvent { /** * Create a new McMMOPlayerAbilityEvent. + * * @param mmoPlayer The McMMOPlayer involved in this event * @param skill The skill involved in this event */ diff --git a/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerBrewEvent.java b/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerBrewEvent.java index cd3dd032a..4b98769da 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerBrewEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerBrewEvent.java @@ -1,5 +1,7 @@ package com.gmail.nossr50.events.skills.alchemy; +import static java.util.Objects.requireNonNull; + import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.events.skills.McMMOPlayerSkillEvent; @@ -11,8 +13,6 @@ import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.jetbrains.annotations.NotNull; -import static java.util.Objects.requireNonNull; - public class McMMOPlayerBrewEvent extends McMMOPlayerSkillEvent implements Cancellable { private final BlockState brewingStand; diff --git a/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerCatalysisEvent.java b/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerCatalysisEvent.java index 385cbaec0..0a5dfe19e 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerCatalysisEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerCatalysisEvent.java @@ -1,5 +1,7 @@ package com.gmail.nossr50.events.skills.alchemy; +import static java.util.Objects.requireNonNull; + import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.events.skills.McMMOPlayerSkillEvent; @@ -7,8 +9,6 @@ import com.gmail.nossr50.util.player.UserManager; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; -import static java.util.Objects.requireNonNull; - public class McMMOPlayerCatalysisEvent extends McMMOPlayerSkillEvent implements Cancellable { private double speed; diff --git a/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerFishingTreasureEvent.java b/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerFishingTreasureEvent.java index 0437e2fc8..e43d4e6e3 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerFishingTreasureEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerFishingTreasureEvent.java @@ -1,5 +1,7 @@ package com.gmail.nossr50.events.skills.fishing; +import static java.util.Objects.requireNonNull; + import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.util.player.UserManager; import org.bukkit.entity.Player; @@ -7,8 +9,6 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import static java.util.Objects.requireNonNull; - public class McMMOPlayerFishingTreasureEvent extends McMMOPlayerFishingEvent { private ItemStack treasure; private int xp; @@ -18,7 +18,8 @@ public class McMMOPlayerFishingTreasureEvent extends McMMOPlayerFishingEvent { this(requireNonNull(UserManager.getPlayer(player)), treasure, xp); } - public McMMOPlayerFishingTreasureEvent(@NotNull McMMOPlayer mmoPlayer, @Nullable ItemStack treasure, int xp) { + public McMMOPlayerFishingTreasureEvent(@NotNull McMMOPlayer mmoPlayer, + @Nullable ItemStack treasure, int xp) { super(mmoPlayer); this.treasure = treasure; this.xp = xp; diff --git a/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerMagicHunterEvent.java b/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerMagicHunterEvent.java index 93cc5c8c8..b98dc2015 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerMagicHunterEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerMagicHunterEvent.java @@ -1,26 +1,27 @@ package com.gmail.nossr50.events.skills.fishing; +import static java.util.Objects.requireNonNull; + import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.util.player.UserManager; +import java.util.HashMap; +import java.util.Map; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import java.util.HashMap; -import java.util.Map; - -import static java.util.Objects.requireNonNull; - public class McMMOPlayerMagicHunterEvent extends McMMOPlayerFishingTreasureEvent { private final Map enchants = new HashMap<>(); @Deprecated(forRemoval = true, since = "2.2.010") - public McMMOPlayerMagicHunterEvent(@NotNull Player player, @NotNull ItemStack treasure, int xp, @NotNull Map enchants) { + public McMMOPlayerMagicHunterEvent(@NotNull Player player, @NotNull ItemStack treasure, int xp, + @NotNull Map enchants) { this(requireNonNull(UserManager.getPlayer(player)), treasure, xp, enchants); } - public McMMOPlayerMagicHunterEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull ItemStack treasure, int xp, @NotNull Map enchants) { + public McMMOPlayerMagicHunterEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull ItemStack treasure, + int xp, @NotNull Map enchants) { super(mmoPlayer, treasure, xp); requireNonNull(enchants, "enchants cannot be null"); this.enchants.putAll(enchants); diff --git a/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerMasterAnglerEvent.java b/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerMasterAnglerEvent.java index a3532fa23..db4e19cae 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerMasterAnglerEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerMasterAnglerEvent.java @@ -9,11 +9,11 @@ public class McMMOPlayerMasterAnglerEvent extends McMMOPlayerFishingEvent { private int reducedMaxWaitTime; private final FishingManager fishingManager; - public McMMOPlayerMasterAnglerEvent(@NotNull McMMOPlayer mcMMOPlayer, - int reducedMinWaitTime, - int reducedMaxWaitTime, - FishingManager fishingManager) { - super(mcMMOPlayer); + public McMMOPlayerMasterAnglerEvent(@NotNull McMMOPlayer mmoPlayer, + int reducedMinWaitTime, + int reducedMaxWaitTime, + FishingManager fishingManager) { + super(mmoPlayer); this.fishingManager = fishingManager; this.reducedMinWaitTime = Math.max(reducedMinWaitTime, getReducedMinWaitTimeLowerBound()); this.reducedMaxWaitTime = Math.max(reducedMaxWaitTime, getReducedMaxWaitTimeLowerBound()); @@ -25,8 +25,9 @@ public class McMMOPlayerMasterAnglerEvent extends McMMOPlayerFishingEvent { public void setReducedMinWaitTime(int reducedMinWaitTime) { if (reducedMinWaitTime < 0 || reducedMinWaitTime > reducedMaxWaitTime) { - throw new IllegalArgumentException("Reduced min wait time must be greater than or equal to 0" + - " and less than reduced max wait time."); + throw new IllegalArgumentException( + "Reduced min wait time must be greater than or equal to 0" + + " and less than reduced max wait time."); } this.reducedMinWaitTime = Math.max(reducedMinWaitTime, getReducedMinWaitTimeLowerBound()); } @@ -37,8 +38,9 @@ public class McMMOPlayerMasterAnglerEvent extends McMMOPlayerFishingEvent { public void setReducedMaxWaitTime(int reducedMaxWaitTime) { if (reducedMaxWaitTime < 0 || reducedMaxWaitTime < reducedMinWaitTime) { - throw new IllegalArgumentException("Reduced max wait time must be greater than or equal to 0" + - " and greater than reduced min wait time."); + throw new IllegalArgumentException( + "Reduced max wait time must be greater than or equal to 0" + + " and greater than reduced min wait time."); } this.reducedMaxWaitTime = Math.max(reducedMaxWaitTime, getReducedMaxWaitTimeLowerBound()); } 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 fd4a02754..d0baf6beb 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 @@ -15,7 +15,8 @@ public class McMMOPlayerRepairCheckEvent extends McMMOPlayerSkillEvent implement private final ItemStack repairedObject; private boolean cancelled; - public McMMOPlayerRepairCheckEvent(Player player, short repairAmount, ItemStack repairMaterial, ItemStack repairedObject) { + public McMMOPlayerRepairCheckEvent(Player player, short repairAmount, ItemStack repairMaterial, + ItemStack repairedObject) { super(player, PrimarySkillType.REPAIR); this.repairAmount = repairAmount; this.repairMaterial = repairMaterial; @@ -44,7 +45,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/rupture/McMMOEntityDamageByRuptureEvent.java b/src/main/java/com/gmail/nossr50/events/skills/rupture/McMMOEntityDamageByRuptureEvent.java index 3190538ae..8f27fde3d 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/rupture/McMMOEntityDamageByRuptureEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/rupture/McMMOEntityDamageByRuptureEvent.java @@ -8,24 +8,25 @@ import org.bukkit.event.entity.EntityEvent; import org.jetbrains.annotations.NotNull; public class McMMOEntityDamageByRuptureEvent extends EntityEvent implements Cancellable { - private final McMMOPlayer damager; + private final McMMOPlayer damager; private final Entity damagee; private double damage; private boolean isCancelled = false; private static final HandlerList handlers = new HandlerList(); - public McMMOEntityDamageByRuptureEvent(@NotNull McMMOPlayer damager, @NotNull Entity damagee, double damage) { + public McMMOEntityDamageByRuptureEvent(@NotNull McMMOPlayer damager, @NotNull Entity damagee, + double damage) { super(damagee); - this.damager = damager; + this.damager = damager; this.damagee = damagee; this.damage = damage; - } + } - @NotNull + @NotNull @Deprecated - public McMMOPlayer getMcMMODamager() { - return damager; - } + public McMMOPlayer getMcMMODamager() { + return damager; + } public McMMOPlayer getDamager() { return damager; 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 6a8061763..ca1f9b0a4 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 @@ -15,7 +15,8 @@ public class McMMOPlayerSalvageCheckEvent extends McMMOPlayerSkillEvent implemen private final ItemStack enchantedBook; private boolean cancelled; - public McMMOPlayerSalvageCheckEvent(Player player, ItemStack salvageItem, ItemStack salvageResults, ItemStack enchantedBook) { + public McMMOPlayerSalvageCheckEvent(Player player, ItemStack salvageItem, + ItemStack salvageResults, ItemStack enchantedBook) { super(player, PrimarySkillType.SALVAGE); this.salvageItem = salvageItem; this.salvageResults = salvageResults; @@ -38,13 +39,16 @@ public class McMMOPlayerSalvageCheckEvent extends McMMOPlayerSkillEvent implemen } /** - * @return The enchanted book that should drop after salvaging or null if no book should be dropped. + * @return The enchanted book that should drop after salvaging or null if no book should be + * dropped. */ public ItemStack getEnchantedBook() { 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/SubSkillBlockEvent.java b/src/main/java/com/gmail/nossr50/events/skills/secondaryabilities/SubSkillBlockEvent.java index 69b730af5..76a553b4f 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/secondaryabilities/SubSkillBlockEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/secondaryabilities/SubSkillBlockEvent.java @@ -8,13 +8,15 @@ import org.jetbrains.annotations.NotNull; public class SubSkillBlockEvent extends SubSkillEvent { private final @NotNull Block block; - public SubSkillBlockEvent(@NotNull Player player, @NotNull SubSkillType subSkillType, @NotNull Block block) { + public SubSkillBlockEvent(@NotNull Player player, @NotNull SubSkillType subSkillType, + @NotNull Block block) { super(player, subSkillType); this.block = block; } /** * Get the block associated with this event + * * @return the block associated with this event */ public @NotNull Block getBlock() { 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 273a6e442..49e6ab588 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 @@ -1,5 +1,7 @@ package com.gmail.nossr50.events.skills.secondaryabilities; +import static java.util.Objects.requireNonNull; + import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.subskills.AbstractSubSkill; @@ -10,8 +12,6 @@ import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.jetbrains.annotations.NotNull; -import static java.util.Objects.requireNonNull; - public class SubSkillEvent extends McMMOPlayerSkillEvent implements Cancellable { private SubSkillType subSkillType; private boolean cancelled = false; @@ -19,6 +19,7 @@ public class SubSkillEvent extends McMMOPlayerSkillEvent implements Cancellable /** * Only skills using the old system will fire this event + * * @param player target player * @param subSkillType target subskill * @deprecated Use {@link #SubSkillEvent(McMMOPlayer, SubSkillType)} instead @@ -30,6 +31,7 @@ public class SubSkillEvent extends McMMOPlayerSkillEvent implements Cancellable /** * Only skills using the old system will fire this event + * * @param mmoPlayer target player * @param subSkillType target subskill */ @@ -40,22 +42,28 @@ public class SubSkillEvent extends McMMOPlayerSkillEvent implements Cancellable /** * Only skills using the old system will fire this event + * * @param player target player * @param subSkillType target subskill - * @param resultModifier a value multiplied against the final result of the dice roll, typically between 0-1.0 + * @param resultModifier a value multiplied against the final result of the dice roll, typically + * between 0-1.0 */ @Deprecated(forRemoval = true, since = "2.2.010") - public SubSkillEvent(@NotNull Player player, @NotNull SubSkillType subSkillType, double resultModifier) { + public SubSkillEvent(@NotNull Player player, @NotNull SubSkillType subSkillType, + double resultModifier) { this(requireNonNull(UserManager.getPlayer(player)), subSkillType, resultModifier); } /** * Only skills using the old system will fire this event + * * @param player target player * @param subSkillType target subskill - * @param resultModifier a value multiplied against the final result of the dice roll, typically between 0-1.0 + * @param resultModifier a value multiplied against the final result of the dice roll, typically + * between 0-1.0 */ - public SubSkillEvent(@NotNull McMMOPlayer player, @NotNull SubSkillType subSkillType, double resultModifier) { + public SubSkillEvent(@NotNull McMMOPlayer player, @NotNull SubSkillType subSkillType, + double resultModifier) { super(player, mcMMO.p.getSkillTools().getPrimarySkillBySubSkill(subSkillType)); this.subSkillType = requireNonNull(subSkillType, "subSkillType cannot be null"); this.resultModifier = resultModifier; @@ -66,7 +74,8 @@ public class SubSkillEvent extends McMMOPlayerSkillEvent implements Cancellable this(requireNonNull(UserManager.getPlayer(player)), abstractSubSkill); } - public SubSkillEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull AbstractSubSkill abstractSubSkill) { + public SubSkillEvent(@NotNull McMMOPlayer mmoPlayer, + @NotNull AbstractSubSkill abstractSubSkill) { super(mmoPlayer, abstractSubSkill.getPrimarySkill()); } @@ -80,6 +89,7 @@ public class SubSkillEvent extends McMMOPlayerSkillEvent implements Cancellable /** * Gets the SubSkillType involved in the event + * * @return the SubSkillType */ public SubSkillType getSubSkillType() { diff --git a/src/main/java/com/gmail/nossr50/events/skills/taming/McMMOPlayerTameEntityEvent.java b/src/main/java/com/gmail/nossr50/events/skills/taming/McMMOPlayerTameEntityEvent.java index 038057d7c..a81f9f2d5 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/taming/McMMOPlayerTameEntityEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/taming/McMMOPlayerTameEntityEvent.java @@ -19,7 +19,8 @@ public class McMMOPlayerTameEntityEvent extends McMMOPlayerExperienceEvent { private float xpGained; private final Entity tamedEntity; - public McMMOPlayerTameEntityEvent(@NotNull McMMOPlayer mmoPlayer, float xp, @NotNull Entity tamedEntity) { + public McMMOPlayerTameEntityEvent(@NotNull McMMOPlayer mmoPlayer, float xp, + @NotNull Entity tamedEntity) { super(mmoPlayer.getPlayer(), PrimarySkillType.TAMING, XPGainReason.PVE); this.mmoPlayer = mmoPlayer; this.xpGained = xp; @@ -58,7 +59,8 @@ public class McMMOPlayerTameEntityEvent extends McMMOPlayerExperienceEvent { } /** - * @apiNote Cancelling this event prevents experience from being awarded, but the entity will remain tamed. + * @apiNote Cancelling this event prevents experience from being awarded, but the entity will + * remain tamed. */ @Override public void setCancelled(boolean cancelled) { 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 7404aaa22..a0c535f8d 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 906ac0483..272609395 100644 --- a/src/main/java/com/gmail/nossr50/listeners/BlockListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/BlockListener.java @@ -1,5 +1,7 @@ package com.gmail.nossr50.listeners; +import static com.gmail.nossr50.util.Misc.getBlockCenter; + import com.gmail.nossr50.api.ItemSpawnReason; import com.gmail.nossr50.config.HiddenConfig; import com.gmail.nossr50.config.WorldBlacklist; @@ -20,27 +22,47 @@ import com.gmail.nossr50.skills.mining.MiningManager; import com.gmail.nossr50.skills.repair.Repair; import com.gmail.nossr50.skills.salvage.Salvage; import com.gmail.nossr50.skills.woodcutting.WoodcuttingManager; -import com.gmail.nossr50.util.*; +import com.gmail.nossr50.util.BlockUtils; +import com.gmail.nossr50.util.ContainerMetadataUtils; +import com.gmail.nossr50.util.EventUtils; +import com.gmail.nossr50.util.ItemUtils; +import com.gmail.nossr50.util.MetadataConstants; +import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.sounds.SoundManager; import com.gmail.nossr50.util.sounds.SoundType; import com.gmail.nossr50.worldguard.WorldGuardManager; import com.gmail.nossr50.worldguard.WorldGuardUtils; -import org.bukkit.*; -import org.bukkit.block.*; +import java.util.HashSet; +import org.bukkit.ChatColor; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.OfflinePlayer; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.BlockState; +import org.bukkit.block.BrewingStand; +import org.bukkit.block.Furnace; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; -import org.bukkit.event.block.*; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockDamageEvent; +import org.bukkit.event.block.BlockDropItemEvent; +import org.bukkit.event.block.BlockFormEvent; +import org.bukkit.event.block.BlockGrowEvent; +import org.bukkit.event.block.BlockMultiPlaceEvent; +import org.bukkit.event.block.BlockPistonExtendEvent; +import org.bukkit.event.block.BlockPistonRetractEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.block.EntityBlockFormEvent; import org.bukkit.inventory.ItemStack; -import java.util.HashSet; - -import static com.gmail.nossr50.util.Misc.getBlockCenter; - public class BlockListener implements Listener { private final mcMMO plugin; @@ -52,29 +74,32 @@ public class BlockListener implements Listener { public void onBlockDropItemEvent(BlockDropItemEvent event) { //Make sure we clean up metadata on these blocks if (event.isCancelled()) { - if (event.getBlock().hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) + if (event.getBlock().hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) { event.getBlock().removeMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, plugin); + } return; } int tileEntityTolerance = 1; // beetroot hotfix, potentially other plants may need this fix - if (event.getBlock().getType() == Material.BEETROOTS) + if (event.getBlock().getType() == Material.BEETROOTS) { tileEntityTolerance = 2; + } //Track how many "things" are being dropped HashSet uniqueMaterials = new HashSet<>(); boolean dontRewardTE = false; //If we suspect TEs are mixed in with other things don't reward bonus drops for anything that isn't a block int blockCount = 0; - for(Item item : event.getItems()) { + for (Item item : event.getItems()) { //Track unique materials uniqueMaterials.add(item.getItemStack().getType()); //Count blocks as a second failsafe - if (item.getItemStack().getType().isBlock()) + if (item.getItemStack().getType().isBlock()) { blockCount++; + } } if (uniqueMaterials.size() > tileEntityTolerance) { @@ -85,17 +110,22 @@ public class BlockListener implements Listener { //If there are more than one block in the item list we can't really trust it and will back out of rewarding bonus drops if (blockCount <= 1) { - for(Item item : event.getItems()) { + for (Item item : event.getItems()) { ItemStack is = new ItemStack(item.getItemStack()); - if (is.getAmount() <= 0) + if (is.getAmount() <= 0) { continue; + } //TODO: Ignore this abomination its rewritten in 2.2 - if (!mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.MINING, is.getType()) - && !mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.HERBALISM, is.getType()) - && !mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, is.getType())) + if (!mcMMO.p.getGeneralConfig() + .getDoubleDropsEnabled(PrimarySkillType.MINING, is.getType()) + && !mcMMO.p.getGeneralConfig() + .getDoubleDropsEnabled(PrimarySkillType.HERBALISM, is.getType()) + && !mcMMO.p.getGeneralConfig() + .getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, is.getType())) { continue; + } //If we suspect TEs might be duped only reward block if (dontRewardTE) { @@ -104,7 +134,8 @@ public class BlockListener implements Listener { } } - if (event.getBlock().getMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS).size() > 0) { + if (event.getBlock().getMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS).size() + > 0) { final BonusDropMeta bonusDropMeta = (BonusDropMeta) event.getBlock().getMetadata( MetadataConstants.METADATA_KEY_BONUS_DROPS).get(0); @@ -119,8 +150,9 @@ public class BlockListener implements Listener { } } - if (event.getBlock().hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) + if (event.getBlock().hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) { event.getBlock().removeMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, plugin); + } } /** @@ -131,8 +163,9 @@ 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; + } if (!ExperienceConfig.getInstance().isPistonCheatingPrevented()) { return; @@ -159,8 +192,9 @@ 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; + } if (!ExperienceConfig.getInstance().isPistonCheatingPrevented()) { return; @@ -176,7 +210,8 @@ public class BlockListener implements Listener { } for (Block block : event.getBlocks()) { - if (BlockUtils.isWithinWorldBounds(block) && BlockUtils.isWithinWorldBounds(block.getRelative(direction))) { + if (BlockUtils.isWithinWorldBounds(block) && BlockUtils.isWithinWorldBounds( + block.getRelative(direction))) { Block relativeBlock = block.getRelative(direction); BlockUtils.setUnnaturalBlock(relativeBlock); } @@ -184,20 +219,22 @@ public class BlockListener implements Listener { } /** - * Monitor blocks formed by entities (snowmen) - * Does not seem to monitor stuff like a falling block creating a new block + * Monitor blocks formed by entities (snowmen) Does not seem to monitor stuff like a falling + * block creating a new block * * @param event The event to watch */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityBlockFormEvent(EntityBlockFormEvent event) { /* WORLD BLACKLIST CHECK */ - if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) { return; + } BlockState blockState = event.getNewState(); - if (ExperienceConfig.getInstance().isSnowExploitPrevented() && BlockUtils.shouldBeWatched(blockState)) { + if (ExperienceConfig.getInstance().isSnowExploitPrevented() && BlockUtils.shouldBeWatched( + blockState)) { Block block = blockState.getBlock(); if (BlockUtils.isWithinWorldBounds(block)) { @@ -214,15 +251,16 @@ public class BlockListener implements Listener { World world = event.getBlock().getWorld(); /* WORLD BLACKLIST CHECK */ - if (WorldBlacklist.isWorldBlacklisted(world)) + if (WorldBlacklist.isWorldBlacklisted(world)) { return; + } if (ExperienceConfig.getInstance().preventStoneLavaFarming()) { BlockState newState = event.getNewState(); if (newState.getType() != Material.OBSIDIAN && ExperienceConfig.getInstance().doesBlockGiveSkillXP( - PrimarySkillType.MINING, newState.getType())) { + PrimarySkillType.MINING, newState.getType())) { Block block = newState.getBlock(); if (BlockUtils.isWithinWorldBounds(block)) { BlockUtils.setUnnaturalBlock(block); @@ -256,22 +294,24 @@ public class BlockListener implements Listener { } } - Player player = event.getPlayer(); if (!UserManager.hasPlayerDataKey(player)) { return; } - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if (mcMMOPlayer == null) + if (mmoPlayer == null) { return; + } - if (blockState.getType() == Repair.anvilMaterial && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.REPAIR)) { - mcMMOPlayer.getRepairManager().placedAnvilCheck(); - } else if (blockState.getType() == Salvage.anvilMaterial && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.SALVAGE)) { - mcMMOPlayer.getSalvageManager().placedAnvilCheck(); + if (blockState.getType() == Repair.anvilMaterial && mcMMO.p.getSkillTools() + .doesPlayerHaveSkillPermission(player, PrimarySkillType.REPAIR)) { + mmoPlayer.getRepairManager().placedAnvilCheck(); + } else if (blockState.getType() == Salvage.anvilMaterial && mcMMO.p.getSkillTools() + .doesPlayerHaveSkillPermission(player, PrimarySkillType.SALVAGE)) { + mmoPlayer.getSalvageManager().placedAnvilCheck(); } } @@ -295,7 +335,7 @@ public class BlockListener implements Listener { } //Track unnatural blocks - for(BlockState replacedState : event.getReplacedBlockStates()) { + for (BlockState replacedState : event.getReplacedBlockStates()) { BlockUtils.setUnnaturalBlock(replacedState.getBlock()); } } @@ -308,8 +348,9 @@ public class BlockListener implements Listener { World world = block.getWorld(); /* WORLD BLACKLIST CHECK */ - if (WorldBlacklist.isWorldBlacklisted(world)) + if (WorldBlacklist.isWorldBlacklisted(world)) { return; + } // Minecraft is dumb, the events still throw when a plant "grows" higher than the max block height. Even though no new block is created if (BlockUtils.isWithinWorldBounds(block)) { @@ -349,9 +390,10 @@ public class BlockListener implements Listener { /* ALCHEMY - Cancel any brew in progress for that BrewingStand */ if (block.getType() == Material.BREWING_STAND) { final BlockState blockState = block.getState(); - if (blockState instanceof BrewingStand && Alchemy.brewingStandMap.containsKey(location)) { - Alchemy.brewingStandMap.get(location).cancelBrew(); - } + if (blockState instanceof BrewingStand && Alchemy.brewingStandMap.containsKey( + location)) { + Alchemy.brewingStandMap.get(location).cancelBrew(); + } } Player player = event.getPlayer(); @@ -361,10 +403,10 @@ public class BlockListener implements Listener { return; } - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); //Check if profile is loaded - if (mcMMOPlayer == null) { + if (mmoPlayer == null) { /* Remove metadata from placed watched blocks */ BlockUtils.cleanupBlockMetadata(block); @@ -375,18 +417,19 @@ public class BlockListener implements Listener { /* HERBALISM */ if (BlockUtils.affectedByGreenTerra(block)) { - HerbalismManager herbalismManager = mcMMOPlayer.getHerbalismManager(); + HerbalismManager herbalismManager = mmoPlayer.getHerbalismManager(); /* Green Terra */ if (herbalismManager.canActivateAbility()) { - mcMMOPlayer.checkAbilityActivation(PrimarySkillType.HERBALISM); + mmoPlayer.checkAbilityActivation(PrimarySkillType.HERBALISM); } /* * We don't check the block store here because herbalism has too many unusual edge cases. * Instead, we check it inside the drops handler. */ - if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.HERBALISM)) { + if (mcMMO.p.getSkillTools() + .doesPlayerHaveSkillPermission(player, PrimarySkillType.HERBALISM)) { herbalismManager.processHerbalismBlockBreakEvent(event); } /* @@ -399,17 +442,19 @@ public class BlockListener implements Listener { /* MINING */ else if (BlockUtils.affectedBySuperBreaker(block) && (ItemUtils.isPickaxe(heldItem) || ItemUtils.isHoe(heldItem)) - && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.MINING) + && mcMMO.p.getSkillTools() + .doesPlayerHaveSkillPermission(player, PrimarySkillType.MINING) && !mcMMO.getUserBlockTracker().isIneligible(block)) { - MiningManager miningManager = mcMMOPlayer.getMiningManager(); + MiningManager miningManager = mmoPlayer.getMiningManager(); miningManager.miningBlockCheck(block); } /* WOOD CUTTING */ else if (BlockUtils.hasWoodcuttingXP(block) && ItemUtils.isAxe(heldItem) - && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.WOODCUTTING) + && mcMMO.p.getSkillTools() + .doesPlayerHaveSkillPermission(player, PrimarySkillType.WOODCUTTING) && !mcMMO.getUserBlockTracker().isIneligible(block)) { - WoodcuttingManager woodcuttingManager = mcMMOPlayer.getWoodcuttingManager(); + WoodcuttingManager woodcuttingManager = mmoPlayer.getWoodcuttingManager(); if (woodcuttingManager.canUseTreeFeller(heldItem)) { woodcuttingManager.processTreeFeller(block); } else { @@ -424,12 +469,13 @@ public class BlockListener implements Listener { /* EXCAVATION */ else if (BlockUtils.affectedByGigaDrillBreaker(block) && ItemUtils.isShovel(heldItem) - && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.EXCAVATION) + && mcMMO.p.getSkillTools() + .doesPlayerHaveSkillPermission(player, PrimarySkillType.EXCAVATION) && !mcMMO.getUserBlockTracker().isIneligible(block)) { - final ExcavationManager excavationManager = mcMMOPlayer.getExcavationManager(); + final ExcavationManager excavationManager = mmoPlayer.getExcavationManager(); excavationManager.excavationBlockCheck(block); - if (mcMMOPlayer.getAbilityMode(SuperAbilityType.GIGA_DRILL_BREAKER)) { + if (mmoPlayer.getAbilityMode(SuperAbilityType.GIGA_DRILL_BREAKER)) { excavationManager.gigaDrillBreaker(block); } } @@ -445,17 +491,20 @@ public class BlockListener implements Listener { */ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockBreakHigher(BlockBreakEvent event) { - if (event instanceof FakeEvent) + if (event instanceof FakeEvent) { return; + } /* 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 (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) { return; + } } Player player = event.getPlayer(); @@ -509,13 +558,15 @@ public class BlockListener implements Listener { final Block block = event.getBlock(); /* 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 (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) { return; + } } if (event instanceof FakeBlockDamageEvent) { @@ -525,10 +576,10 @@ public class BlockListener implements Listener { return; } - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); //Profile not loaded - if (mcMMOPlayer == null) { + if (mmoPlayer == null) { return; } @@ -540,30 +591,40 @@ public class BlockListener implements Listener { if (BlockUtils.canActivateAbilities(block)) { ItemStack heldItem = player.getInventory().getItemInMainHand(); - if (mcMMOPlayer.getToolPreparationMode(ToolType.HOE) + if (mmoPlayer.getToolPreparationMode(ToolType.HOE) && ItemUtils.isHoe(heldItem) && (BlockUtils.affectedByGreenTerra(block) || BlockUtils.canMakeMossy(block)) && Permissions.greenTerra(player)) { - mcMMOPlayer.checkAbilityActivation(PrimarySkillType.HERBALISM); - } else if (mcMMOPlayer.getToolPreparationMode(ToolType.AXE) && ItemUtils.isAxe(heldItem) && BlockUtils.hasWoodcuttingXP(block) && Permissions.treeFeller(player)) { - mcMMOPlayer.checkAbilityActivation(PrimarySkillType.WOODCUTTING); - } else if (mcMMOPlayer.getToolPreparationMode(ToolType.PICKAXE) && ItemUtils.isPickaxe(heldItem) && BlockUtils.affectedBySuperBreaker(block) && Permissions.superBreaker(player)) { - mcMMOPlayer.checkAbilityActivation(PrimarySkillType.MINING); - } else if (mcMMOPlayer.getToolPreparationMode(ToolType.SHOVEL) && ItemUtils.isShovel(heldItem) && BlockUtils.affectedByGigaDrillBreaker(block) && Permissions.gigaDrillBreaker(player)) { - mcMMOPlayer.checkAbilityActivation(PrimarySkillType.EXCAVATION); - } else if (mcMMOPlayer.getToolPreparationMode(ToolType.FISTS) && heldItem.getType() == Material.AIR && (BlockUtils.affectedByGigaDrillBreaker(block) - || mcMMO.getMaterialMapStore().isGlass(block.getType()) - || block.getType() == Material.SNOW - || BlockUtils.affectedByBlockCracker(block) && Permissions.berserk(player))) { - mcMMOPlayer.checkAbilityActivation(PrimarySkillType.UNARMED); + mmoPlayer.checkAbilityActivation(PrimarySkillType.HERBALISM); + } else if (mmoPlayer.getToolPreparationMode(ToolType.AXE) && ItemUtils.isAxe(heldItem) + && BlockUtils.hasWoodcuttingXP(block) && Permissions.treeFeller(player)) { + mmoPlayer.checkAbilityActivation(PrimarySkillType.WOODCUTTING); + } else if (mmoPlayer.getToolPreparationMode(ToolType.PICKAXE) && ItemUtils.isPickaxe( + heldItem) && BlockUtils.affectedBySuperBreaker(block) + && Permissions.superBreaker(player)) { + mmoPlayer.checkAbilityActivation(PrimarySkillType.MINING); + } else if (mmoPlayer.getToolPreparationMode(ToolType.SHOVEL) && ItemUtils.isShovel( + heldItem) && BlockUtils.affectedByGigaDrillBreaker(block) + && Permissions.gigaDrillBreaker(player)) { + mmoPlayer.checkAbilityActivation(PrimarySkillType.EXCAVATION); + } else if (mmoPlayer.getToolPreparationMode(ToolType.FISTS) + && heldItem.getType() == Material.AIR && ( + BlockUtils.affectedByGigaDrillBreaker(block) + || mcMMO.getMaterialMapStore().isGlass(block.getType()) + || block.getType() == Material.SNOW + || BlockUtils.affectedByBlockCracker(block) && Permissions.berserk( + player))) { + mmoPlayer.checkAbilityActivation(PrimarySkillType.UNARMED); - if (mcMMOPlayer.getAbilityMode(SuperAbilityType.BERSERK)) { - if (SuperAbilityType.BERSERK.blockCheck(block) && EventUtils.simulateBlockBreak(block, player)) { + if (mmoPlayer.getAbilityMode(SuperAbilityType.BERSERK)) { + if (SuperAbilityType.BERSERK.blockCheck(block) && EventUtils.simulateBlockBreak( + block, player)) { event.setInstaBreak(true); if (block.getType().getKey().getKey().contains("glass")) { - SoundManager.worldSendSound(player.getWorld(), block.getLocation(), SoundType.GLASS); + SoundManager.worldSendSound(player.getWorld(), block.getLocation(), + SoundType.GLASS); } else { SoundManager.sendSound(player, block.getLocation(), SoundType.POP); } @@ -577,7 +638,8 @@ public class BlockListener implements Listener { * * We don't need to check permissions here because they've already been checked for the ability to even activate. */ - if (mcMMOPlayer.getAbilityMode(SuperAbilityType.TREE_FELLER) && BlockUtils.hasWoodcuttingXP(block) && mcMMO.p.getGeneralConfig().getTreeFellerSoundsEnabled()) { + if (mmoPlayer.getAbilityMode(SuperAbilityType.TREE_FELLER) && BlockUtils.hasWoodcuttingXP( + block) && mcMMO.p.getGeneralConfig().getTreeFellerSoundsEnabled()) { SoundManager.sendSound(player, block.getLocation(), SoundType.FIZZ); } } @@ -590,13 +652,15 @@ 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 (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) { return; + } } if (event instanceof FakeBlockDamageEvent) { @@ -609,9 +673,9 @@ public class BlockListener implements Listener { return; } - final McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if (mcMMOPlayer == null) { + if (mmoPlayer == null) { return; } @@ -623,24 +687,31 @@ public class BlockListener implements Listener { * * We don't need to check permissions here because they've already been checked for the ability to even activate. */ - if (mcMMOPlayer.getAbilityMode(SuperAbilityType.GREEN_TERRA) && BlockUtils.canMakeMossy(block)) { - mcMMOPlayer.getHerbalismManager().processGreenTerraBlockConversion(block); - } else if (mcMMOPlayer.getAbilityMode(SuperAbilityType.BERSERK) && (heldItem.getType() == Material.AIR || mcMMO.p.getGeneralConfig().getUnarmedItemsAsUnarmed())) { - if (mcMMOPlayer.getUnarmedManager().canUseBlockCracker() && BlockUtils.affectedByBlockCracker(block)) { + if (mmoPlayer.getAbilityMode(SuperAbilityType.GREEN_TERRA) && BlockUtils.canMakeMossy( + block)) { + mmoPlayer.getHerbalismManager().processGreenTerraBlockConversion(block); + } else if (mmoPlayer.getAbilityMode(SuperAbilityType.BERSERK) && ( + heldItem.getType() == Material.AIR || mcMMO.p.getGeneralConfig() + .getUnarmedItemsAsUnarmed())) { + if (mmoPlayer.getUnarmedManager().canUseBlockCracker() + && BlockUtils.affectedByBlockCracker(block)) { if (EventUtils.simulateBlockBreak(block, player)) { - mcMMOPlayer.getUnarmedManager().blockCrackerCheck(block.getState()); + mmoPlayer.getUnarmedManager().blockCrackerCheck(block.getState()); } } else if (!event.getInstaBreak() && SuperAbilityType.BERSERK.blockCheck(block) && EventUtils.simulateBlockBreak(block, player)) { event.setInstaBreak(true); if (block.getType().getKey().getKey().contains("glass")) { - SoundManager.worldSendSound(player.getWorld(), block.getLocation(), SoundType.GLASS); + SoundManager.worldSendSound(player.getWorld(), block.getLocation(), + SoundType.GLASS); } else { SoundManager.sendSound(player, block.getLocation(), SoundType.POP); } } - } else if (mcMMOPlayer.getWoodcuttingManager().canUseLeafBlower(heldItem) && BlockUtils.isNonWoodPartOfTree(block) && EventUtils.simulateBlockBreak(block, player)) { + } else if (mmoPlayer.getWoodcuttingManager().canUseLeafBlower(heldItem) + && BlockUtils.isNonWoodPartOfTree(block) && EventUtils.simulateBlockBreak(block, + player)) { event.setInstaBreak(true); SoundManager.sendSound(player, block.getLocation(), SoundType.POP); } @@ -649,7 +720,7 @@ public class BlockListener implements Listener { @EventHandler(priority = EventPriority.MONITOR) public void onBlockDamageCleanup(BlockDamageEvent event) { Player player = event.getPlayer(); - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); //Profile not loaded if (UserManager.getPlayer(player) == null) { @@ -658,7 +729,7 @@ public class BlockListener implements Listener { ItemStack heldItem = player.getInventory().getItemInMainHand(); - cleanupAbilityTools(mcMMOPlayer, event.getBlock(), heldItem); + cleanupAbilityTools(mmoPlayer, event.getBlock(), heldItem); debugStickDump(player, event.getBlock()); } @@ -675,46 +746,61 @@ public class BlockListener implements Listener { final BlockState blockState = block.getState(); if (mmoPlayer.isDebugMode()) { - if (mcMMO.getUserBlockTracker().isIneligible(blockState)) - player.sendMessage("[mcMMO DEBUG] This block is not natural and does not reward treasures/XP"); - else { + if (mcMMO.getUserBlockTracker().isIneligible(blockState)) { + player.sendMessage( + "[mcMMO DEBUG] This block is not natural and does not reward treasures/XP"); + } else { player.sendMessage("[mcMMO DEBUG] This block is considered natural by mcMMO"); mmoPlayer.getExcavationManager().printExcavationDebug(player, block); } 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().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)) - 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 (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 || blockState instanceof BrewingStand) { if (ContainerMetadataUtils.isContainerOwned(blockState)) { player.sendMessage("[mcMMO DEBUG] This container has a registered owner"); - final OfflinePlayer furnacePlayer = ContainerMetadataUtils.getContainerOwner(blockState); + final OfflinePlayer furnacePlayer = ContainerMetadataUtils.getContainerOwner( + blockState); if (furnacePlayer != null) { - player.sendMessage("[mcMMO DEBUG] This container is owned by player "+furnacePlayer.getName()); + player.sendMessage("[mcMMO DEBUG] This container is owned by player " + + furnacePlayer.getName()); } + } else { + player.sendMessage( + "[mcMMO DEBUG] This container does not have a registered owner"); } - else - player.sendMessage("[mcMMO DEBUG] This container does not have a registered owner"); } - 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."); + 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."); + } - player.sendMessage(ChatColor.RED+"You can turn this debug info off by typing "+ChatColor.GOLD+"/mmodebug"); + player.sendMessage( + ChatColor.RED + "You can turn this debug info off by typing " + ChatColor.GOLD + + "/mmodebug"); } } /** * Clean up ability tools after a block break event. + * * @param mmoPlayer The player * @param block The block * @param heldItem The item in the player's hand diff --git a/src/main/java/com/gmail/nossr50/listeners/ChunkListener.java b/src/main/java/com/gmail/nossr50/listeners/ChunkListener.java index 21e0e48e0..56580ece8 100644 --- a/src/main/java/com/gmail/nossr50/listeners/ChunkListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/ChunkListener.java @@ -1,14 +1,13 @@ package com.gmail.nossr50.listeners; import com.gmail.nossr50.mcMMO; +import java.util.Arrays; import org.bukkit.Chunk; import org.bukkit.entity.LivingEntity; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.world.ChunkUnloadEvent; -import java.util.Arrays; - public class ChunkListener implements Listener { @EventHandler(ignoreCancelled = true, priority = org.bukkit.event.EventPriority.MONITOR) @@ -16,7 +15,8 @@ public class ChunkListener implements Listener { final Chunk unloadingChunk = event.getChunk(); // Avoid processing if chunk is null or unloaded - if (unloadingChunk == null || !unloadingChunk.isLoaded() || unloadingChunk.getEntities() == null) { + if (unloadingChunk == null || !unloadingChunk.isLoaded() + || unloadingChunk.getEntities() == null) { return; } @@ -24,9 +24,11 @@ public class ChunkListener implements Listener { Arrays.stream(unloadingChunk.getEntities()) .filter(entity -> entity instanceof LivingEntity) .map(entity -> (LivingEntity) entity) - .forEach(livingEntity -> mcMMO.getTransientEntityTracker().removeTrackedEntity(livingEntity)); + .forEach(livingEntity -> mcMMO.getTransientEntityTracker() + .removeTrackedEntity(livingEntity)); } catch (Exception ex) { - mcMMO.p.getLogger().warning("Caught exception during chunk unload event processing: " + ex.getMessage()); + mcMMO.p.getLogger().warning( + "Caught exception during chunk unload event processing: " + ex.getMessage()); } } } diff --git a/src/main/java/com/gmail/nossr50/listeners/EntityListener.java b/src/main/java/com/gmail/nossr50/listeners/EntityListener.java index 005d4d159..34c53367f 100644 --- a/src/main/java/com/gmail/nossr50/listeners/EntityListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/EntityListener.java @@ -1,5 +1,11 @@ package com.gmail.nossr50.listeners; +import static com.gmail.nossr50.util.AttributeMapper.MAPPED_MAX_HEALTH; +import static com.gmail.nossr50.util.MobMetadataUtils.addMobFlags; +import static com.gmail.nossr50.util.MobMetadataUtils.flagMetadata; +import static com.gmail.nossr50.util.MobMetadataUtils.hasMobFlag; +import static com.gmail.nossr50.util.MobMetadataUtils.hasMobFlags; + import com.gmail.nossr50.config.WorldBlacklist; import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.datatypes.player.McMMOPlayer; @@ -16,7 +22,11 @@ import com.gmail.nossr50.skills.mining.MiningManager; import com.gmail.nossr50.skills.taming.Taming; import com.gmail.nossr50.skills.taming.TamingManager; import com.gmail.nossr50.skills.unarmed.UnarmedManager; -import com.gmail.nossr50.util.*; +import com.gmail.nossr50.util.BlockUtils; +import com.gmail.nossr50.util.ItemUtils; +import com.gmail.nossr50.util.MetadataConstants; +import com.gmail.nossr50.util.Misc; +import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.NotificationManager; import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.random.ProbabilityUtil; @@ -24,19 +34,52 @@ import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.ProjectileUtils; import com.gmail.nossr50.worldguard.WorldGuardManager; import com.gmail.nossr50.worldguard.WorldGuardUtils; +import java.util.Set; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.NamespacedKey; import org.bukkit.OfflinePlayer; import org.bukkit.block.Block; import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.*; +import org.bukkit.entity.AnimalTamer; +import org.bukkit.entity.Animals; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Enderman; +import org.bukkit.entity.Endermite; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.FallingBlock; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.entity.TNTPrimed; +import org.bukkit.entity.Tameable; +import org.bukkit.entity.Trident; +import org.bukkit.entity.Wolf; import org.bukkit.event.Cancellable; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; -import org.bukkit.event.entity.*; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.event.entity.EntityBreedEvent; +import org.bukkit.event.entity.EntityChangeBlockEvent; +import org.bukkit.event.entity.EntityCombustByEntityEvent; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.bukkit.event.entity.EntityDeathEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.entity.EntityShootBowEvent; +import org.bukkit.event.entity.EntityTameEvent; +import org.bukkit.event.entity.EntityTargetEvent; +import org.bukkit.event.entity.EntityTargetLivingEntityEvent; +import org.bukkit.event.entity.EntityTransformEvent; +import org.bukkit.event.entity.ExplosionPrimeEvent; +import org.bukkit.event.entity.FoodLevelChangeEvent; +import org.bukkit.event.entity.PotionSplashEvent; +import org.bukkit.event.entity.ProjectileHitEvent; +import org.bukkit.event.entity.ProjectileLaunchEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.PotionMeta; @@ -45,17 +88,12 @@ import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.projectiles.ProjectileSource; -import java.util.Set; - -import static com.gmail.nossr50.util.AttributeMapper.MAPPED_MAX_HEALTH; -import static com.gmail.nossr50.util.MobMetadataUtils.*; - public class EntityListener implements Listener { private final mcMMO pluginRef; /** - * We can use this {@link NamespacedKey} for {@link Enchantment} comparisons to - * check if a {@link Player} has a {@link Trident} enchanted with "Piercing". + * We can use this {@link NamespacedKey} for {@link Enchantment} comparisons to check if a + * {@link Player} has a {@link Trident} enchanted with "Piercing". */ private final NamespacedKey piercingEnchantment = NamespacedKey.minecraft("piercing"); private final static Set TRANSFORMABLE_ENTITIES @@ -71,7 +109,7 @@ public class EntityListener implements Listener { //Transfer metadata keys from mob-spawned mobs to new mobs if (hasMobFlags(livingEntity)) { - for(Entity entity : event.getTransformedEntities()) { + for (Entity entity : event.getTransformedEntities()) { if (entity instanceof LivingEntity transformedEntity) { addMobFlags(livingEntity, transformedEntity); } @@ -87,8 +125,9 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityTargetEntity(EntityTargetLivingEntityEvent event) { - if (!ExperienceConfig.getInstance().isEndermanEndermiteFarmingPrevented()) + if (!ExperienceConfig.getInstance().isEndermanEndermiteFarmingPrevented()) { return; + } //It's rare but targets can be null sometimes if (event.getTarget() == null) { @@ -109,8 +148,9 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) 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 player) { Entity projectile = event.getProjectile(); @@ -122,16 +162,22 @@ public class EntityListener implements Listener { ItemStack bow = event.getBow(); - if (bow == null) + if (bow == null) { return; + } if (bow.containsEnchantment(mcMMO.p.getEnchantmentMapper().getInfinity())) { - projectile.setMetadata(MetadataConstants.METADATA_KEY_INF_ARROW, MetadataConstants.MCMMO_METADATA_VALUE); + projectile.setMetadata(MetadataConstants.METADATA_KEY_INF_ARROW, + MetadataConstants.MCMMO_METADATA_VALUE); } // Set BowType, Force, and Distance metadata - projectile.setMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE, new FixedMetadataValue(pluginRef, Math.min(event.getForce() * mcMMO.p.getAdvancedConfig().getForceMultiplier(), 1.0))); - projectile.setMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE, new FixedMetadataValue(pluginRef, arrow.getLocation())); + projectile.setMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE, + new FixedMetadataValue(pluginRef, Math.min( + event.getForce() * mcMMO.p.getAdvancedConfig().getForceMultiplier(), + 1.0))); + projectile.setMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE, + new FixedMetadataValue(pluginRef, arrow.getLocation())); //Cleanup metadata in 1 minute in case normal collection falls through CombatUtils.delayArrowMetaCleanup(arrow); @@ -141,15 +187,17 @@ 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().getShooter() instanceof Player player) { /* WORLD GUARD MAIN FLAG CHECK */ if (WorldGuardUtils.isWorldGuardLoaded()) { - if (!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) { return; + } } if (event.getEntity() instanceof Arrow arrow) { @@ -158,22 +206,29 @@ public class EntityListener implements Listener { // If fired from an item with multi-shot, we need to track if (ItemUtils.doesPlayerHaveEnchantmentInHands(player, "multishot")) { - arrow.setMetadata(MetadataConstants.METADATA_KEY_MULTI_SHOT_ARROW, MetadataConstants.MCMMO_METADATA_VALUE); + arrow.setMetadata(MetadataConstants.METADATA_KEY_MULTI_SHOT_ARROW, + MetadataConstants.MCMMO_METADATA_VALUE); } - if (!arrow.hasMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE)) - arrow.setMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE, new FixedMetadataValue(pluginRef, 1.0)); + if (!arrow.hasMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE)) { + arrow.setMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE, + new FixedMetadataValue(pluginRef, 1.0)); + } - if (!arrow.hasMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE)) - arrow.setMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE, new FixedMetadataValue(pluginRef, arrow.getLocation())); + if (!arrow.hasMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE)) { + arrow.setMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE, + new FixedMetadataValue(pluginRef, arrow.getLocation())); + } //Check both hands if (ItemUtils.doesPlayerHaveEnchantmentInHands(player, "piercing")) { return; } - if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.ARCHERY_ARROW_RETRIEVAL, UserManager.getPlayer(player))) { - arrow.setMetadata(MetadataConstants.METADATA_KEY_TRACKED_ARROW, MetadataConstants.MCMMO_METADATA_VALUE); + if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.ARCHERY_ARROW_RETRIEVAL, + UserManager.getPlayer(player))) { + arrow.setMetadata(MetadataConstants.METADATA_KEY_TRACKED_ARROW, + MetadataConstants.MCMMO_METADATA_VALUE); } } } @@ -182,18 +237,19 @@ 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(); Entity entity = event.getEntity(); - Material notYetReplacedType = block.getState().getType(); //because its from getState() this is the block that hasn't been changed yet, which is likely air/lava/water etc + Material notYetReplacedType = block.getState() + .getType(); //because its from getState() this is the block that hasn't been changed yet, which is likely air/lava/water etc // When the event is fired for the falling block that changes back to a // normal block @@ -215,14 +271,18 @@ public class EntityListener implements Listener { if (mcMMO.getUserBlockTracker().isIneligible(block) && !isTracked) { mcMMO.getUserBlockTracker().setEligible(block); - entity.setMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK, MetadataConstants.MCMMO_METADATA_VALUE); - TravelingBlockMetaCleanup metaCleanupTask = new TravelingBlockMetaCleanup(entity, pluginRef); - mcMMO.p.getFoliaLib().getScheduler().runAtEntityTimer(entity, metaCleanupTask, 20, 20*60); //6000 ticks is 5 minutes + entity.setMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK, + MetadataConstants.MCMMO_METADATA_VALUE); + TravelingBlockMetaCleanup metaCleanupTask = new TravelingBlockMetaCleanup(entity, + pluginRef); + mcMMO.p.getFoliaLib().getScheduler().runAtEntityTimer(entity, metaCleanupTask, 20, + 20 * 60); //6000 ticks is 5 minutes } else if (isTracked) { BlockUtils.setUnnaturalBlock(block); entity.removeMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK, pluginRef); } - } else if ((block.getType() == Material.REDSTONE_ORE || block.getType().getKey().getKey().equalsIgnoreCase("deepslate_redstone_ore"))) { + } else if ((block.getType() == Material.REDSTONE_ORE || block.getType().getKey().getKey() + .equalsIgnoreCase("deepslate_redstone_ore"))) { //Redstone ore fire this event and should be ignored } else { if (mcMMO.getUserBlockTracker().isIneligible(block)) { @@ -254,8 +314,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) { @@ -279,7 +338,8 @@ public class EntityListener implements Listener { } else if (attacker instanceof Projectile projectile) { if (projectile.getShooter() instanceof Player) { - if (!WorldGuardManager.getInstance().hasMainFlag((Player) projectile.getShooter())) { + if (!WorldGuardManager.getInstance() + .hasMainFlag((Player) projectile.getShooter())) { return; } } @@ -300,8 +360,9 @@ public class EntityListener implements Listener { return; } - - if ((ExperienceConfig.getInstance().isNPCInteractionPrevented() && Misc.isNPCEntityExcludingVillagers(defender)) || !defender.isValid() || !(defender instanceof LivingEntity target)) { + if ((ExperienceConfig.getInstance().isNPCInteractionPrevented() + && Misc.isNPCEntityExcludingVillagers(defender)) || !defender.isValid() + || !(defender instanceof LivingEntity target)) { return; } @@ -309,7 +370,8 @@ public class EntityListener implements Listener { return; } - if (ExperienceConfig.getInstance().isNPCInteractionPrevented() && Misc.isNPCEntityExcludingVillagers(attacker)) { + if (ExperienceConfig.getInstance().isNPCInteractionPrevented() + && Misc.isNPCEntityExcludingVillagers(attacker)) { return; } @@ -324,7 +386,8 @@ public class EntityListener implements Listener { attacker = (Entity) animalTamer; } } else if (attacker instanceof TNTPrimed && defender instanceof Player) { - if (BlastMining.processBlastMiningExplosion(event, (TNTPrimed) attacker, (Player) defender)) { + if (BlastMining.processBlastMiningExplosion(event, (TNTPrimed) attacker, + (Player) defender)) { return; } } @@ -333,7 +396,8 @@ public class EntityListener implements Listener { if (defender instanceof Player defendingPlayer) { //If the attacker is a Player or a projectile belonging to a player if (attacker instanceof Projectile projectile) { - if (projectile.getShooter() instanceof Player attackingPlayer && !attackingPlayer.equals(defendingPlayer)) { + if (projectile.getShooter() instanceof Player attackingPlayer + && !attackingPlayer.equals(defendingPlayer)) { //Check for friendly fire and cancel the event if (checkIfInPartyOrSamePlayer(event, defendingPlayer, attackingPlayer)) { return; @@ -341,9 +405,9 @@ public class EntityListener implements Listener { } //Deflect checks - final McMMOPlayer mcMMOPlayer = UserManager.getPlayer(defendingPlayer); - if (mcMMOPlayer != null) { - UnarmedManager unarmedManager = mcMMOPlayer.getUnarmedManager(); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(defendingPlayer); + if (mmoPlayer != null) { + UnarmedManager unarmedManager = mmoPlayer.getUnarmedManager(); if (unarmedManager.canDeflect()) { if (projectile instanceof Arrow && unarmedManager.deflectCheck()) { @@ -352,9 +416,10 @@ public class EntityListener implements Listener { } } } - } else if (attacker instanceof Player attackingPlayer){ - if (checkIfInPartyOrSamePlayer(event, defendingPlayer, attackingPlayer)) + } else if (attacker instanceof Player attackingPlayer) { + if (checkIfInPartyOrSamePlayer(event, defendingPlayer, attackingPlayer)) { return; + } } } @@ -385,7 +450,7 @@ public class EntityListener implements Listener { CombatUtils.handleHealthbars(attacker, target, event.getFinalDamage(), pluginRef); } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) public void onEntityDamageMonitor(EntityDamageByEntityEvent entityDamageEvent) { if (entityDamageEvent.getEntity() instanceof LivingEntity livingEntity) { @@ -399,25 +464,31 @@ public class EntityListener implements Listener { CombatUtils.delayArrowMetaCleanup(arrow); } - if (entityDamageEvent.getEntity() instanceof Player player && entityDamageEvent.getDamager() instanceof Player) { - McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + if (entityDamageEvent.getEntity() instanceof Player player + && entityDamageEvent.getDamager() instanceof Player) { + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); if (mmoPlayer != null) { if (mmoPlayer.isDebugMode()) { - player.sendMessage(ChatColor.GOLD + "(mmodebug start of combat report) EntityDamageByEntityEvent DEBUG Info:"); + player.sendMessage(ChatColor.GOLD + + "(mmodebug start of combat report) EntityDamageByEntityEvent DEBUG Info:"); player.sendMessage("You are being damaged by another player in this event"); player.sendMessage("Raw Damage: " + entityDamageEvent.getDamage()); - player.sendMessage("Your max health: "+player.getAttribute(MAPPED_MAX_HEALTH).getValue()); - player.sendMessage("Your current health: "+player.getHealth()); + player.sendMessage("Your max health: " + player.getAttribute(MAPPED_MAX_HEALTH) + .getValue()); + player.sendMessage("Your current health: " + player.getHealth()); player.sendMessage(ChatColor.GREEN + "Damage Modifiers (final damage)"); for (EntityDamageEvent.DamageModifier modifier : EntityDamageEvent.DamageModifier.values()) { - player.sendMessage("Modifier "+modifier.name()+": " + entityDamageEvent.getDamage(modifier)); + player.sendMessage( + "Modifier " + modifier.name() + ": " + entityDamageEvent.getDamage( + modifier)); } player.sendMessage("Final damage: " + entityDamageEvent.getFinalDamage()); if (entityDamageEvent.isCancelled()) { - player.sendMessage("Event was cancelled, which means no damage should be done."); + player.sendMessage( + "Event was cancelled, which means no damage should be done."); } player.sendMessage(ChatColor.RED + "(mmodebug end of combat report)"); @@ -425,25 +496,31 @@ public class EntityListener implements Listener { } } - if (entityDamageEvent.getDamager() instanceof Player player && entityDamageEvent.getEntity() instanceof Player otherPlayer) { - McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + if (entityDamageEvent.getDamager() instanceof Player player + && entityDamageEvent.getEntity() instanceof Player otherPlayer) { + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); if (mmoPlayer != null) { if (mmoPlayer.isDebugMode()) { - player.sendMessage(ChatColor.GOLD + "(mmodebug start of combat report) EntityDamageByEntityEvent DEBUG Info:"); + player.sendMessage(ChatColor.GOLD + + "(mmodebug start of combat report) EntityDamageByEntityEvent DEBUG Info:"); player.sendMessage("You are dealing damage to another player in this event"); player.sendMessage("Raw Damage: " + entityDamageEvent.getDamage()); player.sendMessage(ChatColor.GREEN + "Damage Modifiers (final damage)"); for (EntityDamageEvent.DamageModifier modifier : EntityDamageEvent.DamageModifier.values()) { - player.sendMessage("Modifier "+modifier.name()+": " + entityDamageEvent.getDamage(modifier)); + player.sendMessage( + "Modifier " + modifier.name() + ": " + entityDamageEvent.getDamage( + modifier)); } player.sendMessage("Final damage: " + entityDamageEvent.getFinalDamage()); - player.sendMessage("Target players max health: "+otherPlayer.getAttribute(MAPPED_MAX_HEALTH).getValue()); - player.sendMessage("Target players current health: "+otherPlayer.getHealth()); + player.sendMessage("Target players max health: " + otherPlayer.getAttribute( + MAPPED_MAX_HEALTH).getValue()); + player.sendMessage("Target players current health: " + otherPlayer.getHealth()); if (entityDamageEvent.isCancelled()) { - player.sendMessage("Event was cancelled, which means no damage should be done."); + player.sendMessage( + "Event was cancelled, which means no damage should be done."); } player.sendMessage(ChatColor.RED + "(mmodebug end of combat report)"); @@ -452,7 +529,8 @@ public class EntityListener implements Listener { } } - public boolean checkIfInPartyOrSamePlayer(Cancellable event, Player defendingPlayer, Player attackingPlayer) { + public boolean checkIfInPartyOrSamePlayer(Cancellable event, Player defendingPlayer, + Player attackingPlayer) { // This check is probably necessary outside of the party system if (defendingPlayer.equals(attackingPlayer)) { return true; @@ -462,12 +540,13 @@ public class EntityListener implements Listener { return false; } - if (!UserManager.hasPlayerDataKey(defendingPlayer) || !UserManager.hasPlayerDataKey(attackingPlayer)) { + if (!UserManager.hasPlayerDataKey(defendingPlayer) || !UserManager.hasPlayerDataKey( + attackingPlayer)) { return true; } //Party Friendly Fire - if (!mcMMO.p.getGeneralConfig().getPartyFriendlyFire()) + if (!mcMMO.p.getGeneralConfig().getPartyFriendlyFire()) { if ((mcMMO.p.getPartyManager().inSameParty(defendingPlayer, attackingPlayer) || mcMMO.p.getPartyManager().areAllies(defendingPlayer, attackingPlayer)) && !(Permissions.friendlyFire(attackingPlayer) @@ -475,30 +554,33 @@ public class EntityListener implements Listener { event.setCancelled(true); return true; } + } return false; } /** * 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().hasMetadata(MetadataConstants.METADATA_KEY_EXPLOSION_FROM_RUPTURE)) { - event.getEntity().removeMetadata(MetadataConstants.METADATA_KEY_EXPLOSION_FROM_RUPTURE, mcMMO.p); + event.getEntity() + .removeMetadata(MetadataConstants.METADATA_KEY_EXPLOSION_FROM_RUPTURE, mcMMO.p); } if (event.getEntity() instanceof Player player) { /* WORLD GUARD MAIN FLAG CHECK */ if (WorldGuardUtils.isWorldGuardLoaded()) { - if (!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) { return; + } } } @@ -534,7 +616,9 @@ public class EntityListener implements Listener { } */ - if ((ExperienceConfig.getInstance().isNPCInteractionPrevented() && Misc.isNPCEntityExcludingVillagers(entity)) || !entity.isValid() || !(entity instanceof LivingEntity livingEntity)) { + if ((ExperienceConfig.getInstance().isNPCInteractionPrevented() + && Misc.isNPCEntityExcludingVillagers(entity)) || !entity.isValid() + || !(entity instanceof LivingEntity livingEntity)) { return; } @@ -545,43 +629,43 @@ public class EntityListener implements Listener { DamageCause cause = event.getCause(); if (livingEntity instanceof Player) { - Player player = (Player) entity; + final Player player = (Player) entity; if (!UserManager.hasPlayerDataKey(player)) { return; } - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); //Profile not loaded - if (mcMMOPlayer == null) + if (mmoPlayer == null) { return; + } /* Check for invincibility */ - if (mcMMOPlayer.getGodMode()) { + if (mmoPlayer.getGodMode()) { event.setCancelled(true); return; } if (event.getFinalDamage() >= 1) { - mcMMOPlayer.actualizeRecentlyHurt(); + mmoPlayer.actualizeRecentlyHurt(); } - } - - else if (livingEntity instanceof Tameable pet) { + } else if (livingEntity instanceof Tameable pet) { AnimalTamer owner = pet.getOwner(); if (owner instanceof Player player) { /* WORLD GUARD MAIN FLAG CHECK */ if (WorldGuardUtils.isWorldGuardLoaded()) { - if (!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) { return; + } } } if (Taming.canPreventDamage(pet, owner)) { - Player player = (Player) owner; + final Player player = (Player) owner; Wolf wolf = (Wolf) pet; //Profile not loaded @@ -653,8 +737,7 @@ 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) { @@ -671,8 +754,7 @@ public class EntityListener implements Listener { /** * Monitor EntityDeath events. * - * @param event - * The event to watch + * @param event The event to watch */ @EventHandler(ignoreCancelled = true) public void onEntityDeath(EntityDeathEvent event) { @@ -687,7 +769,8 @@ public class EntityListener implements Listener { return; } - if (ExperienceConfig.getInstance().isNPCInteractionPrevented() && Misc.isNPCEntityExcludingVillagers(entity)) { + if (ExperienceConfig.getInstance().isNPCInteractionPrevented() + && Misc.isNPCEntityExcludingVillagers(entity)) { return; } @@ -697,14 +780,14 @@ public class EntityListener implements Listener { /** * Monitor CreatureSpawn events. * - * @param event - * The event to watch + * @param event The event to watch */ @EventHandler(priority = EventPriority.MONITOR) public void onCreatureSpawn(CreatureSpawnEvent event) { /* WORLD BLACKLIST CHECK */ - if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) { return; + } LivingEntity livingEntity = event.getEntity(); @@ -727,10 +810,11 @@ public class EntityListener implements Listener { } } - private void trackSpawnedAndPassengers(LivingEntity livingEntity, MobMetaFlagType mobMetaFlagType) { + private void trackSpawnedAndPassengers(LivingEntity livingEntity, + MobMetaFlagType mobMetaFlagType) { flagMetadata(mobMetaFlagType, livingEntity); - for(Entity passenger : livingEntity.getPassengers()) { + for (Entity passenger : livingEntity.getPassengers()) { if (passenger != null) { flagMetadata(mobMetaFlagType, livingEntity); } @@ -740,7 +824,8 @@ public class EntityListener implements Listener { @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) public void onEntityBreed(EntityBreedEvent event) { if (ExperienceConfig.getInstance().isCOTWBreedingPrevented()) { - if (hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, event.getFather()) || hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, event.getMother())) { + if (hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, event.getFather()) || hasMobFlag( + MobMetaFlagType.COTW_SUMMONED_MOB, event.getMother())) { event.setCancelled(true); Animals mom = (Animals) event.getMother(); Animals father = (Animals) event.getFather(); @@ -751,7 +836,8 @@ public class EntityListener implements Listener { //Inform the player if (event.getBreeder() instanceof Player player) { - NotificationManager.sendPlayerInformationChatOnly(player, "Taming.Summon.COTW.BreedingDisallowed"); + NotificationManager.sendPlayerInformationChatOnly(player, + "Taming.Summon.COTW.BreedingDisallowed"); } } } @@ -760,18 +846,19 @@ 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; + } final Entity entity = event.getEntity(); - if (!(entity instanceof TNTPrimed) || !entity.hasMetadata(MetadataConstants.METADATA_KEY_TRACKED_TNT)) { + if (!(entity instanceof TNTPrimed) || !entity.hasMetadata( + MetadataConstants.METADATA_KEY_TRACKED_TNT)) { return; } @@ -791,8 +878,9 @@ public class EntityListener implements Listener { /* WORLD GUARD MAIN FLAG CHECK */ if (WorldGuardUtils.isWorldGuardLoaded()) { - if (!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) { return; + } } final MiningManager miningManager = UserManager.getPlayer(player).getMiningManager(); @@ -805,24 +893,26 @@ 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(); - if (!(entity instanceof TNTPrimed) || !entity.hasMetadata(MetadataConstants.METADATA_KEY_TRACKED_TNT)) { + if (!(entity instanceof TNTPrimed) || !entity.hasMetadata( + MetadataConstants.METADATA_KEY_TRACKED_TNT)) { return; } // We can make this assumption because we (should) be the only ones // using this exact metadata - Player player = pluginRef.getServer().getPlayerExact(entity.getMetadata(MetadataConstants.METADATA_KEY_TRACKED_TNT).get(0).asString()); + Player player = pluginRef.getServer().getPlayerExact( + entity.getMetadata(MetadataConstants.METADATA_KEY_TRACKED_TNT).get(0).asString()); if (!UserManager.hasPlayerDataKey(player)) { return; @@ -830,8 +920,9 @@ public class EntityListener implements Listener { /* WORLD GUARD MAIN FLAG CHECK */ if (WorldGuardUtils.isWorldGuardLoaded()) { - if (!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) { return; + } } //Profile not loaded @@ -850,14 +941,14 @@ 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(); @@ -872,8 +963,9 @@ public class EntityListener implements Listener { /* WORLD GUARD MAIN FLAG CHECK */ if (WorldGuardUtils.isWorldGuardLoaded()) { - if (!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) { return; + } } if (!UserManager.hasPlayerDataKey(player)) { @@ -892,9 +984,11 @@ public class EntityListener implements Listener { //The main hand is used over the off hand if they both have food, so check the main hand first Material foodInHand; - if (mcMMO.getMaterialMapStore().isFood(player.getInventory().getItemInMainHand().getType())) { + if (mcMMO.getMaterialMapStore() + .isFood(player.getInventory().getItemInMainHand().getType())) { foodInHand = player.getInventory().getItemInMainHand().getType(); - } else if (mcMMO.getMaterialMapStore().isFood(player.getInventory().getItemInOffHand().getType())) { + } else if (mcMMO.getMaterialMapStore() + .isFood(player.getInventory().getItemInOffHand().getType())) { foodInHand = player.getInventory().getItemInOffHand().getType(); } else { return; //Not Food @@ -909,7 +1003,8 @@ public class EntityListener implements Listener { //Hacky 1.17 support if (foodInHand.getKey().getKey().equalsIgnoreCase("glow_berries")) { if (Permissions.isSubSkillEnabled(player, SubSkillType.HERBALISM_FARMERS_DIET)) { - event.setFoodLevel(UserManager.getPlayer(player).getHerbalismManager().farmersDiet(newFoodLevel)); + event.setFoodLevel(UserManager.getPlayer(player).getHerbalismManager() + .farmersDiet(newFoodLevel)); } return; @@ -917,41 +1012,43 @@ public class EntityListener implements Listener { switch (foodInHand) { 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 + */ if (Permissions.isSubSkillEnabled(player, SubSkillType.HERBALISM_FARMERS_DIET)) { - event.setFoodLevel(UserManager.getPlayer(player).getHerbalismManager().farmersDiet(newFoodLevel)); + event.setFoodLevel(UserManager.getPlayer(player).getHerbalismManager() + .farmersDiet(newFoodLevel)); } return; 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)); + event.setFoodLevel(UserManager.getPlayer(player).getHerbalismManager() + .farmersDiet(newFoodLevel)); } return; case COD: @@ -961,7 +1058,8 @@ public class EntityListener implements Listener { case COOKED_SALMON: if (Permissions.isSubSkillEnabled(player, SubSkillType.FISHING_FISHERMANS_DIET)) { - event.setFoodLevel(UserManager.getPlayer(player).getFishingManager().handleFishermanDiet(newFoodLevel)); + event.setFoodLevel(UserManager.getPlayer(player).getFishingManager() + .handleFishermanDiet(newFoodLevel)); } return; @@ -972,31 +1070,33 @@ 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) { return; } - Player player = (Player) event.getOwner(); + final Player player = (Player) event.getOwner(); /* WORLD GUARD MAIN FLAG CHECK */ if (WorldGuardUtils.isWorldGuardLoaded()) { - if (!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) { return; + } } LivingEntity livingEntity = event.getEntity(); if (!UserManager.hasPlayerDataKey(player) - || (ExperienceConfig.getInstance().isNPCInteractionPrevented() && Misc.isNPCEntityExcludingVillagers(livingEntity)) + || (ExperienceConfig.getInstance().isNPCInteractionPrevented() + && Misc.isNPCEntityExcludingVillagers(livingEntity)) || hasMobFlag(MobMetaFlagType.EGG_MOB, livingEntity) || hasMobFlag(MobMetaFlagType.MOB_SPAWNER_MOB, livingEntity)) { return; @@ -1015,14 +1115,14 @@ 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(); Entity target = event.getTarget(); @@ -1033,8 +1133,9 @@ public class EntityListener implements Listener { /* WORLD GUARD MAIN FLAG CHECK */ if (WorldGuardUtils.isWorldGuardLoaded()) { - if (!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) { return; + } } if (!UserManager.hasPlayerDataKey(player) || !CombatUtils.isFriendlyPet(player, tameable)) { @@ -1044,23 +1145,23 @@ public class EntityListener implements Listener { // 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 - if (!(Permissions.friendlyFire(player) && Permissions.friendlyFire((Player) tameable.getOwner()))) { + if (!(Permissions.friendlyFire(player) && Permissions.friendlyFire( + (Player) tameable.getOwner()))) { event.setCancelled(true); } } /** - * Handle PotionSplash events in order to fix broken Splash Potion of - * Saturation. + * 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; + } ItemMeta meta = event.getPotion().getItem().getItemMeta(); @@ -1075,7 +1176,9 @@ public class EntityListener implements Listener { for (LivingEntity entity : event.getAffectedEntities()) { int duration = (int) (effect.getDuration() * event.getIntensity(entity)); - entity.addPotionEffect(new PotionEffect(effect.getType(), duration, effect.getAmplifier(), effect.isAmbient())); + entity.addPotionEffect( + new PotionEffect(effect.getType(), duration, effect.getAmplifier(), + effect.isAmbient())); } } } @@ -1083,8 +1186,9 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onProjectileHitEvent(ProjectileHitEvent event) { /* WORLD BLACKLIST CHECK */ - if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) { return; + } if (event.getEntity() instanceof Arrow arrow) { if (ProjectileUtils.isCrossbowProjectile(arrow)) { diff --git a/src/main/java/com/gmail/nossr50/listeners/InteractionManager.java b/src/main/java/com/gmail/nossr50/listeners/InteractionManager.java index 0422d1064..b16fa538e 100644 --- a/src/main/java/com/gmail/nossr50/listeners/InteractionManager.java +++ b/src/main/java/com/gmail/nossr50/listeners/InteractionManager.java @@ -6,11 +6,10 @@ import com.gmail.nossr50.datatypes.skills.subskills.interfaces.InteractType; import com.gmail.nossr50.datatypes.skills.subskills.interfaces.Interaction; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.LogUtils; -import org.bukkit.event.Event; - import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; +import org.bukkit.event.Event; public class InteractionManager { private static HashMap> interactRegister; @@ -19,27 +18,33 @@ public class InteractionManager { public static void initMaps() { /* 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<>(); + } } /** * Registers subskills with the Interaction registration + * * @param abstractSubSkill the target subskill to register */ public static void registerSubSkill(AbstractSubSkill abstractSubSkill) { //Store a unique copy of each subskill - if (!subSkillList.contains(abstractSubSkill)) + if (!subSkillList.contains(abstractSubSkill)) { subSkillList.add(abstractSubSkill); + } //Init ArrayList - interactRegister.computeIfAbsent(abstractSubSkill.getInteractType(), k -> new ArrayList<>()); + interactRegister.computeIfAbsent(abstractSubSkill.getInteractType(), + k -> new ArrayList<>()); //Registration array reference ArrayList arrayRef = interactRegister.get(abstractSubSkill.getInteractType()); @@ -52,12 +57,13 @@ public class InteractionManager { //Register in name map subSkillNameMap.putIfAbsent(lowerCaseName, abstractSubSkill); - LogUtils.debug(mcMMO.p.getLogger(), "Registered subskill: "+ abstractSubSkill.getConfigKeyName()); + LogUtils.debug(mcMMO.p.getLogger(), + "Registered subskill: " + abstractSubSkill.getConfigKeyName()); } /** - * Grabs the registered abstract skill by its name - * Is not case sensitive + * 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 */ @@ -67,22 +73,26 @@ public class InteractionManager { /** * Processes the associated Interactions for this event + * * @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) { - if (interactRegister.get(curInteractType) == null) + if (interactRegister.get(curInteractType) == null) { return; + } - for(Interaction interaction : interactRegister.get(curInteractType)) { + for (Interaction interaction : interactRegister.get(curInteractType)) { interaction.doInteraction(event, plugin); } } /** * 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 + * 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() { @@ -99,6 +109,7 @@ public class InteractionManager { /** * 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 9f3722720..b62574aca 100644 --- a/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java @@ -29,8 +29,24 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; -import org.bukkit.event.inventory.*; -import org.bukkit.inventory.*; +import org.bukkit.event.inventory.BrewEvent; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.event.inventory.CraftItemEvent; +import org.bukkit.event.inventory.FurnaceBurnEvent; +import org.bukkit.event.inventory.FurnaceExtractEvent; +import org.bukkit.event.inventory.FurnaceSmeltEvent; +import org.bukkit.event.inventory.InventoryAction; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryDragEvent; +import org.bukkit.event.inventory.InventoryMoveItemEvent; +import org.bukkit.event.inventory.InventoryOpenEvent; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.BrewerInventory; +import org.bukkit.inventory.FurnaceInventory; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; public class InventoryListener implements Listener { private final mcMMO plugin; @@ -42,12 +58,15 @@ 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(); BlockState furnaceState = furnaceBlock.getState(); - ItemStack smelting = furnaceState instanceof Furnace ? ((Furnace) furnaceState).getInventory().getSmelting() : null; + ItemStack smelting = + furnaceState instanceof Furnace ? ((Furnace) furnaceState).getInventory() + .getSmelting() : null; if (!ItemUtils.isSmeltable(smelting)) { return; @@ -64,22 +83,25 @@ public class InventoryListener implements Listener { return; } - McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); if (mmoPlayer != null) { boolean debugMode = mmoPlayer.isDebugMode(); if (debugMode) { player.sendMessage("FURNACE FUEL EFFICIENCY DEBUG REPORT"); - player.sendMessage("Furnace - "+furnace.hashCode()); - player.sendMessage("Furnace Type: "+furnaceBlock.getType()); - player.sendMessage("Burn Length before Fuel Efficiency is applied - "+event.getBurnTime()); + player.sendMessage("Furnace - " + furnace.hashCode()); + player.sendMessage("Furnace Type: " + furnaceBlock.getType()); + player.sendMessage("Burn Length before Fuel Efficiency is applied - " + + event.getBurnTime()); } - event.setBurnTime(mmoPlayer.getSmeltingManager().fuelEfficiency(event.getBurnTime())); + event.setBurnTime( + mmoPlayer.getSmeltingManager().fuelEfficiency(event.getBurnTime())); if (debugMode) { - player.sendMessage("New Furnace Burn Length (after applying fuel efficiency) "+event.getBurnTime()); + player.sendMessage("New Furnace Burn Length (after applying fuel efficiency) " + + event.getBurnTime()); player.sendMessage(""); } } @@ -89,10 +111,12 @@ 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; + } - BlockState blockState = event.getBlock().getState(); //Furnaces can only be cast from a BlockState not a Block + BlockState blockState = event.getBlock() + .getState(); //Furnaces can only be cast from a BlockState not a Block ItemStack smelting = event.getSource(); if (!ItemUtils.isSmeltable(smelting)) { @@ -118,8 +142,9 @@ 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; + } BlockState furnaceBlock = event.getBlock().getState(); @@ -132,11 +157,13 @@ public class InventoryListener implements Listener { if (furnaceBlock instanceof Furnace) { /* WORLD GUARD MAIN FLAG CHECK */ if (WorldGuardUtils.isWorldGuardLoaded()) { - if (!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) { return; + } } - if (!UserManager.hasPlayerDataKey(player) || !Permissions.vanillaXpBoost(player, PrimarySkillType.SMELTING)) { + if (!UserManager.hasPlayerDataKey(player) || !Permissions.vanillaXpBoost(player, + PrimarySkillType.SMELTING)) { return; } @@ -154,8 +181,9 @@ 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; + } //We should never care to do processing if the player clicks outside the window // if (isOutsideWindowClick(event)) @@ -164,18 +192,22 @@ public class InventoryListener implements Listener { Inventory inventory = event.getInventory(); Player player = ((Player) event.getWhoClicked()).getPlayer(); - McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); if (event.getInventory() instanceof FurnaceInventory furnaceInventory) { - if (!mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.SMELTING)) + if (!mcMMO.p.getSkillTools() + .doesPlayerHaveSkillPermission(player, PrimarySkillType.SMELTING)) { return; + } //Switch owners ContainerMetadataUtils.processContainerOwnership(furnaceInventory.getHolder(), player); } if (event.getInventory() instanceof BrewerInventory brewerInventory) { - if (!mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.ALCHEMY)) + if (!mcMMO.p.getSkillTools() + .doesPlayerHaveSkillPermission(player, PrimarySkillType.ALCHEMY)) { return; + } // switch owners ContainerMetadataUtils.processContainerOwnership(brewerInventory.getHolder(), player); } @@ -192,15 +224,17 @@ public class InventoryListener implements Listener { HumanEntity whoClicked = event.getWhoClicked(); - if (mmoPlayer == null || !Permissions.isSubSkillEnabled(whoClicked, SubSkillType.ALCHEMY_CONCOCTIONS)) { + if (mmoPlayer == null || !Permissions.isSubSkillEnabled(whoClicked, + SubSkillType.ALCHEMY_CONCOCTIONS)) { return; } // TODO: Investigate why this WG check is all the way down here? /* WORLD GUARD MAIN FLAG CHECK */ if (WorldGuardUtils.isWorldGuardLoaded()) { - if (!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) { return; + } } final ItemStack clicked = event.getCurrentItem(); @@ -210,8 +244,8 @@ public class InventoryListener implements Listener { || clicked.getType() == Material.SPLASH_POTION || clicked.getType() == Material.LINGERING_POTION)) || (cursor != null && (cursor.getType() == Material.POTION - || cursor.getType() == Material.SPLASH_POTION - || cursor.getType() == Material.LINGERING_POTION))) { + || cursor.getType() == Material.SPLASH_POTION + || cursor.getType() == Material.LINGERING_POTION))) { AlchemyPotionBrewer.scheduleCheck(stand); return; } @@ -230,7 +264,8 @@ public class InventoryListener implements Listener { return; } - if (!AlchemyPotionBrewer.transferItems(event.getView(), event.getRawSlot(), click)) { + if (!AlchemyPotionBrewer.transferItems(event.getView(), event.getRawSlot(), + click)) { return; } @@ -289,8 +324,9 @@ 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(); @@ -306,7 +342,8 @@ public class InventoryListener implements Listener { HumanEntity whoClicked = event.getWhoClicked(); - if (!UserManager.hasPlayerDataKey(event.getWhoClicked()) || !Permissions.isSubSkillEnabled(whoClicked, SubSkillType.ALCHEMY_CONCOCTIONS)) { + if (!UserManager.hasPlayerDataKey(event.getWhoClicked()) || !Permissions.isSubSkillEnabled( + whoClicked, SubSkillType.ALCHEMY_CONCOCTIONS)) { return; } @@ -318,12 +355,13 @@ public class InventoryListener implements Listener { ItemStack ingredient = ((BrewerInventory) inventory).getIngredient(); if (AlchemyPotionBrewer.isEmpty(ingredient) || ingredient.isSimilar(cursor)) { - Player player = (Player) whoClicked; + final Player player = (Player) whoClicked; /* WORLD GUARD MAIN FLAG CHECK */ if (WorldGuardUtils.isWorldGuardLoaded()) { - if (!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) { return; + } } if (AlchemyPotionBrewer.isValidIngredientByPlayer(player, cursor)) { @@ -341,11 +379,13 @@ public class InventoryListener implements Listener { @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) 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) + if (event instanceof FakeBrewEvent) { return; + } Location location = event.getBlock().getLocation(); if (Alchemy.brewingStandMap.containsKey(location)) { @@ -368,9 +408,11 @@ public class InventoryListener implements Listener { public void onInventoryMoveItemEvent(InventoryMoveItemEvent event) { /* WORLD BLACKLIST CHECK */ - if (event.getSource().getLocation() != null) - if (WorldBlacklist.isWorldBlacklisted(event.getSource().getLocation().getWorld())) + if (event.getSource().getLocation() != null) { + if (WorldBlacklist.isWorldBlacklisted(event.getSource().getLocation().getWorld())) { return; + } + } final Inventory inventory = event.getDestination(); @@ -384,12 +426,16 @@ public class InventoryListener implements Listener { ItemStack item = event.getItem(); - if (mcMMO.p.getGeneralConfig().getPreventHopperTransferIngredients() && item.getType() != Material.POTION && item.getType() != Material.SPLASH_POTION && item.getType() != Material.LINGERING_POTION) { + if (mcMMO.p.getGeneralConfig().getPreventHopperTransferIngredients() + && item.getType() != Material.POTION && item.getType() != Material.SPLASH_POTION + && item.getType() != Material.LINGERING_POTION) { event.setCancelled(true); return; } - if (mcMMO.p.getGeneralConfig().getPreventHopperTransferBottles() && (item.getType() == Material.POTION || item.getType() == Material.SPLASH_POTION || item.getType() == Material.LINGERING_POTION)) { + if (mcMMO.p.getGeneralConfig().getPreventHopperTransferBottles() && ( + item.getType() == Material.POTION || item.getType() == Material.SPLASH_POTION + || item.getType() == Material.LINGERING_POTION)) { event.setCancelled(true); return; } @@ -397,7 +443,7 @@ public class InventoryListener implements Listener { OfflinePlayer offlinePlayer = ContainerMetadataUtils.getContainerOwner(brewingStand); if (offlinePlayer != null && offlinePlayer.isOnline()) { - McMMOPlayer mmoPlayer = UserManager.getPlayer(offlinePlayer.getPlayer()); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(offlinePlayer.getPlayer()); if (mmoPlayer != null) { ingredientLevel = mmoPlayer.getAlchemyManager().getTier(); } @@ -419,13 +465,15 @@ public class InventoryListener implements Listener { SkillUtils.removeAbilityBuff(event.getCurrentItem()); if (event.getAction() == InventoryAction.HOTBAR_SWAP) { - if (isOutsideWindowClick(event)) + if (isOutsideWindowClick(event)) { return; + } PlayerInventory playerInventory = event.getWhoClicked().getInventory(); - if (playerInventory.getItem(event.getHotbarButton()) != null) + if (playerInventory.getItem(event.getHotbarButton()) != null) { SkillUtils.removeAbilityBuff(playerInventory.getItem(event.getHotbarButton())); + } } } @@ -437,8 +485,9 @@ 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(); @@ -453,15 +502,17 @@ public class InventoryListener implements Listener { return; } - Player player = (Player) whoClicked; + final Player player = (Player) whoClicked; /* WORLD GUARD MAIN FLAG CHECK */ if (WorldGuardUtils.isWorldGuardLoaded()) { - if (!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) { return; + } } - mcMMO.p.getFoliaLib().getScheduler().runAtEntity(whoClicked, new PlayerUpdateInventoryTask((Player) whoClicked)); + mcMMO.p.getFoliaLib().getScheduler() + .runAtEntity(whoClicked, new PlayerUpdateInventoryTask((Player) whoClicked)); } } diff --git a/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java b/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java index 6ec4e2015..821bd8b66 100644 --- a/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java @@ -20,20 +20,39 @@ import com.gmail.nossr50.skills.repair.RepairManager; import com.gmail.nossr50.skills.salvage.Salvage; import com.gmail.nossr50.skills.salvage.SalvageManager; import com.gmail.nossr50.skills.taming.TamingManager; -import com.gmail.nossr50.util.*; +import com.gmail.nossr50.util.BlockUtils; +import com.gmail.nossr50.util.ChimaeraWing; +import com.gmail.nossr50.util.EventUtils; +import com.gmail.nossr50.util.HardcoreManager; +import com.gmail.nossr50.util.LogUtils; +import com.gmail.nossr50.util.MetadataConstants; +import com.gmail.nossr50.util.Misc; +import com.gmail.nossr50.util.MobHealthbarUtils; +import com.gmail.nossr50.util.Motd; +import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.scoreboards.ScoreboardManager; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.worldguard.WorldGuardManager; import com.gmail.nossr50.worldguard.WorldGuardUtils; +import java.util.Locale; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.*; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.ExperienceOrb; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Item; +import org.bukkit.entity.ItemFrame; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Minecart; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; import org.bukkit.entity.minecart.PoweredMinecart; import org.bukkit.event.Event; import org.bukkit.event.EventHandler; @@ -43,12 +62,21 @@ import org.bukkit.event.block.Action; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityPickupItemEvent; import org.bukkit.event.entity.PlayerDeathEvent; -import org.bukkit.event.player.*; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.PlayerChangedWorldEvent; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.player.PlayerDropItemEvent; +import org.bukkit.event.player.PlayerFishEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.player.PlayerSwapHandItemsEvent; +import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; -import java.util.Locale; - public class PlayerListener implements Listener { private final mcMMO plugin; @@ -59,9 +87,8 @@ public class PlayerListener implements Listener { /** * Monitor PlayerTeleportEvents. *

- * These events are monitored for the purpose of setting the - * player's last teleportation timestamp, in order to prevent - * possible Acrobatics exploitation. + * These events are monitored for the purpose of setting the player's last teleportation + * timestamp, in order to prevent possible Acrobatics exploitation. * * @param event The event to monitor */ @@ -74,7 +101,8 @@ public class PlayerListener implements Listener { ScoreboardManager.teardownPlayer(event.getPlayer()); } return; - } else if (WorldBlacklist.isWorldBlacklisted(event.getFrom().getWorld()) && mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) { + } else if (WorldBlacklist.isWorldBlacklisted(event.getFrom().getWorld()) + && mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) { //This only fires if they are travelling to a non-blacklisted world from a blacklisted world //Setup scoreboards @@ -85,11 +113,14 @@ public class PlayerListener implements Listener { /* WORLD GUARD MAIN FLAG CHECK */ if (WorldGuardUtils.isWorldGuardLoaded()) { - if (!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) { return; + } } - if (!UserManager.hasPlayerDataKey(player) || mcMMO.p.getGeneralConfig().getXPAfterTeleportCooldown() <= 0 || event.getFrom().equals(event.getTo())) { + if (!UserManager.hasPlayerDataKey(player) + || mcMMO.p.getGeneralConfig().getXPAfterTeleportCooldown() <= 0 || event.getFrom() + .equals(event.getTo())) { return; } @@ -104,63 +135,73 @@ public class PlayerListener implements Listener { /** * Handle {@link EntityDamageByEntityEvent} at the highest priority. *

- * This handler is used to clear the names of mobs with health bars to - * fix death messages showing mob health bars on death. + * This handler is used to clear the names of mobs with health bars to fix death messages + * showing mob health bars on death. * * @param event the event to listen to */ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEntityDamageByEntityHighest(EntityDamageByEntityEvent event) { // we only care about players as this is for fixing player death messages - if (!(event.getEntity() instanceof Player player)) + if (!(event.getEntity() instanceof Player player)) { return; + } // get the attacker LivingEntity attacker; - if (event.getDamager() instanceof LivingEntity) + if (event.getDamager() instanceof LivingEntity) { attacker = (LivingEntity) event.getDamager(); + } // attempt to find creator of a projectile - else if (event.getDamager() instanceof Projectile && ((Projectile) event.getDamager()).getShooter() instanceof LivingEntity) + else if (event.getDamager() instanceof Projectile + && ((Projectile) event.getDamager()).getShooter() instanceof LivingEntity) { attacker = (LivingEntity) ((Projectile) event.getDamager()).getShooter(); - else + } else { return; + } - if (attacker instanceof HumanEntity) + if (attacker instanceof HumanEntity) { return; + } // world blacklist check - if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) { return; + } // world guard main flag check - if (WorldGuardUtils.isWorldGuardLoaded() && !WorldGuardManager.getInstance().hasMainFlag((Player) event.getEntity())) + if (WorldGuardUtils.isWorldGuardLoaded() && !WorldGuardManager.getInstance() + .hasMainFlag((Player) event.getEntity())) { return; + } // we only want to handle player deaths - if ((player.getHealth() - event.getFinalDamage()) > 0) + if ((player.getHealth() - event.getFinalDamage()) > 0) { return; + } // temporarily clear the mob's name new MobHealthDisplayUpdaterTask(attacker).run(); // set the name back - mcMMO.p.getFoliaLib().getScheduler().runAtEntityLater(attacker, () -> MobHealthbarUtils.handleMobHealthbars(attacker, 0, mcMMO.p), 1); + mcMMO.p.getFoliaLib().getScheduler().runAtEntityLater(attacker, + () -> MobHealthbarUtils.handleMobHealthbars(attacker, 0, mcMMO.p), 1); } /** * Monitor PlayerDeathEvents. *

- * These events are monitored for the purpose of dealing the penalties - * associated with hardcore and vampirism modes. If neither of these - * modes are enabled, or if the player who died has hardcore bypass - * permissions, this handler does nothing. + * These events are monitored for the purpose of dealing the penalties associated with hardcore + * and vampirism modes. If neither of these modes are enabled, or if the player who died has + * hardcore bypass permissions, this handler does nothing. * * @param event The event to monitor */ @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(); boolean vampirismEnabled = HardcoreManager.isVampirismEnabled(); @@ -171,7 +212,8 @@ public class PlayerListener implements Listener { Player killedPlayer = event.getEntity(); - if (!killedPlayer.hasMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA) || Permissions.hardcoreBypass(killedPlayer)) { + if (!killedPlayer.hasMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA) + || Permissions.hardcoreBypass(killedPlayer)) { return; } @@ -179,8 +221,9 @@ public class PlayerListener implements Listener { /* WORLD GUARD MAIN FLAG CHECK */ if (WorldGuardUtils.isWorldGuardLoaded()) { - if (!WorldGuardManager.getInstance().hasMainFlag(killedPlayer)) + if (!WorldGuardManager.getInstance().hasMainFlag(killedPlayer)) { return; + } } if (statLossEnabled || (killer != null && vampirismEnabled)) { @@ -206,9 +249,8 @@ public class PlayerListener implements Listener { /** * Monitor PlayerChangedWorldEvents. *

- * These events are monitored for the purpose of removing god mode or - * player parties if they are not allowed on the world the player has - * changed to. + * These events are monitored for the purpose of removing god mode or player parties if they are + * not allowed on the world the player has changed to. * * @param event The event to monitor */ @@ -225,34 +267,34 @@ public class PlayerListener implements Listener { return; } - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - mcMMOPlayer.checkGodMode(); - mcMMOPlayer.checkParty(); + mmoPlayer.checkGodMode(); + mmoPlayer.checkParty(); } /** * Monitor PlayerDropItemEvents. *

- * These events are monitored for the purpose of flagging sharable - * dropped items, as well as removing ability buffs from pickaxes - * and shovels. + * These events are monitored for the purpose of flagging sharable dropped items, as well as + * removing ability buffs from pickaxes and shovels. * * @param event The event to monitor */ @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 (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) { return; + } } - // TODO: This sharing item system seems very unoptimized, temporarily disabling /*if (ItemUtils.isSharable(event.getItemDrop().getItemStack())) { event.getItemDrop().getItemStack().setMetadata( @@ -266,26 +308,29 @@ public class PlayerListener implements Listener { /** * Handle PlayerFishEvents at the highest priority. *

- * These events are used for the purpose of handling our anti-exploit - * code, as well as dealing with ice fishing. + * These events are used for the purpose of handling our anti-exploit code, as well as dealing + * with ice fishing. * * @param event The event to modify */ @EventHandler(priority = EventPriority.HIGH, 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 (!WorldGuardManager.getInstance().hasMainFlag(player)) { return; + } } - if (!UserManager.hasPlayerDataKey(player) || !mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.FISHING)) { + if (!UserManager.hasPlayerDataKey(player) || !mcMMO.p.getSkillTools() + .doesPlayerHaveSkillPermission(player, PrimarySkillType.FISHING)) { return; } @@ -310,7 +355,8 @@ public class PlayerListener implements Listener { ItemStack replacementCatch = new ItemStack(Material.SALMON, 1); - McMMOReplaceVanillaTreasureEvent replaceVanillaTreasureEvent = new McMMOReplaceVanillaTreasureEvent(fishingCatch, replacementCatch, player); + McMMOReplaceVanillaTreasureEvent replaceVanillaTreasureEvent = new McMMOReplaceVanillaTreasureEvent( + fishingCatch, replacementCatch, player); Bukkit.getPluginManager().callEvent(replaceVanillaTreasureEvent); //Replace @@ -320,8 +366,10 @@ public class PlayerListener implements Listener { if (Permissions.vanillaXpBoost(player, PrimarySkillType.FISHING)) { //Don't modify XP below vanilla values - if (fishingManager.handleVanillaXpBoost(event.getExpToDrop()) > 1) - event.setExpToDrop(fishingManager.handleVanillaXpBoost(event.getExpToDrop())); + if (fishingManager.handleVanillaXpBoost(event.getExpToDrop()) > 1) { + event.setExpToDrop( + fishingManager.handleVanillaXpBoost(event.getExpToDrop())); + } } } return; @@ -343,33 +391,37 @@ public class PlayerListener implements Listener { private void cancelFishingEventAndDropXp(PlayerFishEvent event, Player player) { event.setCancelled(true); - ExperienceOrb experienceOrb = (ExperienceOrb) player.getWorld().spawnEntity(player.getEyeLocation(), EntityType.EXPERIENCE_ORB); + ExperienceOrb experienceOrb = (ExperienceOrb) player.getWorld() + .spawnEntity(player.getEyeLocation(), EntityType.EXPERIENCE_ORB); experienceOrb.setExperience(event.getExpToDrop()); } /** * Monitor PlayerFishEvents. *

- * These events are monitored for the purpose of handling the various - * Fishing skills and abilities. + * These events are monitored for the purpose of handling the various Fishing skills and + * abilities. * * @param event The event to monitor */ @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 (!WorldGuardManager.getInstance().hasMainFlag(player)) { return; + } } - if (!UserManager.hasPlayerDataKey(player) || !mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.FISHING)) { + if (!UserManager.hasPlayerDataKey(player) || !mcMMO.p.getSkillTools() + .doesPlayerHaveSkillPermission(player, PrimarySkillType.FISHING)) { return; } @@ -383,12 +435,14 @@ public class PlayerListener implements Listener { //Track the hook if (ExperienceConfig.getInstance().isFishingExploitingPrevented()) { - if (event.getHook().getMetadata(MetadataConstants.METADATA_KEY_FISH_HOOK_REF).size() == 0) { + if (event.getHook().getMetadata(MetadataConstants.METADATA_KEY_FISH_HOOK_REF).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); if (caught instanceof Item caughtItem) { @@ -410,39 +464,43 @@ public class PlayerListener implements Listener { && inHand.getItemMeta() != null && inHand.getType().getKey().getKey().equalsIgnoreCase("fishing_rod")) { if (inHand.getItemMeta().hasEnchants()) { - for(Enchantment enchantment : inHand.getItemMeta().getEnchants().keySet()) { + for (Enchantment enchantment : inHand.getItemMeta().getEnchants() + .keySet()) { if (enchantment.toString().toLowerCase().contains("lure")) { lureLevel = inHand.getEnchantmentLevel(enchantment); } } } - // Prevent any potential odd behavior by only processing if no offhand fishing rod is present - if (!player.getInventory().getItemInOffHand().getType().getKey().getKey().equalsIgnoreCase("fishing_rod")) { - // In case of offhand fishing rod, don't process anything - fishingManager.masterAngler(event.getHook(), lureLevel); - fishingManager.setFishingTarget(); + // Prevent any potential odd behavior by only processing if no offhand fishing rod is present + if (!player.getInventory().getItemInOffHand().getType().getKey().getKey() + .equalsIgnoreCase("fishing_rod")) { + // In case of offhand fishing rod, don't process anything + fishingManager.masterAngler(event.getHook(), lureLevel); + fishingManager.setFishingTarget(); + } } } - } return; case CAUGHT_FISH: - if (caught instanceof Item) { + if (caught instanceof Item caughtItem) { if (ExperienceConfig.getInstance().isFishingExploitingPrevented()) { fishingManager.processExploiting(event.getHook().getLocation().toVector()); - if (fishingManager.isExploitingFishing(event.getHook().getLocation().toVector())) { - player.sendMessage(LocaleLoader.getString("Fishing.ScarcityTip", ExperienceConfig.getInstance().getFishingExploitingOptionMoveRange())); + if (fishingManager.isExploitingFishing( + event.getHook().getLocation().toVector())) { + player.sendMessage(LocaleLoader.getString("Fishing.ScarcityTip", + ExperienceConfig.getInstance() + .getFishingExploitingOptionMoveRange())); event.setExpToDrop(0); - Item caughtItem = (Item) caught; caughtItem.remove(); return; } } - fishingManager.processFishing((Item) caught); + fishingManager.processFishing(caughtItem); fishingManager.setFishingTarget(); } return; @@ -459,16 +517,17 @@ public class PlayerListener implements Listener { /** * Handle PlayerPickupItemEvents at the highest priority. *

- * These events are used to handle item sharing between party members and - * are also used to handle item pickup for the Unarmed skill. + * These events are used to handle item sharing between party members and are also used to + * handle item pickup for the Unarmed skill. * * @param event The event to modify */ @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 (Misc.isNPCEntityExcludingVillagers(event.getEntity())) { return; @@ -478,8 +537,9 @@ public class PlayerListener implements Listener { /* WORLD GUARD MAIN FLAG CHECK */ if (WorldGuardUtils.isWorldGuardLoaded()) { - if (!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) { return; + } } if (!UserManager.hasPlayerDataKey(player)) { @@ -487,8 +547,8 @@ public class PlayerListener implements Listener { } //Profile not loaded - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if (mcMMOPlayer == null) { + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + if (mmoPlayer == null) { return; } @@ -500,16 +560,17 @@ public class PlayerListener implements Listener { } if (drop.hasMetadata(MetadataConstants.METADATA_KEY_DISARMED_ITEM)) { - if (!player.getName().equals(drop.getMetadata(MetadataConstants.METADATA_KEY_DISARMED_ITEM).get(0).asString())) { + if (!player.getName() + .equals(drop.getMetadata(MetadataConstants.METADATA_KEY_DISARMED_ITEM) + .get(0).asString())) { event.setCancelled(true); } - return; } // TODO: Temporarily disabling sharing items... - /*if (!drop.hasMetadata(MetadataConstants.METADATA_KEY_TRACKED_ITEM) && mcMMOPlayer.inParty() && ItemUtils.isSharable(dropStack)) { - event.setCancelled(ShareHandler.handleItemShare(drop, mcMMOPlayer)); + /*if (!drop.hasMetadata(MetadataConstants.METADATA_KEY_TRACKED_ITEM) && mmoPlayer.inParty() && ItemUtils.isSharable(dropStack)) { + event.setCancelled(ShareHandler.handleItemShare(drop, mmoPlayer)); if (event.isCancelled()) { SoundManager.sendSound(player, player.getLocation(), SoundType.POP); @@ -532,9 +593,8 @@ public class PlayerListener implements Listener { /** * Monitor PlayerQuitEvents. *

- * These events are monitored for the purpose of resetting player - * variables and other garbage collection tasks that must take place when - * a player exits the server. + * These events are monitored for the purpose of resetting player variables and other garbage + * collection tasks that must take place when a player exits the server. * * @param event The event to monitor */ @@ -546,24 +606,23 @@ public class PlayerListener implements Listener { return; } - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); //Profile not loaded - if (mcMMOPlayer == null) { + if (mmoPlayer == null) { return; } //Use a sync save if the server is shutting down to avoid race conditions - mcMMOPlayer.logout(mcMMO.isServerShutdownExecuted()); + mmoPlayer.logout(mcMMO.isServerShutdownExecuted()); mcMMO.getTransientMetadataTools().cleanLivingEntityMetadata(event.getPlayer()); } /** * Monitor PlayerJoinEvents. *

- * These events are monitored for the purpose of initializing player - * variables, as well as handling the MOTD display and other important - * join messages. + * These events are monitored for the purpose of initializing player variables, as well as + * handling the MOTD display and other important join messages. * * @param event The event to monitor */ @@ -572,23 +631,24 @@ public class PlayerListener implements Listener { Player player = event.getPlayer(); //Delay loading for 3 seconds in case the player has a save task running, its hacky but it should do the trick - mcMMO.p.getFoliaLib().getScheduler().runLaterAsync(new PlayerProfileLoadingTask(player), 60); + mcMMO.p.getFoliaLib().getScheduler() + .runLaterAsync(new PlayerProfileLoadingTask(player), 60); if (mcMMO.p.getGeneralConfig().getMOTDEnabled() && Permissions.motd(player)) { Motd.displayAll(player); } if (plugin.isXPEventEnabled() && mcMMO.p.getGeneralConfig().playerJoinEventInfo()) { - player.sendMessage(LocaleLoader.getString("XPRate.Event", ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier())); + player.sendMessage(LocaleLoader.getString("XPRate.Event", + ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier())); } } /** * Monitor PlayerRespawnEvents. *

- * These events are monitored for the purpose of setting the - * player's last respawn timestamp, in order to prevent - * possible exploitation. + * These events are monitored for the purpose of setting the player's last respawn timestamp, in + * order to prevent possible exploitation. * * @param event The event to monitor */ @@ -616,19 +676,22 @@ 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 (!WorldGuardManager.getInstance().hasMainFlag(player)) { return; + } } - if (event.getClickedBlock() == null) + if (event.getClickedBlock() == null) { return; + } Block clickedBlock = event.getClickedBlock(); Material clickedBlockType = clickedBlock.getType(); @@ -636,12 +699,14 @@ public class PlayerListener implements Listener { if (clickedBlockType == Repair.anvilMaterial || clickedBlockType == Salvage.anvilMaterial) { event.setUseItemInHand(Event.Result.ALLOW); - if (!event.getPlayer().isSneaking() && mcMMO.getMaterialMapStore().isToolActivationBlackListed(clickedBlockType)) { + if (!event.getPlayer().isSneaking() && mcMMO.getMaterialMapStore() + .isToolActivationBlackListed(clickedBlockType)) { event.setUseInteractedBlock(Event.Result.DENY); } } - if (event.getHand() != EquipmentSlot.HAND || !UserManager.hasPlayerDataKey(player) || player.getGameMode() == GameMode.CREATIVE) { + if (event.getHand() != EquipmentSlot.HAND || !UserManager.hasPlayerDataKey(player) + || player.getGameMode() == GameMode.CREATIVE) { return; } @@ -650,21 +715,23 @@ public class PlayerListener implements Listener { return; } - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - MiningManager miningManager = mcMMOPlayer.getMiningManager(); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + MiningManager miningManager = mmoPlayer.getMiningManager(); ItemStack heldItem = player.getInventory().getItemInMainHand(); switch (event.getAction()) { case RIGHT_CLICK_BLOCK: Material type = clickedBlock.getType(); - if (!mcMMO.p.getGeneralConfig().getAbilitiesOnlyActivateWhenSneaking() || player.isSneaking()) { + if (!mcMMO.p.getGeneralConfig().getAbilitiesOnlyActivateWhenSneaking() + || player.isSneaking()) { /* REPAIR CHECKS */ if (type == Repair.anvilMaterial - && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.REPAIR) + && mcMMO.p.getSkillTools() + .doesPlayerHaveSkillPermission(player, PrimarySkillType.REPAIR) && mcMMO.getRepairableManager().isRepairable(heldItem) && heldItem.getAmount() <= 1) { - RepairManager repairManager = mcMMOPlayer.getRepairManager(); + RepairManager repairManager = mmoPlayer.getRepairManager(); event.setCancelled(true); // Make sure the player knows what he's doing when trying to repair an enchanted item @@ -675,19 +742,22 @@ public class PlayerListener implements Listener { } /* SALVAGE CHECKS */ else if (type == Salvage.anvilMaterial - && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.SALVAGE) - && RankUtils.hasUnlockedSubskill(player, SubSkillType.SALVAGE_SCRAP_COLLECTOR) + && mcMMO.p.getSkillTools() + .doesPlayerHaveSkillPermission(player, PrimarySkillType.SALVAGE) + && RankUtils.hasUnlockedSubskill(player, + SubSkillType.SALVAGE_SCRAP_COLLECTOR) && mcMMO.getSalvageableManager().isSalvageable(heldItem) && heldItem.getAmount() <= 1) { - SalvageManager salvageManager = UserManager.getPlayer(player).getSalvageManager(); - event.setCancelled(true); + SalvageManager salvageManager = UserManager.getPlayer(player) + .getSalvageManager(); + event.setCancelled(true); - // Make sure the player knows what he's doing when trying to salvage an enchanted item - if (salvageManager.checkConfirmation(true)) { - SkillUtils.removeAbilityBoostsFromInventory(player); - salvageManager.handleSalvage(clickedBlock.getLocation(), heldItem); - player.updateInventory(); - } + // Make sure the player knows what he's doing when trying to salvage an enchanted item + if (salvageManager.checkConfirmation(true)) { + SkillUtils.removeAbilityBoostsFromInventory(player); + salvageManager.handleSalvage(clickedBlock.getLocation(), heldItem); + player.updateInventory(); + } } } @@ -705,25 +775,32 @@ public class PlayerListener implements Listener { case LEFT_CLICK_BLOCK: type = clickedBlock.getType(); - if (!mcMMO.p.getGeneralConfig().getAbilitiesOnlyActivateWhenSneaking() || player.isSneaking()) { + if (!mcMMO.p.getGeneralConfig().getAbilitiesOnlyActivateWhenSneaking() + || player.isSneaking()) { /* REPAIR CHECKS */ - if (type == Repair.anvilMaterial && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.REPAIR) && mcMMO.getRepairableManager().isRepairable(heldItem)) { - RepairManager repairManager = mcMMOPlayer.getRepairManager(); + if (type == Repair.anvilMaterial && mcMMO.p.getSkillTools() + .doesPlayerHaveSkillPermission(player, PrimarySkillType.REPAIR) + && mcMMO.getRepairableManager().isRepairable(heldItem)) { + RepairManager repairManager = mmoPlayer.getRepairManager(); // Cancel repairing an enchanted item if (repairManager.checkConfirmation(false)) { repairManager.setLastAnvilUse(0); - player.sendMessage(LocaleLoader.getString("Skills.Cancelled", LocaleLoader.getString("Repair.Pretty.Name"))); + player.sendMessage(LocaleLoader.getString("Skills.Cancelled", + LocaleLoader.getString("Repair.Pretty.Name"))); } } /* SALVAGE CHECKS */ - else if (type == Salvage.anvilMaterial && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.SALVAGE) && mcMMO.getSalvageableManager().isSalvageable(heldItem)) { - SalvageManager salvageManager = mcMMOPlayer.getSalvageManager(); + else if (type == Salvage.anvilMaterial && mcMMO.p.getSkillTools() + .doesPlayerHaveSkillPermission(player, PrimarySkillType.SALVAGE) + && mcMMO.getSalvageableManager().isSalvageable(heldItem)) { + SalvageManager salvageManager = mmoPlayer.getSalvageManager(); // Cancel salvaging an enchanted item if (salvageManager.checkConfirmation(false)) { salvageManager.setLastAnvilUse(0); - player.sendMessage(LocaleLoader.getString("Skills.Cancelled", LocaleLoader.getString("Salvage.Pretty.Name"))); + player.sendMessage(LocaleLoader.getString("Skills.Cancelled", + LocaleLoader.getString("Salvage.Pretty.Name"))); } } } @@ -743,15 +820,17 @@ 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 (!WorldGuardManager.getInstance().hasMainFlag(player)) { return; + } } if (event.getHand() != EquipmentSlot.HAND @@ -765,33 +844,40 @@ public class PlayerListener implements Listener { return; } - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if (mcMMOPlayer == null) + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + if (mmoPlayer == null) { return; + } ItemStack heldItem = player.getInventory().getItemInMainHand(); //Spam Fishing Detection - if (event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_AIR) { + if (event.getAction() == Action.RIGHT_CLICK_BLOCK + || event.getAction() == Action.RIGHT_CLICK_AIR) { if (ExperienceConfig.getInstance().isFishingExploitingPrevented() - && (heldItem.getType() == Material.FISHING_ROD || player.getInventory().getItemInOffHand().getType() == Material.FISHING_ROD)) { - if (player.isInsideVehicle() && (player.getVehicle() instanceof Minecart || player.getVehicle() instanceof PoweredMinecart)) { + && (heldItem.getType() == Material.FISHING_ROD + || player.getInventory().getItemInOffHand().getType() + == Material.FISHING_ROD)) { + if (player.isInsideVehicle() && (player.getVehicle() instanceof Minecart + || player.getVehicle() instanceof PoweredMinecart)) { player.getVehicle().eject(); } - //mcMMOPlayer.getFishingManager().setFishingRodCastTimestamp(); + //mmoPlayer.getFishingManager().setFishingRodCastTimestamp(); } } 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; } //Hmm - if (event.getClickedBlock() == null) + if (event.getClickedBlock() == null) { return; + } Block block = event.getClickedBlock(); BlockState blockState = block.getState(); @@ -800,21 +886,21 @@ public class PlayerListener implements Listener { if (BlockUtils.canActivateTools(blockState)) { if (mcMMO.p.getGeneralConfig().getAbilitiesEnabled()) { if (BlockUtils.canActivateHerbalism(blockState)) { - mcMMOPlayer.processAbilityActivation(PrimarySkillType.HERBALISM); + mmoPlayer.processAbilityActivation(PrimarySkillType.HERBALISM); } - mcMMOPlayer.processAbilityActivation(PrimarySkillType.AXES); - mcMMOPlayer.processAbilityActivation(PrimarySkillType.EXCAVATION); - mcMMOPlayer.processAbilityActivation(PrimarySkillType.MINING); - mcMMOPlayer.processAbilityActivation(PrimarySkillType.SWORDS); - mcMMOPlayer.processAbilityActivation(PrimarySkillType.UNARMED); - mcMMOPlayer.processAbilityActivation(PrimarySkillType.WOODCUTTING); + mmoPlayer.processAbilityActivation(PrimarySkillType.AXES); + mmoPlayer.processAbilityActivation(PrimarySkillType.EXCAVATION); + mmoPlayer.processAbilityActivation(PrimarySkillType.MINING); + mmoPlayer.processAbilityActivation(PrimarySkillType.SWORDS); + mmoPlayer.processAbilityActivation(PrimarySkillType.UNARMED); + mmoPlayer.processAbilityActivation(PrimarySkillType.WOODCUTTING); } ChimaeraWing.activationCheck(player); } - HerbalismManager herbalismManager = mcMMOPlayer.getHerbalismManager(); + HerbalismManager herbalismManager = mmoPlayer.getHerbalismManager(); // FakePlayerAnimationEvent fakeSwing = new FakePlayerAnimationEvent(event.getPlayer(), PlayerAnimationType.ARM_SWING); //PlayerAnimationEvent compat if (!event.isCancelled() || event.useInteractedBlock() != Event.Result.DENY) { @@ -835,18 +921,22 @@ public class PlayerListener implements Listener { if (herbalismManager.canGreenThumbBlock(blockState)) { //call event for Green Thumb Block - if (!EventUtils.callSubSkillBlockEvent(player, SubSkillType.HERBALISM_GREEN_THUMB, block).isCancelled()) { + if (!EventUtils.callSubSkillBlockEvent(player, + SubSkillType.HERBALISM_GREEN_THUMB, block).isCancelled()) { // Bukkit.getPluginManager().callEvent(fakeSwing); - player.getInventory().getItemInMainHand().setAmount(heldItem.getAmount() - 1); + player.getInventory().getItemInMainHand() + .setAmount(heldItem.getAmount() - 1); player.updateInventory(); - if (herbalismManager.processGreenThumbBlocks(blockState) && EventUtils.simulateBlockBreak(block, player)) { + if (herbalismManager.processGreenThumbBlocks(blockState) + && EventUtils.simulateBlockBreak(block, player)) { blockState.update(true); } } } /* SHROOM THUMB CHECK */ else if (herbalismManager.canUseShroomThumb(blockState)) { - if (!EventUtils.callSubSkillBlockEvent(player, SubSkillType.HERBALISM_SHROOM_THUMB, block).isCancelled()) { + if (!EventUtils.callSubSkillBlockEvent(player, + SubSkillType.HERBALISM_SHROOM_THUMB, block).isCancelled()) { // Bukkit.getPluginManager().callEvent(fakeSwing); event.setCancelled(true); if (herbalismManager.processShroomThumb(blockState) @@ -861,26 +951,27 @@ 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.p.getGeneralConfig().getAbilitiesEnabled()) { - mcMMOPlayer.processAbilityActivation(PrimarySkillType.AXES); - mcMMOPlayer.processAbilityActivation(PrimarySkillType.EXCAVATION); - mcMMOPlayer.processAbilityActivation(PrimarySkillType.HERBALISM); - mcMMOPlayer.processAbilityActivation(PrimarySkillType.MINING); - mcMMOPlayer.processAbilityActivation(PrimarySkillType.SWORDS); - mcMMOPlayer.processAbilityActivation(PrimarySkillType.UNARMED); - mcMMOPlayer.processAbilityActivation(PrimarySkillType.WOODCUTTING); + mmoPlayer.processAbilityActivation(PrimarySkillType.AXES); + mmoPlayer.processAbilityActivation(PrimarySkillType.EXCAVATION); + mmoPlayer.processAbilityActivation(PrimarySkillType.HERBALISM); + mmoPlayer.processAbilityActivation(PrimarySkillType.MINING); + mmoPlayer.processAbilityActivation(PrimarySkillType.SWORDS); + mmoPlayer.processAbilityActivation(PrimarySkillType.UNARMED); + mmoPlayer.processAbilityActivation(PrimarySkillType.WOODCUTTING); } /* ITEM CHECKS */ ChimaeraWing.activationCheck(player); /* BLAST MINING CHECK */ - MiningManager miningManager = mcMMOPlayer.getMiningManager(); + MiningManager miningManager = mmoPlayer.getMiningManager(); if (miningManager.canDetonate()) { miningManager.remoteDetonation(); } @@ -896,13 +987,16 @@ public class PlayerListener implements Listener { /* CALL OF THE WILD CHECKS */ Material type = heldItem.getType(); - TamingManager tamingManager = mcMMOPlayer.getTamingManager(); + TamingManager tamingManager = mmoPlayer.getTamingManager(); - if (type == mcMMO.p.getGeneralConfig().getTamingCOTWMaterial(CallOfTheWildType.WOLF.getConfigEntityTypeEntry())) { + if (type == mcMMO.p.getGeneralConfig() + .getTamingCOTWMaterial(CallOfTheWildType.WOLF.getConfigEntityTypeEntry())) { tamingManager.summonWolf(); - } else if (type == mcMMO.p.getGeneralConfig().getTamingCOTWMaterial(CallOfTheWildType.CAT.getConfigEntityTypeEntry())) { + } else if (type == mcMMO.p.getGeneralConfig() + .getTamingCOTWMaterial(CallOfTheWildType.CAT.getConfigEntityTypeEntry())) { tamingManager.summonOcelot(); - } else if (type == mcMMO.p.getGeneralConfig().getTamingCOTWMaterial(CallOfTheWildType.HORSE.getConfigEntityTypeEntry())) { + } else if (type == mcMMO.p.getGeneralConfig().getTamingCOTWMaterial( + CallOfTheWildType.HORSE.getConfigEntityTypeEntry())) { tamingManager.summonHorse(); } @@ -922,27 +1016,33 @@ public class PlayerListener implements Listener { public void onPlayerChat(AsyncPlayerChatEvent event) { Player player = event.getPlayer(); - if ((ExperienceConfig.getInstance().isNPCInteractionPrevented() && Misc.isNPCEntityExcludingVillagers(player)) || !UserManager.hasPlayerDataKey(player)) { + if ((ExperienceConfig.getInstance().isNPCInteractionPrevented() + && Misc.isNPCEntityExcludingVillagers(player)) || !UserManager.hasPlayerDataKey( + player)) { return; } - McMMOPlayer mcMMOPlayer = UserManager.getOfflinePlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getOfflinePlayer(player); - if (mcMMOPlayer == null) { - LogUtils.debug(mcMMO.p.getLogger(), player.getName() + "is chatting, but is currently not logged in to the server."); - LogUtils.debug(mcMMO.p.getLogger(), "Party & Admin chat will not work properly for this player."); + if (mmoPlayer == null) { + LogUtils.debug(mcMMO.p.getLogger(), player.getName() + + "is chatting, but is currently not logged in to the server."); + LogUtils.debug(mcMMO.p.getLogger(), + "Party & Admin chat will not work properly for this player."); return; } - if (plugin.getChatManager().isChatChannelEnabled(mcMMOPlayer.getChatChannel())) { - if (mcMMOPlayer.getChatChannel() != ChatChannel.NONE) { - if (plugin.getChatManager().isMessageAllowed(mcMMOPlayer)) { + if (plugin.getChatManager().isChatChannelEnabled(mmoPlayer.getChatChannel())) { + if (mmoPlayer.getChatChannel() != ChatChannel.NONE) { + if (plugin.getChatManager().isMessageAllowed(mmoPlayer)) { //If the message is allowed we cancel this event to avoid double sending messages - plugin.getChatManager().processPlayerMessage(mcMMOPlayer, event.getMessage(), event.isAsynchronous()); + plugin.getChatManager().processPlayerMessage(mmoPlayer, event.getMessage(), + event.isAsynchronous()); event.setCancelled(true); } else { //Message wasn't allowed, remove the player from their channel - plugin.getChatManager().setOrToggleChatChannel(mcMMOPlayer, mcMMOPlayer.getChatChannel()); + plugin.getChatManager() + .setOrToggleChatChannel(mmoPlayer, mmoPlayer.getChatChannel()); } } } @@ -963,7 +1063,8 @@ public class PlayerListener implements Listener { // Do these ACTUALLY have to be lower case to work properly? for (PrimarySkillType skill : PrimarySkillType.values()) { String skillName = skill.toString().toLowerCase(Locale.ENGLISH); - String localizedName = mcMMO.p.getSkillTools().getLocalizedSkillName(skill).toLowerCase(Locale.ENGLISH); + String localizedName = mcMMO.p.getSkillTools().getLocalizedSkillName(skill) + .toLowerCase(Locale.ENGLISH); if (lowerCaseCommand.equals(localizedName)) { event.setMessage(message.replace(command, skillName)); @@ -978,9 +1079,8 @@ public class PlayerListener implements Listener { } /** - * When a {@link Player} attempts to place an {@link ItemStack} - * into an {@link ItemFrame}, we want to make sure to remove any - * Ability buffs from that item. + * When a {@link Player} attempts to place an {@link ItemStack} into an {@link ItemFrame}, we + * want to make sure to remove any Ability buffs from that item. * * @param event The {@link PlayerInteractEntityEvent} to handle */ diff --git a/src/main/java/com/gmail/nossr50/listeners/SelfListener.java b/src/main/java/com/gmail/nossr50/listeners/SelfListener.java index 3d5bb1e0e..fa89eca89 100644 --- a/src/main/java/com/gmail/nossr50/listeners/SelfListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/SelfListener.java @@ -33,25 +33,28 @@ public class SelfListener implements Listener { Player player = event.getPlayer(); PrimarySkillType skill = event.getSkill(); - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); //TODO: Handle proper validation at the event level - if (mcMMOPlayer == null || !mcMMOPlayer.getProfile().isLoaded()) + if (mmoPlayer == null || !mmoPlayer.getProfile().isLoaded()) { return; + } if (player.isOnline()) { //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); + UserManager.getPlayer(player) + .processUnlockNotifications(plugin, event.getSkill(), previousLevelGained); } //Reset the delay timer RankUtils.resetUnlockDelayTimer(); - if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) + if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) { ScoreboardManager.handleLevelUp(player, skill); + } } } @@ -60,8 +63,9 @@ public class SelfListener implements Listener { Player player = event.getPlayer(); if (player.isOnline()) { - if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) + if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) { ScoreboardManager.handleXp(player, event.getSkill()); + } } } @@ -69,25 +73,27 @@ public class SelfListener implements Listener { public void onAbility(McMMOPlayerAbilityActivateEvent event) { Player player = event.getPlayer(); if (player.isOnline()) { - if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) + if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) { ScoreboardManager.cooldownUpdate(event.getPlayer(), event.getSkill()); + } } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onPlayerXpGain(McMMOPlayerXpGainEvent event) { Player player = event.getPlayer(); - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); //TODO: Handle proper validation at the event level - if (mcMMOPlayer == null || !mcMMOPlayer.getProfile().isLoaded()) + if (mmoPlayer == null || !mmoPlayer.getProfile().isLoaded()) { return; + } PrimarySkillType primarySkillType = event.getSkill(); - if (mcMMOPlayer.isDebugMode()) { - mcMMOPlayer.getPlayer().sendMessage(event.getSkill().toString() + " XP Gained"); - mcMMOPlayer.getPlayer().sendMessage("Incoming Raw XP: "+event.getRawXpGained()); + if (mmoPlayer.isDebugMode()) { + mmoPlayer.getPlayer().sendMessage(event.getSkill().toString() + " XP Gained"); + mmoPlayer.getPlayer().sendMessage("Incoming Raw XP: " + event.getRawXpGained()); } //WorldGuard XP Check @@ -100,8 +106,9 @@ public class SelfListener implements Listener { event.setRawXpGained(0); event.setCancelled(true); - if (mcMMOPlayer.isDebugMode()) { - mcMMOPlayer.getPlayer().sendMessage("No WG XP Flag - New Raw XP: "+event.getRawXpGained()); + if (mmoPlayer.isDebugMode()) { + mmoPlayer.getPlayer().sendMessage( + "No WG XP Flag - New Raw XP: " + event.getRawXpGained()); } } } @@ -116,17 +123,18 @@ public class SelfListener implements Listener { int earlyGameBonusXP = 0; //Give some bonus XP for low levels - if (PlayerLevelUtils.qualifiesForEarlyGameBoost(mcMMOPlayer, primarySkillType)) { - earlyGameBonusXP += (mcMMOPlayer.getXpToLevel(primarySkillType) * 0.05); + if (PlayerLevelUtils.qualifiesForEarlyGameBoost(mmoPlayer, primarySkillType)) { + earlyGameBonusXP += (mmoPlayer.getXpToLevel(primarySkillType) * 0.05); event.setRawXpGained(event.getRawXpGained() + earlyGameBonusXP); } } - int threshold = ExperienceConfig.getInstance().getDiminishedReturnsThreshold(primarySkillType); + int threshold = ExperienceConfig.getInstance() + .getDiminishedReturnsThreshold(primarySkillType); if (threshold <= 0 || !ExperienceConfig.getInstance().getDiminishedReturnsEnabled()) { - if (mcMMOPlayer.isDebugMode()) { - mcMMOPlayer.getPlayer().sendMessage("Final Raw XP: "+event.getRawXpGained()); + if (mmoPlayer.isDebugMode()) { + mmoPlayer.getPlayer().sendMessage("Final Raw XP: " + event.getRawXpGained()); } // Diminished returns is turned off return; @@ -145,11 +153,15 @@ public class SelfListener implements Listener { float guaranteedMinimum = ExperienceConfig.getInstance().getDiminishedReturnsCap() * rawXp; - float modifiedThreshold = (float) (threshold / ExperienceConfig.getInstance().getFormulaSkillModifier(primarySkillType) * ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier()); - float difference = (mcMMOPlayer.getProfile().getRegisteredXpGain(primarySkillType) - modifiedThreshold) / modifiedThreshold; + float modifiedThreshold = (float) ( + threshold / ExperienceConfig.getInstance().getFormulaSkillModifier(primarySkillType) + * ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier()); + float difference = + (mmoPlayer.getProfile().getRegisteredXpGain(primarySkillType) - modifiedThreshold) + / modifiedThreshold; if (difference > 0) { -// System.out.println("Total XP Earned: " + mcMMOPlayer.getProfile().getRegisteredXpGain(primarySkillType) + " / Threshold value: " + threshold); +// System.out.println("Total XP Earned: " + mmoPlayer.getProfile().getRegisteredXpGain(primarySkillType) + " / Threshold value: " + threshold); // System.out.println(difference * 100 + "% over the threshold!"); // System.out.println("Previous: " + event.getRawXpGained()); // System.out.println("Adjusted XP " + (event.getRawXpGained() - (event.getRawXpGained() * difference))); @@ -171,8 +183,8 @@ public class SelfListener implements Listener { } - if (mcMMOPlayer.isDebugMode()) { - mcMMOPlayer.getPlayer().sendMessage("Final Raw XP: "+event.getRawXpGained()); + if (mmoPlayer.isDebugMode()) { + mmoPlayer.getPlayer().sendMessage("Final Raw XP: " + event.getRawXpGained()); } } diff --git a/src/main/java/com/gmail/nossr50/listeners/WorldListener.java b/src/main/java/com/gmail/nossr50/listeners/WorldListener.java index 951916d34..ef2286e8d 100644 --- a/src/main/java/com/gmail/nossr50/listeners/WorldListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/WorldListener.java @@ -26,8 +26,9 @@ 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; + } // Using 50 ms later as I do not know of a way to run one tick later (safely) plugin.getFoliaLib().getScheduler().runLater(() -> { @@ -45,8 +46,9 @@ 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.getChunkManager().unloadWorld(event.getWorld()); } @@ -59,8 +61,9 @@ 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 b8598828a..80de6fc0d 100644 --- a/src/main/java/com/gmail/nossr50/locale/LocaleLoader.java +++ b/src/main/java/com/gmail/nossr50/locale/LocaleLoader.java @@ -3,22 +3,32 @@ package com.gmail.nossr50.locale; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.LogUtils; import com.gmail.nossr50.util.text.TextUtils; -import net.kyori.adventure.text.TextComponent; -import org.bukkit.ChatColor; -import org.jetbrains.annotations.NotNull; - -import java.io.*; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.Reader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.MessageFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; -import java.util.*; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.MissingResourceException; +import java.util.PropertyResourceBundle; +import java.util.ResourceBundle; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.regex.Matcher; import java.util.regex.Pattern; +import net.kyori.adventure.text.TextComponent; +import org.bukkit.ChatColor; +import org.jetbrains.annotations.NotNull; public final class LocaleLoader { private static final String BUNDLE_ROOT = "com.gmail.nossr50.locale.locale"; @@ -30,9 +40,11 @@ public final class LocaleLoader { private static ResourceBundle enBundle = null; // Matches the pattern &#RRGGBB private static final Pattern hexPattern = Pattern.compile("&#([A-Fa-f0-9]{6})"); - private static final Pattern minecraftHexPattern = Pattern.compile("§x(§[A-Fa-f0-9])(§[A-Fa-f0-9])(§[A-Fa-f0-9])(§[A-Fa-f0-9])(§[A-Fa-f0-9])(§[A-Fa-f0-9])"); + private static final Pattern minecraftHexPattern = Pattern.compile( + "§x(§[A-Fa-f0-9])(§[A-Fa-f0-9])(§[A-Fa-f0-9])(§[A-Fa-f0-9])(§[A-Fa-f0-9])(§[A-Fa-f0-9])"); - private LocaleLoader() {} + private LocaleLoader() { + } public static String getString(String key) { return getString(key, (Object[]) null); @@ -41,9 +53,8 @@ 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 */ public static String getString(String key, Object... messageArguments) { @@ -56,14 +67,15 @@ public final class LocaleLoader { } /** - * Gets the appropriate TextComponent representation of a formatted string from the Locale files. + * Gets the appropriate TextComponent representation of a formatted 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 text component - * * @return The properly formatted text component */ - public static @NotNull TextComponent getTextComponent(@NotNull String key, Object... messageArguments) { + public static @NotNull TextComponent getTextComponent(@NotNull String key, + Object... messageArguments) { if (bundle == null) { initialize(); } @@ -119,7 +131,8 @@ public final class LocaleLoader { return string; } - public static @NotNull TextComponent formatComponent(@NotNull String string, Object... messageArguments) { + public static @NotNull TextComponent formatComponent(@NotNull String string, + Object... messageArguments) { if (messageArguments != null) { MessageFormat formatter = new MessageFormat("", Locale.US); formatter.applyPattern(string.replace("'", "''")); @@ -149,10 +162,13 @@ public final class LocaleLoader { } if (locale == null) { - throw new IllegalStateException("Failed to parse locale string '" + mcMMO.p.getGeneralConfig().getLocale() + "'"); + throw new IllegalStateException( + "Failed to parse locale string '" + mcMMO.p.getGeneralConfig().getLocale() + + "'"); } - Path localePath = Paths.get(mcMMO.getLocalesDirectory() + "locale_" + locale.toString() + ".properties"); + Path localePath = Paths.get( + mcMMO.getLocalesDirectory() + "locale_" + locale + ".properties"); Path overridePath = Paths.get(mcMMO.getLocalesDirectory() + OVERRIDE_FILE_NAME); File overrideFile = overridePath.toFile(); @@ -169,13 +185,18 @@ public final class LocaleLoader { //Insert our helpful text StringBuilder stringBuilder = new StringBuilder(); - try(BufferedReader bufferedReader = new BufferedReader(new FileReader(overrideFile.getPath()))) { + try (BufferedReader bufferedReader = new BufferedReader( + new FileReader(overrideFile.getPath()))) { // Open the file String line; - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm"); + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern( + "MM/dd/yyyy HH:mm"); LocalDateTime localDateTime = LocalDateTime.now(); - stringBuilder.append("# mcMMO Locale Override File created on ").append(localDateTime.format(dateTimeFormatter)).append("\r\n"); //Empty file - stringBuilder.append(getLocaleHelpTextWithoutExamples()); //Add our helpful text + stringBuilder.append("# mcMMO Locale Override File created on ") + .append(localDateTime.format(dateTimeFormatter)) + .append("\r\n"); //Empty file + stringBuilder.append( + getLocaleHelpTextWithoutExamples()); //Add our helpful text while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line).append("\r\n"); } @@ -183,7 +204,7 @@ public final class LocaleLoader { e.printStackTrace(); } - try(FileWriter fileWriter = new FileWriter(overrideFile.getPath())) { + try (FileWriter fileWriter = new FileWriter(overrideFile.getPath())) { fileWriter.write(stringBuilder.toString()); } catch (IOException e) { e.printStackTrace(); @@ -197,18 +218,24 @@ public final class LocaleLoader { //Use the new locale file if (Files.exists(overridePath) && Files.isRegularFile(overridePath)) { try (Reader localeReader = Files.newBufferedReader(overridePath)) { - LogUtils.debug(mcMMO.p.getLogger(), "Loading locale from " + overridePath.toString()); + LogUtils.debug(mcMMO.p.getLogger(), + "Loading locale from " + overridePath); filesystemBundle = new PropertyResourceBundle(localeReader); } catch (IOException e) { - mcMMO.p.getLogger().log(Level.WARNING, "Failed to load locale from " + overridePath, e); + mcMMO.p.getLogger() + .log(Level.WARNING, "Failed to load locale from " + overridePath, e); } } else { //Create a blank file and fill it in with some helpful text - try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(overrideFile, true))) { + try (BufferedWriter bufferedWriter = new BufferedWriter( + new FileWriter(overrideFile, true))) { // Open the file to write the player - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm"); + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern( + "MM/dd/yyyy HH:mm"); LocalDateTime localDateTime = LocalDateTime.now(); - bufferedWriter.append("# mcMMO Locale Override File created on ").append(localDateTime.format(dateTimeFormatter)).append("\r\n"); //Empty file + bufferedWriter.append("# mcMMO Locale Override File created on ") + .append(localDateTime.format(dateTimeFormatter)) + .append("\r\n"); //Empty file String localeExplanation = getLocaleHelpText(); bufferedWriter.append(localeExplanation); } catch (Exception e) { @@ -225,35 +252,52 @@ public final class LocaleLoader { @NotNull private static String getLocaleHelpText() { String localeExplanation = - "# -- Are you looking to change the language of mcMMO but without editing it yourself? --\n" + + "# -- Are you looking to change the language of mcMMO but without editing it yourself? --\n" + + "\n" + - "# mcMMO has quite a few built in translations, you can choose which translation by editing config.yml with the appropriate locale code. The setting is `General.Locale` in config.yml\n" + - "# Odds are, if you speak a popular language on earth we already have a translation for it.\n" + - "# However our translations are done by the community, and update infrequently. (Please help us out <3)\n" + - "# We would love more people to help update our locales, submit any updated translation file to our GitHub or email it to me at business@neetgames.com\n" + - "# For a list of built in translations, view this link: https://github.com/mcMMO-Dev/mcMMO/tree/master/src/main/resources/locale\n" + + "# mcMMO has quite a few built in translations, you can choose which translation by editing config.yml with the appropriate locale code. The setting is `General.Locale` in config.yml\n" + + + "# Odds are, if you speak a popular language on earth we already have a translation for it.\n" + + + "# However our translations are done by the community, and update infrequently. (Please help us out <3)\n" + + + "# We would love more people to help update our locales, submit any updated translation file to our GitHub or email it to me at business@neetgames.com\n" + + + "# For a list of built in translations, view this link: https://github.com/mcMMO-Dev/mcMMO/tree/master/src/main/resources/locale\n" + + "\n" + "\n" + "# -- Using a built in translation -- \n" + - "# Assuming you read the above section, edit config.yml's General.Locale from en_US to the locale code that we support (see the above link), then reboot your server\n" + + "# Assuming you read the above section, edit config.yml's General.Locale from en_US to the locale code that we support (see the above link), then reboot your server\n" + + "\n" + "\n" + - "# -- Do you want to change the text in mcMMO? Including adding colors? ( Locale Override ) -- \n" + + "# -- Do you want to change the text in mcMMO? Including adding colors? ( Locale Override ) -- \n" + + "# First, a brief explanation.\n" + - "# Locales are the language files used by mcMMO, they also contain color codes and most of the styling used by mcMMO.\n" + - "# You can customize a locale outside of the JAR in version 2.1.51 and up.\n" + + "# Locales are the language files used by mcMMO, they also contain color codes and most of the styling used by mcMMO.\n" + + + "# You can customize a locale outside of the JAR in version 2.1.51 and up.\n" + + "#\n" + "# Locales can be overridden by editing this file\n" + - "# You can find the up to date current locale files here https://github.com/mcMMO-Dev/mcMMO/tree/master/src/main/resources/locale\n" + - "# The master file is en_US, if a translation is missing entries (as they often are) it will pull from the en_US file https://github.com/mcMMO-Dev/mcMMO/blob/master/src/main/resources/locale/locale_en_US.properties\n" + + "# You can find the up to date current locale files here https://github.com/mcMMO-Dev/mcMMO/tree/master/src/main/resources/locale\n" + + + "# The master file is en_US, if a translation is missing entries (as they often are) it will pull from the en_US file https://github.com/mcMMO-Dev/mcMMO/blob/master/src/main/resources/locale/locale_en_US.properties\n" + + "#\n" + - "# To override a locale, add entries to this file and copy ** only ** the strings you want to replace, otherwise you will not see any updated strings when mcMMO updates and will have to manually change them and read patch notes carefully.\n" + - "# If you wish to replace every line in some way, feel free to copy the entire contents of this file, just be advised that you will need to be on top of locale updates in mcMMO and follow our changelog closely.\n" + + "# To override a locale, add entries to this file and copy ** only ** the strings you want to replace, otherwise you will not see any updated strings when mcMMO updates and will have to manually change them and read patch notes carefully.\n" + + + "# If you wish to replace every line in some way, feel free to copy the entire contents of this file, just be advised that you will need to be on top of locale updates in mcMMO and follow our changelog closely.\n" + + "\n" + "\n" + - "# FIND KEYS HERE: On our github repo (en_US is our master file and has ALL the keys) -> https://github.com/mcMMO-Dev/mcMMO/tree/master/src/main/resources/locale\n" + - "# WARNING: Some keys in our master file are unused, make gratuitous use of Ctrl+F\n" + - "# HOW TO APPLY: You can either restart the server for these changes to take effect or run /mcreloadlocale.\n" + + "# FIND KEYS HERE: On our github repo (en_US is our master file and has ALL the keys) -> https://github.com/mcMMO-Dev/mcMMO/tree/master/src/main/resources/locale\n" + + + "# WARNING: Some keys in our master file are unused, make gratuitous use of Ctrl+F\n" + + + "# HOW TO APPLY: You can either restart the server for these changes to take effect or run /mcreloadlocale.\n" + + "# -- Add Keys Below --\n" + getExamples(); return localeExplanation; @@ -278,18 +322,18 @@ public final class LocaleLoader { String localeExplanation = """ # -- Are you looking to change the language of mcMMO but without editing it yourself? -- - + # mcMMO has quite a few built in translations, you can choose which translation by editing config.yml with the appropriate locale code. The setting is `General.Locale` in config.yml # Odds are, if you speak a popular language on earth we already have a translation for it. # However our translations are done by the community, and update infrequently. (Please help us out <3) # We would love more people to help update our locales, submit any updated translation file to our GitHub or email it to me at business@neetgames.com # For a list of built in translations, view this link: https://github.com/mcMMO-Dev/mcMMO/tree/master/src/main/resources/locale - - + + # -- Using a built in translation --\s # Assuming you read the above section, edit config.yml's General.Locale from en_US to the locale code that we support (see the above link), then reboot your server - - + + # -- Do you want to change the text in mcMMO? Including adding colors? ( Locale Override ) --\s # First, a brief explanation. # Locales are the language files used by mcMMO, they also contain color codes and most of the styling used by mcMMO. @@ -301,8 +345,8 @@ public final class LocaleLoader { # # To override a locale, add entries to this file and copy ** only ** the strings you want to replace, otherwise you will not see any updated strings when mcMMO updates and will have to manually change them and read patch notes carefully. # If you wish to replace every line in some way, feel free to copy the entire contents of this file, just be advised that you will need to be on top of locale updates in mcMMO and follow our changelog closely. - - + + # WARNING: Locales only support ASCII and UTF16 characters at the moment, so you'll need to run special characters through a UTF16 converter (google it) to get them to work. This will be fixed in the future! # FIND KEYS HERE: On our github repo (en_US is our master file and has ALL the keys) -> https://github.com/mcMMO-Dev/mcMMO/tree/master/src/main/resources/locale # WARNING: Some keys in our master file are unused, make gratuitous use of Ctrl+F @@ -370,13 +414,13 @@ public final class LocaleLoader { /** * Translates hex color codes to the appropriate Minecraft color codes. *

- * Hex color codes are in the format of &#RRGGBB - * Minecraft color codes are in the format of §x§R§R§G§G§B§B - * Where R, G, and B are the red, green, and blue values respectively. - * The §x is a special character that tells Minecraft to use the following color codes as hex values. - * The §R§R is the red value, the §G§G is the green value, and the §B§B is the blue value. - * Example: §x§R§R§G§G§B§B is the equivalent of the hex color code &#RRGGBB + * Hex color codes are in the format of &#RRGGBB Minecraft color codes are in the format of + * §x§R§R§G§G§B§B Where R, G, and B are the red, green, and blue values respectively. The §x is + * a special character that tells Minecraft to use the following color codes as hex values. The + * §R§R is the red value, the §G§G is the green value, and the §B§B is the blue value. Example: + * §x§R§R§G§G§B§B is the equivalent of the hex color code &#RRGGBB *

+ * * @param messageWithHex The message with hex color codes to translate * @return The message with the hex color codes translated to Minecraft color codes */ diff --git a/src/main/java/com/gmail/nossr50/mcMMO.java b/src/main/java/com/gmail/nossr50/mcMMO.java index 44dd5f9b6..cc7f8107c 100644 --- a/src/main/java/com/gmail/nossr50/mcMMO.java +++ b/src/main/java/com/gmail/nossr50/mcMMO.java @@ -2,7 +2,14 @@ package com.gmail.nossr50; import com.gmail.nossr50.chat.ChatManager; import com.gmail.nossr50.commands.CommandManager; -import com.gmail.nossr50.config.*; +import com.gmail.nossr50.config.AdvancedConfig; +import com.gmail.nossr50.config.CoreSkillsConfig; +import com.gmail.nossr50.config.CustomItemSupportConfig; +import com.gmail.nossr50.config.GeneralConfig; +import com.gmail.nossr50.config.HiddenConfig; +import com.gmail.nossr50.config.RankConfig; +import com.gmail.nossr50.config.SoundConfig; +import com.gmail.nossr50.config.WorldBlacklist; import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.config.party.PartyConfig; import com.gmail.nossr50.config.skills.alchemy.PotionConfig; @@ -14,7 +21,14 @@ import com.gmail.nossr50.database.DatabaseManager; import com.gmail.nossr50.database.DatabaseManagerFactory; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.subskills.acrobatics.Roll; -import com.gmail.nossr50.listeners.*; +import com.gmail.nossr50.listeners.BlockListener; +import com.gmail.nossr50.listeners.ChunkListener; +import com.gmail.nossr50.listeners.EntityListener; +import com.gmail.nossr50.listeners.InteractionManager; +import com.gmail.nossr50.listeners.InventoryListener; +import com.gmail.nossr50.listeners.PlayerListener; +import com.gmail.nossr50.listeners.SelfListener; +import com.gmail.nossr50.listeners.WorldListener; import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.placeholders.PapiExpansion; import com.gmail.nossr50.runnables.SaveTimerTask; @@ -32,7 +46,16 @@ import com.gmail.nossr50.skills.repair.repairables.SimpleRepairableManager; import com.gmail.nossr50.skills.salvage.salvageables.Salvageable; import com.gmail.nossr50.skills.salvage.salvageables.SalvageableManager; import com.gmail.nossr50.skills.salvage.salvageables.SimpleSalvageableManager; -import com.gmail.nossr50.util.*; +import com.gmail.nossr50.util.ChimaeraWing; +import com.gmail.nossr50.util.EnchantmentMapper; +import com.gmail.nossr50.util.LogFilter; +import com.gmail.nossr50.util.LogUtils; +import com.gmail.nossr50.util.MaterialMapStore; +import com.gmail.nossr50.util.MetadataConstants; +import com.gmail.nossr50.util.Misc; +import com.gmail.nossr50.util.Permissions; +import com.gmail.nossr50.util.TransientEntityTracker; +import com.gmail.nossr50.util.TransientMetadataTools; import com.gmail.nossr50.util.blockmeta.ChunkManager; import com.gmail.nossr50.util.blockmeta.ChunkManagerFactory; import com.gmail.nossr50.util.blockmeta.UserBlockTracker; @@ -49,8 +72,12 @@ import com.gmail.nossr50.util.skills.SkillTools; import com.gmail.nossr50.util.upgrade.UpgradeManager; import com.gmail.nossr50.worldguard.WorldGuardManager; import com.tcoded.folialib.FoliaLib; -import com.tcoded.folialib.impl.FoliaImplementation; -import com.tcoded.folialib.util.InvalidTickDelayNotifier; +import java.io.File; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; import net.kyori.adventure.platform.bukkit.BukkitAudiences; import net.shatteredlands.shatt.backup.ZipLibrary; import org.bstats.bukkit.Metrics; @@ -66,13 +93,6 @@ import org.bukkit.plugin.java.JavaPluginLoader; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.File; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - public class mcMMO extends JavaPlugin { /* Managers & Services */ private static PlatformManager platformManager; @@ -143,7 +163,8 @@ public class mcMMO extends JavaPlugin { } - protected mcMMO(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) { + protected mcMMO(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, + File file) { super(loader, description, dataFolder, file); } @@ -167,7 +188,6 @@ public class mcMMO extends JavaPlugin { // This makes the scheduler behave differently between Spigot/Legacy-Paper & Folia/Modern-Paper foliaLib.getOptions().disableIsValidOnNonFolia(); - setupFilePaths(); generalConfig = new GeneralConfig(getDataFolder()); //Load before skillTools skillTools = new SkillTools(this); //Load after general config @@ -203,41 +223,46 @@ public class mcMMO extends JavaPlugin { } if (projectKorraEnabled) { - getLogger().info("ProjectKorra was detected, this can cause some issues with weakness potions and combat skills for mcMMO"); + getLogger().info( + "ProjectKorra was detected, this can cause some issues with weakness potions and combat skills for mcMMO"); } if (healthBarPluginEnabled) { - getLogger().info("HealthBar plugin found, mcMMO's healthbars are automatically disabled."); + getLogger().info( + "HealthBar plugin found, mcMMO's healthbars are automatically disabled."); } - if (pluginManager.getPlugin("NoCheatPlus") != null && pluginManager.getPlugin("CompatNoCheatPlus") == null) { - getLogger().warning("NoCheatPlus plugin found, but CompatNoCheatPlus was not found!"); - getLogger().warning("mcMMO will not work properly alongside NoCheatPlus without CompatNoCheatPlus"); + if (pluginManager.getPlugin("NoCheatPlus") != null && pluginManager.getPlugin( + "CompatNoCheatPlus") == null) { + getLogger().warning( + "NoCheatPlus plugin found, but CompatNoCheatPlus was not found!"); + getLogger().warning( + "mcMMO will not work properly alongside NoCheatPlus without CompatNoCheatPlus"); } // One month in milliseconds this.purgeTime = 2630000000L * generalConfig.getOldUsersCutoff(); - databaseManager = DatabaseManagerFactory.getDatabaseManager(mcMMO.getUsersFilePath(), getLogger(), purgeTime, mcMMO.p.getAdvancedConfig().getStartingLevel()); + databaseManager = DatabaseManagerFactory.getDatabaseManager( + mcMMO.getUsersFilePath(), getLogger(), + purgeTime, mcMMO.p.getAdvancedConfig().getStartingLevel()); //Check for the newer API and tell them what to do if its missing checkForOutdatedAPI(); if (serverAPIOutdated) { - foliaLib - .getImpl() - .runTimer( - () -> getLogger().severe("You are running an outdated version of "+platformManager.getServerSoftware()+", mcMMO will not work unless you update to a newer version!"), - 20, 20*60*30 - ); + foliaLib.getImpl().runTimer( + () -> getLogger().severe( + "You are running an outdated version of " + + platformManager.getServerSoftware() + + ", mcMMO will not work unless you update to a newer version!"), + 20, 20 * 60 * 30); if (platformManager.getServerSoftware() == ServerSoftwareType.CRAFT_BUKKIT) { - foliaLib - .getImpl() - .runTimer( - () -> 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 - ); + foliaLib.getImpl().runTimer( + () -> 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); } } else { registerEvents(); @@ -252,10 +277,13 @@ public class mcMMO extends JavaPlugin { formulaManager = new FormulaManager(); for (Player player : getServer().getOnlinePlayers()) { - getFoliaLib().getScheduler().runLaterAsync(new PlayerProfileLoadingTask(player), 1); // 1 Tick delay to ensure the player is marked as online before we begin loading + getFoliaLib().getScheduler().runLaterAsync( + new PlayerProfileLoadingTask(player), + 1); // 1 Tick delay to ensure the player is marked as online before we begin loading } - LogUtils.debug(mcMMO.p.getLogger(), "Version " + getDescription().getVersion() + " is enabled!"); + LogUtils.debug(mcMMO.p.getLogger(), + "Version " + getDescription().getVersion() + " is enabled!"); scheduleTasks(); CommandRegistrationManager.registerCommands(); @@ -275,12 +303,14 @@ public class mcMMO extends JavaPlugin { if (generalConfig.getIsMetricsEnabled()) { metrics = new Metrics(this, 3894); - metrics.addCustomChart(new SimplePie("version", () -> getDescription().getVersion())); + metrics.addCustomChart( + new SimplePie("version", () -> getDescription().getVersion())); - if (generalConfig.getIsRetroMode()) + if (generalConfig.getIsRetroMode()) { metrics.addCustomChart(new SimplePie("leveling_system", () -> "Retro")); - else + } else { metrics.addCustomChart(new SimplePie("leveling_system", () -> "Standard")); + } } } catch (Throwable t) { getLogger().severe("There was an error while enabling mcMMO!"); @@ -288,7 +318,8 @@ public class mcMMO extends JavaPlugin { if (!(t instanceof ExceptionInInitializerError)) { t.printStackTrace(); } else { - getLogger().info("Please do not replace the mcMMO jar while the server is running."); + getLogger().info( + "Please do not replace the mcMMO jar while the server is running."); } getServer().getPluginManager().disablePlugin(this); @@ -336,7 +367,9 @@ public class mcMMO extends JavaPlugin { } catch (ClassNotFoundException | NoSuchMethodException e) { serverAPIOutdated = true; String software = platformManager.getServerSoftwareStr(); - getLogger().severe("You are running an older version of " + software + " that is not compatible with mcMMO, update your server software!"); + getLogger().severe( + "You are running an older version of " + software + + " that is not compatible with mcMMO, update your server software!"); } } @@ -345,9 +378,6 @@ public class mcMMO extends JavaPlugin { if (getServer().getPluginManager().getPlugin("WorldGuard") != null) { WorldGuardManager.getInstance().registerFlags(); } - - // ProtocolLib - // protocolLibManager = new ProtocolLibManager(this); } /** @@ -357,23 +387,25 @@ public class mcMMO extends JavaPlugin { public void onDisable() { setServerShutdown(true); //TODO: Write code to catch unfinished async save tasks, for now we just hope they finish in time, which they should in most cases - mcMMO.p.getLogger().info("Server shutdown has been executed, saving and cleaning up data..."); + mcMMO.p.getLogger() + .info("Server shutdown has been executed, saving and cleaning up data..."); try { UserManager.saveAll(); // Make sure to save player information if the server shuts down UserManager.clearAll(); Alchemy.finishAllBrews(); // Finish all partially complete AlchemyBrewTasks to prevent vanilla brewing continuation on restart - if (partyConfig.isPartyEnabled()) + if (partyConfig.isPartyEnabled()) { getPartyManager().saveParties(); // Save our parties + } //TODO: Needed? - if (generalConfig.getScoreboardsEnabled()) + if (generalConfig.getScoreboardsEnabled()) { ScoreboardManager.teardownAll(); + } formulaManager.saveFormula(); chunkManager.closeAll(); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } @@ -381,9 +413,10 @@ public class mcMMO extends JavaPlugin { // Remove other tasks BEFORE starting the Backup, or we just cancel it straight away. try { ZipLibrary.mcMMOBackup(); - } catch(NoClassDefFoundError e) { + } catch (NoClassDefFoundError e) { getLogger().severe("Backup class not found!"); - getLogger().info("Please do not replace the mcMMO jar while the server is running."); + getLogger().info( + "Please do not replace the mcMMO jar while the server is running."); } catch (Throwable e) { getLogger().severe(e.toString()); } @@ -436,6 +469,7 @@ public class mcMMO extends JavaPlugin { /** * Get the {@link UserBlockTracker}. + * * @return the {@link UserBlockTracker} */ public static UserBlockTracker getUserBlockTracker() { @@ -444,6 +478,7 @@ public class mcMMO extends JavaPlugin { /** * Get the chunk manager. + * * @return the chunk manager */ public static ChunkManager getChunkManager() { @@ -452,8 +487,9 @@ public class mcMMO extends JavaPlugin { /** * Get the chunk manager. - * @deprecated Use {@link #getChunkManager()} or {@link #getUserBlockTracker()} instead. + * * @return the chunk manager + * @deprecated Use {@link #getChunkManager()} or {@link #getUserBlockTracker()} instead. */ @Deprecated(since = "2.2.013", forRemoval = true) public static ChunkManager getPlaceStore() { @@ -518,10 +554,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"))) { @@ -593,12 +629,11 @@ public class mcMMO extends JavaPlugin { pluginManager.registerEvents(new SelfListener(this), this); pluginManager.registerEvents(new WorldListener(this), this); pluginManager.registerEvents(new ChunkListener(), this); -// pluginManager.registerEvents(new CommandListener(this), this); + // pluginManager.registerEvents(new CommandListener(this), this); } /** - * Registers core skills - * This enables the skills in the new skill system + * Registers core skills This enables the skills in the new skill system */ private void registerCoreSkills() { /* @@ -618,11 +653,12 @@ public class mcMMO extends JavaPlugin { } private void registerCustomRecipes() { - getFoliaLib().getScheduler().runLater(() -> { - if (generalConfig.getChimaeraEnabled()) { - getServer().addRecipe(ChimaeraWing.getChimaeraWingRecipe()); - } - }, 40); + getFoliaLib().getScheduler().runLater( + () -> { + if (generalConfig.getChimaeraEnabled()) { + getServer().addRecipe(ChimaeraWing.getChimaeraWingRecipe()); + } + }, 40); } private void scheduleTasks() { @@ -632,33 +668,44 @@ public class mcMMO extends JavaPlugin { long saveIntervalTicks = Math.max(minute, generalConfig.getSaveInterval() * minute); - getFoliaLib().getScheduler().runTimer(new SaveTimerTask(), saveIntervalTicks, saveIntervalTicks); + getFoliaLib().getScheduler() + .runTimer(new SaveTimerTask(), saveIntervalTicks, saveIntervalTicks); // Cleanup the backups folder getFoliaLib().getScheduler().runAsync(new CleanBackupsTask()); // Old & Powerless User remover - long purgeIntervalTicks = generalConfig.getPurgeInterval() * 60L * 60L * Misc.TICK_CONVERSION_FACTOR; + long purgeIntervalTicks = + generalConfig.getPurgeInterval() * 60L * 60L * Misc.TICK_CONVERSION_FACTOR; if (purgeIntervalTicks == 0) { - getFoliaLib().getScheduler().runLaterAsync(new UserPurgeTask(), 2 * Misc.TICK_CONVERSION_FACTOR); // Start 2 seconds after startup. + getFoliaLib().getScheduler().runLaterAsync( + new UserPurgeTask(), + 2 * Misc.TICK_CONVERSION_FACTOR); // Start 2 seconds after startup. } else if (purgeIntervalTicks > 0) { - getFoliaLib().getScheduler().runTimerAsync(new UserPurgeTask(), purgeIntervalTicks, purgeIntervalTicks); + getFoliaLib().getScheduler() + .runTimerAsync(new UserPurgeTask(), purgeIntervalTicks, purgeIntervalTicks); } // Automatically remove old members from parties if (partyConfig.isPartyEnabled()) { - long kickIntervalTicks = generalConfig.getAutoPartyKickInterval() * 60L * 60L * Misc.TICK_CONVERSION_FACTOR; + long kickIntervalTicks = generalConfig.getAutoPartyKickInterval() * 60L * 60L + * Misc.TICK_CONVERSION_FACTOR; if (kickIntervalTicks == 0) { - getFoliaLib().getScheduler().runLater(new PartyAutoKickTask(), 2 * Misc.TICK_CONVERSION_FACTOR); // Start 2 seconds after startup. + getFoliaLib().getScheduler().runLater( + new PartyAutoKickTask(), + 2 * Misc.TICK_CONVERSION_FACTOR); // Start 2 seconds after startup. } else if (kickIntervalTicks > 0) { - getFoliaLib().getScheduler().runTimer(new PartyAutoKickTask(), kickIntervalTicks, kickIntervalTicks); + getFoliaLib().getScheduler() + .runTimer(new PartyAutoKickTask(), kickIntervalTicks, kickIntervalTicks); } } // Update power level tag scoreboards - getFoliaLib().getScheduler().runTimer(new PowerLevelUpdatingTask(), 2 * Misc.TICK_CONVERSION_FACTOR, 2 * Misc.TICK_CONVERSION_FACTOR); + getFoliaLib().getScheduler().runTimer( + new PowerLevelUpdatingTask(), 2 * Misc.TICK_CONVERSION_FACTOR, + 2 * Misc.TICK_CONVERSION_FACTOR); // Clear the registered XP data so players can earn XP again if (ExperienceConfig.getInstance().getDiminishedReturnsEnabled()) { @@ -666,28 +713,33 @@ public class mcMMO extends JavaPlugin { } if (mcMMO.p.getAdvancedConfig().allowPlayerTips()) { - getFoliaLib().getScheduler().runTimer(new NotifySquelchReminderTask(), 60, ((20 * 60) * 60)); + getFoliaLib().getScheduler() + .runTimer(new NotifySquelchReminderTask(), 60, ((20 * 60) * 60)); } } private void checkModConfigs() { if (!generalConfig.getToolModsEnabled()) { - getLogger().warning("Cauldron implementation found, but the custom tool config for mcMMO is disabled!"); + getLogger().warning( + "Cauldron implementation found, but the custom tool config for mcMMO is disabled!"); getLogger().info("To enable, set Mods.Tool_Mods_Enabled to TRUE in config.yml."); } if (!generalConfig.getArmorModsEnabled()) { - getLogger().warning("Cauldron implementation found, but the custom armor config for mcMMO is disabled!"); + getLogger().warning( + "Cauldron implementation found, but the custom armor config for mcMMO is disabled!"); getLogger().info("To enable, set Mods.Armor_Mods_Enabled to TRUE in config.yml."); } if (!generalConfig.getBlockModsEnabled()) { - getLogger().warning("Cauldron implementation found, but the custom block config for mcMMO is disabled!"); + getLogger().warning( + "Cauldron implementation found, but the custom block config for mcMMO is disabled!"); getLogger().info("To enable, set Mods.Block_Mods_Enabled to TRUE in config.yml."); } if (!generalConfig.getEntityModsEnabled()) { - getLogger().warning("Cauldron implementation found, but the custom entity config for mcMMO is disabled!"); + getLogger().warning( + "Cauldron implementation found, but the custom entity config for mcMMO is disabled!"); getLogger().info("To enable, set Mods.Entity_Mods_Enabled to TRUE in config.yml."); } } @@ -698,9 +750,9 @@ 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 + * 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() { @@ -795,8 +847,4 @@ public class mcMMO extends JavaPlugin { public @NotNull FoliaLib getFoliaLib() { return foliaLib; } - -// public ProtocolLibManager getProtocolLibManager() { -// return protocolLibManager; -// } } diff --git a/src/main/java/com/gmail/nossr50/party/PartyManager.java b/src/main/java/com/gmail/nossr50/party/PartyManager.java index 283ebb1f6..2dcf2188d 100644 --- a/src/main/java/com/gmail/nossr50/party/PartyManager.java +++ b/src/main/java/com/gmail/nossr50/party/PartyManager.java @@ -1,5 +1,7 @@ package com.gmail.nossr50.party; +import static java.util.Objects.requireNonNull; + import com.gmail.nossr50.datatypes.chat.ChatChannel; import com.gmail.nossr50.datatypes.interactions.NotificationType; import com.gmail.nossr50.datatypes.party.ItemShareType; @@ -19,12 +21,6 @@ import com.gmail.nossr50.util.player.NotificationManager; import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.sounds.SoundManager; import com.gmail.nossr50.util.sounds.SoundType; -import org.bukkit.OfflinePlayer; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.io.File; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -32,8 +28,11 @@ import java.util.List; import java.util.Map.Entry; import java.util.UUID; import java.util.logging.Level; - -import static java.util.Objects.requireNonNull; +import org.bukkit.OfflinePlayer; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public final class PartyManager { private final @NotNull List parties; @@ -48,16 +47,20 @@ 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 + * 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 boolean isPartyFull(@NotNull Player player, @NotNull Party targetParty) { requireNonNull(player, "player cannot be null!"); requireNonNull(targetParty, "targetParty cannot be null!"); - return !Permissions.partySizeBypass(player) && pluginRef.getGeneralConfig().getPartyMaxSize() >= 1 && targetParty.getOnlineMembers().size() >= pluginRef.getGeneralConfig().getPartyMaxSize(); + return !Permissions.partySizeBypass(player) && pluginRef.getGeneralConfig() + .getPartyMaxSize() >= 1 + && targetParty.getOnlineMembers().size() >= pluginRef.getGeneralConfig() + .getPartyMaxSize(); } public boolean areAllies(@NotNull Player firstPlayer, @NotNull Player secondPlayer) { @@ -77,7 +80,8 @@ public final class PartyManager { Party firstParty = UserManager.getPlayer(firstPlayer).getParty(); Party secondParty = UserManager.getPlayer(secondPlayer).getParty(); - if (firstParty == null || secondParty == null || firstParty.getAlly() == null || secondParty.getAlly() == null) { + if (firstParty == null || secondParty == null || firstParty.getAlly() == null + || secondParty.getAlly() == null) { return false; } @@ -100,7 +104,8 @@ public final class PartyManager { double range = pluginRef.getGeneralConfig().getPartyShareRange(); for (Player member : party.getOnlineMembers()) { - if (!player.equals(member) && member.isValid() && Misc.isNear(player.getLocation(), member.getLocation(), range)) { + if (!player.equals(member) && member.isValid() && Misc.isNear(player.getLocation(), + member.getLocation(), range)) { nearMembers.add(member); } } @@ -119,9 +124,8 @@ public final class PartyManager { double range = pluginRef.getGeneralConfig().getPartyShareRange(); for (Player member : party.getVisibleMembers(player)) { - if (!player.equals(member) - && member.isValid() - && Misc.isNear(player.getLocation(), member.getLocation(), range)) { + if (!player.equals(member) && member.isValid() && Misc.isNear(player.getLocation(), + member.getLocation(), range)) { nearMembers.add(member); } } @@ -243,8 +247,9 @@ public final class PartyManager { } final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if (mmoPlayer == null) + if (mmoPlayer == null) { return null; + } return mmoPlayer.getParty(); } @@ -262,7 +267,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 void removeFromParty(@NotNull OfflinePlayer player, @NotNull Party party) { requireNonNull(player, "player cannot be null!"); @@ -292,16 +297,16 @@ public final class PartyManager { /** * Remove a player from a party. * - * @param mcMMOPlayer The player to remove + * @param mmoPlayer The player to remove */ - public void removeFromParty(@NotNull McMMOPlayer mcMMOPlayer) { - requireNonNull(mcMMOPlayer, "mcMMOPlayer cannot be null!"); - if (mcMMOPlayer.getParty() == null) { + public void removeFromParty(@NotNull McMMOPlayer mmoPlayer) { + requireNonNull(mmoPlayer, "mmoPlayer cannot be null!"); + if (mmoPlayer.getParty() == null) { return; } - removeFromParty(mcMMOPlayer.getPlayer(), mcMMOPlayer.getParty()); - processPartyLeaving(mcMMOPlayer); + removeFromParty(mmoPlayer.getPlayer(), mmoPlayer.getParty()); + processPartyLeaving(mmoPlayer); } /** @@ -319,10 +324,10 @@ public final class PartyManager { /** * Disband a party. Kicks out all members and removes the party. * - * @param mcMMOPlayer The player to remove (can be null? lol) + * @param mmoPlayer The player to remove (can be null? lol) * @param party The party to remove */ - public void disbandParty(@Nullable McMMOPlayer mcMMOPlayer, @NotNull Party party) { + public void disbandParty(@Nullable McMMOPlayer mmoPlayer, @NotNull Party party) { requireNonNull(party, "party cannot be null!"); //TODO: Potential issues with unloaded profile? for (final Player member : party.getOnlineMembers()) { @@ -340,22 +345,26 @@ public final class PartyManager { } parties.remove(party); - if (mcMMOPlayer != null) { - handlePartyChangeEvent(mcMMOPlayer.getPlayer(), party.getName(), null, EventReason.DISBANDED_PARTY); + if (mmoPlayer != null) { + handlePartyChangeEvent(mmoPlayer.getPlayer(), party.getName(), null, + EventReason.DISBANDED_PARTY); } } /** * 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 mmoPlayer 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 */ - public void createParty(@NotNull McMMOPlayer mcMMOPlayer, @NotNull String partyName, @Nullable String password) { - Player player = mcMMOPlayer.getPlayer(); + public void createParty(@NotNull McMMOPlayer mmoPlayer, @NotNull String partyName, + @Nullable String password) { + Player player = mmoPlayer.getPlayer(); - Party party = new Party(new PartyLeader(player.getUniqueId(), player.getName()), partyName.replace(".", ""), password); + Party party = new Party(new PartyLeader(player.getUniqueId(), player.getName()), + partyName.replace(".", ""), + password); if (password != null) { player.sendMessage(LocaleLoader.getString("Party.Password.Set", password)); @@ -364,19 +373,20 @@ public final class PartyManager { parties.add(party); player.sendMessage(LocaleLoader.getString("Commands.Party.Create", party.getName())); - addToParty(mcMMOPlayer, party); + addToParty(mmoPlayer, party); handlePartyChangeEvent(player, null, partyName, EventReason.CREATED_PARTY); } /** * 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 */ - public boolean checkPartyPassword(@NotNull Player player, @NotNull Party party, @Nullable String password) { + public boolean checkPartyPassword(@NotNull Player player, @NotNull Party party, + @Nullable String password) { if (party.isLocked()) { String partyPassword = party.getPassword(); @@ -402,40 +412,48 @@ public final class PartyManager { /** * Accept a party invitation * - * @param mcMMOPlayer The player to add to the party + * @param mmoPlayer The player to add to the party */ - public void joinInvitedParty(@NotNull McMMOPlayer mcMMOPlayer) { - requireNonNull(mcMMOPlayer, "mcMMOPlayer cannot be null!"); - Party invite = mcMMOPlayer.getPartyInvite(); + public void joinInvitedParty(@NotNull McMMOPlayer mmoPlayer) { + requireNonNull(mmoPlayer, "mmoPlayer cannot be null!"); + Party invite = mmoPlayer.getPartyInvite(); // Check if the party still exists, it might have been disbanded if (!parties.contains(invite)) { - NotificationManager.sendPlayerInformation(mcMMOPlayer.getPlayer(), NotificationType.PARTY_MESSAGE, "Party.Disband"); + NotificationManager.sendPlayerInformation(mmoPlayer.getPlayer(), + NotificationType.PARTY_MESSAGE, + "Party.Disband"); return; } /* * Don't let players join a full party */ - if (pluginRef.getGeneralConfig().getPartyMaxSize() > 0 && invite.getMembers().size() >= pluginRef.getGeneralConfig().getPartyMaxSize()) { - NotificationManager.sendPlayerInformation(mcMMOPlayer.getPlayer(), NotificationType.PARTY_MESSAGE, "Commands.Party.PartyFull.InviteAccept", invite.getName(), String.valueOf(pluginRef.getGeneralConfig().getPartyMaxSize())); + if (pluginRef.getGeneralConfig().getPartyMaxSize() > 0 && invite.getMembers() + .size() >= pluginRef.getGeneralConfig().getPartyMaxSize()) { + NotificationManager.sendPlayerInformation(mmoPlayer.getPlayer(), + NotificationType.PARTY_MESSAGE, + "Commands.Party.PartyFull.InviteAccept", invite.getName(), + String.valueOf(pluginRef.getGeneralConfig().getPartyMaxSize())); return; } - NotificationManager.sendPlayerInformation(mcMMOPlayer.getPlayer(), NotificationType.PARTY_MESSAGE, "Commands.Party.Invite.Accepted", invite.getName()); - mcMMOPlayer.removePartyInvite(); - addToParty(mcMMOPlayer, invite); + NotificationManager.sendPlayerInformation(mmoPlayer.getPlayer(), + NotificationType.PARTY_MESSAGE, + "Commands.Party.Invite.Accepted", invite.getName()); + mmoPlayer.removePartyInvite(); + addToParty(mmoPlayer, invite); } /** * Accept a party alliance invitation * - * @param mcMMOPlayer The player who accepts the alliance invite + * @param mmoPlayer The player who accepts the alliance invite */ - public void acceptAllianceInvite(@NotNull McMMOPlayer mcMMOPlayer) { - requireNonNull(mcMMOPlayer, "mcMMOPlayer cannot be null!"); - Party invite = mcMMOPlayer.getPartyAllianceInvite(); - Player player = mcMMOPlayer.getPlayer(); + public void acceptAllianceInvite(@NotNull McMMOPlayer mmoPlayer) { + requireNonNull(mmoPlayer, "mmoPlayer cannot be null!"); + Party invite = mmoPlayer.getPartyAllianceInvite(); + Player player = mmoPlayer.getPlayer(); // Check if the party still exists, it might have been disbanded if (!parties.contains(invite)) { @@ -443,14 +461,17 @@ public final class PartyManager { return; } - if (!handlePartyChangeAllianceEvent(player, mcMMOPlayer.getParty().getName(), invite.getName(), McMMOPartyAllianceChangeEvent.EventReason.FORMED_ALLIANCE)) { + if (!handlePartyChangeAllianceEvent(player, mmoPlayer.getParty().getName(), + invite.getName(), + McMMOPartyAllianceChangeEvent.EventReason.FORMED_ALLIANCE)) { return; } - player.sendMessage(LocaleLoader.getString("Commands.Party.Alliance.Invite.Accepted", invite.getName())); - mcMMOPlayer.removePartyAllianceInvite(); + player.sendMessage(LocaleLoader.getString("Commands.Party.Alliance.Invite.Accepted", + invite.getName())); + mmoPlayer.removePartyAllianceInvite(); - createAlliance(mcMMOPlayer.getParty(), invite); + createAlliance(mmoPlayer.getParty(), invite); } public void createAlliance(@NotNull Party firstParty, @NotNull Party secondParty) { @@ -461,20 +482,24 @@ public final class PartyManager { secondParty.setAlly(firstParty); for (Player member : firstParty.getOnlineMembers()) { - member.sendMessage(LocaleLoader.getString("Party.Alliance.Formed", secondParty.getName())); + member.sendMessage( + LocaleLoader.getString("Party.Alliance.Formed", secondParty.getName())); } for (Player member : secondParty.getOnlineMembers()) { - member.sendMessage(LocaleLoader.getString("Party.Alliance.Formed", firstParty.getName())); + member.sendMessage( + LocaleLoader.getString("Party.Alliance.Formed", firstParty.getName())); } } - public boolean disbandAlliance(@NotNull Player player, @NotNull Party firstParty, @NotNull Party secondParty) { + public boolean disbandAlliance(@NotNull Player player, @NotNull Party firstParty, + @NotNull Party secondParty) { requireNonNull(player, "player cannot be null!"); requireNonNull(firstParty, "firstParty cannot be null!"); requireNonNull(secondParty, "secondParty cannot be null!"); - if (!handlePartyChangeAllianceEvent(player, firstParty.getName(), secondParty.getName(), McMMOPartyAllianceChangeEvent.EventReason.DISBAND_ALLIANCE)) { + if (!handlePartyChangeAllianceEvent(player, firstParty.getName(), secondParty.getName(), + McMMOPartyAllianceChangeEvent.EventReason.DISBAND_ALLIANCE)) { return false; } @@ -489,29 +514,31 @@ public final class PartyManager { secondParty.setAlly(null); for (Player member : firstParty.getOnlineMembers()) { - member.sendMessage(LocaleLoader.getString("Party.Alliance.Disband", secondParty.getName())); + member.sendMessage( + LocaleLoader.getString("Party.Alliance.Disband", secondParty.getName())); } for (Player member : secondParty.getOnlineMembers()) { - member.sendMessage(LocaleLoader.getString("Party.Alliance.Disband", firstParty.getName())); + member.sendMessage( + LocaleLoader.getString("Party.Alliance.Disband", firstParty.getName())); } } /** * Add a player to a party * - * @param mcMMOPlayer The player to add to the party - * @param party The party + * @param mmoPlayer The player to add to the party + * @param party The party */ - public void addToParty(@NotNull McMMOPlayer mcMMOPlayer, @NotNull Party party) { - requireNonNull(mcMMOPlayer, "mcMMOPlayer cannot be null!"); + public void addToParty(@NotNull McMMOPlayer mmoPlayer, @NotNull Party party) { + requireNonNull(mmoPlayer, "mmoPlayer cannot be null!"); requireNonNull(party, "party cannot be null!"); - Player player = mcMMOPlayer.getPlayer(); + Player player = mmoPlayer.getPlayer(); String playerName = player.getName(); informPartyMembersJoin(party, playerName); - mcMMOPlayer.setParty(party); + mmoPlayer.setParty(party); party.getMembers().put(player.getUniqueId(), player.getName()); party.getOnlineMembers().add(player); } @@ -532,7 +559,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 void setPartyLeader(@NotNull UUID uuid, @NotNull Party party) { @@ -561,17 +588,18 @@ public final class PartyManager { * * @return true if the player can invite */ - public boolean canInvite(@NotNull McMMOPlayer mcMMOPlayer) { - requireNonNull(mcMMOPlayer, "mcMMOPlayer cannot be null!"); - Party party = mcMMOPlayer.getParty(); + public boolean canInvite(@NotNull McMMOPlayer mmoPlayer) { + requireNonNull(mmoPlayer, "mmoPlayer cannot be null!"); + Party party = mmoPlayer.getParty(); - return !party.isLocked() || party.getLeader().getUniqueId().equals(mcMMOPlayer.getPlayer().getUniqueId()); + return !party.isLocked() || party.getLeader().getUniqueId() + .equals(mmoPlayer.getPlayer().getUniqueId()); } /** * 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 */ @@ -590,7 +618,7 @@ public final class PartyManager { /** * Attempt to change parties or join a new party. * - * @param mmoPlayer The player changing or joining parties + * @param mmoPlayer 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 */ @@ -603,12 +631,15 @@ public final class PartyManager { if (mmoPlayer.inParty()) { final Party oldParty = mmoPlayer.getParty(); - if (!handlePartyChangeEvent(player, oldParty.getName(), newPartyName, EventReason.CHANGED_PARTIES)) { + if (!handlePartyChangeEvent(player, oldParty.getName(), newPartyName, + EventReason.CHANGED_PARTIES)) { return false; } removeFromParty(mmoPlayer); - } else return handlePartyChangeEvent(player, null, newPartyName, EventReason.JOINED_PARTY); + } else { + return handlePartyChangeEvent(player, null, newPartyName, EventReason.JOINED_PARTY); + } return true; } @@ -616,7 +647,7 @@ 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 */ @@ -662,8 +693,10 @@ public final class PartyManager { try { Party party = new Party(partyName); - String[] leaderSplit = partiesFile.getString(partyName + ".Leader").split("[|]"); - party.setLeader(new PartyLeader(UUID.fromString(leaderSplit[0]), leaderSplit[1])); + String[] leaderSplit = partiesFile.getString(partyName + ".Leader") + .split("[|]"); + party.setLeader( + new PartyLeader(UUID.fromString(leaderSplit[0]), leaderSplit[1])); party.setPassword(partiesFile.getString(partyName + ".Password")); party.setLocked(partiesFile.getBoolean(partyName + ".Locked")); party.setLevel(partiesFile.getInt(partyName + ".Level")); @@ -673,11 +706,18 @@ public final class PartyManager { hasAlly.add(party); } - party.setXpShareMode(ShareMode.getShareMode(partiesFile.getString(partyName + ".ExpShareMode", "NONE"))); - party.setItemShareMode(ShareMode.getShareMode(partiesFile.getString(partyName + ".ItemShareMode", "NONE"))); + party.setXpShareMode( + ShareMode.getShareMode( + partiesFile.getString(partyName + ".ExpShareMode", "NONE"))); + party.setItemShareMode( + ShareMode.getShareMode( + partiesFile.getString(partyName + ".ItemShareMode", "NONE"))); for (ItemShareType itemShareType : ItemShareType.values()) { - party.setSharingDrops(itemShareType, partiesFile.getBoolean(partyName + ".ItemShareType." + itemShareType.toString(), true)); + party.setSharingDrops(itemShareType, + partiesFile.getBoolean( + partyName + ".ItemShareType." + itemShareType, + true)); } LinkedHashMap members = party.getMembers(); @@ -689,7 +729,10 @@ public final class PartyManager { parties.add(party); } catch (Exception e) { - pluginRef.getLogger().log(Level.WARNING, "An exception occurred while loading a party with name '" + partyName + "'. Skipped loading party.", e); + pluginRef.getLogger().log(Level.WARNING, + "An exception occurred while loading a party with name '" + partyName + + "'. Skipped loading party.", + e); } } @@ -723,23 +766,27 @@ public final class PartyManager { String partyName = party.getName(); PartyLeader leader = party.getLeader(); - partiesFile.set(partyName + ".Leader", leader.getUniqueId().toString() + "|" + leader.getPlayerName()); + partiesFile.set(partyName + ".Leader", + leader.getUniqueId().toString() + "|" + leader.getPlayerName()); partiesFile.set(partyName + ".Password", party.getPassword()); partiesFile.set(partyName + ".Locked", party.isLocked()); partiesFile.set(partyName + ".Level", party.getLevel()); partiesFile.set(partyName + ".Xp", (int) party.getXp()); - partiesFile.set(partyName + ".Ally", (party.getAlly() != null) ? party.getAlly().getName() : ""); + partiesFile.set(partyName + ".Ally", + (party.getAlly() != null) ? party.getAlly().getName() : ""); partiesFile.set(partyName + ".ExpShareMode", party.getXpShareMode().toString()); partiesFile.set(partyName + ".ItemShareMode", party.getItemShareMode().toString()); for (ItemShareType itemShareType : ItemShareType.values()) { - partiesFile.set(partyName + ".ItemShareType." + itemShareType.toString(), party.sharingDrops(itemShareType)); + partiesFile.set(partyName + ".ItemShareType." + itemShareType.toString(), + party.sharingDrops(itemShareType)); } List members = new ArrayList<>(); for (Entry memberEntry : party.getMembers().entrySet()) { - String memberUniqueId = memberEntry.getKey() == null ? "" : memberEntry.getKey().toString(); + String memberUniqueId = + memberEntry.getKey() == null ? "" : memberEntry.getKey().toString(); String memberName = memberEntry.getValue(); if (!members.contains(memberName)) { @@ -760,14 +807,16 @@ 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 boolean handlePartyChangeEvent(Player player, String oldPartyName, String newPartyName, EventReason reason) { - McMMOPartyChangeEvent event = new McMMOPartyChangeEvent(player, oldPartyName, newPartyName, reason); + public boolean handlePartyChangeEvent(Player player, String oldPartyName, String newPartyName, + EventReason reason) { + McMMOPartyChangeEvent event = new McMMOPartyChangeEvent(player, oldPartyName, newPartyName, + reason); pluginRef.getServer().getPluginManager().callEvent(event); return !event.isCancelled(); @@ -776,36 +825,40 @@ 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 boolean handlePartyChangeAllianceEvent(Player player, String oldAllyName, String newAllyName, McMMOPartyAllianceChangeEvent.EventReason reason) { - McMMOPartyAllianceChangeEvent event = new McMMOPartyAllianceChangeEvent(player, oldAllyName, newAllyName, reason); + public boolean handlePartyChangeAllianceEvent(Player player, String oldAllyName, + String newAllyName, + McMMOPartyAllianceChangeEvent.EventReason reason) { + McMMOPartyAllianceChangeEvent event = new McMMOPartyAllianceChangeEvent(player, oldAllyName, + newAllyName, + reason); pluginRef.getServer().getPluginManager().callEvent(event); return !event.isCancelled(); } /** - * Remove party data from the mcMMOPlayer. + * Remove party data from the mmoPlayer. * - * @param mcMMOPlayer The player to remove party data from. + * @param mmoPlayer The player to remove party data from. */ - public void processPartyLeaving(@NotNull McMMOPlayer mcMMOPlayer) { - mcMMOPlayer.removeParty(); - mcMMOPlayer.setChatMode(ChatChannel.NONE); - mcMMOPlayer.setItemShareModifier(10); + public void processPartyLeaving(@NotNull McMMOPlayer mmoPlayer) { + mmoPlayer.removeParty(); + mmoPlayer.setChatMode(ChatChannel.NONE); + mmoPlayer.setItemShareModifier(10); } /** * 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 void informPartyMembersLevelUp(Party party, int levelsGained, int level) { boolean levelUpSoundsEnabled = pluginRef.getGeneralConfig().getLevelUpSoundsEnabled(); @@ -821,7 +874,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 void informPartyMembersJoin(Party party, String playerName) { @@ -833,7 +886,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 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 4719ebc36..a9c38d6e4 100644 --- a/src/main/java/com/gmail/nossr50/party/ShareHandler.java +++ b/src/main/java/com/gmail/nossr50/party/ShareHandler.java @@ -11,41 +11,42 @@ import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.player.UserManager; +import java.util.List; import org.bukkit.entity.Item; import org.bukkit.entity.Player; 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 mmoPlayer Player initiating the Xp gain * @param primarySkillType Skill being used * @return True is the xp has been shared */ - public static boolean handleXpShare(float xp, McMMOPlayer mcMMOPlayer, PrimarySkillType primarySkillType, XPGainReason xpGainReason) { - Party party = mcMMOPlayer.getParty(); + public static boolean handleXpShare(float xp, McMMOPlayer mmoPlayer, + PrimarySkillType primarySkillType, XPGainReason xpGainReason) { + Party party = mmoPlayer.getParty(); if (party.getXpShareMode() != ShareMode.EQUAL) { return false; } - List nearMembers = mcMMO.p.getPartyManager().getNearVisibleMembers(mcMMOPlayer); + List nearMembers = mcMMO.p.getPartyManager().getNearVisibleMembers(mmoPlayer); if (nearMembers.isEmpty()) { return false; } - nearMembers.add(mcMMOPlayer.getPlayer()); + nearMembers.add(mmoPlayer.getPlayer()); int partySize = nearMembers.size(); double shareBonus = Math.min(mcMMO.p.getGeneralConfig().getPartyShareBonusBase() - + (partySize * mcMMO.p.getGeneralConfig().getPartyShareBonusIncrease()), + + (partySize * mcMMO.p.getGeneralConfig().getPartyShareBonusIncrease()), mcMMO.p.getGeneralConfig().getPartyShareBonusCap()); float splitXp = (float) (xp / partySize * shareBonus); @@ -55,7 +56,9 @@ public final class ShareHandler { continue; } - UserManager.getPlayer(member).beginUnsharedXpGain(primarySkillType, splitXp, xpGainReason, XPGainSource.PARTY_MEMBERS); + UserManager.getPlayer(member) + .beginUnsharedXpGain(primarySkillType, splitXp, xpGainReason, + XPGainSource.PARTY_MEMBERS); } return true; @@ -65,10 +68,10 @@ public final class ShareHandler { * Distribute Items amongst party members. * * @param drop Item that will get shared - * @param mcMMOPlayer Player who picked up the item + * @param mmoPlayer Player who picked up the item * @return True if the item has been shared */ - public static boolean handleItemShare(Item drop, McMMOPlayer mcMMOPlayer) { + public static boolean handleItemShare(Item drop, McMMOPlayer mmoPlayer) { ItemStack itemStack = drop.getItemStack(); ItemShareType dropType = ItemShareType.getShareType(itemStack); @@ -76,7 +79,7 @@ public final class ShareHandler { return false; } - Party party = mcMMOPlayer.getParty(); + Party party = mmoPlayer.getParty(); if (!party.sharingDrops(dropType)) { return false; @@ -88,7 +91,7 @@ public final class ShareHandler { return false; } - List nearMembers = mcMMO.p.getPartyManager().getNearMembers(mcMMOPlayer); + List nearMembers = mcMMO.p.getPartyManager().getNearMembers(mmoPlayer); if (nearMembers.isEmpty()) { return false; @@ -97,7 +100,7 @@ public final class ShareHandler { Player winningPlayer = null; ItemStack newStack = itemStack.clone(); - nearMembers.add(mcMMOPlayer.getPlayer()); + nearMembers.add(mmoPlayer.getPlayer()); int partySize = nearMembers.size(); drop.remove(); @@ -130,14 +133,16 @@ public final class ShareHandler { if (winningPlayer != null) { McMMOPlayer mcMMOWinning = UserManager.getPlayer(winningPlayer); - mcMMOWinning.setItemShareModifier(mcMMOWinning.getItemShareModifier() + itemWeight); + mcMMOWinning.setItemShareModifier( + mcMMOWinning.getItemShareModifier() + itemWeight); } winningPlayer = member; } McMMOPlayer mcMMOTarget = UserManager.getPlayer(winningPlayer); - mcMMOTarget.setItemShareModifier(mcMMOTarget.getItemShareModifier() - itemWeight); + mcMMOTarget.setItemShareModifier( + mcMMOTarget.getItemShareModifier() - itemWeight); awardDrop(winningPlayer, newStack); } diff --git a/src/main/java/com/gmail/nossr50/placeholders/PapiExpansion.java b/src/main/java/com/gmail/nossr50/placeholders/PapiExpansion.java index 403d18fce..06ad1b25b 100644 --- a/src/main/java/com/gmail/nossr50/placeholders/PapiExpansion.java +++ b/src/main/java/com/gmail/nossr50/placeholders/PapiExpansion.java @@ -9,17 +9,17 @@ import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.text.StringUtils; +import java.util.Map; +import java.util.TreeMap; import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.expansion.PlaceholderExpansion; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Map; -import java.util.TreeMap; - public class PapiExpansion extends PlaceholderExpansion { - private final Map placeholders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + private final Map placeholders = new TreeMap<>( + String.CASE_INSENSITIVE_ORDER); public PapiExpansion() { init(); @@ -76,19 +76,25 @@ public class PapiExpansion extends PlaceholderExpansion { public Integer getSkillLevel(PrimarySkillType skill, Player player) { final McMMOPlayer user = UserManager.getPlayer(player); - if (user == null) return null; + if (user == null) { + return null; + } return user.getSkillLevel(skill); } public Integer getExpNeeded(PrimarySkillType skill, Player player) { final McMMOPlayer user = UserManager.getPlayer(player); - if (user == null) return null; + if (user == null) { + return null; + } return user.getXpToLevel(skill); } public Integer getExp(PrimarySkillType skill, Player player) { final McMMOPlayer user = UserManager.getPlayer(player); - if (user == null) return null; + if (user == null) { + return null; + } return user.getSkillXpLevel(skill); } @@ -96,7 +102,9 @@ public class PapiExpansion extends PlaceholderExpansion { public Integer getExpRemaining(PrimarySkillType skill, Player player) { final McMMOPlayer user = UserManager.getPlayer(player); - if (user == null) return null; + if (user == null) { + return null; + } int current = user.getSkillXpLevel(skill); int needed = user.getXpToLevel(skill); @@ -105,7 +113,8 @@ public class PapiExpansion extends PlaceholderExpansion { public Integer getRank(PrimarySkillType skill, Player player) { try { - return ExperienceAPI.getPlayerRankSkill(player.getUniqueId(), StringUtils.getCapitalized(skill.toString())); + return ExperienceAPI.getPlayerRankSkill(player.getUniqueId(), + StringUtils.getCapitalized(skill.toString())); } catch (Exception ex) { return null; } @@ -113,7 +122,9 @@ public class PapiExpansion extends PlaceholderExpansion { public Integer getPowerLevel(Player player) { final McMMOPlayer user = UserManager.getPlayer(player); - if (user == null) return null; + if (user == null) { + return null; + } return user.getPowerLevel(); } @@ -123,7 +134,9 @@ public class PapiExpansion extends PlaceholderExpansion { public String getPartyName(Player player) { final McMMOPlayer user = UserManager.getPlayer(player); - if (user == null) return null; + if (user == null) { + return null; + } final Party party = user.getParty(); return (party == null) ? null : party.getName(); @@ -131,14 +144,18 @@ public class PapiExpansion extends PlaceholderExpansion { public String getPartyLeader(Player player) { final McMMOPlayer user = UserManager.getPlayer(player); - if (user == null) return null; + if (user == null) { + return null; + } final Party party = user.getParty(); return (party == null) ? null : party.getLeader().getPlayerName(); } public Integer getPartySize(Player player) { final McMMOPlayer user = UserManager.getPlayer(player); - if (user == null) return null; + if (user == null) { + return null; + } final Party party = user.getParty(); return (party == null) ? null : party.getMembers().size(); } @@ -149,36 +166,42 @@ public class PapiExpansion extends PlaceholderExpansion { public String getSkillXpRate(PrimarySkillType skill, Player player) { final McMMOPlayer user = UserManager.getPlayer(player); - if (user == null) return null; + if (user == null) { + return null; + } double modifier = 1.0F; - if (Permissions.customXpBoost(player, skill)) + if (Permissions.customXpBoost(player, skill)) { modifier = ExperienceConfig.getInstance().getCustomXpPerkBoost(); - else if (Permissions.quadrupleXp(player, skill)) + } else if (Permissions.quadrupleXp(player, skill)) { modifier = 4; - else if (Permissions.tripleXp(player, skill)) + } else if (Permissions.tripleXp(player, skill)) { modifier = 3; - else if (Permissions.doubleAndOneHalfXp(player, skill)) + } else if (Permissions.doubleAndOneHalfXp(player, skill)) { modifier = 2.5; - else if (Permissions.doubleXp(player, skill)) + } else if (Permissions.doubleXp(player, skill)) { modifier = 2; - else if (Permissions.oneAndOneHalfXp(player, skill)) + } else if (Permissions.oneAndOneHalfXp(player, skill)) { modifier = 1.5; - else if (Permissions.oneAndOneTenthXp(player, skill)) + } else if (Permissions.oneAndOneTenthXp(player, skill)) { modifier = 1.1; + } return String.valueOf(modifier); } public String isExpEventActive(Player player) { - return mcMMO.p.isXPEventEnabled() ? PlaceholderAPIPlugin.booleanTrue() : PlaceholderAPIPlugin.booleanFalse(); + return mcMMO.p.isXPEventEnabled() ? PlaceholderAPIPlugin.booleanTrue() + : PlaceholderAPIPlugin.booleanFalse(); } public void registerPlaceholder(Placeholder placeholder) { final Placeholder registered = placeholders.get(placeholder.getName()); - if (registered != null) - throw new IllegalStateException("Placeholder " + placeholder.getName() + " is already registered!"); + if (registered != null) { + throw new IllegalStateException( + "Placeholder " + placeholder.getName() + " is already registered!"); + } placeholders.put(placeholder.getName(), placeholder); } @@ -205,7 +228,6 @@ public class PapiExpansion extends PlaceholderExpansion { registerPlaceholder(new SkillXpRatePlaceholder(this, skill)); } - //%mcmmo_power_level% registerPlaceholder(new PowerLevelPlaceholder(this)); @@ -231,5 +253,6 @@ public class PapiExpansion extends PlaceholderExpansion { registerPlaceholder(new XpEventActivePlaceholder(this)); // %mcmmo_xprate% registerPlaceholder(new XpRatePlaceholder(this)); - }; + } + } diff --git a/src/main/java/com/gmail/nossr50/placeholders/PartyIsMemberPlaceholder.java b/src/main/java/com/gmail/nossr50/placeholders/PartyIsMemberPlaceholder.java index ac385a4ba..a57666628 100644 --- a/src/main/java/com/gmail/nossr50/placeholders/PartyIsMemberPlaceholder.java +++ b/src/main/java/com/gmail/nossr50/placeholders/PartyIsMemberPlaceholder.java @@ -5,6 +5,7 @@ import org.bukkit.entity.Player; public class PartyIsMemberPlaceholder implements Placeholder { private final PapiExpansion papiExpansion; + public PartyIsMemberPlaceholder(PapiExpansion papiExpansion) { this.papiExpansion = papiExpansion; } diff --git a/src/main/java/com/gmail/nossr50/protocollib/ProtocolHandler.java b/src/main/java/com/gmail/nossr50/protocollib/ProtocolHandler.java deleted file mode 100644 index bae3793f9..000000000 --- a/src/main/java/com/gmail/nossr50/protocollib/ProtocolHandler.java +++ /dev/null @@ -1,36 +0,0 @@ -//package com.gmail.nossr50.protocollib; -// -//import com.comphenix.protocol.PacketType; -//import com.comphenix.protocol.ProtocolLibrary; -//import com.comphenix.protocol.ProtocolManager; -//import com.comphenix.protocol.events.ListenerPriority; -//import com.comphenix.protocol.events.PacketAdapter; -//import com.comphenix.protocol.events.PacketContainer; -//import com.comphenix.protocol.events.PacketEvent; -//import com.gmail.nossr50.mcMMO; -//import org.bukkit.entity.Player; -// -//public class ProtocolHandler { -// private final mcMMO pluginRef; -// private final ProtocolManager protocolManager; -// -// public ProtocolHandler(mcMMO pluginRef) { -// this.pluginRef = pluginRef; -// this.protocolManager = ProtocolLibrary.getProtocolManager(); -// // TODO: encapsulate this in a method -// protocolManager.addPacketListener(new PacketAdapter(pluginRef, ListenerPriority.NORMAL, PacketType.Play.Server.WINDOW_DATA) { -// @Override -// public void onPacketSending(PacketEvent event) { -// Player player = event.getPlayer(); -// PacketContainer packet = event.getPacket(); -// if (packet.getIntegers().read(0) == 400) { -// event.setCancelled(true); -// } -// } -// }); -// } -// public void sendPacketToPlayer(Player player) { -// final PacketContainer packet = protocolManager.createPacket(PacketType.Play.Server.WINDOW_DATA); -// protocolManager.sendServerPacket(player, packet); -// } -//} diff --git a/src/main/java/com/gmail/nossr50/protocollib/ProtocolLibManager.java b/src/main/java/com/gmail/nossr50/protocollib/ProtocolLibManager.java deleted file mode 100644 index 77f3c21bf..000000000 --- a/src/main/java/com/gmail/nossr50/protocollib/ProtocolLibManager.java +++ /dev/null @@ -1,40 +0,0 @@ -//package com.gmail.nossr50.protocollib; -// -//import com.gmail.nossr50.mcMMO; -//import org.bukkit.Bukkit; -//import org.bukkit.entity.Player; -//import org.bukkit.plugin.Plugin; -// -//public class ProtocolLibManager { -// final Plugin protocolLibPluginRef; -// final mcMMO pluginRef; -// final ProtocolHandler protocolHandler; -// -// public ProtocolLibManager(mcMMO pluginRef) { -// this.pluginRef = pluginRef; -// -// if (isProtocolLibPresent()) { -// protocolLibPluginRef = pluginRef.getServer().getPluginManager().getPlugin("ProtocolLib"); -// protocolHandler = new ProtocolHandler(pluginRef); -// pluginRef.getLogger().info("ProtocolLib found, enabling ProtocolLib features."); -// } else { -// protocolLibPluginRef = null; -// protocolHandler = null; -// pluginRef.getLogger().info("No ProtocolLib found, some completely optional cosmetic features will not be enabled."); -// } -// } -// -// public boolean usingProtocolLib() { -// return protocolLibPluginRef != null && protocolHandler != null; -// } -// -// private boolean isProtocolLibPresent() { -// return Bukkit.getServer().getPluginManager().getPlugin("ProtocolLib") != null; -// } -// -// public void sendPacketToPlayer(Player player) { -// if (usingProtocolLib()) { -// protocolHandler.sendPacketToPlayer(player); -// } -// } -//} diff --git a/src/main/java/com/gmail/nossr50/runnables/MobHealthDisplayUpdaterTask.java b/src/main/java/com/gmail/nossr50/runnables/MobHealthDisplayUpdaterTask.java index 8e59fcb5b..45d28c557 100644 --- a/src/main/java/com/gmail/nossr50/runnables/MobHealthDisplayUpdaterTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/MobHealthDisplayUpdaterTask.java @@ -15,12 +15,16 @@ public class MobHealthDisplayUpdaterTask extends CancellableRunnable { @Override public void run() { if (target.hasMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME)) { - target.setCustomName(target.getMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME).get(0).asString()); + target.setCustomName( + target.getMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME).get(0) + .asString()); target.removeMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME, mcMMO.p); } if (target.hasMetadata(MetadataConstants.METADATA_KEY_NAME_VISIBILITY)) { - target.setCustomNameVisible(target.getMetadata(MetadataConstants.METADATA_KEY_NAME_VISIBILITY).get(0).asBoolean()); + target.setCustomNameVisible( + target.getMetadata(MetadataConstants.METADATA_KEY_NAME_VISIBILITY).get(0) + .asBoolean()); target.removeMetadata(MetadataConstants.METADATA_KEY_NAME_VISIBILITY, mcMMO.p); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/SaveTimerTask.java b/src/main/java/com/gmail/nossr50/runnables/SaveTimerTask.java index 8ac243158..6fba23714 100644 --- a/src/main/java/com/gmail/nossr50/runnables/SaveTimerTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/SaveTimerTask.java @@ -14,12 +14,14 @@ public class SaveTimerTask extends CancellableRunnable { // All player data will be saved periodically through this int count = 1; - for (McMMOPlayer mcMMOPlayer : UserManager.getPlayers()) { - mcMMO.p.getFoliaLib().getScheduler().runLaterAsync(new PlayerProfileSaveTask(mcMMOPlayer.getProfile(), false), count); + for (McMMOPlayer mmoPlayer : UserManager.getPlayers()) { + mcMMO.p.getFoliaLib().getScheduler() + .runLaterAsync(new PlayerProfileSaveTask(mmoPlayer.getProfile(), false), count); count++; } - if (mcMMO.p.getPartyConfig().isPartyEnabled()) + if (mcMMO.p.getPartyConfig().isPartyEnabled()) { mcMMO.p.getPartyManager().saveParties(); + } } } 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 bae6f4e32..78df232e2 100644 --- a/src/main/java/com/gmail/nossr50/runnables/backups/CleanBackupsTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/backups/CleanBackupsTask.java @@ -3,15 +3,20 @@ package com.gmail.nossr50.runnables.backups; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.CancellableRunnable; import com.gmail.nossr50.util.LogUtils; - import java.io.File; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.*; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; import java.util.concurrent.TimeUnit; public class CleanBackupsTask extends CancellableRunnable { - private static final String BACKUP_DIRECTORY = mcMMO.getMainDirectory() + "backup" + File.separator; + private static final String BACKUP_DIRECTORY = + mcMMO.getMainDirectory() + "backup" + File.separator; private static final File BACKUP_DIR = new File(BACKUP_DIRECTORY); @Override @@ -38,7 +43,8 @@ public class CleanBackupsTask extends CancellableRunnable { Date date = getDate(fileName.split("[.]")[0]); if (!fileName.contains(".zip") || date == null) { - LogUtils.debug(mcMMO.p.getLogger(), "Could not determine date for file: " + fileName); + LogUtils.debug(mcMMO.p.getLogger(), + "Could not determine date for file: " + fileName); continue; } @@ -51,14 +57,17 @@ public class CleanBackupsTask extends CancellableRunnable { if (isPast24Hours(date) && mcMMO.p.getGeneralConfig().getKeepLast24Hours()) { // Keep all files from the last 24 hours continue; - } else if (isLastWeek(date) && !savedDays.contains(dayOfWeek) && mcMMO.p.getGeneralConfig().getKeepDailyLastWeek()) { + } else if (isLastWeek(date) && !savedDays.contains(dayOfWeek) + && mcMMO.p.getGeneralConfig().getKeepDailyLastWeek()) { // Keep daily backups of the past week savedDays.add(dayOfWeek); continue; } else { - List savedWeeks = savedYearsWeeks.computeIfAbsent(year, k -> new ArrayList<>()); + List savedWeeks = savedYearsWeeks.computeIfAbsent(year, + k -> new ArrayList<>()); - if (!savedWeeks.contains(weekOfYear) && mcMMO.p.getGeneralConfig().getKeepWeeklyPastMonth()) { + if (!savedWeeks.contains(weekOfYear) && mcMMO.p.getGeneralConfig() + .getKeepWeeklyPastMonth()) { // Keep one backup of each week savedWeeks.add(weekOfYear); continue; @@ -73,7 +82,9 @@ public class CleanBackupsTask extends CancellableRunnable { return; } - LogUtils.debug(mcMMO.p.getLogger(), "Cleaned backup files. Deleted " + amountDeleted + " of " + amountTotal + " files."); + LogUtils.debug(mcMMO.p.getLogger(), + "Cleaned backup files. Deleted " + amountDeleted + " of " + amountTotal + + " files."); for (File file : toDelete) { if (file.delete()) { @@ -86,11 +97,11 @@ public class CleanBackupsTask extends CancellableRunnable { * 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) { - Date modifiedDate = new Date(System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(24, TimeUnit.HOURS)); + Date modifiedDate = new Date( + System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(24, TimeUnit.HOURS)); return date.after(modifiedDate); } @@ -98,11 +109,11 @@ public class CleanBackupsTask extends CancellableRunnable { * 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) { - Date modifiedDate = new Date(System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(7, TimeUnit.DAYS)); + Date modifiedDate = new Date( + System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(7, TimeUnit.DAYS)); return date.after(modifiedDate); } @@ -112,8 +123,7 @@ public class CleanBackupsTask extends CancellableRunnable { try { date = dateFormat.parse(fileName); - } - catch (ParseException e) { + } catch (ParseException e) { return null; } diff --git a/src/main/java/com/gmail/nossr50/runnables/commands/McRankCommandAsyncTask.java b/src/main/java/com/gmail/nossr50/runnables/commands/McRankCommandAsyncTask.java index 7b75c19c3..4148cd6cd 100644 --- a/src/main/java/com/gmail/nossr50/runnables/commands/McRankCommandAsyncTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/commands/McRankCommandAsyncTask.java @@ -3,23 +3,25 @@ package com.gmail.nossr50.runnables.commands; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.CancellableRunnable; +import java.util.Map; import org.apache.commons.lang3.Validate; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.util.Map; - public class McRankCommandAsyncTask extends CancellableRunnable { private final String playerName; private final CommandSender sender; private final boolean useBoard, useChat; - public McRankCommandAsyncTask(String playerName, CommandSender sender, boolean useBoard, boolean useChat) { - Validate.isTrue(useBoard || useChat, "Attempted to start a rank retrieval with both board and chat off"); + public McRankCommandAsyncTask(String playerName, CommandSender sender, boolean useBoard, + boolean useChat) { + Validate.isTrue(useBoard || useChat, + "Attempted to start a rank retrieval with both board and chat off"); Validate.notNull(sender, "Attempted to start a rank retrieval with no recipient"); if (useBoard) { - Validate.isTrue(sender instanceof Player, "Attempted to start a rank retrieval displaying scoreboard to a non-player"); + Validate.isTrue(sender instanceof Player, + "Attempted to start a rank retrieval displaying scoreboard to a non-player"); } this.playerName = playerName; @@ -32,7 +34,8 @@ public class McRankCommandAsyncTask extends CancellableRunnable { public void run() { Map skills = mcMMO.getDatabaseManager().readRank(playerName); - mcMMO.p.getFoliaLib().getScheduler().runNextTick(new McRankCommandDisplayTask(skills, sender, playerName, useBoard, useChat)); + mcMMO.p.getFoliaLib().getScheduler().runNextTick( + new McRankCommandDisplayTask(skills, sender, playerName, useBoard, useChat)); } } 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 a6cf28069..08c7a9abd 100644 --- a/src/main/java/com/gmail/nossr50/runnables/commands/McRankCommandDisplayTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/commands/McRankCommandDisplayTask.java @@ -7,11 +7,10 @@ import com.gmail.nossr50.util.CancellableRunnable; import com.gmail.nossr50.util.MetadataConstants; import com.gmail.nossr50.util.scoreboards.ScoreboardManager; import com.gmail.nossr50.util.skills.SkillTools; +import java.util.Map; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.util.Map; - /** * Display the results of McrankCommandAsyncTask to the sender. */ @@ -21,8 +20,9 @@ public class McRankCommandDisplayTask extends CancellableRunnable { private final String playerName; private final boolean useBoard, useChat; - McRankCommandDisplayTask(Map skills, CommandSender sender, String playerName, - boolean useBoard, boolean useChat) { + McRankCommandDisplayTask(Map skills, CommandSender sender, + String playerName, + boolean useBoard, boolean useChat) { this.skills = skills; this.sender = sender; this.playerName = playerName; @@ -51,15 +51,19 @@ public class McRankCommandDisplayTask extends CancellableRunnable { for (PrimarySkillType skill : SkillTools.NON_CHILD_SKILLS) { // Check if the command is for Maces but the MC version is not correct if (skill == PrimarySkillType.MACES - && !mcMMO.getCompatibilityManager().getMinecraftGameVersion().isAtLeast(1, 21, 0)) { + && !mcMMO.getCompatibilityManager().getMinecraftGameVersion() + .isAtLeast(1, 21, 0)) { continue; } rank = skills.get(skill); - sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Skill", mcMMO.p.getSkillTools().getLocalizedSkillName(skill), (rank == null ? LocaleLoader.getString("Commands.mcrank.Unranked") : rank))); + sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Skill", + mcMMO.p.getSkillTools().getLocalizedSkillName(skill), + (rank == null ? LocaleLoader.getString("Commands.mcrank.Unranked") : rank))); } rank = skills.get(null); - sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Overall", (rank == null ? LocaleLoader.getString("Commands.mcrank.Unranked") : rank))); + sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Overall", + (rank == null ? LocaleLoader.getString("Commands.mcrank.Unranked") : rank))); } public void displayBoard() { diff --git a/src/main/java/com/gmail/nossr50/runnables/commands/McTopCommandAsyncTask.java b/src/main/java/com/gmail/nossr50/runnables/commands/McTopCommandAsyncTask.java index c52d6d1f9..c8da44146 100644 --- a/src/main/java/com/gmail/nossr50/runnables/commands/McTopCommandAsyncTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/commands/McTopCommandAsyncTask.java @@ -4,24 +4,26 @@ import com.gmail.nossr50.datatypes.database.PlayerStat; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.CancellableRunnable; +import java.util.List; import org.apache.commons.lang3.Validate; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.util.List; - public class McTopCommandAsyncTask extends CancellableRunnable { private final CommandSender sender; private final PrimarySkillType skill; private final int page; private final boolean useBoard, useChat; - public McTopCommandAsyncTask(int page, PrimarySkillType skill, CommandSender sender, boolean useBoard, boolean useChat) { - Validate.isTrue(useBoard || useChat, "Attempted to start a rank retrieval with both board and chat off"); + public McTopCommandAsyncTask(int page, PrimarySkillType skill, CommandSender sender, + boolean useBoard, boolean useChat) { + Validate.isTrue(useBoard || useChat, + "Attempted to start a rank retrieval with both board and chat off"); Validate.notNull(sender, "Attempted to start a rank retrieval with no recipient"); if (useBoard) { - Validate.isTrue(sender instanceof Player, "Attempted to start a rank retrieval displaying scoreboard to a non-player"); + Validate.isTrue(sender instanceof Player, + "Attempted to start a rank retrieval displaying scoreboard to a non-player"); } this.page = page; @@ -33,8 +35,10 @@ public class McTopCommandAsyncTask extends CancellableRunnable { @Override public void run() { - final List userStats = mcMMO.getDatabaseManager().readLeaderboard(skill, page, 10); + final List userStats = mcMMO.getDatabaseManager() + .readLeaderboard(skill, page, 10); - mcMMO.p.getFoliaLib().getScheduler().runNextTick(new MctopCommandDisplayTask(userStats, page, skill, sender, useBoard, useChat)); + mcMMO.p.getFoliaLib().getScheduler().runNextTick( + new MctopCommandDisplayTask(userStats, page, skill, sender, useBoard, useChat)); } } 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 e2e491611..8746b1b75 100644 --- a/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java @@ -7,12 +7,11 @@ import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.CancellableRunnable; import com.gmail.nossr50.util.MetadataConstants; import com.gmail.nossr50.util.scoreboards.ScoreboardManager; +import java.util.List; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.util.List; - /** * Display the results of {@link McTopCommandAsyncTask} to the sender. */ @@ -23,7 +22,8 @@ public class MctopCommandDisplayTask extends CancellableRunnable { private final int page; private final boolean useBoard, useChat; - MctopCommandDisplayTask(List userStats, int page, PrimarySkillType skill, CommandSender sender, boolean useBoard, boolean useChat) { + MctopCommandDisplayTask(List userStats, int page, PrimarySkillType skill, + CommandSender sender, boolean useBoard, boolean useChat) { this.userStats = userStats; this.page = page; this.skill = skill; @@ -43,10 +43,12 @@ public class MctopCommandDisplayTask extends CancellableRunnable { } if (sender instanceof Player) { - ((Player) sender).removeMetadata(MetadataConstants.METADATA_KEY_DATABASE_COMMAND, mcMMO.p); + ((Player) sender).removeMetadata(MetadataConstants.METADATA_KEY_DATABASE_COMMAND, + mcMMO.p); } - if (sender instanceof Player) + if (sender instanceof Player) { sender.sendMessage(LocaleLoader.getString("Commands.mctop.Tip")); + } } private void displayChat() { @@ -55,13 +57,17 @@ public class MctopCommandDisplayTask extends CancellableRunnable { if (sender instanceof Player) { sender.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Leaderboard")); } else { - sender.sendMessage(ChatColor.stripColor(LocaleLoader.getString("Commands.PowerLevel.Leaderboard"))); + sender.sendMessage(ChatColor.stripColor( + LocaleLoader.getString("Commands.PowerLevel.Leaderboard"))); } } else { if (sender instanceof Player) { - sender.sendMessage(LocaleLoader.getString("Commands.Skill.Leaderboard", mcMMO.p.getSkillTools().getLocalizedSkillName(skill))); + sender.sendMessage(LocaleLoader.getString("Commands.Skill.Leaderboard", + mcMMO.p.getSkillTools().getLocalizedSkillName(skill))); } else { - sender.sendMessage(ChatColor.stripColor(LocaleLoader.getString("Commands.Skill.Leaderboard", mcMMO.p.getSkillTools().getLocalizedSkillName(skill)))); + sender.sendMessage(ChatColor.stripColor( + LocaleLoader.getString("Commands.Skill.Leaderboard", + mcMMO.p.getSkillTools().getLocalizedSkillName(skill)))); } } @@ -72,11 +78,13 @@ public class MctopCommandDisplayTask extends CancellableRunnable { // 01. Playername - skill value // 12. Playername - skill value if (sender instanceof Player) { - sender.sendMessage(String.format("%2d. %s%s - %s%s", place, ChatColor.GREEN, stat.name, ChatColor.WHITE, stat.statVal)); + sender.sendMessage( + String.format("%2d. %s%s - %s%s", place, ChatColor.GREEN, stat.name, + ChatColor.WHITE, stat.statVal)); } else { sender.sendMessage(String.format("%2d. %s - %s", place, stat.name, stat.statVal)); } - + place++; } } diff --git a/src/main/java/com/gmail/nossr50/runnables/database/DatabaseConversionTask.java b/src/main/java/com/gmail/nossr50/runnables/database/DatabaseConversionTask.java index 1cf7260bd..8d2e1cb4b 100644 --- a/src/main/java/com/gmail/nossr50/runnables/database/DatabaseConversionTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/database/DatabaseConversionTask.java @@ -11,7 +11,8 @@ public class DatabaseConversionTask extends CancellableRunnable { private final CommandSender sender; private final String message; - public DatabaseConversionTask(DatabaseManager sourceDatabase, CommandSender sender, String oldType, String newType) { + public DatabaseConversionTask(DatabaseManager sourceDatabase, CommandSender sender, + String oldType, String newType) { this.sourceDatabase = sourceDatabase; this.sender = sender; message = LocaleLoader.getString("Commands.mcconvert.Database.Finish", oldType, newType); 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 71ea24ea1..25a3013a2 100644 --- a/src/main/java/com/gmail/nossr50/runnables/database/FormulaConversionTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/database/FormulaConversionTask.java @@ -29,11 +29,11 @@ public class FormulaConversionTask extends CancellableRunnable { int convertedUsers = 0; long startMillis = System.currentTimeMillis(); for (String playerName : mcMMO.getDatabaseManager().getStoredUsers()) { - McMMOPlayer mcMMOPlayer = UserManager.getOfflinePlayer(playerName); + final McMMOPlayer mmoPlayer = UserManager.getOfflinePlayer(playerName); PlayerProfile profile; - // If the mcMMOPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process. - if (mcMMOPlayer == null) { + // If the mmoPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process. + if (mmoPlayer == null) { profile = mcMMO.getDatabaseManager().loadPlayerProfile(playerName); if (!profile.isLoaded()) { @@ -45,7 +45,7 @@ public class FormulaConversionTask extends CancellableRunnable { // Since this is a temporary profile, we save it here. profile.scheduleAsyncSave(); } else { - profile = mcMMOPlayer.getProfile(); + profile = mmoPlayer.getProfile(); editValues(profile); } convertedUsers++; @@ -53,22 +53,29 @@ public class FormulaConversionTask extends CancellableRunnable { } mcMMO.getFormulaManager().setPreviousFormulaType(formulaType); - sender.sendMessage(LocaleLoader.getString("Commands.mcconvert.Experience.Finish", formulaType.toString())); + sender.sendMessage(LocaleLoader.getString("Commands.mcconvert.Experience.Finish", + formulaType.toString())); } private void editValues(PlayerProfile profile) { - LogUtils.debug(mcMMO.p.getLogger(), "========================================================================"); - LogUtils.debug(mcMMO.p.getLogger(), "Conversion report for " + profile.getPlayerName() + ":"); + LogUtils.debug(mcMMO.p.getLogger(), + "========================================================================"); + LogUtils.debug(mcMMO.p.getLogger(), + "Conversion report for " + profile.getPlayerName() + ":"); for (PrimarySkillType primarySkillType : SkillTools.NON_CHILD_SKILLS) { int oldLevel = profile.getSkillLevel(primarySkillType); int oldXPLevel = profile.getSkillXpLevel(primarySkillType); - int totalOldXP = mcMMO.getFormulaManager().calculateTotalExperience(oldLevel, oldXPLevel); + int totalOldXP = mcMMO.getFormulaManager() + .calculateTotalExperience(oldLevel, oldXPLevel); if (totalOldXP == 0) { continue; } - int[] newExperienceValues = mcMMO.getFormulaManager().calculateNewLevel(primarySkillType, (int) Math.floor(totalOldXP / ExperienceConfig.getInstance().getExpModifier()), formulaType); + int[] newExperienceValues = mcMMO.getFormulaManager() + .calculateNewLevel(primarySkillType, (int) Math.floor( + totalOldXP / ExperienceConfig.getInstance().getExpModifier()), + formulaType); int newLevel = newExperienceValues[0]; int newXPlevel = newExperienceValues[1]; @@ -82,7 +89,8 @@ public class FormulaConversionTask extends CancellableRunnable { LogUtils.debug(mcMMO.p.getLogger(), " NEW:"); LogUtils.debug(mcMMO.p.getLogger(), " Level " + newLevel); LogUtils.debug(mcMMO.p.getLogger(), " XP " + newXPlevel); - LogUtils.debug(mcMMO.p.getLogger(), "------------------------------------------------------------------------"); + LogUtils.debug(mcMMO.p.getLogger(), + "------------------------------------------------------------------------"); profile.modifySkill(primarySkillType, newLevel); profile.setSkillXpLevel(primarySkillType, newXPlevel); diff --git a/src/main/java/com/gmail/nossr50/runnables/database/UUIDUpdateAsyncTask.java b/src/main/java/com/gmail/nossr50/runnables/database/UUIDUpdateAsyncTask.java index 5ef42602d..7075eb722 100644 --- a/src/main/java/com/gmail/nossr50/runnables/database/UUIDUpdateAsyncTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/database/UUIDUpdateAsyncTask.java @@ -7,7 +7,6 @@ import com.gmail.nossr50.util.Misc; import com.google.common.collect.ImmutableList; import com.google.gson.Gson; import com.google.gson.JsonObject; - import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -44,10 +43,13 @@ public class UUIDUpdateAsyncTask extends CancellableRunnable { @Override public void run() { // First iteration - if (position == 0) - plugin.getLogger().info("Starting to check and update UUIDs, total amount of users: " + userNames.size()); + if (position == 0) { + plugin.getLogger().info("Starting to check and update UUIDs, total amount of users: " + + userNames.size()); + } - List batch = userNames.subList(position, Math.min(userNames.size(), position + BATCH_SIZE)); + List batch = userNames.subList(position, + Math.min(userNames.size(), position + BATCH_SIZE)); Map fetchedUUIDs = new HashMap<>(); HttpURLConnection connection; @@ -71,16 +73,18 @@ public class UUIDUpdateAsyncTask extends CancellableRunnable { case HttpURLConnection.HTTP_BAD_REQUEST: case HttpURLConnection.HTTP_FORBIDDEN: // Rejected, probably rate limit, just wait it out - this.runTaskLaterAsynchronously(plugin, Misc.TICK_CONVERSION_FACTOR * HARD_LIMIT_PERIOD); + this.runTaskLaterAsynchronously(plugin, + Misc.TICK_CONVERSION_FACTOR * HARD_LIMIT_PERIOD); return; default: // Unknown failure - this.runTaskLaterAsynchronously(plugin, Misc.TICK_CONVERSION_FACTOR * RETRY_PERIOD); + this.runTaskLaterAsynchronously(plugin, + Misc.TICK_CONVERSION_FACTOR * RETRY_PERIOD); return; } try (InputStream input = connection.getInputStream(); - InputStreamReader reader = new InputStreamReader(input)) { + InputStreamReader reader = new InputStreamReader(input)) { for (JsonObject jsonProfile : GSON.fromJson(reader, JsonObject[].class)) { UUID id = toUUID(jsonProfile.get("id").getAsString()); String name = jsonProfile.get("name").getAsString(); @@ -94,18 +98,22 @@ public class UUIDUpdateAsyncTask extends CancellableRunnable { return; } - if (fetchedUUIDs.size() != 0) + if (fetchedUUIDs.size() != 0) { mcMMO.getDatabaseManager().saveUserUUIDs(fetchedUUIDs); + } position += batch.size(); - plugin.getLogger().info(String.format("Conversion progress: %d/%d users", position, userNames.size())); + plugin.getLogger().info(String.format("Conversion progress: %d/%d users", position, + userNames.size())); - if (position +1 >= userNames.size()) { + if (position + 1 >= userNames.size()) { mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.ADD_UUIDS); awaiter.countDown(); plugin.getLogger().info("UUID checks completed"); - } else - this.runTaskLaterAsynchronously(plugin, Misc.TICK_CONVERSION_FACTOR * DELAY_PERIOD); // Schedule next batch + } else { + this.runTaskLaterAsynchronously(plugin, + Misc.TICK_CONVERSION_FACTOR * DELAY_PERIOD); // Schedule next batch + } } // Bukkit runnables don't let themselves reschedule themselves, so we are a pseudo bukkit runnable. @@ -118,7 +126,9 @@ public class UUIDUpdateAsyncTask extends CancellableRunnable { } private static UUID toUUID(String id) { - return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + id.substring(20, 32)); + return UUID.fromString( + id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + + id.substring(16, 20) + "-" + id.substring(20, 32)); } public void waitUntilFinished() { 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 ab2b4cbea..64bcbf8be 100644 --- a/src/main/java/com/gmail/nossr50/runnables/database/UserPurgeTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/database/UserPurgeTask.java @@ -2,11 +2,11 @@ package com.gmail.nossr50.runnables.database; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.CancellableRunnable; - import java.util.concurrent.locks.ReentrantLock; public class UserPurgeTask extends CancellableRunnable { private final ReentrantLock lock = new ReentrantLock(); + @Override public void run() { lock.lock(); diff --git a/src/main/java/com/gmail/nossr50/runnables/items/ChimaeraWingWarmup.java b/src/main/java/com/gmail/nossr50/runnables/items/ChimaeraWingWarmup.java index 1e4eed90d..abe3b338e 100644 --- a/src/main/java/com/gmail/nossr50/runnables/items/ChimaeraWingWarmup.java +++ b/src/main/java/com/gmail/nossr50/runnables/items/ChimaeraWingWarmup.java @@ -1,5 +1,7 @@ package com.gmail.nossr50.runnables.items; +import static com.gmail.nossr50.util.ChimaeraWing.expendChimaeraWing; + import com.gmail.nossr50.datatypes.interactions.NotificationType; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.locale.LocaleLoader; @@ -17,8 +19,6 @@ import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; -import static com.gmail.nossr50.util.ChimaeraWing.expendChimaeraWing; - public class ChimaeraWingWarmup extends CancellableRunnable { private final McMMOPlayer mmoPlayer; private final Location location; @@ -46,8 +46,10 @@ public class ChimaeraWingWarmup extends CancellableRunnable { final ItemStack inHand = player.getInventory().getItemInMainHand(); - if (!ItemUtils.isChimaeraWing(inHand) || inHand.getAmount() < mcMMO.p.getGeneralConfig().getChimaeraUseCost()) { - player.sendMessage(LocaleLoader.getString("Skills.NeedMore", LocaleLoader.getString("Item.ChimaeraWing.Name"))); + if (!ItemUtils.isChimaeraWing(inHand) || inHand.getAmount() < mcMMO.p.getGeneralConfig() + .getChimaeraUseCost()) { + player.sendMessage(LocaleLoader.getString("Skills.NeedMore", + LocaleLoader.getString("Item.ChimaeraWing.Name"))); return; } @@ -55,7 +57,8 @@ public class ChimaeraWingWarmup extends CancellableRunnable { int hurtCooldown = mcMMO.p.getGeneralConfig().getChimaeraRecentlyHurtCooldown(); if (hurtCooldown > 0) { - int timeRemaining = SkillUtils.calculateTimeLeft(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, hurtCooldown, player); + int timeRemaining = SkillUtils.calculateTimeLeft( + recentlyHurt * Misc.TIME_CONVERSION_FACTOR, hurtCooldown, player); if (timeRemaining > 0) { player.sendMessage(LocaleLoader.getString("Item.Injured.Wait", timeRemaining)); @@ -69,8 +72,10 @@ public class ChimaeraWingWarmup extends CancellableRunnable { private void chimaeraExecuteTeleport() { final Player player = mmoPlayer.getPlayer(); - if (mcMMO.p.getGeneralConfig().getChimaeraUseBedSpawn() && player.getBedSpawnLocation() != null) { - mcMMO.p.getFoliaLib().getScheduler().teleportAsync(player, player.getBedSpawnLocation()); + if (mcMMO.p.getGeneralConfig().getChimaeraUseBedSpawn() + && player.getBedSpawnLocation() != null) { + mcMMO.p.getFoliaLib().getScheduler() + .teleportAsync(player, player.getBedSpawnLocation()); } else { final Location spawnLocation = player.getWorld().getSpawnLocation(); if (spawnLocation.getBlock().getType() == Material.AIR) { @@ -81,7 +86,8 @@ public class ChimaeraWingWarmup extends CancellableRunnable { } } - expendChimaeraWing(player, mcMMO.p.getGeneralConfig().getChimaeraUseCost(), player.getInventory().getItemInMainHand()); + expendChimaeraWing(player, mcMMO.p.getGeneralConfig().getChimaeraUseCost(), + player.getInventory().getItemInMainHand()); mmoPlayer.actualizeChimeraWingLastUse(); mmoPlayer.setTeleportCommenceLocation(null); @@ -89,6 +95,7 @@ public class ChimaeraWingWarmup extends CancellableRunnable { SoundManager.sendSound(player, location, SoundType.CHIMAERA_WING); } - NotificationManager.sendPlayerInformation(player, NotificationType.ITEM_MESSAGE, "Item.ChimaeraWing.Pass"); + NotificationManager.sendPlayerInformation(player, NotificationType.ITEM_MESSAGE, + "Item.ChimaeraWing.Pass"); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/items/TeleportationWarmup.java b/src/main/java/com/gmail/nossr50/runnables/items/TeleportationWarmup.java index 362731101..f3f5d38c6 100644 --- a/src/main/java/com/gmail/nossr50/runnables/items/TeleportationWarmup.java +++ b/src/main/java/com/gmail/nossr50/runnables/items/TeleportationWarmup.java @@ -13,26 +13,27 @@ import org.bukkit.World; import org.bukkit.entity.Player; public class TeleportationWarmup extends CancellableRunnable { - private final McMMOPlayer mcMMOPlayer; + private final McMMOPlayer mmoPlayer; private final McMMOPlayer mcMMOTarget; - public TeleportationWarmup(McMMOPlayer mcMMOPlayer, McMMOPlayer mcMMOTarget) { - this.mcMMOPlayer = mcMMOPlayer; + public TeleportationWarmup(McMMOPlayer mmoPlayer, McMMOPlayer mcMMOTarget) { + this.mmoPlayer = mmoPlayer; this.mcMMOTarget = mcMMOTarget; } @Override public void run() { - Player teleportingPlayer = mcMMOPlayer.getPlayer(); + Player teleportingPlayer = mmoPlayer.getPlayer(); Player targetPlayer = mcMMOTarget.getPlayer(); - Location previousLocation = mcMMOPlayer.getTeleportCommenceLocation(); - Location newLocation = mcMMOPlayer.getPlayer().getLocation(); - long recentlyHurt = mcMMOPlayer.getRecentlyHurt(); + Location previousLocation = mmoPlayer.getTeleportCommenceLocation(); + Location newLocation = mmoPlayer.getPlayer().getLocation(); + long recentlyHurt = mmoPlayer.getRecentlyHurt(); - mcMMOPlayer.setTeleportCommenceLocation(null); + mmoPlayer.setTeleportCommenceLocation(null); if (!mcMMO.p.getPartyManager().inSameParty(teleportingPlayer, targetPlayer)) { - teleportingPlayer.sendMessage(LocaleLoader.getString("Party.NotInYourParty", targetPlayer.getName())); + teleportingPlayer.sendMessage( + LocaleLoader.getString("Party.NotInYourParty", targetPlayer.getName())); return; } @@ -44,10 +45,12 @@ public class TeleportationWarmup extends CancellableRunnable { int hurtCooldown = mcMMO.p.getGeneralConfig().getPTPCommandRecentlyHurtCooldown(); if (hurtCooldown > 0) { - int timeRemaining = SkillUtils.calculateTimeLeft(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, hurtCooldown, teleportingPlayer); + int timeRemaining = SkillUtils.calculateTimeLeft( + recentlyHurt * Misc.TIME_CONVERSION_FACTOR, hurtCooldown, teleportingPlayer); if (timeRemaining > 0) { - teleportingPlayer.sendMessage(LocaleLoader.getString("Item.Injured.Wait", timeRemaining)); + teleportingPlayer.sendMessage( + LocaleLoader.getString("Item.Injured.Wait", timeRemaining)); return; } } @@ -58,16 +61,20 @@ public class TeleportationWarmup extends CancellableRunnable { if (!Permissions.partyTeleportAllWorlds(teleportingPlayer)) { if (!Permissions.partyTeleportWorld(targetPlayer, targetWorld)) { - teleportingPlayer.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", targetWorld.getName())); + teleportingPlayer.sendMessage( + LocaleLoader.getString("Commands.ptp.NoWorldPermissions", + targetWorld.getName())); return; - } else if (targetWorld != playerWorld && !Permissions.partyTeleportWorld(teleportingPlayer, targetWorld)) { - teleportingPlayer.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", targetWorld.getName())); + } else if (targetWorld != playerWorld && !Permissions.partyTeleportWorld( + teleportingPlayer, targetWorld)) { + teleportingPlayer.sendMessage( + LocaleLoader.getString("Commands.ptp.NoWorldPermissions", + targetWorld.getName())); return; } } } - EventUtils.handlePartyTeleportEvent(teleportingPlayer, targetPlayer); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/party/PartyAutoKickTask.java b/src/main/java/com/gmail/nossr50/runnables/party/PartyAutoKickTask.java index 1d662dba9..133ef88b8 100644 --- a/src/main/java/com/gmail/nossr50/runnables/party/PartyAutoKickTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/party/PartyAutoKickTask.java @@ -3,16 +3,16 @@ package com.gmail.nossr50.runnables.party; import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.CancellableRunnable; -import org.bukkit.OfflinePlayer; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import java.util.UUID; +import org.bukkit.OfflinePlayer; public class PartyAutoKickTask extends CancellableRunnable { - private final static long KICK_TIME = 24L * 60L * 60L * 1000L * mcMMO.p.getGeneralConfig().getAutoPartyKickTime(); + private final static long KICK_TIME = + 24L * 60L * 60L * 1000L * mcMMO.p.getGeneralConfig().getAutoPartyKickTime(); @Override public void run() { @@ -26,7 +26,8 @@ public class PartyAutoKickTask extends CancellableRunnable { OfflinePlayer member = mcMMO.p.getServer().getOfflinePlayer(memberUniqueId); boolean isProcessed = processedPlayers.contains(memberUniqueId); - if ((!member.isOnline() && (currentTime - member.getLastPlayed() > KICK_TIME)) || isProcessed) { + if ((!member.isOnline() && (currentTime - member.getLastPlayed() > KICK_TIME)) + || isProcessed) { toRemove.put(member, party); } diff --git a/src/main/java/com/gmail/nossr50/runnables/player/ClearRegisteredXPGainTask.java b/src/main/java/com/gmail/nossr50/runnables/player/ClearRegisteredXPGainTask.java index 47923c7a4..f4ba32d16 100644 --- a/src/main/java/com/gmail/nossr50/runnables/player/ClearRegisteredXPGainTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/player/ClearRegisteredXPGainTask.java @@ -7,8 +7,8 @@ import com.gmail.nossr50.util.player.UserManager; public class ClearRegisteredXPGainTask extends CancellableRunnable { @Override public void run() { - for (McMMOPlayer mcMMOPlayer : UserManager.getPlayers()) { - mcMMOPlayer.getProfile().purgeExpiredXpGains(); + for (McMMOPlayer mmoPlayer : UserManager.getPlayers()) { + mmoPlayer.getProfile().purgeExpiredXpGains(); } } } 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 d170ec686..3417e14f5 100644 --- a/src/main/java/com/gmail/nossr50/runnables/player/PlayerProfileLoadingTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/player/PlayerProfileLoadingTask.java @@ -38,21 +38,25 @@ public class PlayerProfileLoadingTask extends CancellableRunnable { // Quit if they logged out if (!player.isOnline()) { - LogUtils.debug(mcMMO.p.getLogger(), "Aborting profile loading recovery for " + player.getName() + " - player logged out"); + LogUtils.debug(mcMMO.p.getLogger(), + "Aborting profile loading recovery for " + player.getName() + + " - player logged out"); return; } PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(player); if (!profile.isLoaded()) { - LogUtils.debug(mcMMO.p.getLogger(), "Creating new data for player: "+player.getName()); + LogUtils.debug(mcMMO.p.getLogger(), + "Creating new data for player: " + player.getName()); //Profile isn't loaded so add as new user profile = mcMMO.getDatabaseManager().newUser(player); } // If successful, schedule the apply if (profile.isLoaded()) { - mcMMO.p.getFoliaLib().getScheduler().runAtEntity(player, new ApplySuccessfulProfile(new McMMOPlayer(player, profile))); + mcMMO.p.getFoliaLib().getScheduler().runAtEntity(player, + new ApplySuccessfulProfile(new McMMOPlayer(player, profile))); EventUtils.callPlayerProfileLoadEvent(player, profile); return; } @@ -64,23 +68,29 @@ public class PlayerProfileLoadingTask extends CancellableRunnable { player.getName(), String.valueOf(attempt))); //Notify the admins - mcMMO.p.getServer().broadcast(LocaleLoader.getString("Profile.Loading.FailureNotice", player.getName()), Server.BROADCAST_CHANNEL_ADMINISTRATIVE); + mcMMO.p.getServer().broadcast( + LocaleLoader.getString("Profile.Loading.FailureNotice", player.getName()), + Server.BROADCAST_CHANNEL_ADMINISTRATIVE); //Notify the player - player.sendMessage(LocaleLoader.getString("Profile.Loading.FailurePlayer", String.valueOf(attempt)).split("\n")); + player.sendMessage( + LocaleLoader.getString("Profile.Loading.FailurePlayer", String.valueOf(attempt)) + .split("\n")); } // Increment attempt counter and try attempt++; - mcMMO.p.getFoliaLib().getScheduler().runLaterAsync(new PlayerProfileLoadingTask(player, attempt), (100 + (attempt * 100L))); + mcMMO.p.getFoliaLib().getScheduler() + .runLaterAsync(new PlayerProfileLoadingTask(player, attempt), + (100 + (attempt * 100L))); } private class ApplySuccessfulProfile extends CancellableRunnable { - private final McMMOPlayer mcMMOPlayer; + private final McMMOPlayer mmoPlayer; - private ApplySuccessfulProfile(McMMOPlayer mcMMOPlayer) { - this.mcMMOPlayer = mcMMOPlayer; + private ApplySuccessfulProfile(McMMOPlayer mmoPlayer) { + this.mmoPlayer = mmoPlayer; } // Synchronized task @@ -88,22 +98,25 @@ public class PlayerProfileLoadingTask extends CancellableRunnable { @Override public void run() { if (!player.isOnline()) { - mcMMO.p.getLogger().info("Aborting profile loading recovery for " + player.getName() + " - player logged out"); + mcMMO.p.getLogger().info("Aborting profile loading recovery for " + player.getName() + + " - player logged out"); return; } - mcMMOPlayer.getProfile().updateLastLogin(); + mmoPlayer.getProfile().updateLastLogin(); - mcMMOPlayer.setupPartyData(); - UserManager.track(mcMMOPlayer); - mcMMOPlayer.actualizeRespawnATS(); + mmoPlayer.setupPartyData(); + UserManager.track(mmoPlayer); + mmoPlayer.actualizeRespawnATS(); if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) { ScoreboardManager.setupPlayer(player); if (mcMMO.p.getGeneralConfig().getShowStatsAfterLogin()) { ScoreboardManager.enablePlayerStatsScoreboard(player); - mcMMO.p.getFoliaLib().getScheduler().runAtEntityLater(player, new McScoreboardKeepTask(player), Misc.TICK_CONVERSION_FACTOR); + mcMMO.p.getFoliaLib().getScheduler() + .runAtEntityLater(player, new McScoreboardKeepTask(player), + Misc.TICK_CONVERSION_FACTOR); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/AbilityCooldownTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/AbilityCooldownTask.java index 9c7d8bfd8..98779d6bf 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/AbilityCooldownTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/AbilityCooldownTask.java @@ -7,21 +7,22 @@ import com.gmail.nossr50.util.CancellableRunnable; import com.gmail.nossr50.util.player.NotificationManager; public class AbilityCooldownTask extends CancellableRunnable { - private final McMMOPlayer mcMMOPlayer; + private final McMMOPlayer mmoPlayer; private final SuperAbilityType ability; - public AbilityCooldownTask(McMMOPlayer mcMMOPlayer, SuperAbilityType ability) { - this.mcMMOPlayer = mcMMOPlayer; + public AbilityCooldownTask(McMMOPlayer mmoPlayer, SuperAbilityType ability) { + this.mmoPlayer = mmoPlayer; this.ability = ability; } @Override public void run() { - if (!mcMMOPlayer.getPlayer().isOnline() || mcMMOPlayer.getAbilityInformed(ability)) { + if (!mmoPlayer.getPlayer().isOnline() || mmoPlayer.getAbilityInformed(ability)) { return; } - mcMMOPlayer.setAbilityInformed(ability, true); // TODO: ?? What does this do again? - NotificationManager.sendPlayerInformation(mcMMOPlayer.getPlayer(), NotificationType.ABILITY_REFRESHED, ability.getAbilityRefresh()); + mmoPlayer.setAbilityInformed(ability, true); // TODO: ?? What does this do again? + NotificationManager.sendPlayerInformation(mmoPlayer.getPlayer(), + NotificationType.ABILITY_REFRESHED, ability.getAbilityRefresh()); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/AbilityDisableTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/AbilityDisableTask.java index 8bcbdb01a..2d613f935 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/AbilityDisableTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/AbilityDisableTask.java @@ -15,21 +15,21 @@ import org.bukkit.World; import org.bukkit.entity.Player; public class AbilityDisableTask extends CancellableRunnable { - private final McMMOPlayer mcMMOPlayer; + private final McMMOPlayer mmoPlayer; private final SuperAbilityType ability; - public AbilityDisableTask(McMMOPlayer mcMMOPlayer, SuperAbilityType ability) { - this.mcMMOPlayer = mcMMOPlayer; + public AbilityDisableTask(McMMOPlayer mmoPlayer, SuperAbilityType ability) { + this.mmoPlayer = mmoPlayer; this.ability = ability; } @Override public void run() { - if (!mcMMOPlayer.getAbilityMode(ability)) { + if (!mmoPlayer.getAbilityMode(ability)) { return; } - Player player = mcMMOPlayer.getPlayer(); + Player player = mmoPlayer.getPlayer(); switch (ability) { case SUPER_BREAKER: @@ -49,21 +49,26 @@ public class AbilityDisableTask extends CancellableRunnable { EventUtils.callAbilityDeactivateEvent(player, ability); - mcMMOPlayer.setAbilityMode(ability, false); - mcMMOPlayer.setAbilityInformed(ability, false); + mmoPlayer.setAbilityMode(ability, false); + mmoPlayer.setAbilityInformed(ability, false); // ParticleEffectUtils.playAbilityDisabledEffect(player); - if (mcMMOPlayer.useChatNotifications()) { + if (mmoPlayer.useChatNotifications()) { //player.sendMessage(ability.getAbilityOff()); - NotificationManager.sendPlayerInformation(player, NotificationType.ABILITY_OFF, ability.getAbilityOff()); + NotificationManager.sendPlayerInformation(player, NotificationType.ABILITY_OFF, + ability.getAbilityOff()); } if (mcMMO.p.getAdvancedConfig().sendAbilityNotificationToOtherPlayers()) { - SkillUtils.sendSkillMessage(player, NotificationType.SUPER_ABILITY_ALERT_OTHERS, ability.getAbilityPlayerOff()); + SkillUtils.sendSkillMessage(player, NotificationType.SUPER_ABILITY_ALERT_OTHERS, + ability.getAbilityPlayerOff()); } if (!mcMMO.isServerShutdownExecuted()) { - mcMMO.p.getFoliaLib().getScheduler().runAtEntityLater(player, new AbilityCooldownTask(mcMMOPlayer, ability), (long) PerksUtils.handleCooldownPerks(player, ability.getCooldown()) * Misc.TICK_CONVERSION_FACTOR); + mcMMO.p.getFoliaLib().getScheduler() + .runAtEntityLater(player, new AbilityCooldownTask(mmoPlayer, ability), + (long) PerksUtils.handleCooldownPerks(player, ability.getCooldown()) + * Misc.TICK_CONVERSION_FACTOR); } } 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 640b498e8..630d05bce 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java @@ -1,10 +1,13 @@ package com.gmail.nossr50.runnables.skills; +import static com.gmail.nossr50.skills.alchemy.AlchemyPotionBrewer.isValidBrew; + import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.skills.alchemy.Alchemy; import com.gmail.nossr50.util.CancellableRunnable; import com.gmail.nossr50.util.ContainerMetadataUtils; import com.gmail.nossr50.util.player.UserManager; +import java.util.Arrays; import org.bukkit.Location; import org.bukkit.OfflinePlayer; import org.bukkit.block.BrewingStand; @@ -13,10 +16,6 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Arrays; - -import static com.gmail.nossr50.skills.alchemy.AlchemyPotionBrewer.isValidBrew; - public class AlchemyBrewCheckTask extends CancellableRunnable { private final BrewingStand brewingStand; private final ItemStack[] oldInventory; @@ -42,13 +41,16 @@ public class AlchemyBrewCheckTask extends CancellableRunnable { } } final Location location = brewingStand.getLocation(); - final ItemStack[] newInventory = Arrays.copyOfRange(brewingStand.getInventory().getContents(), 0, 4); - boolean validBrew = brewingStand.getFuelLevel() > 0 && isValidBrew(ingredientLevel, newInventory); + final ItemStack[] newInventory = Arrays.copyOfRange( + brewingStand.getInventory().getContents(), 0, 4); + boolean validBrew = + brewingStand.getFuelLevel() > 0 && isValidBrew(ingredientLevel, newInventory); if (Alchemy.brewingStandMap.containsKey(location)) { if (oldInventory[Alchemy.INGREDIENT_SLOT] == null || newInventory[Alchemy.INGREDIENT_SLOT] == null - || !oldInventory[Alchemy.INGREDIENT_SLOT].isSimilar(newInventory[Alchemy.INGREDIENT_SLOT]) + || !oldInventory[Alchemy.INGREDIENT_SLOT].isSimilar( + newInventory[Alchemy.INGREDIENT_SLOT]) || !validBrew) { Alchemy.brewingStandMap.get(location).cancelBrew(); } 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 1187aa08f..2bc6a073f 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewTask.java @@ -22,7 +22,7 @@ import org.jetbrains.annotations.NotNull; public class AlchemyBrewTask extends CancellableRunnable { private static final double DEFAULT_BREW_SPEED = 1.0; - private static final int DEFAULT_BREW_TICKS = 400; + private static final int DEFAULT_BREW_TICKS = 400; private final BlockState brewingStand; private final OfflinePlayer offlinePlayer; @@ -52,11 +52,13 @@ public class AlchemyBrewTask extends CancellableRunnable { if (mmoPlayer != null && !Misc.isNPCEntityExcludingVillagers(mmoPlayer.getPlayer()) - && Permissions.isSubSkillEnabled(mmoPlayer.getPlayer(), SubSkillType.ALCHEMY_CATALYSIS)) { + && Permissions.isSubSkillEnabled(mmoPlayer.getPlayer(), + SubSkillType.ALCHEMY_CATALYSIS)) { ingredientLevel = mmoPlayer.getAlchemyManager().getTier(); - double catalysis = mmoPlayer.getAlchemyManager().calculateBrewSpeed(Permissions.lucky(mmoPlayer.getPlayer(), - PrimarySkillType.ALCHEMY)); + double catalysis = mmoPlayer.getAlchemyManager() + .calculateBrewSpeed(Permissions.lucky(mmoPlayer.getPlayer(), + PrimarySkillType.ALCHEMY)); McMMOPlayerCatalysisEvent event = new McMMOPlayerCatalysisEvent(mmoPlayer, catalysis); mcMMO.p.getServer().getPluginManager().callEvent(event); @@ -72,20 +74,22 @@ public class AlchemyBrewTask extends CancellableRunnable { fuel = ((BrewingStand) brewingStand).getFuelLevel(); - if (((BrewingStand) brewingStand).getBrewingTime() == -1) // Only decrement on our end if it isn't a vanilla ingredient. + if (((BrewingStand) brewingStand).getBrewingTime() + == -1) // Only decrement on our end if it isn't a vanilla ingredient. + { fuel--; + } Alchemy.brewingStandMap.put(brewingStand.getLocation(), this); - mcMMO.p.getFoliaLib().getScheduler().runAtLocationTimer(brewingStand.getLocation(), this, 1, 1); + mcMMO.p.getFoliaLib().getScheduler() + .runAtLocationTimer(brewingStand.getLocation(), this, 1, 1); } @Override public void run() { // Check if preconditions for brewing are not met if (shouldCancelBrewing()) { - if (Alchemy.brewingStandMap.containsKey(brewingStand.getLocation())) { - Alchemy.brewingStandMap.remove(brewingStand.getLocation()); - } + Alchemy.brewingStandMap.remove(brewingStand.getLocation()); this.cancel(); return; } @@ -116,7 +120,8 @@ public class AlchemyBrewTask extends CancellableRunnable { return true; } return !AlchemyPotionBrewer.isValidIngredientByLevel( - getIngredientLevelUpdated(), ((BrewingStand) brewingStand).getInventory().getContents()[Alchemy.INGREDIENT_SLOT]); + getIngredientLevelUpdated(), ((BrewingStand) brewingStand).getInventory() + .getContents()[Alchemy.INGREDIENT_SLOT]); } private int getIngredientLevelUpdated() { diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/AprilTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/AprilTask.java index 9b4aa61a4..079a86750 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/AprilTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/AprilTask.java @@ -25,7 +25,7 @@ // if (betterRandom == 0) { // SoundManager.sendSound(player, player.getLocation(), SoundType.LEVEL_UP); // player.sendMessage(unknown("superskill") + " skill increased by 1. Total (" + unknown("12") + ")"); -//// fireworksShow(player); +/// / fireworksShow(player); // } // // for (Statistic statistic : mcMMO.getHolidayManager().movementStatistics) { diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/AwardCombatXpTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/AwardCombatXpTask.java index c909659b7..8ea83dbf6 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/AwardCombatXpTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/AwardCombatXpTask.java @@ -10,15 +10,16 @@ import com.gmail.nossr50.util.CancellableRunnable; import org.bukkit.entity.LivingEntity; public class AwardCombatXpTask extends CancellableRunnable { - private final McMMOPlayer mcMMOPlayer; + private final McMMOPlayer mmoPlayer; private final double baseXp; private final PrimarySkillType primarySkillType; private final LivingEntity target; private final XPGainReason xpGainReason; private final double baseHealth; - public AwardCombatXpTask(McMMOPlayer mcMMOPlayer, PrimarySkillType primarySkillType, double baseXp, LivingEntity target, XPGainReason xpGainReason) { - this.mcMMOPlayer = mcMMOPlayer; + public AwardCombatXpTask(McMMOPlayer mmoPlayer, PrimarySkillType primarySkillType, + double baseXp, LivingEntity target, XPGainReason xpGainReason) { + this.mmoPlayer = mmoPlayer; this.primarySkillType = primarySkillType; this.baseXp = baseXp; this.target = target; @@ -46,6 +47,8 @@ public class AwardCombatXpTask extends CancellableRunnable { } final double finalDamage = damage; - mcMMO.p.getFoliaLib().getScheduler().runAtEntity(mcMMOPlayer.getPlayer(), task -> mcMMOPlayer.beginXpGain(primarySkillType, (int) (finalDamage * baseXp), xpGainReason, XPGainSource.SELF)); + mcMMO.p.getFoliaLib().getScheduler().runAtEntity(mmoPlayer.getPlayer(), + task -> mmoPlayer.beginXpGain(primarySkillType, (int) (finalDamage * baseXp), + xpGainReason, XPGainSource.SELF)); } } 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 3dd31ad93..4a49e14ae 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/BleedContainer.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/BleedContainer.java @@ -9,11 +9,12 @@ 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 f67fa1e86..a38560292 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/BleedTimerTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/BleedTimerTask.java @@ -37,8 +37,8 @@ // LivingEntity target = containerEntry.getKey(); // int toolTier = containerEntry.getValue().toolTier; // -//// String debugMessage = ""; -//// debugMessage += ChatColor.GOLD + "Target ["+target.getName()+"]: " + ChatColor.RESET; +/// / String debugMessage = ""; / debugMessage += ChatColor.GOLD + "Target +/// ["+target.getName()+"]: " + ChatColor.RESET; // //// debugMessage+="RemainingTicks=["+containerEntry.getValue().bleedTicks+"], "; // @@ -63,7 +63,7 @@ // if (containerEntry.getValue().toolTier >= 4 && containerEntry.getValue().bleedRank >= 3) // damage = damage * 1.5; // -// Player player = (Player) target; +// final Player player = (Player) target; // // if (!player.isOnline()) { // continue; diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/DelayedCropReplant.java b/src/main/java/com/gmail/nossr50/runnables/skills/DelayedCropReplant.java index f539cefbf..b04ad0578 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/DelayedCropReplant.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/DelayedCropReplant.java @@ -29,10 +29,12 @@ public class DelayedCropReplant extends CancellableRunnable { /** * Replants a crop after a delay setting the age to desiredCropAge + * * @param cropState target {@link BlockState} * @param desiredCropAge desired age of the crop */ - public DelayedCropReplant(BlockBreakEvent blockBreakEvent, BlockState cropState, int desiredCropAge, boolean wasImmaturePlant) { + public DelayedCropReplant(BlockBreakEvent blockBreakEvent, BlockState cropState, + int desiredCropAge, boolean wasImmaturePlant) { BlockData cropData = cropState.getBlockData(); if (cropData instanceof Directional cropDir) { @@ -54,19 +56,21 @@ public class DelayedCropReplant extends CancellableRunnable { PlantAnchorType plantAnchorType = PlantAnchorType.NORMAL; //Remove the metadata marking the block as recently replanted - mcMMO.p.getFoliaLib().getScheduler().runAtLocationLater(blockBreakEvent.getBlock().getLocation(), new markPlantAsOld(blockBreakEvent.getBlock().getLocation()), 10); + mcMMO.p.getFoliaLib().getScheduler() + .runAtLocationLater(blockBreakEvent.getBlock().getLocation(), + new markPlantAsOld(blockBreakEvent.getBlock().getLocation()), 10); if (blockBreakEvent.isCancelled()) { wasImmaturePlant = true; } //Two kinds of air in Minecraft - if (currentState.getType().equals(cropMaterial) || currentState.getType().equals(Material.AIR) || currentState.getType().equals(Material.CAVE_AIR)) { + if (currentState.getType().equals(cropMaterial) || currentState.getType() + .equals(Material.AIR) || currentState.getType().equals(Material.CAVE_AIR)) { // if (currentState.getBlock().getRelative(BlockFace.DOWN)) //The space is not currently occupied by a block so we can fill it cropBlock.setType(cropMaterial); - //Get new state (necessary?) BlockState newState = cropBlock.getState(); BlockData newData = newState.getBlockData(); @@ -96,12 +100,12 @@ public class DelayedCropReplant extends CancellableRunnable { ageable.setAge(age); newState.setBlockData(ageable); - newState.update(true, true); //Play an effect ParticleEffectUtils.playGreenThumbEffect(cropLocation); - mcMMO.p.getFoliaLib().getScheduler().runAtLocationLater(newState.getLocation(), new PhysicsBlockUpdate(newState.getBlock(), cropFace, plantAnchorType), 1); + mcMMO.p.getFoliaLib().getScheduler().runAtLocationLater(newState.getLocation(), + new PhysicsBlockUpdate(newState.getBlock(), cropFace, plantAnchorType), 1); } } @@ -115,7 +119,8 @@ public class DelayedCropReplant extends CancellableRunnable { private final PlantAnchorType plantAnchorType; private BlockFace plantFace; - private PhysicsBlockUpdate(@NotNull Block plantBlock, @Nullable BlockFace plantFace, @NotNull PlantAnchorType plantAnchorType) { + private PhysicsBlockUpdate(@NotNull Block plantBlock, @Nullable BlockFace plantFace, + @NotNull PlantAnchorType plantAnchorType) { this.plantBlock = plantBlock; this.plantAnchorType = plantAnchorType; @@ -159,7 +164,6 @@ public class DelayedCropReplant extends CancellableRunnable { } - private static class markPlantAsOld extends CancellableRunnable { private final Location cropLoc; @@ -171,8 +175,10 @@ public class DelayedCropReplant extends CancellableRunnable { @Override public void run() { Block cropBlock = cropLoc.getBlock(); - if (cropBlock.getMetadata(MetadataConstants.METADATA_KEY_REPLANT).size() > 0) - cropBlock.setMetadata(MetadataConstants.METADATA_KEY_REPLANT, new RecentlyReplantedCropMeta(mcMMO.p, false)); + if (cropBlock.getMetadata(MetadataConstants.METADATA_KEY_REPLANT).size() > 0) { + cropBlock.setMetadata(MetadataConstants.METADATA_KEY_REPLANT, + new RecentlyReplantedCropMeta(mcMMO.p, false)); + } } } diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/DelayedHerbalismXPCheckTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/DelayedHerbalismXPCheckTask.java index dcc583f02..f992b4439 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/DelayedHerbalismXPCheckTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/DelayedHerbalismXPCheckTask.java @@ -3,21 +3,21 @@ package com.gmail.nossr50.runnables.skills; import com.gmail.nossr50.datatypes.BlockSnapshot; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.util.CancellableRunnable; - import java.util.ArrayList; public class DelayedHerbalismXPCheckTask extends CancellableRunnable { - private final McMMOPlayer mcMMOPlayer; + private final McMMOPlayer mmoPlayer; private final ArrayList chorusBlocks; - public DelayedHerbalismXPCheckTask(McMMOPlayer mcMMOPlayer, ArrayList chorusBlocks) { - this.mcMMOPlayer = mcMMOPlayer; + public DelayedHerbalismXPCheckTask(McMMOPlayer mmoPlayer, + ArrayList chorusBlocks) { + this.mmoPlayer = mmoPlayer; this.chorusBlocks = chorusBlocks; } @Override public void run() { - mcMMOPlayer.getHerbalismManager().awardXPForBlockSnapshots(chorusBlocks); + mmoPlayer.getHerbalismManager().awardXPForBlockSnapshots(chorusBlocks); } } 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 e5da7e81b..035fbf02c 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/ExperienceBarHideTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/ExperienceBarHideTask.java @@ -6,31 +6,33 @@ import com.gmail.nossr50.util.CancellableRunnable; import com.gmail.nossr50.util.experience.ExperienceBarManager; public class ExperienceBarHideTask extends CancellableRunnable { - public final McMMOPlayer mcMMOPlayer; + public final McMMOPlayer mmoPlayer; public final PrimarySkillType primarySkillType; public final ExperienceBarManager experienceBarManagerRef; - public ExperienceBarHideTask(ExperienceBarManager experienceBarManagerRef, McMMOPlayer mcMMOPlayer, PrimarySkillType primarySkillType) { + public ExperienceBarHideTask(ExperienceBarManager experienceBarManagerRef, + McMMOPlayer mmoPlayer, PrimarySkillType primarySkillType) { this.experienceBarManagerRef = experienceBarManagerRef; - this.mcMMOPlayer = mcMMOPlayer; + this.mmoPlayer = mmoPlayer; this.primarySkillType = primarySkillType; } /** - * When an object implementing interface Runnable is used - * to create a thread, starting the thread causes the object's + * When an object implementing interface Runnable is used to create a thread, + * starting the thread causes the object's * run method to be called in that separately executing * thread. *

- * The general contract of the method run is that it may - * take any action whatsoever. + * The general contract of the method run is that it may take any action + * whatsoever. * * @see Thread#run() */ @Override public void run() { - if (experienceBarManagerRef == null || mcMMOPlayer == null) + if (experienceBarManagerRef == null || mmoPlayer == null) { return; + } experienceBarManagerRef.hideExperienceBar(primarySkillType); experienceBarManagerRef.clearTask(primarySkillType); diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/MasterAnglerTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/MasterAnglerTask.java index 39a6c01b4..81f64fbb3 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/MasterAnglerTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/MasterAnglerTask.java @@ -10,7 +10,8 @@ public class MasterAnglerTask extends CancellableRunnable { private final @NotNull FishingManager fishingManager; private final int lureLevel; - public MasterAnglerTask(@NotNull FishHook fishHook, @NotNull FishingManager fishingManager, int lureLevel) { + public MasterAnglerTask(@NotNull FishHook fishHook, @NotNull FishingManager fishingManager, + int lureLevel) { this.fishHook = fishHook; this.fishingManager = fishingManager; this.lureLevel = lureLevel; diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/RuptureTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/RuptureTask.java index 93db0250c..d9445c273 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/RuptureTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/RuptureTask.java @@ -1,5 +1,7 @@ package com.gmail.nossr50.runnables.skills; +import static com.gmail.nossr50.util.AttributeMapper.MAPPED_MAX_HEALTH; + import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.events.skills.rupture.McMMOEntityDamageByRuptureEvent; import com.gmail.nossr50.mcMMO; @@ -7,14 +9,11 @@ import com.gmail.nossr50.util.CancellableRunnable; import com.gmail.nossr50.util.MetadataConstants; import com.gmail.nossr50.util.MobHealthbarUtils; import com.gmail.nossr50.util.skills.ParticleEffectUtils; -import com.google.common.base.Objects; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import static com.gmail.nossr50.util.AttributeMapper.MAPPED_MAX_HEALTH; - public class RuptureTask extends CancellableRunnable { public static final int DAMAGE_TICK_INTERVAL = 10; @@ -40,10 +39,11 @@ public class RuptureTask extends CancellableRunnable { * @param pureTickDamage The amount of damage to be applied per tick. */ public RuptureTask(@NotNull McMMOPlayer ruptureSource, @NotNull LivingEntity targetEntity, - double pureTickDamage) { + double pureTickDamage) { this.ruptureSource = ruptureSource; this.targetEntity = targetEntity; - this.expireTick = mcMMO.p.getAdvancedConfig().getRuptureDurationSeconds(targetEntity instanceof Player) * 20; + this.expireTick = mcMMO.p.getAdvancedConfig() + .getRuptureDurationSeconds(targetEntity instanceof Player) * 20; this.totalTickCeiling = Math.min(this.expireTick, 200); this.ruptureTick = 0; this.damageTickTracker = 0; @@ -54,18 +54,17 @@ public class RuptureTask extends CancellableRunnable { /** * Deprecated constructor for the RuptureTask class. * - * @deprecated This constructor is deprecated and will be removed in future versions. - * Use {@link #RuptureTask(McMMOPlayer, LivingEntity, double)} instead. - * * @param ruptureSource The McMMOPlayer who is the source of the rupture. * @param targetEntity The LivingEntity that is the target of the rupture. * @param pureTickDamage The amount of damage to be applied per tick. * @param ignored This parameter is ignored and should not be used. * @since 2.2.023 + * @deprecated This constructor is deprecated and will be removed in future versions. Use + * {@link #RuptureTask(McMMOPlayer, LivingEntity, double)} instead. */ @Deprecated(forRemoval = true, since = "2.2.023") public RuptureTask(@NotNull McMMOPlayer ruptureSource, @NotNull LivingEntity targetEntity, - double pureTickDamage, double ignored) { + double pureTickDamage, double ignored) { this(ruptureSource, targetEntity, pureTickDamage); } @@ -90,7 +89,9 @@ public class RuptureTask extends CancellableRunnable { //Is it time to damage? if (damageTickTracker >= DAMAGE_TICK_INTERVAL) { damageTickTracker = 0; //Reset timer - if (applyRupture()) return; + if (applyRupture()) { + return; + } playAnimation(); } @@ -123,34 +124,42 @@ public class RuptureTask extends CancellableRunnable { if (healthBeforeRuptureIsApplied > 0.01) { //Send a fake damage event McMMOEntityDamageByRuptureEvent event = - new McMMOEntityDamageByRuptureEvent(ruptureSource, targetEntity, calculateAdjustedTickDamage()); + new McMMOEntityDamageByRuptureEvent(ruptureSource, targetEntity, + calculateAdjustedTickDamage()); mcMMO.p.getServer().getPluginManager().callEvent(event); //Ensure the event wasn't canceled and damage is still greater than 0 double damage = event.getDamage(); //Use raw damage for Rupture - if (event.isCancelled() || damage <= 0 || healthBeforeRuptureIsApplied - damage <= 0) + if (event.isCancelled() || damage <= 0 || healthBeforeRuptureIsApplied - damage <= 0) { return true; + } final double damagedHealth = healthBeforeRuptureIsApplied - damage; - final AttributeInstance maxHealthAttribute = targetEntity.getAttribute(MAPPED_MAX_HEALTH); + final AttributeInstance maxHealthAttribute = targetEntity.getAttribute( + MAPPED_MAX_HEALTH); if (maxHealthAttribute == null) { // Can't remove health if max health is null - mcMMO.p.getLogger().info("RuptureTask: Target entity has an illegal state for its health." + - " Cancelling Rupture. Target has null " + MAPPED_MAX_HEALTH + " attribute."); + mcMMO.p.getLogger() + .info("RuptureTask: Target entity has an illegal state for its health." + + " Cancelling Rupture. Target has null " + MAPPED_MAX_HEALTH + + " attribute."); return true; } if (damagedHealth > maxHealthAttribute.getValue()) { // Something went very wrong here, target has an illegal state for its health - mcMMO.p.getLogger().info("RuptureTask: Target entity has an illegal state for its health." + - " Cancelling Rupture. Target has " + targetEntity.getHealth() + " health," + - " but max health is " + maxHealthAttribute.getValue()); + mcMMO.p.getLogger() + .info("RuptureTask: Target entity has an illegal state for its health." + + " Cancelling Rupture. Target has " + targetEntity.getHealth() + + " health," + + " but max health is " + maxHealthAttribute.getValue()); return true; } - targetEntity.setHealth(damagedHealth); //Hurt entity without the unwanted side effects of damage()} + targetEntity.setHealth( + damagedHealth); //Hurt entity without the unwanted side effects of damage()} MobHealthbarUtils.handleMobHealthbars(targetEntity, damage, mcMMO.p); } @@ -183,7 +192,9 @@ public class RuptureTask extends CancellableRunnable { @Override public final boolean equals(Object o) { - if (!(o instanceof RuptureTask that)) return false; + if (!(o instanceof RuptureTask that)) { + return false; + } return ruptureSource.equals(that.ruptureSource) && targetEntity.equals(that.targetEntity); } 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 eea79ed31..3360149ef 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/SkillUnlockNotificationTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/SkillUnlockNotificationTask.java @@ -7,34 +7,37 @@ import com.gmail.nossr50.util.player.NotificationManager; public class SkillUnlockNotificationTask extends CancellableRunnable { - private final McMMOPlayer mcMMOPlayer; + private final McMMOPlayer mmoPlayer; private final SubSkillType subSkillType; private final int rank; + /** * Notify a player about a newly unlocked subskill - * @param mcMMOPlayer target player + * + * @param mmoPlayer target player * @param subSkillType the subskill that they just unlocked * @param rank the rank of the subskill */ - public SkillUnlockNotificationTask(McMMOPlayer mcMMOPlayer, SubSkillType subSkillType, int rank) { - this.mcMMOPlayer = mcMMOPlayer; + public SkillUnlockNotificationTask(McMMOPlayer mmoPlayer, SubSkillType subSkillType, int rank) { + this.mmoPlayer = mmoPlayer; 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 + * When an object implementing interface Runnable is used to create a thread, + * starting the thread causes the object's * run method to be called in that separately executing * thread. *

- * The general contract of the method run is that it may - * take any action whatsoever. + * The general contract of the method run is that it may take any action + * whatsoever. * * @see Thread#run() */ @Override public void run() { - //mcMMOPlayer.getPlayer().sendTitle(subSkillType.getLocaleName(), "Rank "+rank, 7, 20, 7); - NotificationManager.sendPlayerUnlockNotification(mcMMOPlayer, subSkillType); + //mmoPlayer.getPlayer().sendTitle(subSkillType.getLocaleName(), "Rank "+rank, 7, 20, 7); + NotificationManager.sendPlayerUnlockNotification(mmoPlayer, subSkillType); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/ToolLowerTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/ToolLowerTask.java index 98f336e84..1494101f0 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/ToolLowerTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/ToolLowerTask.java @@ -8,24 +8,25 @@ import com.gmail.nossr50.util.CancellableRunnable; import com.gmail.nossr50.util.player.NotificationManager; public class ToolLowerTask extends CancellableRunnable { - private final McMMOPlayer mcMMOPlayer; + private final McMMOPlayer mmoPlayer; private final ToolType tool; - public ToolLowerTask(McMMOPlayer mcMMOPlayer, ToolType tool) { - this.mcMMOPlayer = mcMMOPlayer; + public ToolLowerTask(McMMOPlayer mmoPlayer, ToolType tool) { + this.mmoPlayer = mmoPlayer; this.tool = tool; } @Override public void run() { - if (!mcMMOPlayer.getToolPreparationMode(tool)) { + if (!mmoPlayer.getToolPreparationMode(tool)) { return; } - mcMMOPlayer.setToolPreparationMode(tool, false); + mmoPlayer.setToolPreparationMode(tool, false); if (mcMMO.p.getGeneralConfig().getAbilityMessagesEnabled()) { - NotificationManager.sendPlayerInformation(mcMMOPlayer.getPlayer(), NotificationType.TOOL, tool.getLowerTool()); + NotificationManager.sendPlayerInformation(mmoPlayer.getPlayer(), NotificationType.TOOL, + tool.getLowerTool()); } } } diff --git a/src/main/java/com/gmail/nossr50/skills/SkillManager.java b/src/main/java/com/gmail/nossr50/skills/SkillManager.java index cc18c9b32..a3c826022 100644 --- a/src/main/java/com/gmail/nossr50/skills/SkillManager.java +++ b/src/main/java/com/gmail/nossr50/skills/SkillManager.java @@ -27,6 +27,7 @@ public abstract class SkillManager { /** * Applies XP to a player, provides SELF as an XpGainSource source + * * @param xp amount of XP to apply * @param xpGainReason the reason for the XP gain * @deprecated use applyXpGain(float, XPGainReason, XPGainSource) @@ -38,6 +39,7 @@ public abstract class SkillManager { /** * Applies XP to a player + * * @param xp amount of XP to apply * @param xpGainReason the reason for the XP gain * @param xpGainSource the source of the XP @@ -47,6 +49,7 @@ public abstract class SkillManager { } public XPGainReason getXPGainReason(LivingEntity target, Entity damager) { - return (damager instanceof Player && target instanceof Player) ? XPGainReason.PVP : XPGainReason.PVE; + return (damager instanceof Player && target instanceof Player) ? XPGainReason.PVP + : XPGainReason.PVE; } } diff --git a/src/main/java/com/gmail/nossr50/skills/acrobatics/Acrobatics.java b/src/main/java/com/gmail/nossr50/skills/acrobatics/Acrobatics.java index 60f948d90..ef4a0024a 100644 --- a/src/main/java/com/gmail/nossr50/skills/acrobatics/Acrobatics.java +++ b/src/main/java/com/gmail/nossr50/skills/acrobatics/Acrobatics.java @@ -4,13 +4,15 @@ import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.mcMMO; public final class Acrobatics { - public static double dodgeDamageModifier = mcMMO.p.getAdvancedConfig().getDodgeDamageModifier(); + public static double dodgeDamageModifier = mcMMO.p.getAdvancedConfig().getDodgeDamageModifier(); public static int dodgeXpModifier = ExperienceConfig.getInstance().getDodgeXPModifier(); - public static boolean dodgeLightningDisabled = mcMMO.p.getGeneralConfig().getDodgeLightningDisabled(); + public static boolean dodgeLightningDisabled = mcMMO.p.getGeneralConfig() + .getDodgeLightningDisabled(); - private Acrobatics() {} + private Acrobatics() { + } - protected static double calculateModifiedDodgeDamage(double damage, double damageModifier) { + static double calculateModifiedDodgeDamage(double damage, double damageModifier) { return Math.max(damage / damageModifier, 1.0); } } 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 80b1329e7..daeefcbdc 100644 --- a/src/main/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsManager.java +++ b/src/main/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsManager.java @@ -29,8 +29,8 @@ import org.bukkit.metadata.MetadataValue; public class AcrobaticsManager extends SkillManager { - public AcrobaticsManager(McMMOPlayer mcMMOPlayer) { - super(mcMMOPlayer, PrimarySkillType.ACROBATICS); + public AcrobaticsManager(McMMOPlayer mmoPlayer) { + super(mmoPlayer, PrimarySkillType.ACROBATICS); fallLocationMap = new BlockLocationHistory(50); } @@ -48,8 +48,9 @@ public class AcrobaticsManager extends SkillManager { } public boolean canGainRollXP() { - if (!ExperienceConfig.getInstance().isAcrobaticsExploitingPrevented()) + if (!ExperienceConfig.getInstance().isAcrobaticsExploitingPrevented()) { return true; + } if (System.currentTimeMillis() >= rollXPCooldown) { rollXPCooldown = System.currentTimeMillis() + rollXPInterval; @@ -63,11 +64,13 @@ public class AcrobaticsManager extends SkillManager { } public boolean canDodge(Entity damager) { - if (getPlayer().isBlocking()) + if (getPlayer().isBlocking()) { return false; + } - if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ACROBATICS_DODGE)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ACROBATICS_DODGE)) { return false; + } if (Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.ACROBATICS_DODGE)) { if (damager instanceof LightningStrike && Acrobatics.dodgeLightningDisabled) { @@ -84,36 +87,49 @@ public class AcrobaticsManager extends SkillManager { * Handle the damage reduction and XP gain from the Dodge ability * * @param damage The amount of damage initially dealt by the event - * @return the modified event damage if the ability was successful, the original event damage otherwise + * @return the modified event damage if the ability was successful, the original event damage + * otherwise */ public double dodgeCheck(Entity attacker, double damage) { - double modifiedDamage = Acrobatics.calculateModifiedDodgeDamage(damage, Acrobatics.dodgeDamageModifier); + double modifiedDamage = Acrobatics.calculateModifiedDodgeDamage(damage, + Acrobatics.dodgeDamageModifier); Player player = getPlayer(); if (!isFatal(modifiedDamage) - && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.ACROBATICS_DODGE, UserManager.getPlayer(player))) { + && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.ACROBATICS_DODGE, + UserManager.getPlayer(player))) { ParticleEffectUtils.playDodgeEffect(player); if (mmoPlayer.useChatNotifications()) { - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, "Acrobatics.Combat.Proc"); + NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, + "Acrobatics.Combat.Proc"); } - if (SkillUtils.cooldownExpired(mmoPlayer.getRespawnATS(), Misc.PLAYER_RESPAWN_COOLDOWN_SECONDS)) { + if (SkillUtils.cooldownExpired(mmoPlayer.getRespawnATS(), + Misc.PLAYER_RESPAWN_COOLDOWN_SECONDS)) { if (attacker instanceof Mob mob) { //Check to see how many dodge XP rewards this mob has handed out - if (mob.hasMetadata(MetadataConstants.METADATA_KEY_DODGE_TRACKER) && ExperienceConfig.getInstance().isAcrobaticsExploitingPrevented()) { + if (mob.hasMetadata(MetadataConstants.METADATA_KEY_DODGE_TRACKER) + && ExperienceConfig.getInstance().isAcrobaticsExploitingPrevented()) { //If Dodge XP has been handed out 5 times then consider it being exploited - MetadataValue metadataValue = mob.getMetadata(MetadataConstants.METADATA_KEY_DODGE_TRACKER).get(0); + MetadataValue metadataValue = mob.getMetadata( + MetadataConstants.METADATA_KEY_DODGE_TRACKER).get(0); int count = metadataValue.asInt(); if (count <= 5) { - applyXpGain((float) (damage * Acrobatics.dodgeXpModifier), XPGainReason.PVE); - mob.setMetadata(MetadataConstants.METADATA_KEY_DODGE_TRACKER, new FixedMetadataValue(mcMMO.p, count + 1)); - MobDodgeMetaCleanup metaCleanupTask = new MobDodgeMetaCleanup(mob, mcMMO.p); - mcMMO.p.getFoliaLib().getScheduler().runAtEntityTimer(mob, metaCleanupTask, 20, 20*60); //one minute + applyXpGain((float) (damage * Acrobatics.dodgeXpModifier), + XPGainReason.PVE); + mob.setMetadata(MetadataConstants.METADATA_KEY_DODGE_TRACKER, + new FixedMetadataValue(mcMMO.p, count + 1)); + MobDodgeMetaCleanup metaCleanupTask = new MobDodgeMetaCleanup(mob, + mcMMO.p); + mcMMO.p.getFoliaLib().getScheduler() + .runAtEntityTimer(mob, metaCleanupTask, 20, + 20 * 60); //one minute } } else { - applyXpGain((float) (damage * Acrobatics.dodgeXpModifier), XPGainReason.PVE); + applyXpGain((float) (damage * Acrobatics.dodgeXpModifier), + XPGainReason.PVE); } } } 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 fd41b3613..5281ab762 100644 --- a/src/main/java/com/gmail/nossr50/skills/alchemy/Alchemy.java +++ b/src/main/java/com/gmail/nossr50/skills/alchemy/Alchemy.java @@ -3,29 +3,32 @@ package com.gmail.nossr50.skills.alchemy; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.runnables.skills.AlchemyBrewTask; import com.gmail.nossr50.util.LogUtils; -import org.bukkit.Location; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.bukkit.Location; public final class Alchemy { public static final int INGREDIENT_SLOT = 3; - public static int catalysisMaxBonusLevel = mcMMO.p.getAdvancedConfig().getCatalysisMaxBonusLevel(); + public static int catalysisMaxBonusLevel = mcMMO.p.getAdvancedConfig() + .getCatalysisMaxBonusLevel(); public static double catalysisMinSpeed = mcMMO.p.getAdvancedConfig().getCatalysisMinSpeed(); public static double catalysisMaxSpeed = mcMMO.p.getAdvancedConfig().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. + * Finish all active brews. Used upon Disable to prevent vanilla potions from being brewed upon + * next Enable. */ public static void finishAllBrews() { - LogUtils.debug(mcMMO.p.getLogger(), "Completing " + brewingStandMap.size() + " unfinished Alchemy brews."); + LogUtils.debug(mcMMO.p.getLogger(), + "Completing " + brewingStandMap.size() + " unfinished Alchemy brews."); List toFinish = new ArrayList<>(brewingStandMap.values()); diff --git a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyManager.java b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyManager.java index 50c8e0974..801473b90 100644 --- a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyManager.java +++ b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyManager.java @@ -1,5 +1,7 @@ package com.gmail.nossr50.skills.alchemy; +import static com.gmail.nossr50.util.text.ConfigStringUtils.getMaterialConfigString; + import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.datatypes.experience.XPGainReason; import com.gmail.nossr50.datatypes.experience.XPGainSource; @@ -10,17 +12,14 @@ import com.gmail.nossr50.datatypes.skills.alchemy.PotionStage; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.skills.SkillManager; import com.gmail.nossr50.util.skills.RankUtils; -import org.bukkit.inventory.ItemStack; - import java.util.List; - -import static com.gmail.nossr50.util.text.ConfigStringUtils.getMaterialConfigString; +import org.bukkit.inventory.ItemStack; public class AlchemyManager extends SkillManager { private final double LUCKY_MODIFIER = 4.0 / 3.0; - public AlchemyManager(McMMOPlayer mcMMOPlayer) { - super(mcMMOPlayer, PrimarySkillType.ALCHEMY); + public AlchemyManager(McMMOPlayer mmoPlayer) { + super(mmoPlayer, PrimarySkillType.ALCHEMY); } public int getTier() { @@ -50,15 +49,22 @@ public class AlchemyManager extends SkillManager { return Alchemy.catalysisMinSpeed; } - return Math.min(Alchemy.catalysisMaxSpeed, Alchemy.catalysisMinSpeed + (Alchemy.catalysisMaxSpeed - Alchemy.catalysisMinSpeed) * (skillLevel - RankUtils.getUnlockLevel(SubSkillType.ALCHEMY_CATALYSIS)) / (Alchemy.catalysisMaxBonusLevel - RankUtils.getUnlockLevel(SubSkillType.ALCHEMY_CATALYSIS))) * (isLucky ? LUCKY_MODIFIER : 1.0); + return Math.min(Alchemy.catalysisMaxSpeed, Alchemy.catalysisMinSpeed + + (Alchemy.catalysisMaxSpeed - Alchemy.catalysisMinSpeed) * (skillLevel + - RankUtils.getUnlockLevel(SubSkillType.ALCHEMY_CATALYSIS)) / ( + Alchemy.catalysisMaxBonusLevel - RankUtils.getUnlockLevel( + SubSkillType.ALCHEMY_CATALYSIS))) * (isLucky ? LUCKY_MODIFIER + : 1.0); } /** * Handle the XP gain for a successful potion brew. + * * @param potionStage The potion stage, this is used to determine the XP gain. * @param amount The amount of potions brewed. */ public void handlePotionBrewSuccesses(PotionStage potionStage, int amount) { - applyXpGain((float) (ExperienceConfig.getInstance().getPotionXP(potionStage) * amount), XPGainReason.PVE, XPGainSource.PASSIVE); + applyXpGain((float) (ExperienceConfig.getInstance().getPotionXP(potionStage) * amount), + XPGainReason.PVE, XPGainSource.PASSIVE); } } \ No newline at end of file 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 6cc536808..20f241e1d 100644 --- a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java +++ b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java @@ -10,6 +10,11 @@ import com.gmail.nossr50.runnables.player.PlayerUpdateInventoryTask; import com.gmail.nossr50.runnables.skills.AlchemyBrewCheckTask; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.UserManager; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import org.bukkit.Material; import org.bukkit.block.BlockState; import org.bukkit.block.BrewingStand; @@ -23,12 +28,6 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - // TODO: Update to use McMMOPlayer public final class AlchemyPotionBrewer { /* @@ -36,6 +35,7 @@ public final class AlchemyPotionBrewer { * This was introduced in Minecraft 1.21 if we drop support for versions older than 1.21 this can be removed. */ private static final Method getItem, setItem; + static { try { final Class clazz = Class.forName("org.bukkit.inventory.InventoryView"); @@ -102,8 +102,9 @@ public final class AlchemyPotionBrewer { } private static void removeIngredient(BrewerInventory inventory, Player player) { - if (inventory.getIngredient() == null) + if (inventory.getIngredient() == null) { return; + } ItemStack ingredient = inventory.getIngredient().clone(); @@ -118,7 +119,8 @@ public final class AlchemyPotionBrewer { } private static boolean hasIngredient(BrewerInventory inventory, Player player) { - ItemStack ingredient = inventory.getIngredient() == null ? null : inventory.getIngredient().clone(); + ItemStack ingredient = + inventory.getIngredient() == null ? null : inventory.getIngredient().clone(); return !isEmpty(ingredient) && isValidIngredientByPlayer(player, ingredient); } @@ -157,11 +159,13 @@ public final class AlchemyPotionBrewer { return mcMMO.p.getPotionConfig().getIngredients(1); } - return mcMMO.p.getPotionConfig().getIngredients(!Permissions.isSubSkillEnabled(mmoPlayer, SubSkillType.ALCHEMY_CONCOCTIONS) - ? 1 : mmoPlayer.getAlchemyManager().getTier()); + return mcMMO.p.getPotionConfig().getIngredients( + !Permissions.isSubSkillEnabled(mmoPlayer, SubSkillType.ALCHEMY_CONCOCTIONS) + ? 1 : mmoPlayer.getAlchemyManager().getTier()); } - public static void finishBrewing(BlockState brewingStand, @Nullable McMMOPlayer mmoPlayer, boolean forced) { + public static void finishBrewing(BlockState brewingStand, @Nullable McMMOPlayer mmoPlayer, + boolean forced) { // Check if the brewing stand block state is an actual brewing stand if (!(brewingStand instanceof BrewingStand)) { return; @@ -169,7 +173,8 @@ public final class AlchemyPotionBrewer { // Retrieve the inventory of the brewing stand and clone the current ingredient for safe manipulation final BrewerInventory inventory = ((BrewingStand) brewingStand).getInventory(); - final ItemStack ingredient = inventory.getIngredient() == null ? null : inventory.getIngredient().clone(); + final ItemStack ingredient = + inventory.getIngredient() == null ? null : inventory.getIngredient().clone(); Player player = mmoPlayer != null ? mmoPlayer.getPlayer() : null; if (ingredient == null) { @@ -208,12 +213,14 @@ public final class AlchemyPotionBrewer { // If there is a valid output potion, add it to the output list if (output != null) { - outputList.set(i, output.toItemStack(potionInBrewStandInputSlot.getAmount()).clone()); + outputList.set(i, + output.toItemStack(potionInBrewStandInputSlot.getAmount()).clone()); } } // Create a fake brewing event and pass it to the plugin's event system - FakeBrewEvent event = new FakeBrewEvent(brewingStand.getBlock(), inventory, outputList, ((BrewingStand) brewingStand).getFuelLevel()); + FakeBrewEvent event = new FakeBrewEvent(brewingStand.getBlock(), inventory, outputList, + ((BrewingStand) brewingStand).getFuelLevel()); mcMMO.p.getServer().getPluginManager().callEvent(event); // If the event is cancelled or there are no potions processed, exit the method @@ -234,7 +241,9 @@ public final class AlchemyPotionBrewer { // Handle potion brewing success and related effects for each potion processed for (AlchemyPotion input : inputList) { - if (input == null) continue; + if (input == null) { + continue; + } AlchemyPotion output = input.getChild(ingredient); @@ -243,7 +252,8 @@ public final class AlchemyPotionBrewer { // Update player alchemy skills or effects based on brewing success if (UserManager.getPlayer(player) != null) { - UserManager.getPlayer(player).getAlchemyManager().handlePotionBrewSuccesses(potionStage, 1); + UserManager.getPlayer(player).getAlchemyManager() + .handlePotionBrewSuccesses(potionStage, 1); } } } @@ -350,7 +360,8 @@ public final class AlchemyPotionBrewer { public static void scheduleUpdate(Inventory inventory) { for (HumanEntity humanEntity : inventory.getViewers()) { if (humanEntity instanceof Player) { - mcMMO.p.getFoliaLib().getScheduler().runAtEntity(humanEntity, new PlayerUpdateInventoryTask((Player) humanEntity)); + mcMMO.p.getFoliaLib().getScheduler().runAtEntity(humanEntity, + new PlayerUpdateInventoryTask((Player) humanEntity)); } } } 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 b549c9a2c..b5e2c5737 100644 --- a/src/main/java/com/gmail/nossr50/skills/archery/Archery.java +++ b/src/main/java/com/gmail/nossr50/skills/archery/Archery.java @@ -6,24 +6,25 @@ import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.ItemUtils; import com.gmail.nossr50.util.skills.RankUtils; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; import org.bukkit.Material; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - public class Archery { private static final List trackedEntities = new ArrayList<>(); - public static double skillShotMaxBonusDamage = mcMMO.p.getAdvancedConfig().getSkillShotDamageMax(); + public static double skillShotMaxBonusDamage = mcMMO.p.getAdvancedConfig() + .getSkillShotDamageMax(); public static double dazeBonusDamage = mcMMO.p.getAdvancedConfig().getDazeBonusDamage(); - public static final double DISTANCE_XP_MULTIPLIER = ExperienceConfig.getInstance().getArcheryDistanceMultiplier(); + public static final double DISTANCE_XP_MULTIPLIER = ExperienceConfig.getInstance() + .getArcheryDistanceMultiplier(); protected static void incrementTrackerValue(LivingEntity livingEntity) { for (TrackedEntity trackedEntity : trackedEntities) { @@ -53,11 +54,14 @@ public class Archery { * @param livingEntity The entity hit by the arrows */ public static void arrowRetrievalCheck(@NotNull 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()) { - ItemUtils.spawnItems(null, livingEntity.getLocation(), new ItemStack(Material.ARROW), trackedEntity.getArrowCount(), ItemSpawnReason.ARROW_RETRIEVAL_ACTIVATED); + ItemUtils.spawnItems(null, livingEntity.getLocation(), + new ItemStack(Material.ARROW), trackedEntity.getArrowCount(), + ItemSpawnReason.ARROW_RETRIEVAL_ACTIVATED); entityIterator.remove(); return; } @@ -71,6 +75,7 @@ public class Archery { } public static double getDamageBonusPercent(Player player) { - return ((RankUtils.getRank(player, SubSkillType.ARCHERY_SKILL_SHOT)) * (mcMMO.p.getAdvancedConfig().getSkillShotRankDamageMultiplier()) / 100.0D); + return ((RankUtils.getRank(player, SubSkillType.ARCHERY_SKILL_SHOT)) + * (mcMMO.p.getAdvancedConfig().getSkillShotRankDamageMultiplier()) / 100.0D); } } 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 02ee6ee53..ee41e3ff0 100644 --- a/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java +++ b/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java @@ -1,5 +1,7 @@ package com.gmail.nossr50.skills.archery; +import static com.gmail.nossr50.util.PotionEffectUtil.getNauseaPotionEffectType; + import com.gmail.nossr50.datatypes.interactions.NotificationType; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; @@ -19,30 +21,32 @@ import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.potion.PotionEffect; -import static com.gmail.nossr50.util.PotionEffectUtil.getNauseaPotionEffectType; - public class ArcheryManager extends SkillManager { - public ArcheryManager(McMMOPlayer mcMMOPlayer) { - super(mcMMOPlayer, PrimarySkillType.ARCHERY); + public ArcheryManager(McMMOPlayer mmoPlayer) { + super(mmoPlayer, PrimarySkillType.ARCHERY); } 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); + 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); } @@ -55,20 +59,24 @@ public class ArcheryManager extends SkillManager { */ public static double distanceXpBonusMultiplier(LivingEntity target, Entity arrow) { //Hacky Fix - some plugins spawn arrows and assign them to players after the ProjectileLaunchEvent fires - if (!arrow.hasMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE)) + if (!arrow.hasMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE)) { return 1; + } - Location firedLocation = (Location) arrow.getMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE).get(0).value(); + Location firedLocation = (Location) arrow.getMetadata( + MetadataConstants.METADATA_KEY_ARROW_DISTANCE).get(0).value(); Location targetLocation = target.getLocation(); - if (firedLocation == null || firedLocation.getWorld() == null) + if (firedLocation == null || firedLocation.getWorld() == null) { return 1; + } if (firedLocation.getWorld() != targetLocation.getWorld()) { return 1; } - return 1 + Math.min(firedLocation.distance(targetLocation), 50) * Archery.DISTANCE_XP_MULTIPLIER; + return 1 + Math.min(firedLocation.distance(targetLocation), 50) + * Archery.DISTANCE_XP_MULTIPLIER; } /** @@ -79,7 +87,8 @@ public class ArcheryManager extends SkillManager { public void retrieveArrows(LivingEntity target, Projectile projectile) { if (projectile.hasMetadata(MetadataConstants.METADATA_KEY_TRACKED_ARROW)) { Archery.incrementTrackerValue(target); - projectile.removeMetadata(MetadataConstants.METADATA_KEY_TRACKED_ARROW, mcMMO.p); //Only 1 entity per projectile + projectile.removeMetadata(MetadataConstants.METADATA_KEY_TRACKED_ARROW, + mcMMO.p); //Only 1 entity per projectile } } @@ -100,11 +109,13 @@ public class ArcheryManager extends SkillManager { defender.addPotionEffect(new PotionEffect(getNauseaPotionEffectType(), 20 * 10, 10)); if (NotificationManager.doesPlayerUseNotifications(defender)) { - NotificationManager.sendPlayerInformation(defender, NotificationType.SUBSKILL_MESSAGE, "Combat.TouchedFuzzy"); + NotificationManager.sendPlayerInformation(defender, NotificationType.SUBSKILL_MESSAGE, + "Combat.TouchedFuzzy"); } if (mmoPlayer.useChatNotifications()) { - NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Combat.TargetDazed"); + NotificationManager.sendPlayerInformation(getPlayer(), + NotificationType.SUBSKILL_MESSAGE, "Combat.TargetDazed"); } return Archery.dazeBonusDamage; @@ -116,7 +127,8 @@ public class ArcheryManager extends SkillManager { * @param oldDamage The raw damage value of this arrow before we modify it */ public double skillShot(double oldDamage) { - if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.ARCHERY_SKILL_SHOT, mmoPlayer)) { + if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.ARCHERY_SKILL_SHOT, + mmoPlayer)) { return Archery.getSkillShotBonusDamage(getPlayer(), oldDamage); } else { return oldDamage; diff --git a/src/main/java/com/gmail/nossr50/skills/archery/TrackedEntity.java b/src/main/java/com/gmail/nossr50/skills/archery/TrackedEntity.java index 042b35adc..bc0a283f9 100644 --- a/src/main/java/com/gmail/nossr50/skills/archery/TrackedEntity.java +++ b/src/main/java/com/gmail/nossr50/skills/archery/TrackedEntity.java @@ -2,9 +2,8 @@ package com.gmail.nossr50.skills.archery; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.CancellableRunnable; -import org.bukkit.entity.LivingEntity; - import java.util.UUID; +import org.bukkit.entity.LivingEntity; public class TrackedEntity extends CancellableRunnable { private final LivingEntity livingEntity; 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 0ea49854c..a3fbfd7c3 100644 --- a/src/main/java/com/gmail/nossr50/skills/axes/Axes.java +++ b/src/main/java/com/gmail/nossr50/skills/axes/Axes.java @@ -9,26 +9,34 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class Axes { - public static double axeMasteryRankDamageMultiplier = mcMMO.p.getAdvancedConfig().getAxeMasteryRankDamageMultiplier(); + public static double axeMasteryRankDamageMultiplier = mcMMO.p.getAdvancedConfig() + .getAxeMasteryRankDamageMultiplier(); - public static double criticalHitPVPModifier = mcMMO.p.getAdvancedConfig().getCriticalStrikesPVPModifier(); - public static double criticalHitPVEModifier = mcMMO.p.getAdvancedConfig().getCriticalStrikesPVEModifier(); + public static double criticalHitPVPModifier = mcMMO.p.getAdvancedConfig() + .getCriticalStrikesPVPModifier(); + public static double criticalHitPVEModifier = mcMMO.p.getAdvancedConfig() + .getCriticalStrikesPVEModifier(); - public static double impactChance = mcMMO.p.getAdvancedConfig().getImpactChance(); + public static double impactChance = mcMMO.p.getAdvancedConfig().getImpactChance(); - public static double greaterImpactBonusDamage = mcMMO.p.getAdvancedConfig().getGreaterImpactBonusDamage(); - public static double greaterImpactChance = mcMMO.p.getAdvancedConfig().getGreaterImpactChance(); - public static double greaterImpactKnockbackMultiplier = mcMMO.p.getAdvancedConfig().getGreaterImpactModifier(); + public static double greaterImpactBonusDamage = mcMMO.p.getAdvancedConfig() + .getGreaterImpactBonusDamage(); + public static double greaterImpactChance = mcMMO.p.getAdvancedConfig().getGreaterImpactChance(); + public static double greaterImpactKnockbackMultiplier = mcMMO.p.getAdvancedConfig() + .getGreaterImpactModifier(); - public static double skullSplitterModifier = mcMMO.p.getAdvancedConfig().getSkullSplitterModifier(); + public static double skullSplitterModifier = mcMMO.p.getAdvancedConfig() + .getSkullSplitterModifier(); protected static boolean hasArmor(LivingEntity target) { - if (target == null || !target.isValid() || target.getEquipment() == null) + if (target == null || !target.isValid() || target.getEquipment() == null) { return false; + } for (ItemStack itemStack : target.getEquipment().getArmorContents()) { - if (itemStack == null) + if (itemStack == null) { continue; + } if (ItemUtils.isArmor(itemStack)) { return true; @@ -39,11 +47,14 @@ public class Axes { } /** - * For every rank in Axe Mastery we add RankDamageMultiplier to get the total bonus damage from Axe Mastery + * 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) { - return RankUtils.getRank(player, SubSkillType.AXES_AXE_MASTERY) * Axes.axeMasteryRankDamageMultiplier; + 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 7f6827acf..61df4f015 100644 --- a/src/main/java/com/gmail/nossr50/skills/axes/AxesManager.java +++ b/src/main/java/com/gmail/nossr50/skills/axes/AxesManager.java @@ -1,5 +1,8 @@ package com.gmail.nossr50.skills.axes; +import static com.gmail.nossr50.util.random.ProbabilityUtil.isSkillRNGSuccessful; +import static com.gmail.nossr50.util.skills.SkillUtils.handleArmorDurabilityChange; + import com.gmail.nossr50.datatypes.interactions.NotificationType; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; @@ -21,58 +24,66 @@ import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import static com.gmail.nossr50.util.random.ProbabilityUtil.isSkillRNGSuccessful; -import static com.gmail.nossr50.util.skills.SkillUtils.handleArmorDurabilityChange; - public class AxesManager extends SkillManager { - public AxesManager(McMMOPlayer mcMMOPlayer) { - super(mcMMOPlayer, PrimarySkillType.AXES); + public AxesManager(McMMOPlayer mmoPlayer) { + super(mmoPlayer, PrimarySkillType.AXES); } 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(@NotNull 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); + return target.isValid() && Permissions.isSubSkillEnabled(getPlayer(), + SubSkillType.AXES_CRITICAL_STRIKES); } public boolean canImpact(@NotNull 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); + return target.isValid() && Permissions.isSubSkillEnabled(getPlayer(), + SubSkillType.AXES_ARMOR_IMPACT) && Axes.hasArmor(target); } public boolean canGreaterImpact(@NotNull 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); + return target.isValid() && Permissions.isSubSkillEnabled(getPlayer(), + SubSkillType.AXES_GREATER_IMPACT) && !Axes.hasArmor(target); } public boolean canUseSkullSplitter(@NotNull LivingEntity target) { - if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_SKULL_SPLITTER)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_SKULL_SPLITTER)) { return false; + } - return target.isValid() && mmoPlayer.getAbilityMode(SuperAbilityType.SKULL_SPLITTER) && Permissions.skullSplitter(getPlayer()); + return target.isValid() && mmoPlayer.getAbilityMode(SuperAbilityType.SKULL_SPLITTER) + && Permissions.skullSplitter(getPlayer()); } public boolean canActivateAbility() { - return mmoPlayer.getToolPreparationMode(ToolType.AXE) && Permissions.skullSplitter(getPlayer()); + return mmoPlayer.getToolPreparationMode(ToolType.AXE) && Permissions.skullSplitter( + getPlayer()); } /** * Handle the effects of the Axe Mastery ability */ public double axeMastery() { - if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.AXES_AXE_MASTERY, mmoPlayer)) { + if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.AXES_AXE_MASTERY, + mmoPlayer)) { return Axes.getAxeMasteryBonusDamage(getPlayer()); } @@ -86,20 +97,23 @@ public class AxesManager extends SkillManager { * @param damage The amount of damage initially dealt by the event */ public double criticalHit(LivingEntity target, double damage) { - if (!isSkillRNGSuccessful(SubSkillType.AXES_CRITICAL_STRIKES, mmoPlayer, mmoPlayer.getAttackStrength())) { + if (!isSkillRNGSuccessful(SubSkillType.AXES_CRITICAL_STRIKES, mmoPlayer, + mmoPlayer.getAttackStrength())) { return 0; } Player player = getPlayer(); if (mmoPlayer.useChatNotifications()) { - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, "Axes.Combat.CriticalHit"); + NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, + "Axes.Combat.CriticalHit"); } if (target instanceof Player defender) { if (NotificationManager.doesPlayerUseNotifications(defender)) { - NotificationManager.sendPlayerInformation(defender, NotificationType.SUBSKILL_MESSAGE, "Axes.Combat.CritStruck"); + NotificationManager.sendPlayerInformation(defender, + NotificationType.SUBSKILL_MESSAGE, "Axes.Combat.CritStruck"); } damage = (damage * Axes.criticalHitPVPModifier) - damage; @@ -125,7 +139,8 @@ public class AxesManager extends SkillManager { for (ItemStack armor : equipment.getArmorContents()) { if (armor != null && ItemUtils.isArmor(armor)) { - if (isSkillRNGSuccessful(SubSkillType.AXES_ARMOR_IMPACT, mmoPlayer, mmoPlayer.getAttackStrength())) { + if (isSkillRNGSuccessful(SubSkillType.AXES_ARMOR_IMPACT, mmoPlayer, + mmoPlayer.getAttackStrength())) { handleArmorDurabilityChange(armor, durabilityDamage, 1); } } @@ -133,7 +148,8 @@ public class AxesManager extends SkillManager { } public double getImpactDurabilityDamage() { - return mcMMO.p.getAdvancedConfig().getImpactDurabilityDamageMultiplier() * RankUtils.getRank(getPlayer(), SubSkillType.AXES_ARMOR_IMPACT); + return mcMMO.p.getAdvancedConfig().getImpactDurabilityDamageMultiplier() + * RankUtils.getRank(getPlayer(), SubSkillType.AXES_ARMOR_IMPACT); } /** @@ -142,7 +158,8 @@ public class AxesManager extends SkillManager { * @param target The {@link LivingEntity} being affected by the ability */ public double greaterImpact(@NotNull LivingEntity target) { - if (!isSkillRNGSuccessful(SubSkillType.AXES_GREATER_IMPACT, mmoPlayer, mmoPlayer.getAttackStrength())) { + if (!isSkillRNGSuccessful(SubSkillType.AXES_GREATER_IMPACT, mmoPlayer, + mmoPlayer.getAttackStrength())) { return 0; } @@ -150,16 +167,19 @@ public class AxesManager extends SkillManager { ParticleEffectUtils.playGreaterImpactEffect(target); target.setVelocity( - player.getLocation().getDirection().normalize().multiply(Axes.greaterImpactKnockbackMultiplier)); + player.getLocation().getDirection().normalize() + .multiply(Axes.greaterImpactKnockbackMultiplier)); if (mmoPlayer.useChatNotifications()) { - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, "Axes.Combat.GI.Proc"); + NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, + "Axes.Combat.GI.Proc"); } if (target instanceof Player defender) { if (NotificationManager.doesPlayerUseNotifications(defender)) { - NotificationManager.sendPlayerInformation(defender, NotificationType.SUBSKILL_MESSAGE, "Axes.Combat.GI.Struck"); + NotificationManager.sendPlayerInformation(defender, + NotificationType.SUBSKILL_MESSAGE, "Axes.Combat.GI.Struck"); } } @@ -168,10 +188,12 @@ public class AxesManager extends SkillManager { /** * Handle the effects of the Skull Splitter ability - * @param target The {@link LivingEntity} being affected by the ability + * + * @param target The {@link LivingEntity} being affected by the ability * @param damage The amount of damage initially dealt by the event */ public void skullSplitterCheck(@NotNull LivingEntity target, double damage) { - CombatUtils.applyAbilityAoE(getPlayer(), target, (damage / Axes.skullSplitterModifier) * mmoPlayer.getAttackStrength(), skill); + CombatUtils.applyAbilityAoE(getPlayer(), target, + (damage / Axes.skullSplitterModifier) * mmoPlayer.getAttackStrength(), skill); } } diff --git a/src/main/java/com/gmail/nossr50/skills/crossbows/Crossbows.java b/src/main/java/com/gmail/nossr50/skills/crossbows/Crossbows.java index 1a60efd7d..867ecca7d 100644 --- a/src/main/java/com/gmail/nossr50/skills/crossbows/Crossbows.java +++ b/src/main/java/com/gmail/nossr50/skills/crossbows/Crossbows.java @@ -1,5 +1,7 @@ package com.gmail.nossr50.skills.crossbows; +import static com.gmail.nossr50.util.skills.ProjectileUtils.getNormal; + import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.util.player.UserManager; import org.bukkit.entity.Arrow; @@ -7,8 +9,6 @@ import org.bukkit.entity.Player; import org.bukkit.event.entity.ProjectileHitEvent; import org.bukkit.plugin.Plugin; -import static com.gmail.nossr50.util.skills.ProjectileUtils.getNormal; - /** * Util class for crossbows. */ @@ -16,21 +16,23 @@ public class Crossbows { /** * Process events that may happen from a crossbow hitting an entity. * - * @param event the projectile hit event - * @param pluginRef the plugin ref - * @param arrow the arrow + * @param event the projectile hit event + * @param pluginRef the plugin ref + * @param arrow the arrow */ public static void processCrossbows(ProjectileHitEvent event, Plugin pluginRef, Arrow arrow) { if (arrow.getShooter() instanceof Player) { - McMMOPlayer mmoPlayer = UserManager.getPlayer((Player) arrow.getShooter()); - if (mmoPlayer == null) + final McMMOPlayer mmoPlayer = UserManager.getPlayer((Player) arrow.getShooter()); + if (mmoPlayer == null) { return; + } processTrickShot(event, pluginRef, arrow, mmoPlayer); } } - private static void processTrickShot(ProjectileHitEvent event, Plugin pluginRef, Arrow arrow, McMMOPlayer mmoPlayer) { + private static void processTrickShot(ProjectileHitEvent event, Plugin pluginRef, Arrow arrow, + McMMOPlayer mmoPlayer) { if (event.getHitBlock() != null && event.getHitBlockFace() != null) { mmoPlayer.getCrossbowsManager().handleRicochet( pluginRef, diff --git a/src/main/java/com/gmail/nossr50/skills/crossbows/CrossbowsManager.java b/src/main/java/com/gmail/nossr50/skills/crossbows/CrossbowsManager.java index a339f902c..41d079906 100644 --- a/src/main/java/com/gmail/nossr50/skills/crossbows/CrossbowsManager.java +++ b/src/main/java/com/gmail/nossr50/skills/crossbows/CrossbowsManager.java @@ -1,5 +1,10 @@ package com.gmail.nossr50.skills.crossbows; +import static com.gmail.nossr50.util.MetadataConstants.MCMMO_METADATA_VALUE; +import static com.gmail.nossr50.util.MetadataConstants.METADATA_KEY_CROSSBOW_PROJECTILE; +import static com.gmail.nossr50.util.skills.CombatUtils.delayArrowMetaCleanup; +import static com.gmail.nossr50.util.skills.ProjectileUtils.isCrossbowProjectile; + import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; @@ -20,19 +25,16 @@ import org.bukkit.projectiles.ProjectileSource; import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; -import static com.gmail.nossr50.util.MetadataConstants.MCMMO_METADATA_VALUE; -import static com.gmail.nossr50.util.MetadataConstants.METADATA_KEY_CROSSBOW_PROJECTILE; -import static com.gmail.nossr50.util.skills.CombatUtils.delayArrowMetaCleanup; -import static com.gmail.nossr50.util.skills.ProjectileUtils.isCrossbowProjectile; - public class CrossbowsManager extends SkillManager { public CrossbowsManager(McMMOPlayer mmoPlayer) { super(mmoPlayer, PrimarySkillType.CROSSBOWS); } - public void handleRicochet(@NotNull Plugin pluginRef, @NotNull Arrow arrow, @NotNull Vector hitBlockNormal) { - if (!isCrossbowProjectile(arrow)) + public void handleRicochet(@NotNull Plugin pluginRef, @NotNull Arrow arrow, + @NotNull Vector hitBlockNormal) { + if (!isCrossbowProjectile(arrow)) { return; + } // Check player permission if (!Permissions.trickShot(mmoPlayer.getPlayer())) { @@ -44,11 +46,12 @@ public class CrossbowsManager extends SkillManager { } private void spawnReflectedArrow(@NotNull Plugin pluginRef, @NotNull Arrow originalArrow, - @NotNull Location origin, @NotNull Vector normal) { + @NotNull Location origin, @NotNull Vector normal) { int bounceCount = 0; if (originalArrow.hasMetadata(MetadataConstants.METADATA_KEY_BOUNCE_COUNT)) { - bounceCount = originalArrow.getMetadata(MetadataConstants.METADATA_KEY_BOUNCE_COUNT).get(0).asInt(); + bounceCount = originalArrow.getMetadata(MetadataConstants.METADATA_KEY_BOUNCE_COUNT) + .get(0).asInt(); if (bounceCount >= getTrickShotMaxBounceCount()) { return; } @@ -56,7 +59,8 @@ public class CrossbowsManager extends SkillManager { final ProjectileSource originalArrowShooter = originalArrow.getShooter(); final Vector arrowInBlockVector = originalArrow.getVelocity(); - final Vector reflectedDirection = arrowInBlockVector.subtract(normal.multiply(2 * arrowInBlockVector.dot(normal))); + final Vector reflectedDirection = arrowInBlockVector.subtract( + normal.multiply(2 * arrowInBlockVector.dot(normal))); final Vector inverseNormal = normal.multiply(-1); // check the angle of the arrow against the inverse normal to see if the angle was too shallow @@ -66,7 +70,8 @@ public class CrossbowsManager extends SkillManager { } // Spawn new arrow with the reflected direction - final Arrow spawnedArrow = originalArrow.getWorld().spawnArrow(origin, reflectedDirection, 1, 1); + final Arrow spawnedArrow = originalArrow.getWorld() + .spawnArrow(origin, reflectedDirection, 1, 1); // copy some properties from the old arrow spawnedArrow.setShooter(originalArrowShooter); spawnedArrow.setCritical(originalArrow.isCritical()); @@ -95,7 +100,8 @@ public class CrossbowsManager extends SkillManager { // Easy fix to recognize the arrow as a crossbow projectile // TODO: Replace the hack with the new API for setting weapon on projectiles if (!spawnedArrow.hasMetadata(METADATA_KEY_CROSSBOW_PROJECTILE)) { - spawnedArrow.setMetadata(MetadataConstants.METADATA_KEY_CROSSBOW_PROJECTILE, MCMMO_METADATA_VALUE); + spawnedArrow.setMetadata(MetadataConstants.METADATA_KEY_CROSSBOW_PROJECTILE, + MCMMO_METADATA_VALUE); } // There are reasons to keep this despite using the metadata values above spawnedArrow.setShotFromCrossbow(true); @@ -117,15 +123,18 @@ public class CrossbowsManager extends SkillManager { public double getPoweredShotBonusDamage(Player player, double oldDamage) { double damageBonusPercent = getDamageBonusPercent(player); double newDamage = oldDamage + (oldDamage * damageBonusPercent); - return Math.min(newDamage, (oldDamage + mcMMO.p.getAdvancedConfig().getPoweredShotDamageMax())); + return Math.min(newDamage, + (oldDamage + mcMMO.p.getAdvancedConfig().getPoweredShotDamageMax())); } public double getDamageBonusPercent(Player player) { - return ((RankUtils.getRank(player, SubSkillType.CROSSBOWS_POWERED_SHOT)) * (mcMMO.p.getAdvancedConfig().getPoweredShotRankDamageMultiplier()) / 100.0D); + return ((RankUtils.getRank(player, SubSkillType.CROSSBOWS_POWERED_SHOT)) + * (mcMMO.p.getAdvancedConfig().getPoweredShotRankDamageMultiplier()) / 100.0D); } public double poweredShot(double oldDamage) { - if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.CROSSBOWS_POWERED_SHOT, mmoPlayer)) { + if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.CROSSBOWS_POWERED_SHOT, + mmoPlayer)) { return getPoweredShotBonusDamage(getPlayer(), oldDamage); } else { return oldDamage; diff --git a/src/main/java/com/gmail/nossr50/skills/excavation/Excavation.java b/src/main/java/com/gmail/nossr50/skills/excavation/Excavation.java index 7b424e2d5..47b69955b 100644 --- a/src/main/java/com/gmail/nossr50/skills/excavation/Excavation.java +++ b/src/main/java/com/gmail/nossr50/skills/excavation/Excavation.java @@ -1,25 +1,26 @@ package com.gmail.nossr50.skills.excavation; -import com.gmail.nossr50.config.treasure.TreasureConfig; -import com.gmail.nossr50.datatypes.treasure.ExcavationTreasure; -import org.bukkit.block.Block; - -import java.util.ArrayList; -import java.util.List; - import static com.gmail.nossr50.util.text.ConfigStringUtils.getMaterialConfigString; +import com.gmail.nossr50.config.treasure.TreasureConfig; +import com.gmail.nossr50.datatypes.treasure.ExcavationTreasure; +import java.util.ArrayList; +import java.util.List; +import org.bukkit.block.Block; + public class Excavation { /** - * Get the list of possible {@link ExcavationTreasure|ExcavationTreasures} obtained from a given block. + * Get the list of possible {@link ExcavationTreasure|ExcavationTreasures} obtained from a given + * block. * * @param block The {@link Block} to check for treasures * @return the list of treasures that could be found */ protected static List getTreasures(Block block) { String friendly = getMaterialConfigString(block.getBlockData().getMaterial()); - if (TreasureConfig.getInstance().excavationMap.containsKey(friendly)) + if (TreasureConfig.getInstance().excavationMap.containsKey(friendly)) { return TreasureConfig.getInstance().excavationMap.get(friendly); + } return new ArrayList<>(); } } 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 f90b8247d..e47f2b57e 100644 --- a/src/main/java/com/gmail/nossr50/skills/excavation/ExcavationManager.java +++ b/src/main/java/com/gmail/nossr50/skills/excavation/ExcavationManager.java @@ -1,5 +1,7 @@ package com.gmail.nossr50.skills.excavation; +import static java.util.Objects.requireNonNull; + import com.gmail.nossr50.api.ItemSpawnReason; import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.datatypes.experience.XPGainReason; @@ -16,6 +18,7 @@ import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.skills.SkillUtils; +import java.util.List; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.block.BlockState; @@ -23,13 +26,9 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.VisibleForTesting; -import java.util.List; - -import static java.util.Objects.requireNonNull; - public class ExcavationManager extends SkillManager { - public ExcavationManager(McMMOPlayer mcMMOPlayer) { - super(mcMMOPlayer, PrimarySkillType.EXCAVATION); + public ExcavationManager(McMMOPlayer mmoPlayer) { + super(mmoPlayer, PrimarySkillType.EXCAVATION); } /** @@ -55,7 +54,8 @@ public class ExcavationManager extends SkillManager { for (ExcavationTreasure treasure : treasures) { if (skillLevel >= treasure.getDropLevel() && ProbabilityUtil.isStaticSkillRNGSuccessful( - PrimarySkillType.EXCAVATION, mmoPlayer, treasure.getDropProbability())) { + PrimarySkillType.EXCAVATION, mmoPlayer, + treasure.getDropProbability())) { processExcavationBonusesOnBlock(treasure, centerOfBlock); } } @@ -78,7 +78,8 @@ public class ExcavationManager extends SkillManager { @VisibleForTesting @Deprecated(forRemoval = true, since = "2.2.024") - public void processExcavationBonusesOnBlock(BlockState ignored, ExcavationTreasure treasure, Location location) { + public void processExcavationBonusesOnBlock(BlockState ignored, ExcavationTreasure treasure, + Location location) { processExcavationBonusesOnBlock(treasure, location); } @@ -91,7 +92,8 @@ public class ExcavationManager extends SkillManager { int xp = 0; xp += treasure.getXp(); - ItemUtils.spawnItem(getPlayer(), location, treasure.getDrop(), ItemSpawnReason.EXCAVATION_TREASURE); + ItemUtils.spawnItem(getPlayer(), location, treasure.getDrop(), + ItemSpawnReason.EXCAVATION_TREASURE); if (xp > 0) { applyXpGain(xp, XPGainReason.PVE, XPGainSource.SELF); } @@ -116,10 +118,13 @@ public class ExcavationManager extends SkillManager { 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() + ")"); + 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 d453edaf0..e4f752d56 100644 --- a/src/main/java/com/gmail/nossr50/skills/fishing/Fishing.java +++ b/src/main/java/com/gmail/nossr50/skills/fishing/Fishing.java @@ -3,30 +3,30 @@ package com.gmail.nossr50.skills.fishing; import com.gmail.nossr50.config.treasure.FishingTreasureConfig; import com.gmail.nossr50.datatypes.treasure.ShakeTreasure; import com.gmail.nossr50.util.Misc; +import java.util.HashMap; +import java.util.List; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.LivingEntity; import org.bukkit.inventory.ItemStack; -import java.util.HashMap; -import java.util.List; - public final class Fishing { static final HashMap> ENCHANTABLE_CACHE = new HashMap<>(); - private Fishing() {} + private 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 */ static List findPossibleDrops(LivingEntity target) { - if (FishingTreasureConfig.getInstance().shakeMap.containsKey(target.getType())) + if (FishingTreasureConfig.getInstance().shakeMap.containsKey(target.getType())) { return FishingTreasureConfig.getInstance().shakeMap.get(target.getType()); + } return null; } @@ -34,8 +34,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 */ static ItemStack chooseDrop(List possibleDrops) { 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 2418e52b1..7a5845e81 100644 --- a/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java @@ -8,7 +8,11 @@ import com.gmail.nossr50.datatypes.interactions.NotificationType; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; -import com.gmail.nossr50.datatypes.treasure.*; +import com.gmail.nossr50.datatypes.treasure.EnchantmentTreasure; +import com.gmail.nossr50.datatypes.treasure.FishingTreasure; +import com.gmail.nossr50.datatypes.treasure.FishingTreasureBook; +import com.gmail.nossr50.datatypes.treasure.Rarity; +import com.gmail.nossr50.datatypes.treasure.ShakeTreasure; import com.gmail.nossr50.events.skills.fishing.McMMOPlayerFishingTreasureEvent; import com.gmail.nossr50.events.skills.fishing.McMMOPlayerMasterAnglerEvent; import com.gmail.nossr50.events.skills.fishing.McMMOPlayerShakeEvent; @@ -16,7 +20,12 @@ import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.runnables.skills.MasterAnglerTask; import com.gmail.nossr50.skills.SkillManager; -import com.gmail.nossr50.util.*; +import com.gmail.nossr50.util.BlockUtils; +import com.gmail.nossr50.util.EventUtils; +import com.gmail.nossr50.util.ItemUtils; +import com.gmail.nossr50.util.MetadataConstants; +import com.gmail.nossr50.util.Misc; +import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.adapter.BiomeAdapter; import com.gmail.nossr50.util.compat.layers.skills.MasterAnglerCompatibilityLayer; import com.gmail.nossr50.util.player.NotificationManager; @@ -24,13 +33,24 @@ import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.skills.SkillUtils; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.*; +import org.bukkit.entity.Boat; +import org.bukkit.entity.Entity; +import org.bukkit.entity.FishHook; +import org.bukkit.entity.Item; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.entity.Sheep; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.SkullMeta; @@ -39,8 +59,6 @@ import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; - public class FishingManager extends SkillManager { public static final int FISHING_ROD_CAST_CD_MILLISECONDS = 100; private final long FISHING_COOLDOWN_SECONDS = 1000L; @@ -48,7 +66,7 @@ public class FishingManager extends SkillManager { private long fishingRodCastTimestamp = 0L; private long fishHookSpawnTimestamp = 0L; private long lastWarned = 0L; - private long lastWarnedExhaust = 0L; + private final long lastWarnedExhaust = 0L; private FishHook fishHookReference; private BoundingBox lastFishingBoundingBox; private boolean sameTarget; @@ -58,18 +76,20 @@ public class FishingManager extends SkillManager { private final int masterAnglerMinWaitLowerBound; private final int masterAnglerMaxWaitLowerBound; - public FishingManager(McMMOPlayer mcMMOPlayer) { - super(mcMMOPlayer, PrimarySkillType.FISHING); + public FishingManager(McMMOPlayer mmoPlayer) { + super(mmoPlayer, PrimarySkillType.FISHING); //Ticks for minWait and maxWait never go below this value int bonusCapMin = mcMMO.p.getAdvancedConfig().getFishingReductionMinWaitCap(); int bonusCapMax = mcMMO.p.getAdvancedConfig().getFishingReductionMaxWaitCap(); this.masterAnglerMinWaitLowerBound = Math.max(bonusCapMin, 0); - this.masterAnglerMaxWaitLowerBound = Math.max(bonusCapMax, masterAnglerMinWaitLowerBound + 40); + this.masterAnglerMaxWaitLowerBound = Math.max(bonusCapMax, + masterAnglerMinWaitLowerBound + 40); } public boolean canShake(Entity target) { - return target instanceof LivingEntity && RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.FISHING_SHAKE) + return target instanceof LivingEntity && RankUtils.hasUnlockedSubskill(getPlayer(), + SubSkillType.FISHING_SHAKE) && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.FISHING_SHAKE); } @@ -111,10 +131,12 @@ public class FishingManager extends SkillManager { // } public void setFishHookReference(FishHook fishHook) { - if (fishHook.getMetadata(MetadataConstants.METADATA_KEY_FISH_HOOK_REF).size() > 0) + if (fishHook.getMetadata(MetadataConstants.METADATA_KEY_FISH_HOOK_REF).size() > 0) { return; + } - fishHook.setMetadata(MetadataConstants.METADATA_KEY_FISH_HOOK_REF, MetadataConstants.MCMMO_METADATA_VALUE); + fishHook.setMetadata(MetadataConstants.METADATA_KEY_FISH_HOOK_REF, + MetadataConstants.MCMMO_METADATA_VALUE); this.fishHookReference = fishHook; fishHookSpawnTimestamp = System.currentTimeMillis(); fishingRodCastTimestamp = System.currentTimeMillis(); @@ -136,7 +158,8 @@ public class FishingManager extends SkillManager { public void processExploiting(Vector centerOfCastVector) { BoundingBox newCastBoundingBox = makeBoundingBox(centerOfCastVector); - this.sameTarget = lastFishingBoundingBox != null && lastFishingBoundingBox.overlaps(newCastBoundingBox); + this.sameTarget = lastFishingBoundingBox != null && lastFishingBoundingBox.overlaps( + newCastBoundingBox); if (this.sameTarget) { fishCaughtCounter++; @@ -145,10 +168,14 @@ public class FishingManager extends SkillManager { } //If the new bounding box does not intersect with the old one, then update our bounding box reference - if (!this.sameTarget) lastFishingBoundingBox = newCastBoundingBox; + if (!this.sameTarget) { + lastFishingBoundingBox = newCastBoundingBox; + } - if (fishCaughtCounter + 1 == ExperienceConfig.getInstance().getFishingExploitingOptionOverFishLimit()) { - getPlayer().sendMessage(LocaleLoader.getString("Fishing.LowResourcesTip", ExperienceConfig.getInstance().getFishingExploitingOptionMoveRange())); + if (fishCaughtCounter + 1 == ExperienceConfig.getInstance() + .getFishingExploitingOptionOverFishLimit()) { + getPlayer().sendMessage(LocaleLoader.getString("Fishing.LowResourcesTip", + ExperienceConfig.getInstance().getFishingExploitingOptionMoveRange())); } } @@ -160,7 +187,8 @@ public class FishingManager extends SkillManager { return false; }*/ - return this.sameTarget && fishCaughtCounter >= ExperienceConfig.getInstance().getFishingExploitingOptionOverFishLimit(); + return this.sameTarget && fishCaughtCounter >= ExperienceConfig.getInstance() + .getFishingExploitingOptionOverFishLimit(); } public static BoundingBox makeBoundingBox(Vector centerOfCastVector) { @@ -206,7 +234,8 @@ public class FishingManager extends SkillManager { } public double getShakeChance() { - return mcMMO.p.getAdvancedConfig().getShakeChance(RankUtils.getRank(mmoPlayer.getPlayer(), SubSkillType.FISHING_SHAKE)); + return mcMMO.p.getAdvancedConfig().getShakeChance( + RankUtils.getRank(mmoPlayer.getPlayer(), SubSkillType.FISHING_SHAKE)); } protected int getVanillaXPBoostModifier() { @@ -226,11 +255,11 @@ 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) { - return SkillUtils.handleFoodSkills(getPlayer(), eventFoodLevel, SubSkillType.FISHING_FISHERMANS_DIET); + return SkillUtils.handleFoodSkills(getPlayer(), eventFoodLevel, + SubSkillType.FISHING_FISHERMANS_DIET); } public void iceFishing(FishHook hook, Block block) { @@ -252,16 +281,19 @@ public class FishingManager extends SkillManager { } public void masterAngler(@NotNull FishHook hook, int lureLevel) { - mcMMO.p.getFoliaLib().getScheduler().runAtEntityLater(hook, new MasterAnglerTask(hook, this, lureLevel), 1); //We run later to get the lure bonus applied + mcMMO.p.getFoliaLib().getScheduler() + .runAtEntityLater(hook, new MasterAnglerTask(hook, this, lureLevel), + 1); //We run later to get the lure bonus applied } /** - * Processes master angler - * Reduced tick time on fish hook, etc + * Processes master angler Reduced tick time on fish hook, etc + * * @param fishHook target fish hook */ public void processMasterAngler(@NotNull FishHook fishHook, int lureLevel) { - MasterAnglerCompatibilityLayer masterAnglerCompatibilityLayer = (MasterAnglerCompatibilityLayer) mcMMO.getCompatibilityManager().getMasterAnglerCompatibilityLayer(); + MasterAnglerCompatibilityLayer masterAnglerCompatibilityLayer = (MasterAnglerCompatibilityLayer) mcMMO.getCompatibilityManager() + .getMasterAnglerCompatibilityLayer(); if (masterAnglerCompatibilityLayer != null) { int maxWaitTicks = masterAnglerCompatibilityLayer.getMaxWaitTime(fishHook); @@ -278,10 +310,13 @@ public class FishingManager extends SkillManager { boolean boatBonus = isInBoat(); int minWaitReduction = getMasterAnglerTickMinWaitReduction(masterAnglerRank, boatBonus); - int maxWaitReduction = getMasterAnglerTickMaxWaitReduction(masterAnglerRank, boatBonus, convertedLureBonus); + int maxWaitReduction = getMasterAnglerTickMaxWaitReduction(masterAnglerRank, boatBonus, + convertedLureBonus); - int reducedMinWaitTime = getReducedTicks(minWaitTicks, minWaitReduction, masterAnglerMinWaitLowerBound); - int reducedMaxWaitTime = getReducedTicks(maxWaitTicks, maxWaitReduction, masterAnglerMaxWaitLowerBound); + int reducedMinWaitTime = getReducedTicks(minWaitTicks, minWaitReduction, + masterAnglerMinWaitLowerBound); + int reducedMaxWaitTime = getReducedTicks(maxWaitTicks, maxWaitReduction, + masterAnglerMaxWaitLowerBound); boolean badValuesFix = false; @@ -292,7 +327,8 @@ public class FishingManager extends SkillManager { } final McMMOPlayerMasterAnglerEvent event = - new McMMOPlayerMasterAnglerEvent(mmoPlayer, reducedMinWaitTime, reducedMaxWaitTime, this); + new McMMOPlayerMasterAnglerEvent(mmoPlayer, reducedMinWaitTime, + reducedMaxWaitTime, this); mcMMO.p.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { @@ -306,36 +342,46 @@ public class FishingManager extends SkillManager { mmoPlayer.getPlayer().sendMessage(ChatColor.GOLD + "Master Angler Debug"); if (badValuesFix) { - mmoPlayer.getPlayer().sendMessage(ChatColor.RED + "Bad values were applied and corrected," + - " check your configs, minWaitLowerBound wait should never be lower than min wait."); + mmoPlayer.getPlayer() + .sendMessage(ChatColor.RED + "Bad values were applied and corrected," + + " check your configs, minWaitLowerBound wait should never be lower than min wait."); } - mmoPlayer.getPlayer().sendMessage("ALLOW STACK WITH LURE: " + masterAnglerCompatibilityLayer.getApplyLure(fishHook)); + mmoPlayer.getPlayer().sendMessage( + "ALLOW STACK WITH LURE: " + masterAnglerCompatibilityLayer.getApplyLure( + fishHook)); mmoPlayer.getPlayer().sendMessage("MIN TICK REDUCTION: " + minWaitReduction); mmoPlayer.getPlayer().sendMessage("MAX TICK REDUCTION: " + maxWaitReduction); mmoPlayer.getPlayer().sendMessage("BOAT BONUS: " + boatBonus); if (boatBonus) { - mmoPlayer.getPlayer().sendMessage("BOAT MAX TICK REDUCTION: " + maxWaitReduction); - mmoPlayer.getPlayer().sendMessage("BOAT MIN TICK REDUCTION: " + maxWaitReduction); + mmoPlayer.getPlayer() + .sendMessage("BOAT MAX TICK REDUCTION: " + maxWaitReduction); + mmoPlayer.getPlayer() + .sendMessage("BOAT MIN TICK REDUCTION: " + maxWaitReduction); } mmoPlayer.getPlayer().sendMessage(""); - mmoPlayer.getPlayer().sendMessage(ChatColor.DARK_AQUA + "BEFORE MASTER ANGLER WAS APPLIED"); + mmoPlayer.getPlayer() + .sendMessage(ChatColor.DARK_AQUA + "BEFORE MASTER ANGLER WAS APPLIED"); mmoPlayer.getPlayer().sendMessage("Original Max Wait Ticks: " + maxWaitTicks); mmoPlayer.getPlayer().sendMessage("Original Min Wait Ticks: " + minWaitTicks); mmoPlayer.getPlayer().sendMessage(""); - mmoPlayer.getPlayer().sendMessage(ChatColor.DARK_AQUA + "AFTER MASTER ANGLER WAS APPLIED"); + mmoPlayer.getPlayer() + .sendMessage(ChatColor.DARK_AQUA + "AFTER MASTER ANGLER WAS APPLIED"); mmoPlayer.getPlayer().sendMessage("Current Max Wait Ticks: " + reducedMaxWaitTime); mmoPlayer.getPlayer().sendMessage("Current Min Wait Ticks: " + reducedMinWaitTime); mmoPlayer.getPlayer().sendMessage(""); - mmoPlayer.getPlayer().sendMessage(ChatColor.DARK_AQUA + "Caps / Limits (edit in advanced.yml)"); - mmoPlayer.getPlayer().sendMessage("Lowest possible minWaitLowerBound wait ticks " + masterAnglerMinWaitLowerBound); - mmoPlayer.getPlayer().sendMessage("Lowest possible min wait ticks " + masterAnglerMaxWaitLowerBound); + mmoPlayer.getPlayer() + .sendMessage(ChatColor.DARK_AQUA + "Caps / Limits (edit in advanced.yml)"); + mmoPlayer.getPlayer().sendMessage("Lowest possible minWaitLowerBound wait ticks " + + masterAnglerMinWaitLowerBound); + mmoPlayer.getPlayer().sendMessage( + "Lowest possible min wait ticks " + masterAnglerMaxWaitLowerBound); } masterAnglerCompatibilityLayer.setMaxWaitTime(fishHook, reducedMaxWaitTime); @@ -349,11 +395,14 @@ public class FishingManager extends SkillManager { } public boolean isInBoat() { - return mmoPlayer.getPlayer().isInsideVehicle() && mmoPlayer.getPlayer().getVehicle() instanceof Boat; + return mmoPlayer.getPlayer().isInsideVehicle() && mmoPlayer.getPlayer() + .getVehicle() instanceof Boat; } - public int getMasterAnglerTickMaxWaitReduction(int masterAnglerRank, boolean boatBonus, int emulatedLureBonus) { - int totalBonus = mcMMO.p.getAdvancedConfig().getFishingReductionMaxWaitTicks() * masterAnglerRank; + public int getMasterAnglerTickMaxWaitReduction(int masterAnglerRank, boolean boatBonus, + int emulatedLureBonus) { + int totalBonus = + mcMMO.p.getAdvancedConfig().getFishingReductionMaxWaitTicks() * masterAnglerRank; if (boatBonus) { totalBonus += getFishingBoatMaxWaitReduction(); @@ -365,7 +414,8 @@ public class FishingManager extends SkillManager { } public int getMasterAnglerTickMinWaitReduction(int masterAnglerRank, boolean boatBonus) { - int totalBonus = mcMMO.p.getAdvancedConfig().getFishingReductionMinWaitTicks() * masterAnglerRank; + int totalBonus = + mcMMO.p.getAdvancedConfig().getFishingReductionMinWaitTicks() * masterAnglerRank; if (boatBonus) { totalBonus += getFishingBoatMinWaitReduction(); @@ -395,14 +445,16 @@ public class FishingManager extends SkillManager { */ public void processFishing(@NotNull Item fishingCatch) { this.fishingCatch = fishingCatch; - int fishXp = ExperienceConfig.getInstance().getXp(PrimarySkillType.FISHING, fishingCatch.getItemStack().getType()); + int fishXp = ExperienceConfig.getInstance() + .getXp(PrimarySkillType.FISHING, fishingCatch.getItemStack().getType()); int treasureXp = 0; ItemStack treasureDrop = null; Player player = getPlayer(); FishingTreasure treasure = null; boolean fishingSucceeds = false; - if (mcMMO.p.getGeneralConfig().getFishingDropsEnabled() && Permissions.isSubSkillEnabled(player, SubSkillType.FISHING_TREASURE_HUNTER)) { + if (mcMMO.p.getGeneralConfig().getFishingDropsEnabled() && Permissions.isSubSkillEnabled( + player, SubSkillType.FISHING_TREASURE_HUNTER)) { treasure = getFishingTreasure(); this.fishingCatch = null; } @@ -426,13 +478,15 @@ public class FishingManager extends SkillManager { enchants.putAll(treasureDrop.getItemMeta().getEnchants()); } - event = EventUtils.callFishingTreasureEvent(mmoPlayer, treasureDrop, treasure.getXp(), enchants); + event = EventUtils.callFishingTreasureEvent(mmoPlayer, treasureDrop, + treasure.getXp(), enchants); } else { if (isMagicHunterEnabled() && ItemUtils.isEnchantable(treasureDrop)) { enchants = processMagicHunter(treasureDrop); } - event = EventUtils.callFishingTreasureEvent(mmoPlayer, treasureDrop, treasure.getXp(), enchants); + event = EventUtils.callFishingTreasureEvent(mmoPlayer, treasureDrop, + treasure.getXp(), enchants); } if (!event.isCancelled()) { @@ -452,7 +506,8 @@ public class FishingManager extends SkillManager { } if (enchanted) { - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, "Fishing.Ability.TH.MagicFound"); + NotificationManager.sendPlayerInformation(player, + NotificationType.SUBSKILL_MESSAGE, "Fishing.Ability.TH.MagicFound"); } } @@ -464,7 +519,8 @@ public class FishingManager extends SkillManager { if (fishingSucceeds) { if (mcMMO.p.getGeneralConfig().getFishingExtraFish()) { - ItemUtils.spawnItem(getPlayer(), player.getEyeLocation(), fishingCatch.getItemStack(), ItemSpawnReason.FISHING_EXTRA_FISH); + ItemUtils.spawnItem(getPlayer(), player.getEyeLocation(), + fishingCatch.getItemStack(), ItemSpawnReason.FISHING_EXTRA_FISH); } fishingCatch.setItemStack(treasureDrop); @@ -477,7 +533,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 handleVanillaXpBoost(int experience) { @@ -494,7 +549,8 @@ public class FishingManager extends SkillManager { * @param target The {@link LivingEntity} affected by the ability */ public void shakeCheck(@NotNull LivingEntity target) { - if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.FISHING, mmoPlayer, getShakeChance())) { + if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.FISHING, mmoPlayer, + getShakeChance())) { List possibleDrops = Fishing.findPossibleDrops(target); if (possibleDrops == null || possibleDrops.isEmpty()) { @@ -535,7 +591,9 @@ public class FishingManager extends SkillManager { if (FishingTreasureConfig.getInstance().getInventoryStealStacks()) { inventory.setItem(slot, null); } else { - inventory.setItem(slot, (drop.getAmount() > 1) ? new ItemStack(drop.getType(), drop.getAmount() - 1) : null); + inventory.setItem(slot, + (drop.getAmount() > 1) ? new ItemStack(drop.getType(), + drop.getAmount() - 1) : null); drop.setAmount(1); } @@ -570,7 +628,8 @@ public class FishingManager extends SkillManager { return; } - ItemUtils.spawnItem(getPlayer(), target.getLocation(), drop, ItemSpawnReason.FISHING_SHAKE_TREASURE); + ItemUtils.spawnItem(getPlayer(), target.getLocation(), drop, + ItemSpawnReason.FISHING_SHAKE_TREASURE); // Make it so you can shake a mob no more than 4 times. double dmg = Math.min(Math.max(target.getMaxHealth() / 4, 1), 10); CombatUtils.safeDealDamage(target, dmg, getPlayer()); @@ -602,11 +661,13 @@ public class FishingManager extends SkillManager { FishingTreasure treasure = null; for (Rarity rarity : Rarity.values()) { - double dropRate = FishingTreasureConfig.getInstance().getItemDropRate(getLootTier(), rarity); + double dropRate = FishingTreasureConfig.getInstance() + .getItemDropRate(getLootTier(), rarity); if (diceRoll <= dropRate) { - List fishingTreasures = FishingTreasureConfig.getInstance().fishingRewards.get(rarity); + List fishingTreasures = FishingTreasureConfig.getInstance().fishingRewards.get( + rarity); if (fishingTreasures.isEmpty()) { return null; @@ -653,7 +714,8 @@ public class FishingManager extends SkillManager { for (Rarity rarity : Rarity.values()) { - double dropRate = FishingTreasureConfig.getInstance().getEnchantmentDropRate(getLootTier(), rarity); + double dropRate = FishingTreasureConfig.getInstance() + .getEnchantmentDropRate(getLootTier(), rarity); if (diceRoll <= dropRate) { // Make sure enchanted books always get some kind of enchantment. --hoorigan @@ -662,7 +724,8 @@ public class FishingManager extends SkillManager { continue; } - fishingEnchantments = FishingTreasureConfig.getInstance().fishingEnchantments.get(rarity); + fishingEnchantments = FishingTreasureConfig.getInstance().fishingEnchantments.get( + rarity); break; } @@ -694,7 +757,8 @@ public class FishingManager extends SkillManager { for (EnchantmentTreasure enchantmentTreasure : possibleEnchants) { Enchantment possibleEnchantment = enchantmentTreasure.getEnchantment(); - if (treasureDrop.getItemMeta().hasConflictingEnchant(possibleEnchantment) || Misc.getRandom().nextInt(specificChance) != 0) { + if (treasureDrop.getItemMeta().hasConflictingEnchant(possibleEnchantment) + || Misc.getRandom().nextInt(specificChance) != 0) { continue; } 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 00c05d20e..452219280 100644 --- a/src/main/java/com/gmail/nossr50/skills/herbalism/Herbalism.java +++ b/src/main/java/com/gmail/nossr50/skills/herbalism/Herbalism.java @@ -9,7 +9,6 @@ public class Herbalism { * Convert blocks affected by the Green Thumb & Green Terra abilities. * * @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) { @@ -40,7 +39,6 @@ public class Herbalism { * Convert blocks affected by the Green Thumb & Green Terra abilities. * * @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) { 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 bf3c5ac7c..30314b5a7 100644 --- a/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java +++ b/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java @@ -1,5 +1,11 @@ package com.gmail.nossr50.skills.herbalism; +import static com.gmail.nossr50.util.ItemUtils.hasItemIncludingOffHand; +import static com.gmail.nossr50.util.ItemUtils.removeItemIncludingOffHand; +import static com.gmail.nossr50.util.Misc.getBlockCenter; +import static com.gmail.nossr50.util.text.ConfigStringUtils.getMaterialConfigString; +import static java.util.Objects.requireNonNull; + import com.gmail.nossr50.api.ItemSpawnReason; import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.config.treasure.TreasureConfig; @@ -18,7 +24,13 @@ import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.runnables.skills.DelayedCropReplant; import com.gmail.nossr50.runnables.skills.DelayedHerbalismXPCheckTask; import com.gmail.nossr50.skills.SkillManager; -import com.gmail.nossr50.util.*; +import com.gmail.nossr50.util.BlockUtils; +import com.gmail.nossr50.util.CancellableRunnable; +import com.gmail.nossr50.util.EventUtils; +import com.gmail.nossr50.util.ItemUtils; +import com.gmail.nossr50.util.MetadataConstants; +import com.gmail.nossr50.util.Misc; +import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.NotificationManager; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.RankUtils; @@ -26,6 +38,13 @@ import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.sounds.SoundManager; import com.gmail.nossr50.util.sounds.SoundType; import com.gmail.nossr50.util.text.StringUtils; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; @@ -39,14 +58,6 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.jetbrains.annotations.NotNull; -import java.util.*; - -import static com.gmail.nossr50.util.ItemUtils.hasItemIncludingOffHand; -import static com.gmail.nossr50.util.ItemUtils.removeItemIncludingOffHand; -import static com.gmail.nossr50.util.Misc.getBlockCenter; -import static com.gmail.nossr50.util.text.ConfigStringUtils.getMaterialConfigString; -import static java.util.Objects.requireNonNull; - public class HerbalismManager extends SkillManager { private final static HashMap plantBreakLimits; @@ -63,13 +74,14 @@ public class HerbalismManager extends SkillManager { plantBreakLimits.put("chorus_plant", 22); } - public HerbalismManager(McMMOPlayer mcMMOPlayer) { - super(mcMMOPlayer, PrimarySkillType.HERBALISM); + public HerbalismManager(McMMOPlayer mmoPlayer) { + super(mmoPlayer, PrimarySkillType.HERBALISM); } public boolean canGreenThumbBlock(BlockState blockState) { - if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.HERBALISM_GREEN_THUMB)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.HERBALISM_GREEN_THUMB)) { return false; + } final Player player = getPlayer(); final ItemStack item = player.getInventory().getItemInMainHand(); @@ -85,8 +97,9 @@ public class HerbalismManager extends SkillManager { return false; } - if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.HERBALISM_SHROOM_THUMB)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.HERBALISM_SHROOM_THUMB)) { return false; + } Player player = getPlayer(); PlayerInventory inventory = player.getInventory(); @@ -121,15 +134,18 @@ public class HerbalismManager extends SkillManager { mmoPlayer.getPlayer().sendMessage("Bush Reward Multiplier: " + rewardByAge); } - int xpReward = ExperienceConfig.getInstance().getXp(PrimarySkillType.HERBALISM, blockState.getType()) + int xpReward = ExperienceConfig.getInstance() + .getXp(PrimarySkillType.HERBALISM, blockState.getType()) * rewardByAge; if (mmoPlayer.isDebugMode()) { mmoPlayer.getPlayer().sendMessage("Bush XP: " + xpReward); } - CheckBushAge checkBushAge = new CheckBushAge(blockState.getBlock(), mmoPlayer, xpReward); - mcMMO.p.getFoliaLib().getScheduler().runAtLocationLater(blockState.getLocation(), checkBushAge, 1); + CheckBushAge checkBushAge = new CheckBushAge(blockState.getBlock(), mmoPlayer, + xpReward); + mcMMO.p.getFoliaLib().getScheduler() + .runAtLocationLater(blockState.getLocation(), checkBushAge, 1); } } } @@ -163,14 +179,16 @@ 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); } public boolean canActivateAbility() { - return mmoPlayer.getToolPreparationMode(ToolType.HOE) && Permissions.greenTerra(getPlayer()); + return mmoPlayer.getToolPreparationMode(ToolType.HOE) && Permissions.greenTerra( + getPlayer()); } public boolean isGreenTerraActive() { @@ -184,7 +202,8 @@ public class HerbalismManager extends SkillManager { * @return the modified change in hunger for the event */ public int farmersDiet(int eventFoodLevel) { - return SkillUtils.handleFoodSkills(getPlayer(), eventFoodLevel, SubSkillType.HERBALISM_FARMERS_DIET); + return SkillUtils.handleFoodSkills(getPlayer(), eventFoodLevel, + SubSkillType.HERBALISM_FARMERS_DIET); } public void processGreenTerraBlockConversion(BlockState blockState) { @@ -221,6 +240,7 @@ public class HerbalismManager extends SkillManager { /** * Handles herbalism abilities and XP rewards from a BlockBreakEvent + * * @param blockBreakEvent The Block Break Event to process */ public void processHerbalismBlockBreakEvent(BlockBreakEvent blockBreakEvent) { @@ -258,8 +278,9 @@ public class HerbalismManager extends SkillManager { //Grab all broken blocks final HashSet brokenBlocks = getBrokenHerbalismBlocks(blockBreakEvent); - if (brokenBlocks.isEmpty()) + if (brokenBlocks.isEmpty()) { return; + } //Handle rewards, xp, ability interactions, etc processHerbalismOnBlocksBroken(blockBreakEvent, brokenBlocks); @@ -267,12 +288,15 @@ public class HerbalismManager extends SkillManager { /** * Process rewards for a set of plant blocks for Herbalism + * * @param blockBreakEvent the block break event * @param brokenPlants plant blocks to process */ - private void processHerbalismOnBlocksBroken(BlockBreakEvent blockBreakEvent, HashSet brokenPlants) { - if (blockBreakEvent.isCancelled()) + private void processHerbalismOnBlocksBroken(BlockBreakEvent blockBreakEvent, + HashSet brokenPlants) { + if (blockBreakEvent.isCancelled()) { return; + } final BlockState originalBreak = blockBreakEvent.getBlock().getState(); // TODO: Storing this boolean for no reason, refactor @@ -282,7 +306,8 @@ public class HerbalismManager extends SkillManager { if (Permissions.greenThumbPlant(getPlayer(), originalBreak.getType())) { if (mcMMO.p.getGeneralConfig().isGreenThumbReplantableCrop(originalBreak.getType())) { if (!getPlayer().isSneaking()) { - greenThumbActivated = processGreenThumbPlants(originalBreak, blockBreakEvent, isGreenTerraActive()); + greenThumbActivated = processGreenThumbPlants(originalBreak, blockBreakEvent, + isGreenTerraActive()); } } } @@ -298,7 +323,7 @@ public class HerbalismManager extends SkillManager { ArrayList delayedChorusBlocks = new ArrayList<>(); //Blocks that will be checked in future ticks HashSet noDelayPlantBlocks = new HashSet<>(); //Blocks that will be checked immediately - for(Block brokenPlant : brokenPlants) { + for (Block brokenPlant : brokenPlants) { /* * This check is to make XP bars appear to work properly with Chorus Trees by giving XP for the originalBreak immediately instead of later */ @@ -311,9 +336,11 @@ public class HerbalismManager extends SkillManager { } else { if (isChorusTree(brokenPlant.getType())) { //If its a chorus tree AND it was marked as true in the placestore then we add this block to the list of chorus blocks - delayedChorusBlocks.add(new BlockSnapshot(brokenPlant.getType(), brokenPlant)); + delayedChorusBlocks.add( + new BlockSnapshot(brokenPlant.getType(), brokenPlant)); } else { - noDelayPlantBlocks.add(brokenPlant); //If its not a chorus plant that was marked as unnatural but it was marked unnatural, put it in the nodelay list to be handled + noDelayPlantBlocks.add( + brokenPlant); //If its not a chorus plant that was marked as unnatural but it was marked unnatural, put it in the nodelay list to be handled } } } else if (isChorusTree(brokenPlant.getType())) { @@ -332,16 +359,19 @@ public class HerbalismManager extends SkillManager { if (!delayedChorusBlocks.isEmpty()) { //Check XP for chorus blocks - DelayedHerbalismXPCheckTask delayedHerbalismXPCheckTask = new DelayedHerbalismXPCheckTask(mmoPlayer, delayedChorusBlocks); + DelayedHerbalismXPCheckTask delayedHerbalismXPCheckTask = new DelayedHerbalismXPCheckTask( + mmoPlayer, delayedChorusBlocks); //Large delay because the tree takes a while to break - mcMMO.p.getFoliaLib().getScheduler().runAtEntity(mmoPlayer.getPlayer(), delayedHerbalismXPCheckTask); //Calculate Chorus XP + Bonus Drops 1 tick later + mcMMO.p.getFoliaLib().getScheduler().runAtEntity(mmoPlayer.getPlayer(), + delayedHerbalismXPCheckTask); //Calculate Chorus XP + Bonus Drops 1 tick later } } /** - * Check for double drops on a collection of broken blocks - * If a double drop has occurred, it will be marked here for bonus drops + * Check for double drops on a collection of broken blocks If a double drop has occurred, it + * will be marked here for bonus drops + * * @param player player who broke the blocks * @param brokenPlants the collection of broken plants */ @@ -353,7 +383,7 @@ public class HerbalismManager extends SkillManager { return; } - for(Block brokenPlant : brokenPlants) { + for (Block brokenPlant : brokenPlants) { BlockState brokenPlantState = brokenPlant.getState(); BlockData plantData = brokenPlantState.getBlockData(); @@ -388,7 +418,9 @@ public class HerbalismManager extends SkillManager { } /** - * Checks if BlockData is bizarre ageable, and we cannot trust that age for Herbalism rewards/XP reasons + * Checks if BlockData is bizarre ageable, and we cannot trust that age for Herbalism rewards/XP + * reasons + * * @param blockData target BlockData * @return returns true if the BlockData is a bizarre ageable for Herbalism XP / Rewards */ @@ -406,6 +438,7 @@ public class HerbalismManager extends SkillManager { /** * Mark a block for bonus drops. + * * @param block the block to mark */ public void markForBonusDrops(Block block) { @@ -416,6 +449,7 @@ public class HerbalismManager extends SkillManager { /** * Checks if a block is an ageable and if that ageable is fully mature + * * @param plantData target plant * @return returns true if the block is both an ageable and fully mature */ @@ -427,7 +461,7 @@ public class HerbalismManager extends SkillManager { int xpToReward = 0; int firstXpReward = -1; - for(Block brokenPlantBlock : brokenPlants) { + for (Block brokenPlantBlock : brokenPlants) { BlockState brokenBlockNewState = brokenPlantBlock.getState(); BlockData plantData = brokenBlockNewState.getBlockData(); @@ -437,9 +471,11 @@ public class HerbalismManager extends SkillManager { */ //If its a Crop we need to reward XP when its fully grown if (isAgeableAndFullyMature(plantData) && !isBizarreAgeable(plantData)) { - xpToReward += ExperienceConfig.getInstance().getXp(PrimarySkillType.HERBALISM, brokenBlockNewState.getType()); - if (firstXpReward == -1) + xpToReward += ExperienceConfig.getInstance() + .getXp(PrimarySkillType.HERBALISM, brokenBlockNewState.getType()); + if (firstXpReward == -1) { firstXpReward = xpToReward; + } } //Mark it as natural again as it is being broken @@ -452,15 +488,19 @@ public class HerbalismManager extends SkillManager { if (plantData instanceof Ageable plantAgeable) { if (isAgeableMature(plantAgeable) || isBizarreAgeable(plantData)) { - xpToReward += ExperienceConfig.getInstance().getXp(PrimarySkillType.HERBALISM, brokenBlockNewState.getType()); - if (firstXpReward == -1) + xpToReward += ExperienceConfig.getInstance() + .getXp(PrimarySkillType.HERBALISM, brokenBlockNewState.getType()); + if (firstXpReward == -1) { firstXpReward = xpToReward; + } } } else { - xpToReward += ExperienceConfig.getInstance().getXp(PrimarySkillType.HERBALISM, brokenPlantBlock.getType()); - if (firstXpReward == -1) + xpToReward += ExperienceConfig.getInstance() + .getXp(PrimarySkillType.HERBALISM, brokenPlantBlock.getType()); + if (firstXpReward == -1) { firstXpReward = xpToReward; + } } } } @@ -476,7 +516,8 @@ public class HerbalismManager extends SkillManager { if (firstBlock != null && ExperienceConfig.getInstance().limitXPOnTallPlants() && plantBreakLimits.containsKey(firstBlock.getType().getKey().getKey())) { - int limit = plantBreakLimits.get(firstBlock.getType().getKey().getKey()) * firstXpReward; + int limit = plantBreakLimits.get(firstBlock.getType().getKey().getKey()) + * firstXpReward; // Plant may be unnaturally tall, limit XP applyXpGain(Math.min(xpToReward, limit), XPGainReason.PVE, XPGainSource.SELF); } else { @@ -492,6 +533,7 @@ public class HerbalismManager extends SkillManager { /** * Award XP for any blocks that used to be something else but are now AIR + * * @param brokenPlants snapshot of broken blocks */ public void awardXPForBlockSnapshots(ArrayList brokenPlants) { @@ -502,12 +544,13 @@ public class HerbalismManager extends SkillManager { int xpToReward = 0; int blocksGivingXP = 0; - for(BlockSnapshot blockSnapshot : brokenPlants) { + for (BlockSnapshot blockSnapshot : brokenPlants) { final BlockState brokenBlockNewState = blockSnapshot.getBlockRef().getState(); //Remove metadata from the snapshot of blocks if (brokenBlockNewState.hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) { - brokenBlockNewState.removeMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, mcMMO.p); + brokenBlockNewState.removeMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, + mcMMO.p); } //If the block is not AIR that means it wasn't broken @@ -521,14 +564,16 @@ public class HerbalismManager extends SkillManager { } else { //TODO: Do we care about chorus flower age? //Calculate XP for the old type - xpToReward += ExperienceConfig.getInstance().getXp(PrimarySkillType.HERBALISM, blockSnapshot.getOldType()); + xpToReward += ExperienceConfig.getInstance() + .getXp(PrimarySkillType.HERBALISM, blockSnapshot.getOldType()); blocksGivingXP++; } } if (mmoPlayer.isDebugMode()) { - mmoPlayer.getPlayer().sendMessage("Chorus Plants checked for XP: "+brokenPlants.size()); - mmoPlayer.getPlayer().sendMessage("Valid Chorus Plant XP Gains: "+blocksGivingXP); + mmoPlayer.getPlayer() + .sendMessage("Chorus Plants checked for XP: " + brokenPlants.size()); + mmoPlayer.getPlayer().sendMessage("Valid Chorus Plant XP Gains: " + blocksGivingXP); } //Reward XP @@ -539,6 +584,7 @@ public class HerbalismManager extends SkillManager { /** * Process and return plant blocks from a BlockBreakEvent + * * @param blockBreakEvent target event * @return a set of plant-blocks that were broken as a result of this event */ @@ -561,41 +607,52 @@ public class HerbalismManager extends SkillManager { } private void addChorusTreeBrokenBlocks(Block currentBlock, Set traversed) { - if (!isChorusTree(currentBlock.getType())) + if (!isChorusTree(currentBlock.getType())) { return; + } // Prevent any infinite loops, who needs more than 256 chorus anyways - if (traversed.size() > 256) + if (traversed.size() > 256) { return; + } - if (!traversed.add(currentBlock)) + if (!traversed.add(currentBlock)) { return; + } //Grab all Blocks in the Tree - 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}) { addChorusTreeBrokenBlocks(currentBlock.getRelative(blockFace, 1), traversed); + } } - protected void addBrokenBlocksMultiBlockPlants(BlockState brokenBlock, Set brokenBlocks) { + protected void addBrokenBlocksMultiBlockPlants(BlockState brokenBlock, + Set brokenBlocks) { if (isChorusBranch(brokenBlock.getType())) { addChorusTreeBrokenBlocks(brokenBlock.getBlock(), brokenBlocks); } else if (isCactus(brokenBlock.getType())) { addCactusBlocks(brokenBlock.getBlock(), brokenBlocks); } else { - addBlocksBrokenAboveOrBelow(brokenBlock.getBlock(), brokenBlocks, mcMMO.getMaterialMapStore().isMultiBlockHangingPlant(brokenBlock.getType())); + addBlocksBrokenAboveOrBelow(brokenBlock.getBlock(), brokenBlocks, + mcMMO.getMaterialMapStore().isMultiBlockHangingPlant(brokenBlock.getType())); } } private void addCactusBlocks(Block currentBlock, Set traversed) { - if (!isCactus(currentBlock.getType())) + if (!isCactus(currentBlock.getType())) { return; + } if (traversed.size() > 4) // Max size 3 cactus + flower + { return; + } - if (!traversed.add(currentBlock)) + if (!traversed.add(currentBlock)) { return; + } addCactusBlocks(currentBlock.getRelative(BlockFace.UP), traversed); addCactusBlocks(currentBlock.getRelative(BlockFace.DOWN), traversed); @@ -614,7 +671,8 @@ public class HerbalismManager extends SkillManager { return blockType == Material.CHORUS_PLANT || blockType == Material.CHORUS_FLOWER; } - private void addBlocksBrokenAboveOrBelow(Block originBlock, Set brokenBlocks, boolean below) { + private void addBlocksBrokenAboveOrBelow(Block originBlock, Set brokenBlocks, + boolean below) { //Limit our search int maxHeight = 512; @@ -625,21 +683,24 @@ public class HerbalismManager extends SkillManager { final Block relativeBlock = originBlock.getRelative(relativeFace, y); //Abandon our search if the block isn't multi - if (isOneBlockPlant(relativeBlock.getType())) + if (isOneBlockPlant(relativeBlock.getType())) { break; + } brokenBlocks.add(relativeBlock); } } /** - * If the plant is considered a one block plant - * This is determined by seeing if it exists in a hard-coded collection of Multi-Block plants + * If the plant is considered a one block plant This is determined by seeing if it exists in a + * hard-coded collection of Multi-Block plants + * * @param material target plant material * @return true if the block is not contained in the collection of multi-block plants */ private boolean isOneBlockPlant(Material material) { - return !mcMMO.getMaterialMapStore().isMultiBlockPlant(material) && !mcMMO.getMaterialMapStore().isMultiBlockHangingPlant(material); + return !mcMMO.getMaterialMapStore().isMultiBlockPlant(material) + && !mcMMO.getMaterialMapStore().isMultiBlockHangingPlant(material); } /** @@ -661,7 +722,8 @@ public class HerbalismManager extends SkillManager { */ public boolean processGreenThumbBlocks(BlockState blockState) { if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.HERBALISM_GREEN_THUMB, mmoPlayer)) { - NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE_FAILED, "Herbalism.Ability.GTh.Fail"); + NotificationManager.sendPlayerInformation(getPlayer(), + NotificationType.SUBSKILL_MESSAGE_FAILED, "Herbalism.Ability.GTh.Fail"); return false; } @@ -679,10 +741,13 @@ public class HerbalismManager extends SkillManager { return false; } - final String materialConfigString = getMaterialConfigString(blockState.getBlockData().getMaterial()); - if (!TreasureConfig.getInstance().hylianMap.containsKey(materialConfigString)) + final String materialConfigString = getMaterialConfigString( + blockState.getBlockData().getMaterial()); + if (!TreasureConfig.getInstance().hylianMap.containsKey(materialConfigString)) { return false; - List treasures = TreasureConfig.getInstance().hylianMap.get(materialConfigString); + } + List treasures = TreasureConfig.getInstance().hylianMap.get( + materialConfigString); if (treasures.isEmpty()) { return false; @@ -692,13 +757,16 @@ public class HerbalismManager extends SkillManager { for (HylianTreasure treasure : treasures) { if (skillLevel >= treasure.getDropLevel() - && ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.HERBALISM, mmoPlayer, treasure.getDropChance())) { + && ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.HERBALISM, + mmoPlayer, treasure.getDropChance())) { if (!EventUtils.simulateBlockBreak(blockState.getBlock(), mmoPlayer.getPlayer())) { return false; } blockState.setType(Material.AIR); - ItemUtils.spawnItem(getPlayer(), centerOfBlock, treasure.getDrop(), ItemSpawnReason.HYLIAN_LUCK_TREASURE); - NotificationManager.sendPlayerInformation(mmoPlayer.getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Herbalism.HylianLuck"); + ItemUtils.spawnItem(getPlayer(), centerOfBlock, treasure.getDrop(), + ItemSpawnReason.HYLIAN_LUCK_TREASURE); + NotificationManager.sendPlayerInformation(mmoPlayer.getPlayer(), + NotificationType.SUBSKILL_MESSAGE, "Herbalism.HylianLuck"); return true; } } @@ -713,14 +781,18 @@ public class HerbalismManager extends SkillManager { */ public boolean processShroomThumb(BlockState blockState) { PlayerInventory playerInventory = getPlayer().getInventory(); - + if (!playerInventory.contains(Material.BROWN_MUSHROOM, 1)) { - NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.REQUIREMENTS_NOT_MET, "Skills.NeedMore", StringUtils.getPrettyMaterialString(Material.BROWN_MUSHROOM)); + NotificationManager.sendPlayerInformation(getPlayer(), + NotificationType.REQUIREMENTS_NOT_MET, "Skills.NeedMore", + StringUtils.getPrettyMaterialString(Material.BROWN_MUSHROOM)); return false; } if (!playerInventory.contains(Material.RED_MUSHROOM, 1)) { - NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.REQUIREMENTS_NOT_MET, "Skills.NeedMore", StringUtils.getPrettyMaterialString(Material.RED_MUSHROOM)); + NotificationManager.sendPlayerInformation(getPlayer(), + NotificationType.REQUIREMENTS_NOT_MET, "Skills.NeedMore", + StringUtils.getPrettyMaterialString(Material.RED_MUSHROOM)); return false; } @@ -729,7 +801,8 @@ public class HerbalismManager extends SkillManager { getPlayer().updateInventory(); if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.HERBALISM_SHROOM_THUMB, mmoPlayer)) { - NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE_FAILED, "Herbalism.Ability.ShroomThumb.Fail"); + NotificationManager.sendPlayerInformation(getPlayer(), + NotificationType.SUBSKILL_MESSAGE_FAILED, "Herbalism.Ability.ShroomThumb.Fail"); return false; } @@ -738,14 +811,20 @@ public class HerbalismManager extends SkillManager { /** * Starts the delayed replant task and turns + * * @param desiredCropAge the desired age of the crop * @param blockBreakEvent the {@link BlockBreakEvent} this crop was involved in * @param cropState the {@link BlockState} of the crop */ - private void startReplantTask(int desiredCropAge, BlockBreakEvent blockBreakEvent, BlockState cropState, boolean isImmature) { + private void startReplantTask(int desiredCropAge, BlockBreakEvent blockBreakEvent, + BlockState cropState, boolean isImmature) { //Mark the plant as recently replanted to avoid accidental breakage - mcMMO.p.getFoliaLib().getScheduler().runAtLocationLater(blockBreakEvent.getBlock().getLocation(), new DelayedCropReplant(blockBreakEvent, cropState, desiredCropAge, isImmature), 2 * Misc.TICK_CONVERSION_FACTOR); - blockBreakEvent.getBlock().setMetadata(MetadataConstants.METADATA_KEY_REPLANT, new RecentlyReplantedCropMeta(mcMMO.p, true)); + mcMMO.p.getFoliaLib().getScheduler() + .runAtLocationLater(blockBreakEvent.getBlock().getLocation(), + new DelayedCropReplant(blockBreakEvent, cropState, desiredCropAge, + isImmature), 2 * Misc.TICK_CONVERSION_FACTOR); + blockBreakEvent.getBlock().setMetadata(MetadataConstants.METADATA_KEY_REPLANT, + new RecentlyReplantedCropMeta(mcMMO.p, true)); } /** @@ -754,10 +833,12 @@ public class HerbalismManager extends SkillManager { * @param blockState The {@link BlockState} to check ability activation for * @param greenTerra boolean to determine if greenTerra is active or not */ - private boolean processGreenThumbPlants(@NotNull BlockState blockState, @NotNull BlockBreakEvent blockBreakEvent, - boolean greenTerra) { + private boolean processGreenThumbPlants(@NotNull BlockState blockState, + @NotNull BlockBreakEvent blockBreakEvent, + boolean greenTerra) { if (!ItemUtils.isHoe(blockBreakEvent.getPlayer().getInventory().getItemInMainHand()) - && !ItemUtils.isAxe(blockBreakEvent.getPlayer().getInventory().getItemInMainHand())) { + && !ItemUtils.isAxe( + blockBreakEvent.getPlayer().getInventory().getItemInMainHand())) { return false; } @@ -794,7 +875,8 @@ public class HerbalismManager extends SkillManager { return false; } - if (!greenTerra && !ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.HERBALISM_GREEN_THUMB, mmoPlayer)) { + if (!greenTerra && !ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.HERBALISM_GREEN_THUMB, + mmoPlayer)) { return false; } @@ -802,7 +884,8 @@ public class HerbalismManager extends SkillManager { return false; } - if (EventUtils.callSubSkillBlockEvent(player, SubSkillType.HERBALISM_GREEN_THUMB, blockState.getBlock()) + if (EventUtils.callSubSkillBlockEvent(player, SubSkillType.HERBALISM_GREEN_THUMB, + blockState.getBlock()) .isCancelled()) { return false; } else { @@ -819,7 +902,8 @@ public class HerbalismManager extends SkillManager { } } - private boolean processGrowingPlants(BlockState blockState, Ageable ageable, BlockBreakEvent blockBreakEvent, boolean greenTerra) { + private boolean processGrowingPlants(BlockState blockState, Ageable ageable, + BlockBreakEvent blockBreakEvent, boolean greenTerra) { //This check is needed if (isBizarreAgeable(ageable)) { return false; @@ -843,7 +927,7 @@ public class HerbalismManager extends SkillManager { case "carrots": case "wheat": - finalAge = getGreenThumbStage(greenTerra); + finalAge = getGreenThumbStage(greenTerra); break; case "beetroots": @@ -871,16 +955,16 @@ public class HerbalismManager extends SkillManager { return false; } - //Start the delayed replant startReplantTask(finalAge, blockBreakEvent, blockState, false); return true; } private int getGreenThumbStage(boolean greenTerraActive) { - if (greenTerraActive) + if (greenTerraActive) { return Math.min(RankUtils.getHighestRank(SubSkillType.HERBALISM_GREEN_THUMB), RankUtils.getRank(getPlayer(), SubSkillType.HERBALISM_GREEN_THUMB) + 1); + } return RankUtils.getRank(getPlayer(), SubSkillType.HERBALISM_GREEN_THUMB); } diff --git a/src/main/java/com/gmail/nossr50/skills/maces/MacesManager.java b/src/main/java/com/gmail/nossr50/skills/maces/MacesManager.java index fc8f23575..0dbade619 100644 --- a/src/main/java/com/gmail/nossr50/skills/maces/MacesManager.java +++ b/src/main/java/com/gmail/nossr50/skills/maces/MacesManager.java @@ -11,6 +11,7 @@ import com.gmail.nossr50.util.player.NotificationManager; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.ParticleEffectUtils; import com.gmail.nossr50.util.skills.RankUtils; +import java.util.Locale; import org.bukkit.NamespacedKey; import org.bukkit.Registry; import org.bukkit.entity.LivingEntity; @@ -19,8 +20,6 @@ import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Locale; - public class MacesManager extends SkillManager { private static @Nullable PotionEffectType slowEffectType; @@ -41,8 +40,9 @@ public class MacesManager extends SkillManager { * @return the Crush damage bonus. */ public double getCrushDamage() { - if (!Permissions.canUseSubSkill(mmoPlayer.getPlayer(), SubSkillType.MACES_CRUSH)) + if (!Permissions.canUseSubSkill(mmoPlayer.getPlayer(), SubSkillType.MACES_CRUSH)) { return 0; + } int rank = RankUtils.getRank(getPlayer(), SubSkillType.MACES_CRUSH); @@ -84,7 +84,8 @@ public class MacesManager extends SkillManager { double crippleOdds = (mcMMO.p.getAdvancedConfig().getCrippleChanceToApplyOnHit(crippleRank) * mmoPlayer.getAttackStrength()); - if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.MACES, mmoPlayer, crippleOdds)) { + if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.MACES, mmoPlayer, + crippleOdds)) { if (mmoPlayer.useChatNotifications()) { NotificationManager.sendPlayerInformation(mmoPlayer.getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Maces.SubSkill.Cripple.Activated"); 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 95b853548..c4f8a18b4 100644 --- a/src/main/java/com/gmail/nossr50/skills/mining/BlastMining.java +++ b/src/main/java/com/gmail/nossr50/skills/mining/BlastMining.java @@ -21,30 +21,35 @@ public class BlastMining { } public static int getDemolitionExpertUnlockLevel() { - 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; } public static int getBiggerBombsUnlockLevel() { - 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; } - public static boolean processBlastMiningExplosion(EntityDamageByEntityEvent event, TNTPrimed tnt, Player defender) { - if (!tnt.hasMetadata(MetadataConstants.METADATA_KEY_TRACKED_TNT) || !UserManager.hasPlayerDataKey(defender)) { + public static boolean processBlastMiningExplosion(EntityDamageByEntityEvent event, + TNTPrimed tnt, Player defender) { + if (!tnt.hasMetadata(MetadataConstants.METADATA_KEY_TRACKED_TNT) + || !UserManager.hasPlayerDataKey(defender)) { return false; } // We can make this assumption because we (should) be the only ones using this exact metadata - Player player = mcMMO.p.getServer().getPlayerExact(tnt.getMetadata(MetadataConstants.METADATA_KEY_TRACKED_TNT).get(0).asString()); + Player player = mcMMO.p.getServer().getPlayerExact( + tnt.getMetadata(MetadataConstants.METADATA_KEY_TRACKED_TNT).get(0).asString()); if (!(player != null && player.equals(defender))) { return false; @@ -54,7 +59,7 @@ public class BlastMining { return false; } - final MiningManager miningManager = UserManager.getPlayer(defender).getMiningManager(); + final MiningManager miningManager = UserManager.getPlayer(defender).getMiningManager(); if (!miningManager.canUseDemolitionsExpertise()) { return false; 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 05808ae74..3044d87c4 100644 --- a/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java +++ b/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java @@ -1,5 +1,8 @@ package com.gmail.nossr50.skills.mining; +import static com.gmail.nossr50.util.ItemUtils.isPickaxe; +import static com.gmail.nossr50.util.Misc.getBlockCenter; + import com.gmail.nossr50.api.ItemSpawnReason; import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.datatypes.experience.XPGainReason; @@ -12,12 +15,22 @@ import com.gmail.nossr50.datatypes.skills.SuperAbilityType; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.runnables.skills.AbilityCooldownTask; import com.gmail.nossr50.skills.SkillManager; -import com.gmail.nossr50.util.*; +import com.gmail.nossr50.util.BlockUtils; +import com.gmail.nossr50.util.EventUtils; +import com.gmail.nossr50.util.ItemUtils; +import com.gmail.nossr50.util.MetadataConstants; +import com.gmail.nossr50.util.Misc; +import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.NotificationManager; import com.gmail.nossr50.util.random.Probability; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.skills.SkillUtils; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Locale; +import java.util.Set; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockState; @@ -29,11 +42,6 @@ import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import java.util.*; - -import static com.gmail.nossr50.util.ItemUtils.isPickaxe; -import static com.gmail.nossr50.util.Misc.getBlockCenter; - public class MiningManager extends SkillManager { private static final String BUDDING_AMETHYST = "budding_amethyst"; @@ -41,17 +49,20 @@ public class MiningManager extends SkillManager { Material.INFESTED_COBBLESTONE, Material.INFESTED_DEEPSLATE, Material.INFESTED_STONE, Material.INFESTED_STONE_BRICKS, Material.INFESTED_CRACKED_STONE_BRICKS, Material.INFESTED_CHISELED_STONE_BRICKS, Material.INFESTED_MOSSY_STONE_BRICKS); - private final static Set INFESTED_BLOCKS = Set.of("infested_stone", "infested_cobblestone", + private final static Set INFESTED_BLOCKS = Set.of("infested_stone", + "infested_cobblestone", "infested_stone_bricks", "infested_cracked_stone_bricks", "infested_mossy_stone_bricks", "infested_chiseled_stone_bricks", "infested_deepslate"); - public MiningManager(@NotNull McMMOPlayer mcMMOPlayer) { - super(mcMMOPlayer, PrimarySkillType.MINING); + public MiningManager(@NotNull McMMOPlayer mmoPlayer) { + super(mmoPlayer, PrimarySkillType.MINING); } 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()); @@ -62,12 +73,14 @@ public class MiningManager extends SkillManager { return canUseBlastMining() && player.isSneaking() - && (isPickaxe(getPlayer().getInventory().getItemInMainHand()) || isDetonatorInHand(player)) + && (isPickaxe(getPlayer().getInventory().getItemInMainHand()) || isDetonatorInHand( + player)) && Permissions.remoteDetonation(player); } private static boolean isDetonatorInHand(Player player) { - return player.getInventory().getItemInMainHand().getType() == mcMMO.p.getGeneralConfig().getDetonatorItem(); + return player.getInventory().getItemInMainHand().getType() == mcMMO.p.getGeneralConfig() + .getDetonatorItem(); } public boolean canUseBlastMining() { @@ -76,10 +89,12 @@ 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()); + return getSkillLevel() >= BlastMining.getBiggerBombsUnlockLevel() + && Permissions.biggerBombs(getPlayer()); } public boolean canDoubleDrop() { @@ -105,23 +120,30 @@ public class MiningManager extends SkillManager { public void miningBlockCheck(Block block) { Player player = getPlayer(); - applyXpGain(ExperienceConfig.getInstance().getXp(PrimarySkillType.MINING, block), XPGainReason.PVE); + applyXpGain(ExperienceConfig.getInstance().getXp(PrimarySkillType.MINING, block), + XPGainReason.PVE); if (!Permissions.isSubSkillEnabled(player, SubSkillType.MINING_DOUBLE_DROPS)) { return; } if (mmoPlayer.getAbilityMode(mcMMO.p.getSkillTools().getSuperAbility(skill))) { - SkillUtils.handleDurabilityChange(getPlayer().getInventory().getItemInMainHand(), mcMMO.p.getGeneralConfig().getAbilityToolDamage()); + SkillUtils.handleDurabilityChange(getPlayer().getInventory().getItemInMainHand(), + mcMMO.p.getGeneralConfig().getAbilityToolDamage()); } - if (!mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.MINING, block.getType()) || !canDoubleDrop()) + if (!mcMMO.p.getGeneralConfig() + .getDoubleDropsEnabled(PrimarySkillType.MINING, block.getType()) + || !canDoubleDrop()) { return; + } - boolean silkTouch = player.getInventory().getItemInMainHand().containsEnchantment(Enchantment.SILK_TOUCH); + boolean silkTouch = player.getInventory().getItemInMainHand() + .containsEnchantment(Enchantment.SILK_TOUCH); - if (silkTouch && !mcMMO.p.getAdvancedConfig().getDoubleDropSilkTouchEnabled()) + if (silkTouch && !mcMMO.p.getAdvancedConfig().getDoubleDropSilkTouchEnabled()) { return; + } //Mining mastery allows for a chance of triple drops if (canMotherLode()) { @@ -159,7 +181,8 @@ public class MiningManager extends SkillManager { */ public void remoteDetonation() { final Player player = getPlayer(); - final Block targetBlock = player.getTargetBlock(BlockUtils.getTransparentBlocks(), BlastMining.MAXIMUM_REMOTE_DETONATION_DISTANCE); + final Block targetBlock = player.getTargetBlock(BlockUtils.getTransparentBlocks(), + BlastMining.MAXIMUM_REMOTE_DETONATION_DISTANCE); //Blast mining cooldown check needs to be first so the player can be messaged if (!blastMiningCooldownOver() @@ -170,7 +193,8 @@ public class MiningManager extends SkillManager { final TNTPrimed tnt = player.getWorld().spawn(targetBlock.getLocation(), TNTPrimed.class); - NotificationManager.sendPlayerInformation(player, NotificationType.SUPER_ABILITY, "Mining.Blast.Boom"); + NotificationManager.sendPlayerInformation(player, NotificationType.SUPER_ABILITY, + "Mining.Blast.Boom"); tnt.setMetadata(MetadataConstants.METADATA_KEY_TRACKED_TNT, mmoPlayer.getPlayerMetadata()); tnt.setFuseTicks(0); @@ -195,8 +219,9 @@ public class MiningManager extends SkillManager { * @param event The {@link EntityExplodeEvent} */ public void blastMiningDropProcessing(float yield, EntityExplodeEvent event) { - if (yield == 0) + if (yield == 0) { return; + } var increasedYieldFromBonuses = yield + (yield * getOreBonus()); // Strip out only stuff that gives mining XP @@ -204,8 +229,9 @@ public class MiningManager extends SkillManager { final List notOres = new ArrayList<>(); for (Block targetBlock : event.blockList()) { - if(mcMMO.getUserBlockTracker().isIneligible(targetBlock)) + if (mcMMO.getUserBlockTracker().isIneligible(targetBlock)) { continue; + } if (ExperienceConfig.getInstance().getXp(PrimarySkillType.MINING, targetBlock) != 0) { if (BlockUtils.isOre(targetBlock) && !(targetBlock instanceof Container)) { @@ -221,9 +247,10 @@ public class MiningManager extends SkillManager { int xp = 0; int dropMultiplier = getDropMultiplier(); - for(Block block : notOres) { - if (isDropIllegal(block.getType())) + for (Block block : notOres) { + if (isDropIllegal(block.getType())) { continue; + } if (block.getType().isItem() && Probability.ofPercent(10).evaluate()) { ItemUtils.spawnItem(getPlayer(), @@ -243,11 +270,13 @@ public class MiningManager extends SkillManager { // Always give XP for every ore destroyed xp += ExperienceConfig.getInstance().getXp(PrimarySkillType.MINING, block); - while(currentOreYield > 0) { + while (currentOreYield > 0) { if (Probability.ofValue(currentOreYield).evaluate()) { - Collection oreDrops = isPickaxe(mmoPlayer.getPlayer().getInventory().getItemInMainHand()) - ? block.getDrops(mmoPlayer.getPlayer().getInventory().getItemInMainHand()) - : List.of(new ItemStack(block.getType())); + Collection oreDrops = + isPickaxe(mmoPlayer.getPlayer().getInventory().getItemInMainHand()) + ? block.getDrops( + mmoPlayer.getPlayer().getInventory().getItemInMainHand()) + : List.of(new ItemStack(block.getType())); ItemUtils.spawnItems(getPlayer(), getBlockCenter(block), oreDrops, BLAST_MINING_BLACKLIST, ItemSpawnReason.BLAST_MINING_ORES); @@ -273,8 +302,8 @@ public class MiningManager extends SkillManager { } /** - * Checks if it would be illegal (in vanilla) to obtain the block - * Certain things should never drop (such as budding_amethyst, infested blocks or spawners) + * Checks if it would be illegal (in vanilla) to obtain the block Certain things should never + * drop (such as budding_amethyst, infested blocks or spawners) * * @param material target material * @return true if it's not legal to get the block through normal gameplay @@ -380,7 +409,9 @@ public class MiningManager extends SkillManager { if (timeRemaining > 0) { //getPlayer().sendMessage(LocaleLoader.getString("Skills.TooTired", timeRemaining)); - NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.ABILITY_COOLDOWN, "Skills.TooTired", String.valueOf(timeRemaining)); + NotificationManager.sendPlayerInformation(getPlayer(), + NotificationType.ABILITY_COOLDOWN, "Skills.TooTired", + String.valueOf(timeRemaining)); return false; } diff --git a/src/main/java/com/gmail/nossr50/skills/repair/ArcaneForging.java b/src/main/java/com/gmail/nossr50/skills/repair/ArcaneForging.java index 05bcfb160..1729627c8 100644 --- a/src/main/java/com/gmail/nossr50/skills/repair/ArcaneForging.java +++ b/src/main/java/com/gmail/nossr50/skills/repair/ArcaneForging.java @@ -4,6 +4,8 @@ import com.gmail.nossr50.mcMMO; public class ArcaneForging { - public static boolean arcaneForgingDowngrades = mcMMO.p.getAdvancedConfig().getArcaneForgingDowngradeEnabled(); - public static boolean arcaneForgingEnchantLoss = mcMMO.p.getAdvancedConfig().getArcaneForgingEnchantLossEnabled(); + public static boolean arcaneForgingDowngrades = mcMMO.p.getAdvancedConfig() + .getArcaneForgingDowngradeEnabled(); + public static boolean arcaneForgingEnchantLoss = mcMMO.p.getAdvancedConfig() + .getArcaneForgingEnchantLossEnabled(); } 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 36ba8cdc5..b8d86ca59 100644 --- a/src/main/java/com/gmail/nossr50/skills/repair/Repair.java +++ b/src/main/java/com/gmail/nossr50/skills/repair/Repair.java @@ -5,8 +5,10 @@ import com.gmail.nossr50.mcMMO; import org.bukkit.Material; public class Repair { - public static int repairMasteryMaxBonusLevel = mcMMO.p.getAdvancedConfig().getMaxBonusLevel(SubSkillType.REPAIR_REPAIR_MASTERY); - public static double repairMasteryMaxBonus = mcMMO.p.getAdvancedConfig().getRepairMasteryMaxBonus(); + public static int repairMasteryMaxBonusLevel = mcMMO.p.getAdvancedConfig() + .getMaxBonusLevel(SubSkillType.REPAIR_REPAIR_MASTERY); + public static double repairMasteryMaxBonus = mcMMO.p.getAdvancedConfig() + .getRepairMasteryMaxBonus(); - public static Material anvilMaterial = mcMMO.p.getGeneralConfig().getRepairAnvilMaterial(); + public static Material anvilMaterial = mcMMO.p.getGeneralConfig().getRepairAnvilMaterial(); } 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 6094a7277..0963d9554 100644 --- a/src/main/java/com/gmail/nossr50/skills/repair/RepairManager.java +++ b/src/main/java/com/gmail/nossr50/skills/repair/RepairManager.java @@ -20,6 +20,11 @@ import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.sounds.SoundManager; import com.gmail.nossr50.util.sounds.SoundType; import com.gmail.nossr50.util.text.StringUtils; +import java.util.Arrays; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Objects; +import java.util.Optional; import org.bukkit.Material; import org.bukkit.SoundCategory; import org.bukkit.enchantments.Enchantment; @@ -27,18 +32,12 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; -import java.util.Arrays; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Objects; -import java.util.Optional; - public class RepairManager extends SkillManager { private boolean placedAnvil; - private int lastClick; + private int lastClick; - public RepairManager(McMMOPlayer mcMMOPlayer) { - super(mcMMOPlayer, PrimarySkillType.REPAIR); + public RepairManager(McMMOPlayer mmoPlayer) { + super(mmoPlayer, PrimarySkillType.REPAIR); } /** @@ -52,11 +51,13 @@ public class RepairManager extends SkillManager { } if (mcMMO.p.getGeneralConfig().getRepairAnvilMessagesEnabled()) { - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, "Repair.Listener.Anvil"); + NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, + "Repair.Listener.Anvil"); } if (mcMMO.p.getGeneralConfig().getRepairAnvilPlaceSoundsEnabled()) { - SoundManager.sendCategorizedSound(player, player.getLocation(), SoundType.ANVIL, SoundCategory.BLOCKS); + SoundManager.sendCategorizedSound(player, player.getLocation(), SoundType.ANVIL, + SoundCategory.BLOCKS); } togglePlacedAnvil(); @@ -68,26 +69,30 @@ public class RepairManager extends SkillManager { if (item.getItemMeta() != null) { if (item.getItemMeta().hasCustomModelData()) { if (!mcMMO.p.getCustomItemSupportConfig().isCustomRepairAllowed()) { - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE_FAILED, + NotificationManager.sendPlayerInformation(player, + NotificationType.SUBSKILL_MESSAGE_FAILED, "Anvil.Repair.Reject.CustomModelData"); return; } } if (item.getItemMeta().isUnbreakable()) { - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE_FAILED, "Anvil.Unbreakable"); + NotificationManager.sendPlayerInformation(player, + NotificationType.SUBSKILL_MESSAGE_FAILED, "Anvil.Unbreakable"); return; } } // Permissions checks on material and item types if (!Permissions.repairMaterialType(player, repairable.getRepairMaterialType())) { - NotificationManager.sendPlayerInformation(player, NotificationType.NO_PERMISSION, "mcMMO.NoPermission"); + NotificationManager.sendPlayerInformation(player, NotificationType.NO_PERMISSION, + "mcMMO.NoPermission"); return; } if (!Permissions.repairItemType(player, repairable.getRepairItemType())) { - NotificationManager.sendPlayerInformation(player, NotificationType.NO_PERMISSION, "mcMMO.NoPermission"); + NotificationManager.sendPlayerInformation(player, NotificationType.NO_PERMISSION, + "mcMMO.NoPermission"); return; } @@ -96,7 +101,10 @@ public class RepairManager extends SkillManager { // Level check if (skillLevel < minimumRepairableLevel) { - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE_FAILED, "Repair.Skills.Adept", String.valueOf(minimumRepairableLevel), StringUtils.getPrettyMaterialString(item.getType())); + NotificationManager.sendPlayerInformation(player, + NotificationType.SUBSKILL_MESSAGE_FAILED, "Repair.Skills.Adept", + String.valueOf(minimumRepairableLevel), + StringUtils.getPrettyMaterialString(item.getType())); return; } @@ -109,23 +117,29 @@ public class RepairManager extends SkillManager { // Do not repair if at full durability if (startDurability <= 0) { - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE_FAILED, "Repair.Skills.FullDurability"); + NotificationManager.sendPlayerInformation(player, + NotificationType.SUBSKILL_MESSAGE_FAILED, "Repair.Skills.FullDurability"); return; } // Check if they have the proper material to repair with if (!inventory.contains(repairMaterial)) { - String prettyName = repairable.getRepairMaterialPrettyName() == null ? StringUtils.getPrettyMaterialString(repairMaterial) : repairable.getRepairMaterialPrettyName(); + String prettyName = repairable.getRepairMaterialPrettyName() == null + ? StringUtils.getPrettyMaterialString(repairMaterial) + : repairable.getRepairMaterialPrettyName(); String materialsNeeded = ""; - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE_FAILED, "Skills.NeedMore.Extra", prettyName, materialsNeeded); + NotificationManager.sendPlayerInformation(player, + NotificationType.SUBSKILL_MESSAGE_FAILED, "Skills.NeedMore.Extra", prettyName, + materialsNeeded); return; } // Do not repair stacked items if (item.getAmount() != 1) { - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE_FAILED, "Repair.Skills.StackedItems"); + NotificationManager.sendPlayerInformation(player, + NotificationType.SUBSKILL_MESSAGE_FAILED, "Repair.Skills.StackedItems"); return; } @@ -134,8 +148,10 @@ public class RepairManager extends SkillManager { // Lets get down to business, // To defeat, the huns. - int baseRepairAmount = repairable.getBaseRepairDurability(item); // Did they send me daughters? - short newDurability = repairCalculate(startDurability, baseRepairAmount); // When I asked for sons? + int baseRepairAmount = repairable.getBaseRepairDurability( + item); // Did they send me daughters? + short newDurability = repairCalculate(startDurability, + baseRepairAmount); // When I asked for sons? // toRemove should be refreshed before the event call. toRemove = inventory.getItem(inventory.first(repairMaterial)).clone(); @@ -156,11 +172,15 @@ public class RepairManager extends SkillManager { // Fail out with "you need material" if we don't find a suitable alternative. if (possibleMaterial.isEmpty()) { - String prettyName = repairable.getRepairMaterialPrettyName() == null ? StringUtils.getPrettyMaterialString(repairMaterial) : repairable.getRepairMaterialPrettyName(); + String prettyName = repairable.getRepairMaterialPrettyName() == null + ? StringUtils.getPrettyMaterialString(repairMaterial) + : repairable.getRepairMaterialPrettyName(); String materialsNeeded = ""; - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE_FAILED, "Skills.NeedMore.Extra", prettyName, materialsNeeded); + NotificationManager.sendPlayerInformation(player, + NotificationType.SUBSKILL_MESSAGE_FAILED, "Skills.NeedMore.Extra", + prettyName, materialsNeeded); return; } @@ -170,12 +190,14 @@ public class RepairManager extends SkillManager { } // Call event - if (EventUtils.callRepairCheckEvent(player, (short) (startDurability - newDurability), toRemove, item).isCancelled()) { + if (EventUtils.callRepairCheckEvent(player, (short) (startDurability - newDurability), + toRemove, item).isCancelled()) { return; } // Handle the enchants - if (ArcaneForging.arcaneForgingEnchantLoss && !Permissions.hasRepairEnchantBypassPerk(player)) { + if (ArcaneForging.arcaneForgingEnchantLoss && !Permissions.hasRepairEnchantBypassPerk( + player)) { addEnchants(item); } @@ -185,22 +207,27 @@ public class RepairManager extends SkillManager { inventory.removeItem(toRemove); // Give out XP like candy - applyXpGain((float) ((getPercentageRepaired(startDurability, newDurability, repairable.getMaximumDurability()) - * repairable.getXpMultiplier()) - * ExperienceConfig.getInstance().getRepairXPBase() - * ExperienceConfig.getInstance().getRepairXP(repairable.getRepairMaterialType())), XPGainReason.PVE); + applyXpGain((float) ((getPercentageRepaired(startDurability, newDurability, + repairable.getMaximumDurability()) + * repairable.getXpMultiplier()) + * ExperienceConfig.getInstance().getRepairXPBase() + * ExperienceConfig.getInstance().getRepairXP(repairable.getRepairMaterialType())), + XPGainReason.PVE); // BWONG BWONG BWONG if (mcMMO.p.getGeneralConfig().getRepairAnvilUseSoundsEnabled()) { - SoundManager.sendCategorizedSound(player, player.getLocation(), SoundType.ANVIL, SoundCategory.BLOCKS); - SoundManager.sendCategorizedSound(player, player.getLocation(), SoundType.ITEM_BREAK, SoundCategory.PLAYERS); + SoundManager.sendCategorizedSound(player, player.getLocation(), SoundType.ANVIL, + SoundCategory.BLOCKS); + SoundManager.sendCategorizedSound(player, player.getLocation(), SoundType.ITEM_BREAK, + SoundCategory.PLAYERS); } // Repair the item! item.setDurability(newDurability); } - private float getPercentageRepaired(short startDurability, short newDurability, short totalDurability) { + private float getPercentageRepaired(short startDurability, short newDurability, + short totalDurability) { return ((startDurability - newDurability) / (float) totalDurability); } @@ -213,7 +240,8 @@ public class RepairManager extends SkillManager { Player player = getPlayer(); long lastUse = getLastAnvilUse(); - if (!SkillUtils.cooldownExpired(lastUse, 3) || !mcMMO.p.getGeneralConfig().getRepairConfirmRequired()) { + if (!SkillUtils.cooldownExpired(lastUse, 3) || !mcMMO.p.getGeneralConfig() + .getRepairConfirmRequired()) { return true; } @@ -222,7 +250,8 @@ public class RepairManager extends SkillManager { } actualizeLastAnvilUse(); - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, "Skills.ConfirmOrCancel", LocaleLoader.getString("Repair.Pretty.Name")); + NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, + "Skills.ConfirmOrCancel", LocaleLoader.getString("Repair.Pretty.Name")); return false; } @@ -242,7 +271,8 @@ public class RepairManager extends SkillManager { * @return The chance of keeping the enchantment */ public double getKeepEnchantChance() { - return mcMMO.p.getAdvancedConfig().getArcaneForgingKeepEnchantsChance(getArcaneForgingRank()); + return mcMMO.p.getAdvancedConfig() + .getArcaneForgingKeepEnchantsChance(getArcaneForgingRank()); } /** @@ -302,14 +332,16 @@ public class RepairManager extends SkillManager { && RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.REPAIR_REPAIR_MASTERY)) { double maxBonusCalc = Repair.repairMasteryMaxBonus / 100.0D; - double skillLevelBonusCalc = (Repair.repairMasteryMaxBonus / Repair.repairMasteryMaxBonusLevel) * (getSkillLevel() / 100.0D); + double skillLevelBonusCalc = + (Repair.repairMasteryMaxBonus / Repair.repairMasteryMaxBonusLevel) * ( + getSkillLevel() / 100.0D); double bonus = repairAmount * Math.min(skillLevelBonusCalc, maxBonusCalc); - repairAmount += bonus; } - if (Permissions.isSubSkillEnabled(player, SubSkillType.REPAIR_SUPER_REPAIR) && checkPlayerProcRepair()) { + if (Permissions.isSubSkillEnabled(player, SubSkillType.REPAIR_SUPER_REPAIR) + && checkPlayerProcRepair()) { repairAmount *= 2.0D; } @@ -326,11 +358,13 @@ 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 (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.REPAIR_SUPER_REPAIR, mmoPlayer)) { - NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Repair.Skills.FeltEasy"); + NotificationManager.sendPlayerInformation(getPlayer(), + NotificationType.SUBSKILL_MESSAGE, "Repair.Skills.FeltEasy"); return true; } @@ -352,16 +386,19 @@ public class RepairManager extends SkillManager { } if (Permissions.arcaneBypass(player)) { - NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Repair.Arcane.Perfect"); + NotificationManager.sendPlayerInformation(getPlayer(), + NotificationType.SUBSKILL_MESSAGE, "Repair.Arcane.Perfect"); return; } - if (getArcaneForgingRank() == 0 || !Permissions.isSubSkillEnabled(player, SubSkillType.REPAIR_ARCANE_FORGING)) { + if (getArcaneForgingRank() == 0 || !Permissions.isSubSkillEnabled(player, + SubSkillType.REPAIR_ARCANE_FORGING)) { for (Enchantment enchant : enchants.keySet()) { item.removeEnchantment(enchant); } - NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE_FAILED, "Repair.Arcane.Lost"); + NotificationManager.sendPlayerInformation(getPlayer(), + NotificationType.SUBSKILL_MESSAGE_FAILED, "Repair.Arcane.Lost"); return; } @@ -380,10 +417,12 @@ public class RepairManager extends SkillManager { Enchantment enchantment = enchant.getKey(); - if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.REPAIR, mmoPlayer, getKeepEnchantChance())) { + if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.REPAIR, mmoPlayer, + getKeepEnchantChance())) { if (ArcaneForging.arcaneForgingDowngrades && enchantLevel > 1 - && (!ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.REPAIR, mmoPlayer, 100 - getDowngradeEnchantChance()))) { + && (!ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.REPAIR, + mmoPlayer, 100 - getDowngradeEnchantChance()))) { item.addUnsafeEnchantment(enchantment, enchantLevel - 1); downgraded = true; } @@ -395,11 +434,12 @@ public class RepairManager extends SkillManager { Map newEnchants = item.getEnchantments(); if (newEnchants.isEmpty()) { - NotificationManager.sendPlayerInformationChatOnly(getPlayer(), "Repair.Arcane.Fail"); + NotificationManager.sendPlayerInformationChatOnly(getPlayer(), "Repair.Arcane.Fail"); } else if (downgraded || newEnchants.size() < enchants.size()) { - NotificationManager.sendPlayerInformationChatOnly(getPlayer(), "Repair.Arcane.Downgrade"); + NotificationManager.sendPlayerInformationChatOnly(getPlayer(), + "Repair.Arcane.Downgrade"); } else { - NotificationManager.sendPlayerInformationChatOnly(getPlayer(), "Repair.Arcane.Perfect"); + NotificationManager.sendPlayerInformationChatOnly(getPlayer(), "Repair.Arcane.Perfect"); } } diff --git a/src/main/java/com/gmail/nossr50/skills/repair/repairables/Repairable.java b/src/main/java/com/gmail/nossr50/skills/repair/repairables/Repairable.java index b59333f9d..4a3a00947 100644 --- a/src/main/java/com/gmail/nossr50/skills/repair/repairables/Repairable.java +++ b/src/main/java/com/gmail/nossr50/skills/repair/repairables/Repairable.java @@ -44,8 +44,9 @@ public interface Repairable { /** * Gets the minimum quantity of repair materials ignoring all other repair bonuses - * - * This is typically set to the number of items needed to create that item, for example 5 for helmets or 2 for swords + *

+ * This is typically set to the number of items needed to create that item, for example 5 for + * helmets or 2 for swords * * @return the minimum number of items */ @@ -60,7 +61,7 @@ public interface Repairable { /** * Gets the base repair durability on which to calculate bonuses. - * + *

* This is actually the maximum durability divided by the minimum quantity * * @return the base repair durability diff --git a/src/main/java/com/gmail/nossr50/skills/repair/repairables/RepairableFactory.java b/src/main/java/com/gmail/nossr50/skills/repair/repairables/RepairableFactory.java index 85ed7d8ae..a6826cc91 100644 --- a/src/main/java/com/gmail/nossr50/skills/repair/repairables/RepairableFactory.java +++ b/src/main/java/com/gmail/nossr50/skills/repair/repairables/RepairableFactory.java @@ -6,23 +6,35 @@ import org.bukkit.Material; public class RepairableFactory { - public static Repairable getRepairable(Material itemMaterial, Material repairMaterial, short maximumDurability) { - return getRepairable(itemMaterial, repairMaterial, null, 0, maximumDurability, ItemType.OTHER, MaterialType.OTHER, 1); + public static Repairable getRepairable(Material itemMaterial, Material repairMaterial, + short maximumDurability) { + return getRepairable(itemMaterial, repairMaterial, null, 0, maximumDurability, + ItemType.OTHER, MaterialType.OTHER, 1); } - public static Repairable getRepairable(Material itemMaterial, Material repairMaterial, int minimumLevel, short maximumDurability, ItemType repairItemType, MaterialType repairMaterialType, double xpMultiplier) { - return getRepairable(itemMaterial, repairMaterial, null, minimumLevel, maximumDurability, repairItemType, repairMaterialType, xpMultiplier); + public static Repairable getRepairable(Material itemMaterial, Material repairMaterial, + int minimumLevel, short maximumDurability, ItemType repairItemType, + MaterialType repairMaterialType, double xpMultiplier) { + return getRepairable(itemMaterial, repairMaterial, null, minimumLevel, maximumDurability, + repairItemType, repairMaterialType, xpMultiplier); } - public static Repairable getRepairable(Material itemMaterial, Material repairMaterial, String repairMaterialPrettyName, - int minimumLevel, short maximumDurability, ItemType repairItemType, MaterialType repairMaterialType, double xpMultiplier) { + public static Repairable getRepairable(Material itemMaterial, Material repairMaterial, + String repairMaterialPrettyName, + int minimumLevel, short maximumDurability, ItemType repairItemType, + MaterialType repairMaterialType, double xpMultiplier) { // TODO: Add in loading from config what type of repairable we want. - return new SimpleRepairable(itemMaterial, repairMaterial, repairMaterialPrettyName, minimumLevel, maximumDurability, repairItemType, repairMaterialType, xpMultiplier); + return new SimpleRepairable(itemMaterial, repairMaterial, repairMaterialPrettyName, + minimumLevel, maximumDurability, repairItemType, repairMaterialType, xpMultiplier); } - public static Repairable getRepairable(Material itemMaterial, Material repairMaterial, String repairMaterialPrettyName, - int minimumLevel, short maximumDurability, ItemType repairItemType, MaterialType repairMaterialType, double xpMultiplier, int minQuantity) { + public static Repairable getRepairable(Material itemMaterial, Material repairMaterial, + String repairMaterialPrettyName, + int minimumLevel, short maximumDurability, ItemType repairItemType, + MaterialType repairMaterialType, double xpMultiplier, int minQuantity) { // TODO: Add in loading from config what type of repairable we want. - return new SimpleRepairable(itemMaterial, repairMaterial, repairMaterialPrettyName, minimumLevel, maximumDurability, repairItemType, repairMaterialType, xpMultiplier, minQuantity); + return new SimpleRepairable(itemMaterial, repairMaterial, repairMaterialPrettyName, + minimumLevel, maximumDurability, repairItemType, repairMaterialType, xpMultiplier, + minQuantity); } } 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 fbfe46019..bfb744f33 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 @@ -1,10 +1,9 @@ package com.gmail.nossr50.skills.repair.repairables; +import java.util.List; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; -import java.util.List; - public interface RepairableManager { /** * Register a repairable with the RepairManager @@ -24,7 +23,6 @@ public interface RepairableManager { * Checks if an item is repairable * * @param type Material to check if repairable - * * @return true if repairable, false if not */ boolean isRepairable(Material type); @@ -33,7 +31,6 @@ public interface RepairableManager { * Checks if an item is repairable * * @param itemStack Item to check if repairable - * * @return true if repairable, false if not */ boolean isRepairable(ItemStack itemStack); @@ -42,7 +39,6 @@ public interface RepairableManager { * Gets the repairable with this type * * @param type Material of the repairable to look for - * * @return the repairable, can be null */ Repairable getRepairable(Material type); diff --git a/src/main/java/com/gmail/nossr50/skills/repair/repairables/SimpleRepairable.java b/src/main/java/com/gmail/nossr50/skills/repair/repairables/SimpleRepairable.java index 2849c9dae..af1913962 100644 --- a/src/main/java/com/gmail/nossr50/skills/repair/repairables/SimpleRepairable.java +++ b/src/main/java/com/gmail/nossr50/skills/repair/repairables/SimpleRepairable.java @@ -17,7 +17,9 @@ public class SimpleRepairable implements Repairable { private final double xpMultiplier; private int minQuantity = -1; - protected SimpleRepairable(Material type, Material repairMaterial, String repairMaterialPrettyName, int minimumLevel, short maximumDurability, ItemType repairItemType, MaterialType repairMaterialType, double xpMultiplier) { + protected SimpleRepairable(Material type, Material repairMaterial, + String repairMaterialPrettyName, int minimumLevel, short maximumDurability, + ItemType repairItemType, MaterialType repairMaterialType, double xpMultiplier) { this.itemMaterial = type; this.repairMaterial = repairMaterial; this.repairMaterialPrettyName = repairMaterialPrettyName; @@ -28,7 +30,10 @@ public class SimpleRepairable implements Repairable { this.xpMultiplier = xpMultiplier; } - protected SimpleRepairable(Material type, Material repairMaterial, String repairMaterialPrettyName, int minimumLevel, short maximumDurability, ItemType repairItemType, MaterialType repairMaterialType, double xpMultiplier, int minQuantity) { + protected SimpleRepairable(Material type, Material repairMaterial, + String repairMaterialPrettyName, int minimumLevel, short maximumDurability, + ItemType repairItemType, MaterialType repairMaterialType, double xpMultiplier, + int minQuantity) { this.itemMaterial = type; this.repairMaterial = repairMaterial; this.repairMaterialPrettyName = repairMaterialPrettyName; @@ -67,10 +72,12 @@ public class SimpleRepairable implements Repairable { @Override public int getMinimumQuantity() { - if (minQuantity == -1) - return Math.max(SkillUtils.getRepairAndSalvageQuantities(itemMaterial, repairMaterial), 1); - else + if (minQuantity == -1) { + return Math.max(SkillUtils.getRepairAndSalvageQuantities(itemMaterial, repairMaterial), + 1); + } else { return minQuantity; + } } @Override diff --git a/src/main/java/com/gmail/nossr50/skills/repair/repairables/SimpleRepairableManager.java b/src/main/java/com/gmail/nossr50/skills/repair/repairables/SimpleRepairableManager.java index dd7a74f36..f437e9511 100644 --- a/src/main/java/com/gmail/nossr50/skills/repair/repairables/SimpleRepairableManager.java +++ b/src/main/java/com/gmail/nossr50/skills/repair/repairables/SimpleRepairableManager.java @@ -1,10 +1,9 @@ package com.gmail.nossr50.skills.repair.repairables; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - import java.util.HashMap; import java.util.List; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; public class SimpleRepairableManager implements RepairableManager { private final HashMap repairables; diff --git a/src/main/java/com/gmail/nossr50/skills/salvage/Salvage.java b/src/main/java/com/gmail/nossr50/skills/salvage/Salvage.java index 4f510f909..92f1937bb 100644 --- a/src/main/java/com/gmail/nossr50/skills/salvage/Salvage.java +++ b/src/main/java/com/gmail/nossr50/skills/salvage/Salvage.java @@ -6,11 +6,12 @@ import org.bukkit.Material; public final class Salvage { /** - * This is a static utility class, therefore we don't want any instances of - * this class. Making the constructor private prevents accidents like that. + * This is a static utility class, therefore we don't want any instances of this class. Making + * the constructor private prevents accidents like that. */ - private Salvage() {} - + private Salvage() { + } + public static Material anvilMaterial = mcMMO.p.getGeneralConfig().getSalvageAnvilMaterial(); /*public static int salvageMaxPercentageLevel = mcMMO.p.getAdvancedConfig().getSalvageMaxPercentageLevel(); @@ -18,11 +19,15 @@ public final class Salvage { public static int advancedSalvageUnlockLevel = RankUtils.getRankUnlockLevel(SubSkillType.SALVAGE_SCRAP_COLLECTOR, 1);*/ - public static boolean arcaneSalvageDowngrades = mcMMO.p.getAdvancedConfig().getArcaneSalvageEnchantDowngradeEnabled(); - public static boolean arcaneSalvageEnchantLoss = mcMMO.p.getAdvancedConfig().getArcaneSalvageEnchantLossEnabled(); + public static boolean arcaneSalvageDowngrades = mcMMO.p.getAdvancedConfig() + .getArcaneSalvageEnchantDowngradeEnabled(); + public static boolean arcaneSalvageEnchantLoss = mcMMO.p.getAdvancedConfig() + .getArcaneSalvageEnchantLossEnabled(); - static int calculateSalvageableAmount(int currentDurability, short maxDurability, int baseAmount) { - double percentDamaged = (maxDurability <= 0) ? 1D : (double) (maxDurability - currentDurability) / maxDurability; + static int calculateSalvageableAmount(int currentDurability, short maxDurability, + int baseAmount) { + double percentDamaged = (maxDurability <= 0) ? 1D + : (double) (maxDurability - currentDurability) / maxDurability; return (int) Math.floor(baseAmount * percentDamaged); } 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 319a517db..5fd5f05bb 100644 --- a/src/main/java/com/gmail/nossr50/skills/salvage/SalvageManager.java +++ b/src/main/java/com/gmail/nossr50/skills/salvage/SalvageManager.java @@ -21,6 +21,8 @@ import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.sounds.SoundManager; import com.gmail.nossr50.util.sounds.SoundType; import com.gmail.nossr50.util.text.StringUtils; +import java.util.Map; +import java.util.Map.Entry; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; @@ -30,15 +32,12 @@ import org.bukkit.inventory.meta.Damageable; import org.bukkit.inventory.meta.EnchantmentStorageMeta; import org.bukkit.inventory.meta.ItemMeta; -import java.util.Map; -import java.util.Map.Entry; - public class SalvageManager extends SkillManager { private boolean placedAnvil; private int lastClick; - public SalvageManager(McMMOPlayer mcMMOPlayer) { - super(mcMMOPlayer, PrimarySkillType.SALVAGE); + public SalvageManager(McMMOPlayer mmoPlayer) { + super(mmoPlayer, PrimarySkillType.SALVAGE); } /** @@ -52,7 +51,8 @@ public class SalvageManager extends SkillManager { } if (mcMMO.p.getGeneralConfig().getSalvageAnvilMessagesEnabled()) { - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, "Salvage.Listener.Anvil"); + NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, + "Salvage.Listener.Anvil"); } if (mcMMO.p.getGeneralConfig().getSalvageAnvilPlaceSoundsEnabled()) { @@ -65,27 +65,34 @@ public class SalvageManager extends SkillManager { public void handleSalvage(Location location, ItemStack item) { final Player player = getPlayer(); - final Salvageable salvageable = mcMMO.getSalvageableManager().getSalvageable(item.getType()); + final Salvageable salvageable = mcMMO.getSalvageableManager() + .getSalvageable(item.getType()); final ItemMeta meta = item.getItemMeta(); if (meta != null) { - if (meta.hasCustomModelData() && !mcMMO.p.getCustomItemSupportConfig().isCustomSalvageAllowed()) { - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE_FAILED, "Anvil.Salvage.Reject.CustomModelData"); + if (meta.hasCustomModelData() && !mcMMO.p.getCustomItemSupportConfig() + .isCustomSalvageAllowed()) { + NotificationManager.sendPlayerInformation(player, + NotificationType.SUBSKILL_MESSAGE_FAILED, + "Anvil.Salvage.Reject.CustomModelData"); return; } if (meta.isUnbreakable()) { - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE_FAILED, "Anvil.Unbreakable"); + NotificationManager.sendPlayerInformation(player, + NotificationType.SUBSKILL_MESSAGE_FAILED, "Anvil.Unbreakable"); return; } } // Permissions checks on material and item types if (!Permissions.salvageItemType(player, salvageable.getSalvageItemType())) { - NotificationManager.sendPlayerInformation(player, NotificationType.NO_PERMISSION, "mcMMO.NoPermission"); + NotificationManager.sendPlayerInformation(player, NotificationType.NO_PERMISSION, + "mcMMO.NoPermission"); return; } if (!Permissions.salvageMaterialType(player, salvageable.getSalvageMaterialType())) { - NotificationManager.sendPlayerInformation(player, NotificationType.NO_PERMISSION, "mcMMO.NoPermission"); + NotificationManager.sendPlayerInformation(player, NotificationType.NO_PERMISSION, + "mcMMO.NoPermission"); return; } @@ -96,19 +103,23 @@ public class SalvageManager extends SkillManager { if (getSkillLevel() < minimumSalvageableLevel) { NotificationManager.sendPlayerInformation(player, NotificationType.REQUIREMENTS_NOT_MET, "Salvage.Skills.Adept.Level", - String.valueOf(minimumSalvageableLevel), StringUtils.getPrettyMaterialString(item.getType())); + String.valueOf(minimumSalvageableLevel), + StringUtils.getPrettyMaterialString(item.getType())); return; } - int durability = meta instanceof Damageable ? ((Damageable) meta).getDamage(): 0; - int potentialSalvageYield = Salvage.calculateSalvageableAmount(durability, salvageable.getMaximumDurability(), salvageable.getMaximumQuantity()); + int durability = meta instanceof Damageable ? ((Damageable) meta).getDamage() : 0; + int potentialSalvageYield = Salvage.calculateSalvageableAmount(durability, + salvageable.getMaximumDurability(), salvageable.getMaximumQuantity()); if (potentialSalvageYield <= 0) { - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE_FAILED, "Salvage.Skills.TooDamaged"); + NotificationManager.sendPlayerInformation(player, + NotificationType.SUBSKILL_MESSAGE_FAILED, "Salvage.Skills.TooDamaged"); return; } - potentialSalvageYield = Math.min(potentialSalvageYield, getSalvageLimit(getPlayer())); // Always get at least something back, if you're capable of salvaging it. + potentialSalvageYield = Math.min(potentialSalvageYield, getSalvageLimit( + getPlayer())); // Always get at least something back, if you're capable of salvaging it. location.add(0.5, 1, 0.5); @@ -119,15 +130,18 @@ public class SalvageManager extends SkillManager { enchantBook = arcaneSalvageCheck(enchants); } - ItemStack salvageResults = new ItemStack(salvageable.getSalvageMaterial(), potentialSalvageYield); + ItemStack salvageResults = new ItemStack(salvageable.getSalvageMaterial(), + potentialSalvageYield); //Call event - if (EventUtils.callSalvageCheckEvent(player, item, salvageResults, enchantBook).isCancelled()) { + if (EventUtils.callSalvageCheckEvent(player, item, salvageResults, enchantBook) + .isCancelled()) { return; } - NotificationManager.sendPlayerInformationChatOnly(player, "Salvage.Skills.Lottery.Normal", - String.valueOf(potentialSalvageYield), StringUtils.getPrettyMaterialString(item.getType())); + NotificationManager.sendPlayerInformationChatOnly(player, "Salvage.Skills.Lottery.Normal", + String.valueOf(potentialSalvageYield), + StringUtils.getPrettyMaterialString(item.getType())); player.getInventory().setItemInMainHand(new ItemStack(Material.AIR)); @@ -145,17 +159,20 @@ public class SalvageManager extends SkillManager { anvilLoc.add(0, .1, 0); if (enchantBook != null) { - ItemUtils.spawnItemTowardsLocation(getPlayer(), anvilLoc.clone(), playerLoc.clone(), enchantBook, vectorSpeed, ItemSpawnReason.SALVAGE_ENCHANTMENT_BOOK); + ItemUtils.spawnItemTowardsLocation(getPlayer(), anvilLoc.clone(), playerLoc.clone(), + enchantBook, vectorSpeed, ItemSpawnReason.SALVAGE_ENCHANTMENT_BOOK); } - ItemUtils.spawnItemTowardsLocation(getPlayer(), anvilLoc.clone(), playerLoc.clone(), salvageResults, vectorSpeed, ItemSpawnReason.SALVAGE_MATERIALS); + ItemUtils.spawnItemTowardsLocation(getPlayer(), anvilLoc.clone(), playerLoc.clone(), + salvageResults, vectorSpeed, ItemSpawnReason.SALVAGE_MATERIALS); // BWONG BWONG BWONG - CLUNK! if (mcMMO.p.getGeneralConfig().getSalvageAnvilUseSoundsEnabled()) { SoundManager.sendSound(player, player.getLocation(), SoundType.ITEM_BREAK); } - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, "Salvage.Skills.Success"); + NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, + "Salvage.Skills.Success"); } /*public double getMaxSalvagePercentage() { @@ -181,21 +198,26 @@ public class SalvageManager extends SkillManager { } public double getExtractFullEnchantChance() { - if (Permissions.hasSalvageEnchantBypassPerk(getPlayer())) + if (Permissions.hasSalvageEnchantBypassPerk(getPlayer())) { return 100.0D; + } - return mcMMO.p.getAdvancedConfig().getArcaneSalvageExtractFullEnchantsChance(getArcaneSalvageRank()); + return mcMMO.p.getAdvancedConfig() + .getArcaneSalvageExtractFullEnchantsChance(getArcaneSalvageRank()); } public double getExtractPartialEnchantChance() { - return mcMMO.p.getAdvancedConfig().getArcaneSalvageExtractPartialEnchantsChance(getArcaneSalvageRank()); + return mcMMO.p.getAdvancedConfig() + .getArcaneSalvageExtractPartialEnchantsChance(getArcaneSalvageRank()); } private ItemStack arcaneSalvageCheck(Map enchants) { Player player = getPlayer(); - if (!RankUtils.hasUnlockedSubskill(player, SubSkillType.SALVAGE_ARCANE_SALVAGE) || !Permissions.arcaneSalvage(player)) { - NotificationManager.sendPlayerInformationChatOnly(player, "Salvage.Skills.ArcaneFailed"); + if (!RankUtils.hasUnlockedSubskill(player, SubSkillType.SALVAGE_ARCANE_SALVAGE) + || !Permissions.arcaneSalvage(player)) { + NotificationManager.sendPlayerInformationChatOnly(player, + "Salvage.Skills.ArcaneFailed"); return null; } @@ -218,12 +240,12 @@ public class SalvageManager extends SkillManager { if (!Salvage.arcaneSalvageEnchantLoss || Permissions.hasSalvageEnchantBypassPerk(player) || ProbabilityUtil.isStaticSkillRNGSuccessful( - PrimarySkillType.SALVAGE, mmoPlayer, getExtractFullEnchantChance())) { + PrimarySkillType.SALVAGE, mmoPlayer, getExtractFullEnchantChance())) { enchantMeta.addStoredEnchant(enchant.getKey(), enchantLevel, true); } else if (enchantLevel > 1 && Salvage.arcaneSalvageDowngrades && ProbabilityUtil.isStaticSkillRNGSuccessful( - PrimarySkillType.SALVAGE, mmoPlayer, getExtractPartialEnchantChance())) { + PrimarySkillType.SALVAGE, mmoPlayer, getExtractPartialEnchantChance())) { enchantMeta.addStoredEnchant(enchant.getKey(), enchantLevel - 1, true); downgraded = true; } else { @@ -231,11 +253,13 @@ public class SalvageManager extends SkillManager { } } - if (failedAllEnchants(arcaneFailureCount, enchants.entrySet().size())) { - NotificationManager.sendPlayerInformationChatOnly(player, "Salvage.Skills.ArcaneFailed"); + if (failedAllEnchants(arcaneFailureCount, enchants.size())) { + NotificationManager.sendPlayerInformationChatOnly(player, + "Salvage.Skills.ArcaneFailed"); return null; } else if (downgraded) { - NotificationManager.sendPlayerInformationChatOnly(player, "Salvage.Skills.ArcanePartial"); + NotificationManager.sendPlayerInformationChatOnly(player, + "Salvage.Skills.ArcanePartial"); } book.setItemMeta(enchantMeta); @@ -248,15 +272,16 @@ 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) { Player player = getPlayer(); long lastUse = getLastAnvilUse(); - if (!SkillUtils.cooldownExpired(lastUse, 3) || !mcMMO.p.getGeneralConfig().getSalvageConfirmRequired()) { + if (!SkillUtils.cooldownExpired(lastUse, 3) || !mcMMO.p.getGeneralConfig() + .getSalvageConfirmRequired()) { return true; } @@ -266,7 +291,8 @@ public class SalvageManager extends SkillManager { actualizeLastAnvilUse(); - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, "Skills.ConfirmOrCancel", LocaleLoader.getString("Salvage.Pretty.Name")); + NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, + "Skills.ConfirmOrCancel", LocaleLoader.getString("Salvage.Pretty.Name")); return false; } 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 1d9ac26a9..bcf46e866 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 @@ -35,8 +35,9 @@ public interface Salvageable { /** * Gets the maximum quantity of salvage materials ignoring all other salvage bonuses - * - * This is typically set to the number of items needed to create that item, for example 5 for helmets or 2 for swords + *

+ * This is typically set to the number of items needed to create that item, for example 5 for + * helmets or 2 for swords * * @return the maximum number of items */ @@ -51,7 +52,7 @@ public interface Salvageable { /** * Gets the base salvage durability on which to calculate bonuses. - * + *

* This is actually the maximum durability divided by the minimum quantity * * @return the base salvage durability diff --git a/src/main/java/com/gmail/nossr50/skills/salvage/salvageables/SalvageableFactory.java b/src/main/java/com/gmail/nossr50/skills/salvage/salvageables/SalvageableFactory.java index d408b1992..cb59884d8 100644 --- a/src/main/java/com/gmail/nossr50/skills/salvage/salvageables/SalvageableFactory.java +++ b/src/main/java/com/gmail/nossr50/skills/salvage/salvageables/SalvageableFactory.java @@ -6,17 +6,23 @@ import org.bukkit.Material; public final class SalvageableFactory { /** - * This is a static utility class, therefore we don't want any instances of - * this class. Making the constructor private prevents accidents like that. + * This is a static utility class, therefore we don't want any instances of this class. Making + * the constructor private prevents accidents like that. */ - private SalvageableFactory() {} - - public static Salvageable getSalvageable(Material itemMaterial, Material recipeMaterial, int maximumQuantity, short maximumDurability) { - return getSalvageable(itemMaterial, recipeMaterial, 0, maximumQuantity, maximumDurability, ItemType.OTHER, MaterialType.OTHER, 1); + private SalvageableFactory() { } - public static Salvageable getSalvageable(Material itemMaterial, Material recipeMaterial, int minimumLevel, int maximumQuantity, short maximumDurability, ItemType repairItemType, MaterialType repairMaterialType, double xpMultiplier) { + public static Salvageable getSalvageable(Material itemMaterial, Material recipeMaterial, + int maximumQuantity, short maximumDurability) { + return getSalvageable(itemMaterial, recipeMaterial, 0, maximumQuantity, maximumDurability, + ItemType.OTHER, MaterialType.OTHER, 1); + } + + public static Salvageable getSalvageable(Material itemMaterial, Material recipeMaterial, + int minimumLevel, int maximumQuantity, short maximumDurability, ItemType repairItemType, + MaterialType repairMaterialType, double xpMultiplier) { // TODO: Add in loading from config what type of repairable we want. - return new SimpleSalvageable(itemMaterial, recipeMaterial, minimumLevel, maximumQuantity, maximumDurability, repairItemType, repairMaterialType, xpMultiplier); + return new SimpleSalvageable(itemMaterial, recipeMaterial, minimumLevel, maximumQuantity, + maximumDurability, repairItemType, repairMaterialType, xpMultiplier); } } 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 24add9b40..7d2a1bc79 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 @@ -1,10 +1,9 @@ package com.gmail.nossr50.skills.salvage.salvageables; +import java.util.List; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; -import java.util.List; - public interface SalvageableManager { /** * Register a salvageable with the SalvageManager @@ -24,7 +23,6 @@ public interface SalvageableManager { * Checks if an item is salvageable * * @param type Material to check if salvageable - * * @return true if salvageable, false if not */ boolean isSalvageable(Material type); @@ -33,7 +31,6 @@ public interface SalvageableManager { * Checks if an item is salvageable * * @param itemStack Item to check if salvageable - * * @return true if salvageable, false if not */ boolean isSalvageable(ItemStack itemStack); @@ -42,7 +39,6 @@ public interface SalvageableManager { * Gets the salvageable with this type * * @param type Material of the salvageable to look for - * * @return the salvageable, can be null */ Salvageable getSalvageable(Material type); diff --git a/src/main/java/com/gmail/nossr50/skills/salvage/salvageables/SimpleSalvageable.java b/src/main/java/com/gmail/nossr50/skills/salvage/salvageables/SimpleSalvageable.java index d7484425c..7978d2b6b 100644 --- a/src/main/java/com/gmail/nossr50/skills/salvage/salvageables/SimpleSalvageable.java +++ b/src/main/java/com/gmail/nossr50/skills/salvage/salvageables/SimpleSalvageable.java @@ -13,7 +13,9 @@ public class SimpleSalvageable implements Salvageable { private final MaterialType salvageMaterialType; private final double xpMultiplier; - protected SimpleSalvageable(Material type, Material salvageMaterial, int minimumLevel, int maximumQuantity, short maximumDurability, ItemType salvageItemType, MaterialType salvageMaterialType, double xpMultiplier) { + protected SimpleSalvageable(Material type, Material salvageMaterial, int minimumLevel, + int maximumQuantity, short maximumDurability, ItemType salvageItemType, + MaterialType salvageMaterialType, double xpMultiplier) { this.itemMaterial = type; this.salvageMaterial = salvageMaterial; this.salvageItemType = salvageItemType; diff --git a/src/main/java/com/gmail/nossr50/skills/salvage/salvageables/SimpleSalvageableManager.java b/src/main/java/com/gmail/nossr50/skills/salvage/salvageables/SimpleSalvageableManager.java index 1a6d8a1f3..6a9d70ff0 100644 --- a/src/main/java/com/gmail/nossr50/skills/salvage/salvageables/SimpleSalvageableManager.java +++ b/src/main/java/com/gmail/nossr50/skills/salvage/salvageables/SimpleSalvageableManager.java @@ -1,11 +1,10 @@ package com.gmail.nossr50.skills.salvage.salvageables; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - import java.util.HashMap; import java.util.List; import java.util.Map; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; public class SimpleSalvageableManager implements SalvageableManager { private final Map salvageables; 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 f8c43c0ca..12d1c57ac 100644 --- a/src/main/java/com/gmail/nossr50/skills/smelting/SmeltingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/smelting/SmeltingManager.java @@ -18,13 +18,14 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class SmeltingManager extends SkillManager { - public SmeltingManager(McMMOPlayer mcMMOPlayer) { - super(mcMMOPlayer, PrimarySkillType.SMELTING); + public SmeltingManager(McMMOPlayer mmoPlayer) { + super(mmoPlayer, PrimarySkillType.SMELTING); } public boolean isSecondSmeltSuccessful() { return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.SMELTING_SECOND_SMELT) - && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.SMELTING_SECOND_SMELT, mmoPlayer); + && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.SMELTING_SECOND_SMELT, + mmoPlayer); } /** @@ -45,20 +46,24 @@ public class SmeltingManager extends SkillManager { }; } - public void smeltProcessing(@NotNull FurnaceSmeltEvent furnaceSmeltEvent, @NotNull Furnace furnace) { - applyXpGain(Smelting.getSmeltXP(furnaceSmeltEvent.getSource()), XPGainReason.PVE, XPGainSource.PASSIVE); //Add XP + public void smeltProcessing(@NotNull FurnaceSmeltEvent furnaceSmeltEvent, + @NotNull Furnace furnace) { + applyXpGain(Smelting.getSmeltXP(furnaceSmeltEvent.getSource()), XPGainReason.PVE, + XPGainSource.PASSIVE); //Add XP processDoubleSmelt(furnaceSmeltEvent, furnace); } - private void processDoubleSmelt(@NotNull FurnaceSmeltEvent furnaceSmeltEvent, @NotNull Furnace furnace) { + private void processDoubleSmelt(@NotNull FurnaceSmeltEvent furnaceSmeltEvent, + @NotNull Furnace furnace) { ItemStack resultItemStack = furnaceSmeltEvent.getResult(); /* doubleSmeltCondition should be equal to the max */ //Process double smelt - if (mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.SMELTING, resultItemStack.getType()) + if (mcMMO.p.getGeneralConfig() + .getDoubleDropsEnabled(PrimarySkillType.SMELTING, resultItemStack.getType()) && canDoubleSmeltItemStack(furnace) //Effectively two less than max stack size && isSecondSmeltSuccessful()) { @@ -72,12 +77,14 @@ public class SmeltingManager extends SkillManager { FurnaceInventory furnaceInventory = furnace.getInventory(); ItemStack furnaceResult = furnaceInventory.getResult(); - if (furnaceResult == null) + if (furnaceResult == null) { return true; //This actually means there is nothing yet in the resulting item slot, which means it should always be okay to double smelt + } int resultAmount = furnaceResult.getAmount(); //Amount before double smelt int itemLimit = furnaceResult.getMaxStackSize(); - int doubleSmeltCondition = itemLimit - 2; //Don't double smelt if it would cause an illegal stack size + int doubleSmeltCondition = + itemLimit - 2; //Don't double smelt if it would cause an illegal stack size return resultAmount <= doubleSmeltCondition; } @@ -92,6 +99,7 @@ public class SmeltingManager extends SkillManager { * @return the vanilla XP multiplier */ public int getVanillaXpMultiplier() { - return Math.max(1, RankUtils.getRank(getPlayer(), SubSkillType.SMELTING_UNDERSTANDING_THE_ART)); + return Math.max(1, + RankUtils.getRank(getPlayer(), SubSkillType.SMELTING_UNDERSTANDING_THE_ART)); } } \ No newline at end of file diff --git a/src/main/java/com/gmail/nossr50/skills/swords/Swords.java b/src/main/java/com/gmail/nossr50/skills/swords/Swords.java index 7dda504ea..7db420921 100644 --- a/src/main/java/com/gmail/nossr50/skills/swords/Swords.java +++ b/src/main/java/com/gmail/nossr50/skills/swords/Swords.java @@ -3,7 +3,8 @@ package com.gmail.nossr50.skills.swords; import com.gmail.nossr50.mcMMO; public class Swords { - public static double counterAttackModifier = mcMMO.p.getAdvancedConfig().getCounterModifier(); + public static double counterAttackModifier = mcMMO.p.getAdvancedConfig().getCounterModifier(); - public static double serratedStrikesModifier = mcMMO.p.getAdvancedConfig().getSerratedStrikesModifier(); + public static double serratedStrikesModifier = mcMMO.p.getAdvancedConfig() + .getSerratedStrikesModifier(); } 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 c232e61b3..23810d5b9 100644 --- a/src/main/java/com/gmail/nossr50/skills/swords/SwordsManager.java +++ b/src/main/java/com/gmail/nossr50/skills/swords/SwordsManager.java @@ -22,32 +22,38 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; public class SwordsManager extends SkillManager { - public SwordsManager(McMMOPlayer mcMMOPlayer) { - super(mcMMOPlayer, PrimarySkillType.SWORDS); + public SwordsManager(McMMOPlayer mmoPlayer) { + super(mmoPlayer, PrimarySkillType.SWORDS); } public boolean canActivateAbility() { - return mmoPlayer.getToolPreparationMode(ToolType.SWORD) && Permissions.serratedStrikes(getPlayer()); + return mmoPlayer.getToolPreparationMode(ToolType.SWORD) && Permissions.serratedStrikes( + getPlayer()); } public boolean canUseStab() { - return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.SWORDS_STAB) && RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.SWORDS_STAB); + return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.SWORDS_STAB) + && RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.SWORDS_STAB); } public boolean canUseRupture() { - return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.SWORDS_RUPTURE) && RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.SWORDS_RUPTURE); + return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.SWORDS_RUPTURE) + && RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.SWORDS_RUPTURE); } 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); + 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 mmoPlayer.getAbilityMode(SuperAbilityType.SERRATED_STRIKES); } @@ -58,14 +64,17 @@ public class SwordsManager extends SkillManager { * @param target The defending entity */ public void processRupture(@NotNull LivingEntity target) { - if (!canUseRupture()) + if (!canUseRupture()) { return; + } if (target.hasMetadata(MetadataConstants.METADATA_KEY_RUPTURE)) { - RuptureTaskMeta ruptureTaskMeta = (RuptureTaskMeta) target.getMetadata(MetadataConstants.METADATA_KEY_RUPTURE).get(0); + RuptureTaskMeta ruptureTaskMeta = (RuptureTaskMeta) target.getMetadata( + MetadataConstants.METADATA_KEY_RUPTURE).get(0); if (mmoPlayer.isDebugMode()) { - mmoPlayer.getPlayer().sendMessage("Rupture task ongoing for target " + target.toString()); + mmoPlayer.getPlayer() + .sendMessage("Rupture task ongoing for target " + target); mmoPlayer.getPlayer().sendMessage(ruptureTaskMeta.getRuptureTimerTask().toString()); } @@ -73,23 +82,28 @@ public class SwordsManager extends SkillManager { return; //Don't apply bleed } - double ruptureOdds = mcMMO.p.getAdvancedConfig().getRuptureChanceToApplyOnHit(getRuptureRank()) - * mmoPlayer.getAttackStrength(); - if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.SWORDS, mmoPlayer, ruptureOdds)) { + double ruptureOdds = + mcMMO.p.getAdvancedConfig().getRuptureChanceToApplyOnHit(getRuptureRank()) + * mmoPlayer.getAttackStrength(); + if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.SWORDS, mmoPlayer, + ruptureOdds)) { if (target instanceof Player defender) { //Don't start or add to a bleed if they are blocking - if (defender.isBlocking()) + if (defender.isBlocking()) { return; + } if (NotificationManager.doesPlayerUseNotifications(defender)) { - NotificationManager.sendPlayerInformation(defender, NotificationType.SUBSKILL_MESSAGE, "Swords.Combat.Bleeding.Started"); + NotificationManager.sendPlayerInformation(defender, + NotificationType.SUBSKILL_MESSAGE, "Swords.Combat.Bleeding.Started"); } } final RuptureTask ruptureTask = new RuptureTask(mmoPlayer, target, - mcMMO.p.getAdvancedConfig().getRuptureTickDamage(target instanceof Player, getRuptureRank())); + mcMMO.p.getAdvancedConfig() + .getRuptureTickDamage(target instanceof Player, getRuptureRank())); final RuptureTaskMeta ruptureTaskMeta = new RuptureTaskMeta(mcMMO.p, ruptureTask); @@ -122,13 +136,14 @@ public class SwordsManager extends SkillManager { */ public void counterAttackChecks(@NotNull LivingEntity attacker, double damage) { if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.SWORDS_COUNTER_ATTACK, mmoPlayer)) { - CombatUtils.safeDealDamage(attacker, damage / Swords.counterAttackModifier, getPlayer()); + CombatUtils.safeDealDamage(attacker, damage / Swords.counterAttackModifier, + getPlayer()); NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Swords.Combat.Countered"); if (attacker instanceof Player) { - NotificationManager.sendPlayerInformation((Player)attacker, + NotificationManager.sendPlayerInformation((Player) attacker, NotificationType.SUBSKILL_MESSAGE, "Swords.Combat.Counter.Hit"); } } @@ -136,10 +151,12 @@ public class SwordsManager extends SkillManager { /** * Handle the effects of the Serrated Strikes ability - * @param target The {@link LivingEntity} being affected by the ability + * + * @param target The {@link LivingEntity} being affected by the ability * @param damage The amount of damage initially dealt by the event */ public void serratedStrikes(@NotNull LivingEntity target, double damage) { - CombatUtils.applyAbilityAoE(getPlayer(), target, damage / Swords.serratedStrikesModifier, skill); + CombatUtils.applyAbilityAoE(getPlayer(), target, damage / Swords.serratedStrikesModifier, + skill); } } diff --git a/src/main/java/com/gmail/nossr50/skills/taming/Taming.java b/src/main/java/com/gmail/nossr50/skills/taming/Taming.java index 26ee15a67..edfce6813 100644 --- a/src/main/java/com/gmail/nossr50/skills/taming/Taming.java +++ b/src/main/java/com/gmail/nossr50/skills/taming/Taming.java @@ -2,19 +2,25 @@ package com.gmail.nossr50.skills.taming; import com.gmail.nossr50.mcMMO; import org.bukkit.EntityEffect; -import org.bukkit.entity.*; +import org.bukkit.entity.AnimalTamer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.entity.Tameable; +import org.bukkit.entity.Wolf; public class Taming { - public static double fastFoodServiceActivationChance = mcMMO.p.getAdvancedConfig().getFastFoodChance(); + public static double fastFoodServiceActivationChance = mcMMO.p.getAdvancedConfig() + .getFastFoodChance(); - public static int goreBleedTicks = 2; //Equivalent to rank 1 in Rupture - public static double goreModifier = mcMMO.p.getAdvancedConfig().getGoreModifier(); + public static int goreBleedTicks = 2; //Equivalent to rank 1 in Rupture + public static double goreModifier = mcMMO.p.getAdvancedConfig().getGoreModifier(); - public static double sharpenedClawsBonusDamage = mcMMO.p.getAdvancedConfig().getSharpenedClawsBonus(); + public static double sharpenedClawsBonusDamage = mcMMO.p.getAdvancedConfig() + .getSharpenedClawsBonus(); - public static double shockProofModifier = mcMMO.p.getAdvancedConfig().getShockProofModifier(); + public static double shockProofModifier = mcMMO.p.getAdvancedConfig().getShockProofModifier(); - public static double thickFurModifier = mcMMO.p.getAdvancedConfig().getThickFurModifier(); + public static double thickFurModifier = mcMMO.p.getAdvancedConfig().getThickFurModifier(); public static boolean canPreventDamage(Tameable pet, AnimalTamer owner) { return pet.isTamed() && owner instanceof Player && pet instanceof Wolf; 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 9d514aaa0..d16444715 100644 --- a/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java @@ -1,5 +1,9 @@ package com.gmail.nossr50.skills.taming; +import static com.gmail.nossr50.util.AttributeMapper.MAPPED_JUMP_STRENGTH; +import static com.gmail.nossr50.util.AttributeMapper.MAPPED_MOVEMENT_SPEED; +import static com.gmail.nossr50.util.MobMetadataUtils.flagMetadata; + import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.datatypes.experience.XPGainReason; import com.gmail.nossr50.datatypes.experience.XPGainSource; @@ -23,27 +27,32 @@ import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.sounds.SoundManager; import com.gmail.nossr50.util.sounds.SoundType; import com.gmail.nossr50.util.text.StringUtils; +import java.util.HashMap; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.attribute.AttributeInstance; -import org.bukkit.entity.*; +import org.bukkit.entity.AbstractHorse; +import org.bukkit.entity.Ageable; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Horse; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Llama; +import org.bukkit.entity.Ocelot; +import org.bukkit.entity.Player; +import org.bukkit.entity.Tameable; +import org.bukkit.entity.Wolf; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import java.util.HashMap; - -import static com.gmail.nossr50.util.AttributeMapper.MAPPED_JUMP_STRENGTH; -import static com.gmail.nossr50.util.AttributeMapper.MAPPED_MOVEMENT_SPEED; -import static com.gmail.nossr50.util.MobMetadataUtils.flagMetadata; - public class TamingManager extends SkillManager { //TODO: Temporary static cache, will be changed in 2.2 private static HashMap summoningItems; private static HashMap cotwSummonDataProperties; private long lastSummonTimeStamp; - public TamingManager(@NotNull McMMOPlayer mcMMOPlayer) { - super(mcMMOPlayer, PrimarySkillType.TAMING); + public TamingManager(@NotNull McMMOPlayer mmoPlayer) { + super(mmoPlayer, PrimarySkillType.TAMING); init(); } @@ -65,9 +74,15 @@ public class TamingManager extends SkillManager { if (summoningItems == null) { summoningItems = new HashMap<>(); - summoningItems.put(mcMMO.p.getGeneralConfig().getTamingCOTWMaterial(CallOfTheWildType.CAT.getConfigEntityTypeEntry()), CallOfTheWildType.CAT); - summoningItems.put(mcMMO.p.getGeneralConfig().getTamingCOTWMaterial(CallOfTheWildType.WOLF.getConfigEntityTypeEntry()), CallOfTheWildType.WOLF); - summoningItems.put(mcMMO.p.getGeneralConfig().getTamingCOTWMaterial(CallOfTheWildType.HORSE.getConfigEntityTypeEntry()), CallOfTheWildType.HORSE); + summoningItems.put(mcMMO.p.getGeneralConfig() + .getTamingCOTWMaterial(CallOfTheWildType.CAT.getConfigEntityTypeEntry()), + CallOfTheWildType.CAT); + summoningItems.put(mcMMO.p.getGeneralConfig() + .getTamingCOTWMaterial(CallOfTheWildType.WOLF.getConfigEntityTypeEntry()), + CallOfTheWildType.WOLF); + summoningItems.put(mcMMO.p.getGeneralConfig() + .getTamingCOTWMaterial(CallOfTheWildType.HORSE.getConfigEntityTypeEntry()), + CallOfTheWildType.HORSE); } //TODO: Temporary static cache, will be changed in 2.2 @@ -75,14 +90,21 @@ public class TamingManager extends SkillManager { if (cotwSummonDataProperties == null) { cotwSummonDataProperties = new HashMap<>(); - for(CallOfTheWildType callOfTheWildType : CallOfTheWildType.values()) { - Material itemSummonMaterial = mcMMO.p.getGeneralConfig().getTamingCOTWMaterial(callOfTheWildType.getConfigEntityTypeEntry()); - int itemAmountRequired = mcMMO.p.getGeneralConfig().getTamingCOTWCost(callOfTheWildType.getConfigEntityTypeEntry()); - int entitiesSummonedPerCOTW = mcMMO.p.getGeneralConfig().getTamingCOTWAmount(callOfTheWildType.getConfigEntityTypeEntry()); - int summonLifespanSeconds = mcMMO.p.getGeneralConfig().getTamingCOTWLength(callOfTheWildType.getConfigEntityTypeEntry()); - int perPlayerMaxAmount = mcMMO.p.getGeneralConfig().getTamingCOTWMaxAmount(callOfTheWildType.getConfigEntityTypeEntry()); + for (CallOfTheWildType callOfTheWildType : CallOfTheWildType.values()) { + Material itemSummonMaterial = mcMMO.p.getGeneralConfig() + .getTamingCOTWMaterial(callOfTheWildType.getConfigEntityTypeEntry()); + int itemAmountRequired = mcMMO.p.getGeneralConfig() + .getTamingCOTWCost(callOfTheWildType.getConfigEntityTypeEntry()); + int entitiesSummonedPerCOTW = mcMMO.p.getGeneralConfig() + .getTamingCOTWAmount(callOfTheWildType.getConfigEntityTypeEntry()); + int summonLifespanSeconds = mcMMO.p.getGeneralConfig() + .getTamingCOTWLength(callOfTheWildType.getConfigEntityTypeEntry()); + int perPlayerMaxAmount = mcMMO.p.getGeneralConfig() + .getTamingCOTWMaxAmount(callOfTheWildType.getConfigEntityTypeEntry()); - TamingSummon tamingSummon = new TamingSummon(callOfTheWildType, itemSummonMaterial, itemAmountRequired, entitiesSummonedPerCOTW, summonLifespanSeconds, perPlayerMaxAmount); + TamingSummon tamingSummon = new TamingSummon(callOfTheWildType, itemSummonMaterial, + itemAmountRequired, entitiesSummonedPerCOTW, summonLifespanSeconds, + perPlayerMaxAmount); cotwSummonDataProperties.put(callOfTheWildType, tamingSummon); } } @@ -95,7 +117,8 @@ public class TamingManager extends SkillManager { public boolean canUseEnvironmentallyAware() { return RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_ENVIRONMENTALLY_AWARE) - && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.TAMING_ENVIRONMENTALLY_AWARE); + && Permissions.isSubSkillEnabled(getPlayer(), + SubSkillType.TAMING_ENVIRONMENTALLY_AWARE); } public boolean canUseShockProof() { @@ -110,7 +133,8 @@ public class TamingManager extends SkillManager { public boolean canUseFastFoodService() { return RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_FAST_FOOD_SERVICE) - && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.TAMING_FAST_FOOD_SERVICE); + && Permissions.isSubSkillEnabled(getPlayer(), + SubSkillType.TAMING_FAST_FOOD_SERVICE); } public boolean canUseSharpenedClaws() { @@ -119,15 +143,17 @@ 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); } @@ -140,11 +166,13 @@ public class TamingManager extends SkillManager { public void awardTamingXP(@NotNull LivingEntity entity) { int xp = ExperienceConfig.getInstance().getTamingXP(entity.getType()); - final McMMOPlayerTameEntityEvent event = new McMMOPlayerTameEntityEvent(mmoPlayer, xp, entity); + final McMMOPlayerTameEntityEvent event = new McMMOPlayerTameEntityEvent(mmoPlayer, xp, + entity); mcMMO.p.getServer().getPluginManager().callEvent(event); - if (!event.isCancelled()) + if (!event.isCancelled()) { applyXpGain(event.getXpGained(), XPGainReason.PVE, XPGainSource.SELF); + } } /** @@ -154,7 +182,8 @@ public class TamingManager extends SkillManager { * @param damage The damage being absorbed by the wolf */ public void fastFoodService(@NotNull Wolf wolf, double damage) { - if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.TAMING_FAST_FOOD_SERVICE, mmoPlayer)) { + if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.TAMING_FAST_FOOD_SERVICE, + mmoPlayer)) { return; } @@ -187,8 +216,9 @@ 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)) { return; @@ -201,8 +231,9 @@ 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)) { return; @@ -215,8 +246,9 @@ 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)) { return; @@ -237,10 +269,14 @@ public class TamingManager extends SkillManager { String message = LocaleLoader.getString("Combat.BeastLore") + " "; if (beast.isTamed() && beast.getOwner() != null) { - message = message.concat(LocaleLoader.getString("Combat.BeastLoreOwner", beast.getOwner().getName()) + " "); + message = message.concat( + LocaleLoader.getString("Combat.BeastLoreOwner", beast.getOwner().getName()) + + " "); } - message = message.concat(LocaleLoader.getString("Combat.BeastLoreHealth", target.getHealth(), target.getMaxHealth())); + message = message.concat( + LocaleLoader.getString("Combat.BeastLoreHealth", target.getHealth(), + target.getMaxHealth())); // Bred mules & donkeys can actually have horse-like stats, but llamas cannot. if (beast instanceof AbstractHorse horseLikeCreature && !(beast instanceof Llama)) { @@ -249,9 +285,12 @@ public class TamingManager extends SkillManager { if (jumpAttribute != null) { double jumpStrength = jumpAttribute.getValue(); // Taken from https://minecraft.wiki/w/Horse#Jump_strength - jumpStrength = -0.1817584952 * Math.pow(jumpStrength, 3) + 3.689713992 * Math.pow(jumpStrength, 2) + 2.128599134 * jumpStrength - 0.343930367; - message = message.concat("\n" + LocaleLoader.getString("Combat.BeastLoreHorseSpeed", horseLikeCreature.getAttribute(MAPPED_MOVEMENT_SPEED).getValue() * 43)) - .concat("\n" + LocaleLoader.getString("Combat.BeastLoreHorseJumpStrength", jumpStrength)); + jumpStrength = -0.1817584952 * Math.pow(jumpStrength, 3) + 3.689713992 * Math.pow( + jumpStrength, 2) + 2.128599134 * jumpStrength - 0.343930367; + message = message.concat("\n" + LocaleLoader.getString("Combat.BeastLoreHorseSpeed", + horseLikeCreature.getAttribute(MAPPED_MOVEMENT_SPEED).getValue() * 43)) + .concat("\n" + LocaleLoader.getString("Combat.BeastLoreHorseJumpStrength", + jumpStrength)); } } @@ -266,15 +305,19 @@ public class TamingManager extends SkillManager { Player owner = getPlayer(); wolf.teleport(owner); - NotificationManager.sendPlayerInformation(owner, NotificationType.SUBSKILL_MESSAGE, "Taming.Listener.Wolf"); + NotificationManager.sendPlayerInformation(owner, NotificationType.SUBSKILL_MESSAGE, + "Taming.Listener.Wolf"); } public void pummel(LivingEntity target, Wolf wolf) { - if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_PUMMEL)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_PUMMEL)) { return; + } - if (!ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.TAMING, mmoPlayer, mcMMO.p.getAdvancedConfig().getPummelChance())) + if (!ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.TAMING, mmoPlayer, + mcMMO.p.getAdvancedConfig().getPummelChance())) { return; + } ParticleEffectUtils.playGreaterImpactEffect(target); target.setVelocity(wolf.getLocation().getDirection().normalize().multiply(1.5D)); @@ -282,7 +325,8 @@ public class TamingManager extends SkillManager { if (target instanceof Player defender) { if (NotificationManager.doesPlayerUseNotifications(defender)) { - NotificationManager.sendPlayerInformation(defender, NotificationType.SUBSKILL_MESSAGE, "Taming.SubSkill.Pummel.TargetMessage"); + NotificationManager.sendPlayerInformation(defender, + NotificationType.SUBSKILL_MESSAGE, "Taming.SubSkill.Pummel.TargetMessage"); } } } @@ -296,8 +340,9 @@ public class TamingManager extends SkillManager { double range = 5; Player player = getPlayer(); - if (!target.getWorld().equals(player.getWorld())) + if (!target.getWorld().equals(player.getWorld())) { return; + } for (Entity entity : player.getNearbyEntities(range, range, range)) { if (entity.getType() != EntityType.WOLF) { @@ -343,8 +388,10 @@ public class TamingManager extends SkillManager { //COTW can summon multiple entities per usage for (int i = 0; i < tamingSummon.getEntitiesSummoned(); i++) { - if (getAmountCurrentlySummoned(callOfTheWildType) >= tamingSummon.getSummonCap()) { - NotificationManager.sendPlayerInformationChatOnly(player, "Taming.Summon.COTW.Limit", + if (getAmountCurrentlySummoned(callOfTheWildType) + >= tamingSummon.getSummonCap()) { + NotificationManager.sendPlayerInformationChatOnly(player, + "Taming.Summon.COTW.Limit", String.valueOf(tamingSummon.getSummonCap()), StringUtils.getCapitalized(callOfTheWildType.toString())); break; @@ -355,14 +402,19 @@ public class TamingManager extends SkillManager { //Inform the player about what they have just done if (tamingSummon.getSummonLifespan() > 0) { - NotificationManager.sendPlayerInformationChatOnly(player, "Taming.Summon.COTW.Success.WithLifespan", - StringUtils.getCapitalized(callOfTheWildType.toString()), String.valueOf(tamingSummon.getSummonLifespan())); + NotificationManager.sendPlayerInformationChatOnly(player, + "Taming.Summon.COTW.Success.WithLifespan", + StringUtils.getCapitalized(callOfTheWildType.toString()), + String.valueOf(tamingSummon.getSummonLifespan())); } else { - NotificationManager.sendPlayerInformationChatOnly(player, "Taming.Summon.COTW.Success.WithoutLifespan", StringUtils.getCapitalized(callOfTheWildType.toString())); + NotificationManager.sendPlayerInformationChatOnly(player, + "Taming.Summon.COTW.Success.WithoutLifespan", + StringUtils.getCapitalized(callOfTheWildType.toString())); } //Send Sound - SoundManager.sendSound(player, player.getLocation(), SoundType.ABILITY_ACTIVATED_GENERIC); + SoundManager.sendSound(player, player.getLocation(), + SoundType.ABILITY_ACTIVATED_GENERIC); amountSummoned++; } @@ -370,7 +422,8 @@ public class TamingManager extends SkillManager { //Remove items from the player if they had at least one entity summoned successfully if (amountSummoned >= 1) { //Remove the items used to summon - int itemAmountAfterPayingCost = itemInMainHand.getAmount() - tamingSummon.getItemAmountRequired(); + int itemAmountAfterPayingCost = + itemInMainHand.getAmount() - tamingSummon.getItemAmountRequired(); itemInMainHand.setAmount(itemAmountAfterPayingCost); player.updateInventory(); } @@ -378,12 +431,15 @@ public class TamingManager extends SkillManager { } else { //Player did not have enough of the item in their main hand int difference = tamingSummon.getItemAmountRequired() - itemInMainHand.getAmount(); - NotificationManager.sendPlayerInformationChatOnly(player, "Taming.Summon.COTW.NeedMoreItems", String.valueOf(difference), StringUtils.getPrettyMaterialString(itemInMainHand.getType())); + NotificationManager.sendPlayerInformationChatOnly(player, + "Taming.Summon.COTW.NeedMoreItems", String.valueOf(difference), + StringUtils.getPrettyMaterialString(itemInMainHand.getType())); } } } - private void spawnCOTWEntity(CallOfTheWildType callOfTheWildType, Location spawnLocation, EntityType entityType) { + private void spawnCOTWEntity(CallOfTheWildType callOfTheWildType, Location spawnLocation, + EntityType entityType) { switch (callOfTheWildType) { case CAT -> //Entity type is needed for cats because in 1.13 and below we spawn ocelots, in 1.14 and above we spawn cats @@ -394,7 +450,8 @@ public class TamingManager extends SkillManager { } private void spawnWolf(Location spawnLocation) { - LivingEntity callOfWildEntity = (LivingEntity) getPlayer().getWorld().spawnEntity(spawnLocation, EntityType.WOLF); + LivingEntity callOfWildEntity = (LivingEntity) getPlayer().getWorld() + .spawnEntity(spawnLocation, EntityType.WOLF); //This is used to prevent XP gains for damaging this entity applyMetaDataToCOTWEntity(callOfWildEntity); @@ -408,12 +465,15 @@ public class TamingManager extends SkillManager { callOfWildEntity.setMaxHealth(20.0); callOfWildEntity.setHealth(callOfWildEntity.getMaxHealth()); - callOfWildEntity.setCustomName(LocaleLoader.getString("Taming.Summon.Name.Format", getPlayer().getName(), StringUtils.getPrettyEntityTypeString(EntityType.WOLF))); + callOfWildEntity.setCustomName( + LocaleLoader.getString("Taming.Summon.Name.Format", getPlayer().getName(), + StringUtils.getPrettyEntityTypeString(EntityType.WOLF))); } @SuppressWarnings("deprecation") private void spawnCat(Location spawnLocation, EntityType entityType) { - LivingEntity callOfWildEntity = (LivingEntity) getPlayer().getWorld().spawnEntity(spawnLocation, entityType); + LivingEntity callOfWildEntity = (LivingEntity) getPlayer().getWorld() + .spawnEntity(spawnLocation, entityType); //This is used to prevent XP gains for damaging this entity applyMetaDataToCOTWEntity(callOfWildEntity); @@ -426,19 +486,23 @@ public class TamingManager extends SkillManager { if (callOfWildEntity instanceof Ocelot) { // Ocelot.Type is deprecated, but that's fine since this only runs on 1.13 int numberOfTypes = Ocelot.Type.values().length; - ((Ocelot) callOfWildEntity).setCatType(Ocelot.Type.values()[Misc.getRandom().nextInt(numberOfTypes)]); + ((Ocelot) callOfWildEntity).setCatType( + Ocelot.Type.values()[Misc.getRandom().nextInt(numberOfTypes)]); } ((Ageable) callOfWildEntity).setAdult(); - callOfWildEntity.setCustomName(LocaleLoader.getString("Taming.Summon.Name.Format", getPlayer().getName(), StringUtils.getPrettyEntityTypeString(entityType))); + callOfWildEntity.setCustomName( + LocaleLoader.getString("Taming.Summon.Name.Format", getPlayer().getName(), + StringUtils.getPrettyEntityTypeString(entityType))); //Particle effect ParticleEffectUtils.playCallOfTheWildEffect(callOfWildEntity); } private void spawnHorse(Location spawnLocation) { - LivingEntity callOfWildEntity = (LivingEntity) getPlayer().getWorld().spawnEntity(spawnLocation, EntityType.HORSE); + LivingEntity callOfWildEntity = (LivingEntity) getPlayer().getWorld() + .spawnEntity(spawnLocation, EntityType.HORSE); applyMetaDataToCOTWEntity(callOfWildEntity); setBaseCOTWEntityProperties(callOfWildEntity); @@ -452,12 +516,16 @@ public class TamingManager extends SkillManager { callOfWildEntity.setHealth(callOfWildEntity.getMaxHealth()); horse.setColor(Horse.Color.values()[Misc.getRandom().nextInt(Horse.Color.values().length)]); horse.setStyle(Horse.Style.values()[Misc.getRandom().nextInt(Horse.Style.values().length)]); - horse.setJumpStrength(Math.max(mcMMO.p.getAdvancedConfig().getMinHorseJumpStrength(), Math.min(Math.min(Misc.getRandom().nextDouble(), Misc.getRandom().nextDouble()) * 2, mcMMO.p.getAdvancedConfig().getMaxHorseJumpStrength()))); + horse.setJumpStrength(Math.max(mcMMO.p.getAdvancedConfig().getMinHorseJumpStrength(), + Math.min(Math.min(Misc.getRandom().nextDouble(), Misc.getRandom().nextDouble()) * 2, + mcMMO.p.getAdvancedConfig().getMaxHorseJumpStrength()))); horse.setAdult(); //TODO: setSpeed, once available - callOfWildEntity.setCustomName(LocaleLoader.getString("Taming.Summon.Name.Format", getPlayer().getName(), StringUtils.getPrettyEntityTypeString(EntityType.HORSE))); + callOfWildEntity.setCustomName( + LocaleLoader.getString("Taming.Summon.Name.Format", getPlayer().getName(), + StringUtils.getPrettyEntityTypeString(EntityType.HORSE))); //Particle effect ParticleEffectUtils.playCallOfTheWildEffect(callOfWildEntity); @@ -475,6 +543,7 @@ public class TamingManager extends SkillManager { /** * Whether the itemstack is used for COTW + * * @param itemStack target ItemStack * @return true if it is used for any COTW */ @@ -483,17 +552,19 @@ public class TamingManager extends SkillManager { } private int getAmountCurrentlySummoned(@NotNull CallOfTheWildType callOfTheWildType) { - return mcMMO.getTransientEntityTracker().getActiveSummonsForPlayerOfType(getPlayer().getUniqueId(), callOfTheWildType); + return mcMMO.getTransientEntityTracker() + .getActiveSummonsForPlayerOfType(getPlayer().getUniqueId(), callOfTheWildType); } - private void addToTracker(@NotNull LivingEntity livingEntity, @NotNull CallOfTheWildType callOfTheWildType) { + private void addToTracker(@NotNull LivingEntity livingEntity, + @NotNull CallOfTheWildType callOfTheWildType) { mcMMO.getTransientEntityTracker().addSummon(getPlayer().getUniqueId(), new TrackedTamingEntity(livingEntity, callOfTheWildType, getPlayer())); } /** - * Remove all tracked entities from existence if they currently exist - * Clear the tracked entity lists afterwards + * Remove all tracked entities from existence if they currently exist Clear the tracked entity + * lists afterwards */ //TODO: The way this tracker was written is garbo, I should just rewrite it, I'll save that for a future update public void cleanupAllSummons() { diff --git a/src/main/java/com/gmail/nossr50/skills/taming/TrackedTamingEntity.java b/src/main/java/com/gmail/nossr50/skills/taming/TrackedTamingEntity.java index 746a37cd6..e004a5e7a 100644 --- a/src/main/java/com/gmail/nossr50/skills/taming/TrackedTamingEntity.java +++ b/src/main/java/com/gmail/nossr50/skills/taming/TrackedTamingEntity.java @@ -4,26 +4,27 @@ import com.gmail.nossr50.datatypes.skills.subskills.taming.CallOfTheWildType; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.CancellableRunnable; import com.gmail.nossr50.util.Misc; +import java.util.UUID; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.UUID; - public class TrackedTamingEntity extends CancellableRunnable { private final @NotNull LivingEntity livingEntity; private final @NotNull CallOfTheWildType callOfTheWildType; private final @NotNull Player player; private final @NotNull UUID playerUUID; - public TrackedTamingEntity(@NotNull LivingEntity livingEntity, @NotNull CallOfTheWildType callOfTheWildType, - @NotNull Player player) { + public TrackedTamingEntity(@NotNull LivingEntity livingEntity, + @NotNull CallOfTheWildType callOfTheWildType, + @NotNull Player player) { this.player = player; this.playerUUID = player.getUniqueId(); this.callOfTheWildType = callOfTheWildType; this.livingEntity = livingEntity; - int tamingCOTWLength = mcMMO.p.getGeneralConfig().getTamingCOTWLength(callOfTheWildType.getConfigEntityTypeEntry()); + int tamingCOTWLength = mcMMO.p.getGeneralConfig() + .getTamingCOTWLength(callOfTheWildType.getConfigEntityTypeEntry()); if (tamingCOTWLength > 0) { int length = tamingCOTWLength * Misc.TICK_CONVERSION_FACTOR; @@ -33,7 +34,8 @@ public class TrackedTamingEntity extends CancellableRunnable { @Override public void run() { - mcMMO.getTransientEntityTracker().killSummonAndCleanMobFlags(this.getLivingEntity(), player, true); + mcMMO.getTransientEntityTracker() + .killSummonAndCleanMobFlags(this.getLivingEntity(), player, true); mcMMO.getTransientEntityTracker().removeSummonFromTracker(playerUUID, this); this.cancel(); } 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 2e759f7df..407e20a8c 100644 --- a/src/main/java/com/gmail/nossr50/skills/unarmed/Unarmed.java +++ b/src/main/java/com/gmail/nossr50/skills/unarmed/Unarmed.java @@ -8,7 +8,8 @@ import org.bukkit.event.entity.EntityPickupItemEvent; import org.bukkit.inventory.ItemStack; public class Unarmed { - public static boolean blockCrackerSmoothBrick = mcMMO.p.getGeneralConfig().getUnarmedBlockCrackerSmoothbrickToCracked(); + public static boolean blockCrackerSmoothBrick = mcMMO.p.getGeneralConfig() + .getUnarmedBlockCrackerSmoothbrickToCracked(); public static double berserkDamageModifier = 1.5; public static void handleItemPickup(Player player, EntityPickupItemEvent event) { @@ -19,12 +20,14 @@ 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) { @@ -32,9 +35,11 @@ public class Unarmed { 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()); @@ -44,7 +49,8 @@ public class Unarmed { } else { //Add what we can from this stack ItemStack modifiedAmount = storageContents[i]; - int amountThatCanFit = storageContents[i].getMaxStackSize() - storageContents[i].getAmount(); + int amountThatCanFit = + storageContents[i].getMaxStackSize() - storageContents[i].getAmount(); modifiedAmount.setAmount(amountThatCanFit); player.getInventory().setItem(i, modifiedAmount); @@ -56,10 +62,11 @@ public class Unarmed { } } - if (amount <= 0) + if (amount <= 0) { event.getItem().remove(); //Cleanup Item - else + } else { event.getItem().getItemStack().setAmount(amount); + } event.setCancelled(true); 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 741618b6d..6cc57ab88 100644 --- a/src/main/java/com/gmail/nossr50/skills/unarmed/UnarmedManager.java +++ b/src/main/java/com/gmail/nossr50/skills/unarmed/UnarmedManager.java @@ -1,5 +1,7 @@ package com.gmail.nossr50.skills.unarmed; +import static com.gmail.nossr50.util.random.ProbabilityUtil.isSkillRNGSuccessful; + import com.gmail.nossr50.api.ItemSpawnReason; import com.gmail.nossr50.datatypes.interactions.NotificationType; import com.gmail.nossr50.datatypes.player.McMMOPlayer; @@ -9,7 +11,11 @@ import com.gmail.nossr50.datatypes.skills.SuperAbilityType; import com.gmail.nossr50.datatypes.skills.ToolType; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.skills.SkillManager; -import com.gmail.nossr50.util.*; +import com.gmail.nossr50.util.EventUtils; +import com.gmail.nossr50.util.ItemUtils; +import com.gmail.nossr50.util.MetadataConstants; +import com.gmail.nossr50.util.Misc; +import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.NotificationManager; import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.random.ProbabilityUtil; @@ -22,12 +28,10 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import static com.gmail.nossr50.util.random.ProbabilityUtil.isSkillRNGSuccessful; - public class UnarmedManager extends SkillManager { - public UnarmedManager(McMMOPlayer mcMMOPlayer) { - super(mcMMOPlayer, PrimarySkillType.UNARMED); + public UnarmedManager(McMMOPlayer mmoPlayer) { + super(mmoPlayer, PrimarySkillType.UNARMED); } public boolean canActivateAbility() { @@ -35,8 +39,9 @@ public class UnarmedManager extends SkillManager { } public boolean canUseSteelArm() { - if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_STEEL_ARM_STYLE)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_STEEL_ARM_STYLE)) { return false; + } return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.UNARMED_STEEL_ARM_STYLE); } @@ -46,30 +51,37 @@ 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); + 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(); - return ItemUtils.isUnarmed(player.getInventory().getItemInMainHand()) && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.UNARMED_ARROW_DEFLECT); + return ItemUtils.isUnarmed(player.getInventory().getItemInMainHand()) + && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.UNARMED_ARROW_DEFLECT); } 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); } public void blockCrackerCheck(@NotNull BlockState blockState) { - if (!ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.UNARMED_BLOCK_CRACKER, mmoPlayer)) { + if (!ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.UNARMED_BLOCK_CRACKER, + mmoPlayer)) { return; } @@ -100,24 +112,29 @@ public class UnarmedManager extends SkillManager { * @param defender The defending player */ public void disarmCheck(@NotNull Player defender) { - if (isSkillRNGSuccessful(SubSkillType.UNARMED_DISARM, mmoPlayer, mmoPlayer.getAttackStrength()) + if (isSkillRNGSuccessful(SubSkillType.UNARMED_DISARM, mmoPlayer, + mmoPlayer.getAttackStrength()) && !hasIronGrip(defender)) { if (EventUtils.callDisarmEvent(defender).isCancelled()) { return; } - if (UserManager.getPlayer(defender) == null) + if (UserManager.getPlayer(defender) == null) { return; + } final Item item = ItemUtils.spawnItem(getPlayer(), defender.getLocation(), - defender.getInventory().getItemInMainHand(), ItemSpawnReason.UNARMED_DISARMED_ITEM); + defender.getInventory().getItemInMainHand(), + ItemSpawnReason.UNARMED_DISARMED_ITEM); if (item != null && mcMMO.p.getAdvancedConfig().getDisarmProtected()) { - item.setMetadata(MetadataConstants.METADATA_KEY_DISARMED_ITEM, UserManager.getPlayer(defender).getPlayerMetadata()); + item.setMetadata(MetadataConstants.METADATA_KEY_DISARMED_ITEM, + UserManager.getPlayer(defender).getPlayerMetadata()); } defender.getInventory().setItemInMainHand(new ItemStack(Material.AIR)); - NotificationManager.sendPlayerInformation(defender, NotificationType.SUBSKILL_MESSAGE, "Skills.Disarmed"); + NotificationManager.sendPlayerInformation(defender, NotificationType.SUBSKILL_MESSAGE, + "Skills.Disarmed"); } } @@ -126,7 +143,8 @@ public class UnarmedManager extends SkillManager { */ public boolean deflectCheck() { if (isSkillRNGSuccessful(SubSkillType.UNARMED_ARROW_DEFLECT, mmoPlayer)) { - NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Combat.ArrowDeflect"); + NotificationManager.sendPlayerInformation(getPlayer(), + NotificationType.SUBSKILL_MESSAGE, "Combat.ArrowDeflect"); return true; } @@ -139,7 +157,8 @@ public class UnarmedManager extends SkillManager { * @param damage The amount of damage initially dealt by the event */ public double berserkDamage(double damage) { - damage = ((damage * Unarmed.berserkDamageModifier) * mmoPlayer.getAttackStrength()) - damage; + damage = + ((damage * Unarmed.berserkDamageModifier) * mmoPlayer.getAttackStrength()) - damage; return damage; } @@ -148,7 +167,8 @@ public class UnarmedManager extends SkillManager { * Handle the effects of the Iron Arm ability */ public double calculateSteelArmStyleDamage() { - if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.UNARMED_STEEL_ARM_STYLE, mmoPlayer)) { + if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.UNARMED_STEEL_ARM_STYLE, + mmoPlayer)) { return getSteelArmStyleDamage(); } @@ -160,14 +180,16 @@ public class UnarmedManager extends SkillManager { double bonus = 0; - if (rank >= 18) + if (rank >= 18) { bonus = 1 + rank - 18; + } double finalBonus = bonus + 0.5 + (rank / 2); - if (mcMMO.p.getAdvancedConfig().isSteelArmDamageCustom()) { - return mcMMO.p.getAdvancedConfig().getSteelArmOverride(RankUtils.getRank(getPlayer(), SubSkillType.UNARMED_STEEL_ARM_STYLE), finalBonus); + return mcMMO.p.getAdvancedConfig().getSteelArmOverride( + RankUtils.getRank(getPlayer(), SubSkillType.UNARMED_STEEL_ARM_STYLE), + finalBonus); } else { return finalBonus; } @@ -182,9 +204,12 @@ public class UnarmedManager extends SkillManager { private boolean hasIronGrip(@NotNull Player defender) { if (!Misc.isNPCEntityExcludingVillagers(defender) && Permissions.isSubSkillEnabled(defender, SubSkillType.UNARMED_IRON_GRIP) - && isSkillRNGSuccessful(SubSkillType.UNARMED_IRON_GRIP, UserManager.getPlayer(defender))) { - NotificationManager.sendPlayerInformation(defender, NotificationType.SUBSKILL_MESSAGE, "Unarmed.Ability.IronGrip.Defender"); - NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Unarmed.Ability.IronGrip.Attacker"); + && isSkillRNGSuccessful(SubSkillType.UNARMED_IRON_GRIP, + UserManager.getPlayer(defender))) { + NotificationManager.sendPlayerInformation(defender, NotificationType.SUBSKILL_MESSAGE, + "Unarmed.Ability.IronGrip.Defender"); + NotificationManager.sendPlayerInformation(getPlayer(), + NotificationType.SUBSKILL_MESSAGE, "Unarmed.Ability.IronGrip.Attacker"); return true; } diff --git a/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java b/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java index 58d13c37e..17b2d497c 100644 --- a/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java @@ -1,5 +1,9 @@ package com.gmail.nossr50.skills.woodcutting; +import static com.gmail.nossr50.util.ItemUtils.spawnItemsFromCollection; +import static com.gmail.nossr50.util.Misc.getBlockCenter; +import static com.gmail.nossr50.util.skills.RankUtils.hasUnlockedSubskill; + import com.gmail.nossr50.api.FakeBlockBreakEventType; import com.gmail.nossr50.api.ItemSpawnReason; import com.gmail.nossr50.config.experience.ExperienceConfig; @@ -12,12 +16,22 @@ import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.SuperAbilityType; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.skills.SkillManager; -import com.gmail.nossr50.util.*; +import com.gmail.nossr50.util.BlockUtils; +import com.gmail.nossr50.util.EventUtils; +import com.gmail.nossr50.util.ItemUtils; +import com.gmail.nossr50.util.Misc; +import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.NotificationManager; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.skills.SkillUtils; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ThreadLocalRandom; +import java.util.function.Predicate; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.Block; @@ -30,17 +44,6 @@ import org.bukkit.inventory.meta.Damageable; import org.bukkit.inventory.meta.ItemMeta; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.ThreadLocalRandom; -import java.util.function.Predicate; - -import static com.gmail.nossr50.util.ItemUtils.spawnItemsFromCollection; -import static com.gmail.nossr50.util.Misc.getBlockCenter; -import static com.gmail.nossr50.util.skills.RankUtils.hasUnlockedSubskill; - public class WoodcuttingManager extends SkillManager { public static final String SAPLING = "sapling"; public static final String PROPAGULE = "propagule"; @@ -51,19 +54,20 @@ public class WoodcuttingManager extends SkillManager { private static int treeFellerThreshold; /** - * The x/y differences to the blocks in a flat cylinder around the center - * block, which is excluded. + * 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}, + 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}, }; - public WoodcuttingManager(McMMOPlayer mcMMOPlayer) { - super(mcMMOPlayer, PrimarySkillType.WOODCUTTING); + public WoodcuttingManager(McMMOPlayer mmoPlayer) { + super(mmoPlayer, PrimarySkillType.WOODCUTTING); treeFellerThreshold = mcMMO.p.getGeneralConfig().getTreeFellerThreshold(); } @@ -81,15 +85,19 @@ public class WoodcuttingManager extends SkillManager { private boolean checkHarvestLumberActivation(Material material) { return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.WOODCUTTING_HARVEST_LUMBER) && RankUtils.hasReachedRank(1, getPlayer(), SubSkillType.WOODCUTTING_HARVEST_LUMBER) - && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.WOODCUTTING_HARVEST_LUMBER, mmoPlayer) - && mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, material); + && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.WOODCUTTING_HARVEST_LUMBER, + mmoPlayer) + && mcMMO.p.getGeneralConfig() + .getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, material); } private boolean checkCleanCutsActivation(Material material) { return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.WOODCUTTING_HARVEST_LUMBER) && RankUtils.hasReachedRank(1, getPlayer(), SubSkillType.WOODCUTTING_HARVEST_LUMBER) - && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.WOODCUTTING_CLEAN_CUTS, mmoPlayer) - && mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, material); + && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.WOODCUTTING_CLEAN_CUTS, + mmoPlayer) + && mcMMO.p.getGeneralConfig() + .getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, material); } /** @@ -104,7 +112,8 @@ public class WoodcuttingManager extends SkillManager { public void processBonusDropCheck(@NotNull Block block) { //TODO: Why isn't this using the item drop event? Potentially because of Tree Feller? This should be adjusted either way. - if (mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, block.getType())) { + if (mcMMO.p.getGeneralConfig() + .getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, block.getType())) { //Mastery enabled for player if (Permissions.canUseSubSkill(getPlayer(), SubSkillType.WOODCUTTING_CLEAN_CUTS)) { if (checkCleanCutsActivation(block.getType())) { @@ -118,7 +127,8 @@ public class WoodcuttingManager extends SkillManager { } } //No Mastery (no Clean Cuts) - } else if (Permissions.canUseSubSkill(getPlayer(), SubSkillType.WOODCUTTING_HARVEST_LUMBER)) { + } else if (Permissions.canUseSubSkill(getPlayer(), + SubSkillType.WOODCUTTING_HARVEST_LUMBER)) { if (checkHarvestLumberActivation(block.getType())) { spawnHarvestLumberBonusDrops(block); } @@ -132,8 +142,9 @@ public class WoodcuttingManager extends SkillManager { } public void processWoodcuttingBlockXP(@NotNull Block block) { - if (mcMMO.getUserBlockTracker().isIneligible(block)) + if (mcMMO.getUserBlockTracker().isIneligible(block)) { return; + } int xp = getExperienceFromLog(block); applyXpGain(xp, XPGainReason.PVE, XPGainSource.SELF); @@ -153,8 +164,11 @@ public class WoodcuttingManager extends SkillManager { processTree(startingBlock, treeFellerBlocks); // If the tool can't sustain the durability loss - if (!handleDurabilityLoss(treeFellerBlocks, player.getInventory().getItemInMainHand(), player)) { - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE_FAILED, "Woodcutting.Skills.TreeFeller.Splinter"); + if (!handleDurabilityLoss(treeFellerBlocks, player.getInventory().getItemInMainHand(), + player)) { + NotificationManager.sendPlayerInformation(player, + NotificationType.SUBSKILL_MESSAGE_FAILED, + "Woodcutting.Skills.TreeFeller.Splinter"); double health = player.getHealth(); @@ -173,35 +187,34 @@ public class WoodcuttingManager extends SkillManager { /** * Process the tree feller ability. *

- * Algorithm: An int[][] of X/Z directions is created on static class - * initialization, representing a cylinder with radius of about 2 - the - * (0,0) center and all (+-2, +-2) corners are omitted. + * Algorithm: An int[][] of X/Z directions is created on static class initialization, + * representing a cylinder with radius of about 2 - the (0,0) center and all (+-2, +-2) corners + * are omitted. *

* processTreeFellerTargetBlock() returns a boolean, which is used for the sole purpose of * switching between these two behaviors: *

* (Call blockState "this log" for the below explanation.) *

- * [A] There is another log above this log (TRUNK) - * Only the flat cylinder in the directions array is searched. - * [B] There is not another log above this log (BRANCH AND TOP) - * The cylinder in the directions array is extended up and down by 1 - * block in the Y-axis, and the block below this log is checked as - * well. Due to the fact that the directions array will catch all - * blocks on a red mushroom, the special method for it is eliminated. + * [A] There is another log above this log (TRUNK) Only the flat cylinder in the directions + * array is searched. [B] There is not another log above this log (BRANCH AND TOP) The cylinder + * in the directions array is extended up and down by 1 block in the Y-axis, and the block below + * this log is checked as well. Due to the fact that the directions array will catch all blocks + * on a red mushroom, the special method for it is eliminated. *

- * This algorithm has been shown to achieve a performance of 2-5 - * milliseconds on regular trees and 10-15 milliseconds on jungle trees - * once the JIT has optimized the function (use the ability about 4 times - * before taking measurements). + * This algorithm has been shown to achieve a performance of 2-5 milliseconds on regular trees + * and 10-15 milliseconds on jungle trees once the JIT has optimized the function (use the + * ability about 4 times before taking measurements). */ private void processTree(Block block, Set treeFellerBlocks) { List futureCenterBlocks = new ArrayList<>(); // Check the block up and take different behavior (smaller search) if it's a log - if (processTreeFellerTargetBlock(block.getRelative(BlockFace.UP), futureCenterBlocks, treeFellerBlocks)) { + if (processTreeFellerTargetBlock(block.getRelative(BlockFace.UP), futureCenterBlocks, + treeFellerBlocks)) { for (int[] dir : directions) { - processTreeFellerTargetBlock(block.getRelative(dir[0], 0, dir[1]), futureCenterBlocks, treeFellerBlocks); + processTreeFellerTargetBlock(block.getRelative(dir[0], 0, dir[1]), + futureCenterBlocks, treeFellerBlocks); if (treeFellerReachedThreshold) { return; @@ -209,11 +222,13 @@ public class WoodcuttingManager extends SkillManager { } } else { // Cover DOWN - processTreeFellerTargetBlock(block.getRelative(BlockFace.DOWN), futureCenterBlocks, treeFellerBlocks); + processTreeFellerTargetBlock(block.getRelative(BlockFace.DOWN), futureCenterBlocks, + treeFellerBlocks); // Search in a cube for (int y = -1; y <= 1; y++) { for (int[] dir : directions) { - processTreeFellerTargetBlock(block.getRelative(dir[0], y, dir[1]), futureCenterBlocks, treeFellerBlocks); + processTreeFellerTargetBlock(block.getRelative(dir[0], y, dir[1]), + futureCenterBlocks, treeFellerBlocks); if (treeFellerReachedThreshold) { return; @@ -241,7 +256,7 @@ public class WoodcuttingManager extends SkillManager { * @return True if the tool can sustain the durability loss */ private static boolean handleDurabilityLoss(@NotNull Set treeFellerBlocks, - @NotNull ItemStack inHand, @NotNull Player player) { + @NotNull ItemStack inHand, @NotNull Player player) { //Treat the NBT tag for unbreakable and the durability enchant differently ItemMeta meta = inHand.getItemMeta(); @@ -260,7 +275,8 @@ public class WoodcuttingManager extends SkillManager { // Call PlayerItemDamageEvent first to make sure it's not cancelled //TODO: Put this event stuff in handleDurabilityChange - final PlayerItemDamageEvent event = new PlayerItemDamageEvent(player, inHand, durabilityLoss); + final PlayerItemDamageEvent event = new PlayerItemDamageEvent(player, inHand, + durabilityLoss); Bukkit.getPluginManager().callEvent(event); if (event.isCancelled()) { @@ -268,27 +284,24 @@ public class WoodcuttingManager extends SkillManager { } SkillUtils.handleDurabilityChange(inHand, durabilityLoss); - int durability = meta instanceof Damageable ? ((Damageable) meta).getDamage(): 0; + int durability = meta instanceof Damageable ? ((Damageable) meta).getDamage() : 0; return (durability < (mcMMO.getRepairableManager().isRepairable(type) ? mcMMO.getRepairableManager().getRepairable(type).getMaximumDurability() : type.getMaxDurability())); } /** - * Handle a block addition to the list of blocks to be removed and to the - * list of blocks used for future recursive calls of - * 'processTree()' + * Handle a block addition to the list of blocks to be removed and to the list of blocks used + * for future recursive calls of 'processTree()' * * @param block Block to be added - * @param futureCenterBlocks List of blocks that will be used to call - * 'processTree()' + * @param futureCenterBlocks List of blocks that will be used to call 'processTree()' * @param treeFellerBlocks List of blocks to be removed - * @return true if and only if the given block was a Log not already - * in treeFellerBlocks. + * @return true if and only if the given block was a Log not already in treeFellerBlocks. */ private boolean processTreeFellerTargetBlock(@NotNull Block block, - @NotNull List futureCenterBlocks, - @NotNull Set treeFellerBlocks) { + @NotNull List futureCenterBlocks, + @NotNull Set treeFellerBlocks) { if (treeFellerBlocks.contains(block) || mcMMO.getUserBlockTracker().isIneligible(block)) { return false; } @@ -323,7 +336,8 @@ public class WoodcuttingManager extends SkillManager { for (Block block : treeFellerBlocks) { int beforeXP = xp; - if (!EventUtils.simulateBlockBreak(block, player, FakeBlockBreakEventType.TREE_FELLER)) { + if (!EventUtils.simulateBlockBreak(block, player, + FakeBlockBreakEventType.TREE_FELLER)) { continue; } @@ -361,9 +375,11 @@ public class WoodcuttingManager extends SkillManager { //Drop displaced non-woodcutting XP blocks if (hasUnlockedSubskill(player, SubSkillType.WOODCUTTING_KNOCK_ON_WOOD)) { - if (RankUtils.hasReachedRank(2, player, SubSkillType.WOODCUTTING_KNOCK_ON_WOOD)) { + if (RankUtils.hasReachedRank(2, player, + SubSkillType.WOODCUTTING_KNOCK_ON_WOOD)) { if (mcMMO.p.getAdvancedConfig().isKnockOnWoodXPOrbEnabled()) { - if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.WOODCUTTING, mmoPlayer, 10)) { + if (ProbabilityUtil.isStaticSkillRNGSuccessful( + PrimarySkillType.WOODCUTTING, mmoPlayer, 10)) { int randOrbCount = Math.max(1, Misc.getRandom().nextInt(100)); Misc.spawnExperienceOrb(block.getLocation(), randOrbCount); } @@ -382,37 +398,42 @@ public class WoodcuttingManager extends SkillManager { } private int updateProcessedLogCount(int xp, int processedLogCount, int beforeXP) { - if (beforeXP != xp) - processedLogCount+=1; + if (beforeXP != xp) { + processedLogCount += 1; + } return processedLogCount; } /** - * Retrieves the experience reward from logging via Tree Feller - * Experience is reduced per log processed so far - * Experience is only reduced if the config option to reduce Tree Feller XP is set - * Experience per log will not fall below 1 unless the experience for that log is set to 0 in the config + * Retrieves the experience reward from logging via Tree Feller Experience is reduced per log + * processed so far Experience is only reduced if the config option to reduce Tree Feller XP is + * set Experience per log will not fall below 1 unless the experience for that log is set to 0 + * in the config * * @param block Log being broken * @param woodCount how many logs have given out XP for this tree feller so far * @return Amount of experience */ private static int processTreeFellerXPGains(Block block, int woodCount) { - if (mcMMO.getUserBlockTracker().isIneligible(block)) + if (mcMMO.getUserBlockTracker().isIneligible(block)) { return 0; + } - int rawXP = ExperienceConfig.getInstance().getXp(PrimarySkillType.WOODCUTTING, block.getType()); + int rawXP = ExperienceConfig.getInstance() + .getXp(PrimarySkillType.WOODCUTTING, block.getType()); - if (rawXP <= 0) + if (rawXP <= 0) { return 0; + } if (ExperienceConfig.getInstance().isTreeFellerXPReduced()) { int reducedXP = rawXP - (woodCount * 5); rawXP = Math.max(1, reducedXP); return rawXP; } else { - return ExperienceConfig.getInstance().getXp(PrimarySkillType.WOODCUTTING, block.getType()); + return ExperienceConfig.getInstance() + .getXp(PrimarySkillType.WOODCUTTING, block.getType()); } } diff --git a/src/main/java/com/gmail/nossr50/util/AttributeMapper.java b/src/main/java/com/gmail/nossr50/util/AttributeMapper.java index c9b115b56..c1388c15f 100644 --- a/src/main/java/com/gmail/nossr50/util/AttributeMapper.java +++ b/src/main/java/com/gmail/nossr50/util/AttributeMapper.java @@ -1,14 +1,13 @@ package com.gmail.nossr50.util; import com.gmail.nossr50.mcMMO; -import org.bukkit.attribute.Attribute; - import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Optional; import java.util.stream.Stream; +import org.bukkit.attribute.Attribute; public class AttributeMapper { @@ -39,8 +38,10 @@ public class AttributeMapper { static { MAPPED_MAX_HEALTH = findAttribute(MAX_HEALTH_1_21_3_STR, MAX_HEALTH_1_18_2_STR); - MAPPED_JUMP_STRENGTH = findAttribute(JUMP_STRENGTH_1_23_1, JUMP_STRENGTH_1_21_1, JUMP_STR_1_18_2); - MAPPED_MOVEMENT_SPEED = findAttribute(MOVEMENT_SPEED_1_18_2, MOVEMENT_SPEED_1_21_1, MOVEMENT_SPEED_1_21_3); + MAPPED_JUMP_STRENGTH = findAttribute(JUMP_STRENGTH_1_23_1, JUMP_STRENGTH_1_21_1, + JUMP_STR_1_18_2); + MAPPED_MOVEMENT_SPEED = findAttribute(MOVEMENT_SPEED_1_18_2, MOVEMENT_SPEED_1_21_1, + MOVEMENT_SPEED_1_21_3); } private static Attribute findAttribute(String... keys) { @@ -54,7 +55,8 @@ public class AttributeMapper { // Get the stream() method of the attribute registry Method streamMethod = attributeRegistry.getClass().getMethod("stream"); attributeStream = (Stream) streamMethod.invoke(attributeRegistry); - } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException | NoSuchMethodException | + } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException | + NoSuchMethodException | InvocationTargetException e) { // Fallback to older versions where Attribute is an enum Object[] enumConstants = Attribute.class.getEnumConstants(); @@ -72,7 +74,8 @@ public class AttributeMapper { Object namespacedKey = getKeyMethod.invoke(attr); if (namespacedKey != null) { - Method getKeyStringMethod = namespacedKey.getClass().getMethod("getKey"); + Method getKeyStringMethod = namespacedKey.getClass() + .getMethod("getKey"); attrKey = (String) getKeyStringMethod.invoke(namespacedKey); } @@ -94,8 +97,10 @@ public class AttributeMapper { } } } catch (Exception e) { - mcMMO.p.getLogger().severe("Unable to find the attribute with possible keys: " - + Arrays.toString(keys) + ", mcMMO will not function properly."); + mcMMO.p.getLogger() + .severe("Unable to find the attribute with possible keys: " + + Arrays.toString(keys) + + ", mcMMO will not function properly."); throw new RuntimeException(e); } return false; diff --git a/src/main/java/com/gmail/nossr50/util/BlockUtils.java b/src/main/java/com/gmail/nossr50/util/BlockUtils.java index f5e064225..174a83fb9 100644 --- a/src/main/java/com/gmail/nossr50/util/BlockUtils.java +++ b/src/main/java/com/gmail/nossr50/util/BlockUtils.java @@ -1,5 +1,7 @@ package com.gmail.nossr50.util; +import static java.util.Objects.requireNonNull; + import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.datatypes.meta.BonusDropMeta; import com.gmail.nossr50.datatypes.player.McMMOPlayer; @@ -10,6 +12,7 @@ import com.gmail.nossr50.skills.repair.Repair; import com.gmail.nossr50.skills.salvage.Salvage; import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.random.ProbabilityUtil; +import java.util.HashSet; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; @@ -20,10 +23,6 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.HashSet; - -import static java.util.Objects.requireNonNull; - public final class BlockUtils { public static final String SHORT_GRASS = "SHORT_GRASS"; @@ -36,25 +35,32 @@ public final class BlockUtils { * Mark a block for giving bonus drops, double drops are used if triple is false * * @param blockState target blockstate - * @param triple marks the block to give triple drops + * @param triple marks the block to give triple drops */ @Deprecated(forRemoval = true, since = "2.2.024") public static void markDropsAsBonus(BlockState blockState, boolean triple) { - if (triple) - blockState.getBlock().setMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, new BonusDropMeta(2, mcMMO.p)); - else - blockState.getBlock().setMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, new BonusDropMeta(1, mcMMO.p)); + if (triple) { + blockState.getBlock().setMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, + new BonusDropMeta(2, mcMMO.p)); + } else { + blockState.getBlock().setMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, + new BonusDropMeta(1, mcMMO.p)); + } } public static void markDropsAsBonus(Block block, boolean triple) { - if (triple) - block.setMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, new BonusDropMeta(2, mcMMO.p)); - else - block.setMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, new BonusDropMeta(1, mcMMO.p)); + if (triple) { + block.setMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, + new BonusDropMeta(2, mcMMO.p)); + } else { + block.setMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, + new BonusDropMeta(1, mcMMO.p)); + } } /** - * Util method for compatibility across Minecraft versions, grabs the {@link Material} enum for short_grass + * Util method for compatibility across Minecraft versions, grabs the {@link Material} enum for + * short_grass * * @return the {@link Material} enum for short_grass */ @@ -69,20 +75,24 @@ public final class BlockUtils { } /** - * Set up the state for a block to be seen as unnatural and cleanup any unwanted metadata from the block + * Set up the state for a block to be seen as unnatural and cleanup any unwanted metadata from + * the block + * * @param block target block */ public static void setUnnaturalBlock(@NotNull Block block) { mcMMO.getUserBlockTracker().setIneligible(block); // Failsafe against lingering metadata - if (block.hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) + if (block.hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) { block.removeMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, mcMMO.p); + } } /** - * Cleans up some block metadata when a block breaks and the metadata is no longer needed - * This also sets the blocks coords to false in our chunk store + * Cleans up some block metadata when a block breaks and the metadata is no longer needed This + * also sets the blocks coords to false in our chunk store + * * @param block target block */ public static void cleanupBlockMetadata(Block block) { @@ -95,21 +105,25 @@ public final class BlockUtils { /** * Marks a block to drop extra copies of items + * * @param blockState target blockstate * @param amount amount of extra items to drop */ @Deprecated(forRemoval = true, since = "2.2.024") public static void markDropsAsBonus(BlockState blockState, int amount) { - blockState.setMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, new BonusDropMeta(amount, mcMMO.p)); + blockState.setMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, + new BonusDropMeta(amount, mcMMO.p)); } /** * Marks a block to drop extra copies of items + * * @param block target block * @param amount the number of extra items to drop */ public static void markDropsAsBonus(Block block, int amount) { - block.setMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, new BonusDropMeta(amount, mcMMO.p)); + block.setMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, + new BonusDropMeta(amount, mcMMO.p)); } /** @@ -120,24 +134,27 @@ public final class BlockUtils { * @deprecated Use {@link #checkDoubleDrops(McMMOPlayer, BlockState, SubSkillType)} instead */ @Deprecated(forRemoval = true, since = "2.2.010") - public static boolean checkDoubleDrops(Player player, BlockState blockState, PrimarySkillType ignored, SubSkillType subSkillType) { + public static boolean checkDoubleDrops(Player player, BlockState blockState, + PrimarySkillType ignored, SubSkillType subSkillType) { return checkDoubleDrops(UserManager.getPlayer(player), blockState, subSkillType); } /** * Checks if a player successfully passed the double drop check * - * @param mmoPlayer the player involved in the check - * @param blockState the blockstate of the block + * @param mmoPlayer the player involved in the check + * @param blockState the blockstate of the block * @param subSkillType the subskill involved * @return true if the player succeeded in the check */ @Deprecated(forRemoval = true, since = "2.2.024") - public static boolean checkDoubleDrops(@Nullable McMMOPlayer mmoPlayer, @NotNull BlockState blockState, - @NotNull SubSkillType subSkillType) { + public static boolean checkDoubleDrops(@Nullable McMMOPlayer mmoPlayer, + @NotNull BlockState blockState, + @NotNull SubSkillType subSkillType) { requireNonNull(blockState, "blockState cannot be null"); requireNonNull(subSkillType, "subSkillType cannot be null"); - if (mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(subSkillType.getParentSkill(), blockState.getType()) + if (mcMMO.p.getGeneralConfig() + .getDoubleDropsEnabled(subSkillType.getParentSkill(), blockState.getType()) && Permissions.isSubSkillEnabled(mmoPlayer, subSkillType)) { return ProbabilityUtil.isSkillRNGSuccessful(subSkillType, mmoPlayer); } @@ -147,16 +164,18 @@ public final class BlockUtils { /** * Checks if a player successfully passed the double drop check + * * @param mmoPlayer the player involved in the check * @param block the block * @param subSkillType the subskill involved * @return true if the player succeeded in the check */ public static boolean checkDoubleDrops(@Nullable McMMOPlayer mmoPlayer, @NotNull Block block, - @NotNull SubSkillType subSkillType) { + @NotNull SubSkillType subSkillType) { requireNonNull(block, "block cannot be null"); requireNonNull(subSkillType, "subSkillType cannot be null"); - if (mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(subSkillType.getParentSkill(), block.getType()) + if (mcMMO.p.getGeneralConfig() + .getDoubleDropsEnabled(subSkillType.getParentSkill(), block.getType()) && Permissions.isSubSkillEnabled(mmoPlayer, subSkillType)) { return ProbabilityUtil.isSkillRNGSuccessful(subSkillType, mmoPlayer); } @@ -179,18 +198,21 @@ public final class BlockUtils { || affectedByGreenTerra(material) || affectedBySuperBreaker(material) || hasWoodcuttingXP(material) - || mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.MINING, material) - || mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.EXCAVATION, material) - || mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, material) - || mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.SMELTING, material); + || mcMMO.p.getGeneralConfig() + .getDoubleDropsEnabled(PrimarySkillType.MINING, material) + || mcMMO.p.getGeneralConfig() + .getDoubleDropsEnabled(PrimarySkillType.EXCAVATION, material) + || mcMMO.p.getGeneralConfig() + .getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, material) + || mcMMO.p.getGeneralConfig() + .getDoubleDropsEnabled(PrimarySkillType.SMELTING, material); } /** * Check if a given block should allow for the activation of abilities * * @param blockState The {@link BlockState} of the block to check - * @return true if the block should allow ability activation, false - * otherwise + * @return true if the block should allow ability activation, false otherwise */ @Deprecated(forRemoval = true, since = "2.2.024") public static boolean canActivateAbilities(BlockState blockState) { @@ -202,12 +224,11 @@ public final class BlockUtils { } /** - * Check if a given block should allow for the activation of tools - * Activating a tool is step 1 of a 2 step process for super ability activation + * Check if a given block should allow for the activation of tools Activating a tool is step 1 + * of a 2 step process for super ability activation * * @param blockState The {@link BlockState} of the block to check - * @return true if the block should allow ability activation, false - * otherwise + * @return true if the block should allow ability activation, false otherwise */ public static boolean canActivateTools(BlockState blockState) { return !mcMMO.getMaterialMapStore().isToolActivationBlackListed(blockState.getType()) @@ -227,6 +248,7 @@ public final class BlockUtils { /** * Check if a given block is an ore + * * @param block The {@link Block} to check * @return true if the block is an ore, false otherwise */ @@ -236,6 +258,7 @@ public final class BlockUtils { /** * Check if a given material is an ore + * * @param material The {@link Material} to check * @return true if the material is an ore, false otherwise */ @@ -273,7 +296,8 @@ public final class BlockUtils { } public static boolean affectedByGreenTerra(Material material) { - return ExperienceConfig.getInstance().doesBlockGiveSkillXP(PrimarySkillType.HERBALISM, material); + return ExperienceConfig.getInstance() + .doesBlockGiveSkillXP(PrimarySkillType.HERBALISM, material); } public static boolean affectedBySuperBreaker(BlockState blockState) { @@ -284,26 +308,26 @@ public final class BlockUtils { * Determine if a given block should be affected by Super Breaker * * @param block The {@link Block} to check - * @return true if the block should affected by Super Breaker, false - * otherwise + * @return true if the block should affected by Super Breaker, false otherwise */ public static boolean affectedBySuperBreaker(Block block) { return affectedBySuperBreaker(block.getType()); } public static boolean affectedBySuperBreaker(Material material) { - if (mcMMO.getMaterialMapStore().isIntendedToolPickaxe(material)) + if (mcMMO.getMaterialMapStore().isIntendedToolPickaxe(material)) { return true; + } - return ExperienceConfig.getInstance().doesBlockGiveSkillXP(PrimarySkillType.MINING, material); + return ExperienceConfig.getInstance() + .doesBlockGiveSkillXP(PrimarySkillType.MINING, material); } /** * Determine if a given block should be affected by Giga Drill Breaker * * @param blockState The {@link BlockState} of the block to check - * @return true if the block should be affected by Giga Drill Breaker, false - * otherwise + * @return true if the block should be affected by Giga Drill Breaker, false otherwise */ public static boolean affectedByGigaDrillBreaker(@NotNull BlockState blockState) { return affectedByGigaDrillBreaker(blockState.getType()); @@ -314,7 +338,8 @@ public final class BlockUtils { } public static boolean affectedByGigaDrillBreaker(@NotNull Material material) { - return ExperienceConfig.getInstance().doesBlockGiveSkillXP(PrimarySkillType.EXCAVATION, material); + return ExperienceConfig.getInstance() + .doesBlockGiveSkillXP(PrimarySkillType.EXCAVATION, material); } /** @@ -332,7 +357,8 @@ public final class BlockUtils { } public static boolean hasWoodcuttingXP(@NotNull Material material) { - return ExperienceConfig.getInstance().doesBlockGiveSkillXP(PrimarySkillType.WOODCUTTING, material); + return ExperienceConfig.getInstance() + .doesBlockGiveSkillXP(PrimarySkillType.WOODCUTTING, material); } /** @@ -374,8 +400,7 @@ public final class BlockUtils { * Determine if a given block can activate Herbalism abilities * * @param blockState The {@link BlockState} of the block to check - * @return true if the block can be activate Herbalism abilities, false - * otherwise + * @return true if the block can be activate Herbalism abilities, false otherwise */ public static boolean canActivateHerbalism(BlockState blockState) { return mcMMO.getMaterialMapStore().isHerbalismAbilityWhiteListed(blockState.getType()); @@ -385,8 +410,7 @@ public final class BlockUtils { * Determine if a given block should be affected by Block Cracker * * @param blockState The {@link BlockState} of the block to check - * @return true if the block should affected by Block Cracker, false - * otherwise + * @return true if the block should affected by Block Cracker, false otherwise */ public static boolean affectedByBlockCracker(BlockState blockState) { return affectedByBlockCracker(blockState.getType()); @@ -461,8 +485,10 @@ public final class BlockUtils { } /** - * Checks to see if a Block is within the world bounds - * Prevent processing blocks from other plugins (or perhaps odd spigot anomalies) from sending blocks that can't exist within the world + * Checks to see if a Block is within the world bounds Prevent processing blocks from other + * plugins (or perhaps odd spigot anomalies) from sending blocks that can't exist within the + * world + * * @param block * @return */ diff --git a/src/main/java/com/gmail/nossr50/util/CancellableRunnable.java b/src/main/java/com/gmail/nossr50/util/CancellableRunnable.java index a47cdcda3..23f9eaeaa 100644 --- a/src/main/java/com/gmail/nossr50/util/CancellableRunnable.java +++ b/src/main/java/com/gmail/nossr50/util/CancellableRunnable.java @@ -1,7 +1,6 @@ package com.gmail.nossr50.util; import com.tcoded.folialib.wrapper.task.WrappedTask; - import java.util.function.Consumer; public abstract class CancellableRunnable implements Consumer { diff --git a/src/main/java/com/gmail/nossr50/util/ChimaeraWing.java b/src/main/java/com/gmail/nossr50/util/ChimaeraWing.java index d5c010755..3f9e9b28b 100644 --- a/src/main/java/com/gmail/nossr50/util/ChimaeraWing.java +++ b/src/main/java/com/gmail/nossr50/util/ChimaeraWing.java @@ -9,6 +9,8 @@ import com.gmail.nossr50.util.player.NotificationManager; import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.SkillUtils; +import java.util.ArrayList; +import java.util.List; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; @@ -19,11 +21,9 @@ import org.bukkit.inventory.ShapelessRecipe; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.util.Vector; -import java.util.ArrayList; -import java.util.List; - public final class ChimaeraWing { - private ChimaeraWing() {} + private ChimaeraWing() { + } /** * Check for item usage. @@ -42,47 +42,56 @@ public final class ChimaeraWing { } if (!Permissions.chimaeraWing(player)) { - NotificationManager.sendPlayerInformation(player, NotificationType.NO_PERMISSION, "mcMMO.NoPermission"); + NotificationManager.sendPlayerInformation(player, NotificationType.NO_PERMISSION, + "mcMMO.NoPermission"); return; } - final McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); //Not loaded - if (mcMMOPlayer == null) + if (mmoPlayer == null) { return; + } - if (mcMMOPlayer.getTeleportCommenceLocation() != null) { + if (mmoPlayer.getTeleportCommenceLocation() != null) { return; } int amountInHand = inHand.getAmount(); if (amountInHand < mcMMO.p.getGeneralConfig().getChimaeraUseCost()) { - NotificationManager.sendPlayerInformation(player, NotificationType.REQUIREMENTS_NOT_MET, "Item.ChimaeraWing.NotEnough",String.valueOf(mcMMO.p.getGeneralConfig().getChimaeraUseCost() - amountInHand), "Item.ChimaeraWing.Name"); + NotificationManager.sendPlayerInformation(player, NotificationType.REQUIREMENTS_NOT_MET, + "Item.ChimaeraWing.NotEnough", + String.valueOf(mcMMO.p.getGeneralConfig().getChimaeraUseCost() - amountInHand), + "Item.ChimaeraWing.Name"); return; } - long lastTeleport = mcMMOPlayer.getChimeraWingLastUse(); + long lastTeleport = mmoPlayer.getChimeraWingLastUse(); int cooldown = mcMMO.p.getGeneralConfig().getChimaeraCooldown(); if (cooldown > 0) { - int timeRemaining = SkillUtils.calculateTimeLeft(lastTeleport * Misc.TIME_CONVERSION_FACTOR, cooldown, player); + int timeRemaining = SkillUtils.calculateTimeLeft( + lastTeleport * Misc.TIME_CONVERSION_FACTOR, cooldown, player); if (timeRemaining > 0) { - NotificationManager.sendPlayerInformation(player, NotificationType.ABILITY_COOLDOWN, "Item.Generic.Wait", String.valueOf(timeRemaining)); + NotificationManager.sendPlayerInformation(player, NotificationType.ABILITY_COOLDOWN, + "Item.Generic.Wait", String.valueOf(timeRemaining)); return; } } - long recentlyHurt = mcMMOPlayer.getRecentlyHurt(); + long recentlyHurt = mmoPlayer.getRecentlyHurt(); int hurtCooldown = mcMMO.p.getGeneralConfig().getChimaeraRecentlyHurtCooldown(); if (hurtCooldown > 0) { - int timeRemaining = SkillUtils.calculateTimeLeft(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, hurtCooldown, player); + int timeRemaining = SkillUtils.calculateTimeLeft( + recentlyHurt * Misc.TIME_CONVERSION_FACTOR, hurtCooldown, player); if (timeRemaining > 0) { - NotificationManager.sendPlayerInformation(player, NotificationType.ITEM_MESSAGE, "Item.Injured.Wait", String.valueOf(timeRemaining)); + NotificationManager.sendPlayerInformation(player, NotificationType.ITEM_MESSAGE, + "Item.Injured.Wait", String.valueOf(timeRemaining)); return; } } @@ -97,18 +106,22 @@ public final class ChimaeraWing { player.setVelocity(new Vector(0, 0.5D, 0)); final int dmg = Misc.getRandom().nextInt((int) (player.getHealth() - 10)); CombatUtils.safeDealDamage(player, dmg); - mcMMOPlayer.actualizeChimeraWingLastUse(); + mmoPlayer.actualizeChimeraWingLastUse(); return; } } - mcMMOPlayer.actualizeTeleportCommenceLocation(player); + mmoPlayer.actualizeTeleportCommenceLocation(player); long teleportDelay = mcMMO.p.getGeneralConfig().getChimaeraWarmup(); if (teleportDelay > 0) { - NotificationManager.sendPlayerInformation(player, NotificationType.ITEM_MESSAGE, "Teleport.Commencing", String.valueOf(teleportDelay)); - mcMMO.p.getFoliaLib().getScheduler().runAtEntityLater(player, new ChimaeraWingWarmup(mcMMOPlayer, playerLocation), 20 * teleportDelay); + NotificationManager.sendPlayerInformation(player, NotificationType.ITEM_MESSAGE, + "Teleport.Commencing", String.valueOf(teleportDelay)); + mcMMO.p.getFoliaLib().getScheduler() + .runAtEntityLater(player, new ChimaeraWingWarmup(mmoPlayer, playerLocation), + 20 * teleportDelay); } else { - mcMMO.p.getFoliaLib().getScheduler().runAtEntityLater(player, new ChimaeraWingWarmup(mcMMOPlayer, playerLocation), 0); + mcMMO.p.getFoliaLib().getScheduler() + .runAtEntityLater(player, new ChimaeraWingWarmup(mmoPlayer, playerLocation), 0); } } @@ -142,7 +155,8 @@ public final class ChimaeraWing { Material ingredient = mcMMO.p.getGeneralConfig().getChimaeraItem(); int amount = mcMMO.p.getGeneralConfig().getChimaeraRecipeCost(); - ShapelessRecipe chimeraWing = new ShapelessRecipe(new NamespacedKey(mcMMO.p, "Chimera"), getChimaeraWing(1)); + ShapelessRecipe chimeraWing = new ShapelessRecipe(new NamespacedKey(mcMMO.p, "Chimera"), + getChimaeraWing(1)); chimeraWing.addIngredient(amount, ingredient); return chimeraWing; } diff --git a/src/main/java/com/gmail/nossr50/util/ContainerMetadataUtils.java b/src/main/java/com/gmail/nossr50/util/ContainerMetadataUtils.java index 3844b4f0e..b36b9e682 100644 --- a/src/main/java/com/gmail/nossr50/util/ContainerMetadataUtils.java +++ b/src/main/java/com/gmail/nossr50/util/ContainerMetadataUtils.java @@ -1,7 +1,11 @@ package com.gmail.nossr50.util; +import static com.gmail.nossr50.util.MetadataService.NSK_CONTAINER_UUID_LEAST_SIG; +import static com.gmail.nossr50.util.MetadataService.NSK_CONTAINER_UUID_MOST_SIG; + import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.util.player.UserManager; +import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; @@ -13,14 +17,10 @@ import org.bukkit.persistence.PersistentDataType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.UUID; - -import static com.gmail.nossr50.util.MetadataService.NSK_CONTAINER_UUID_LEAST_SIG; -import static com.gmail.nossr50.util.MetadataService.NSK_CONTAINER_UUID_MOST_SIG; - public class ContainerMetadataUtils { - public static void changeContainerOwnership(@Nullable BlockState blockState, @Nullable Player player) { + public static void changeContainerOwnership(@Nullable BlockState blockState, + @Nullable Player player) { // no-op when the blockState is null or player is null if (blockState == null || player == null) { return; @@ -36,11 +36,12 @@ public class ContainerMetadataUtils { setOwner(blockState, player.getUniqueId()); } - public static void printOwnershipGainDebug(@NotNull BlockState blockState, @Nullable McMMOPlayer mmoPlayer) { + public static void printOwnershipGainDebug(@NotNull BlockState blockState, + @Nullable McMMOPlayer mmoPlayer) { if (mmoPlayer != null && mmoPlayer.isDebugMode()) { mmoPlayer.getPlayer().sendMessage("Container ownership " + - ChatColor.GREEN +"gained " + ChatColor.RESET + - "at location: " + blockState.getLocation().toString()); + ChatColor.GREEN + "gained " + ChatColor.RESET + + "at location: " + blockState.getLocation()); } } @@ -54,7 +55,7 @@ public class ContainerMetadataUtils { if (mmoContainerOwner.isDebugMode()) { mmoContainerOwner.getPlayer().sendMessage("Container ownership " + ChatColor.RED + "lost " + ChatColor.RESET + - "at location: " + blockState.getLocation().toString()); + "at location: " + blockState.getLocation()); } } } @@ -84,8 +85,9 @@ public class ContainerMetadataUtils { } if (getContainerOwner(blockState) != null) { - if (getContainerOwner(blockState).getUniqueId().equals(player.getUniqueId())) + if (getContainerOwner(blockState).getUniqueId().equals(player.getUniqueId())) { return; + } } changeContainerOwnership(blockState, player); @@ -96,8 +98,10 @@ public class ContainerMetadataUtils { final PersistentDataContainer dataContainer = persistentDataHolder.getPersistentDataContainer(); //Too lazy to make a custom data type for this stuff - final Long mostSigBits = dataContainer.get(NSK_CONTAINER_UUID_MOST_SIG, PersistentDataType.LONG); - final Long leastSigBits = dataContainer.get(NSK_CONTAINER_UUID_LEAST_SIG, PersistentDataType.LONG); + final Long mostSigBits = dataContainer.get(NSK_CONTAINER_UUID_MOST_SIG, + PersistentDataType.LONG); + final Long leastSigBits = dataContainer.get(NSK_CONTAINER_UUID_LEAST_SIG, + PersistentDataType.LONG); if (mostSigBits != null && leastSigBits != null) { return new UUID(mostSigBits, leastSigBits); @@ -109,8 +113,10 @@ public class ContainerMetadataUtils { public static void setOwner(@NotNull BlockState blockState, @NotNull UUID uuid) { PersistentDataContainer dataContainer = ((PersistentDataHolder) blockState).getPersistentDataContainer(); - dataContainer.set(NSK_CONTAINER_UUID_MOST_SIG, PersistentDataType.LONG, uuid.getMostSignificantBits()); - dataContainer.set(NSK_CONTAINER_UUID_LEAST_SIG, PersistentDataType.LONG, uuid.getLeastSignificantBits()); + dataContainer.set(NSK_CONTAINER_UUID_MOST_SIG, PersistentDataType.LONG, + uuid.getMostSignificantBits()); + dataContainer.set(NSK_CONTAINER_UUID_LEAST_SIG, PersistentDataType.LONG, + uuid.getLeastSignificantBits()); blockState.update(); } diff --git a/src/main/java/com/gmail/nossr50/util/EnchantmentMapper.java b/src/main/java/com/gmail/nossr50/util/EnchantmentMapper.java index 0b948dd96..474912b1e 100644 --- a/src/main/java/com/gmail/nossr50/util/EnchantmentMapper.java +++ b/src/main/java/com/gmail/nossr50/util/EnchantmentMapper.java @@ -1,14 +1,13 @@ package com.gmail.nossr50.util; import com.gmail.nossr50.mcMMO; +import java.util.Locale; import org.bukkit.NamespacedKey; import org.bukkit.Registry; import org.bukkit.enchantments.Enchantment; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Locale; - public class EnchantmentMapper { private final mcMMO pluginRef; private final Enchantment efficiency; @@ -25,7 +24,7 @@ public class EnchantmentMapper { this.featherFalling = initFeatherFalling(); this.luckOfTheSea = initLuckOfTheSea(); } - + private static @Nullable Enchantment mockSpigotMatch(@NotNull String input) { // Replicates match() behaviour for older versions lacking this API final String filtered = input.toLowerCase(Locale.ROOT).replaceAll("\\s+", "_"); diff --git a/src/main/java/com/gmail/nossr50/util/EnchantmentUtils.java b/src/main/java/com/gmail/nossr50/util/EnchantmentUtils.java index 9e0850ed7..17034f6be 100644 --- a/src/main/java/com/gmail/nossr50/util/EnchantmentUtils.java +++ b/src/main/java/com/gmail/nossr50/util/EnchantmentUtils.java @@ -1,10 +1,9 @@ package com.gmail.nossr50.util; +import java.util.HashMap; import org.bukkit.enchantments.Enchantment; import org.jetbrains.annotations.Nullable; -import java.util.HashMap; - public class EnchantmentUtils { private static final HashMap legacyEnchantments = new HashMap<>(); @@ -35,7 +34,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 */ @SuppressWarnings("deprecation") @@ -48,7 +46,8 @@ public class EnchantmentUtils { } @SuppressWarnings("deprecation") - private static void addLegacyEnchantmentLookup(String enchantmentName, String legacyBukkitName) { + private static void addLegacyEnchantmentLookup(String enchantmentName, + String legacyBukkitName) { if (Enchantment.getByName(legacyBukkitName) != null) { legacyEnchantments.put(enchantmentName, Enchantment.getByName(legacyBukkitName)); } diff --git a/src/main/java/com/gmail/nossr50/util/EventUtils.java b/src/main/java/com/gmail/nossr50/util/EventUtils.java index c83f5a6af..984d24d8b 100644 --- a/src/main/java/com/gmail/nossr50/util/EventUtils.java +++ b/src/main/java/com/gmail/nossr50/util/EventUtils.java @@ -1,5 +1,7 @@ package com.gmail.nossr50.util; +import static java.util.Objects.requireNonNull; + import com.gmail.nossr50.api.FakeBlockBreakEventType; import com.gmail.nossr50.api.TreeFellerBlockBreakEvent; import com.gmail.nossr50.datatypes.experience.XPGainReason; @@ -40,6 +42,8 @@ import com.gmail.nossr50.util.player.NotificationManager; import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.SkillTools; +import java.util.HashMap; +import java.util.Map; import org.bukkit.block.Block; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Entity; @@ -55,21 +59,17 @@ import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.jetbrains.annotations.NotNull; -import java.util.HashMap; -import java.util.Map; - -import static java.util.Objects.requireNonNull; - /** * This class is meant to help make event related code less boilerplate */ public final class EventUtils { /** - * This is a static utility class, therefore we don't want any instances of - * this class. Making the constructor private prevents accidents like that. + * This is a static utility class, therefore we don't want any instances of this class. Making + * the constructor private prevents accidents like that. */ - private EventUtils() {} + private EventUtils() { + } /* * Quality of Life methods @@ -77,11 +77,12 @@ public final class EventUtils { /** * This is a simple check to see if an {@link Event} is fake or not. - * {@link FakeEvent FakeEvents} should not be processed like normally and maybe even - * be ignored by other {@link Plugin plugins} completely. - * + * {@link FakeEvent FakeEvents} should not be processed like normally and maybe even be ignored + * by other {@link Plugin plugins} completely. + * * @param event The {@link Event} in question - * @return Whether this {@link Event} has been faked by mcMMO and should not be processed normally. + * @return Whether this {@link Event} has been faked by mcMMO and should not be processed + * normally. */ public static boolean isFakeEvent(@NotNull Event event) { return event instanceof FakeEvent; @@ -89,23 +90,21 @@ public final 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(@NotNull Entity entity) { - return UserManager.getPlayer((Player)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 - * 4) The player is loaded into our mcMMO user profiles + *

+ * 1) The player is real and not an NPC 2) The player is not in god mode 3) The damage dealt is + * above 0 4) The player is loaded into our mcMMO user profiles * * @param entityDamageEvent * @return @@ -121,8 +120,9 @@ public final class EventUtils { Entity entity = entityDamageEvent.getEntity(); //Check to make sure the entity is not an NPC - if (Misc.isNPCEntityExcludingVillagers(entity)) + if (Misc.isNPCEntityExcludingVillagers(entity)) { return false; + } if (!entity.isValid() || !(entity instanceof LivingEntity livingEntity)) { return false; @@ -133,20 +133,20 @@ public final class EventUtils { } if (livingEntity instanceof Player) { - Player player = (Player) entity; + final Player player = (Player) entity; if (!UserManager.hasPlayerDataKey(player)) { return true; } - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if (mcMMOPlayer == null) { + if (mmoPlayer == null) { return true; } /* Check for invincibility */ - if (mcMMOPlayer.getGodMode()) { + if (mmoPlayer.getGodMode()) { entityDamageEvent.setCancelled(true); return false; } @@ -162,22 +162,26 @@ public final class EventUtils { */ @Deprecated(forRemoval = true, since = "2.2.010") - public static @NotNull McMMOPlayerAbilityActivateEvent callPlayerAbilityActivateEvent(@NotNull Player player, - @NotNull PrimarySkillType skill) { + public static @NotNull McMMOPlayerAbilityActivateEvent callPlayerAbilityActivateEvent( + @NotNull Player player, + @NotNull PrimarySkillType skill) { return callPlayerAbilityActivateEvent(requireNonNull(UserManager.getPlayer(player)), skill); } - public static @NotNull McMMOPlayerAbilityActivateEvent callPlayerAbilityActivateEvent(@NotNull McMMOPlayer mmoPlayer, - @NotNull PrimarySkillType skill) { + public static @NotNull McMMOPlayerAbilityActivateEvent callPlayerAbilityActivateEvent( + @NotNull McMMOPlayer mmoPlayer, + @NotNull PrimarySkillType skill) { requireNonNull(mmoPlayer, "mmoPlayer cannot be null"); requireNonNull(skill, "skill cannot be null"); - McMMOPlayerAbilityActivateEvent event = new McMMOPlayerAbilityActivateEvent(mmoPlayer, skill); + McMMOPlayerAbilityActivateEvent event = new McMMOPlayerAbilityActivateEvent(mmoPlayer, + skill); mcMMO.p.getServer().getPluginManager().callEvent(event); return event; } - public static @NotNull McMMOPlayerProfileLoadEvent callPlayerProfileLoadEvent(@NotNull Player player, @NotNull PlayerProfile profile){ + public static @NotNull McMMOPlayerProfileLoadEvent callPlayerProfileLoadEvent( + @NotNull Player player, @NotNull PlayerProfile profile) { McMMOPlayerProfileLoadEvent event = new McMMOPlayerProfileLoadEvent(player, profile); mcMMO.p.getServer().getPluginManager().callEvent(event); @@ -186,22 +190,26 @@ public final class EventUtils { /** * Calls a new SubSkillEvent for this SubSkill and then returns it + * * @param player target player * @param subSkillType target subskill * @return the event after it has been fired */ @Deprecated(forRemoval = true, since = "2.2.010") - public static @NotNull SubSkillEvent callSubSkillEvent(@NotNull Player player, @NotNull SubSkillType subSkillType) { + public static @NotNull SubSkillEvent callSubSkillEvent(@NotNull Player player, + @NotNull SubSkillType subSkillType) { return callSubSkillEvent(requireNonNull(UserManager.getPlayer(player)), subSkillType); } /** * Calls a new SubSkillEvent for this SubSkill and then returns it + * * @param mmoPlayer target mmoPlayer * @param subSkillType target subskill * @return the event after it has been fired */ - public static @NotNull SubSkillEvent callSubSkillEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull SubSkillType subSkillType) { + public static @NotNull SubSkillEvent callSubSkillEvent(@NotNull McMMOPlayer mmoPlayer, + @NotNull SubSkillType subSkillType) { requireNonNull(mmoPlayer, "mmoPlayer cannot be null"); requireNonNull(subSkillType, "subSkillType cannot be null"); final SubSkillEvent event = new SubSkillEvent(mmoPlayer, subSkillType); @@ -212,20 +220,25 @@ public final class EventUtils { /** * Calls a new SubSkillBlockEvent for this SubSkill and its related block and then returns it + * * @param player target player * @param subSkillType target subskill * @param block associated block * @return the event after it has been fired */ - public static @NotNull SubSkillBlockEvent callSubSkillBlockEvent(@NotNull Player player, @NotNull SubSkillType subSkillType, @NotNull Block block) { + public static @NotNull SubSkillBlockEvent callSubSkillBlockEvent(@NotNull Player player, + @NotNull SubSkillType subSkillType, @NotNull Block block) { SubSkillBlockEvent event = new SubSkillBlockEvent(player, subSkillType, block); mcMMO.p.getServer().getPluginManager().callEvent(event); return event; } - public static boolean tryLevelChangeEvent(Player player, PrimarySkillType skill, int levelsChanged, float xpRemoved, boolean isLevelUp, XPGainReason xpGainReason) { - McMMOPlayerLevelChangeEvent event = isLevelUp ? new McMMOPlayerLevelUpEvent(player, skill, levelsChanged, xpGainReason) : new McMMOPlayerLevelDownEvent(player, skill, levelsChanged, xpGainReason); + public static boolean tryLevelChangeEvent(Player player, PrimarySkillType skill, + int levelsChanged, float xpRemoved, boolean isLevelUp, XPGainReason xpGainReason) { + McMMOPlayerLevelChangeEvent event = + isLevelUp ? new McMMOPlayerLevelUpEvent(player, skill, levelsChanged, xpGainReason) + : new McMMOPlayerLevelDownEvent(player, skill, levelsChanged, xpGainReason); mcMMO.p.getServer().getPluginManager().callEvent(event); boolean isCancelled = event.isCancelled(); @@ -233,26 +246,36 @@ public final class EventUtils { if (isCancelled) { PlayerProfile profile = UserManager.getPlayer(player).getProfile(); - profile.modifySkill(skill, profile.getSkillLevel(skill) - (isLevelUp ? levelsChanged : -levelsChanged)); + profile.modifySkill(skill, + profile.getSkillLevel(skill) - (isLevelUp ? levelsChanged : -levelsChanged)); profile.addXp(skill, xpRemoved); } return isCancelled; } - public static boolean tryLevelChangeEvent(@NotNull McMMOPlayer mmoPlayer, PrimarySkillType skill, int levelsChanged, float xpRemoved, boolean isLevelUp, XPGainReason xpGainReason) { - McMMOPlayerLevelChangeEvent event = isLevelUp ? new McMMOPlayerLevelUpEvent(mmoPlayer.getPlayer(), skill, levelsChanged, xpGainReason) : new McMMOPlayerLevelDownEvent(mmoPlayer.getPlayer(), skill, levelsChanged, xpGainReason); + public static boolean tryLevelChangeEvent(@NotNull McMMOPlayer mmoPlayer, + PrimarySkillType skill, int levelsChanged, float xpRemoved, boolean isLevelUp, + XPGainReason xpGainReason) { + McMMOPlayerLevelChangeEvent event = + isLevelUp ? new McMMOPlayerLevelUpEvent(mmoPlayer.getPlayer(), skill, levelsChanged, + xpGainReason) + : new McMMOPlayerLevelDownEvent(mmoPlayer.getPlayer(), skill, levelsChanged, + xpGainReason); mcMMO.p.getServer().getPluginManager().callEvent(event); boolean isCancelled = event.isCancelled(); if (isCancelled) { - mmoPlayer.modifySkill(skill, mmoPlayer.getSkillLevel(skill) - (isLevelUp ? levelsChanged : -levelsChanged)); + mmoPlayer.modifySkill(skill, + mmoPlayer.getSkillLevel(skill) - (isLevelUp ? levelsChanged : -levelsChanged)); mmoPlayer.addXp(skill, xpRemoved); } else { if (isLevelUp) { - NotificationManager.processLevelUpBroadcasting(mmoPlayer, skill, mmoPlayer.getSkillLevel(skill)); - NotificationManager.processPowerLevelUpBroadcasting(mmoPlayer, mmoPlayer.getPowerLevel()); + NotificationManager.processLevelUpBroadcasting(mmoPlayer, skill, + mmoPlayer.getSkillLevel(skill)); + NotificationManager.processPowerLevelUpBroadcasting(mmoPlayer, + mmoPlayer.getPowerLevel()); } } @@ -260,8 +283,13 @@ public final class EventUtils { return isCancelled; } - public static boolean tryLevelEditEvent(Player player, PrimarySkillType skill, int levelsChanged, float xpRemoved, boolean isLevelUp, XPGainReason xpGainReason, int oldLevel) { - McMMOPlayerLevelChangeEvent event = isLevelUp ? new McMMOPlayerLevelUpEvent(player, skill, levelsChanged - oldLevel, xpGainReason) : new McMMOPlayerLevelDownEvent(player, skill, levelsChanged, xpGainReason); + public static boolean tryLevelEditEvent(Player player, PrimarySkillType skill, + int levelsChanged, float xpRemoved, boolean isLevelUp, XPGainReason xpGainReason, + int oldLevel) { + McMMOPlayerLevelChangeEvent event = + isLevelUp ? new McMMOPlayerLevelUpEvent(player, skill, levelsChanged - oldLevel, + xpGainReason) + : new McMMOPlayerLevelDownEvent(player, skill, levelsChanged, xpGainReason); mcMMO.p.getServer().getPluginManager().callEvent(event); boolean isCancelled = event.isCancelled(); @@ -269,26 +297,36 @@ public final class EventUtils { if (isCancelled) { PlayerProfile profile = UserManager.getPlayer(player).getProfile(); - profile.modifySkill(skill, profile.getSkillLevel(skill) - (isLevelUp ? levelsChanged : -levelsChanged)); + profile.modifySkill(skill, + profile.getSkillLevel(skill) - (isLevelUp ? levelsChanged : -levelsChanged)); profile.addXp(skill, xpRemoved); } return isCancelled; } - public static boolean tryLevelEditEvent(@NotNull McMMOPlayer mmoPlayer, PrimarySkillType skill, int levelsChanged, float xpRemoved, boolean isLevelUp, XPGainReason xpGainReason, int oldLevel) { - McMMOPlayerLevelChangeEvent event = isLevelUp ? new McMMOPlayerLevelUpEvent(mmoPlayer.getPlayer(), skill, levelsChanged - oldLevel, xpGainReason) : new McMMOPlayerLevelDownEvent(mmoPlayer.getPlayer(), skill, levelsChanged, xpGainReason); + public static boolean tryLevelEditEvent(@NotNull McMMOPlayer mmoPlayer, PrimarySkillType skill, + int levelsChanged, float xpRemoved, boolean isLevelUp, XPGainReason xpGainReason, + int oldLevel) { + McMMOPlayerLevelChangeEvent event = + isLevelUp ? new McMMOPlayerLevelUpEvent(mmoPlayer.getPlayer(), skill, + levelsChanged - oldLevel, xpGainReason) + : new McMMOPlayerLevelDownEvent(mmoPlayer.getPlayer(), skill, levelsChanged, + xpGainReason); mcMMO.p.getServer().getPluginManager().callEvent(event); boolean isCancelled = event.isCancelled(); if (isCancelled) { - mmoPlayer.modifySkill(skill, mmoPlayer.getSkillLevel(skill) - (isLevelUp ? levelsChanged : -levelsChanged)); + mmoPlayer.modifySkill(skill, + mmoPlayer.getSkillLevel(skill) - (isLevelUp ? levelsChanged : -levelsChanged)); mmoPlayer.addXp(skill, xpRemoved); } else { if (isLevelUp) { - NotificationManager.processLevelUpBroadcasting(mmoPlayer, skill, mmoPlayer.getSkillLevel(skill)); - NotificationManager.processPowerLevelUpBroadcasting(mmoPlayer, mmoPlayer.getPowerLevel()); + NotificationManager.processLevelUpBroadcasting(mmoPlayer, skill, + mmoPlayer.getSkillLevel(skill)); + NotificationManager.processPowerLevelUpBroadcasting(mmoPlayer, + mmoPlayer.getPowerLevel()); } } @@ -298,11 +336,11 @@ public final 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 ignored (here for API compatibility) - * @return true if the event wasn't cancelled, false otherwise - * {@code @Deprecated} use {@link #simulateBlockBreak(Block, Player, FakeBlockBreakEventType)} instead + * @return true if the event wasn't cancelled, false otherwise {@code @Deprecated} use + * {@link #simulateBlockBreak(Block, Player, FakeBlockBreakEventType)} instead */ public static boolean simulateBlockBreak(Block block, Player player, boolean shouldArmSwing) { return simulateBlockBreak(block, player); @@ -313,8 +351,8 @@ public final class EventUtils { * * @param block The block to break * @param player The player breaking the block - * @return true if the event wasn't cancelled, false otherwise - * {@code @Deprecated} use {@link #simulateBlockBreak(Block, Player, FakeBlockBreakEventType)} instead + * @return true if the event wasn't cancelled, false otherwise {@code @Deprecated} use + * {@link #simulateBlockBreak(Block, Player, FakeBlockBreakEventType)} instead */ public static boolean simulateBlockBreak(Block block, Player player) { return simulateBlockBreak(block, player, FakeBlockBreakEventType.FAKE); @@ -323,15 +361,17 @@ public final class EventUtils { /** * Simulate a block break event. * - * @param block The block to break + * @param block The block to break * @param player The player breaking the block * @param eventType The type of event to signal to other plugins * @return true if the event wasn't cancelled, false otherwise */ - public static boolean simulateBlockBreak(Block block, Player player, FakeBlockBreakEventType eventType) { + public static boolean simulateBlockBreak(Block block, Player player, + FakeBlockBreakEventType eventType) { PluginManager pluginManager = mcMMO.p.getServer().getPluginManager(); - FakeBlockDamageEvent damageEvent = new FakeBlockDamageEvent(player, block, player.getInventory().getItemInMainHand(), true); + FakeBlockDamageEvent damageEvent = new FakeBlockDamageEvent(player, block, + player.getInventory().getItemInMainHand(), true); pluginManager.callEvent(damageEvent); BlockBreakEvent fakeBlockBreakEvent = null; @@ -345,12 +385,14 @@ public final class EventUtils { } public static void handlePartyTeleportEvent(Player teleportingPlayer, Player targetPlayer) { - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(teleportingPlayer); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(teleportingPlayer); - if (mcMMOPlayer == null) + if (mmoPlayer == null) { return; + } - McMMOPartyTeleportEvent event = new McMMOPartyTeleportEvent(teleportingPlayer, targetPlayer, mcMMOPlayer.getParty().getName()); + McMMOPartyTeleportEvent event = new McMMOPartyTeleportEvent(teleportingPlayer, targetPlayer, + mmoPlayer.getParty().getName()); mcMMO.p.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { @@ -358,12 +400,15 @@ public final class EventUtils { } // teleportingPlayer.teleport(targetPlayer); - mcMMO.p.getFoliaLib().getScheduler().teleportAsync(teleportingPlayer, targetPlayer.getLocation()); + mcMMO.p.getFoliaLib().getScheduler() + .teleportAsync(teleportingPlayer, targetPlayer.getLocation()); - teleportingPlayer.sendMessage(LocaleLoader.getString("Party.Teleport.Player", targetPlayer.getName())); - targetPlayer.sendMessage(LocaleLoader.getString("Party.Teleport.Target", teleportingPlayer.getName())); + teleportingPlayer.sendMessage( + LocaleLoader.getString("Party.Teleport.Player", targetPlayer.getName())); + targetPlayer.sendMessage( + LocaleLoader.getString("Party.Teleport.Target", teleportingPlayer.getName())); - mcMMOPlayer.getPartyTeleportRecord().actualizeLastUse(); + mmoPlayer.getPartyTeleportRecord().actualizeLastUse(); } public static boolean handlePartyXpGainEvent(Party party, float xpGained) { @@ -379,7 +424,8 @@ public final class EventUtils { return !isCancelled; } - public static boolean handlePartyLevelChangeEvent(Party party, int levelsChanged, float xpRemoved) { + public static boolean handlePartyLevelChangeEvent(Party party, int levelsChanged, + float xpRemoved) { McMMOPartyLevelUpEvent event = new McMMOPartyLevelUpEvent(party, levelsChanged); mcMMO.p.getServer().getPluginManager().callEvent(event); @@ -393,12 +439,15 @@ public final class EventUtils { return !isCancelled; } - public static boolean handleXpGainEvent(Player player, PrimarySkillType skill, float xpGained, XPGainReason xpGainReason) { - McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if (mmoPlayer == null) + public static boolean handleXpGainEvent(Player player, PrimarySkillType skill, float xpGained, + XPGainReason xpGainReason) { + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + if (mmoPlayer == null) { return true; + } - McMMOPlayerXpGainEvent event = new McMMOPlayerXpGainEvent(player, skill, xpGained, xpGainReason); + McMMOPlayerXpGainEvent event = new McMMOPlayerXpGainEvent(player, skill, xpGained, + xpGainReason); mcMMO.p.getServer().getPluginManager().callEvent(event); boolean isCancelled = event.isCancelled(); @@ -411,11 +460,14 @@ public final class EventUtils { return !isCancelled; } - public static boolean handleStatsLossEvent(Player player, HashMap levelChanged, HashMap experienceChanged) { - if (UserManager.getPlayer(player) == null) + public static boolean handleStatsLossEvent(Player player, HashMap levelChanged, + HashMap experienceChanged) { + if (UserManager.getPlayer(player) == null) { return true; + } - McMMOPlayerStatLossEvent event = new McMMOPlayerStatLossEvent(player, levelChanged, experienceChanged); + McMMOPlayerStatLossEvent event = new McMMOPlayerStatLossEvent(player, levelChanged, + experienceChanged); mcMMO.p.getServer().getPluginManager().callEvent(event); boolean isCancelled = event.isCancelled(); @@ -428,9 +480,11 @@ public final class EventUtils { for (PrimarySkillType primarySkillType : SkillTools.NON_CHILD_SKILLS) { String skillName = primarySkillType.toString(); int playerSkillLevel = playerProfile.getSkillLevel(primarySkillType); - int threshold = mcMMO.p.getGeneralConfig().getHardcoreDeathStatPenaltyLevelThreshold(); + int threshold = mcMMO.p.getGeneralConfig() + .getHardcoreDeathStatPenaltyLevelThreshold(); if (playerSkillLevel > threshold) { - playerProfile.modifySkill(primarySkillType, Math.max(threshold, playerSkillLevel - levelChanged.get(skillName))); + playerProfile.modifySkill(primarySkillType, + Math.max(threshold, playerSkillLevel - levelChanged.get(skillName))); playerProfile.removeXp(primarySkillType, experienceChanged.get(skillName)); if (playerProfile.getSkillXpLevel(primarySkillType) < 0) { @@ -447,9 +501,12 @@ public final class EventUtils { return !isCancelled; } - public static boolean handleVampirismEvent(Player killer, Player victim, HashMap levelChanged, HashMap experienceChanged) { - McMMOPlayerVampirismEvent eventKiller = new McMMOPlayerVampirismEvent(killer, false, levelChanged, experienceChanged); - McMMOPlayerVampirismEvent eventVictim = new McMMOPlayerVampirismEvent(victim, true, levelChanged, experienceChanged); + public static boolean handleVampirismEvent(Player killer, Player victim, + HashMap levelChanged, HashMap experienceChanged) { + McMMOPlayerVampirismEvent eventKiller = new McMMOPlayerVampirismEvent(killer, false, + levelChanged, experienceChanged); + McMMOPlayerVampirismEvent eventVictim = new McMMOPlayerVampirismEvent(victim, true, + levelChanged, experienceChanged); mcMMO.p.getServer().getPluginManager().callEvent(eventKiller); mcMMO.p.getServer().getPluginManager().callEvent(eventVictim); @@ -465,12 +522,14 @@ public final 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(); @@ -479,9 +538,12 @@ public final class EventUtils { int victimSkillLevel = victimProfile.getSkillLevel(primarySkillType); killerPlayer.addLevels(primarySkillType, levelChangedKiller.get(skillName)); - killerPlayer.beginUnsharedXpGain(primarySkillType, experienceChangedKiller.get(skillName), XPGainReason.VAMPIRISM, XPGainSource.VAMPIRISM); + killerPlayer.beginUnsharedXpGain(primarySkillType, + experienceChangedKiller.get(skillName), XPGainReason.VAMPIRISM, + XPGainSource.VAMPIRISM); - victimProfile.modifySkill(primarySkillType, victimSkillLevel - levelChangedVictim.get(skillName)); + victimProfile.modifySkill(primarySkillType, + victimSkillLevel - levelChangedVictim.get(skillName)); victimProfile.removeXp(primarySkillType, experienceChangedVictim.get(skillName)); if (victimProfile.getSkillXpLevel(primarySkillType) < 0) { @@ -498,38 +560,51 @@ public final class EventUtils { } @Deprecated(forRemoval = true, since = "2.2.010") - public static McMMOPlayerAbilityDeactivateEvent callAbilityDeactivateEvent(Player player, SuperAbilityType ability) { + public static McMMOPlayerAbilityDeactivateEvent callAbilityDeactivateEvent(Player player, + SuperAbilityType ability) { return callAbilityDeactivateEvent(requireNonNull(UserManager.getPlayer(player)), ability); } - public static McMMOPlayerAbilityDeactivateEvent callAbilityDeactivateEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull SuperAbilityType ability) { - final McMMOPlayerAbilityDeactivateEvent event = new McMMOPlayerAbilityDeactivateEvent(mmoPlayer, mcMMO.p.getSkillTools().getPrimarySkillBySuperAbility(ability)); + public static McMMOPlayerAbilityDeactivateEvent callAbilityDeactivateEvent( + @NotNull McMMOPlayer mmoPlayer, @NotNull SuperAbilityType ability) { + final McMMOPlayerAbilityDeactivateEvent event = new McMMOPlayerAbilityDeactivateEvent( + mmoPlayer, mcMMO.p.getSkillTools().getPrimarySkillBySuperAbility(ability)); mcMMO.p.getServer().getPluginManager().callEvent(event); return event; } @Deprecated(forRemoval = true, since = "2.2.010") - public static McMMOPlayerFishingTreasureEvent callFishingTreasureEvent(Player player, ItemStack treasureDrop, int treasureXp, Map enchants) { - return callFishingTreasureEvent(requireNonNull(UserManager.getPlayer(player)), treasureDrop, treasureXp, enchants); + public static McMMOPlayerFishingTreasureEvent callFishingTreasureEvent(Player player, + ItemStack treasureDrop, int treasureXp, Map enchants) { + return callFishingTreasureEvent(requireNonNull(UserManager.getPlayer(player)), treasureDrop, + treasureXp, enchants); } - public static McMMOPlayerFishingTreasureEvent callFishingTreasureEvent(McMMOPlayer mmoPlayer, ItemStack treasureDrop, int treasureXp, Map enchants) { - final McMMOPlayerFishingTreasureEvent event = enchants.isEmpty() ? new McMMOPlayerFishingTreasureEvent(mmoPlayer, treasureDrop, treasureXp) : new McMMOPlayerMagicHunterEvent(mmoPlayer, treasureDrop, treasureXp, enchants); + public static McMMOPlayerFishingTreasureEvent callFishingTreasureEvent(McMMOPlayer mmoPlayer, + ItemStack treasureDrop, int treasureXp, Map enchants) { + final McMMOPlayerFishingTreasureEvent event = + enchants.isEmpty() ? new McMMOPlayerFishingTreasureEvent(mmoPlayer, treasureDrop, + treasureXp) + : new McMMOPlayerMagicHunterEvent(mmoPlayer, treasureDrop, treasureXp, + enchants); mcMMO.p.getServer().getPluginManager().callEvent(event); return event; } public static FakePlayerFishEvent callFakeFishEvent(Player player, FishHook hook) { - FakePlayerFishEvent event = new FakePlayerFishEvent(player, null, hook, PlayerFishEvent.State.FISHING); + FakePlayerFishEvent event = new FakePlayerFishEvent(player, null, hook, + PlayerFishEvent.State.FISHING); mcMMO.p.getServer().getPluginManager().callEvent(event); return event; } - public static McMMOPlayerRepairCheckEvent callRepairCheckEvent(Player player, short durability, ItemStack repairMaterial, ItemStack repairedObject) { - McMMOPlayerRepairCheckEvent event = new McMMOPlayerRepairCheckEvent(player, durability, repairMaterial, repairedObject); + public static McMMOPlayerRepairCheckEvent callRepairCheckEvent(Player player, short durability, + ItemStack repairMaterial, ItemStack repairedObject) { + McMMOPlayerRepairCheckEvent event = new McMMOPlayerRepairCheckEvent(player, durability, + repairMaterial, repairedObject); mcMMO.p.getServer().getPluginManager().callEvent(event); return event; @@ -549,8 +624,10 @@ public final class EventUtils { return event; } - public static McMMOPlayerSalvageCheckEvent callSalvageCheckEvent(Player player, ItemStack salvageMaterial, ItemStack salvageResults, ItemStack enchantedBook) { - McMMOPlayerSalvageCheckEvent event = new McMMOPlayerSalvageCheckEvent(player, salvageMaterial, salvageResults, enchantedBook); + public static McMMOPlayerSalvageCheckEvent callSalvageCheckEvent(Player player, + ItemStack salvageMaterial, ItemStack salvageResults, ItemStack enchantedBook) { + McMMOPlayerSalvageCheckEvent event = new McMMOPlayerSalvageCheckEvent(player, + salvageMaterial, salvageResults, enchantedBook); mcMMO.p.getServer().getPluginManager().callEvent(event); return event; diff --git a/src/main/java/com/gmail/nossr50/util/FixSpellingNetheriteUtil.java b/src/main/java/com/gmail/nossr50/util/FixSpellingNetheriteUtil.java index 9f5b9dd52..e500d2853 100644 --- a/src/main/java/com/gmail/nossr50/util/FixSpellingNetheriteUtil.java +++ b/src/main/java/com/gmail/nossr50/util/FixSpellingNetheriteUtil.java @@ -2,8 +2,11 @@ package com.gmail.nossr50.util; import com.gmail.nossr50.datatypes.database.UpgradeType; import com.gmail.nossr50.mcMMO; - -import java.io.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; public class FixSpellingNetheriteUtil { @@ -53,7 +56,8 @@ public class FixSpellingNetheriteUtil { } } - pluginRef.getLogger().info("Finished checking "+fileName+" for certain misspelled material names."); + pluginRef.getLogger() + .info("Finished checking " + fileName + " for certain misspelled material names."); mcMMO.getUpgradeManager().setUpgradeCompleted(upgradeType); } diff --git a/src/main/java/com/gmail/nossr50/util/HardcoreManager.java b/src/main/java/com/gmail/nossr50/util/HardcoreManager.java index 01b085952..dd50a6c67 100644 --- a/src/main/java/com/gmail/nossr50/util/HardcoreManager.java +++ b/src/main/java/com/gmail/nossr50/util/HardcoreManager.java @@ -9,25 +9,28 @@ import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.SkillTools; import com.gmail.nossr50.worldguard.WorldGuardManager; import com.gmail.nossr50.worldguard.WorldGuardUtils; +import java.util.HashMap; import org.bukkit.entity.Player; -import java.util.HashMap; - public final class HardcoreManager { - private HardcoreManager() {} + private HardcoreManager() { + } public static void invokeStatPenalty(Player player) { if (WorldGuardUtils.isWorldGuardLoaded()) { - if (!WorldGuardManager.getInstance().hasHardcoreFlag(player)) + if (!WorldGuardManager.getInstance().hasHardcoreFlag(player)) { return; + } } - double statLossPercentage = mcMMO.p.getGeneralConfig().getHardcoreDeathStatPenaltyPercentage(); + double statLossPercentage = mcMMO.p.getGeneralConfig() + .getHardcoreDeathStatPenaltyPercentage(); int levelThreshold = mcMMO.p.getGeneralConfig().getHardcoreDeathStatPenaltyLevelThreshold(); - if (UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) { return; + } PlayerProfile playerProfile = UserManager.getPlayer(player).getProfile(); int totalLevelsLost = 0; @@ -51,7 +54,8 @@ public final class HardcoreManager { continue; } - double statsLost = Math.max(0, (playerSkillLevel - levelThreshold)) * (statLossPercentage * 0.01D); + double statsLost = + Math.max(0, (playerSkillLevel - levelThreshold)) * (statLossPercentage * 0.01D); int levelsLost = (int) statsLost; int xpLost = (int) Math.floor(playerSkillXpLevel * (statsLost - levelsLost)); levelChanged.put(primarySkillType.toString(), levelsLost); @@ -64,21 +68,26 @@ public final class HardcoreManager { return; } - NotificationManager.sendPlayerInformation(player, NotificationType.HARDCORE_MODE, "Hardcore.DeathStatLoss.PlayerDeath", String.valueOf(totalLevelsLost)); + NotificationManager.sendPlayerInformation(player, NotificationType.HARDCORE_MODE, + "Hardcore.DeathStatLoss.PlayerDeath", String.valueOf(totalLevelsLost)); } public static void invokeVampirism(Player killer, Player victim) { if (WorldGuardUtils.isWorldGuardLoaded()) { - if (!WorldGuardManager.getInstance().hasHardcoreFlag(killer) || !WorldGuardManager.getInstance().hasHardcoreFlag(victim)) + if (!WorldGuardManager.getInstance().hasHardcoreFlag(killer) + || !WorldGuardManager.getInstance().hasHardcoreFlag(victim)) { return; + } } - double vampirismStatLeechPercentage = mcMMO.p.getGeneralConfig().getHardcoreVampirismStatLeechPercentage(); + double vampirismStatLeechPercentage = mcMMO.p.getGeneralConfig() + .getHardcoreVampirismStatLeechPercentage(); int levelThreshold = mcMMO.p.getGeneralConfig().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(); PlayerProfile victimProfile = UserManager.getPlayer(victim).getProfile(); @@ -97,7 +106,8 @@ public final class HardcoreManager { int killerSkillLevel = killerProfile.getSkillLevel(primarySkillType); int victimSkillLevel = victimProfile.getSkillLevel(primarySkillType); - if (victimSkillLevel <= 0 || victimSkillLevel < killerSkillLevel / 2 || victimSkillLevel <= levelThreshold) { + if (victimSkillLevel <= 0 || victimSkillLevel < killerSkillLevel / 2 + || victimSkillLevel <= levelThreshold) { levelChanged.put(primarySkillType.toString(), 0); experienceChanged.put(primarySkillType.toString(), 0F); continue; @@ -119,11 +129,17 @@ 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)); + 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 { - NotificationManager.sendPlayerInformation(killer, NotificationType.HARDCORE_MODE, "Hardcore.Vampirism.Killer.Failure", victim.getName()); - NotificationManager.sendPlayerInformation(victim, NotificationType.HARDCORE_MODE, "Hardcore.Vampirism.Victim.Failure", killer.getName()); + 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/HolidayManager.java b/src/main/java/com/gmail/nossr50/util/HolidayManager.java index 37adbbc1b..fab896915 100644 --- a/src/main/java/com/gmail/nossr50/util/HolidayManager.java +++ b/src/main/java/com/gmail/nossr50/util/HolidayManager.java @@ -110,9 +110,8 @@ // } // } // -//// for (DyeColor color : DyeColor.values()) { -//// colors.add(color.getFireworkColor()); -//// } +/// / for (DyeColor color : DyeColor.values()) { / +/// colors.add(color.getFireworkColor()); / } // // Collections.shuffle(chatColors, Misc.getRandom()); // Collections.shuffle(colors, Misc.getRandom()); diff --git a/src/main/java/com/gmail/nossr50/util/ItemMetadataUtils.java b/src/main/java/com/gmail/nossr50/util/ItemMetadataUtils.java index ff565f71d..95d5c824f 100644 --- a/src/main/java/com/gmail/nossr50/util/ItemMetadataUtils.java +++ b/src/main/java/com/gmail/nossr50/util/ItemMetadataUtils.java @@ -1,16 +1,15 @@ package com.gmail.nossr50.util; +import static com.gmail.nossr50.util.MetadataService.NSK_SUPER_ABILITY_BOOSTED_ITEM; + import com.gmail.nossr50.mcMMO; +import java.util.List; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.persistence.PersistentDataContainer; import org.bukkit.persistence.PersistentDataType; import org.jetbrains.annotations.NotNull; -import java.util.List; - -import static com.gmail.nossr50.util.MetadataService.NSK_SUPER_ABILITY_BOOSTED_ITEM; - public final class ItemMetadataUtils { public static final @NotNull String LEGACY_ABILITY_TOOL_LORE = "mcMMO Ability Tool"; @@ -19,30 +18,35 @@ public final class ItemMetadataUtils { // private ctor } - public static void setSuperAbilityBoostedItem(@NotNull ItemStack itemStack, int originalDigSpeed) { + public static void setSuperAbilityBoostedItem(@NotNull ItemStack itemStack, + int originalDigSpeed) { if (itemStack.getItemMeta() == null) { - mcMMO.p.getLogger().severe("Can not assign persistent data to an item with null item metadata"); + mcMMO.p.getLogger() + .severe("Can not assign persistent data to an item with null item metadata"); return; } ItemMeta itemMeta = itemStack.getItemMeta(); PersistentDataContainer dataContainer = itemMeta.getPersistentDataContainer(); - dataContainer.set(NSK_SUPER_ABILITY_BOOSTED_ITEM, PersistentDataType.INTEGER, originalDigSpeed); + dataContainer.set(NSK_SUPER_ABILITY_BOOSTED_ITEM, PersistentDataType.INTEGER, + originalDigSpeed); itemStack.setItemMeta(itemMeta); } public static boolean isSuperAbilityBoosted(@NotNull ItemStack itemStack) { - if (itemStack.getItemMeta() == null) + if (itemStack.getItemMeta() == null) { return false; + } ItemMeta itemMeta = itemStack.getItemMeta(); //Get container from entity PersistentDataContainer dataContainer = itemMeta.getPersistentDataContainer(); //If this value isn't null, then the tool can be considered dig speed boosted - Integer boostValue = dataContainer.get(NSK_SUPER_ABILITY_BOOSTED_ITEM, PersistentDataType.INTEGER); + Integer boostValue = dataContainer.get(NSK_SUPER_ABILITY_BOOSTED_ITEM, + PersistentDataType.INTEGER); return boostValue != null; } @@ -51,8 +55,9 @@ public final class ItemMetadataUtils { //Get container from entity ItemMeta itemMeta = itemStack.getItemMeta(); - if (itemMeta == null) + if (itemMeta == null) { return 0; + } PersistentDataContainer dataContainer = itemMeta.getPersistentDataContainer(); @@ -61,7 +66,8 @@ public final class ItemMetadataUtils { return 0; } else { //Too lazy to make a custom data type for this stuff - Integer boostValue = dataContainer.get(NSK_SUPER_ABILITY_BOOSTED_ITEM, PersistentDataType.INTEGER); + Integer boostValue = dataContainer.get(NSK_SUPER_ABILITY_BOOSTED_ITEM, + PersistentDataType.INTEGER); return Math.max(boostValue, 0); } } @@ -77,7 +83,8 @@ public final class ItemMetadataUtils { } if (originalSpeed > 0) { - itemMeta.addEnchant(mcMMO.p.getEnchantmentMapper().getEfficiency(), originalSpeed, true); + itemMeta.addEnchant(mcMMO.p.getEnchantmentMapper().getEfficiency(), originalSpeed, + true); } PersistentDataContainer dataContainer = itemMeta.getPersistentDataContainer(); @@ -91,13 +98,15 @@ public final class ItemMetadataUtils { public static boolean isLegacyAbilityTool(@NotNull ItemStack itemStack) { ItemMeta itemMeta = itemStack.getItemMeta(); - if (itemMeta == null) + if (itemMeta == null) { return false; + } List lore = itemMeta.getLore(); - if (lore == null || lore.isEmpty()) + if (lore == null || lore.isEmpty()) { return false; + } return lore.contains(LEGACY_ABILITY_TOOL_LORE); } diff --git a/src/main/java/com/gmail/nossr50/util/ItemUtils.java b/src/main/java/com/gmail/nossr50/util/ItemUtils.java index 74ef4d807..16034f905 100644 --- a/src/main/java/com/gmail/nossr50/util/ItemUtils.java +++ b/src/main/java/com/gmail/nossr50/util/ItemUtils.java @@ -1,5 +1,7 @@ package com.gmail.nossr50.util; +import static java.util.Objects.requireNonNull; + import com.gmail.nossr50.api.ItemSpawnReason; import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.config.party.ItemWeightConfig; @@ -9,6 +11,13 @@ import com.gmail.nossr50.events.items.McMMOItemSpawnEvent; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.skills.smelting.Smelting; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.function.Predicate; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; @@ -25,16 +34,6 @@ import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Locale; -import java.util.function.Predicate; - -import static java.util.Objects.requireNonNull; - public final class ItemUtils { // Reflection for setItemName only available in newer APIs private static final Method setItemName; @@ -56,11 +55,10 @@ public final class ItemUtils { } /** - * Sets the item name using the new API if available - * or falls back to the old API. + * Sets the item name using the new API if available or falls back to the old API. * * @param itemMeta The item meta to set the name on - * @param name The name to set + * @param name The name to set */ public static void setItemName(ItemMeta itemMeta, String name) { if (setItemName != null) { @@ -125,7 +123,7 @@ public final class ItemUtils { /** * Checks if a player has an item in their inventory or offhand. * - * @param player Player to check + * @param player Player to check * @param material Material to check for * @return true if the player has the item in their inventory or offhand, false otherwise */ @@ -143,11 +141,12 @@ public final class ItemUtils { /** * Removes an item from a player's inventory, including their offhand. * - * @param player Player to remove the item from + * @param player Player to remove the item from * @param material Material to remove - * @param amount Amount of the material to remove + * @param amount Amount of the material to remove */ - public static void removeItemIncludingOffHand(@NotNull Player player, @NotNull Material material, int amount) { + public static void removeItemIncludingOffHand(@NotNull Player player, + @NotNull Material material, int amount) { // Checks main inventory / item bar if (player.getInventory().contains(material)) { player.getInventory().removeItem(new ItemStack(material, amount)); @@ -185,69 +184,80 @@ public final class ItemUtils { || player.getInventory().getItemInOffHand().getType() == material; } - public static boolean doesPlayerHaveEnchantmentOnArmor(@NotNull Player player, @NotNull String enchantmentByName) { + public static boolean doesPlayerHaveEnchantmentOnArmor(@NotNull Player player, + @NotNull String enchantmentByName) { Enchantment enchantment = getEnchantment(enchantmentByName); - if (enchantment == null) + if (enchantment == null) { return false; + } return doesPlayerHaveEnchantmentOnArmor(player, enchantment); } - public static boolean doesPlayerHaveEnchantmentOnArmor(@NotNull Player player, @NotNull Enchantment enchantment) { + public static boolean doesPlayerHaveEnchantmentOnArmor(@NotNull Player player, + @NotNull Enchantment enchantment) { for (ItemStack itemStack : player.getInventory().getArmorContents()) { if (itemStack != null) { - if (hasEnchantment(itemStack, enchantment)) + if (hasEnchantment(itemStack, enchantment)) { return true; + } } } return false; } - public static boolean doesPlayerHaveEnchantmentOnArmorOrHands(@NotNull Player player, @NotNull String enchantmentName) { + public static boolean doesPlayerHaveEnchantmentOnArmorOrHands(@NotNull Player player, + @NotNull String enchantmentName) { Enchantment enchantment = getEnchantment(enchantmentName); - if (enchantment == null) + if (enchantment == null) { return false; + } return doesPlayerHaveEnchantmentOnArmorOrHands(player, enchantment); } - public static boolean doesPlayerHaveEnchantmentOnArmorOrHands(@NotNull Player player, @NotNull Enchantment enchantment) { - if (doesPlayerHaveEnchantmentOnArmor(player, enchantment)) + public static boolean doesPlayerHaveEnchantmentOnArmorOrHands(@NotNull Player player, + @NotNull Enchantment enchantment) { + if (doesPlayerHaveEnchantmentOnArmor(player, enchantment)) { return true; + } - if (doesPlayerHaveEnchantmentInHands(player, enchantment)) - return true; - - return false; + return doesPlayerHaveEnchantmentInHands(player, enchantment); } - public static boolean doesPlayerHaveEnchantmentInHands(@NotNull Player player, @NotNull NamespacedKey enchantmentNameKey) { + public static boolean doesPlayerHaveEnchantmentInHands(@NotNull Player player, + @NotNull NamespacedKey enchantmentNameKey) { Enchantment enchantment = Enchantment.getByKey(enchantmentNameKey); - if (enchantment == null) + if (enchantment == null) { return false; + } return doesPlayerHaveEnchantmentInHands(player, enchantment); } - public static boolean doesPlayerHaveEnchantmentInHands(@NotNull Player player, @NotNull String enchantmentName) { + public static boolean doesPlayerHaveEnchantmentInHands(@NotNull Player player, + @NotNull String enchantmentName) { Enchantment enchantment = getEnchantment(enchantmentName); - if (enchantment == null) + if (enchantment == null) { return false; + } return doesPlayerHaveEnchantmentInHands(player, enchantment); } - public static boolean doesPlayerHaveEnchantmentInHands(@NotNull Player player, @NotNull Enchantment enchantment) { + public static boolean doesPlayerHaveEnchantmentInHands(@NotNull Player player, + @NotNull Enchantment enchantment) { return hasEnchantment(player.getInventory().getItemInMainHand(), enchantment) || hasEnchantment(player.getInventory().getItemInOffHand(), enchantment); } - public static boolean hasEnchantment(@NotNull ItemStack itemStack, @NotNull Enchantment enchantment) { + public static boolean hasEnchantment(@NotNull ItemStack itemStack, + @NotNull Enchantment enchantment) { if (itemStack.getItemMeta() != null) { return itemStack.getItemMeta().hasEnchant(enchantment); } @@ -529,8 +539,10 @@ public final class ItemUtils { //TODO: 1.14 This needs to be updated return switch (item.getType()) { // Should we also have Glowing Redstone Ore here? // Should we also have Glowstone here? - case COAL, COAL_ORE, DIAMOND, DIAMOND_ORE, EMERALD, EMERALD_ORE, GOLD_ORE, IRON_ORE, LAPIS_ORE, - REDSTONE_ORE, REDSTONE, GLOWSTONE_DUST, QUARTZ, NETHER_QUARTZ_ORE, LAPIS_LAZULI -> true; + case COAL, COAL_ORE, DIAMOND, DIAMOND_ORE, EMERALD, EMERALD_ORE, GOLD_ORE, IRON_ORE, + LAPIS_ORE, + REDSTONE_ORE, REDSTONE, GLOWSTONE_DUST, QUARTZ, NETHER_QUARTZ_ORE, LAPIS_LAZULI -> + true; default -> false; }; } @@ -544,9 +556,12 @@ public final class ItemUtils { public static boolean isHerbalismDrop(ItemStack item) { //TODO: 1.14 This needs to be updated return switch (item.getType().getKey().getKey().toLowerCase()) { - case "wheat", "wheat_seeds", "carrot", "chorus_fruit", "chorus_flower", "potato", "beetroot", "beetroots", - "beetroot_seeds", "nether_wart", "brown_mushroom", "red_mushroom", "rose_bush", "dandelion", "cactus", - "sugar_cane", "melon", "melon_seeds", "pumpkin", "pumpkin_seeds", "lily_pad", "vine", "tall_grass", + case "wheat", "wheat_seeds", "carrot", "chorus_fruit", "chorus_flower", "potato", + "beetroot", "beetroots", + "beetroot_seeds", "nether_wart", "brown_mushroom", "red_mushroom", "rose_bush", + "dandelion", "cactus", + "sugar_cane", "melon", "melon_seeds", "pumpkin", "pumpkin_seeds", "lily_pad", + "vine", "tall_grass", "cocoa_beans" -> true; default -> false; }; @@ -562,11 +577,16 @@ public final class ItemUtils { public static boolean isMobDrop(ItemStack item) { //TODO: 1.14 This needs to be updated return switch (item.getType()) { - case STRING, FEATHER, CHICKEN, COOKED_CHICKEN, LEATHER, BEEF, COOKED_BEEF, PORKCHOP, COOKED_PORKCHOP, - WHITE_WOOL, BLACK_WOOL, BLUE_WOOL, BROWN_WOOL, CYAN_WOOL, GRAY_WOOL, GREEN_WOOL, LIGHT_BLUE_WOOL, - LIGHT_GRAY_WOOL, LIME_WOOL, MAGENTA_WOOL, ORANGE_WOOL, PINK_WOOL, PURPLE_WOOL, RED_WOOL, YELLOW_WOOL, - IRON_INGOT, SNOWBALL, BLAZE_ROD, SPIDER_EYE, GUNPOWDER, ENDER_PEARL, GHAST_TEAR, MAGMA_CREAM, BONE, - ARROW, SLIME_BALL, NETHER_STAR, ROTTEN_FLESH, GOLD_NUGGET, EGG, ROSE_BUSH, COAL -> true; + case STRING, FEATHER, CHICKEN, COOKED_CHICKEN, LEATHER, BEEF, COOKED_BEEF, PORKCHOP, + COOKED_PORKCHOP, + WHITE_WOOL, BLACK_WOOL, BLUE_WOOL, BROWN_WOOL, CYAN_WOOL, GRAY_WOOL, GREEN_WOOL, + LIGHT_BLUE_WOOL, + LIGHT_GRAY_WOOL, LIME_WOOL, MAGENTA_WOOL, ORANGE_WOOL, PINK_WOOL, PURPLE_WOOL, + RED_WOOL, YELLOW_WOOL, + IRON_INGOT, SNOWBALL, BLAZE_ROD, SPIDER_EYE, GUNPOWDER, ENDER_PEARL, GHAST_TEAR, + MAGMA_CREAM, BONE, + ARROW, SLIME_BALL, NETHER_STAR, ROTTEN_FLESH, GOLD_NUGGET, EGG, ROSE_BUSH, COAL -> + true; default -> false; }; } @@ -579,11 +599,16 @@ public final class ItemUtils { */ public static boolean isWoodcuttingDrop(ItemStack item) { return switch (item.getType().toString()) { - case "ACACIA_LOG", "BIRCH_LOG", "DARK_OAK_LOG", "PALE_OAK_LOG", "JUNGLE_LOG", "OAK_LOG", "SPRUCE_LOG", - "STRIPPED_ACACIA_LOG", "STRIPPED_BIRCH_LOG", "STRIPPED_DARK_OAK_LOG", "STRIPPED_PALE_OAK_LOG", - "STRIPPED_JUNGLE_LOG", "STRIPPED_OAK_LOG", "STRIPPED_SPRUCE_LOG", "STRIPPED_MANGROVE_LOG", - "ACACIA_SAPLING", "SPRUCE_SAPLING", "BIRCH_SAPLING", "DARK_OAK_SAPLING", "PALE_OAK_SAPLING", - "JUNGLE_SAPLING", "OAK_SAPLING", "ACACIA_LEAVES", "BIRCH_LEAVES", "DARK_OAK_LEAVES", "PALE_OAK_LEAVES", + case "ACACIA_LOG", "BIRCH_LOG", "DARK_OAK_LOG", "PALE_OAK_LOG", "JUNGLE_LOG", "OAK_LOG", + "SPRUCE_LOG", + "STRIPPED_ACACIA_LOG", "STRIPPED_BIRCH_LOG", "STRIPPED_DARK_OAK_LOG", + "STRIPPED_PALE_OAK_LOG", + "STRIPPED_JUNGLE_LOG", "STRIPPED_OAK_LOG", "STRIPPED_SPRUCE_LOG", + "STRIPPED_MANGROVE_LOG", + "ACACIA_SAPLING", "SPRUCE_SAPLING", "BIRCH_SAPLING", "DARK_OAK_SAPLING", + "PALE_OAK_SAPLING", + "JUNGLE_SAPLING", "OAK_SAPLING", "ACACIA_LEAVES", "BIRCH_LEAVES", + "DARK_OAK_LEAVES", "PALE_OAK_LEAVES", "JUNGLE_LEAVES", "OAK_LEAVES", "SPRUCE_LEAVES", "BEE_NEST", "APPLE" -> true; default -> false; }; @@ -599,7 +624,7 @@ public final class ItemUtils { return ItemWeightConfig.getInstance().getMiscItems().contains(item.getType()); } - // TODO: This is used exclusively for Chimaera Wing... should revisit this sometime + // TODO: This is used exclusively for Chimaera Wing... should revisit this sometime public static boolean isMcMMOItem(ItemStack item) { if (!item.hasItemMeta()) { return false; @@ -607,8 +632,9 @@ public final class ItemUtils { ItemMeta itemMeta = item.getItemMeta(); - if (itemMeta == null) + if (itemMeta == null) { return false; + } return itemMeta.getLore() != null && itemMeta.getLore().contains("mcMMO Item"); @@ -621,23 +647,27 @@ public final class ItemUtils { ItemMeta itemMeta = item.getItemMeta(); - if (itemMeta == null) + if (itemMeta == null) { return false; + } - return itemMeta.hasDisplayName() && itemMeta.getDisplayName().equals(ChatColor.GOLD + LocaleLoader.getString("Item.ChimaeraWing.Name")); + return itemMeta.hasDisplayName() && itemMeta.getDisplayName() + .equals(ChatColor.GOLD + LocaleLoader.getString("Item.ChimaeraWing.Name")); } public static void removeAbilityLore(@NotNull ItemStack itemStack) { ItemMeta itemMeta = itemStack.getItemMeta(); - if (itemMeta == null) + if (itemMeta == null) { return; + } if (itemMeta.hasLore()) { List itemLore = itemMeta.getLore(); - if (itemLore == null) + if (itemLore == null) { return; + } if (itemLore.remove("mcMMO Ability Tool")) { itemMeta.setLore(itemLore); @@ -647,11 +677,12 @@ public final class ItemUtils { } public static void addDigSpeedToItem(@NotNull ItemStack itemStack, - int existingEnchantLevel) { + int existingEnchantLevel) { ItemMeta itemMeta = itemStack.getItemMeta(); - if (itemMeta == null) + if (itemMeta == null) { return; + } itemMeta.addEnchant(mcMMO.p.getEnchantmentMapper().getEfficiency(), existingEnchantLevel + mcMMO.p.getAdvancedConfig().getEnchantBuff(), true); @@ -662,9 +693,11 @@ public final class ItemUtils { return isShovel(itemStack) || isPickaxe(itemStack); } - public static @NotNull ItemStack createEnchantBook(@NotNull FishingTreasureBook fishingTreasureBook) { + public static @NotNull ItemStack createEnchantBook( + @NotNull FishingTreasureBook fishingTreasureBook) { ItemStack itemStack = fishingTreasureBook.getDrop().clone(); - EnchantmentWrapper enchantmentWrapper = getRandomEnchantment(fishingTreasureBook.getLegalEnchantments()); + EnchantmentWrapper enchantmentWrapper = getRandomEnchantment( + fishingTreasureBook.getLegalEnchantments()); ItemMeta itemMeta = itemStack.getItemMeta(); if (itemMeta == null) { @@ -695,9 +728,9 @@ public final class ItemUtils { * @param itemStacks The items to drop */ public static void spawnItems(@Nullable Player player, - @NotNull Location location, - @NotNull Collection itemStacks, - @NotNull ItemSpawnReason itemSpawnReason) { + @NotNull Location location, + @NotNull Collection itemStacks, + @NotNull ItemSpawnReason itemSpawnReason) { for (ItemStack is : itemStacks) { spawnItem(player, location, is, itemSpawnReason); } @@ -713,13 +746,13 @@ public final class ItemUtils { * @param itemSpawnReason the reason for the item drop */ public static void spawnItems(@Nullable Player player, - @NotNull Location location, - @NotNull Collection itemStacks, - @NotNull Collection blackList, - @NotNull ItemSpawnReason itemSpawnReason) { + @NotNull Location location, + @NotNull Collection itemStacks, + @NotNull Collection blackList, + @NotNull ItemSpawnReason itemSpawnReason) { for (ItemStack is : itemStacks) { // Skip blacklisted items - if(blackList.contains(is.getType())) { + if (blackList.contains(is.getType())) { continue; } spawnItem(player, location, is, itemSpawnReason); @@ -730,14 +763,14 @@ public final class ItemUtils { * 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 spawnItems(@Nullable Player player, - @NotNull Location location, - @NotNull ItemStack is, - int quantity, - @NotNull ItemSpawnReason itemSpawnReason) { + @NotNull Location location, + @NotNull ItemStack is, + int quantity, + @NotNull ItemSpawnReason itemSpawnReason) { for (int i = 0; i < quantity; i++) { spawnItem(player, location, is, itemSpawnReason); } @@ -746,21 +779,22 @@ public final class ItemUtils { /** * Drop an item at a given location. * - * @param location The location to drop the item at - * @param itemStack The item to drop + * @param location The location to drop the item at + * @param itemStack The item to drop * @param itemSpawnReason the reason for the item drop * @return Dropped Item entity or null if invalid or cancelled */ public static @Nullable Item spawnItem(@Nullable Player player, - @NotNull Location location, - @NotNull ItemStack itemStack, - @NotNull ItemSpawnReason itemSpawnReason) { + @NotNull Location location, + @NotNull ItemStack itemStack, + @NotNull ItemSpawnReason itemSpawnReason) { if (itemStack.getType() == Material.AIR || location.getWorld() == null) { return null; } // We can't get the item until we spawn it and we want to make it cancellable, so we have a custom event. - final McMMOItemSpawnEvent event = new McMMOItemSpawnEvent(location, itemStack, itemSpawnReason, player); + final McMMOItemSpawnEvent event = new McMMOItemSpawnEvent(location, itemStack, + itemSpawnReason, player); mcMMO.p.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { @@ -773,21 +807,22 @@ public final class ItemUtils { /** * Drop an item at a given location. * - * @param location The location to drop the item at - * @param itemStack The item to drop + * @param location The location to drop the item at + * @param itemStack The item to drop * @param itemSpawnReason the reason for the item drop * @return Dropped Item entity or null if invalid or cancelled */ public static @Nullable Item spawnItemNaturally(@Nullable Player player, - @NotNull Location location, - @NotNull ItemStack itemStack, - @NotNull ItemSpawnReason itemSpawnReason) { + @NotNull Location location, + @NotNull ItemStack itemStack, + @NotNull ItemSpawnReason itemSpawnReason) { if (itemStack.getType() == Material.AIR || location.getWorld() == null) { return null; } // We can't get the item until we spawn it and we want to make it cancellable, so we have a custom event. - final McMMOItemSpawnEvent event = new McMMOItemSpawnEvent(location, itemStack, itemSpawnReason, player); + final McMMOItemSpawnEvent event = new McMMOItemSpawnEvent(location, itemStack, + itemSpawnReason, player); mcMMO.p.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { @@ -801,38 +836,38 @@ public final class ItemUtils { * Drop items at a given location. * * @param fromLocation The location to drop the items at - * @param is The items to drop - * @param speed the speed that the item should travel - * @param quantity The amount of items to drop + * @param is The items to drop + * @param speed the speed that the item should travel + * @param quantity The amount of items to drop */ public static void spawnItemsTowardsLocation(@Nullable Player player, - @NotNull Location fromLocation, - @NotNull Location toLocation, - @NotNull ItemStack is, - int quantity, - double speed, - @NotNull ItemSpawnReason itemSpawnReason) { + @NotNull Location fromLocation, + @NotNull Location toLocation, + @NotNull ItemStack is, + int quantity, + double speed, + @NotNull ItemSpawnReason itemSpawnReason) { for (int i = 0; i < quantity; i++) { spawnItemTowardsLocation(player, fromLocation, toLocation, is, speed, itemSpawnReason); } } /** - * Drop an item at a given location. - * This method is fairly expensive as it creates clones of everything passed to itself since they are mutable objects + * Drop an item at a given location. This method is fairly expensive as it creates clones of + * everything passed to itself since they are mutable objects * * @param fromLocation The location to drop the item at - * @param toLocation The location the item will travel towards - * @param itemToSpawn The item to spawn - * @param speed the speed that the item should travel + * @param toLocation The location the item will travel towards + * @param itemToSpawn The item to spawn + * @param speed the speed that the item should travel * @return Dropped Item entity or null if invalid or cancelled */ public static @Nullable Item spawnItemTowardsLocation(@Nullable Player player, - @NotNull Location fromLocation, - @NotNull Location toLocation, - @NotNull ItemStack itemToSpawn, - double speed, - @NotNull ItemSpawnReason itemSpawnReason) { + @NotNull Location fromLocation, + @NotNull Location toLocation, + @NotNull ItemStack itemToSpawn, + double speed, + @NotNull ItemSpawnReason itemSpawnReason) { if (itemToSpawn.getType() == Material.AIR) { return null; } @@ -842,11 +877,13 @@ public final class ItemUtils { Location spawnLocation = fromLocation.clone(); Location targetLocation = toLocation.clone(); - if (spawnLocation.getWorld() == null) + if (spawnLocation.getWorld() == null) { return null; + } // We can't get the item until we spawn it and we want to make it cancellable, so we have a custom event. - McMMOItemSpawnEvent event = new McMMOItemSpawnEvent(spawnLocation, clonedItem, itemSpawnReason, player); + McMMOItemSpawnEvent event = new McMMOItemSpawnEvent(spawnLocation, clonedItem, + itemSpawnReason, player); mcMMO.p.getServer().getPluginManager().callEvent(event); clonedItem = event.getItemStack(); @@ -870,9 +907,9 @@ public final class ItemUtils { } public static void spawnItemsFromCollection(@NotNull Player player, - @NotNull Location location, - @NotNull Collection drops, - @NotNull ItemSpawnReason itemSpawnReason) { + @NotNull Location location, + @NotNull Collection drops, + @NotNull ItemSpawnReason itemSpawnReason) { requireNonNull(drops, "drops cannot be null"); for (ItemStack drop : drops) { spawnItem(player, location, drop, itemSpawnReason); @@ -880,18 +917,18 @@ public final class ItemUtils { } /** - * Drops only the first n items in a collection - * Size should always be a positive integer above 0 + * Drops only the first n items in a collection Size should always be a positive integer above + * 0 * - * @param location target drop location - * @param drops collection to iterate over + * @param location target drop location + * @param drops collection to iterate over * @param sizeLimit the number of drops to process */ public static void spawnItemsFromCollection(@Nullable Player player, - @NotNull Location location, - @NotNull Collection drops, - @NotNull ItemSpawnReason itemSpawnReason, - int sizeLimit) { + @NotNull Location location, + @NotNull Collection drops, + @NotNull ItemSpawnReason itemSpawnReason, + int sizeLimit) { // TODO: This doesn't make much sense, unit test time? final ItemStack[] arrayDrops = drops.toArray(new ItemStack[0]); @@ -901,21 +938,21 @@ public final class ItemUtils { } /** - * Spawn items form a collection if conditions are met. - * Each item is tested against the condition and spawned if it passes. + * Spawn items form a collection if conditions are met. Each item is tested against the + * condition and spawned if it passes. * - * @param potentialItemDrops The collection of items to iterate over, each one is tested and spawned if the - * predicate is true - * @param predicate The predicate to test the item against - * @param itemSpawnReason The reason for the item drop - * @param spawnLocation The location to spawn the item at - * @param player The player to spawn the item for + * @param potentialItemDrops The collection of items to iterate over, each one is tested and + * spawned if the predicate is true + * @param predicate The predicate to test the item against + * @param itemSpawnReason The reason for the item drop + * @param spawnLocation The location to spawn the item at + * @param player The player to spawn the item for */ public static void spawnItemsConditionally(@NotNull Collection potentialItemDrops, - @NotNull Predicate predicate, - @NotNull ItemSpawnReason itemSpawnReason, - @NotNull Location spawnLocation, - @NotNull Player player) { + @NotNull Predicate predicate, + @NotNull ItemSpawnReason itemSpawnReason, + @NotNull Location spawnLocation, + @NotNull Player player) { potentialItemDrops.stream() .filter(predicate) .forEach(itemStack -> spawnItem(player, spawnLocation, itemStack, itemSpawnReason)); diff --git a/src/main/java/com/gmail/nossr50/util/LogFilter.java b/src/main/java/com/gmail/nossr50/util/LogFilter.java index 4a1ee3898..25f9885e4 100644 --- a/src/main/java/com/gmail/nossr50/util/LogFilter.java +++ b/src/main/java/com/gmail/nossr50/util/LogFilter.java @@ -1,12 +1,11 @@ package com.gmail.nossr50.util; -import com.gmail.nossr50.mcMMO; +import static com.gmail.nossr50.util.LogUtils.DEBUG_STR; +import com.gmail.nossr50.mcMMO; import java.util.logging.Filter; import java.util.logging.LogRecord; -import static com.gmail.nossr50.util.LogUtils.DEBUG_STR; - public class LogFilter implements Filter { private final boolean debug; diff --git a/src/main/java/com/gmail/nossr50/util/LogUtils.java b/src/main/java/com/gmail/nossr50/util/LogUtils.java index b0c114d00..e9c970465 100644 --- a/src/main/java/com/gmail/nossr50/util/LogUtils.java +++ b/src/main/java/com/gmail/nossr50/util/LogUtils.java @@ -1,8 +1,7 @@ package com.gmail.nossr50.util; -import org.jetbrains.annotations.NotNull; - import java.util.logging.Logger; +import org.jetbrains.annotations.NotNull; public class LogUtils { diff --git a/src/main/java/com/gmail/nossr50/util/MaterialMapStore.java b/src/main/java/com/gmail/nossr50/util/MaterialMapStore.java index da7a21da5..99ff99c70 100644 --- a/src/main/java/com/gmail/nossr50/util/MaterialMapStore.java +++ b/src/main/java/com/gmail/nossr50/util/MaterialMapStore.java @@ -1,15 +1,14 @@ package com.gmail.nossr50.util; -import org.bukkit.Material; -import org.jetbrains.annotations.NotNull; - import java.util.HashMap; import java.util.HashSet; import java.util.Locale; +import org.bukkit.Material; +import org.jetbrains.annotations.NotNull; /** - * Stores hash tables for item and block names - * This allows for better support across multiple versions of Minecraft + * Stores hash tables for item and block names This allows for better support across multiple + * versions of Minecraft */ public class MaterialMapStore { @@ -171,27 +170,27 @@ public class MaterialMapStore { } private void fillTierMap() { - for(String id : leatherArmor) { + for (String id : leatherArmor) { tierValue.put(id, 1); } - for(String id : ironArmor) { + for (String id : ironArmor) { tierValue.put(id, 2); } - for(String id : goldArmor) { + for (String id : goldArmor) { tierValue.put(id, 3); } - for(String id : chainmailArmor) { + for (String id : chainmailArmor) { tierValue.put(id, 3); } - for(String id : diamondArmor) { + for (String id : diamondArmor) { tierValue.put(id, 6); } - for(String id : netheriteArmor) { + for (String id : netheriteArmor) { tierValue.put(id, 12); } } @@ -768,6 +767,7 @@ public class MaterialMapStore { /** * Checks if a Material is used for Armor + * * @param material target material * @return true if it is used for armor */ @@ -777,6 +777,7 @@ public class MaterialMapStore { /** * Checks if the id provided is used as armor + * * @param id target item id * @return true if the item id matches armor */ @@ -1202,7 +1203,7 @@ public class MaterialMapStore { abilityBlackList.add("lodestone"); abilityBlackList.add("respawn_anchor"); } - + private void fillToolBlackList() { toolBlackList.add("chiseled_bookshelf"); toolBlackList.add("black_bed"); diff --git a/src/main/java/com/gmail/nossr50/util/MaterialUtils.java b/src/main/java/com/gmail/nossr50/util/MaterialUtils.java index 4a38eba2f..3715249e7 100644 --- a/src/main/java/com/gmail/nossr50/util/MaterialUtils.java +++ b/src/main/java/com/gmail/nossr50/util/MaterialUtils.java @@ -4,9 +4,10 @@ import com.gmail.nossr50.mcMMO; import org.bukkit.Material; public final class MaterialUtils { - private MaterialUtils() {} + private MaterialUtils() { + } - protected static boolean isOre(Material data) { + static boolean isOre(Material data) { return mcMMO.getMaterialMapStore().isOre(data.getKey().getKey()); } } diff --git a/src/main/java/com/gmail/nossr50/util/MetadataConstants.java b/src/main/java/com/gmail/nossr50/util/MetadataConstants.java index cf57fffe9..e0d4d54a4 100644 --- a/src/main/java/com/gmail/nossr50/util/MetadataConstants.java +++ b/src/main/java/com/gmail/nossr50/util/MetadataConstants.java @@ -1,28 +1,27 @@ package com.gmail.nossr50.util; -import org.bukkit.metadata.FixedMetadataValue; -import org.jetbrains.annotations.NotNull; - import java.util.List; import java.util.Set; +import org.bukkit.metadata.FixedMetadataValue; +import org.jetbrains.annotations.NotNull; /** * Stores our constants related to metadata */ public class MetadataConstants { public static final @NotNull Set MOB_METADATA_KEYS = Set.of( - MetadataConstants.METADATA_KEY_MOB_SPAWNER_MOB, - MetadataConstants.METADATA_KEY_EGG_MOB, - MetadataConstants.METADATA_KEY_NETHER_PORTAL_MOB, - MetadataConstants.METADATA_KEY_COTW_SUMMONED_MOB, - MetadataConstants.METADATA_KEY_PLAYER_BRED_MOB, - MetadataConstants.METADATA_KEY_PLAYER_TAMED_MOB, - MetadataConstants.METADATA_KEY_EXPLOITED_ENDERMEN, - MetadataConstants.METADATA_KEY_CUSTOM_NAME, - MetadataConstants.METADATA_KEY_RUPTURE, - MetadataConstants.METADATA_KEY_EXPLOSION_FROM_RUPTURE, - MetadataConstants.METADATA_KEY_OLD_NAME_KEY, - MetadataConstants.METADATA_KEY_DODGE_TRACKER + MetadataConstants.METADATA_KEY_MOB_SPAWNER_MOB, + MetadataConstants.METADATA_KEY_EGG_MOB, + MetadataConstants.METADATA_KEY_NETHER_PORTAL_MOB, + MetadataConstants.METADATA_KEY_COTW_SUMMONED_MOB, + MetadataConstants.METADATA_KEY_PLAYER_BRED_MOB, + MetadataConstants.METADATA_KEY_PLAYER_TAMED_MOB, + MetadataConstants.METADATA_KEY_EXPLOITED_ENDERMEN, + MetadataConstants.METADATA_KEY_CUSTOM_NAME, + MetadataConstants.METADATA_KEY_RUPTURE, + MetadataConstants.METADATA_KEY_EXPLOSION_FROM_RUPTURE, + MetadataConstants.METADATA_KEY_OLD_NAME_KEY, + MetadataConstants.METADATA_KEY_DODGE_TRACKER ); public static final @NotNull List ARROW_METADATA_KEYS = List.of( diff --git a/src/main/java/com/gmail/nossr50/util/MetadataService.java b/src/main/java/com/gmail/nossr50/util/MetadataService.java index fac2b83a3..f42b8ce85 100644 --- a/src/main/java/com/gmail/nossr50/util/MetadataService.java +++ b/src/main/java/com/gmail/nossr50/util/MetadataService.java @@ -22,24 +22,28 @@ public final class MetadataService { } static { - NSK_SUPER_ABILITY_BOOSTED_ITEM = getNamespacedKey(MetadataConstants.METADATA_KEY_SUPER_ABILITY_BOOSTED_ITEM); + NSK_SUPER_ABILITY_BOOSTED_ITEM = getNamespacedKey( + MetadataConstants.METADATA_KEY_SUPER_ABILITY_BOOSTED_ITEM); NSK_MOB_SPAWNER_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_MOB_SPAWNER_MOB); NSK_EGG_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_EGG_MOB); NSK_NETHER_GATE_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_NETHER_PORTAL_MOB); NSK_COTW_SUMMONED_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_COTW_SUMMONED_MOB); NSK_PLAYER_BRED_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_PLAYER_BRED_MOB); NSK_PLAYER_TAMED_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_PLAYER_TAMED_MOB); - NSK_VILLAGER_TRADE_ORIGIN_ITEM = getNamespacedKey(MetadataConstants.METADATA_KEY_VILLAGER_TRADE_ORIGIN_ITEM); - NSK_EXPLOITED_ENDERMEN = getNamespacedKey(MetadataConstants.METADATA_KEY_EXPLOITED_ENDERMEN); - NSK_CONTAINER_UUID_MOST_SIG = getNamespacedKey(MetadataConstants.METADATA_KEY_CONTAINER_UUID_MOST_SIG); - NSK_CONTAINER_UUID_LEAST_SIG = getNamespacedKey(MetadataConstants.METADATA_KEY_CONTAINER_UUID_LEAST_SIG); + NSK_VILLAGER_TRADE_ORIGIN_ITEM = getNamespacedKey( + MetadataConstants.METADATA_KEY_VILLAGER_TRADE_ORIGIN_ITEM); + NSK_EXPLOITED_ENDERMEN = getNamespacedKey( + MetadataConstants.METADATA_KEY_EXPLOITED_ENDERMEN); + NSK_CONTAINER_UUID_MOST_SIG = getNamespacedKey( + MetadataConstants.METADATA_KEY_CONTAINER_UUID_MOST_SIG); + NSK_CONTAINER_UUID_LEAST_SIG = getNamespacedKey( + MetadataConstants.METADATA_KEY_CONTAINER_UUID_LEAST_SIG); } /** * Helper method to simplify generating namespaced keys * * @param key the {@link String} value of the key - * * @return the generated {@link NamespacedKey} */ public static @NotNull NamespacedKey getNamespacedKey(@NotNull String key) { diff --git a/src/main/java/com/gmail/nossr50/util/Misc.java b/src/main/java/com/gmail/nossr50/util/Misc.java index 3b90ff96c..c3603f8f4 100644 --- a/src/main/java/com/gmail/nossr50/util/Misc.java +++ b/src/main/java/com/gmail/nossr50/util/Misc.java @@ -5,16 +5,20 @@ import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.runnables.player.PlayerProfileLoadingTask; import com.gmail.nossr50.util.player.UserManager; import com.google.common.collect.ImmutableSet; -import org.bukkit.Location; -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; -import org.bukkit.entity.*; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.util.Locale; import java.util.Random; import java.util.Set; +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.ExperienceOrb; +import org.bukkit.entity.NPC; +import org.bukkit.entity.Player; +import org.bukkit.entity.Villager; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public final class Misc { private static final @NotNull Random random = new Random(); @@ -36,25 +40,30 @@ public final class Misc { public static final float LEVELUP_PITCH = 0.5F; // Reduced to differentiate between vanilla level-up public static final float LEVELUP_VOLUME = 0.75F * Config.getInstance().getMasterVolume(); // Use max volume always*/ - public static final @NotNull Set modNames = ImmutableSet.of("LOTR", "BUILDCRAFT", "ENDERIO", - "ENHANCEDBIOMES", "IC2", "METALLURGY", "FORESTRY", "GALACTICRAFT", "RAILCRAFT", "TWILIGHTFOREST", - "THAUMCRAFT", "GRAVESTONEMOD", "GROWTHCRAFT", "ARCTICMOBS", "DEMONMOBS", "INFERNOMOBS", "SWAMPMOBS", + public static final @NotNull 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() { + } /** - * Determines if an entity is an NPC but not a villager - * This method aims to establish compatibility between mcMMO and other plugins which create "NPCs" + * Determines if an entity is an NPC but not a villager This method aims to establish + * compatibility between mcMMO and other plugins which create "NPCs" + *

+ * It does this by checking the following 1) The entity is not a Villager 2) The entity can be + * considered an NPC + *

+ * In this context, an NPC is a bit hard to define. Various plugins determine what an NPC is in + * different ways. * - * It does this by checking the following - * 1) The entity is not a Villager - * 2) The entity can be considered an NPC - * - * In this context, an NPC is a bit hard to define. Various plugins determine what an NPC is in different ways. - * @see Misc::isNPCIncludingVillagers * @param entity target entity * @return true if the entity is not a Villager and is not a "NPC" + * @see Misc::isNPCIncludingVillagers */ public static boolean isNPCEntityExcludingVillagers(@NotNull Entity entity) { return (!isVillager(entity) @@ -88,15 +97,18 @@ public final class Misc { * @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 + * @return true if the distance between {@code first} and {@code second} is less than + * {@code maxDistance}, false otherwise */ - public static boolean isNear(@NotNull Location first, @NotNull Location second, double maxDistance) { - return (first.getWorld() == second.getWorld()) && (first.distanceSquared(second) < (maxDistance * maxDistance) || maxDistance == 0); + public static boolean isNear(@NotNull Location first, @NotNull Location second, + double maxDistance) { + return (first.getWorld() == second.getWorld()) && ( + first.distanceSquared(second) < (maxDistance * maxDistance) || maxDistance == 0); } /** * 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 */ @@ -117,15 +129,18 @@ public final class Misc { if (player != null) { UserManager.remove(player); - mcMMO.p.getFoliaLib().getScheduler().runLaterAsync(new PlayerProfileLoadingTask(player), 1); // 1 Tick delay to ensure the player is marked as online before we begin loading + mcMMO.p.getFoliaLib().getScheduler().runLaterAsync(new PlayerProfileLoadingTask(player), + 1); // 1 Tick delay to ensure the player is marked as online before we begin loading } } public static void printProgress(int convertedUsers, int progressInterval, long startMillis) { if ((convertedUsers % progressInterval) == 0) { - mcMMO.p.getLogger().info(String.format("Conversion progress: %d users at %.2f users/second", - convertedUsers, - convertedUsers / (double) ((System.currentTimeMillis() - startMillis) / TIME_CONVERSION_FACTOR))); + mcMMO.p.getLogger() + .info(String.format("Conversion progress: %d users at %.2f users/second", + convertedUsers, + convertedUsers / (double) ((System.currentTimeMillis() - startMillis) + / TIME_CONVERSION_FACTOR))); } } @@ -173,7 +188,8 @@ public final class Misc { * @return true if the player is the party leader */ public static boolean isPartyLeader(@NotNull McMMOPlayer mmoPlayer) { - return mmoPlayer.getParty().getLeader().getUniqueId().equals(mmoPlayer.getPlayer().getUniqueId()); + return mmoPlayer.getParty().getLeader().getUniqueId() + .equals(mmoPlayer.getPlayer().getUniqueId()); } // public static void spawnExperienceOrb(@NotNull Location location, int orbAmount, int experienceValue) { @@ -183,16 +199,18 @@ public final class Misc { // } public static void spawnExperienceOrb(@NotNull Location location, int experienceValue) { - if (location.getWorld() == null) + if (location.getWorld() == null) { return; + } - ExperienceOrb experienceOrb = (ExperienceOrb) location.getWorld().spawnEntity(location, EntityType.EXPERIENCE_ORB); + ExperienceOrb experienceOrb = (ExperienceOrb) location.getWorld() + .spawnEntity(location, EntityType.EXPERIENCE_ORB); experienceOrb.setExperience(experienceValue); } private static class SpawnOrbTask implements Runnable { private final Location location; - private int orbExpValue; + private final int orbExpValue; private SpawnOrbTask(Location location, int orbExpValue) { this.location = location; @@ -201,10 +219,12 @@ public final class Misc { @Override public void run() { - if (location == null || location.getWorld() == null) + if (location == null || location.getWorld() == null) { return; + } - ExperienceOrb experienceOrb = (ExperienceOrb) location.getWorld().spawnEntity(location, EntityType.EXPERIENCE_ORB); + ExperienceOrb experienceOrb = (ExperienceOrb) location.getWorld() + .spawnEntity(location, EntityType.EXPERIENCE_ORB); experienceOrb.setExperience(orbExpValue); } } diff --git a/src/main/java/com/gmail/nossr50/util/MobHealthbarUtils.java b/src/main/java/com/gmail/nossr50/util/MobHealthbarUtils.java index cf36faf12..aa24e4ba3 100644 --- a/src/main/java/com/gmail/nossr50/util/MobHealthbarUtils.java +++ b/src/main/java/com/gmail/nossr50/util/MobHealthbarUtils.java @@ -13,7 +13,8 @@ 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. @@ -24,18 +25,23 @@ public final class MobHealthbarUtils { */ public static String fixDeathMessage(String deathMessage, Player player) { EntityDamageEvent lastDamageCause = player.getLastDamageCause(); - String replaceString = lastDamageCause instanceof EntityDamageByEntityEvent ? StringUtils.getPrettyEntityTypeString(((EntityDamageByEntityEvent) lastDamageCause).getDamager().getType()) : "a mob"; + String replaceString = lastDamageCause instanceof EntityDamageByEntityEvent + ? StringUtils.getPrettyEntityTypeString( + ((EntityDamageByEntityEvent) lastDamageCause).getDamager().getType()) : "a mob"; - return deathMessage.replaceAll("(?:(§(?:[0-9A-FK-ORa-fk-or]))*(?:[❤■]{1,10})){1,2}", replaceString); + return deathMessage.replaceAll("(?:(§(?:[0-9A-FK-ORa-fk-or]))*(?:[❤■]{1,10})){1,2}", + replaceString); } /** * 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) { - if (mcMMO.isHealthBarPluginEnabled() || !mcMMO.p.getGeneralConfig().getMobHealthbarEnabled()) { + if (mcMMO.isHealthBarPluginEnabled() || !mcMMO.p.getGeneralConfig() + .getMobHealthbarEnabled()) { return; } @@ -54,15 +60,18 @@ public final class MobHealthbarUtils { /* * Store the name in metadata */ - if (target.getMetadata(MetadataConstants.METADATA_KEY_OLD_NAME_KEY).size() <= 0) - target.setMetadata(MetadataConstants.METADATA_KEY_OLD_NAME_KEY, new OldName(originalName, plugin)); + if (target.getMetadata(MetadataConstants.METADATA_KEY_OLD_NAME_KEY).size() <= 0) { + target.setMetadata(MetadataConstants.METADATA_KEY_OLD_NAME_KEY, + new OldName(originalName, plugin)); + } if (oldName == null) { oldName = ""; } boolean oldNameVisible = target.isCustomNameVisible(); - String newName = createHealthDisplay(mcMMO.p.getGeneralConfig().getMobHealthbarDefault(), target, damage); + String newName = createHealthDisplay(mcMMO.p.getGeneralConfig().getMobHealthbarDefault(), + target, damage); target.setCustomName(newName); target.setCustomNameVisible(true); @@ -70,21 +79,30 @@ public final class MobHealthbarUtils { int displayTime = mcMMO.p.getGeneralConfig().getMobHealthbarTime(); if (displayTime != -1) { - boolean updateName = !ChatColor.stripColor(oldName).equalsIgnoreCase(ChatColor.stripColor(newName)); + boolean updateName = !ChatColor.stripColor(oldName) + .equalsIgnoreCase(ChatColor.stripColor(newName)); if (updateName) { - target.setMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME, new FixedMetadataValue(mcMMO.p, oldName)); - target.setMetadata(MetadataConstants.METADATA_KEY_NAME_VISIBILITY, new FixedMetadataValue(mcMMO.p, oldNameVisible)); + target.setMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME, + new FixedMetadataValue(mcMMO.p, oldName)); + target.setMetadata(MetadataConstants.METADATA_KEY_NAME_VISIBILITY, + new FixedMetadataValue(mcMMO.p, oldNameVisible)); } else if (!target.hasMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME)) { - target.setMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME, new FixedMetadataValue(mcMMO.p, "")); - target.setMetadata(MetadataConstants.METADATA_KEY_NAME_VISIBILITY, new FixedMetadataValue(mcMMO.p, false)); + target.setMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME, + new FixedMetadataValue(mcMMO.p, "")); + target.setMetadata(MetadataConstants.METADATA_KEY_NAME_VISIBILITY, + new FixedMetadataValue(mcMMO.p, false)); } - mcMMO.p.getFoliaLib().getScheduler().runAtEntityLater(target, new MobHealthDisplayUpdaterTask(target), (long) displayTime * Misc.TICK_CONVERSION_FACTOR); // Clear health display after 3 seconds + mcMMO.p.getFoliaLib().getScheduler() + .runAtEntityLater(target, new MobHealthDisplayUpdaterTask(target), + (long) displayTime + * Misc.TICK_CONVERSION_FACTOR); // Clear health display after 3 seconds } } - private static String createHealthDisplay(MobHealthbarType mobHealthbarType, LivingEntity entity, double damage) { + private static String createHealthDisplay(MobHealthbarType mobHealthbarType, + LivingEntity entity, double damage) { double maxHealth = entity.getMaxHealth(); double currentHealth = Math.max(entity.getHealth() - damage, 0); double healthPercentage = (currentHealth / maxHealth) * 100.0D; @@ -124,7 +142,8 @@ public final class MobHealthbarUtils { return null; } - int coloredDisplay = (int) Math.max(Math.ceil(fullDisplay * (healthPercentage / 100.0D)), 0.5); + int coloredDisplay = (int) Math.max(Math.ceil(fullDisplay * (healthPercentage / 100.0D)), + 0.5); int grayDisplay = fullDisplay - coloredDisplay; StringBuilder healthbar = new StringBuilder(color + ""); diff --git a/src/main/java/com/gmail/nossr50/util/MobMetadataUtils.java b/src/main/java/com/gmail/nossr50/util/MobMetadataUtils.java index 9f25f503d..9e31ad01c 100644 --- a/src/main/java/com/gmail/nossr50/util/MobMetadataUtils.java +++ b/src/main/java/com/gmail/nossr50/util/MobMetadataUtils.java @@ -1,9 +1,21 @@ package com.gmail.nossr50.util; +import static com.gmail.nossr50.util.MetadataService.NSK_COTW_SUMMONED_MOB; +import static com.gmail.nossr50.util.MetadataService.NSK_EGG_MOB; +import static com.gmail.nossr50.util.MetadataService.NSK_EXPLOITED_ENDERMEN; +import static com.gmail.nossr50.util.MetadataService.NSK_MOB_SPAWNER_MOB; +import static com.gmail.nossr50.util.MetadataService.NSK_NETHER_GATE_MOB; +import static com.gmail.nossr50.util.MetadataService.NSK_PLAYER_BRED_MOB; +import static com.gmail.nossr50.util.MetadataService.NSK_PLAYER_TAMED_MOB; + import com.gmail.nossr50.api.exceptions.IncompleteNamespacedKeyRegister; import com.gmail.nossr50.config.PersistentDataConfig; import com.gmail.nossr50.metadata.MobMetaFlagType; import com.google.common.collect.MapMaker; +import java.util.EnumMap; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; import org.bukkit.NamespacedKey; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; @@ -11,13 +23,6 @@ import org.bukkit.persistence.PersistentDataContainer; import org.bukkit.persistence.PersistentDataType; import org.jetbrains.annotations.NotNull; -import java.util.EnumMap; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import static com.gmail.nossr50.util.MetadataService.*; - public final class MobMetadataUtils { private static final @NotNull ConcurrentMap> mobRegistry; // transient data private static final @NotNull EnumMap mobFlagKeyMap; // used for persistent data @@ -48,8 +53,8 @@ public final class MobMetadataUtils { } /** - * Registers the namespaced keys required by the API (CB/Spigot) - * Used primarily for persistent data + * Registers the namespaced keys required by the API (CB/Spigot) Used primarily for persistent + * data */ private static void initMobFlagKeyMap() throws IncompleteNamespacedKeyRegister { for (MobMetaFlagType mobMetaFlagType : MobMetaFlagType.values()) { @@ -59,9 +64,11 @@ public final class MobMetadataUtils { case NETHER_PORTAL_MOB -> mobFlagKeyMap.put(mobMetaFlagType, NSK_NETHER_GATE_MOB); case COTW_SUMMONED_MOB -> mobFlagKeyMap.put(mobMetaFlagType, NSK_COTW_SUMMONED_MOB); case PLAYER_BRED_MOB -> mobFlagKeyMap.put(mobMetaFlagType, NSK_PLAYER_BRED_MOB); - case EXPLOITED_ENDERMEN -> mobFlagKeyMap.put(mobMetaFlagType, NSK_EXPLOITED_ENDERMEN); + case EXPLOITED_ENDERMEN -> + mobFlagKeyMap.put(mobMetaFlagType, NSK_EXPLOITED_ENDERMEN); case PLAYER_TAMED_MOB -> mobFlagKeyMap.put(mobMetaFlagType, NSK_PLAYER_TAMED_MOB); - default -> throw new IncompleteNamespacedKeyRegister("Missing namespaced key register for type: " + mobMetaFlagType); + default -> throw new IncompleteNamespacedKeyRegister( + "Missing namespaced key register for type: " + mobMetaFlagType); } } } @@ -69,13 +76,15 @@ public final class MobMetadataUtils { /** * Checks if a {@link LivingEntity} has a specific mcMMO mob flag. * - * @param flag the type of mob flag to check for + * @param flag the type of mob flag to check for * @param livingEntity the living entity to check * @return true if the mob has the specified metadata flag */ - public static boolean hasMobFlag(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity) { + public static boolean hasMobFlag(@NotNull MobMetaFlagType flag, + @NotNull LivingEntity livingEntity) { if (PersistentDataConfig.getInstance().isMobPersistent(flag)) { - return livingEntity.getPersistentDataContainer().has(mobFlagKeyMap.get(flag), PersistentDataType.BYTE); + return livingEntity.getPersistentDataContainer() + .has(mobFlagKeyMap.get(flag), PersistentDataType.BYTE); } else { final Set flags = mobRegistry.get(livingEntity); return flags != null && flags.contains(flag); @@ -103,13 +112,14 @@ public final class MobMetadataUtils { } /** - * Copies all mcMMO mob flags from one {@link LivingEntity} to another. - * This does not clear existing mcMMO mob flags on the target. + * Copies all mcMMO mob flags from one {@link LivingEntity} to another. This does not clear + * existing mcMMO mob flags on the target. * * @param sourceEntity entity to copy from * @param targetEntity entity to copy to */ - public static void addMobFlags(@NotNull LivingEntity sourceEntity, @NotNull LivingEntity targetEntity) { + public static void addMobFlags(@NotNull LivingEntity sourceEntity, + @NotNull LivingEntity targetEntity) { if (!hasMobFlags(sourceEntity)) { return; } @@ -123,27 +133,31 @@ public final class MobMetadataUtils { } else { Set sourceFlags = mobRegistry.get(sourceEntity); if (sourceFlags != null) { - Set targetFlags = mobRegistry.computeIfAbsent(targetEntity, k -> ConcurrentHashMap.newKeySet()); + Set targetFlags = mobRegistry.computeIfAbsent(targetEntity, + k -> ConcurrentHashMap.newKeySet()); targetFlags.addAll(sourceFlags); } } } /** - * Adds a mob flag to a {@link LivingEntity}. - * The existence of the flag acts as a true value; non-existence is false. + * Adds a mob flag to a {@link LivingEntity}. The existence of the flag acts as a true value; + * non-existence is false. * - * @param flag the desired flag to assign + * @param flag the desired flag to assign * @param livingEntity the target living entity */ - public static void flagMetadata(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity) { + public static void flagMetadata(@NotNull MobMetaFlagType flag, + @NotNull LivingEntity livingEntity) { if (PersistentDataConfig.getInstance().isMobPersistent(flag)) { if (!hasMobFlag(flag, livingEntity)) { PersistentDataContainer persistentDataContainer = livingEntity.getPersistentDataContainer(); - persistentDataContainer.set(mobFlagKeyMap.get(flag), PersistentDataType.BYTE, MetadataConstants.SIMPLE_FLAG_VALUE); + persistentDataContainer.set(mobFlagKeyMap.get(flag), PersistentDataType.BYTE, + MetadataConstants.SIMPLE_FLAG_VALUE); } } else { - final Set flags = mobRegistry.computeIfAbsent(livingEntity, k -> ConcurrentHashMap.newKeySet()); + final Set flags = mobRegistry.computeIfAbsent(livingEntity, + k -> ConcurrentHashMap.newKeySet()); flags.add(flag); } } @@ -151,10 +165,11 @@ public final class MobMetadataUtils { /** * Removes a specific mob flag from a {@link LivingEntity}. * - * @param flag the flag to remove + * @param flag the flag to remove * @param livingEntity the target living entity */ - public static void removeMobFlag(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity) { + public static void removeMobFlag(@NotNull MobMetaFlagType flag, + @NotNull LivingEntity livingEntity) { if (PersistentDataConfig.getInstance().isMobPersistent(flag)) { if (hasMobFlag(flag, livingEntity)) { PersistentDataContainer persistentDataContainer = livingEntity.getPersistentDataContainer(); diff --git a/src/main/java/com/gmail/nossr50/util/Motd.java b/src/main/java/com/gmail/nossr50/util/Motd.java index 8e1ec7c20..dec741b5c 100644 --- a/src/main/java/com/gmail/nossr50/util/Motd.java +++ b/src/main/java/com/gmail/nossr50/util/Motd.java @@ -4,18 +4,18 @@ import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.skills.PerksUtils; -import org.bukkit.entity.Player; -import org.bukkit.plugin.PluginDescriptionFile; - import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Locale; +import org.bukkit.entity.Player; +import org.bukkit.plugin.PluginDescriptionFile; 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()); @@ -30,7 +30,7 @@ public final class Motd { /** * Display version info. * - * @param player Target player + * @param player Target player * @param version Plugin version */ public static void displayVersion(Player player, String version) { @@ -68,14 +68,17 @@ public final class Motd { seperator = " & "; } - player.sendMessage(LocaleLoader.getString("MOTD.Hardcore.Enabled", statLossInfo + seperator + vampirismInfo)); + player.sendMessage(LocaleLoader.getString("MOTD.Hardcore.Enabled", + statLossInfo + seperator + vampirismInfo)); if (deathStatLossEnabled) { - player.sendMessage(LocaleLoader.getString("MOTD.Hardcore.DeathStatLoss.Stats", mcMMO.p.getGeneralConfig().getHardcoreDeathStatPenaltyPercentage())); + player.sendMessage(LocaleLoader.getString("MOTD.Hardcore.DeathStatLoss.Stats", + mcMMO.p.getGeneralConfig().getHardcoreDeathStatPenaltyPercentage())); } if (vampirismEnabled) { - player.sendMessage(LocaleLoader.getString("MOTD.Hardcore.Vampirism.Stats", mcMMO.p.getGeneralConfig().getHardcoreVampirismStatLeechPercentage())); + player.sendMessage(LocaleLoader.getString("MOTD.Hardcore.Vampirism.Stats", + mcMMO.p.getGeneralConfig().getHardcoreVampirismStatLeechPercentage())); } } @@ -88,7 +91,9 @@ public final class Motd { for (PrimarySkillType skill : PrimarySkillType.values()) { //TODO: Wow this is horrifying... if (PerksUtils.handleXpPerks(player, 1, skill) > 1) { - player.sendMessage(PERK_PREFIX + LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Perks.XP.Name"), LocaleLoader.getString("Perks.XP.Desc"))); + player.sendMessage(PERK_PREFIX + LocaleLoader.getString("Effects.Template", + LocaleLoader.getString("Perks.XP.Name"), + LocaleLoader.getString("Perks.XP.Desc"))); return; } } @@ -103,8 +108,12 @@ public final class Motd { double cooldownReduction = 1 - (PerksUtils.handleCooldownPerks(player, 12) / 12.0); if (cooldownReduction > 0.0) { - DecimalFormat percent = new DecimalFormat("##0.00%", DecimalFormatSymbols.getInstance(Locale.US)); - player.sendMessage(PERK_PREFIX + LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Perks.Cooldowns.Name"), LocaleLoader.getString("Perks.Cooldowns.Desc", percent.format(cooldownReduction)))); + DecimalFormat percent = new DecimalFormat("##0.00%", + DecimalFormatSymbols.getInstance(Locale.US)); + player.sendMessage(PERK_PREFIX + LocaleLoader.getString("Effects.Template", + LocaleLoader.getString("Perks.Cooldowns.Name"), + LocaleLoader.getString("Perks.Cooldowns.Desc", + percent.format(cooldownReduction)))); } } @@ -117,7 +126,9 @@ public final class Motd { int perkAmount = PerksUtils.handleActivationPerks(player, 0, 0); if (perkAmount > 0) { - player.sendMessage(PERK_PREFIX + LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Perks.ActivationTime.Name"), LocaleLoader.getString("Perks.ActivationTime.Desc", perkAmount))); + player.sendMessage(PERK_PREFIX + LocaleLoader.getString("Effects.Template", + LocaleLoader.getString("Perks.ActivationTime.Name"), + LocaleLoader.getString("Perks.ActivationTime.Desc", perkAmount))); } } @@ -129,7 +140,9 @@ public final class Motd { public static void displayLuckyPerks(Player player) { for (PrimarySkillType skill : PrimarySkillType.values()) { if (Permissions.lucky(player, skill)) { - player.sendMessage(PERK_PREFIX + LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Perks.Lucky.Name"), LocaleLoader.getString("Perks.Lucky.Desc.Login"))); + player.sendMessage(PERK_PREFIX + LocaleLoader.getString("Effects.Template", + LocaleLoader.getString("Perks.Lucky.Name"), + LocaleLoader.getString("Perks.Lucky.Desc.Login"))); return; } } @@ -138,7 +151,7 @@ public final class Motd { /** * Display website info. * - * @param player Target player + * @param player Target player * @param website Plugin website */ public static void displayWebsite(Player player, String website) { diff --git a/src/main/java/com/gmail/nossr50/util/Permissions.java b/src/main/java/com/gmail/nossr50/util/Permissions.java index 03fcae47a..60d905b4c 100644 --- a/src/main/java/com/gmail/nossr50/util/Permissions.java +++ b/src/main/java/com/gmail/nossr50/util/Permissions.java @@ -8,6 +8,7 @@ import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.skills.RankUtils; +import java.util.Locale; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.World; @@ -20,86 +21,214 @@ import org.bukkit.plugin.PluginManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Locale; - public final class Permissions { - private Permissions() {} + private Permissions() { + } /* * GENERAL */ - public static boolean motd(Permissible permissible) { return permissible.hasPermission("mcmmo.motd"); } - public static boolean levelUpBroadcast(Permissible permissible) { return permissible.hasPermission("mcmmo.broadcast.levelup"); } - 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 levelUpBroadcast(Permissible permissible) { + return permissible.hasPermission("mcmmo.broadcast.levelup"); + } + + 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 hardcoreBypass(Permissible permissible) { + return permissible.hasPermission("mcmmo.bypass.hardcoremode"); + } + + public static boolean arcaneBypass(Permissible permissible) { + return permissible.hasPermission("mcmmo.bypass.arcanebypass"); + } /* 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 colorChat(Permissible permissible) { return permissible.hasPermission("mcmmo.chat.colors"); } + 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 colorChat(Permissible permissible) { + return permissible.hasPermission("mcmmo.chat.colors"); + } /* * 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 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(Locale.ENGLISH)); } + public static boolean mcability(Permissible permissible) { + return (permissible.hasPermission("mcmmo.commands.mcability")); + } - 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 mcabilityOthers(Permissible permissible) { + return (permissible.hasPermission("mcmmo.commands.mcability.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(Locale.ENGLISH)); } - 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(Locale.ENGLISH)); } + public static boolean adminChatSpy(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.mcchatspy"); + } - public static boolean xplock(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.commands.xplock." + skill.toString().toLowerCase(Locale.ENGLISH)); } + public static boolean adminChatSpyOthers(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.mcchatspy.others"); + } - 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 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 reloadlocale(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.reloadlocale"); } + 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(Locale.ENGLISH)); + } + + 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(Locale.ENGLISH)); + } + + 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(Locale.ENGLISH)); + } + + public static boolean xplock(Permissible permissible, PrimarySkillType skill) { + return permissible.hasPermission( + "mcmmo.commands.xplock." + skill.toString().toLowerCase(Locale.ENGLISH)); + } + + 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 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 reloadlocale(Permissible permissible) { + return permissible.hasPermission("mcmmo.commands.reloadlocale"); + } /* * PERKS @@ -107,178 +236,339 @@ 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(Locale.ENGLISH)); } + 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(Locale.ENGLISH)); + } /* XP PERKS */ - public static boolean quadrupleXp(Permissible permissible, PrimarySkillType skill) { + public static boolean quadrupleXp(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.xp.quadruple.all") - || permissible.hasPermission("mcmmo.perks.xp.quadruple." + skill.toString().toLowerCase(Locale.ENGLISH)); + || permissible.hasPermission( + "mcmmo.perks.xp.quadruple." + skill.toString().toLowerCase(Locale.ENGLISH)); } - - public static boolean tripleXp(Permissible permissible, PrimarySkillType skill) { + + public static boolean tripleXp(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.xp.triple.all") - || permissible.hasPermission("mcmmo.perks.xp.triple." + skill.toString().toLowerCase(Locale.ENGLISH)); + || permissible.hasPermission( + "mcmmo.perks.xp.triple." + skill.toString().toLowerCase(Locale.ENGLISH)); } - - public static boolean doubleAndOneHalfXp(Permissible permissible, PrimarySkillType skill) { + + public static boolean doubleAndOneHalfXp(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.xp.150percentboost.all") - || permissible.hasPermission("mcmmo.perks.xp.150percentboost." + skill.toString().toLowerCase(Locale.ENGLISH)); + || permissible.hasPermission( + "mcmmo.perks.xp.150percentboost." + skill.toString().toLowerCase(Locale.ENGLISH)); } - - public static boolean doubleXp(Permissible permissible, PrimarySkillType skill) { + + public static boolean doubleXp(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.xp.double.all") - || permissible.hasPermission("mcmmo.perks.xp.double." + skill.toString().toLowerCase(Locale.ENGLISH)); + || permissible.hasPermission( + "mcmmo.perks.xp.double." + skill.toString().toLowerCase(Locale.ENGLISH)); } - - public static boolean oneAndOneHalfXp(Permissible permissible, PrimarySkillType skill) { + + public static boolean oneAndOneHalfXp(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.xp.50percentboost.all") - || permissible.hasPermission("mcmmo.perks.xp.50percentboost." + skill.toString().toLowerCase(Locale.ENGLISH)); + || permissible.hasPermission( + "mcmmo.perks.xp.50percentboost." + skill.toString().toLowerCase(Locale.ENGLISH)); } public static boolean oneAndAQuarterXp(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.xp.25percentboost.all") - || permissible.hasPermission("mcmmo.perks.xp.25percentboost." + skill.toString().toLowerCase(Locale.ENGLISH)); + || permissible.hasPermission( + "mcmmo.perks.xp.25percentboost." + skill.toString().toLowerCase(Locale.ENGLISH)); } - public static boolean oneAndOneTenthXp(Permissible permissible, PrimarySkillType skill) { + public static boolean oneAndOneTenthXp(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.xp.10percentboost.all") - || permissible.hasPermission("mcmmo.perks.xp.10percentboost." + skill.toString().toLowerCase(Locale.ENGLISH)); + || permissible.hasPermission( + "mcmmo.perks.xp.10percentboost." + skill.toString().toLowerCase(Locale.ENGLISH)); } public static boolean customXpBoost(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.xp.customboost.all") - || permissible.hasPermission("mcmmo.perks.xp.customboost." + skill.toString().toLowerCase(Locale.ENGLISH)); + || permissible.hasPermission( + "mcmmo.perks.xp.customboost." + skill.toString().toLowerCase(Locale.ENGLISH)); } /* 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(Locale.ENGLISH)); + return permissible.hasPermission( + "mcmmo.skills." + skill.toString().toLowerCase(Locale.ENGLISH)); } - public static boolean vanillaXpBoost(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.ability." + skill.toString().toLowerCase(Locale.ENGLISH) + ".vanillaxpboost"); } - public static boolean isSubSkillEnabled(@Nullable Permissible permissible, @NotNull SubSkillType subSkillType) { - if (permissible == null) + public static boolean vanillaXpBoost(Permissible permissible, PrimarySkillType skill) { + return permissible.hasPermission( + "mcmmo.ability." + skill.toString().toLowerCase(Locale.ENGLISH) + + ".vanillaxpboost"); + } + + public static boolean isSubSkillEnabled(@Nullable Permissible permissible, + @NotNull SubSkillType subSkillType) { + if (permissible == null) { return false; + } return permissible.hasPermission(subSkillType.getPermissionNodeAddress()); } - public static boolean isSubSkillEnabled(@Nullable McMMOPlayer permissible, @NotNull SubSkillType subSkillType) { - if (permissible == null) + public static boolean isSubSkillEnabled(@Nullable McMMOPlayer permissible, + @NotNull SubSkillType subSkillType) { + if (permissible == null) { return false; + } return isSubSkillEnabled(permissible.getPlayer(), subSkillType); } /* 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(Locale.ENGLISH)); } - public static boolean greenThumbPlant(Permissible permissible, Material material) { return permissible.hasPermission("mcmmo.ability.herbalism.greenthumb.plants." + material.toString().replace("_", "").toLowerCase(Locale.ENGLISH)); } + 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(Locale.ENGLISH)); + } + + public static boolean greenThumbPlant(Permissible permissible, Material material) { + return permissible.hasPermission( + "mcmmo.ability.herbalism.greenthumb.plants." + material.toString().replace("_", "") + .toLowerCase(Locale.ENGLISH)); + } /* 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(Locale.ENGLISH) + "repair"); } - public static boolean repairMaterialType(Permissible permissible, MaterialType repairMaterialType) { return permissible.hasPermission("mcmmo.ability.repair." + repairMaterialType.toString().toLowerCase(Locale.ENGLISH) + "repair"); } + public static boolean repairItemType(Permissible permissible, ItemType repairItemType) { + return permissible.hasPermission( + "mcmmo.ability.repair." + repairItemType.toString().toLowerCase(Locale.ENGLISH) + + "repair"); + } + + public static boolean repairMaterialType(Permissible permissible, + MaterialType repairMaterialType) { + return permissible.hasPermission( + "mcmmo.ability.repair." + repairMaterialType.toString().toLowerCase(Locale.ENGLISH) + + "repair"); + } /* SALVAGE */ - public static boolean arcaneSalvage(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.salvage.arcanesalvage"); } + 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(Locale.ENGLISH) + "salvage"); } - public static boolean salvageMaterialType(Permissible permissible, MaterialType salvageMaterialType) { return permissible.hasPermission("mcmmo.ability.salvage." + salvageMaterialType.toString().toLowerCase(Locale.ENGLISH) + "salvage"); } + public static boolean salvageItemType(Permissible permissible, ItemType salvageItemType) { + return permissible.hasPermission( + "mcmmo.ability.salvage." + salvageItemType.toString().toLowerCase(Locale.ENGLISH) + + "salvage"); + } + + public static boolean salvageMaterialType(Permissible permissible, + MaterialType salvageMaterialType) { + return permissible.hasPermission("mcmmo.ability.salvage." + salvageMaterialType.toString() + .toLowerCase(Locale.ENGLISH) + "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(Locale.ENGLISH)); } + public static boolean callOfTheWild(Permissible permissible, EntityType type) { + return permissible.hasPermission("mcmmo.ability.taming.callofthewild." + type.toString() + .toLowerCase(Locale.ENGLISH)); + } /* 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"); + } /* CROSSBOWS */ - public static boolean trickShot(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.crossbows.trickshot"); } - public static boolean poweredShot(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.crossbows.poweredshot"); } + public static boolean trickShot(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.crossbows.trickshot"); + } + + public static boolean poweredShot(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.crossbows.poweredshot"); + } /* TRIDENTS */ - public static boolean tridentsLimitBreak(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.tridents.superability"); } + public static boolean tridentsLimitBreak(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.tridents.superability"); + } /* MACES */ - public static boolean macesLimitBreak(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.maces.limitbreak"); } + public static boolean macesLimitBreak(Permissible permissible) { + return permissible.hasPermission("mcmmo.ability.maces.limitbreak"); + } /* * 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(Locale.ENGLISH)); } - 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(Locale.ENGLISH)); + } + + 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(); PluginManager pluginManager = server.getPluginManager(); for (World world : server.getWorlds()) { - addDynamicPermission("mcmmo.commands.ptp.world." + world.getName(), PermissionDefault.OP, pluginManager); + addDynamicPermission("mcmmo.commands.ptp.world." + world.getName(), + PermissionDefault.OP, pluginManager); } } - private static void addDynamicPermission(String permissionName, PermissionDefault permissionDefault, PluginManager pluginManager) { + private static void addDynamicPermission(String permissionName, + PermissionDefault permissionDefault, PluginManager pluginManager) { Permission permission = new Permission(permissionName); permission.setDefault(permissionDefault); pluginManager.addPermission(permission); @@ -291,7 +581,9 @@ public final class Permissions { * @param subSkillType target subskill * @return true if the player has permission and has the skill unlocked */ - public static boolean canUseSubSkill(@NotNull Player player, @NotNull SubSkillType subSkillType) { - return isSubSkillEnabled(player, subSkillType) && RankUtils.hasUnlockedSubskill(player, subSkillType); + public static boolean canUseSubSkill(@NotNull Player player, + @NotNull SubSkillType subSkillType) { + return isSubSkillEnabled(player, subSkillType) && RankUtils.hasUnlockedSubskill(player, + subSkillType); } } diff --git a/src/main/java/com/gmail/nossr50/util/PotionEffectUtil.java b/src/main/java/com/gmail/nossr50/util/PotionEffectUtil.java index 706cc8c9f..d84a969d5 100644 --- a/src/main/java/com/gmail/nossr50/util/PotionEffectUtil.java +++ b/src/main/java/com/gmail/nossr50/util/PotionEffectUtil.java @@ -3,9 +3,9 @@ package com.gmail.nossr50.util; import org.bukkit.potion.PotionEffectType; /** - * This util class is responsible for mapping the correct potion effect types for the server version. - * This is necessary because the potion effect types have changed between versions. - * This util class will provide the correct potion effect types for the server version. + * This util class is responsible for mapping the correct potion effect types for the server + * version. This is necessary because the potion effect types have changed between versions. This + * util class will provide the correct potion effect types for the server version. */ final public class PotionEffectUtil { private static final PotionEffectType haste; @@ -57,7 +57,8 @@ final public class PotionEffectUtil { private static PotionEffectType getHasteLegacy() { try { - Object potionEffectTypeWrapper = PotionEffectType.class.getField("FAST_DIGGING").get(null); + Object potionEffectTypeWrapper = PotionEffectType.class.getField("FAST_DIGGING") + .get(null); return (PotionEffectType) potionEffectTypeWrapper; } catch (IllegalAccessException | NoSuchFieldException e) { return null; @@ -73,8 +74,9 @@ final public class PotionEffectUtil { } /** - * Get the Haste potion effect type. - * This will return the correct potion effect type for the server version. + * Get the Haste potion effect type. This will return the correct potion effect type for the + * server version. + * * @return The Haste potion effect type. */ public static PotionEffectType getHastePotionEffectType() { @@ -82,8 +84,9 @@ final public class PotionEffectUtil { } /** - * Get the Nausea potion effect type. - * This will return the correct potion effect type for the server version. + * Get the Nausea potion effect type. This will return the correct potion effect type for the + * server version. + * * @return The Nausea potion effect type. */ public static PotionEffectType getNauseaPotionEffectType() { diff --git a/src/main/java/com/gmail/nossr50/util/PotionUtil.java b/src/main/java/com/gmail/nossr50/util/PotionUtil.java index 6ca19618b..9fee5840c 100644 --- a/src/main/java/com/gmail/nossr50/util/PotionUtil.java +++ b/src/main/java/com/gmail/nossr50/util/PotionUtil.java @@ -1,6 +1,13 @@ package com.gmail.nossr50.util; import com.gmail.nossr50.mcMMO; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; import org.bukkit.NamespacedKey; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionEffectType; @@ -8,10 +15,6 @@ import org.bukkit.potion.PotionType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.*; - public class PotionUtil { // Some of the old potion types got renamed, our configs can still contain these old names private static final Map legacyPotionTypes = new HashMap<>(); @@ -65,10 +68,13 @@ public class PotionUtil { /** * Derive a potion from a partial name, and whether it should be upgraded or extended. - * @param partialName potion type as a string, can be a substring of the potion type but must match exactly + * + * @param partialName potion type as a string, can be a substring of the potion type but must + * match exactly * @return The potion type */ - public static PotionType matchPotionType(String partialName, boolean isUpgraded, boolean isExtended) { + public static PotionType matchPotionType(String partialName, boolean isUpgraded, + boolean isExtended) { if (COMPATIBILITY_MODE == PotionCompatibilityType.PRE_1_20_5) { return matchLegacyPotionType(partialName); } else { @@ -99,7 +105,8 @@ public class PotionUtil { .findAny().orElse(null); } - private static String convertUpgradedOrExtended(String potionType, boolean isUpgraded, boolean isExtended) { + private static String convertUpgradedOrExtended(String potionType, boolean isUpgraded, + boolean isExtended) { if (isUpgraded) { potionType = STRONG + "_" + potionType; } @@ -132,8 +139,9 @@ public class PotionUtil { } /** - * Older versions of Spigot do not have getKey() in PotionType - * We need to check for the existence of this method before calling it + * Older versions of Spigot do not have getKey() in PotionType We need to check for the + * existence of this method before calling it + * * @return The getKey method */ private static @Nullable Method getKeyMethod() { @@ -325,7 +333,8 @@ public class PotionUtil { } } - private static NamespacedKey getModernPotionTypeKey(PotionMeta potionMeta) throws IllegalAccessException, InvocationTargetException { + private static NamespacedKey getModernPotionTypeKey(PotionMeta potionMeta) + throws IllegalAccessException, InvocationTargetException { PotionType potionType = (PotionType) methodPotionMetaGetBasePotionType.invoke(potionMeta); return (NamespacedKey) methodPotionTypeGetKey.invoke(potionType); } @@ -352,7 +361,8 @@ public class PotionUtil { } } - public static boolean isPotionTypeWithoutEffects(@NotNull PotionMeta potionMeta, String potionType) { + public static boolean isPotionTypeWithoutEffects(@NotNull PotionMeta potionMeta, + String potionType) { return isPotionType(potionMeta, potionType) && !hasBasePotionEffects(potionMeta) && potionMeta.getCustomEffects().isEmpty(); @@ -389,7 +399,8 @@ public class PotionUtil { private static boolean isPotionTypeWaterModern(@NotNull PotionMeta potionMeta) { try { - return getModernPotionTypeKey(potionMeta).getKey().equalsIgnoreCase(WATER_POTION_TYPE_STR); + return getModernPotionTypeKey(potionMeta).getKey() + .equalsIgnoreCase(WATER_POTION_TYPE_STR); } catch (IllegalAccessException | InvocationTargetException ex) { throw new RuntimeException(ex); } @@ -408,7 +419,8 @@ public class PotionUtil { Object potionData = methodPotionMetaGetBasePotionData.invoke(potionMeta); Object otherPotionData = methodPotionMetaGetBasePotionData.invoke(otherPotionMeta); PotionType potionType = (PotionType) methodPotionDataGetType.invoke(potionData); - PotionType otherPotionType = (PotionType) methodPotionDataGetType.invoke(otherPotionData); + PotionType otherPotionType = (PotionType) methodPotionDataGetType.invoke( + otherPotionData); return potionType == otherPotionType; } catch (IllegalAccessException | InvocationTargetException ex) { throw new RuntimeException(ex); @@ -417,8 +429,10 @@ public class PotionUtil { private static boolean samePotionTypeModern(PotionMeta potionMeta, PotionMeta otherPotionMeta) { try { - PotionType potionType = (PotionType) methodPotionMetaGetBasePotionType.invoke(potionMeta); - PotionType otherPotionType = (PotionType) methodPotionMetaGetBasePotionType.invoke(otherPotionMeta); + PotionType potionType = (PotionType) methodPotionMetaGetBasePotionType.invoke( + potionMeta); + PotionType otherPotionType = (PotionType) methodPotionMetaGetBasePotionType.invoke( + otherPotionMeta); return potionType == otherPotionType; } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); @@ -433,7 +447,8 @@ public class PotionUtil { } } - private static boolean samePotionEffectsModern(PotionMeta potionMeta, PotionMeta otherPotionMeta) { + private static boolean samePotionEffectsModern(PotionMeta potionMeta, + PotionMeta otherPotionMeta) { return potionMeta.getCustomEffects().equals(otherPotionMeta.getCustomEffects()); } @@ -457,8 +472,10 @@ public class PotionUtil { private static boolean hasBasePotionEffectsModern(PotionMeta potionMeta) { try { - PotionType potionType = (PotionType) methodPotionMetaGetBasePotionType.invoke(potionMeta); - List potionEffectTypeList = (List) methodPotionTypeGetPotionEffects.invoke(potionType); + PotionType potionType = (PotionType) methodPotionMetaGetBasePotionType.invoke( + potionMeta); + List potionEffectTypeList = (List) methodPotionTypeGetPotionEffects.invoke( + potionType); return potionEffectTypeList != null && !potionEffectTypeList.isEmpty(); } catch (IllegalAccessException | InvocationTargetException ex) { throw new RuntimeException(ex); @@ -466,14 +483,15 @@ public class PotionUtil { } /** - * Set the base potion type of a potion meta. - * Note that extended/upgraded are ignored in 1.20.5 and later. + * Set the base potion type of a potion meta. Note that extended/upgraded are ignored in 1.20.5 + * and later. * * @param potionMeta the potion meta * @param extended true if the potion is extended * @param upgraded true if the potion is upgraded */ - public static void setBasePotionType(PotionMeta potionMeta, PotionType potionType, boolean extended, boolean upgraded) { + public static void setBasePotionType(PotionMeta potionMeta, PotionType potionType, + boolean extended, boolean upgraded) { if (methodPotionMetaSetBasePotionType == null) { setBasePotionTypeLegacy(potionMeta, potionType, extended, upgraded); } else { @@ -481,14 +499,17 @@ public class PotionUtil { } } - public static void setUpgradedAndExtendedProperties(PotionType potionType, PotionMeta potionMeta, - boolean isUpgraded, boolean isExtended) { - if (potionDataClass == null || mcMMO.getCompatibilityManager().getMinecraftGameVersion().isAtLeast(1, 20, 5)) { + public static void setUpgradedAndExtendedProperties(PotionType potionType, + PotionMeta potionMeta, + boolean isUpgraded, boolean isExtended) { + if (potionDataClass == null || mcMMO.getCompatibilityManager().getMinecraftGameVersion() + .isAtLeast(1, 20, 5)) { return; } try { - final Object potionData = potionDataClass.getConstructor(PotionType.class, boolean.class, boolean.class) + final Object potionData = potionDataClass.getConstructor(PotionType.class, + boolean.class, boolean.class) .newInstance(potionType, isExtended, isUpgraded); methodPotionMetaSetBasePotionData.invoke(potionMeta, potionData); } catch (IllegalAccessException | InvocationTargetException | InstantiationException @@ -497,13 +518,16 @@ public class PotionUtil { } } - private static void setBasePotionTypeLegacy(PotionMeta potionMeta, PotionType potionType, boolean extended, - boolean upgraded) { + private static void setBasePotionTypeLegacy(PotionMeta potionMeta, PotionType potionType, + boolean extended, + boolean upgraded) { try { - Object potionData = potionDataClass.getConstructor(PotionType.class, boolean.class, boolean.class) + Object potionData = potionDataClass.getConstructor(PotionType.class, boolean.class, + boolean.class) .newInstance(potionType, extended, upgraded); methodPotionMetaSetBasePotionData.invoke(potionMeta, potionData); - } catch (IllegalAccessException | InvocationTargetException | InstantiationException | NoSuchMethodException ex) { + } catch (IllegalAccessException | InvocationTargetException | InstantiationException | + NoSuchMethodException ex) { throw new RuntimeException(ex); } } @@ -522,19 +546,21 @@ public class PotionUtil { } else { try { final Object potionData = methodPotionMetaGetBasePotionData.invoke(potionMeta); - final Object otherPotionData = methodPotionMetaGetBasePotionData.invoke(otherPotionMeta); - final PotionType potionType = (PotionType) methodPotionDataGetType.invoke(potionData); - final PotionType otherPotionType = (PotionType) methodPotionDataGetType.invoke(otherPotionData); + final Object otherPotionData = methodPotionMetaGetBasePotionData.invoke( + otherPotionMeta); + final PotionType potionType = (PotionType) methodPotionDataGetType.invoke( + potionData); + final PotionType otherPotionType = (PotionType) methodPotionDataGetType.invoke( + otherPotionData); if (potionType != otherPotionType) { return false; } - if (methodPotionDataIsExtended.invoke(potionData) != methodPotionDataIsExtended.invoke(otherPotionData)) { + if (methodPotionDataIsExtended.invoke(potionData) + != methodPotionDataIsExtended.invoke(otherPotionData)) { return false; } - if (methodPotionDataIsUpgraded.invoke(potionData) != methodPotionDataIsUpgraded.invoke(otherPotionData)) { - return false; - } - return true; + return methodPotionDataIsUpgraded.invoke(potionData) + == methodPotionDataIsUpgraded.invoke(otherPotionData); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } diff --git a/src/main/java/com/gmail/nossr50/util/TransientEntityTracker.java b/src/main/java/com/gmail/nossr50/util/TransientEntityTracker.java index fccff2664..08bbbe3a7 100644 --- a/src/main/java/com/gmail/nossr50/util/TransientEntityTracker.java +++ b/src/main/java/com/gmail/nossr50/util/TransientEntityTracker.java @@ -1,10 +1,19 @@ package com.gmail.nossr50.util; +import static java.util.stream.Collectors.toSet; + import com.gmail.nossr50.datatypes.skills.subskills.taming.CallOfTheWildType; import com.gmail.nossr50.skills.taming.TrackedTamingEntity; import com.gmail.nossr50.util.player.NotificationManager; import com.gmail.nossr50.util.skills.ParticleEffectUtils; import com.gmail.nossr50.util.text.StringUtils; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; import org.bukkit.Location; import org.bukkit.Sound; import org.bukkit.entity.LivingEntity; @@ -12,11 +21,6 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; - -import static java.util.stream.Collectors.toSet; - public class TransientEntityTracker { final @NotNull Map> playerSummonedEntityTracker; // used for fast lookups during chunk unload events @@ -28,28 +32,32 @@ public class TransientEntityTracker { } public void initPlayer(@NotNull Player player) { - playerSummonedEntityTracker.computeIfAbsent(player.getUniqueId(), __ -> ConcurrentHashMap.newKeySet()); + playerSummonedEntityTracker.computeIfAbsent(player.getUniqueId(), + __ -> ConcurrentHashMap.newKeySet()); } public void cleanupPlayer(@NotNull Player player) { cleanPlayer(player, player.getUniqueId()); } - public int getActiveSummonsForPlayerOfType(@NotNull UUID playerUUID, @NotNull CallOfTheWildType callOfTheWildType) { + public int getActiveSummonsForPlayerOfType(@NotNull UUID playerUUID, + @NotNull CallOfTheWildType callOfTheWildType) { return getTrackedEntities(playerUUID, callOfTheWildType).stream() .filter(tte -> tte.getLivingEntity().isValid()) .mapToInt(tte -> 1) .sum(); } - public void addSummon(@NotNull UUID playerUUID, @NotNull TrackedTamingEntity trackedTamingEntity) { + public void addSummon(@NotNull UUID playerUUID, + @NotNull TrackedTamingEntity trackedTamingEntity) { playerSummonedEntityTracker.computeIfAbsent(playerUUID, __ -> ConcurrentHashMap.newKeySet()) .add(trackedTamingEntity); entityLookupCache.add(trackedTamingEntity.getLivingEntity()); } - public void killSummonAndCleanMobFlags(@NotNull LivingEntity livingEntity, @Nullable Player player, - boolean timeExpired) { + public void killSummonAndCleanMobFlags(@NotNull LivingEntity livingEntity, + @Nullable Player player, + boolean timeExpired) { if (livingEntity.isValid()) { livingEntity.setHealth(0); // Should trigger entity death events livingEntity.remove(); @@ -64,10 +72,12 @@ public class TransientEntityTracker { // Inform player of summon death if (player != null && player.isOnline()) { if (timeExpired) { - NotificationManager.sendPlayerInformationChatOnly(player, "Taming.Summon.COTW.TimeExpired", + NotificationManager.sendPlayerInformationChatOnly(player, + "Taming.Summon.COTW.TimeExpired", StringUtils.getPrettyEntityTypeString(livingEntity.getType())); } else { - NotificationManager.sendPlayerInformationChatOnly(player, "Taming.Summon.COTW.Removed", + NotificationManager.sendPlayerInformationChatOnly(player, + "Taming.Summon.COTW.Removed", StringUtils.getPrettyEntityTypeString(livingEntity.getType())); } } @@ -79,11 +89,13 @@ public class TransientEntityTracker { } private @NotNull Set getTrackedEntities(@NotNull UUID playerUUID, - @NotNull CallOfTheWildType callOfTheWildType) { + @NotNull CallOfTheWildType callOfTheWildType) { final Set entities = - playerSummonedEntityTracker.computeIfAbsent(playerUUID, __ -> ConcurrentHashMap.newKeySet()); + playerSummonedEntityTracker.computeIfAbsent(playerUUID, + __ -> ConcurrentHashMap.newKeySet()); return entities.stream() - .filter(trackedTamingEntity -> trackedTamingEntity.getCallOfTheWildType() == callOfTheWildType) + .filter(trackedTamingEntity -> trackedTamingEntity.getCallOfTheWildType() + == callOfTheWildType) .collect(toSet()); } @@ -107,12 +119,13 @@ public class TransientEntityTracker { } public void killAndCleanSummon(@NotNull UUID playerUUID, @Nullable Player player, - @NotNull TrackedTamingEntity trackedTamingEntity) { + @NotNull TrackedTamingEntity trackedTamingEntity) { killSummonAndCleanMobFlags(trackedTamingEntity.getLivingEntity(), player, false); removeSummonFromTracker(playerUUID, trackedTamingEntity); } - public void removeSummonFromTracker(@NotNull UUID playerUUID, @NotNull TrackedTamingEntity trackedTamingEntity) { + public void removeSummonFromTracker(@NotNull UUID playerUUID, + @NotNull TrackedTamingEntity trackedTamingEntity) { entityLookupCache.remove(trackedTamingEntity.getLivingEntity()); if (playerSummonedEntityTracker.containsKey(playerUUID)) { @@ -131,7 +144,8 @@ public class TransientEntityTracker { // Collect matching entities without copying each set playerSummonedEntityTracker.values().forEach(trackedEntitiesPerPlayer -> trackedEntitiesPerPlayer.stream() - .filter(trackedTamingEntity -> trackedTamingEntity.getLivingEntity() == livingEntity) + .filter(trackedTamingEntity -> trackedTamingEntity.getLivingEntity() + == livingEntity) .forEach(matchingEntities::add) ); diff --git a/src/main/java/com/gmail/nossr50/util/TransientMetadataTools.java b/src/main/java/com/gmail/nossr50/util/TransientMetadataTools.java index c7f1e335a..5e9ef8a9d 100644 --- a/src/main/java/com/gmail/nossr50/util/TransientMetadataTools.java +++ b/src/main/java/com/gmail/nossr50/util/TransientMetadataTools.java @@ -1,11 +1,11 @@ package com.gmail.nossr50.util; +import static com.gmail.nossr50.util.MobMetadataUtils.removeMobFlags; + import com.gmail.nossr50.mcMMO; import org.bukkit.entity.LivingEntity; import org.jetbrains.annotations.NotNull; -import static com.gmail.nossr50.util.MobMetadataUtils.removeMobFlags; - public class TransientMetadataTools { private final mcMMO pluginRef; @@ -16,13 +16,17 @@ public class TransientMetadataTools { public void cleanLivingEntityMetadata(@NotNull LivingEntity entity) { //Since it's not written anywhere, apparently the GC won't touch objects with metadata still present on them if (entity.hasMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME)) { - entity.setCustomName(entity.getMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME).get(0).asString()); + entity.setCustomName( + entity.getMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME).get(0) + .asString()); entity.removeMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME, pluginRef); } //Involved in changing mob names to hearts if (entity.hasMetadata(MetadataConstants.METADATA_KEY_NAME_VISIBILITY)) { - entity.setCustomNameVisible(entity.getMetadata(MetadataConstants.METADATA_KEY_NAME_VISIBILITY).get(0).asBoolean()); + entity.setCustomNameVisible( + entity.getMetadata(MetadataConstants.METADATA_KEY_NAME_VISIBILITY).get(0) + .asBoolean()); entity.removeMetadata(MetadataConstants.METADATA_KEY_NAME_VISIBILITY, pluginRef); } @@ -35,7 +39,7 @@ public class TransientMetadataTools { removeMobFlags(entity); //TODO: This loop has some redundancy, this whole method needs to be rewritten - for(String key : MetadataConstants.MOB_METADATA_KEYS) { + for (String key : MetadataConstants.MOB_METADATA_KEYS) { if (entity.hasMetadata(key)) { entity.removeMetadata(key, pluginRef); } 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 ceeeef0ba..57ab7f5ce 100644 --- a/src/main/java/com/gmail/nossr50/util/adapter/BiomeAdapter.java +++ b/src/main/java/com/gmail/nossr50/util/adapter/BiomeAdapter.java @@ -1,19 +1,25 @@ package com.gmail.nossr50.util.adapter; -import org.bukkit.block.Biome; -import org.jetbrains.annotations.NotNull; - import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.util.*; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; import java.util.function.Function; +import org.bukkit.block.Biome; +import org.jetbrains.annotations.NotNull; public class BiomeAdapter { public static final Set ICE_BIOMES; - static final List knownColdBiomes = Arrays.asList("COLD_OCEAN", "DEEP_COLD_OCEAN", "ICE_SPIKES", + static final List knownColdBiomes = Arrays.asList("COLD_OCEAN", "DEEP_COLD_OCEAN", + "ICE_SPIKES", "FROZEN_PEAKS", "FROZEN_OCEAN", "FROZEN_RIVER", "DEEP_FROZEN_OCEAN", "SNOWY_TAIGA", - "OLD_GROWTH_PINE_TAIGA", "OLD_GROWTH_SPRUCE_TAIGA", "TAIGA", "SNOWY_SLOPES", "SNOWY_BEACH"); + "OLD_GROWTH_PINE_TAIGA", "OLD_GROWTH_SPRUCE_TAIGA", "TAIGA", "SNOWY_SLOPES", + "SNOWY_BEACH"); static { final Set iceBiomes = new HashSet<>(); diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/BitSetChunkStore.java b/src/main/java/com/gmail/nossr50/util/blockmeta/BitSetChunkStore.java index 2142fa81c..17e8cb0c7 100644 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/BitSetChunkStore.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/BitSetChunkStore.java @@ -1,14 +1,23 @@ package com.gmail.nossr50.util.blockmeta; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InvalidClassException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.ObjectStreamClass; +import java.io.ObjectStreamConstants; +import java.io.PushbackInputStream; +import java.io.Serializable; +import java.util.BitSet; +import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.World; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.*; -import java.util.BitSet; -import java.util.UUID; - public class BitSetChunkStore implements ChunkStore { private static final int CURRENT_VERSION = 9; private static final int MAGIC_NUMBER = 0xEA5EDEBB; @@ -102,8 +111,11 @@ public class BitSetChunkStore implements ChunkStore { } private static int coordToIndex(int x, int y, int z, int worldMin, int worldMax) { - if (x < 0 || x >= 16 || y < worldMin || y > worldMax || z < 0 || z >= 16) - throw new IndexOutOfBoundsException(String.format("x: %d y: %d z: %d World Min: %d World Max: %d", x, y, z, worldMin, worldMax)); + if (x < 0 || x >= 16 || y < worldMin || y > worldMax || z < 0 || z >= 16) { + throw new IndexOutOfBoundsException( + String.format("x: %d y: %d z: %d World Min: %d World Max: %d", x, y, z, + worldMin, worldMax)); + } int yOffset = -worldMin; // Ensures y multiplier remains positive return (z * 16 + x) + (256 * (y + yOffset)); } @@ -112,8 +124,9 @@ public class BitSetChunkStore implements ChunkStore { World world = Bukkit.getWorld(worldUid); // Not sure how this case could come up, but might as well handle it gracefully. Loading a chunkstore for an unloaded world? - if (world == null) + if (world == null) { throw new RuntimeException("Cannot grab a minimum world height for an unloaded world"); + } return world.getMinHeight(); } @@ -122,8 +135,9 @@ public class BitSetChunkStore implements ChunkStore { World world = Bukkit.getWorld(worldUid); // Not sure how this case could come up, but might as well handle it gracefully. Loading a chunkstore for an unloaded world? - if (world == null) + if (world == null) { throw new RuntimeException("Cannot grab a maximum world height for an unloaded world"); + } return world.getMaxHeight(); } @@ -147,13 +161,15 @@ public class BitSetChunkStore implements ChunkStore { dirty = false; } - private static @NotNull BitSetChunkStore deserialize(@NotNull DataInputStream in) throws IOException { + private static @NotNull BitSetChunkStore deserialize(@NotNull DataInputStream in) + throws IOException { int magic = in.readInt(); // Can be used to determine the format of the file int fileVersionNumber = in.readInt(); - if (magic != MAGIC_NUMBER || fileVersionNumber < 8) + if (magic != MAGIC_NUMBER || fileVersionNumber < 8) { throw new IOException(); + } long lsb = in.readLong(); long msb = in.readLong(); @@ -162,8 +178,9 @@ public class BitSetChunkStore implements ChunkStore { int cz = in.readInt(); int worldMin = 0; - if (fileVersionNumber >= 9) + if (fileVersionNumber >= 9) { worldMin = in.readInt(); + } int worldMax = in.readInt(); byte[] temp = new byte[in.readInt()]; in.readFully(temp); @@ -174,22 +191,29 @@ public class BitSetChunkStore implements ChunkStore { // The order in which the world height update code occurs here is important, the world max truncate math only holds up if done before adjusting for min changes // Lop off extra data if world max has shrunk - if (currentWorldMax < worldMax) - stored.clear(coordToIndex(16, currentWorldMax, 16, worldMin, worldMax), stored.length()); + if (currentWorldMax < worldMax) { + stored.clear(coordToIndex(16, currentWorldMax, 16, worldMin, worldMax), + stored.length()); + } // Left shift store if world min has shrunk - if (currentWorldMin > worldMin) - stored = stored.get(currentWorldMin, stored.length()); // Because BitSet's aren't fixed size, a "substring" operation is equivalent to a left shift + if (currentWorldMin > worldMin) { + stored = stored.get(currentWorldMin, + stored.length()); // Because BitSet's aren't fixed size, a "substring" operation is equivalent to a left shift + } // Right shift store if world min has expanded if (currentWorldMin < worldMin) { - int offset = (worldMin - currentWorldMin) * 16 * 16; // We are adding this many bits to the front + int offset = (worldMin - currentWorldMin) * 16 + * 16; // We are adding this many bits to the front // This isn't the most efficient way to do this, however, its a rare case to occur, and in the grand scheme of things, the small performance we could gain would cost us significant reduced readability of the code BitSet shifted = new BitSet(); - for (int i = 0; i < stored.length(); i++) + for (int i = 0; i < stored.length(); i++) { shifted.set(i + offset, stored.get(i)); + } stored = shifted; } - BitSetChunkStore chunkStore = new BitSetChunkStore(worldUid, currentWorldMin, currentWorldMax, cx, cz); + BitSetChunkStore chunkStore = new BitSetChunkStore(worldUid, currentWorldMin, + currentWorldMax, cx, cz); chunkStore.store.or(stored); chunkStore.dirty = currentWorldMin != worldMin || currentWorldMax != worldMax; @@ -198,11 +222,13 @@ public class BitSetChunkStore implements ChunkStore { public static class Serialization { - public static final short STREAM_MAGIC = (short)0xACDC; // Rock on + public static final short STREAM_MAGIC = (short) 0xACDC; // Rock on - public static @Nullable ChunkStore readChunkStore(@NotNull DataInputStream inputStream) throws IOException { - if (inputStream.markSupported()) + public static @Nullable ChunkStore readChunkStore(@NotNull DataInputStream inputStream) + throws IOException { + if (inputStream.markSupported()) { inputStream.mark(2); + } short magicNumber = inputStream.readShort(); // Java serializable, use legacy serialization @@ -212,7 +238,8 @@ public class BitSetChunkStore implements ChunkStore { inputStream.reset(); // Pretend we never read those bytes } else { // Creates a new stream with the two magic number bytes and then the rest of the original stream... Java is so dumb. I just wanted to look at two bytes. - PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream, 2); + PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream, + 2); pushbackInputStream.unread((magicNumber) & 0xFF); pushbackInputStream.unread((magicNumber >>> 8) & 0xFF); inputStream = new DataInputStream(pushbackInputStream); @@ -225,11 +252,13 @@ public class BitSetChunkStore implements ChunkStore { throw new IOException("Bad Data Format"); } - public static void writeChunkStore(@NotNull DataOutputStream outputStream, @NotNull ChunkStore chunkStore) throws IOException { - if (!(chunkStore instanceof BitSetChunkStore)) + public static void writeChunkStore(@NotNull DataOutputStream outputStream, + @NotNull ChunkStore chunkStore) throws IOException { + if (!(chunkStore instanceof BitSetChunkStore)) { throw new InvalidClassException("ChunkStore must be instance of BitSetChunkStore"); + } outputStream.writeShort(STREAM_MAGIC); - ((BitSetChunkStore)chunkStore).serialize(outputStream); + ((BitSetChunkStore) chunkStore).serialize(outputStream); } // Handles loading the old serialized class @@ -243,7 +272,8 @@ public class BitSetChunkStore implements ChunkStore { private UUID worldUid; private boolean[][][] store; - private LegacyChunkStoreDeserializer() {} + private LegacyChunkStoreDeserializer() { + } @Deprecated private void writeObject(@NotNull ObjectOutputStream out) throws IOException { @@ -251,7 +281,8 @@ public class BitSetChunkStore implements ChunkStore { } @Deprecated - private void readObject(@NotNull ObjectInputStream in) throws IOException, ClassNotFoundException { + private void readObject(@NotNull ObjectInputStream in) + throws IOException, ClassNotFoundException { in.readInt(); // Magic number in.readInt(); // Format version long lsb = in.readLong(); @@ -269,13 +300,15 @@ public class BitSetChunkStore implements ChunkStore { int currentWorldMin = getWorldMin(worldUid); int currentWorldMax = getWorldMax(worldUid); - BitSetChunkStore converted = new BitSetChunkStore(worldUid, currentWorldMin, currentWorldMax, cx, cz); + BitSetChunkStore converted = new BitSetChunkStore(worldUid, currentWorldMin, + currentWorldMax, cx, cz); // Read old data into new chunkstore for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { for (int y = 0; y < worldMax && y < currentWorldMax; y++) { - converted.store.set(converted.coordToIndex(x, y, z), store[x][z][y]); + converted.store.set(converted.coordToIndex(x, y, z), + store[x][z][y]); } } } @@ -292,16 +325,19 @@ public class BitSetChunkStore implements ChunkStore { } @Override - protected @NotNull ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException { + protected @NotNull ObjectStreamClass readClassDescriptor() + throws IOException, ClassNotFoundException { ObjectStreamClass read = super.readClassDescriptor(); - if (read.getName().contentEquals("com.gmail.nossr50.util.blockmeta.chunkmeta.PrimitiveChunkStore")) + if (read.getName().contentEquals( + "com.gmail.nossr50.util.blockmeta.chunkmeta.PrimitiveChunkStore")) { return ObjectStreamClass.lookup(LegacyChunkStoreDeserializer.class); + } return read; } - public @Nullable ChunkStore readLegacyChunkStore(){ + public @Nullable ChunkStore readLegacyChunkStore() { try { - LegacyChunkStoreDeserializer deserializer = (LegacyChunkStoreDeserializer)readObject(); + LegacyChunkStoreDeserializer deserializer = (LegacyChunkStoreDeserializer) readObject(); return deserializer.convert(); } catch (IOException | ClassNotFoundException e) { return null; diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/ChunkManager.java b/src/main/java/com/gmail/nossr50/util/blockmeta/ChunkManager.java index a0b61ba6f..c695b5673 100644 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/ChunkManager.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/ChunkManager.java @@ -5,6 +5,8 @@ import org.jetbrains.annotations.NotNull; public interface ChunkManager extends UserBlockTracker { void closeAll(); + void chunkUnloaded(int cx, int cz, @NotNull World world); + void unloadWorld(@NotNull World world); } diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/ChunkStore.java b/src/main/java/com/gmail/nossr50/util/blockmeta/ChunkStore.java index 632cde2e2..f0d194d45 100644 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/ChunkStore.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/ChunkStore.java @@ -1,8 +1,7 @@ package com.gmail.nossr50.util.blockmeta; -import org.jetbrains.annotations.NotNull; - import java.util.UUID; +import org.jetbrains.annotations.NotNull; /** * A ChunkStore should be responsible for a 16x16xWorldHeight area of data @@ -37,6 +36,7 @@ public interface ChunkStore { int getChunkZ(); int getChunkMin(); + int getChunkMax(); @NotNull UUID getWorldId(); diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/HashChunkManager.java b/src/main/java/com/gmail/nossr50/util/blockmeta/HashChunkManager.java index 5d860e0e3..d25beacc0 100644 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/HashChunkManager.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/HashChunkManager.java @@ -1,5 +1,15 @@ package com.gmail.nossr50.util.blockmeta; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.block.Block; @@ -7,12 +17,6 @@ import org.bukkit.block.BlockState; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.IOException; -import java.util.*; - public class HashChunkManager implements ChunkManager { private final HashMap regionMap = new HashMap<>(); // Tracks active regions private final HashMap> chunkUsageMap = new HashMap<>(); // Tracks active chunks by region @@ -22,47 +26,56 @@ public class HashChunkManager implements ChunkManager { public synchronized void closeAll() { // Save all dirty chunkstores for (ChunkStore chunkStore : chunkMap.values()) { - if (!chunkStore.isDirty()) + if (!chunkStore.isDirty()) { continue; + } World world = Bukkit.getWorld(chunkStore.getWorldId()); - if (world == null) + if (world == null) { continue; // Oh well + } writeChunkStore(world, chunkStore); } // Clear in memory chunks chunkMap.clear(); chunkUsageMap.clear(); // Close all region files - for (McMMOSimpleRegionFile rf : regionMap.values()) + for (McMMOSimpleRegionFile rf : regionMap.values()) { rf.close(); + } regionMap.clear(); } - private synchronized @Nullable ChunkStore readChunkStore(@NotNull World world, int cx, int cz) throws IOException { + private synchronized @Nullable ChunkStore readChunkStore(@NotNull World world, int cx, int cz) + throws IOException { final McMMOSimpleRegionFile rf = getWriteableSimpleRegionFile(world, cx, cz); try (DataInputStream in = rf.getInputStream(cx, cz)) { // Get input stream for chunk - if (in == null) + if (in == null) { return null; // No chunk + } return BitSetChunkStore.Serialization.readChunkStore(in); // Read in the chunkstore } } private synchronized void writeChunkStore(@NotNull World world, @NotNull ChunkStore data) { - if (!data.isDirty()) + if (!data.isDirty()) { return; // Don't save unchanged data + } try { - McMMOSimpleRegionFile rf = getWriteableSimpleRegionFile(world, data.getChunkX(), data.getChunkZ()); + McMMOSimpleRegionFile rf = getWriteableSimpleRegionFile(world, data.getChunkX(), + data.getChunkZ()); try (DataOutputStream out = rf.getOutputStream(data.getChunkX(), data.getChunkZ())) { BitSetChunkStore.Serialization.writeChunkStore(out, data); } data.setDirty(false); - } - catch (IOException e) { - throw new RuntimeException("Unable to write chunk meta data for " + data.getChunkX() + ", " + data.getChunkZ(), e); + } catch (IOException e) { + throw new RuntimeException( + "Unable to write chunk meta data for " + data.getChunkX() + ", " + + data.getChunkZ(), e); } } - private synchronized @NotNull McMMOSimpleRegionFile getWriteableSimpleRegionFile(@NotNull World world, int cx, int cz) { + private synchronized @NotNull McMMOSimpleRegionFile getWriteableSimpleRegionFile( + @NotNull World world, int cx, int cz) { CoordinateKey regionKey = toRegionKey(world.getUID(), cx, cz); return regionMap.computeIfAbsent(regionKey, k -> { @@ -73,16 +86,18 @@ public class HashChunkManager implements ChunkManager { } private @NotNull File getRegionFile(@NotNull World world, @NotNull CoordinateKey regionKey) { - if (world.getUID() != regionKey.worldID) + if (world.getUID() != regionKey.worldID) { throw new IllegalArgumentException(); - return new File(new File(world.getWorldFolder(), "mcmmo_regions"), "mcmmo_" + regionKey.x + "_" + regionKey.z + "_.mcm"); + } + return new File(new File(world.getWorldFolder(), "mcmmo_regions"), + "mcmmo_" + regionKey.x + "_" + regionKey.z + "_.mcm"); } private @Nullable ChunkStore loadChunk(int cx, int cz, @NotNull World world) { try { return readChunkStore(world, cx, cz); + } catch (Exception ignored) { } - catch (Exception ignored) {} return null; } @@ -90,11 +105,13 @@ public class HashChunkManager implements ChunkManager { private void unloadChunk(int cx, int cz, @NotNull World world) { CoordinateKey chunkKey = toChunkKey(world.getUID(), cx, cz); ChunkStore chunkStore = chunkMap.remove(chunkKey); // Remove from chunk map - if (chunkStore == null) + if (chunkStore == null) { return; + } - if (chunkStore.isDirty()) + if (chunkStore.isDirty()) { writeChunkStore(world, chunkStore); + } CoordinateKey regionKey = toRegionKey(world.getUID(), cx, cz); HashSet chunkKeys = chunkUsageMap.get(regionKey); @@ -118,21 +135,24 @@ public class HashChunkManager implements ChunkManager { // Save and remove all the chunks List chunkKeys = new ArrayList<>(chunkMap.keySet()); for (CoordinateKey chunkKey : chunkKeys) { - if (!wID.equals(chunkKey.worldID)) + if (!wID.equals(chunkKey.worldID)) { continue; + } ChunkStore chunkStore = chunkMap.remove(chunkKey); - if (!chunkStore.isDirty()) + if (!chunkStore.isDirty()) { continue; + } try { writeChunkStore(world, chunkStore); + } catch (Exception ignore) { } - catch (Exception ignore) { } } // Clear all the region files List regionKeys = new ArrayList<>(regionMap.keySet()); for (CoordinateKey regionKey : regionKeys) { - if (!wID.equals(regionKey.worldID)) + if (!wID.equals(regionKey.worldID)) { continue; + } regionMap.remove(regionKey).close(); chunkUsageMap.remove(regionKey); } @@ -147,11 +167,13 @@ public class HashChunkManager implements ChunkManager { // Load from file ChunkStore loaded = loadChunk(chunkKey.x, chunkKey.z, world); if (loaded != null) { - chunkUsageMap.computeIfAbsent(toRegionKey(chunkKey.worldID, chunkKey.x, chunkKey.z), j -> new HashSet<>()).add(chunkKey); + chunkUsageMap.computeIfAbsent(toRegionKey(chunkKey.worldID, chunkKey.x, chunkKey.z), + j -> new HashSet<>()).add(chunkKey); return loaded; } // Mark chunk in-use for region tracking - chunkUsageMap.computeIfAbsent(toRegionKey(chunkKey.worldID, chunkKey.x, chunkKey.z), j -> new HashSet<>()).add(chunkKey); + chunkUsageMap.computeIfAbsent(toRegionKey(chunkKey.worldID, chunkKey.x, chunkKey.z), + j -> new HashSet<>()).add(chunkKey); // Create a new chunkstore return new BitSetChunkStore(world, chunkKey.x, chunkKey.z); }); @@ -169,7 +191,8 @@ public class HashChunkManager implements ChunkManager { @Override public synchronized boolean isIneligible(@NotNull BlockState blockState) { - return isIneligible(blockState.getX(), blockState.getY(), blockState.getZ(), blockState.getWorld()); + return isIneligible(blockState.getX(), blockState.getY(), blockState.getZ(), + blockState.getWorld()); } @Override @@ -202,7 +225,7 @@ public class HashChunkManager implements ChunkManager { set(blockState.getX(), blockState.getY(), blockState.getZ(), blockState.getWorld(), false); } - private synchronized void set(int x, int y, int z, @NotNull World world, boolean value){ + private synchronized void set(int x, int y, int z, @NotNull World world, boolean value) { CoordinateKey chunkKey = blockCoordinateToChunkKey(world.getUID(), x, y, z); // Get/Load/Create chunkstore @@ -210,11 +233,13 @@ public class HashChunkManager implements ChunkManager { // Load from file ChunkStore loaded = loadChunk(chunkKey.x, chunkKey.z, world); if (loaded != null) { - chunkUsageMap.computeIfAbsent(toRegionKey(chunkKey.worldID, chunkKey.x, chunkKey.z), j -> new HashSet<>()).add(chunkKey); + chunkUsageMap.computeIfAbsent(toRegionKey(chunkKey.worldID, chunkKey.x, chunkKey.z), + j -> new HashSet<>()).add(chunkKey); return loaded; } // Mark chunk in-use for region tracking - chunkUsageMap.computeIfAbsent(toRegionKey(chunkKey.worldID, chunkKey.x, chunkKey.z), j -> new HashSet<>()).add(chunkKey); + chunkUsageMap.computeIfAbsent(toRegionKey(chunkKey.worldID, chunkKey.x, chunkKey.z), + j -> new HashSet<>()).add(chunkKey); // Create a new chunkstore return new BitSetChunkStore(world, chunkKey.x, chunkKey.z); }); @@ -227,11 +252,12 @@ public class HashChunkManager implements ChunkManager { cStore.set(ix, y, iz, value); } - private @NotNull CoordinateKey blockCoordinateToChunkKey(@NotNull UUID worldUid, int x, int y, int z) { + private @NotNull CoordinateKey blockCoordinateToChunkKey(@NotNull UUID worldUid, int x, int y, + int z) { return toChunkKey(worldUid, x >> 4, z >> 4); } - private @NotNull CoordinateKey toChunkKey(@NotNull UUID worldUid, int cx, int cz){ + private @NotNull CoordinateKey toChunkKey(@NotNull UUID worldUid, int cx, int cz) { return new CoordinateKey(worldUid, cx, cz); } @@ -255,8 +281,12 @@ public class HashChunkManager implements ChunkManager { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } CoordinateKey coordinateKey = (CoordinateKey) o; return x == coordinateKey.x && z == coordinateKey.z && diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/McMMOSimpleRegionFile.java b/src/main/java/com/gmail/nossr50/util/blockmeta/McMMOSimpleRegionFile.java index 1e5f860fa..065ae70b4 100644 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/McMMOSimpleRegionFile.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/McMMOSimpleRegionFile.java @@ -19,26 +19,30 @@ */ package com.gmail.nossr50.util.blockmeta; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.io.*; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; import java.util.BitSet; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; /** - * File format: - * bytes 0-4096 contain 1024 integer values representing the segment index of each chunk - * bytes 4096-8192 contain 1024 integer values representing the byte length of each chunk - * bytes 8192-8196 is the integer value of the segment exponent - * bytes 8196-12288 are reserved for future use - * bytes 12288+ contain the data segments, by default 1024 byte segments. - * Chunk data is compressed and stored in 1 or more segments as needed. + * File format: bytes 0-4096 contain 1024 integer values representing the segment index of each + * chunk bytes 4096-8192 contain 1024 integer values representing the byte length of each chunk + * bytes 8192-8196 is the integer value of the segment exponent bytes 8196-12288 are reserved for + * future use bytes 12288+ contain the data segments, by default 1024 byte segments. Chunk data is + * compressed and stored in 1 or more segments as needed. */ public class McMMOSimpleRegionFile { private static final int DEFAULT_SEGMENT_EXPONENT = 10; // TODO, analyze real world usage and determine if a smaller segment(512) is worth it or not. (need to know average chunkstore bytesize) - private static final int DEFAULT_SEGMENT_SIZE = (int)Math.pow(2, DEFAULT_SEGMENT_EXPONENT); // 1024 + private static final int DEFAULT_SEGMENT_SIZE = (int) Math.pow(2, + DEFAULT_SEGMENT_EXPONENT); // 1024 private static final int RESERVED_HEADER_BYTES = 12288; // This needs to be divisible by segment size private static final int NUM_CHUNKS = 1024; // 32x32 private static final int SEEK_CHUNK_SEGMENT_INDICES = 0; @@ -90,8 +94,9 @@ public class McMMOSimpleRegionFile { // Read chunk header data file.seek(SEEK_CHUNK_SEGMENT_INDICES); - for (int i = 0; i < NUM_CHUNKS; i++) + for (int i = 0; i < NUM_CHUNKS; i++) { chunkSegmentIndex[i] = file.readInt(); + } file.seek(SEEK_CHUNK_BYTE_LENGTHS); for (int i = 0; i < NUM_CHUNKS; i++) { @@ -101,15 +106,15 @@ public class McMMOSimpleRegionFile { } fixFileLength(); - } - catch (IOException fnfe) { + } catch (IOException fnfe) { throw new RuntimeException(fnfe); } } public synchronized @NotNull DataOutputStream getOutputStream(int x, int z) { int index = getChunkIndex(x, z); // Get chunk index - return new DataOutputStream(new DeflaterOutputStream(new McMMOSimpleChunkBuffer(this, index))); + return new DataOutputStream( + new DeflaterOutputStream(new McMMOSimpleChunkBuffer(this, index))); } private static class McMMOSimpleChunkBuffer extends ByteArrayOutputStream { @@ -131,7 +136,8 @@ public class McMMOSimpleRegionFile { private synchronized void write(int index, byte[] buffer, int size) throws IOException { int oldSegmentIndex = chunkSegmentIndex[index]; // Get current segment index markChunkSegments(index, false); // Clear our old segments - int newSegmentIndex = findContiguousSegments(oldSegmentIndex, size); // Find contiguous segments to save to + int newSegmentIndex = findContiguousSegments(oldSegmentIndex, + size); // Find contiguous segments to save to file.seek((long) newSegmentIndex << segmentExponent); // Seek to file location file.write(buffer, 0, size); // Write data // update in memory info @@ -152,8 +158,9 @@ public class McMMOSimpleRegionFile { int byteLength = chunkNumBytes[index]; // Get byte length of data // No bytes - if (byteLength == 0) + if (byteLength == 0) { return null; + } byte[] data = new byte[byteLength]; @@ -166,16 +173,16 @@ public class McMMOSimpleRegionFile { try { file.close(); segments.clear(); - } - catch (IOException ioe) { + } catch (IOException ioe) { throw new RuntimeException("Unable to close file", ioe); } } private synchronized void markChunkSegments(int index, boolean inUse) { // No bytes used - if (chunkNumBytes[index] == 0) + if (chunkNumBytes[index] == 0) { return; + } int start = chunkSegmentIndex[index]; int end = start + chunkNumSegments[index]; @@ -183,16 +190,18 @@ public class McMMOSimpleRegionFile { // If we are writing, assert we don't write over any in-use segments if (inUse) { int nextSetBit = segments.nextSetBit(start); - if (nextSetBit != -1 && nextSetBit < end) + if (nextSetBit != -1 && nextSetBit < end) { throw new IllegalStateException("Attempting to overwrite an in-use segment"); + } } segments.set(start, end, inUse); } private synchronized void fixFileLength() throws IOException { - int fileLength = (int)file.length(); - int extend = -fileLength & segmentMask; // how many bytes do we need to be divisible by segment size + int fileLength = (int) file.length(); + int extend = -fileLength + & segmentMask; // how many bytes do we need to be divisible by segment size // Go to end of file file.seek(fileLength); @@ -201,8 +210,9 @@ public class McMMOSimpleRegionFile { } private synchronized int findContiguousSegments(int hint, int size) { - if (size == 0) + if (size == 0) { return 0; // Zero byte data will not claim any chunks anyways + } int segments = bytesToSegments(size); // Number of segments we need @@ -216,8 +226,9 @@ public class McMMOSimpleRegionFile { } // We fit! - if (oldFree) + if (oldFree) { return hint; + } // Find somewhere to put us int start = 0; @@ -228,12 +239,14 @@ public class McMMOSimpleRegionFile { current++; // Move up a segment // Move up start if the segment was in use - if (segmentInUse) + if (segmentInUse) { start = current; + } // If we have enough segments now, return - if (current - start >= segments) + if (current - start >= segments) { return start; + } } // Return the end of the segments (will expand to fit them) @@ -241,15 +254,17 @@ public class McMMOSimpleRegionFile { } private synchronized int bytesToSegments(int bytes) { - if (bytes <= 0) + if (bytes <= 0) { return 1; + } return ((bytes - 1) >> segmentExponent) + 1; // ((bytes - 1) / segmentSize) + 1 } private synchronized int getChunkIndex(int x, int z) { - if (rx != (x >> 5) || rz != (z >> 5)) + if (rx != (x >> 5) || rz != (z >> 5)) { throw new IndexOutOfBoundsException(); + } x = x & 0x1F; // 5 bits (mod 32) z = z & 0x1F; // 5 bits (mod 32) diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/NullChunkManager.java b/src/main/java/com/gmail/nossr50/util/blockmeta/NullChunkManager.java index f972b934a..e1d638ed9 100644 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/NullChunkManager.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/NullChunkManager.java @@ -8,13 +8,16 @@ import org.jetbrains.annotations.NotNull; public class NullChunkManager implements ChunkManager { @Override - public void closeAll() {} + public void closeAll() { + } @Override - public void chunkUnloaded(int cx, int cz, @NotNull World world) {} + public void chunkUnloaded(int cx, int cz, @NotNull World world) { + } @Override - public void unloadWorld(@NotNull World world) {} + public void unloadWorld(@NotNull World world) { + } @Override public boolean isIneligible(@NotNull Block block) { @@ -37,14 +40,18 @@ public class NullChunkManager implements ChunkManager { } @Override - public void setIneligible(@NotNull Block block) {} + public void setIneligible(@NotNull Block block) { + } @Override - public void setIneligible(@NotNull BlockState blockState) {} + public void setIneligible(@NotNull BlockState blockState) { + } @Override - public void setEligible(@NotNull Block block) {} + public void setEligible(@NotNull Block block) { + } @Override - public void setEligible(@NotNull BlockState blockState) {} + public void setEligible(@NotNull BlockState blockState) { + } } diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/UserBlockTracker.java b/src/main/java/com/gmail/nossr50/util/blockmeta/UserBlockTracker.java index 8979e9125..01d9c8baa 100644 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/UserBlockTracker.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/UserBlockTracker.java @@ -6,13 +6,13 @@ import org.bukkit.block.BlockState; import org.jetbrains.annotations.NotNull; /** - * Contains blockstore methods that are safe for external plugins to access. - * An instance can be retrieved via {@link mcMMO#getUserBlockTracker() mcMMO.getPlaceStore()} + * Contains blockstore methods that are safe for external plugins to access. An instance can be + * retrieved via {@link mcMMO#getUserBlockTracker() mcMMO.getPlaceStore()} */ public interface UserBlockTracker { /** - * Check to see if a given {@link Block} is ineligible for rewards. - * This is a location-based lookup, and the other properties of the {@link Block} do not matter. + * Check to see if a given {@link Block} is ineligible for rewards. This is a location-based + * lookup, and the other properties of the {@link Block} do not matter. * * @param block Block to check * @return true if the given block should not give rewards, false if otherwise @@ -20,8 +20,8 @@ public interface UserBlockTracker { boolean isIneligible(@NotNull Block block); /** - * Check to see if a given {@link Block} is eligible for rewards. - * This is a location-based lookup, and the other properties of the {@link Block} do not matter. + * Check to see if a given {@link Block} is eligible for rewards. This is a location-based + * lookup, and the other properties of the {@link Block} do not matter. * * @param block Block to check * @return true if the given block should give rewards, false if otherwise @@ -29,8 +29,8 @@ public interface UserBlockTracker { boolean isEligible(@NotNull Block block); /** - * Check to see if a given {@link BlockState} is eligible for rewards. - * This is a location-based lookup, and the other properties of the {@link BlockState} do not matter. + * Check to see if a given {@link BlockState} is eligible for rewards. This is a location-based + * lookup, and the other properties of the {@link BlockState} do not matter. * * @param blockState BlockState to check * @return true if the given BlockState location is set to true, false if otherwise @@ -38,8 +38,8 @@ public interface UserBlockTracker { boolean isEligible(@NotNull BlockState blockState); /** - * Check to see if a given {@link BlockState} is ineligible for rewards. - * This is a location-based lookup, and the other properties of the {@link BlockState} do not matter. + * Check to see if a given {@link BlockState} is ineligible for rewards. This is a + * location-based lookup, and the other properties of the {@link BlockState} do not matter. * * @param blockState BlockState to check * @return true if the given BlockState location is set to true, false if otherwise @@ -47,8 +47,8 @@ public interface UserBlockTracker { boolean isIneligible(@NotNull BlockState blockState); /** - * Set a given {@link Block} as ineligible for rewards. - * This is a location-based lookup, and the other properties of the {@link Block} do not matter. + * Set a given {@link Block} as ineligible for rewards. This is a location-based lookup, and the + * other properties of the {@link Block} do not matter. * * @param block block whose location to set as ineligible */ @@ -62,8 +62,8 @@ public interface UserBlockTracker { void setIneligible(@NotNull BlockState blockState); /** - * Set a given {@link Block} as eligible for rewards. - * This is a location-based lookup, and the other properties of the {@link Block} do not matter. + * Set a given {@link Block} as eligible for rewards. This is a location-based lookup, and the + * other properties of the {@link Block} do not matter. * * @param block block whose location to set as eligible */ 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 15faa6df6..224aed5ec 100644 --- a/src/main/java/com/gmail/nossr50/util/commands/CommandRegistrationManager.java +++ b/src/main/java/com/gmail/nossr50/util/commands/CommandRegistrationManager.java @@ -1,6 +1,13 @@ package com.gmail.nossr50.util.commands; -import com.gmail.nossr50.commands.*; +import com.gmail.nossr50.commands.McabilityCommand; +import com.gmail.nossr50.commands.McconvertCommand; +import com.gmail.nossr50.commands.McgodCommand; +import com.gmail.nossr50.commands.McmmoCommand; +import com.gmail.nossr50.commands.McnotifyCommand; +import com.gmail.nossr50.commands.McrefreshCommand; +import com.gmail.nossr50.commands.McscoreboardCommand; +import com.gmail.nossr50.commands.XprateCommand; import com.gmail.nossr50.commands.admin.CompatibilityCommand; import com.gmail.nossr50.commands.admin.McmmoReloadLocaleCommand; import com.gmail.nossr50.commands.admin.PlayerDebugCommand; @@ -14,32 +21,57 @@ import com.gmail.nossr50.commands.experience.MmoeditCommand; import com.gmail.nossr50.commands.experience.SkillresetCommand; import com.gmail.nossr50.commands.party.PartyCommand; import com.gmail.nossr50.commands.party.teleport.PtpCommand; -import com.gmail.nossr50.commands.player.*; -import com.gmail.nossr50.commands.skills.*; +import com.gmail.nossr50.commands.player.InspectCommand; +import com.gmail.nossr50.commands.player.McRankCommand; +import com.gmail.nossr50.commands.player.McTopCommand; +import com.gmail.nossr50.commands.player.MccooldownCommand; +import com.gmail.nossr50.commands.player.McstatsCommand; +import com.gmail.nossr50.commands.player.XPBarCommand; +import com.gmail.nossr50.commands.skills.AcrobaticsCommand; +import com.gmail.nossr50.commands.skills.AlchemyCommand; +import com.gmail.nossr50.commands.skills.ArcheryCommand; +import com.gmail.nossr50.commands.skills.AxesCommand; +import com.gmail.nossr50.commands.skills.CrossbowsCommand; +import com.gmail.nossr50.commands.skills.ExcavationCommand; +import com.gmail.nossr50.commands.skills.FishingCommand; +import com.gmail.nossr50.commands.skills.HerbalismCommand; +import com.gmail.nossr50.commands.skills.MacesCommand; +import com.gmail.nossr50.commands.skills.MiningCommand; +import com.gmail.nossr50.commands.skills.MmoInfoCommand; +import com.gmail.nossr50.commands.skills.RepairCommand; +import com.gmail.nossr50.commands.skills.SalvageCommand; +import com.gmail.nossr50.commands.skills.SmeltingCommand; +import com.gmail.nossr50.commands.skills.SwordsCommand; +import com.gmail.nossr50.commands.skills.TamingCommand; +import com.gmail.nossr50.commands.skills.TridentsCommand; +import com.gmail.nossr50.commands.skills.UnarmedCommand; +import com.gmail.nossr50.commands.skills.WoodcuttingCommand; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.text.StringUtils; -import org.bukkit.command.PluginCommand; - import java.util.ArrayList; import java.util.List; import java.util.Locale; +import org.bukkit.command.PluginCommand; public final class CommandRegistrationManager { - private CommandRegistrationManager() {} + private CommandRegistrationManager() { + } private static final String permissionsMessage = LocaleLoader.getString("mcMMO.NoPermission"); private static void registerSkillCommands() { for (PrimarySkillType primarySkillType : PrimarySkillType.values()) { if (primarySkillType == PrimarySkillType.MACES - && !mcMMO.getCompatibilityManager().getMinecraftGameVersion().isAtLeast(1, 21, 0)) { + && !mcMMO.getCompatibilityManager().getMinecraftGameVersion() + .isAtLeast(1, 21, 0)) { continue; } final String commandName = primarySkillType.toString().toLowerCase(Locale.ENGLISH); - final String localizedName = mcMMO.p.getSkillTools().getLocalizedSkillName(primarySkillType).toLowerCase(Locale.ENGLISH); + final String localizedName = mcMMO.p.getSkillTools() + .getLocalizedSkillName(primarySkillType).toLowerCase(Locale.ENGLISH); final PluginCommand command = mcMMO.p.getCommand(commandName); if (command == null) { @@ -47,11 +79,13 @@ public final class CommandRegistrationManager { continue; } - command.setDescription(LocaleLoader.getString("Commands.Description.Skill", StringUtils.getCapitalized(localizedName))); + command.setDescription(LocaleLoader.getString("Commands.Description.Skill", + StringUtils.getCapitalized(localizedName))); command.setPermission("mcmmo.commands." + commandName); command.setPermissionMessage(permissionsMessage); command.setUsage(LocaleLoader.getString("Commands.Usage.0", commandName)); - command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.2", commandName, "?", "[" + LocaleLoader.getString("Commands.Usage.Page") + "]")); + command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.2", + commandName, "?", "[" + LocaleLoader.getString("Commands.Usage.Page") + "]")); switch (primarySkillType) { case ACROBATICS -> command.setExecutor(new AcrobaticsCommand()); @@ -82,7 +116,10 @@ public final class CommandRegistrationManager { command.setDescription(LocaleLoader.getString("Commands.Description.addlevels")); command.setPermission("mcmmo.commands.addlevels;mcmmo.commands.addlevels.others"); command.setPermissionMessage(permissionsMessage); - command.setUsage(LocaleLoader.getString("Commands.Usage.3.XP", "addlevels", "[" + LocaleLoader.getString("Commands.Usage.Player") + "]", "<" + LocaleLoader.getString("Commands.Usage.Skill") + ">", "<" + LocaleLoader.getString("Commands.Usage.Level") + ">")); + command.setUsage(LocaleLoader.getString("Commands.Usage.3.XP", "addlevels", + "[" + LocaleLoader.getString("Commands.Usage.Player") + "]", + "<" + LocaleLoader.getString("Commands.Usage.Skill") + ">", + "<" + LocaleLoader.getString("Commands.Usage.Level") + ">")); command.setExecutor(new AddlevelsCommand()); } @@ -91,7 +128,10 @@ public final class CommandRegistrationManager { command.setDescription(LocaleLoader.getString("Commands.Description.addxp")); command.setPermission("mcmmo.commands.addxp;mcmmo.commands.addxp.others"); command.setPermissionMessage(permissionsMessage); - command.setUsage(LocaleLoader.getString("Commands.Usage.3.XP", "addxp", "[" + LocaleLoader.getString("Commands.Usage.Player") + "]", "<" + LocaleLoader.getString("Commands.Usage.Skill") + ">", "<" + LocaleLoader.getString("Commands.Usage.XP") + ">")); + command.setUsage(LocaleLoader.getString("Commands.Usage.3.XP", "addxp", + "[" + LocaleLoader.getString("Commands.Usage.Player") + "]", + "<" + LocaleLoader.getString("Commands.Usage.Skill") + ">", + "<" + LocaleLoader.getString("Commands.Usage.XP") + ">")); command.setExecutor(new AddxpCommand()); } @@ -100,7 +140,8 @@ public final class CommandRegistrationManager { command.setDescription(LocaleLoader.getString("Commands.Description.mcgod")); command.setPermission("mcmmo.commands.mcgod;mcmmo.commands.mcgod.others"); command.setPermissionMessage(permissionsMessage); - command.setUsage(LocaleLoader.getString("Commands.Usage.1", "mcgod", "[" + LocaleLoader.getString("Commands.Usage.Player") + "]")); + command.setUsage(LocaleLoader.getString("Commands.Usage.1", "mcgod", + "[" + LocaleLoader.getString("Commands.Usage.Player") + "]")); command.setExecutor(new McgodCommand()); } @@ -109,7 +150,8 @@ public final class CommandRegistrationManager { command.setDescription(LocaleLoader.getString("Commands.Description.mmoinfo")); command.setPermission("mcmmo.commands.mmoinfo"); command.setPermissionMessage(permissionsMessage); - command.setUsage(LocaleLoader.getString("Commands.Usage.1", "mmoinfo", "[" + LocaleLoader.getString("Commands.Usage.SubSkill") + "]")); + command.setUsage(LocaleLoader.getString("Commands.Usage.1", "mmoinfo", + "[" + LocaleLoader.getString("Commands.Usage.SubSkill") + "]")); command.setExecutor(new MmoInfoCommand()); } @@ -127,7 +169,8 @@ public final class CommandRegistrationManager { command.setDescription(LocaleLoader.getString("Commands.Description.mcchatspy")); command.setPermission("mcmmo.commands.mcchatspy;mcmmo.commands.mcchatspy.others"); command.setPermissionMessage(permissionsMessage); - command.setUsage(LocaleLoader.getString("Commands.Usage.1", "mcchatspy", "[" + LocaleLoader.getString("Commands.Usage.Player") + "]")); + command.setUsage(LocaleLoader.getString("Commands.Usage.1", "mcchatspy", + "[" + LocaleLoader.getString("Commands.Usage.Player") + "]")); command.setExecutor(new McChatSpy()); } @@ -136,7 +179,8 @@ public final class CommandRegistrationManager { command.setDescription(LocaleLoader.getString("Commands.Description.mcrefresh")); command.setPermission("mcmmo.commands.mcrefresh;mcmmo.commands.mcrefresh.others"); command.setPermissionMessage(permissionsMessage); - command.setUsage(LocaleLoader.getString("Commands.Usage.1", "mcrefresh", "[" + LocaleLoader.getString("Commands.Usage.Player") + "]")); + command.setUsage(LocaleLoader.getString("Commands.Usage.1", "mcrefresh", + "[" + LocaleLoader.getString("Commands.Usage.Player") + "]")); command.setExecutor(new McrefreshCommand()); } @@ -145,16 +189,22 @@ public final class CommandRegistrationManager { command.setDescription(LocaleLoader.getString("Commands.Description.mmoedit")); command.setPermission("mcmmo.commands.mmoedit;mcmmo.commands.mmoedit.others"); command.setPermissionMessage(permissionsMessage); - command.setUsage(LocaleLoader.getString("Commands.Usage.3.XP", "mmoedit", "[" + LocaleLoader.getString("Commands.Usage.Player") + "]", "<" + LocaleLoader.getString("Commands.Usage.Skill") + ">", "<" + LocaleLoader.getString("Commands.Usage.Level") + ">")); + command.setUsage(LocaleLoader.getString("Commands.Usage.3.XP", "mmoedit", + "[" + LocaleLoader.getString("Commands.Usage.Player") + "]", + "<" + LocaleLoader.getString("Commands.Usage.Skill") + ">", + "<" + LocaleLoader.getString("Commands.Usage.Level") + ">")); command.setExecutor(new MmoeditCommand()); } private static void registerSkillresetCommand() { PluginCommand command = mcMMO.p.getCommand("skillreset"); command.setDescription(LocaleLoader.getString("Commands.Description.skillreset")); - command.setPermission("mcmmo.commands.skillreset;mcmmo.commands.skillreset.others"); // Only need the main ones, not the individual skill ones + command.setPermission( + "mcmmo.commands.skillreset;mcmmo.commands.skillreset.others"); // Only need the main ones, not the individual skill ones command.setPermissionMessage(permissionsMessage); - command.setUsage(LocaleLoader.getString("Commands.Usage.2", "skillreset", "[" + LocaleLoader.getString("Commands.Usage.Player") + "]", "<" + LocaleLoader.getString("Commands.Usage.Skill") + ">")); + command.setUsage(LocaleLoader.getString("Commands.Usage.2", "skillreset", + "[" + LocaleLoader.getString("Commands.Usage.Player") + "]", + "<" + LocaleLoader.getString("Commands.Usage.Skill") + ">")); command.setExecutor(new SkillresetCommand()); } @@ -164,10 +214,14 @@ public final class CommandRegistrationManager { PluginCommand command = mcMMO.p.getCommand("xprate"); command.setDescription(LocaleLoader.getString("Commands.Description.xprate")); - command.setPermission("mcmmo.commands.xprate;mcmmo.commands.xprate.reset;mcmmo.commands.xprate.set"); + command.setPermission( + "mcmmo.commands.xprate;mcmmo.commands.xprate.reset;mcmmo.commands.xprate.set"); command.setPermissionMessage(permissionsMessage); - command.setUsage(LocaleLoader.getString("Commands.Usage.2", "xprate", "<" + LocaleLoader.getString("Commands.Usage.Rate") + ">", "")); - command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.1", "xprate", "reset")); + command.setUsage(LocaleLoader.getString("Commands.Usage.2", "xprate", + "<" + LocaleLoader.getString("Commands.Usage.Rate") + ">", "")); + command.setUsage( + command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.1", "xprate", + "reset")); command.setAliases(aliasList); command.setExecutor(new XprateCommand()); } @@ -175,9 +229,11 @@ public final class CommandRegistrationManager { private static void registerInspectCommand() { PluginCommand command = mcMMO.p.getCommand("inspect"); command.setDescription(LocaleLoader.getString("Commands.Description.inspect")); - command.setPermission("mcmmo.commands.inspect;mcmmo.commands.inspect.far;mcmmo.commands.inspect.offline"); + command.setPermission( + "mcmmo.commands.inspect;mcmmo.commands.inspect.far;mcmmo.commands.inspect.offline"); command.setPermissionMessage(permissionsMessage); - command.setUsage(LocaleLoader.getString("Commands.Usage.1", "inspect", "<" + LocaleLoader.getString("Commands.Usage.Player") + ">")); + command.setUsage(LocaleLoader.getString("Commands.Usage.1", "inspect", + "<" + LocaleLoader.getString("Commands.Usage.Player") + ">")); command.setExecutor(new InspectCommand()); } @@ -195,7 +251,8 @@ public final class CommandRegistrationManager { command.setDescription(LocaleLoader.getString("Commands.Description.mcability")); command.setPermission("mcmmo.commands.mcability;mcmmo.commands.mcability.others"); command.setPermissionMessage(permissionsMessage); - command.setUsage(LocaleLoader.getString("Commands.Usage.1", "mcability", "[" + LocaleLoader.getString("Commands.Usage.Player") + "]")); + command.setUsage(LocaleLoader.getString("Commands.Usage.1", "mcability", + "[" + LocaleLoader.getString("Commands.Usage.Player") + "]")); command.setExecutor(new McabilityCommand()); } @@ -205,16 +262,20 @@ public final class CommandRegistrationManager { command.setPermission("mcmmo.commands.mcmmo.description;mcmmo.commands.mcmmo.help"); command.setPermissionMessage(permissionsMessage); command.setUsage(LocaleLoader.getString("Commands.Usage.0", "mcmmo")); - command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.1", "mcmmo", "help")); + command.setUsage( + command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.1", "mcmmo", + "help")); command.setExecutor(new McmmoCommand()); } private static void registerMcrankCommand() { PluginCommand command = mcMMO.p.getCommand("mcrank"); command.setDescription(LocaleLoader.getString("Commands.Description.mcrank")); - command.setPermission("mcmmo.commands.mcrank;mcmmo.commands.mcrank.others;mcmmo.commands.mcrank.others.far;mcmmo.commands.mcrank.others.offline"); + command.setPermission( + "mcmmo.commands.mcrank;mcmmo.commands.mcrank.others;mcmmo.commands.mcrank.others.far;mcmmo.commands.mcrank.others.offline"); command.setPermissionMessage(permissionsMessage); - command.setUsage(LocaleLoader.getString("Commands.Usage.1", "mcrank", "[" + LocaleLoader.getString("Commands.Usage.Player") + "]")); + command.setUsage(LocaleLoader.getString("Commands.Usage.1", "mcrank", + "[" + LocaleLoader.getString("Commands.Usage.Player") + "]")); command.setExecutor(new McRankCommand()); } @@ -230,15 +291,19 @@ public final class CommandRegistrationManager { private static void registerMctopCommand() { PluginCommand command = mcMMO.p.getCommand("mctop"); command.setDescription(LocaleLoader.getString("Commands.Description.mctop")); - command.setPermission("mcmmo.commands.mctop"); // Only need the main one, not the individual skill ones + command.setPermission( + "mcmmo.commands.mctop"); // Only need the main one, not the individual skill ones command.setPermissionMessage(permissionsMessage); - command.setUsage(LocaleLoader.getString("Commands.Usage.2", "mctop", "[" + LocaleLoader.getString("Commands.Usage.Skill") + "]", "[" + LocaleLoader.getString("Commands.Usage.Page") + "]")); + command.setUsage(LocaleLoader.getString("Commands.Usage.2", "mctop", + "[" + LocaleLoader.getString("Commands.Usage.Skill") + "]", + "[" + LocaleLoader.getString("Commands.Usage.Page") + "]")); command.setExecutor(new McTopCommand()); } private static void registerMcpurgeCommand() { PluginCommand command = mcMMO.p.getCommand("mcpurge"); - command.setDescription(LocaleLoader.getString("Commands.Description.mcpurge", mcMMO.p.getGeneralConfig().getOldUsersCutoff())); + command.setDescription(LocaleLoader.getString("Commands.Description.mcpurge", + mcMMO.p.getGeneralConfig().getOldUsersCutoff())); command.setPermission("mcmmo.commands.mcpurge"); command.setPermissionMessage(permissionsMessage); command.setUsage(LocaleLoader.getString("Commands.Usage.0", "mcpurge")); @@ -250,7 +315,8 @@ public final class CommandRegistrationManager { command.setDescription(LocaleLoader.getString("Commands.Description.mcremove")); command.setPermission("mcmmo.commands.mcremove"); command.setPermissionMessage(permissionsMessage); - command.setUsage(LocaleLoader.getString("Commands.Usage.1", "mcremove", "<" + LocaleLoader.getString("Commands.Usage.Player") + ">")); + command.setUsage(LocaleLoader.getString("Commands.Usage.1", "mcremove", + "<" + LocaleLoader.getString("Commands.Usage.Player") + ">")); command.setExecutor(new McremoveCommand()); } @@ -266,20 +332,28 @@ public final class CommandRegistrationManager { private static void registerMcconvertCommand() { PluginCommand command = mcMMO.p.getCommand("mcconvert"); command.setDescription(LocaleLoader.getString("Commands.Description.mcconvert")); - command.setPermission("mcmmo.commands.mcconvert;mcmmo.commands.mcconvert.experience;mcmmo.commands.mcconvert.database"); + command.setPermission( + "mcmmo.commands.mcconvert;mcmmo.commands.mcconvert.experience;mcmmo.commands.mcconvert.database"); command.setPermissionMessage(permissionsMessage); - command.setUsage(LocaleLoader.getString("Commands.Usage.2", "mcconvert", "database", "")); - command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.2", "mcconvert", "experience", "")); + command.setUsage(LocaleLoader.getString("Commands.Usage.2", "mcconvert", "database", + "")); + command.setUsage( + command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.2", "mcconvert", + "experience", "")); command.setExecutor(new McconvertCommand()); } private static void registerPartyCommand() { 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"); + 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"); command.setPermissionMessage(permissionsMessage); command.setExecutor(new PartyCommand()); } @@ -287,10 +361,14 @@ public final class CommandRegistrationManager { private static void registerPtpCommand() { PluginCommand command = mcMMO.p.getCommand("ptp"); command.setDescription(LocaleLoader.getString("Commands.Description.ptp")); - command.setPermission("mcmmo.commands.ptp"); // Only need the main one, not the individual ones for toggle/accept/acceptall + command.setPermission( + "mcmmo.commands.ptp"); // Only need the main one, not the individual ones for toggle/accept/acceptall command.setPermissionMessage(permissionsMessage); - command.setUsage(LocaleLoader.getString("Commands.Usage.1", "ptp", "<" + LocaleLoader.getString("Commands.Usage.Player") + ">")); - command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.1", "ptp", "")); + command.setUsage(LocaleLoader.getString("Commands.Usage.1", "ptp", + "<" + LocaleLoader.getString("Commands.Usage.Player") + ">")); + command.setUsage( + command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.1", "ptp", + "")); command.setExecutor(new PtpCommand()); } @@ -305,11 +383,14 @@ public final class CommandRegistrationManager { private static void registerMcscoreboardCommand() { PluginCommand command = mcMMO.p.getCommand("mcscoreboard"); - command.setDescription("Change the current mcMMO scoreboard being displayed"); //TODO: Localize + command.setDescription( + "Change the current mcMMO scoreboard being displayed"); //TODO: Localize command.setPermission("mcmmo.commands.mcscoreboard"); command.setPermissionMessage(permissionsMessage); - command.setUsage(LocaleLoader.getString("Commands.Usage.1", "mcscoreboard", "")); - command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.2", "mcscoreboard", "time", "")); + command.setUsage( + LocaleLoader.getString("Commands.Usage.1", "mcscoreboard", "")); + command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.2", + "mcscoreboard", "time", "")); command.setExecutor(new McscoreboardCommand()); } @@ -332,8 +413,11 @@ public final class CommandRegistrationManager { private static void registerXPBarCommand() { PluginCommand command = mcMMO.p.getCommand("mmoxpbar"); //TODO: Localize command.setDescription(LocaleLoader.getString("Commands.Description.mmoxpbar")); - command.setUsage(LocaleLoader.getString("Commands.Usage.1", "mmoxpbar", "")); - command.setUsage(command.getUsage() +"\n" + LocaleLoader.getString("Commands.Usage.2", "mmoxpbar", "", "")); + command.setUsage( + LocaleLoader.getString("Commands.Usage.1", "mmoxpbar", "")); + command.setUsage( + command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.2", "mmoxpbar", + "", "")); command.setExecutor(new XPBarCommand()); } 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 ff6a234e9..f08a5ab0c 100644 --- a/src/main/java/com/gmail/nossr50/util/commands/CommandUtils.java +++ b/src/main/java/com/gmail/nossr50/util/commands/CommandUtils.java @@ -12,26 +12,28 @@ import com.gmail.nossr50.util.skills.SkillTools; import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.text.StringUtils; import com.google.common.collect.ImmutableList; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - public final class CommandUtils { - public static final List TRUE_FALSE_OPTIONS = ImmutableList.of("on", "off", "true", "false", "enabled", "disabled"); + 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 || !SkillTools.isChildSkill(skill)) { return false; } - sender.sendMessage("Child skills are not supported by this command."); // TODO: Localize this + sender.sendMessage( + "Child skills are not supported by this command."); // TODO: Localize this return true; } @@ -39,7 +41,9 @@ public final class CommandUtils { if (!target.isOnline() && !hasPermission) { sender.sendMessage(LocaleLoader.getString("Inspect.Offline")); return true; - } else if (sender instanceof Player && !Misc.isNear(((Player) sender).getLocation(), target.getLocation(), mcMMO.p.getGeneralConfig().getInspectDistance()) && !hasPermission) { + } else if (sender instanceof Player && !Misc.isNear(((Player) sender).getLocation(), + target.getLocation(), mcMMO.p.getGeneralConfig().getInspectDistance()) + && !hasPermission) { sender.sendMessage(LocaleLoader.getString("Inspect.TooFar")); return true; } @@ -70,17 +74,17 @@ public final class CommandUtils { } /** - * Checks if there is a valid mcMMOPlayer object. + * Checks if there is a valid mmoPlayer object. * * @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 + * @param mmoPlayer mmoPlayer object of the target player + * @return true if the player is online and a valid mmoPlayer object was found */ - public static boolean checkPlayerExistence(CommandSender sender, String playerName, McMMOPlayer mcMMOPlayer) { - if (mcMMOPlayer != null) { - if (CommandUtils.hidden(sender, mcMMOPlayer.getPlayer(), false)) { + public static boolean checkPlayerExistence(CommandSender sender, String playerName, + McMMOPlayer mmoPlayer) { + if (mmoPlayer != null) { + if (CommandUtils.hidden(sender, mmoPlayer.getPlayer(), false)) { sender.sendMessage(LocaleLoader.getString("Commands.Offline")); return false; } @@ -111,7 +115,8 @@ public final class CommandUtils { return false; } - boolean hasPlayerDataKey = ((Player) sender).hasMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA); + boolean hasPlayerDataKey = ((Player) sender).hasMetadata( + MetadataConstants.METADATA_KEY_PLAYER_DATA); if (!hasPlayerDataKey) { sender.sendMessage(LocaleLoader.getString("Commands.NotLoaded")); @@ -157,11 +162,13 @@ public final class CommandUtils { } public static boolean shouldEnableToggle(String arg) { - return arg.equalsIgnoreCase("on") || arg.equalsIgnoreCase("true") || arg.equalsIgnoreCase("enabled"); + return arg.equalsIgnoreCase("on") || arg.equalsIgnoreCase("true") || arg.equalsIgnoreCase( + "enabled"); } public static boolean shouldDisableToggle(String arg) { - return arg.equalsIgnoreCase("off") || arg.equalsIgnoreCase("false") || arg.equalsIgnoreCase("disabled"); + return arg.equalsIgnoreCase("off") || arg.equalsIgnoreCase("false") || arg.equalsIgnoreCase( + "disabled"); } /** @@ -171,7 +178,8 @@ public final class CommandUtils { * @param display The sender to display stats to */ public static void printGatheringSkills(Player inspect, CommandSender display) { - printGroupedSkillData(inspect, display, LocaleLoader.getString("Stats.Header.Gathering"), mcMMO.p.getSkillTools().GATHERING_SKILLS); + printGroupedSkillData(inspect, display, LocaleLoader.getString("Stats.Header.Gathering"), + mcMMO.p.getSkillTools().GATHERING_SKILLS); } public static void printGatheringSkills(Player player) { @@ -185,7 +193,8 @@ public final class CommandUtils { * @param display The sender to display stats to */ public static void printCombatSkills(Player inspect, CommandSender display) { - printGroupedSkillData(inspect, display, LocaleLoader.getString("Stats.Header.Combat"), mcMMO.p.getSkillTools().COMBAT_SKILLS); + printGroupedSkillData(inspect, display, LocaleLoader.getString("Stats.Header.Combat"), + mcMMO.p.getSkillTools().COMBAT_SKILLS); } public static void printCombatSkills(Player player) { @@ -199,7 +208,8 @@ public final class CommandUtils { * @param display The sender to display stats to */ public static void printMiscSkills(Player inspect, CommandSender display) { - printGroupedSkillData(inspect, display, LocaleLoader.getString("Stats.Header.Misc"), mcMMO.p.getSkillTools().getMiscSkills()); + printGroupedSkillData(inspect, display, LocaleLoader.getString("Stats.Header.Misc"), + mcMMO.p.getSkillTools().getMiscSkills()); } public static void printMiscSkills(Player player) { @@ -208,18 +218,27 @@ public final class CommandUtils { public static String displaySkill(PlayerProfile profile, PrimarySkillType skill) { if (SkillTools.isChildSkill(skill)) { - return LocaleLoader.getString("Skills.ChildStats", LocaleLoader.getString(StringUtils.getCapitalized(skill.toString()) + ".Listener") + " ", profile.getSkillLevel(skill)); + return LocaleLoader.getString("Skills.ChildStats", LocaleLoader.getString( + StringUtils.getCapitalized(skill.toString()) + ".Listener") + " ", + profile.getSkillLevel(skill)); } - if (profile.getSkillLevel(skill) == mcMMO.p.getSkillTools().getLevelCap(skill)){ - return LocaleLoader.getString("Skills.Stats", LocaleLoader.getString(StringUtils.getCapitalized(skill.toString()) + ".Listener") + " ", profile.getSkillLevel(skill), profile.getSkillXpLevel(skill), LocaleLoader.getString("Skills.MaxXP")); + if (profile.getSkillLevel(skill) == mcMMO.p.getSkillTools().getLevelCap(skill)) { + return LocaleLoader.getString("Skills.Stats", LocaleLoader.getString( + StringUtils.getCapitalized(skill.toString()) + ".Listener") + " ", + profile.getSkillLevel(skill), profile.getSkillXpLevel(skill), + LocaleLoader.getString("Skills.MaxXP")); } - return LocaleLoader.getString("Skills.Stats", LocaleLoader.getString(StringUtils.getCapitalized(skill.toString()) + ".Listener") + " ", profile.getSkillLevel(skill), profile.getSkillXpLevel(skill), profile.getXpToLevel(skill)); + return LocaleLoader.getString("Skills.Stats", + LocaleLoader.getString(StringUtils.getCapitalized(skill.toString()) + ".Listener") + + " ", profile.getSkillLevel(skill), profile.getSkillXpLevel(skill), + profile.getXpToLevel(skill)); } private static void printGroupedSkillData(Player inspectTarget, CommandSender display, - String header, List skillGroup) { - if (UserManager.getPlayer(inspectTarget) == null) + String header, List skillGroup) { + if (UserManager.getPlayer(inspectTarget) == null) { return; + } final PlayerProfile profile = UserManager.getPlayer(inspectTarget).getProfile(); @@ -227,7 +246,8 @@ public final class CommandUtils { displayData.add(header); for (PrimarySkillType primarySkillType : skillGroup) { - if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(inspectTarget, primarySkillType)) { + if (mcMMO.p.getSkillTools() + .doesPlayerHaveSkillPermission(inspectTarget, primarySkillType)) { displayData.add(displaySkill(profile, primarySkillType)); } } @@ -256,7 +276,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) { @@ -278,10 +297,11 @@ 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. + * 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. * * @param partialName Name to match * @return List of all possible names @@ -291,10 +311,13 @@ 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 + + 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 } if (partialName.equalsIgnoreCase(playerName)) { @@ -304,7 +327,8 @@ public final class CommandUtils { break; } - if (playerName.toLowerCase(Locale.ENGLISH).contains(partialName.toLowerCase(Locale.ENGLISH))) { + if (playerName.toLowerCase(Locale.ENGLISH) + .contains(partialName.toLowerCase(Locale.ENGLISH))) { // Partial match matchedPlayers.add(playerName); } diff --git a/src/main/java/com/gmail/nossr50/util/compat/CompatibilityLayer.java b/src/main/java/com/gmail/nossr50/util/compat/CompatibilityLayer.java index 5abbaa818..7dbd576bf 100644 --- a/src/main/java/com/gmail/nossr50/util/compat/CompatibilityLayer.java +++ b/src/main/java/com/gmail/nossr50/util/compat/CompatibilityLayer.java @@ -6,7 +6,11 @@ package com.gmail.nossr50.util.compat; public interface CompatibilityLayer { /** * Whether this CompatibilityLayer successfully initialized and in theory should be functional + * * @return true if this CompatibilityLayer is functional */ - default boolean noErrorsOnInitialize() { return true; }; + default boolean noErrorsOnInitialize() { + return true; + } + } diff --git a/src/main/java/com/gmail/nossr50/util/compat/CompatibilityManager.java b/src/main/java/com/gmail/nossr50/util/compat/CompatibilityManager.java index db6de7825..e7a9237ad 100644 --- a/src/main/java/com/gmail/nossr50/util/compat/CompatibilityManager.java +++ b/src/main/java/com/gmail/nossr50/util/compat/CompatibilityManager.java @@ -11,17 +11,14 @@ import com.gmail.nossr50.util.compat.layers.skills.MasterAnglerCompatibilityLaye import com.gmail.nossr50.util.nms.NMSVersion; import com.gmail.nossr50.util.platform.MinecraftGameVersion; import com.gmail.nossr50.util.text.StringUtils; +import java.util.HashMap; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.HashMap; - /** - * - * These classes are a band-aid solution for adding NMS support into 2.1.XXX - * In 2.2 we are switching to modules and that will clean things up significantly - * + * These classes are a band-aid solution for adding NMS support into 2.1.XXX In 2.2 we are switching + * to modules and that will clean things up significantly */ public class CompatibilityManager { private @NotNull HashMap supportedLayers; @@ -49,14 +46,14 @@ public class CompatibilityManager { private void initSupportedLayersMap() { supportedLayers = new HashMap<>(); //Init map - for(CompatibilityType compatibilityType : CompatibilityType.values()) { - supportedLayers.put(compatibilityType, false); //All layers are set to false when initialized + for (CompatibilityType compatibilityType : CompatibilityType.values()) { + supportedLayers.put(compatibilityType, + false); //All layers are set to false when initialized } } /** - * Initialize all necessary compatibility layers - * For any unsupported layers, load a dummy layer + * Initialize all necessary compatibility layers For any unsupported layers, load a dummy layer */ private void initCompatibilityLayers() { initBungeeSerializerLayer(); @@ -90,15 +87,17 @@ public class CompatibilityManager { "mcMMO is fully compatible with the currently running server software.")); } else { //TODO: Better messages for each incompatible layer - for(CompatibilityType compatibilityType : CompatibilityType.values()) { + for (CompatibilityType compatibilityType : CompatibilityType.values()) { if (!supportedLayers.get(compatibilityType)) { commandSender.sendMessage(LocaleLoader.getString("mcMMO.Template.Prefix", - LocaleLoader.getString("Compatibility.Layer.Unsupported", StringUtils.getCapitalized(compatibilityType.toString())))); + LocaleLoader.getString("Compatibility.Layer.Unsupported", + StringUtils.getCapitalized(compatibilityType.toString())))); } } } - commandSender.sendMessage(LocaleLoader.getString("mcMMO.Template.Prefix", "NMS Status - " + nmsVersion.toString())); + commandSender.sendMessage(LocaleLoader.getString("mcMMO.Template.Prefix", + "NMS Status - " + nmsVersion)); } public boolean isCompatibilityLayerOperational(@NotNull CompatibilityType compatibilityType) { diff --git a/src/main/java/com/gmail/nossr50/util/compat/layers/AbstractCompatibilityLayer.java b/src/main/java/com/gmail/nossr50/util/compat/layers/AbstractCompatibilityLayer.java index 2ae4a61e1..ab32dc2b4 100644 --- a/src/main/java/com/gmail/nossr50/util/compat/layers/AbstractCompatibilityLayer.java +++ b/src/main/java/com/gmail/nossr50/util/compat/layers/AbstractCompatibilityLayer.java @@ -3,10 +3,8 @@ package com.gmail.nossr50.util.compat.layers; import com.gmail.nossr50.util.compat.CompatibilityLayer; /** - * - * These classes are a band-aid solution for adding NMS support into 2.1.XXX - * In 2.2 we are switching to modules and that will clean things up significantly - * + * These classes are a band-aid solution for adding NMS support into 2.1.XXX In 2.2 we are switching + * to modules and that will clean things up significantly */ public abstract class AbstractCompatibilityLayer implements CompatibilityLayer { @@ -14,6 +12,7 @@ public abstract class AbstractCompatibilityLayer implements CompatibilityLayer { /** * Initialize the CompatibilityLayer + * * @return true if the CompatibilityLayer initialized and should be functional */ public abstract boolean initializeLayer(); diff --git a/src/main/java/com/gmail/nossr50/util/compat/layers/AbstractNMSCompatibilityLayer.java b/src/main/java/com/gmail/nossr50/util/compat/layers/AbstractNMSCompatibilityLayer.java index 05136c189..f337f61fd 100644 --- a/src/main/java/com/gmail/nossr50/util/compat/layers/AbstractNMSCompatibilityLayer.java +++ b/src/main/java/com/gmail/nossr50/util/compat/layers/AbstractNMSCompatibilityLayer.java @@ -4,10 +4,8 @@ import com.gmail.nossr50.util.nms.NMSVersion; import org.jetbrains.annotations.NotNull; /** - * - * These classes are a band-aid solution for adding NMS support into 2.1.XXX - * In 2.2 we are switching to modules and that will clean things up significantly - * + * These classes are a band-aid solution for adding NMS support into 2.1.XXX In 2.2 we are switching + * to modules and that will clean things up significantly */ public abstract class AbstractNMSCompatibilityLayer extends AbstractCompatibilityLayer { @@ -19,6 +17,7 @@ public abstract class AbstractNMSCompatibilityLayer extends AbstractCompatibilit /** * Initialize the CompatibilityLayer + * * @return true if the CompatibilityLayer initialized and should be functional */ public abstract boolean initializeLayer(); diff --git a/src/main/java/com/gmail/nossr50/util/compat/layers/attackcooldown/PlayerAttackCooldownMethods.java b/src/main/java/com/gmail/nossr50/util/compat/layers/attackcooldown/PlayerAttackCooldownMethods.java index 510577a68..c7ae24085 100644 --- a/src/main/java/com/gmail/nossr50/util/compat/layers/attackcooldown/PlayerAttackCooldownMethods.java +++ b/src/main/java/com/gmail/nossr50/util/compat/layers/attackcooldown/PlayerAttackCooldownMethods.java @@ -1,24 +1,30 @@ package com.gmail.nossr50.util.compat.layers.attackcooldown; +import java.lang.reflect.InvocationTargetException; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.lang.reflect.InvocationTargetException; - public interface PlayerAttackCooldownMethods { /** - * Grabs the attack strength for a player - * Should be noted that as of today there is no way to capture a players current attack strength in spigot when they attack an entity outside of network packet listening + * Grabs the attack strength for a player Should be noted that as of today there is no way to + * capture a players current attack strength in spigot when they attack an entity outside of + * network packet listening + * * @param player target player * @return the float value of the player's attack strength */ - float getAttackStrength(@NotNull Player player) throws InvocationTargetException, IllegalAccessException; + float getAttackStrength(@NotNull Player player) + throws InvocationTargetException, IllegalAccessException; - float getCooldownValue(@NotNull Player player) throws InvocationTargetException, IllegalAccessException; + float getCooldownValue(@NotNull Player player) + throws InvocationTargetException, IllegalAccessException; - void resetAttackStrength(@NotNull Player player) throws InvocationTargetException, IllegalAccessException; + void resetAttackStrength(@NotNull Player player) + throws InvocationTargetException, IllegalAccessException; - int getCooldownFieldValue(@NotNull Player player) throws InvocationTargetException, IllegalAccessException; + int getCooldownFieldValue(@NotNull Player player) + throws InvocationTargetException, IllegalAccessException; - void setCooldownFieldValue(@NotNull Player player, int fieldValue) throws InvocationTargetException, IllegalAccessException; + void setCooldownFieldValue(@NotNull Player player, int fieldValue) + throws InvocationTargetException, IllegalAccessException; } diff --git a/src/main/java/com/gmail/nossr50/util/compat/layers/attackcooldown/PlayerAttackCooldownToolLayer.java b/src/main/java/com/gmail/nossr50/util/compat/layers/attackcooldown/PlayerAttackCooldownToolLayer.java index 7a870c27a..c35d7f6ad 100644 --- a/src/main/java/com/gmail/nossr50/util/compat/layers/attackcooldown/PlayerAttackCooldownToolLayer.java +++ b/src/main/java/com/gmail/nossr50/util/compat/layers/attackcooldown/PlayerAttackCooldownToolLayer.java @@ -12,7 +12,7 @@ //import java.lang.reflect.InvocationTargetException; //import java.lang.reflect.Method; // -///** +/// ** // * // * These classes are a band-aid solution for adding NMS support into 2.1.XXX // * In 2.2 we are switching to modules and that will clean things up significantly diff --git a/src/main/java/com/gmail/nossr50/util/compat/layers/bungee/AbstractBungeeSerializerCompatibilityLayer.java b/src/main/java/com/gmail/nossr50/util/compat/layers/bungee/AbstractBungeeSerializerCompatibilityLayer.java index 590a65381..683f0efee 100644 --- a/src/main/java/com/gmail/nossr50/util/compat/layers/bungee/AbstractBungeeSerializerCompatibilityLayer.java +++ b/src/main/java/com/gmail/nossr50/util/compat/layers/bungee/AbstractBungeeSerializerCompatibilityLayer.java @@ -6,6 +6,6 @@ import org.checkerframework.checker.nullness.qual.NonNull; public abstract class AbstractBungeeSerializerCompatibilityLayer { - public abstract @NonNull Component deserialize(final @NonNull BaseComponent @NonNull[] input); + public abstract @NonNull Component deserialize(final @NonNull BaseComponent @NonNull [] input); } diff --git a/src/main/java/com/gmail/nossr50/util/compat/layers/bungee/BungeeLegacySerializerCompatibilityLayer.java b/src/main/java/com/gmail/nossr50/util/compat/layers/bungee/BungeeLegacySerializerCompatibilityLayer.java index 09c44faaa..24f614157 100644 --- a/src/main/java/com/gmail/nossr50/util/compat/layers/bungee/BungeeLegacySerializerCompatibilityLayer.java +++ b/src/main/java/com/gmail/nossr50/util/compat/layers/bungee/BungeeLegacySerializerCompatibilityLayer.java @@ -5,7 +5,8 @@ import net.kyori.adventure.text.serializer.bungeecord.BungeeComponentSerializer; import net.md_5.bungee.api.chat.BaseComponent; import org.checkerframework.checker.nullness.qual.NonNull; -public class BungeeLegacySerializerCompatibilityLayer extends AbstractBungeeSerializerCompatibilityLayer { +public class BungeeLegacySerializerCompatibilityLayer extends + AbstractBungeeSerializerCompatibilityLayer { @Override public @NonNull Component deserialize(@NonNull BaseComponent @NonNull [] input) { return BungeeComponentSerializer.legacy().deserialize(input); diff --git a/src/main/java/com/gmail/nossr50/util/compat/layers/bungee/BungeeModernSerializerCompatibilityLayer.java b/src/main/java/com/gmail/nossr50/util/compat/layers/bungee/BungeeModernSerializerCompatibilityLayer.java index 0fc93a702..41d27030c 100644 --- a/src/main/java/com/gmail/nossr50/util/compat/layers/bungee/BungeeModernSerializerCompatibilityLayer.java +++ b/src/main/java/com/gmail/nossr50/util/compat/layers/bungee/BungeeModernSerializerCompatibilityLayer.java @@ -5,7 +5,8 @@ import net.kyori.adventure.text.serializer.bungeecord.BungeeComponentSerializer; import net.md_5.bungee.api.chat.BaseComponent; import org.checkerframework.checker.nullness.qual.NonNull; -public class BungeeModernSerializerCompatibilityLayer extends AbstractBungeeSerializerCompatibilityLayer { +public class BungeeModernSerializerCompatibilityLayer extends + AbstractBungeeSerializerCompatibilityLayer { @Override public @NonNull Component deserialize(@NonNull BaseComponent @NonNull [] input) { return BungeeComponentSerializer.get().deserialize(input); diff --git a/src/main/java/com/gmail/nossr50/util/compat/layers/skills/MasterAnglerCompatibilityLayer.java b/src/main/java/com/gmail/nossr50/util/compat/layers/skills/MasterAnglerCompatibilityLayer.java index 665bd1aec..e0b5a4d5f 100644 --- a/src/main/java/com/gmail/nossr50/util/compat/layers/skills/MasterAnglerCompatibilityLayer.java +++ b/src/main/java/com/gmail/nossr50/util/compat/layers/skills/MasterAnglerCompatibilityLayer.java @@ -12,8 +12,7 @@ public class MasterAnglerCompatibilityLayer extends AbstractMasterAnglerCompatib /** * Get the minimum number of ticks one has to wait for a fish biting. *

- * The default is 100 ticks (5 seconds).
- * Note that this is before applying lure. + * The default is 100 ticks (5 seconds).
Note that this is before applying lure. * * @return Minimum number of ticks one has to wait for a fish biting */ @@ -24,11 +23,9 @@ public class MasterAnglerCompatibilityLayer extends AbstractMasterAnglerCompatib /** * Set the minimum number of ticks one has to wait for a fish biting. *

- * The default is 100 ticks (5 seconds).
- * Note that this is before applying lure. + * The default is 100 ticks (5 seconds).
Note that this is before applying lure. * - * @param minWaitTime Minimum number of ticks one has to wait for a fish - * biting + * @param minWaitTime Minimum number of ticks one has to wait for a fish biting */ public void setMinWaitTime(@NotNull FishHook fishHook, int minWaitTime) { fishHook.setMinWaitTime(minWaitTime); @@ -37,8 +34,7 @@ public class MasterAnglerCompatibilityLayer extends AbstractMasterAnglerCompatib /** * Get the maximum number of ticks one has to wait for a fish biting. *

- * The default is 600 ticks (30 seconds).
- * Note that this is before applying lure. + * The default is 600 ticks (30 seconds).
Note that this is before applying lure. * * @return Maximum number of ticks one has to wait for a fish biting */ @@ -49,41 +45,33 @@ public class MasterAnglerCompatibilityLayer extends AbstractMasterAnglerCompatib /** * Set the maximum number of ticks one has to wait for a fish biting. *

- * The default is 600 ticks (30 seconds).
- * Note that this is before applying lure. + * The default is 600 ticks (30 seconds).
Note that this is before applying lure. * - * @param maxWaitTime Maximum number of ticks one has to wait for a fish - * biting + * @param maxWaitTime Maximum number of ticks one has to wait for a fish biting */ public void setMaxWaitTime(@NotNull FishHook fishHook, int maxWaitTime) { fishHook.setMaxWaitTime(maxWaitTime); } /** - * Get whether the lure enchantment should be applied to reduce the wait - * time. + * Get whether the lure enchantment should be applied to reduce the wait time. *

- * The default is true.
- * Lure reduces the wait time by 100 ticks (5 seconds) for each level of the - * enchantment. + * The default is true.
Lure reduces the wait time by 100 ticks (5 seconds) for each level + * of the enchantment. * - * @return Whether the lure enchantment should be applied to reduce the wait - * time + * @return Whether the lure enchantment should be applied to reduce the wait time */ public boolean getApplyLure(@NotNull FishHook fishHook) { return fishHook.getApplyLure(); } /** - * Set whether the lure enchantment should be applied to reduce the wait - * time. + * Set whether the lure enchantment should be applied to reduce the wait time. *

- * The default is true.
- * Lure reduces the wait time by 100 ticks (5 seconds) for each level of the - * enchantment. + * The default is true.
Lure reduces the wait time by 100 ticks (5 seconds) for each level + * of the enchantment. * - * @param applyLure Whether the lure enchantment should be applied to reduce - * the wait time + * @param applyLure Whether the lure enchantment should be applied to reduce the wait time */ public void setApplyLure(@NotNull FishHook fishHook, boolean applyLure) { fishHook.setApplyLure(applyLure); 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 3c6191644..34948abc7 100644 --- a/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarManager.java +++ b/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarManager.java @@ -7,19 +7,18 @@ import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.runnables.skills.ExperienceBarHideTask; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.player.NotificationManager; +import java.util.HashMap; +import java.util.HashSet; import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.HashMap; -import java.util.HashSet; - /** - * ExperienceBarManager handles displaying and updating mcMMO experience bars for players - * Each ExperienceBarManager only manages a single player + * ExperienceBarManager handles displaying and updating mcMMO experience bars for players Each + * ExperienceBarManager only manages a single player */ public class ExperienceBarManager { - private final McMMOPlayer mcMMOPlayer; + private final McMMOPlayer mmoPlayer; int delaySeconds = 3; private HashMap experienceBars; @@ -28,8 +27,8 @@ public class ExperienceBarManager { private HashSet alwaysVisible; private HashSet disabledBars; - public ExperienceBarManager(McMMOPlayer mcMMOPlayer) { - this.mcMMOPlayer = mcMMOPlayer; + public ExperienceBarManager(McMMOPlayer mmoPlayer) { + this.mmoPlayer = mmoPlayer; init(); } @@ -46,18 +45,22 @@ public class ExperienceBarManager { public void updateExperienceBar(PrimarySkillType primarySkillType, Plugin plugin) { if (disabledBars.contains(primarySkillType) || !ExperienceConfig.getInstance().isExperienceBarsEnabled() - || !ExperienceConfig.getInstance().isExperienceBarEnabled(primarySkillType)) + || !ExperienceConfig.getInstance().isExperienceBarEnabled(primarySkillType)) { return; + } //Init Bar - if (experienceBars.get(primarySkillType) == null) - experienceBars.put(primarySkillType, new ExperienceBarWrapper(primarySkillType, mcMMOPlayer)); + if (experienceBars.get(primarySkillType) == null) { + experienceBars.put(primarySkillType, + new ExperienceBarWrapper(primarySkillType, mmoPlayer)); + } //Get Bar ExperienceBarWrapper experienceBarWrapper = experienceBars.get(primarySkillType); //Update Progress - experienceBarWrapper.setProgress(mcMMOPlayer.getProgressInCurrentSkillLevel(primarySkillType)); + experienceBarWrapper.setProgress( + mmoPlayer.getProgressInCurrentSkillLevel(primarySkillType)); //Show Bar experienceBarWrapper.showExperienceBar(); @@ -71,17 +74,22 @@ public class ExperienceBarManager { } private void scheduleHideTask(PrimarySkillType primarySkillType, Plugin plugin) { - if (alwaysVisible.contains(primarySkillType)) + if (alwaysVisible.contains(primarySkillType)) { return; + } - ExperienceBarHideTask experienceBarHideTask = new ExperienceBarHideTask(this, mcMMOPlayer, primarySkillType); - mcMMO.p.getFoliaLib().getScheduler().runAtEntityLater(mcMMOPlayer.getPlayer(), experienceBarHideTask, (long) delaySeconds * Misc.TICK_CONVERSION_FACTOR); + ExperienceBarHideTask experienceBarHideTask = new ExperienceBarHideTask(this, mmoPlayer, + primarySkillType); + mcMMO.p.getFoliaLib().getScheduler() + .runAtEntityLater(mmoPlayer.getPlayer(), experienceBarHideTask, + (long) delaySeconds * Misc.TICK_CONVERSION_FACTOR); experienceBarHideTaskHashMap.put(primarySkillType, experienceBarHideTask); } public void hideExperienceBar(PrimarySkillType primarySkillType) { - if (experienceBars.containsKey(primarySkillType)) + if (experienceBars.containsKey(primarySkillType)) { experienceBars.get(primarySkillType).hideExperienceBar(); + } } public void clearTask(PrimarySkillType primarySkillType) { @@ -89,15 +97,17 @@ public class ExperienceBarManager { } public void disableAllBars() { - for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { + for (PrimarySkillType primarySkillType : PrimarySkillType.values()) { xpBarSettingToggle(XPBarSettingTarget.HIDE, primarySkillType); } - NotificationManager.sendPlayerInformationChatOnlyPrefixed(mcMMOPlayer.getPlayer(), "Commands.XPBar.DisableAll"); + NotificationManager.sendPlayerInformationChatOnlyPrefixed(mmoPlayer.getPlayer(), + "Commands.XPBar.DisableAll"); } - public void xpBarSettingToggle(@NotNull XPBarSettingTarget settingTarget, @Nullable PrimarySkillType skillType) { - switch(settingTarget) { + public void xpBarSettingToggle(@NotNull XPBarSettingTarget settingTarget, + @Nullable PrimarySkillType skillType) { + switch (settingTarget) { case SHOW: disabledBars.remove(skillType); alwaysVisible.add(skillType); @@ -130,7 +140,7 @@ public class ExperienceBarManager { private void resetBarSettings() { //Hide all currently permanent bars - for(PrimarySkillType permanent : alwaysVisible) { + for (PrimarySkillType permanent : alwaysVisible) { hideExperienceBar(permanent); } @@ -142,14 +152,20 @@ public class ExperienceBarManager { disabledBars.add(PrimarySkillType.SMELTING); } - private void informPlayer(@NotNull ExperienceBarManager.@NotNull XPBarSettingTarget settingTarget, @Nullable PrimarySkillType primarySkillType) { + private void informPlayer( + @NotNull ExperienceBarManager.@NotNull XPBarSettingTarget settingTarget, + @Nullable PrimarySkillType primarySkillType) { //Inform player of setting change if (settingTarget != XPBarSettingTarget.RESET) { - NotificationManager.sendPlayerInformationChatOnlyPrefixed(mcMMOPlayer.getPlayer(), "Commands.XPBar.SettingChanged", mcMMO.p.getSkillTools().getLocalizedSkillName(primarySkillType), settingTarget.toString()); + NotificationManager.sendPlayerInformationChatOnlyPrefixed(mmoPlayer.getPlayer(), + "Commands.XPBar.SettingChanged", + mcMMO.p.getSkillTools().getLocalizedSkillName(primarySkillType), + settingTarget.toString()); } else { - NotificationManager.sendPlayerInformationChatOnlyPrefixed(mcMMOPlayer.getPlayer(), "Commands.XPBar.Reset"); + NotificationManager.sendPlayerInformationChatOnlyPrefixed(mmoPlayer.getPlayer(), + "Commands.XPBar.Reset"); } } - public enum XPBarSettingTarget { SHOW, HIDE, RESET, DISABLE } + public enum XPBarSettingTarget {SHOW, HIDE, RESET, DISABLE} } 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 d90eae7b2..4da3da66f 100644 --- a/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarWrapper.java +++ b/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarWrapper.java @@ -6,13 +6,12 @@ import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.util.player.PlayerLevelUtils; import com.gmail.nossr50.util.text.StringUtils; +import java.util.List; import org.bukkit.boss.BarColor; import org.bukkit.boss.BarStyle; import org.bukkit.boss.BossBar; import org.bukkit.entity.Player; -import java.util.List; - /** * A visual representation of a player's skill level progress for a PrimarySkillType */ @@ -20,7 +19,7 @@ public class ExperienceBarWrapper { private final PrimarySkillType primarySkillType; //Primary Skill private BossBar bossBar; - protected final McMMOPlayer mcMMOPlayer; + protected final McMMOPlayer mmoPlayer; private int lastLevelUpdated; /* @@ -29,8 +28,8 @@ public class ExperienceBarWrapper { protected String niceSkillName; protected String title; - public ExperienceBarWrapper(PrimarySkillType primarySkillType, McMMOPlayer mcMMOPlayer) { - this.mcMMOPlayer = mcMMOPlayer; + public ExperienceBarWrapper(PrimarySkillType primarySkillType, McMMOPlayer mmoPlayer) { + this.mmoPlayer = mmoPlayer; this.primarySkillType = primarySkillType; title = ""; lastLevelUpdated = 0; @@ -55,21 +54,38 @@ public class ExperienceBarWrapper { private String getTitleTemplate() { //If they are using extra details - if (ExperienceConfig.getInstance().isEarlyGameBoostEnabled() && PlayerLevelUtils.qualifiesForEarlyGameBoost(mcMMOPlayer, primarySkillType)) { - return LocaleLoader.getString("XPBar.Template.EarlyGameBoost"); - } else if (ExperienceConfig.getInstance().getAddExtraDetails()) - return LocaleLoader.getString("XPBar.Complex.Template", LocaleLoader.getString("XPBar."+niceSkillName, getLevel()), getCurrentXP(), getMaxXP(), getPowerLevel(), getPercentageOfLevel()); + if (ExperienceConfig.getInstance().isEarlyGameBoostEnabled() + && PlayerLevelUtils.qualifiesForEarlyGameBoost(mmoPlayer, primarySkillType)) { + return LocaleLoader.getString("XPBar.Template.EarlyGameBoost"); + } else 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); + return mmoPlayer.getSkillLevel(primarySkillType); + } + + private int getCurrentXP() { + return mmoPlayer.getSkillXpLevel(primarySkillType); + } + + private int getMaxXP() { + return mmoPlayer.getXpToLevel(primarySkillType); + } + + private int getPowerLevel() { + return mmoPlayer.getPowerLevel(); + } + + private int getPercentageOfLevel() { + return (int) (mmoPlayer.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(); @@ -97,23 +113,25 @@ public class ExperienceBarWrapper { 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 + } else { bossBar.setProgress(v); + } //Check player level - if (ExperienceConfig.getInstance().isEarlyGameBoostEnabled() && PlayerLevelUtils.qualifiesForEarlyGameBoost(mcMMOPlayer, primarySkillType)) { - setColor(BarColor.YELLOW); + if (ExperienceConfig.getInstance().isEarlyGameBoostEnabled() + && PlayerLevelUtils.qualifiesForEarlyGameBoost(mmoPlayer, primarySkillType)) { + setColor(BarColor.YELLOW); } else { setColor(ExperienceConfig.getInstance().getExperienceBarColor(primarySkillType)); } //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(); } @@ -144,10 +162,10 @@ public class ExperienceBarWrapper { }*/ private void createBossBar() { - bossBar = mcMMOPlayer.getPlayer().getServer().createBossBar( + bossBar = mmoPlayer.getPlayer().getServer().createBossBar( title, ExperienceConfig.getInstance().getExperienceBarColor(primarySkillType), ExperienceConfig.getInstance().getExperienceBarStyle(primarySkillType)); - bossBar.addPlayer(mcMMOPlayer.getPlayer()); + bossBar.addPlayer(mmoPlayer.getPlayer()); } } 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 01964d0a8..4eb9e5178 100644 --- a/src/main/java/com/gmail/nossr50/util/experience/FormulaManager.java +++ b/src/main/java/com/gmail/nossr50/util/experience/FormulaManager.java @@ -5,11 +5,10 @@ import com.gmail.nossr50.datatypes.experience.FormulaType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.LogUtils; -import org.bukkit.configuration.file.YamlConfiguration; - import java.io.File; import java.util.HashMap; import java.util.Map; +import org.bukkit.configuration.file.YamlConfiguration; public class FormulaManager { private static final File formulaFile = new File(mcMMO.getFlatFileDirectory() + "formula.yml"); @@ -57,9 +56,8 @@ public class FormulaManager { } /** - * Calculate the total amount of experience earned based on - * the amount of levels and experience, using the previously - * used formula type. + * Calculate the total amount of experience earned based on the amount of levels and experience, + * using the previously used formula type. * * @param skillLevel Amount of levels * @param skillXPLevel Amount of experience @@ -78,15 +76,15 @@ public class FormulaManager { } /** - * Calculate how many levels a player should have using - * the new formula type. + * Calculate how many levels a player should have using 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} * @return the amount of levels and experience */ - public int[] calculateNewLevel(PrimarySkillType primarySkillType, int experience, FormulaType formulaType) { + public int[] calculateNewLevel(PrimarySkillType primarySkillType, int experience, + FormulaType formulaType) { int newLevel = 0; int remainder = 0; int maxLevel = mcMMO.p.getSkillTools().getLevelCap(primarySkillType); @@ -103,13 +101,12 @@ public class FormulaManager { experience -= experienceToNextLevel; } - return new int[]{ newLevel, remainder }; + return new int[]{newLevel, remainder}; } /** - * Get the cached amount of experience needed to reach the next level, - * if cache doesn't contain the given value it is calculated and added - * to the cached data. + * Get the cached amount of experience needed to reach the next level, if cache doesn't contain + * the given value it is calculated and added to the cached data. * * @param level level to check * @param formulaType The {@link FormulaType} used @@ -130,7 +127,9 @@ public class FormulaManager { } /** - * Gets the value of XP needed for the next level based on the level Scaling, the level, and the formula type + * Gets the value of XP needed for the next level based on the level Scaling, the level, and the + * formula type + * * @param level target level * @param formulaType target formulaType */ @@ -143,19 +142,23 @@ public class FormulaManager { } /** - * Calculate the XP needed for the next level for the linear formula for Standard scaling (1-100) + * Calculate the XP needed for the next level for the linear formula for Standard scaling + * (1-100) + * * @param level target level * @return raw xp needed to reach the next level */ private int processStandardXPToNextLevel(int level, FormulaType formulaType) { - Map experienceMapRef = formulaType == FormulaType.LINEAR ? experienceNeededStandardLinear : experienceNeededStandardExponential; + Map experienceMapRef = + formulaType == FormulaType.LINEAR ? experienceNeededStandardLinear + : experienceNeededStandardExponential; if (!experienceMapRef.containsKey(level)) { int experienceSum = 0; int retroIndex = (level * 10) + 1; //Sum the range of levels in Retro that this Standard level would represent - for(int x = retroIndex; x < (retroIndex + 10); x++) { + for (int x = retroIndex; x < (retroIndex + 10); x++) { //calculateXPNeeded doesn't cache results so we use that instead of invoking the Retro XP methods to avoid memory bloat experienceSum += calculateXPNeeded(x, formulaType); } @@ -167,14 +170,17 @@ public class FormulaManager { } /** - * Calculates the XP to next level for Retro Mode scaling - * Results are cached to reduce needless operations + * Calculates the XP to next level for Retro Mode scaling Results are cached to reduce needless + * operations + * * @param level target level * @param formulaType target formula type * @return raw xp needed to reach the next level based on formula type */ private int processXPRetroToNextLevel(int level, FormulaType formulaType) { - Map experienceMapRef = formulaType == FormulaType.LINEAR ? experienceNeededRetroLinear : experienceNeededRetroExponential; + Map experienceMapRef = + formulaType == FormulaType.LINEAR ? experienceNeededRetroLinear + : experienceNeededRetroExponential; if (!experienceMapRef.containsKey(level)) { int experience = calculateXPNeeded(level, formulaType); @@ -185,8 +191,9 @@ public class FormulaManager { } /** - * Does the actual math to get the XP needed for a level in RetroMode scaling - * Standard uses a sum of RetroMode XP needed levels for its own thing, so it uses this too + * Does the actual math to get the XP needed for a level in RetroMode scaling Standard uses a + * sum of RetroMode XP needed levels for its own thing, so it uses this too + * * @param level target level * @param formulaType target formulatype * @return the raw XP needed for the next level based on formula type @@ -195,7 +202,7 @@ public class FormulaManager { int base = ExperienceConfig.getInstance().getBase(formulaType); double multiplier = ExperienceConfig.getInstance().getMultiplier(formulaType); - switch(formulaType) { + switch (formulaType) { case LINEAR: return (int) Math.floor(base + level * multiplier); case EXPONENTIAL: @@ -203,7 +210,8 @@ public class FormulaManager { return (int) Math.floor(multiplier * Math.pow(level, exponent) + base); default: //TODO: Should never be called - mcMMO.p.getLogger().severe("Invalid formula specified for calculation, defaulting to Linear"); + mcMMO.p.getLogger() + .severe("Invalid formula specified for calculation, defaulting to Linear"); return calculateXPNeeded(level, FormulaType.LINEAR); } } @@ -217,7 +225,9 @@ public class FormulaManager { return; } - previousFormula = FormulaType.getFormulaType(YamlConfiguration.loadConfiguration(formulaFile).getString("Previous_Formula", "UNKNOWN")); + previousFormula = FormulaType.getFormulaType( + YamlConfiguration.loadConfiguration(formulaFile) + .getString("Previous_Formula", "UNKNOWN")); } /** @@ -230,8 +240,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/nms/NMSConstants.java b/src/main/java/com/gmail/nossr50/util/nms/NMSConstants.java index 38d65eb4b..dd931b859 100644 --- a/src/main/java/com/gmail/nossr50/util/nms/NMSConstants.java +++ b/src/main/java/com/gmail/nossr50/util/nms/NMSConstants.java @@ -12,10 +12,12 @@ public class NMSConstants { /** * Grabs the fully qualified path of a class from CB + * * @param targetClass source root path * @return the fully qualified path of a CB class */ - protected static String getFullyQualifiedCraftBukkitPath(String cbVersionPackage, String targetClass) { + protected static String getFullyQualifiedCraftBukkitPath(String cbVersionPackage, + String targetClass) { return CRAFT_BUKKIT_PACKAGE_PATH + "." + cbVersionPackage + "." + targetClass; } @@ -23,8 +25,9 @@ public class NMSConstants { return BUKKIT_PACKAGE_PATH + "." + fromSourceRoot; } - protected static String getFullyQualifiedNMSPath(String cbVersionPackage, String fromSourceRoot) { - return NET_MINECRAFT_SERVER + "." +cbVersionPackage + "." + fromSourceRoot; + protected static String getFullyQualifiedNMSPath(String cbVersionPackage, + String fromSourceRoot) { + return NET_MINECRAFT_SERVER + "." + cbVersionPackage + "." + fromSourceRoot; } public static String getCraftPlayerClassPath(String cbVersionPackage) { diff --git a/src/main/java/com/gmail/nossr50/util/nms/NMSVersion.java b/src/main/java/com/gmail/nossr50/util/nms/NMSVersion.java index 8c1e3c8b4..4df964049 100644 --- a/src/main/java/com/gmail/nossr50/util/nms/NMSVersion.java +++ b/src/main/java/com/gmail/nossr50/util/nms/NMSVersion.java @@ -36,7 +36,8 @@ public enum NMSVersion { /** * The standardized major.minor.patch {@link String} for the current NMS mappings * - * @return the standardized major.minor.patch version string, patch is omitted if it is not a patch version + * @return the standardized major.minor.patch version string, patch is omitted if it is not a + * patch version */ public String getSanitizedVersionNumber() { return sanitizedVersionNumber; diff --git a/src/main/java/com/gmail/nossr50/util/platform/AbstractPlatform.java b/src/main/java/com/gmail/nossr50/util/platform/AbstractPlatform.java index 3a6e11ed5..e8f891215 100644 --- a/src/main/java/com/gmail/nossr50/util/platform/AbstractPlatform.java +++ b/src/main/java/com/gmail/nossr50/util/platform/AbstractPlatform.java @@ -3,18 +3,17 @@ package com.gmail.nossr50.util.platform; import com.gmail.nossr50.util.compat.CompatibilityManager; /** - * - * These classes are a band-aid solution for adding NMS support into 2.1.XXX - * In 2.2 we are switching to modules and that will clean things up significantly - * + * These classes are a band-aid solution for adding NMS support into 2.1.XXX In 2.2 we are switching + * to modules and that will clean things up significantly */ -public abstract class AbstractPlatform implements Platform{ +public abstract class AbstractPlatform implements Platform { protected final CompatibilityManager compatibilityManager; protected final MinecraftGameVersion minecraftGameVersion; protected final ServerSoftwareType serverSoftwareType; - public AbstractPlatform(MinecraftGameVersion minecraftGameVersion, ServerSoftwareType serverSoftwareType, CompatibilityManager compatibilityManager) { + public AbstractPlatform(MinecraftGameVersion minecraftGameVersion, + ServerSoftwareType serverSoftwareType, CompatibilityManager compatibilityManager) { this.minecraftGameVersion = minecraftGameVersion; this.serverSoftwareType = serverSoftwareType; this.compatibilityManager = compatibilityManager; diff --git a/src/main/java/com/gmail/nossr50/util/platform/BukkitPlatform.java b/src/main/java/com/gmail/nossr50/util/platform/BukkitPlatform.java index 7183665a4..0f6ca778e 100644 --- a/src/main/java/com/gmail/nossr50/util/platform/BukkitPlatform.java +++ b/src/main/java/com/gmail/nossr50/util/platform/BukkitPlatform.java @@ -4,14 +4,13 @@ import com.gmail.nossr50.util.compat.CompatibilityManager; import org.jetbrains.annotations.NotNull; /** - * - * These classes are a band-aid solution for adding NMS support into 2.1.XXX - * In 2.2 we are switching to modules and that will clean things up significantly - * + * These classes are a band-aid solution for adding NMS support into 2.1.XXX In 2.2 we are switching + * to modules and that will clean things up significantly */ public class BukkitPlatform extends AbstractPlatform { public BukkitPlatform(MinecraftGameVersion minecraftGameVersion) { - super(minecraftGameVersion, ServerSoftwareType.CRAFT_BUKKIT, new CompatibilityManager(minecraftGameVersion)); + super(minecraftGameVersion, ServerSoftwareType.CRAFT_BUKKIT, + new CompatibilityManager(minecraftGameVersion)); } @Override diff --git a/src/main/java/com/gmail/nossr50/util/platform/MajorMinorPatchVersion.java b/src/main/java/com/gmail/nossr50/util/platform/MajorMinorPatchVersion.java index ea114508e..c944cf858 100644 --- a/src/main/java/com/gmail/nossr50/util/platform/MajorMinorPatchVersion.java +++ b/src/main/java/com/gmail/nossr50/util/platform/MajorMinorPatchVersion.java @@ -2,16 +2,13 @@ package com.gmail.nossr50.util.platform; import com.gmail.nossr50.util.platform.version.SimpleNumericVersion; import com.gmail.nossr50.util.platform.version.Versioned; +import java.util.Objects; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Objects; - /** - * - * These classes are a band-aid solution for adding NMS support into 2.1.XXX - * In 2.2 we are switching to modules and that will clean things up significantly - * + * These classes are a band-aid solution for adding NMS support into 2.1.XXX In 2.2 we are switching + * to modules and that will clean things up significantly */ public abstract class MajorMinorPatchVersion implements Versioned { @@ -22,17 +19,21 @@ public abstract class MajorMinorPatchVersion implements Versioned { @NotNull private final SimpleNumericVersion patchVersion; - public MajorMinorPatchVersion(@NotNull SimpleNumericVersion majorVersion, @NotNull SimpleNumericVersion minorVersion) { + public MajorMinorPatchVersion(@NotNull SimpleNumericVersion majorVersion, + @NotNull SimpleNumericVersion minorVersion) { this.majorVersion = majorVersion; this.minorVersion = minorVersion; this.patchVersion = new SimpleNumericVersion(0); } - public MajorMinorPatchVersion(@NotNull SimpleNumericVersion majorVersion, @NotNull SimpleNumericVersion minorVersion, @Nullable SimpleNumericVersion patchVersion) { + public MajorMinorPatchVersion(@NotNull SimpleNumericVersion majorVersion, + @NotNull SimpleNumericVersion minorVersion, + @Nullable SimpleNumericVersion patchVersion) { this.majorVersion = majorVersion; this.minorVersion = minorVersion; - this.patchVersion = Objects.requireNonNullElseGet(patchVersion, () -> new SimpleNumericVersion(0)); + this.patchVersion = Objects.requireNonNullElseGet(patchVersion, + () -> new SimpleNumericVersion(0)); } public MajorMinorPatchVersion(int majorVerNumber, int minorVerNumber, int patchVerNumber) { @@ -49,6 +50,7 @@ public abstract class MajorMinorPatchVersion implements Versioned { /** * Get the major version string + * * @return the major version string */ public @NotNull SimpleNumericVersion getMajorVersion() { @@ -57,6 +59,7 @@ public abstract class MajorMinorPatchVersion implements Versioned { /** * Get the minor version string + * * @return the minor version string */ public @NotNull SimpleNumericVersion getMinorVersion() { @@ -65,6 +68,7 @@ public abstract class MajorMinorPatchVersion implements Versioned { /** * Get the patch version string + * * @return patch version string or null if patch numeric value is less than or equal to 0 */ public @NotNull SimpleNumericVersion getPatchVersion() { @@ -84,8 +88,9 @@ public abstract class MajorMinorPatchVersion implements Versioned { } /** - * Whether this version of Minecraft is a patch - * a patch version value above 0 will indicate that this is a patch + * Whether this version of Minecraft is a patch a patch version value above 0 will indicate that + * this is a patch + * * @return true if this version is a patch */ public boolean isPatch() { @@ -94,8 +99,12 @@ public abstract class MajorMinorPatchVersion implements Versioned { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } MajorMinorPatchVersion that = (MajorMinorPatchVersion) o; return majorVersion.equals(that.majorVersion) && minorVersion.equals(that.minorVersion) && diff --git a/src/main/java/com/gmail/nossr50/util/platform/MinecraftGameVersion.java b/src/main/java/com/gmail/nossr50/util/platform/MinecraftGameVersion.java index 34ccdede9..73b12ae63 100644 --- a/src/main/java/com/gmail/nossr50/util/platform/MinecraftGameVersion.java +++ b/src/main/java/com/gmail/nossr50/util/platform/MinecraftGameVersion.java @@ -5,17 +5,18 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** - * - * These classes are a band-aid solution for adding NMS support into 2.1.XXX - * In 2.2 we are switching to modules and that will clean things up significantly - * + * These classes are a band-aid solution for adding NMS support into 2.1.XXX In 2.2 we are switching + * to modules and that will clean things up significantly */ public class MinecraftGameVersion extends MajorMinorPatchVersion { - public MinecraftGameVersion(@NotNull SimpleNumericVersion majorVersion, @NotNull SimpleNumericVersion minorVersion) { + public MinecraftGameVersion(@NotNull SimpleNumericVersion majorVersion, + @NotNull SimpleNumericVersion minorVersion) { super(majorVersion, minorVersion); } - public MinecraftGameVersion(@NotNull SimpleNumericVersion majorVersion, @NotNull SimpleNumericVersion minorVersion, @Nullable SimpleNumericVersion patchVersion) { + public MinecraftGameVersion(@NotNull SimpleNumericVersion majorVersion, + @NotNull SimpleNumericVersion minorVersion, + @Nullable SimpleNumericVersion patchVersion) { super(majorVersion, minorVersion, patchVersion); } @@ -29,10 +30,13 @@ public class MinecraftGameVersion extends MajorMinorPatchVersion { /** * Returns whether the Minecraft version is at least equal to or higher than a target version - * @param majorVerNumber target major version number - for example 1.16.5 , the 1 is the major version - * @param minorVerNumber target minor version number - for example 1.16.5, the 16 is the minor version - * @param patchVerNumber target patch version number - for example 1.16.5, the 5 is the patch version number * + * @param majorVerNumber target major version number - for example 1.16.5 , the 1 is the major + * version + * @param minorVerNumber target minor version number - for example 1.16.5, the 16 is the minor + * version + * @param patchVerNumber target patch version number - for example 1.16.5, the 5 is the patch + * version number * @return returns true if Minecraft is at least a certain version */ public boolean isAtLeast(int majorVerNumber, int minorVerNumber, int patchVerNumber) { diff --git a/src/main/java/com/gmail/nossr50/util/platform/Platform.java b/src/main/java/com/gmail/nossr50/util/platform/Platform.java index 7a6c81395..b9c5cda7e 100644 --- a/src/main/java/com/gmail/nossr50/util/platform/Platform.java +++ b/src/main/java/com/gmail/nossr50/util/platform/Platform.java @@ -4,27 +4,28 @@ import com.gmail.nossr50.util.compat.CompatibilityManager; import org.jetbrains.annotations.NotNull; /** - * - * These classes are a band-aid solution for adding NMS support into 2.1.XXX - * In 2.2 we are switching to modules and that will clean things up significantly - * + * These classes are a band-aid solution for adding NMS support into 2.1.XXX In 2.2 we are switching + * to modules and that will clean things up significantly */ public interface Platform { /** * Target {@link ServerSoftwareType} for this {@link Platform} + * * @return the {@link ServerSoftwareType} for this {@link Platform} */ @NotNull ServerSoftwareType getServerSoftwareType(); /** * Get the {@link CompatibilityManager} for this {@link Platform} + * * @return the {@link CompatibilityManager} for this platform */ @NotNull CompatibilityManager getCompatibilityManager(); /** * The target game version of this {@link Platform} + * * @return the target {@link MinecraftGameVersion} of this {@link Platform} */ @NotNull MinecraftGameVersion getGameVersion(); diff --git a/src/main/java/com/gmail/nossr50/util/platform/PlatformBuilder.java b/src/main/java/com/gmail/nossr50/util/platform/PlatformBuilder.java index 733bf58a0..7cafd8a2f 100644 --- a/src/main/java/com/gmail/nossr50/util/platform/PlatformBuilder.java +++ b/src/main/java/com/gmail/nossr50/util/platform/PlatformBuilder.java @@ -4,10 +4,8 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** - * - * These classes are a band-aid solution for adding NMS support into 2.1.XXX - * In 2.2 we are switching to modules and that will clean things up significantly - * + * These classes are a band-aid solution for adding NMS support into 2.1.XXX In 2.2 we are switching + * to modules and that will clean things up significantly */ public class PlatformBuilder { private MinecraftGameVersion minecraftGameVersion; @@ -17,7 +15,8 @@ public class PlatformBuilder { } - public PlatformBuilder setMinecraftGameVersion(@NotNull MinecraftGameVersion minecraftGameVersion) { + public PlatformBuilder setMinecraftGameVersion( + @NotNull MinecraftGameVersion minecraftGameVersion) { this.minecraftGameVersion = minecraftGameVersion; return this; } diff --git a/src/main/java/com/gmail/nossr50/util/platform/PlatformManager.java b/src/main/java/com/gmail/nossr50/util/platform/PlatformManager.java index a638dabfd..f14e95f78 100644 --- a/src/main/java/com/gmail/nossr50/util/platform/PlatformManager.java +++ b/src/main/java/com/gmail/nossr50/util/platform/PlatformManager.java @@ -3,19 +3,16 @@ package com.gmail.nossr50.util.platform; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.LogUtils; import com.gmail.nossr50.util.compat.CompatibilityManager; +import java.util.Locale; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.bukkit.Bukkit; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Locale; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - /** - * - * These classes are a band-aid solution for adding NMS support into 2.1.XXX - * In 2.2 we are switching to modules and that will clean things up significantly - * + * These classes are a band-aid solution for adding NMS support into 2.1.XXX In 2.2 we are switching + * to modules and that will clean things up significantly */ public class PlatformManager { protected Platform platform; //current platform @@ -51,7 +48,8 @@ public class PlatformManager { LogUtils.debug(mcMMO.p.getLogger(), "Platform String: " + platformVersionString); // Gets two numbers separated by . and optional third number after next dot. Must end with - or _ - Matcher versionMatch = Pattern.compile("(\\d+)\\.(\\d+)(?:\\.(\\d+))?[-_].*").matcher(platformVersionString); + Matcher versionMatch = Pattern.compile("(\\d+)\\.(\\d+)(?:\\.(\\d+))?[-_].*") + .matcher(platformVersionString); if (versionMatch.find()) { major = Integer.parseInt(versionMatch.group(1)); @@ -72,12 +70,13 @@ public class PlatformManager { //TODO: Rewrite this properly once we actually support a not-bukkit platform private @NotNull ServerSoftwareType determinePlatformType() { - if (Bukkit.getVersion().toLowerCase(Locale.ENGLISH).contains("paper")) + if (Bukkit.getVersion().toLowerCase(Locale.ENGLISH).contains("paper")) { return ServerSoftwareType.PAPER; - else if (Bukkit.getVersion().toLowerCase(Locale.ENGLISH).contains("spigot")) + } else if (Bukkit.getVersion().toLowerCase(Locale.ENGLISH).contains("spigot")) { return ServerSoftwareType.SPIGOT; - else + } else { return ServerSoftwareType.CRAFT_BUKKIT; + } } public ServerSoftwareType getServerSoftware() { 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 1cfb89f41..357272029 100644 --- a/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java +++ b/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java @@ -15,6 +15,7 @@ import com.gmail.nossr50.util.sounds.SoundManager; import com.gmail.nossr50.util.sounds.SoundType; import com.gmail.nossr50.util.text.McMMOMessageType; import com.gmail.nossr50.util.text.TextComponentFactory; +import java.time.LocalDate; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.identity.Identity; import net.kyori.adventure.text.Component; @@ -29,93 +30,111 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.time.LocalDate; - public class NotificationManager { public static final String HEX_BEIGE_COLOR = "#c2a66e"; public static final String HEX_LIME_GREEN_COLOR = "#8ec26e"; /** - * Sends players notifications from mcMMO - * Does so by sending out an event so other plugins can cancel it + * Sends players notifications from mcMMO Does so by sending out an event so other plugins can + * cancel it + * * @param player target player * @param notificationType notifications defined type * @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; + } McMMOMessageType destination = mcMMO.p.getAdvancedConfig().doesNotificationUseActionBar(notificationType) ? McMMOMessageType.ACTION_BAR : McMMOMessageType.SYSTEM; Component message = TextComponentFactory.getNotificationTextComponentFromLocale(key); - McMMOPlayerNotificationEvent customEvent = checkNotificationEvent(player, notificationType, destination, message); + McMMOPlayerNotificationEvent customEvent = checkNotificationEvent(player, notificationType, + destination, message); sendNotification(player, customEvent); } public static boolean doesPlayerUseNotifications(Player player) { - if (UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) { return false; - else + } else { return UserManager.getPlayer(player).useChatNotifications(); + } } /** - * 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 + * 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 targetPlayer the recipient player for this message * @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 */ - public static void sendNearbyPlayersInformation(Player targetPlayer, NotificationType notificationType, String key, - String... values) { + public static void sendNearbyPlayersInformation(Player targetPlayer, + NotificationType notificationType, String key, + String... values) { sendPlayerInformation(targetPlayer, notificationType, key, values); } public static void sendPlayerInformationChatOnly(Player player, String key, String... values) { - if (UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) + if (UserManager.getPlayer(player) == null || !UserManager.getPlayer(player) + .useChatNotifications()) { return; + } String preColoredString = LocaleLoader.getString(key, (Object[]) values); player.sendMessage(preColoredString); } - public static void sendPlayerInformationChatOnlyPrefixed(Player player, String key, String... values) { - if (UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) + public static void sendPlayerInformationChatOnlyPrefixed(Player player, String key, + String... values) { + if (UserManager.getPlayer(player) == null || !UserManager.getPlayer(player) + .useChatNotifications()) { return; + } String preColoredString = LocaleLoader.getString(key, (Object[]) values); - String prefixFormattedMessage = LocaleLoader.getString("mcMMO.Template.Prefix", preColoredString); + String prefixFormattedMessage = LocaleLoader.getString("mcMMO.Template.Prefix", + preColoredString); player.sendMessage(prefixFormattedMessage); } - 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; + } - McMMOMessageType destination = mcMMO.p.getAdvancedConfig().doesNotificationUseActionBar(notificationType) ? McMMOMessageType.ACTION_BAR : McMMOMessageType.SYSTEM; + McMMOMessageType destination = + mcMMO.p.getAdvancedConfig().doesNotificationUseActionBar(notificationType) + ? McMMOMessageType.ACTION_BAR : McMMOMessageType.SYSTEM; Component message = TextComponentFactory.getNotificationMultipleValues(key, values); - McMMOPlayerNotificationEvent customEvent = checkNotificationEvent(player, notificationType, destination, message); + McMMOPlayerNotificationEvent customEvent = checkNotificationEvent(player, notificationType, + destination, message); sendNotification(player, customEvent); } private static void sendNotification(Player player, McMMOPlayerNotificationEvent customEvent) { - if (customEvent.isCancelled()) + if (customEvent.isCancelled()) { return; + } final Audience audience = mcMMO.getAudiences().player(player); - Component notificationTextComponent = customEvent.getNotificationTextComponent(); if (customEvent.getChatMessageType() == McMMOMessageType.ACTION_BAR) { audience.sendActionBar(notificationTextComponent); @@ -130,9 +149,10 @@ public class NotificationManager { } } - private static McMMOPlayerNotificationEvent checkNotificationEvent(Player player, NotificationType notificationType, - McMMOMessageType destination, - Component message) { + private static McMMOPlayerNotificationEvent checkNotificationEvent(Player player, + NotificationType notificationType, + McMMOMessageType destination, + Component message) { //Init event McMMOPlayerNotificationEvent customEvent = new McMMOPlayerNotificationEvent(player, notificationType, message, destination, @@ -144,63 +164,75 @@ public class NotificationManager { } /** - * Handles sending level up notifications to a mcMMOPlayer - * @param mcMMOPlayer target mcMMOPlayer + * Handles sending level up notifications to a mmoPlayer + * + * @param mmoPlayer target mmoPlayer * @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 mmoPlayer, + PrimarySkillType skillName, + int levelsGained, int newLevel) { + if (!mmoPlayer.useChatNotifications()) { return; + } McMMOMessageType destination - = mcMMO.p.getAdvancedConfig().doesNotificationUseActionBar(NotificationType.LEVEL_UP_MESSAGE) + = mcMMO.p.getAdvancedConfig() + .doesNotificationUseActionBar(NotificationType.LEVEL_UP_MESSAGE) ? McMMOMessageType.ACTION_BAR : McMMOMessageType.SYSTEM; Component levelUpTextComponent = TextComponentFactory.getNotificationLevelUpTextComponent( skillName, levelsGained, newLevel); McMMOPlayerNotificationEvent customEvent = checkNotificationEvent( - mcMMOPlayer.getPlayer(), + mmoPlayer.getPlayer(), NotificationType.LEVEL_UP_MESSAGE, destination, levelUpTextComponent); - sendNotification(mcMMOPlayer.getPlayer(), customEvent); + sendNotification(mmoPlayer.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 mmoPlayer, + SubSkillType subSkillType) { + if (!mmoPlayer.useChatNotifications()) { return; + } //CHAT MESSAGE - mcMMO.getAudiences().player(mcMMOPlayer.getPlayer()).sendMessage(Identity.nil(), - TextComponentFactory.getSubSkillUnlockedNotificationComponents(mcMMOPlayer.getPlayer(), subSkillType)); + mcMMO.getAudiences().player(mmoPlayer.getPlayer()).sendMessage(Identity.nil(), + TextComponentFactory.getSubSkillUnlockedNotificationComponents( + mmoPlayer.getPlayer(), subSkillType)); //Unlock Sound Effect - SoundManager.sendCategorizedSound(mcMMOPlayer.getPlayer(), mcMMOPlayer.getPlayer().getLocation(), + SoundManager.sendCategorizedSound(mmoPlayer.getPlayer(), + mmoPlayer.getPlayer().getLocation(), SoundType.SKILL_UNLOCKED, SoundCategory.MASTER); } /** - * Sends a message to all admins with the admin notification formatting from the locale - * Admins are currently players with either Operator status or Admin Chat permission + * Sends a message to all admins with the admin notification formatting from the locale Admins + * are currently players with either Operator status or Admin Chat permission + * * @param msg message fetched from locale */ private static void sendAdminNotification(String msg) { //If its not enabled exit - if (!mcMMO.p.getGeneralConfig().adminNotifications()) + if (!mcMMO.p.getGeneralConfig().adminNotifications()) { return; + } - for(Player player : Bukkit.getServer().getOnlinePlayers()) { + for (Player player : Bukkit.getServer().getOnlinePlayers()) { if (player.isOp() || Permissions.adminChat(player)) { - player.sendMessage(LocaleLoader.getString("Notifications.Admin.Format.Others", msg)); + player.sendMessage( + LocaleLoader.getString("Notifications.Admin.Format.Others", msg)); } } @@ -210,6 +242,7 @@ public class NotificationManager { /** * Sends a confirmation message to the CommandSender who just executed an admin command + * * @param commandSender target command sender * @param msg message fetched from locale */ @@ -219,11 +252,12 @@ public class NotificationManager { /** * Convenience method to report info about a command sender using a sensitive command + * * @param commandSender the command user * @param sensitiveCommandType type of command issued */ public static void processSensitiveCommandNotification(CommandSender commandSender, - SensitiveCommandType sensitiveCommandType, String... args) { + SensitiveCommandType sensitiveCommandType, String... args) { /* * Determine the 'identity' of the one who executed the command to pass as a parameters */ @@ -235,12 +269,14 @@ public class NotificationManager { } //Send the notification - switch(sensitiveCommandType) { + switch (sensitiveCommandType) { case XPRATE_MODIFY: - sendAdminNotification(LocaleLoader.getString("Notifications.Admin.XPRate.Start.Others", - addItemToFirstPositionOfArray(senderName, args))); + sendAdminNotification( + LocaleLoader.getString("Notifications.Admin.XPRate.Start.Others", + addItemToFirstPositionOfArray(senderName, args))); sendAdminCommandConfirmation( - commandSender, LocaleLoader.getString("Notifications.Admin.XPRate.Start.Self", args)); + commandSender, + LocaleLoader.getString("Notifications.Admin.XPRate.Start.Self", args)); break; case XPRATE_END: sendAdminNotification( @@ -254,13 +290,18 @@ public class NotificationManager { } /** - * Takes an array and an object, makes a new array with object in the first position of the new array, - * and the following elements in this new array being a copy of the existing array retaining their order + * Takes an array and an object, makes a new array with object in the first position of the new + * array, and the following elements in this new array being a copy of the existing array + * retaining their order + * * @param itemToAdd the string to put at the beginning of the new array - * @param existingArray the existing array to be copied to the new array at position [0]+1 relative to their original index - * @return the new array combining itemToAdd at the start and existing array elements following while retaining their order + * @param existingArray the existing array to be copied to the new array at position [0]+1 + * relative to their original index + * @return the new array combining itemToAdd at the start and existing array elements following + * while retaining their order */ - public static String[] addItemToFirstPositionOfArray(String itemToAdd, String... existingArray) { + public static String[] addItemToFirstPositionOfArray(String itemToAdd, + String... existingArray) { String[] newArray = new String[existingArray.length + 1]; newArray[0] = itemToAdd; @@ -269,9 +310,11 @@ public class NotificationManager { return newArray; } - public static void processLevelUpBroadcasting(@NotNull McMMOPlayer mmoPlayer, @NotNull PrimarySkillType primarySkillType, int level) { - if (level <= 0) + public static void processLevelUpBroadcasting(@NotNull McMMOPlayer mmoPlayer, + @NotNull PrimarySkillType primarySkillType, int level) { + if (level <= 0) { return; + } //Check if broadcasting is enabled if (mcMMO.p.getGeneralConfig().shouldLevelUpBroadcasts()) { @@ -285,19 +328,23 @@ public class NotificationManager { if (remainder == 0) { //Grab appropriate audience - Audience audience = mcMMO.getAudiences().filter(getLevelUpBroadcastPredicate(mmoPlayer.getPlayer())); + Audience audience = mcMMO.getAudiences() + .filter(getLevelUpBroadcastPredicate(mmoPlayer.getPlayer())); //TODO: Make prettier - HoverEvent levelMilestoneHover = Component.text(mmoPlayer.getPlayer().getName()) + HoverEvent levelMilestoneHover = Component.text( + mmoPlayer.getPlayer().getName()) .append(Component.newline()) .append(Component.text(LocalDate.now().toString())) .append(Component.newline()) .append(Component.text( mcMMO.p.getSkillTools().getLocalizedSkillName(primarySkillType) - + " reached level "+level)).color(TextColor.fromHexString(HEX_BEIGE_COLOR)) + + " reached level " + level)) + .color(TextColor.fromHexString(HEX_BEIGE_COLOR)) .asHoverEvent(); String localeMessage = LocaleLoader.getString( - "Broadcasts.LevelUpMilestone", mmoPlayer.getPlayer().getDisplayName(), level, + "Broadcasts.LevelUpMilestone", mmoPlayer.getPlayer().getDisplayName(), + level, mcMMO.p.getSkillTools().getLocalizedSkillName(primarySkillType)); Component component = LegacyComponentSerializer .legacySection() @@ -313,9 +360,11 @@ public class NotificationManager { //TODO: Remove the code duplication, am lazy atm //TODO: Fix broadcasts being skipped for situations where a player skips over the milestone like with the addlevels command - public static void processPowerLevelUpBroadcasting(@NotNull McMMOPlayer mmoPlayer, int powerLevel) { - if (powerLevel <= 0) + public static void processPowerLevelUpBroadcasting(@NotNull McMMOPlayer mmoPlayer, + int powerLevel) { + if (powerLevel <= 0) { return; + } //Check if broadcasting is enabled if (mcMMO.p.getGeneralConfig().shouldPowerLevelUpBroadcasts()) { @@ -329,29 +378,37 @@ public class NotificationManager { if (remainder == 0) { //Grab appropriate audience - Audience audience = mcMMO.getAudiences().filter(getPowerLevelUpBroadcastPredicate(mmoPlayer.getPlayer())); + Audience audience = mcMMO.getAudiences() + .filter(getPowerLevelUpBroadcastPredicate(mmoPlayer.getPlayer())); //TODO: Make prettier - HoverEvent levelMilestoneHover = Component.text(mmoPlayer.getPlayer().getName()) + HoverEvent levelMilestoneHover = Component.text( + mmoPlayer.getPlayer().getName()) .append(Component.newline()) .append(Component.text(LocalDate.now().toString())) .append(Component.newline()) - .append(Component.text("Power level has reached "+powerLevel)).color(TextColor.fromHexString(HEX_BEIGE_COLOR)) + .append(Component.text("Power level has reached " + powerLevel)) + .color(TextColor.fromHexString(HEX_BEIGE_COLOR)) .asHoverEvent(); - String localeMessage = LocaleLoader.getString("Broadcasts.PowerLevelUpMilestone", mmoPlayer.getPlayer().getDisplayName(), powerLevel); - Component message = LegacyComponentSerializer.legacySection().deserialize(localeMessage).hoverEvent(levelMilestoneHover); + String localeMessage = LocaleLoader.getString("Broadcasts.PowerLevelUpMilestone", + mmoPlayer.getPlayer().getDisplayName(), powerLevel); + Component message = LegacyComponentSerializer.legacySection() + .deserialize(localeMessage).hoverEvent(levelMilestoneHover); - mcMMO.p.getFoliaLib().getScheduler().runNextTick(t -> audience.sendMessage(message)); + mcMMO.p.getFoliaLib().getScheduler() + .runNextTick(t -> audience.sendMessage(message)); } } } //TODO: Could cache - public static @NotNull LevelUpBroadcastPredicate getLevelUpBroadcastPredicate(@NotNull CommandSender levelUpPlayer) { + public static @NotNull LevelUpBroadcastPredicate getLevelUpBroadcastPredicate( + @NotNull CommandSender levelUpPlayer) { return new LevelUpBroadcastPredicate<>(levelUpPlayer); } - public static @NotNull PowerLevelUpBroadcastPredicate getPowerLevelUpBroadcastPredicate(@NotNull CommandSender levelUpPlayer) { + public static @NotNull PowerLevelUpBroadcastPredicate getPowerLevelUpBroadcastPredicate( + @NotNull CommandSender levelUpPlayer) { return new PowerLevelUpBroadcastPredicate<>(levelUpPlayer); } diff --git a/src/main/java/com/gmail/nossr50/util/player/PlayerLevelUtils.java b/src/main/java/com/gmail/nossr50/util/player/PlayerLevelUtils.java index 5a0d5f3de..d1ec0ea6c 100644 --- a/src/main/java/com/gmail/nossr50/util/player/PlayerLevelUtils.java +++ b/src/main/java/com/gmail/nossr50/util/player/PlayerLevelUtils.java @@ -35,13 +35,17 @@ public class PlayerLevelUtils { } /** - * Check if a player is currently qualifying for the early game boosted XP - * Will return false only if a player is above the boost level cutoff, it does not check config settings to see if the early game boost is on - * @param mcMMOPlayer target player + * Check if a player is currently qualifying for the early game boosted XP Will return false + * only if a player is above the boost level cutoff, it does not check config settings to see if + * the early game boost is on + * + * @param mmoPlayer target player * @param primarySkillType target skill * @return if the player would qualify for the XP boost if its enabled */ - public static boolean qualifiesForEarlyGameBoost(McMMOPlayer mcMMOPlayer, PrimarySkillType primarySkillType) { - return mcMMOPlayer.getSkillLevel(primarySkillType) < mcMMO.getPlayerLevelUtils().getEarlyGameCutoff(primarySkillType); + public static boolean qualifiesForEarlyGameBoost(McMMOPlayer mmoPlayer, + PrimarySkillType primarySkillType) { + return mmoPlayer.getSkillLevel(primarySkillType) < mcMMO.getPlayerLevelUtils() + .getEarlyGameCutoff(primarySkillType); } } 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 04457d103..5d8a64408 100644 --- a/src/main/java/com/gmail/nossr50/util/player/UserManager.java +++ b/src/main/java/com/gmail/nossr50/util/player/UserManager.java @@ -5,6 +5,9 @@ import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.LogUtils; import com.gmail.nossr50.util.MetadataConstants; import com.google.common.collect.ImmutableList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; @@ -12,33 +15,33 @@ import org.bukkit.metadata.FixedMetadataValue; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; - public final class UserManager { private static HashSet playerDataSet; //Used to track players for sync saves on shutdown - private UserManager() {} + private UserManager() { + } /** * Track a new user. * - * @param mcMMOPlayer the player profile to start tracking + * @param mmoPlayer the player profile to start tracking */ - public static void track(@NotNull McMMOPlayer mcMMOPlayer) { - mcMMOPlayer.getPlayer().setMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA, new FixedMetadataValue(mcMMO.p, mcMMOPlayer)); + public static void track(@NotNull McMMOPlayer mmoPlayer) { + mmoPlayer.getPlayer().setMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA, + new FixedMetadataValue(mcMMO.p, mmoPlayer)); - if (playerDataSet == null) + if (playerDataSet == null) { playerDataSet = new HashSet<>(); + } - playerDataSet.add(mcMMOPlayer); //for sync saves on shutdown + playerDataSet.add(mmoPlayer); //for sync saves on shutdown } - public static void cleanupPlayer(McMMOPlayer mcMMOPlayer) { - if (playerDataSet != null) - playerDataSet.remove(mcMMOPlayer); + public static void cleanupPlayer(McMMOPlayer mmoPlayer) { + if (playerDataSet != null) { + playerDataSet.remove(mmoPlayer); + } } /** @@ -47,16 +50,17 @@ public final class UserManager { * @param player The Player object */ public static void remove(@NotNull Player player) { - McMMOPlayer mcMMOPlayer = getPlayer(player); + final McMMOPlayer mmoPlayer = getPlayer(player); - if (mcMMOPlayer == null) + if (mmoPlayer == null) { return; + } - mcMMOPlayer.cleanup(); + mmoPlayer.cleanup(); player.removeMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA, mcMMO.p); if (playerDataSet != null) { - playerDataSet.remove(mcMMOPlayer); //Clear sync save tracking + playerDataSet.remove(mmoPlayer); //Clear sync save tracking } } @@ -68,32 +72,36 @@ public final class UserManager { remove(player); } - if (playerDataSet != null) + if (playerDataSet != null) { playerDataSet.clear(); //Clear sync save tracking + } } /** * Save all users ON THIS THREAD. */ public static void saveAll() { - if (playerDataSet == null) + if (playerDataSet == null) { return; + } ImmutableList trackedSyncData = ImmutableList.copyOf(playerDataSet); - mcMMO.p.getLogger().info("Saving mcMMOPlayers... (" + trackedSyncData.size() + ")"); + mcMMO.p.getLogger().info("Saving mmoPlayers... (" + trackedSyncData.size() + ")"); for (McMMOPlayer playerData : trackedSyncData) { try { - LogUtils.debug(mcMMO.p.getLogger(), "Saving data for player: "+playerData.getPlayerName()); + LogUtils.debug(mcMMO.p.getLogger(), + "Saving data for player: " + playerData.getPlayerName()); playerData.getProfile().save(true); - } - catch (Exception e) { - mcMMO.p.getLogger().warning("Could not save mcMMO player data for player: " + playerData.getPlayerName()); + } catch (Exception e) { + mcMMO.p.getLogger().warning("Could not save mcMMO player data for player: " + + playerData.getPlayerName()); } } - mcMMO.p.getLogger().info("Finished save operation for "+trackedSyncData.size()+" players!"); + mcMMO.p.getLogger() + .info("Finished save operation for " + trackedSyncData.size() + " players!"); } public static @NotNull Collection getPlayers() { @@ -131,27 +139,34 @@ public final class UserManager { } /** - * Gets the McMMOPlayer object for a player, this can be null if the player has not yet been loaded. + * 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 @Nullable McMMOPlayer getPlayer(@Nullable Player player) { //Avoid Array Index out of bounds - if (player != null && player.hasMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA)) - return (McMMOPlayer) player.getMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA).get(0).value(); - else + if (player != null && player.hasMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA)) { + return (McMMOPlayer) player.getMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA) + .get(0).value(); + } else { return null; + } } - private static @Nullable McMMOPlayer retrieveMcMMOPlayer(@Nullable String playerName, boolean offlineValid) { - if (playerName == null) + private static @Nullable McMMOPlayer retrieveMcMMOPlayer(@Nullable String playerName, + boolean offlineValid) { + if (playerName == null) { return null; + } Player player = mcMMO.p.getServer().getPlayerExact(playerName); if (player == null) { if (!offlineValid) { - mcMMO.p.getLogger().warning("A valid mcMMOPlayer object could not be found for " + playerName + "."); + mcMMO.p.getLogger().warning( + "A valid mmoPlayer object could not be found for " + playerName + "."); } return null; diff --git a/src/main/java/com/gmail/nossr50/util/random/Probability.java b/src/main/java/com/gmail/nossr50/util/random/Probability.java index 6873371a2..ca63ced3f 100644 --- a/src/main/java/com/gmail/nossr50/util/random/Probability.java +++ b/src/main/java/com/gmail/nossr50/util/random/Probability.java @@ -1,9 +1,7 @@ package com.gmail.nossr50.util.random; -import com.gmail.nossr50.api.exceptions.ValueOutOfBoundsException; -import org.jetbrains.annotations.NotNull; - import java.util.concurrent.ThreadLocalRandom; +import org.jetbrains.annotations.NotNull; public interface Probability { /** @@ -17,33 +15,21 @@ public interface Probability { Probability ALWAYS_SUCCEEDS = () -> 1; /** - * The value of this Probability - * Should return a result between 0 and 1 (inclusive) - * A value of 1 or greater represents something that will always succeed - * A value of around 0.5 represents something that succeeds around half the time - * A value of 0 represents something that will always fail - * - * @return the value of probability - */ - double getValue(); - - /** - * Create a new Probability of a percentage. - * This method takes a percentage and creates a Probability of equivalent odds. - * - * A value of 100 would represent 100% chance of success, - * A value of 50 would represent 50% chance of success, - * A value of 0 would represent 0% chance of success, - * A value of 1 would represent 1% chance of success, - * A value of 0.5 would represent 0.5% chance of success, - * A value of 0.01 would represent 0.01% chance of success. + * Create a new Probability of a percentage. This method takes a percentage and creates a + * Probability of equivalent odds. + *

+ * A value of 100 would represent 100% chance of success, A value of 50 would represent 50% + * chance of success, A value of 0 would represent 0% chance of success, A value of 1 would + * represent 1% chance of success, A value of 0.5 would represent 0.5% chance of success, A + * value of 0.01 would represent 0.01% chance of success. * * @param percentage the value of the probability * @return a new Probability with the given value */ static @NotNull Probability ofPercent(double percentage) { if (percentage < 0) { - throw new ValueOutOfBoundsException("Value should never be negative for Probability! This suggests a coding mistake, contact the devs!"); + throw new IllegalArgumentException( + "Value should never be negative for Probability! This suggests a coding mistake, contact the devs!"); } // Convert to a 0-1 floating point representation @@ -52,11 +38,11 @@ public interface Probability { } /** - * Create a new Probability of a value. - * This method takes a value between 0 and 1 and creates a Probability of equivalent odds. - * A value of 1 or greater represents something that will always succeed. - * A value of around 0.5 represents something that succeeds around half the time. - * A value of 0 represents something that will always fail. + * Create a new Probability of a value. This method takes a value between 0 and 1 and creates a + * Probability of equivalent odds. A value of 1 or greater represents something that will always + * succeed. A value of around 0.5 represents something that succeeds around half the time. A + * value of 0 represents something that will always fail. + * * @param value the value of the probability * @return a new Probability with the given value */ @@ -65,8 +51,8 @@ public interface Probability { } /** - * Simulates a "roll of the dice" - * If the value passed is higher than the "random" value, than it is a successful roll + * Simulates a "roll of the dice" If the value passed is higher than the "random" value, than it + * is a successful roll * * @param probabilityValue probability value * @return true for succeeding, false for failing @@ -75,6 +61,16 @@ public interface Probability { return (probabilityValue) >= ThreadLocalRandom.current().nextDouble(1D); } + /** + * The value of this Probability Should return a result between 0 and 1 (inclusive) A value of 1 + * or greater represents something that will always succeed A value of around 0.5 represents + * something that succeeds around half the time A value of 0 represents something that will + * always fail + * + * @return the value of probability + */ + double getValue(); + /** * Simulate an outcome on a probability and return true or false for the result of that outcome * @@ -85,9 +81,11 @@ public interface Probability { } /** - * Modify and then Simulate an outcome on a probability and return true or false for the result of that outcome + * Modify and then Simulate an outcome on a probability and return true or false for the result + * of that outcome * - * @param probabilityMultiplier probability will be multiplied by this before success is checked + * @param probabilityMultiplier probability will be multiplied by this before success is + * checked * @return true if the probability succeeded, false if it failed */ default boolean evaluate(double probabilityMultiplier) { @@ -96,11 +94,13 @@ public interface Probability { } /** - * Modify and then Simulate an outcome on a probability and return true or false for the result of that outcome. + * Modify and then Simulate an outcome on a probability and return true or false for the result + * of that outcome. * - * @param probabilityMultiplier probability will be multiplied by this before success is checked - * @param finalProbabilityMultiplier probability will be multiplied by this after the first multiplier, - * should be between 0 and 1 + * @param probabilityMultiplier probability will be multiplied by this before success is + * checked + * @param finalProbabilityMultiplier probability will be multiplied by this after the first + * multiplier, should be between 0 and 1 * @return true if the probability succeeded, false if it failed */ default boolean evaluate(double probabilityMultiplier, double finalProbabilityMultiplier) { diff --git a/src/main/java/com/gmail/nossr50/util/random/ProbabilityImpl.java b/src/main/java/com/gmail/nossr50/util/random/ProbabilityImpl.java index b62110567..2ada7236b 100644 --- a/src/main/java/com/gmail/nossr50/util/random/ProbabilityImpl.java +++ b/src/main/java/com/gmail/nossr50/util/random/ProbabilityImpl.java @@ -1,6 +1,5 @@ package com.gmail.nossr50.util.random; -import com.gmail.nossr50.api.exceptions.ValueOutOfBoundsException; import com.google.common.base.Objects; public class ProbabilityImpl implements Probability { @@ -8,18 +7,15 @@ public class ProbabilityImpl implements Probability { private final double probabilityValue; /** - * Create a probability from a static value. - * A value of 0 represents a 0% chance of success, - * A value of 1 represents a 100% chance of success. - * A value of 0.5 represents a 50% chance of success. - * A value of 0.01 represents a 1% chance of success. - * And so on. + * Create a probability from a static value. A value of 0 represents a 0% chance of success, A + * value of 1 represents a 100% chance of success. A value of 0.5 represents a 50% chance of + * success. A value of 0.01 represents a 1% chance of success. And so on. * * @param value the value of the probability between 0 and 100 */ - public ProbabilityImpl(double value) throws ValueOutOfBoundsException { + public ProbabilityImpl(double value) throws IllegalArgumentException { if (value < 0) { - throw new ValueOutOfBoundsException("Value should never be negative for Probability!" + + throw new IndexOutOfBoundsException("Value should never be negative for Probability!" + " This suggests a coding mistake, contact the devs!"); } @@ -33,15 +29,17 @@ public class ProbabilityImpl implements Probability { @Override public String toString() { - return "ProbabilityImpl{" + - "probabilityValue=" + probabilityValue + - '}'; + return "ProbabilityImpl{" + "probabilityValue=" + probabilityValue + '}'; } @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } ProbabilityImpl that = (ProbabilityImpl) o; return Double.compare(that.probabilityValue, probabilityValue) == 0; } diff --git a/src/main/java/com/gmail/nossr50/util/random/ProbabilityUtil.java b/src/main/java/com/gmail/nossr50/util/random/ProbabilityUtil.java index 8e25ac34b..5bc7b7b96 100644 --- a/src/main/java/com/gmail/nossr50/util/random/ProbabilityUtil.java +++ b/src/main/java/com/gmail/nossr50/util/random/ProbabilityUtil.java @@ -1,5 +1,7 @@ package com.gmail.nossr50.util.random; +import static java.util.Objects.requireNonNull; + import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; @@ -8,19 +10,17 @@ import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.EventUtils; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.UserManager; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.Locale; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.VisibleForTesting; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.util.Locale; - -import static java.util.Objects.requireNonNull; - public class ProbabilityUtil { - public static final @NotNull DecimalFormat percent = new DecimalFormat("##0.00%", DecimalFormatSymbols.getInstance(Locale.US)); + public static final @NotNull DecimalFormat percent = new DecimalFormat("##0.00%", + DecimalFormatSymbols.getInstance(Locale.US)); public static final double LUCKY_MODIFIER = 1.333D; /** @@ -29,20 +29,21 @@ public class ProbabilityUtil { * @param player target player * @param subSkillType target subskill * @param isLucky whether to apply luck modifiers - * * @return "percentage" representation of success - * @deprecated use {@link #chanceOfSuccessPercentage(McMMOPlayer, SubSkillType, boolean)} instead + * @deprecated use {@link #chanceOfSuccessPercentage(McMMOPlayer, SubSkillType, boolean)} + * instead */ @Deprecated(forRemoval = true, since = "2.2.010") public static double chanceOfSuccessPercentage(@Nullable Player player, - @NotNull SubSkillType subSkillType, - boolean isLucky) { - return chanceOfSuccessPercentage(requireNonNull(UserManager.getPlayer(player)), subSkillType, isLucky); + @NotNull SubSkillType subSkillType, + boolean isLucky) { + return chanceOfSuccessPercentage(requireNonNull(UserManager.getPlayer(player)), + subSkillType, isLucky); } public static double chanceOfSuccessPercentage(@Nullable McMMOPlayer mmoPlayer, - @NotNull SubSkillType subSkillType, - boolean isLucky) { + @NotNull SubSkillType subSkillType, + boolean isLucky) { final Probability probability = getSubSkillProbability(subSkillType, mmoPlayer); //Probability values are on a 0-1 scale and need to be "transformed" into a 1-100 scale double percentageValue = probability.getValue(); //Doesn't need to be scaled @@ -62,7 +63,8 @@ public class ProbabilityUtil { * @param isLucky whether to apply luck modifiers * @return a double as a "percentage" representation of success */ - public static double chanceOfSuccessPercentage(@NotNull Probability probability, boolean isLucky) { + public static double chanceOfSuccessPercentage(@NotNull Probability probability, + boolean isLucky) { //Probability values are on a 0-1 scale and need to be "transformed" into a 1-100 scale double percentageValue = probability.getValue(); @@ -75,11 +77,15 @@ public class ProbabilityUtil { } @VisibleForTesting - static Probability getStaticRandomChance(@NotNull SubSkillType subSkillType) throws InvalidStaticChance { + static Probability getStaticRandomChance(@NotNull SubSkillType subSkillType) + throws InvalidStaticChance { return switch (subSkillType) { - case AXES_ARMOR_IMPACT -> Probability.ofPercent(mcMMO.p.getAdvancedConfig().getImpactChance()); - case AXES_GREATER_IMPACT -> Probability.ofPercent(mcMMO.p.getAdvancedConfig().getGreaterImpactChance()); - case TAMING_FAST_FOOD_SERVICE -> Probability.ofPercent(mcMMO.p.getAdvancedConfig().getFastFoodChance()); + case AXES_ARMOR_IMPACT -> + Probability.ofPercent(mcMMO.p.getAdvancedConfig().getImpactChance()); + case AXES_GREATER_IMPACT -> + Probability.ofPercent(mcMMO.p.getAdvancedConfig().getGreaterImpactChance()); + case TAMING_FAST_FOOD_SERVICE -> + Probability.ofPercent(mcMMO.p.getAdvancedConfig().getFastFoodChance()); default -> throw new InvalidStaticChance(); }; } @@ -89,19 +95,22 @@ public class ProbabilityUtil { if (subSkillType == SubSkillType.TAMING_FAST_FOOD_SERVICE || subSkillType == SubSkillType.AXES_ARMOR_IMPACT - || subSkillType == SubSkillType.AXES_GREATER_IMPACT) + || subSkillType == SubSkillType.AXES_GREATER_IMPACT) { skillProbabilityType = SkillProbabilityType.STATIC_CONFIGURABLE; + } return skillProbabilityType; } @Deprecated(forRemoval = true, since = "2.2.010") - private static @NotNull Probability ofSubSkill(@Nullable Player player, @NotNull SubSkillType subSkillType) { + private static @NotNull Probability ofSubSkill(@Nullable Player player, + @NotNull SubSkillType subSkillType) { // no null check needed here return ofSubSkill(UserManager.getPlayer(player), subSkillType); } - private static @NotNull Probability ofSubSkill(@Nullable McMMOPlayer mmoPlayer, @NotNull SubSkillType subSkillType) { + private static @NotNull Probability ofSubSkill(@Nullable McMMOPlayer mmoPlayer, + @NotNull SubSkillType subSkillType) { switch (getProbabilityType(subSkillType)) { case DYNAMIC_CONFIGURABLE: double probabilityCeiling; @@ -115,10 +124,12 @@ public class ProbabilityUtil { } //Probability ceiling is configurable in this type - probabilityCeiling = mcMMO.p.getAdvancedConfig().getMaximumProbability(subSkillType); + probabilityCeiling = mcMMO.p.getAdvancedConfig() + .getMaximumProbability(subSkillType); //The xCeiling is configurable in this type maxBonusLevel = mcMMO.p.getAdvancedConfig().getMaxBonusLevel(subSkillType); - return calculateCurrentSkillProbability(skillLevel, 0, probabilityCeiling, maxBonusLevel); + return calculateCurrentSkillProbability(skillLevel, 0, probabilityCeiling, + maxBonusLevel); case STATIC_CONFIGURABLE: try { return getStaticRandomChance(subSkillType); @@ -126,62 +137,71 @@ public class ProbabilityUtil { throw new RuntimeException(invalidStaticChance); } default: - throw new IllegalStateException("No case in switch statement for Skill Probability Type!"); + throw new IllegalStateException( + "No case in switch statement for Skill Probability Type!"); } } /** - * This is one of several Skill RNG check methods - * This helper method is for specific {@link SubSkillType}, which help mcMMO understand where the RNG values used in our calculations come from this {@link SubSkillType} + * This is one of several Skill RNG check methods This helper method is for specific + * {@link SubSkillType}, which help mcMMO understand where the RNG values used in our + * calculations come from this {@link SubSkillType} *

- * 1) Determine where the RNG values come from for the passed {@link SubSkillType} - * NOTE: In the config file, there are values which are static and which are more dynamic, this is currently a bit hardcoded and will need to be updated manually + * 1) Determine where the RNG values come from for the passed {@link SubSkillType} NOTE: In the + * config file, there are values which are static and which are more dynamic, this is currently + * a bit hardcoded and will need to be updated manually *

* 2) Determine whether to use Lucky multiplier and influence the outcome *

- * 3) Creates a {@link Probability} and pipes it to {@link ProbabilityUtil} which processes the result and returns it + * 3) Creates a {@link Probability} and pipes it to {@link ProbabilityUtil} which processes the + * result and returns it *

- * This also calls a {@link SubSkillEvent} which can be cancelled, if it is cancelled this will return false - * The outcome of the probability can also be modified by this event that is called + * This also calls a {@link SubSkillEvent} which can be cancelled, if it is cancelled this will + * return false The outcome of the probability can also be modified by this event that is + * called * * @param subSkillType target subskill - * @param player target player - * can be null (null players are given odds equivalent to a player with no levels or luck) + * @param player target player can be null (null players are given odds equivalent to a player + * with no levels or luck) * @return true if the Skill RNG succeeds, false if it fails * @deprecated use {@link #isSkillRNGSuccessful(SubSkillType, McMMOPlayer)} instead */ @Deprecated(forRemoval = true, since = "2.2.010") - public static boolean isSkillRNGSuccessful(@NotNull SubSkillType subSkillType, @Nullable Player player) { + public static boolean isSkillRNGSuccessful(@NotNull SubSkillType subSkillType, + @Nullable Player player) { return isSkillRNGSuccessful(subSkillType, UserManager.getPlayer(player)); } /** - * This is one of several Skill RNG check methods - * This helper method is for specific {@link SubSkillType}, - * which help mcMMO understand where the RNG values used in our calculations come from this {@link SubSkillType} + * This is one of several Skill RNG check methods This helper method is for specific + * {@link SubSkillType}, which help mcMMO understand where the RNG values used in our + * calculations come from this {@link SubSkillType} *

- * 1) Determine where the RNG values come from for the passed {@link SubSkillType} - * NOTE: In the config file, there are values which are static and which are more dynamic, - * this is currently a bit hardcoded and will need to be updated manually + * 1) Determine where the RNG values come from for the passed {@link SubSkillType} NOTE: In the + * config file, there are values which are static and which are more dynamic, this is currently + * a bit hardcoded and will need to be updated manually *

* 2) Determine whether to use Lucky multiplier and influence the outcome *

- * 3) - * Creates a {@link Probability} and pipes it to {@link ProbabilityUtil} which processes the result and returns it + * 3) Creates a {@link Probability} and pipes it to {@link ProbabilityUtil} which processes the + * result and returns it *

- * This also calls a {@link SubSkillEvent} which can be cancelled, if it is cancelled this will return false - * The outcome of the probability can also be modified by this event that is called + * This also calls a {@link SubSkillEvent} which can be cancelled, if it is cancelled this will + * return false The outcome of the probability can also be modified by this event that is + * called * * @param subSkillType target subskill - * @param mmoPlayer target player - * can be null (null players are given odds equivalent to a player with no levels or luck) + * @param mmoPlayer target player can be null (null players are given odds equivalent to a + * player with no levels or luck) * @return true if the Skill RNG succeeds, false if it fails */ - public static boolean isSkillRNGSuccessful(@NotNull SubSkillType subSkillType, @Nullable McMMOPlayer mmoPlayer) { + public static boolean isSkillRNGSuccessful(@NotNull SubSkillType subSkillType, + @Nullable McMMOPlayer mmoPlayer) { final Probability probability = getSkillProbability(subSkillType, mmoPlayer); //Luck - boolean isLucky = mmoPlayer != null && Permissions.lucky(mmoPlayer.getPlayer(), subSkillType.getParentSkill()); + boolean isLucky = mmoPlayer != null && Permissions.lucky(mmoPlayer.getPlayer(), + subSkillType.getParentSkill()); if (isLucky) { return probability.evaluate(LUCKY_MODIFIER); @@ -191,36 +211,39 @@ public class ProbabilityUtil { } /** - * This is one of several Skill RNG evaluation methods. - * This one specifically allows for a probability multiplier to be passed in. - * This probability multiplier is applied after any lucky modifiers, affecting the final result. + * This is one of several Skill RNG evaluation methods. This one specifically allows for a + * probability multiplier to be passed in. This probability multiplier is applied after any + * lucky modifiers, affecting the final result. *

- * This helper method is for specific {@link SubSkillType}, - * which help mcMMO understand where the RNG values used in our calculations come from this {@link SubSkillType} + * This helper method is for specific {@link SubSkillType}, which help mcMMO understand where + * the RNG values used in our calculations come from this {@link SubSkillType} *

- * 1) Determine where the RNG values come from for the passed {@link SubSkillType} - * NOTE: In the config file, there are values which are static and which are more dynamic, - * this is currently a bit hardcoded and will need to be updated manually + * 1) Determine where the RNG values come from for the passed {@link SubSkillType} NOTE: In the + * config file, there are values which are static and which are more dynamic, this is currently + * a bit hardcoded and will need to be updated manually *

* 2) Determine whether to use Lucky multiplier and influence the outcome *

- * 3) - * Creates a {@link Probability} and pipes it to {@link ProbabilityUtil} which processes the result and returns it + * 3) Creates a {@link Probability} and pipes it to {@link ProbabilityUtil} which processes the + * result and returns it *

- * This also calls a {@link SubSkillEvent} which can be cancelled, if it is cancelled this will return false - * The outcome of the probability can also be modified by this event that is called + * This also calls a {@link SubSkillEvent} which can be cancelled, if it is cancelled this will + * return false The outcome of the probability can also be modified by this event that is + * called * * @param subSkillType target subskill - * @param mmoPlayer target player - * can be null (null players are given odds equivalent to a player with no levels or luck) + * @param mmoPlayer target player can be null (null players are given odds equivalent to a + * player with no levels or luck) * @return true if the Skill RNG succeeds, false if it fails */ - public static boolean isSkillRNGSuccessful(@NotNull SubSkillType subSkillType, @Nullable McMMOPlayer mmoPlayer, - double probabilityMultiplier) { + public static boolean isSkillRNGSuccessful(@NotNull SubSkillType subSkillType, + @Nullable McMMOPlayer mmoPlayer, + double probabilityMultiplier) { final Probability probability = getSkillProbability(subSkillType, mmoPlayer); //Luck - boolean isLucky = mmoPlayer != null && Permissions.lucky(mmoPlayer.getPlayer(), subSkillType.getParentSkill()); + boolean isLucky = mmoPlayer != null && Permissions.lucky(mmoPlayer.getPlayer(), + subSkillType.getParentSkill()); if (isLucky) { return probability.evaluate(LUCKY_MODIFIER, probabilityMultiplier); @@ -230,34 +253,34 @@ public class ProbabilityUtil { } /** - * Returns the {@link Probability} for a specific {@link SubSkillType} for a specific {@link Player}. - * This does not take into account perks such as lucky for the player. - * This is affected by other plugins who can listen to the {@link SubSkillEvent} and cancel it or mutate it. - * Null players will be treated as zero skill players. + * Returns the {@link Probability} for a specific {@link SubSkillType} for a specific + * {@link Player}. This does not take into account perks such as lucky for the player. This is + * affected by other plugins who can listen to the {@link SubSkillEvent} and cancel it or mutate + * it. Null players will be treated as zero skill players. * * @param subSkillType the target subskill - * @param player the target player - * can be null (null players have the worst odds) + * @param player the target player can be null (null players have the worst odds) * @return the probability for this skill * @deprecated use {@link #getSkillProbability(SubSkillType, McMMOPlayer)} instead */ @Deprecated(forRemoval = true) - public static Probability getSkillProbability(@NotNull SubSkillType subSkillType, @Nullable Player player) { + public static Probability getSkillProbability(@NotNull SubSkillType subSkillType, + @Nullable Player player) { return getSkillProbability(subSkillType, UserManager.getPlayer(player)); } /** - * Returns the {@link Probability} for a specific {@link SubSkillType} for a specific {@link Player}. - * This does not take into account perks such as lucky for the player. - * This is affected by other plugins who can listen to the {@link SubSkillEvent} and cancel it or mutate it. - * Null players will be treated as zero skill players. + * Returns the {@link Probability} for a specific {@link SubSkillType} for a specific + * {@link Player}. This does not take into account perks such as lucky for the player. This is + * affected by other plugins who can listen to the {@link SubSkillEvent} and cancel it or mutate + * it. Null players will be treated as zero skill players. * * @param subSkillType the target subskill - * @param mmoPlayer the target player - * can be null (null players have the worst odds) + * @param mmoPlayer the target player can be null (null players have the worst odds) * @return the probability for this skill */ - public static Probability getSkillProbability(@NotNull SubSkillType subSkillType, @Nullable McMMOPlayer mmoPlayer) { + public static Probability getSkillProbability(@NotNull SubSkillType subSkillType, + @Nullable McMMOPlayer mmoPlayer) { // Process probability Probability probability = getSubSkillProbability(subSkillType, mmoPlayer); @@ -273,39 +296,45 @@ public class ProbabilityUtil { double resultModifier = subSkillEvent.getResultModifier(); // Mutate probability - if (resultModifier != 1.0D) + if (resultModifier != 1.0D) { probability = Probability.ofPercent(probability.getValue() * resultModifier); + } } return probability; } /** - * This is one of several Skill RNG check methods - * This helper method is specific to static value RNG, which can be influenced by a player's Luck + * This is one of several Skill RNG check methods This helper method is specific to static value + * RNG, which can be influenced by a player's Luck * * @param primarySkillType the related primary skill * @param player the target player can be null (null players have the worst odds) - * @param probabilityPercentage the probability of this player succeeding in "percentage" format (0-100 inclusive) + * @param probabilityPercentage the probability of this player succeeding in "percentage" format + * (0-100 inclusive) * @return true if the RNG succeeds, false if it fails - * @deprecated use {@link #isStaticSkillRNGSuccessful(PrimarySkillType, McMMOPlayer, double)} instead + * @deprecated use {@link #isStaticSkillRNGSuccessful(PrimarySkillType, McMMOPlayer, double)} + * instead */ @Deprecated(forRemoval = true, since = "2.2.010") - public static boolean isStaticSkillRNGSuccessful(@NotNull PrimarySkillType primarySkillType, @Nullable Player player, double probabilityPercentage) { - return isStaticSkillRNGSuccessful(primarySkillType, player, Probability.ofPercent(probabilityPercentage)); + public static boolean isStaticSkillRNGSuccessful(@NotNull PrimarySkillType primarySkillType, + @Nullable Player player, double probabilityPercentage) { + return isStaticSkillRNGSuccessful(primarySkillType, player, + Probability.ofPercent(probabilityPercentage)); } /** - * This is one of several Skill RNG check methods - * This helper method is specific to static value RNG, which can be influenced by a player's Luck + * This is one of several Skill RNG check methods This helper method is specific to static value + * RNG, which can be influenced by a player's Luck * * @param primarySkillType the related primary skill * @param mmoPlayer the target player can be null (null players have the worst odds) - * @param probabilityPercentage the probability of this player succeeding in "percentage" format (0-100 inclusive) + * @param probabilityPercentage the probability of this player succeeding in "percentage" format + * (0-100 inclusive) * @return true if the RNG succeeds, false if it fails */ public static boolean isStaticSkillRNGSuccessful(@NotNull PrimarySkillType primarySkillType, - @Nullable McMMOPlayer mmoPlayer, double probabilityPercentage) { + @Nullable McMMOPlayer mmoPlayer, double probabilityPercentage) { //Grab a probability converted from a "percentage" value final Probability probability = Probability.ofPercent(probabilityPercentage); @@ -313,36 +342,37 @@ public class ProbabilityUtil { } /** - * This is one of several Skill RNG check methods - * This helper method is specific to static value RNG, which can be influenced by a player's Luck + * This is one of several Skill RNG check methods This helper method is specific to static value + * RNG, which can be influenced by a player's Luck * * @param primarySkillType the related primary skill - * @param player the target player - * can be null (null players have the worst odds) + * @param player the target player can be null (null players have the worst odds) * @param probability the probability of this player succeeding * @return true if the RNG succeeds, false if it fails - * @deprecated use {@link #isStaticSkillRNGSuccessful(PrimarySkillType, McMMOPlayer, Probability)} instead, this + * @deprecated use + * {@link #isStaticSkillRNGSuccessful(PrimarySkillType, McMMOPlayer, Probability)} instead, this * method is redundant and will be removed. */ @Deprecated(forRemoval = true, since = "2.2.010") public static boolean isStaticSkillRNGSuccessful(@NotNull PrimarySkillType primarySkillType, - @Nullable Player player, @NotNull Probability probability) { - return isStaticSkillRNGSuccessful(primarySkillType, UserManager.getPlayer(player), probability); + @Nullable Player player, @NotNull Probability probability) { + return isStaticSkillRNGSuccessful(primarySkillType, UserManager.getPlayer(player), + probability); } /** - * This is one of several Skill RNG check methods - * This helper method is specific to static value RNG, which can be influenced by a mmoPlayer's Luck + * This is one of several Skill RNG check methods This helper method is specific to static value + * RNG, which can be influenced by a mmoPlayer's Luck * * @param primarySkillType the related primary skill - * @param mmoPlayer the target mmoPlayer - * can be null (null players have the worst odds) + * @param mmoPlayer the target mmoPlayer can be null (null players have the worst odds) * @param probability the probability of this mmoPlayer succeeding * @return true if the RNG succeeds, false if it fails */ public static boolean isStaticSkillRNGSuccessful(@NotNull PrimarySkillType primarySkillType, - @Nullable McMMOPlayer mmoPlayer, @NotNull Probability probability) { - boolean isLucky = mmoPlayer != null && Permissions.lucky(mmoPlayer.getPlayer(), primarySkillType); + @Nullable McMMOPlayer mmoPlayer, @NotNull Probability probability) { + boolean isLucky = + mmoPlayer != null && Permissions.lucky(mmoPlayer.getPlayer(), primarySkillType); if (isLucky) { return probability.evaluate(LUCKY_MODIFIER); @@ -353,58 +383,63 @@ public class ProbabilityUtil { /** * Skills activate without RNG, this allows other plugins to prevent that activation + * * @param subSkillType target subskill * @param player target player * @return true if the skill succeeds (wasn't cancelled by any other plugin) * @deprecated use {@link #isNonRNGSkillActivationSuccessful(SubSkillType, McMMOPlayer)} instead */ @Deprecated(forRemoval = true, since = "2.2.010") - public static boolean isNonRNGSkillActivationSuccessful(@NotNull SubSkillType subSkillType, @NotNull Player player) { - return isNonRNGSkillActivationSuccessful(subSkillType, requireNonNull(UserManager.getPlayer(player))); + public static boolean isNonRNGSkillActivationSuccessful(@NotNull SubSkillType subSkillType, + @NotNull Player player) { + return isNonRNGSkillActivationSuccessful(subSkillType, + requireNonNull(UserManager.getPlayer(player))); } /** * Skills activate without RNG, this allows other plugins to prevent that activation + * * @param subSkillType target subskill * @param mmoPlayer target player * @return true if the skill succeeds (wasn't cancelled by any other plugin) */ public static boolean isNonRNGSkillActivationSuccessful(@NotNull SubSkillType subSkillType, - @NotNull McMMOPlayer mmoPlayer) { + @NotNull McMMOPlayer mmoPlayer) { return !EventUtils.callSubSkillEvent(mmoPlayer, subSkillType).isCancelled(); } /** - * Retrieves the {@link Probability} of success for a specified {@link SubSkillType} for a given {@link Player}. + * Retrieves the {@link Probability} of success for a specified {@link SubSkillType} for a given + * {@link Player}. * * @param subSkillType The targeted subskill. - * @param player The player in question. - * If null, the method treats it as a player with no levels or luck and calculates the probability - * accordingly. + * @param player The player in question. If null, the method treats it as a player with no + * levels or luck and calculates the probability accordingly. * @return The probability that the specified skill will succeed. * @deprecated use {@link #getSubSkillProbability(SubSkillType, McMMOPlayer)} instead */ @Deprecated(forRemoval = true, since = "2.2.010") public static @NotNull Probability getSubSkillProbability(@NotNull SubSkillType subSkillType, - @Nullable Player player) { + @Nullable Player player) { return ProbabilityUtil.ofSubSkill(player, subSkillType); } /** - * Retrieves the {@link Probability} of success for a specified {@link SubSkillType} for a given {@link Player}. + * Retrieves the {@link Probability} of success for a specified {@link SubSkillType} for a given + * {@link Player}. * * @param subSkillType The targeted subskill. - * @param mmoPlayer The player in question. - * If null, the method treats it as a player with no levels or luck and calculates the probability - * accordingly. + * @param mmoPlayer The player in question. If null, the method treats it as a player with no + * levels or luck and calculates the probability accordingly. * @return The probability that the specified skill will succeed. */ public static @NotNull Probability getSubSkillProbability(@NotNull SubSkillType subSkillType, - @Nullable McMMOPlayer mmoPlayer) { + @Nullable McMMOPlayer mmoPlayer) { return ProbabilityUtil.ofSubSkill(mmoPlayer, subSkillType); } - public static @NotNull String[] getRNGDisplayValues(@Nullable McMMOPlayer mmoPlayer, @NotNull SubSkillType subSkill) { + public static @NotNull String[] getRNGDisplayValues(@Nullable McMMOPlayer mmoPlayer, + @NotNull SubSkillType subSkill) { double firstValue = chanceOfSuccessPercentage(mmoPlayer, subSkill, false); double secondValue = chanceOfSuccessPercentage(mmoPlayer, subSkill, true); @@ -420,15 +455,16 @@ public class ProbabilityUtil { /** * Helper function to calculate what probability a given skill has at a certain level + * * @param skillLevel the skill level currently between the floor and the ceiling * @param floor the minimum odds this skill can have * @param ceiling the maximum odds this skill can have * @param maxBonusLevel the maximum level this skill can have to reach the ceiling - * * @return the probability of success for this skill at this level */ public static Probability calculateCurrentSkillProbability(double skillLevel, double floor, - double ceiling, double maxBonusLevel) { + double ceiling, + double maxBonusLevel) { // The odds of success are between the value of the floor and the value of the ceiling. // If the skill has a maxBonusLevel of 500 on this skill, then at skill level 500 you would have the full odds, // at skill level 250 it would be half odds. 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 7bb64188d..8531edab6 100644 --- a/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardManager.java +++ b/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardManager.java @@ -15,6 +15,11 @@ import com.gmail.nossr50.util.player.UserManager; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; @@ -24,8 +29,6 @@ import org.bukkit.scoreboard.Scoreboard; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; - /** * Manages the Scoreboards used to display a variety of mcMMO related information to the player */ @@ -37,7 +40,8 @@ public class ScoreboardManager { static final String POWER_OBJECTIVE = "mcmmo_pwrlvl"; static final String HEADER_STATS = LocaleLoader.getString("Scoreboard.Header.PlayerStats"); - static final String HEADER_COOLDOWNS = LocaleLoader.getString("Scoreboard.Header.PlayerCooldowns"); + static final String HEADER_COOLDOWNS = LocaleLoader.getString( + "Scoreboard.Header.PlayerCooldowns"); static final String HEADER_RANK = LocaleLoader.getString("Scoreboard.Header.PlayerRank"); static final String TAG_POWER_LEVEL = LocaleLoader.getString("Scoreboard.Header.PowerLevel"); @@ -50,7 +54,7 @@ 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; @@ -94,13 +98,19 @@ public class ScoreboardManager { int i = 0; for (PrimarySkillType primarySkillType : PrimarySkillType.values()) { // Include child skills - skillLabelBuilder.put(primarySkillType, getShortenedName(colors.get(i) + mcMMO.p.getSkillTools().getLocalizedSkillName(primarySkillType), false)); + skillLabelBuilder.put(primarySkillType, getShortenedName( + colors.get(i) + mcMMO.p.getSkillTools() + .getLocalizedSkillName(primarySkillType), false)); if (mcMMO.p.getSkillTools().getSuperAbility(primarySkillType) != null) { - abilityLabelBuilder.put(mcMMO.p.getSkillTools().getSuperAbility(primarySkillType), getShortenedName(colors.get(i) + mcMMO.p.getSkillTools().getSuperAbility(primarySkillType).getLocalizedName())); + abilityLabelBuilder.put( + mcMMO.p.getSkillTools().getSuperAbility(primarySkillType), + getShortenedName(colors.get(i) + mcMMO.p.getSkillTools() + .getSuperAbility(primarySkillType).getLocalizedName())); if (primarySkillType == PrimarySkillType.MINING) { - abilityLabelBuilder.put(SuperAbilityType.BLAST_MINING, getShortenedName(colors.get(i) + SuperAbilityType.BLAST_MINING.getLocalizedName())); + abilityLabelBuilder.put(SuperAbilityType.BLAST_MINING, getShortenedName( + colors.get(i) + SuperAbilityType.BLAST_MINING.getLocalizedName())); } } @@ -116,20 +126,28 @@ public class ScoreboardManager { else { for (PrimarySkillType primarySkillType : PrimarySkillType.values()) { // Include child skills - skillLabelBuilder.put(primarySkillType, getShortenedName(ChatColor.GREEN + mcMMO.p.getSkillTools().getLocalizedSkillName(primarySkillType))); + skillLabelBuilder.put(primarySkillType, getShortenedName( + ChatColor.GREEN + mcMMO.p.getSkillTools() + .getLocalizedSkillName(primarySkillType))); if (mcMMO.p.getSkillTools().getSuperAbility(primarySkillType) != null) { - abilityLabelBuilder.put(mcMMO.p.getSkillTools().getSuperAbility(primarySkillType), formatAbility(mcMMO.p.getSkillTools().getSuperAbility(primarySkillType).getLocalizedName())); + abilityLabelBuilder.put( + mcMMO.p.getSkillTools().getSuperAbility(primarySkillType), + formatAbility(mcMMO.p.getSkillTools().getSuperAbility(primarySkillType) + .getLocalizedName())); if (primarySkillType == PrimarySkillType.MINING) { - abilityLabelBuilder.put(SuperAbilityType.BLAST_MINING, formatAbility(SuperAbilityType.BLAST_MINING.getLocalizedName())); + abilityLabelBuilder.put(SuperAbilityType.BLAST_MINING, + formatAbility(SuperAbilityType.BLAST_MINING.getLocalizedName())); } } } } for (SuperAbilityType type : SuperAbilityType.values()) { - abilityLabelSkillBuilder.put(type, formatAbility((type == SuperAbilityType.BLAST_MINING ? ChatColor.BLUE : ChatColor.AQUA), type.getLocalizedName())); + abilityLabelSkillBuilder.put(type, formatAbility( + (type == SuperAbilityType.BLAST_MINING ? ChatColor.BLUE : ChatColor.AQUA), + type.getLocalizedName())); } skillLabels = skillLabelBuilder.build(); @@ -184,13 +202,15 @@ public class ScoreboardManager { // Called by PlayerQuitEvent listener and OnPlayerTeleport under certain circumstances public static void teardownPlayer(Player player) { - if (player == null) + if (player == null) { return; + } //Hacky world blacklist fix if (player.isOnline() && player.isValid()) { - if (Bukkit.getServer().getScoreboardManager() != null) + if (Bukkit.getServer().getScoreboardManager() != null) { player.setScoreboard(Bukkit.getServer().getScoreboardManager().getMainScoreboard()); + } } if (getWrapper(player) != null) { @@ -203,8 +223,10 @@ public class ScoreboardManager { // Called in onDisable() public static void teardownAll() { - ImmutableList onlinePlayers = ImmutableList.copyOf(mcMMO.p.getServer().getOnlinePlayers()); - LogUtils.debug(mcMMO.p.getLogger(), "Tearing down scoreboards... (" + onlinePlayers.size() + ")"); + ImmutableList onlinePlayers = ImmutableList.copyOf( + mcMMO.p.getServer().getOnlinePlayers()); + LogUtils.debug(mcMMO.p.getLogger(), + "Tearing down scoreboards... (" + onlinePlayers.size() + ")"); for (Player player : onlinePlayers) { teardownPlayer(player); } @@ -230,7 +252,8 @@ public class ScoreboardManager { } if (wrapper != null) { - if ((wrapper.isSkillScoreboard() && wrapper.targetSkill == skill) || (wrapper.isStatsScoreboard()) && wrapper.isBoardShown()) { + if ((wrapper.isSkillScoreboard() && wrapper.targetSkill == skill) + || (wrapper.isStatsScoreboard()) && wrapper.isBoardShown()) { wrapper.doSidebarUpdateSoon(); } @@ -238,12 +261,14 @@ public class ScoreboardManager { String playerName = player.getName(); for (ScoreboardWrapper iWrapper : PLAYER_SCOREBOARDS.values()) { - if (iWrapper.isStatsScoreboard() && playerName.equals(iWrapper.targetPlayer) && wrapper.isBoardShown()) { + if (iWrapper.isStatsScoreboard() && playerName.equals(iWrapper.targetPlayer) + && wrapper.isBoardShown()) { wrapper.doSidebarUpdateSoon(); } } - if (mcMMO.p.getGeneralConfig().getPowerLevelTagsEnabled() && !dirtyPowerLevels.contains(playerName)) { + if (mcMMO.p.getGeneralConfig().getPowerLevelTagsEnabled() && !dirtyPowerLevels.contains( + playerName)) { dirtyPowerLevels.add(playerName); } @@ -259,7 +284,8 @@ public class ScoreboardManager { // Selfboards ScoreboardWrapper wrapper = getWrapper(player); - if (wrapper != null && wrapper.isSkillScoreboard() && wrapper.targetSkill == skill && wrapper.isBoardShown()) { + if (wrapper != null && wrapper.isSkillScoreboard() && wrapper.targetSkill == skill + && wrapper.isBoardShown()) { wrapper.doSidebarUpdateSoon(); } } @@ -275,7 +301,9 @@ public class ScoreboardManager { } if (wrapper != null) { - if ((wrapper.isCooldownScoreboard() || wrapper.isSkillScoreboard() && wrapper.targetSkill == skill) && wrapper.isBoardShown()) { + if ((wrapper.isCooldownScoreboard() + || wrapper.isSkillScoreboard() && wrapper.targetSkill == skill) + && wrapper.isBoardShown()) { wrapper.doSidebarUpdateSoon(); } } @@ -284,7 +312,7 @@ public class ScoreboardManager { // **** Setup methods **** // public static void enablePlayerSkillScoreboard(Player player, PrimarySkillType skill) { - McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); mmoPlayer.setLastSkillShownScoreboard(skill); ScoreboardWrapper wrapper = getWrapper(player); @@ -303,7 +331,7 @@ public class ScoreboardManager { } public static void retryLastSkillBoard(Player player) { - McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); PrimarySkillType primarySkillType = mmoPlayer.getLastSkillShownScoreboard(); ScoreboardWrapper wrapper = getWrapper(player); @@ -327,8 +355,9 @@ public class ScoreboardManager { // Do NOT run if already shown if (wrapper != null && wrapper.isBoardShown()) { - if (wrapper.isBoardShown()) + if (wrapper.isBoardShown()) { return; + } wrapper.setOldScoreboard(); wrapper.setTypeSkill(skill); @@ -339,9 +368,9 @@ public class ScoreboardManager { public static void enablePlayerStatsScoreboard(Player player) { ScoreboardWrapper wrapper = getWrapper(player); - if (wrapper == null) + if (wrapper == null) { return; - + } wrapper.setOldScoreboard(); wrapper.setTypeSelfStats(); @@ -349,7 +378,8 @@ public class ScoreboardManager { changeScoreboard(wrapper, mcMMO.p.getGeneralConfig().getStatsScoreboardTime()); } - public static void enablePlayerInspectScoreboard(@NotNull Player player, @NotNull PlayerProfile targetProfile) { + public static void enablePlayerInspectScoreboard(@NotNull Player player, + @NotNull PlayerProfile targetProfile) { ScoreboardWrapper wrapper = getWrapper(player); if (wrapper == null) { @@ -365,7 +395,8 @@ public class ScoreboardManager { } } - public static void enablePlayerInspectScoreboard(@NotNull Player player, @NotNull McMMOPlayer targetMcMMOPlayer) { + public static void enablePlayerInspectScoreboard(@NotNull Player player, + @NotNull McMMOPlayer targetMcMMOPlayer) { ScoreboardWrapper wrapper = getWrapper(player); if (wrapper == null) { @@ -397,7 +428,8 @@ public class ScoreboardManager { } } - public static void showPlayerRankScoreboard(Player player, Map rank) { + public static void showPlayerRankScoreboard(Player player, + Map rank) { ScoreboardWrapper wrapper = getWrapper(player); if (wrapper == null) { @@ -414,7 +446,8 @@ public class ScoreboardManager { } } - public static void showPlayerRankScoreboardOthers(Player player, String targetName, Map rank) { + public static void showPlayerRankScoreboardOthers(Player player, String targetName, + Map rank) { ScoreboardWrapper wrapper = getWrapper(player); if (wrapper == null) { @@ -431,7 +464,8 @@ public class ScoreboardManager { } } - public static void showTopScoreboard(Player player, PrimarySkillType skill, int pageNumber, List stats) { + public static void showTopScoreboard(Player player, PrimarySkillType skill, int pageNumber, + List stats) { ScoreboardWrapper wrapper = getWrapper(player); @@ -449,7 +483,8 @@ public class ScoreboardManager { } } - public static void showTopPowerScoreboard(Player player, int pageNumber, List stats) { + public static void showTopPowerScoreboard(Player player, int pageNumber, + List stats) { ScoreboardWrapper wrapper = getWrapper(player); if (wrapper == null) { @@ -487,14 +522,14 @@ public class ScoreboardManager { } for (String playerName : dirtyPowerLevels) { - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(playerName); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(playerName); - if (mcMMOPlayer == null) { + if (mmoPlayer == null) { continue; } - Player player = mcMMOPlayer.getPlayer(); - int power = mcMMOPlayer.getPowerLevel(); + Player player = mmoPlayer.getPlayer(); + int power = mmoPlayer.getPowerLevel(); mainObjective.getScore(playerName).setScore(power); @@ -510,34 +545,38 @@ public class ScoreboardManager { /** * Gets or creates the power level objective on the main targetBoard. *

- * If power levels are disabled, the objective is deleted and null is - * returned. + * If power levels are disabled, the objective is deleted and null is returned. * * @return the main targetBoard objective, or null if disabled */ public static @Nullable Objective getPowerLevelObjective() { if (!mcMMO.p.getGeneralConfig().getPowerLevelTagsEnabled()) { - if (getScoreboardManager() == null) + if (getScoreboardManager() == null) { return null; + } - Objective objective = getScoreboardManager().getMainScoreboard().getObjective(POWER_OBJECTIVE); + Objective objective = getScoreboardManager().getMainScoreboard() + .getObjective(POWER_OBJECTIVE); if (objective != null) { objective.unregister(); - LogUtils.debug(mcMMO.p.getLogger(), "Removed leftover targetBoard objects from Power Level Tags."); + LogUtils.debug(mcMMO.p.getLogger(), + "Removed leftover targetBoard objects from Power Level Tags."); } return null; } - - if (getScoreboardManager() == null) + if (getScoreboardManager() == null) { return null; + } - Objective powerObjective = getScoreboardManager().getMainScoreboard().getObjective(POWER_OBJECTIVE); + Objective powerObjective = getScoreboardManager().getMainScoreboard() + .getObjective(POWER_OBJECTIVE); if (powerObjective == null) { - powerObjective = getScoreboardManager().getMainScoreboard().registerNewObjective(POWER_OBJECTIVE, "dummy", DISPLAY_NAME); + powerObjective = getScoreboardManager().getMainScoreboard() + .registerNewObjective(POWER_OBJECTIVE, "dummy", DISPLAY_NAME); powerObjective.setDisplayName(TAG_POWER_LEVEL); powerObjective.setDisplaySlot(DisplaySlot.BELOW_NAME); } @@ -545,7 +584,8 @@ public class ScoreboardManager { return powerObjective; } - public @Nullable static org.bukkit.scoreboard.ScoreboardManager getScoreboardManager() { + public @Nullable + static org.bukkit.scoreboard.ScoreboardManager getScoreboardManager() { return mcMMO.p.getServer().getScoreboardManager(); } @@ -570,7 +610,8 @@ public class ScoreboardManager { } public static void setRevertTimer(String playerName, int seconds) { - PLAYER_SCOREBOARDS.get(playerName).showBoardAndScheduleRevert(seconds * Misc.TICK_CONVERSION_FACTOR); + PLAYER_SCOREBOARDS.get(playerName) + .showBoardAndScheduleRevert(seconds * Misc.TICK_CONVERSION_FACTOR); } public static boolean isPlayerBoardSetup(@NotNull String playerName) { @@ -578,12 +619,14 @@ public class ScoreboardManager { } public static @Nullable ScoreboardWrapper makeNewScoreboard(Player player) { - if (getScoreboardManager() == null) + if (getScoreboardManager() == null) { return null; + } //Call our custom event Scoreboard scoreboard = getScoreboardManager().getNewScoreboard(); - McMMOScoreboardMakeboardEvent event = new McMMOScoreboardMakeboardEvent(scoreboard, player.getScoreboard(), player, ScoreboardEventReason.CREATING_NEW_SCOREBOARD); + McMMOScoreboardMakeboardEvent event = new McMMOScoreboardMakeboardEvent(scoreboard, + player.getScoreboard(), player, ScoreboardEventReason.CREATING_NEW_SCOREBOARD); player.getServer().getPluginManager().callEvent(event); //Use the values from the event return new ScoreboardWrapper(event.getTargetPlayer(), event.getTargetBoard()); 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 bc22d2baa..01ee569f9 100644 --- a/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardWrapper.java +++ b/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardWrapper.java @@ -1,5 +1,7 @@ package com.gmail.nossr50.util.scoreboards; +import static java.util.Objects.requireNonNull; + import com.gmail.nossr50.datatypes.database.PlayerStat; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.PlayerProfile; @@ -18,6 +20,8 @@ import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.scoreboards.ScoreboardManager.SidebarType; import com.gmail.nossr50.util.skills.SkillTools; import com.tcoded.folialib.wrapper.task.WrappedTask; +import java.util.List; +import java.util.Map; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.scoreboard.DisplaySlot; @@ -26,11 +30,6 @@ import org.bukkit.scoreboard.Score; import org.bukkit.scoreboard.Scoreboard; import org.jetbrains.annotations.NotNull; -import java.util.List; -import java.util.Map; - -import static java.util.Objects.requireNonNull; - public class ScoreboardWrapper { public static final String SIDE_OBJECTIVE = "mcMMO_sideObjective"; public static final String POWER_OBJECTIVE = "mcMMO_powerObjective"; @@ -69,8 +68,10 @@ public class ScoreboardWrapper { powerObjective = scoreboard.getObjective(ScoreboardManager.POWER_OBJECTIVE); } else { //Register Objectives - sidebarObjective = this.scoreboard.registerNewObjective(ScoreboardManager.SIDEBAR_OBJECTIVE, "dummy", SIDE_OBJECTIVE); - powerObjective = this.scoreboard.registerNewObjective(ScoreboardManager.POWER_OBJECTIVE, "dummy", POWER_OBJECTIVE); + sidebarObjective = this.scoreboard.registerNewObjective( + ScoreboardManager.SIDEBAR_OBJECTIVE, "dummy", SIDE_OBJECTIVE); + powerObjective = this.scoreboard.registerNewObjective(ScoreboardManager.POWER_OBJECTIVE, + "dummy", POWER_OBJECTIVE); registered = true; } @@ -78,8 +79,9 @@ public class ScoreboardWrapper { powerObjective.setDisplayName(ScoreboardManager.TAG_POWER_LEVEL); powerObjective.setDisplaySlot(DisplaySlot.BELOW_NAME); - for (McMMOPlayer mcMMOPlayer : UserManager.getPlayers()) { - powerObjective.getScore(mcMMOPlayer.getProfile().getPlayerName()).setScore(mcMMOPlayer.getPowerLevel()); + for (McMMOPlayer mmoPlayer : UserManager.getPlayers()) { + powerObjective.getScore(mmoPlayer.getProfile().getPlayerName()) + .setScore(mmoPlayer.getPowerLevel()); } } } @@ -122,7 +124,8 @@ public class ScoreboardWrapper { public void doSidebarUpdateSoon() { if (updateTask == null) { // To avoid spamming the scheduler, store the instance and run 2 ticks later - updateTask = mcMMO.p.getFoliaLib().getScheduler().runAtEntityLater(player, new ScoreboardQuickUpdate(), 2L); + updateTask = mcMMO.p.getFoliaLib().getScheduler() + .runAtEntityLater(player, new ScoreboardQuickUpdate(), 2L); } } @@ -130,7 +133,9 @@ public class ScoreboardWrapper { if (cooldownTask == null) { // Repeat every 5 seconds. // Cancels once all cooldowns are done, using stopCooldownUpdating(). - cooldownTask = mcMMO.p.getFoliaLib().getScheduler().runAtEntityTimer(player, new ScoreboardCooldownTask(), 5 * Misc.TICK_CONVERSION_FACTOR, 5 * Misc.TICK_CONVERSION_FACTOR); + cooldownTask = mcMMO.p.getFoliaLib().getScheduler() + .runAtEntityTimer(player, new ScoreboardCooldownTask(), + 5 * Misc.TICK_CONVERSION_FACTOR, 5 * Misc.TICK_CONVERSION_FACTOR); } } @@ -138,8 +143,7 @@ public class ScoreboardWrapper { if (cooldownTask != null) { try { cooldownTask.cancel(); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } @@ -175,8 +179,9 @@ public class ScoreboardWrapper { if (previousBoard == scoreboard) { // Already displaying it if (this.oldBoard == null) { // (Shouldn't happen) Use failsafe value - we're already displaying our board, but we don't have the one we should revert to - if (mcMMO.p.getServer().getScoreboardManager() != null) + if (mcMMO.p.getServer().getScoreboardManager() != null) { this.oldBoard = mcMMO.p.getServer().getScoreboardManager().getMainScoreboard(); + } } } else { this.oldBoard = previousBoard; @@ -212,13 +217,15 @@ public class ScoreboardWrapper { } player.setScoreboard(scoreboard); - revertTask = mcMMO.p.getFoliaLib().getScheduler().runAtEntityLater(player, new ScoreboardChangeTask(), ticks); + revertTask = mcMMO.p.getFoliaLib().getScheduler() + .runAtEntityLater(player, new ScoreboardChangeTask(), ticks); // TODO is there any way to do the time that looks acceptable? // player.sendMessage(LocaleLoader.getString("Commands.Scoreboard.Timer", StringUtils.capitalize(sidebarType.toString().toLowerCase(Locale.ENGLISH)), ticks / 20F)); - if (UserManager.getPlayer(playerName) == null) + if (UserManager.getPlayer(playerName) == null) { return; + } PlayerProfile profile = UserManager.getPlayer(player).getProfile(); @@ -249,13 +256,15 @@ public class ScoreboardWrapper { /* Call the revert scoreboard custom event */ - McMMOScoreboardRevertEvent event = new McMMOScoreboardRevertEvent(oldBoard, player.getScoreboard(), player, ScoreboardEventReason.REVERTING_BOARD); + McMMOScoreboardRevertEvent event = new McMMOScoreboardRevertEvent(oldBoard, + player.getScoreboard(), player, ScoreboardEventReason.REVERTING_BOARD); player.getServer().getPluginManager().callEvent(event); //Modify the player based on the event event.getTargetPlayer().setScoreboard(event.getTargetBoard()); oldBoard = null; } else { - LogUtils.debug(mcMMO.p.getLogger(), "Not reverting targetBoard for " + playerName + " - targetBoard was changed by another plugin (Consider disabling the mcMMO scoreboards if you don't want them!)"); + LogUtils.debug(mcMMO.p.getLogger(), "Not reverting targetBoard for " + playerName + + " - targetBoard was changed by another plugin (Consider disabling the mcMMO scoreboards if you don't want them!)"); } } @@ -334,10 +343,10 @@ public class ScoreboardWrapper { loadObjective(LocaleLoader.getString("Scoreboard.Header.PlayerInspect", targetPlayer)); } - public void setTypeInspectStats(@NotNull McMMOPlayer mcMMOPlayer) { + public void setTypeInspectStats(@NotNull McMMOPlayer mmoPlayer) { this.sidebarType = SidebarType.STATS_BOARD; - targetPlayer = mcMMOPlayer.getPlayer().getName(); - targetProfile = mcMMOPlayer.getProfile(); + targetPlayer = mmoPlayer.getPlayer().getName(); + targetProfile = mmoPlayer.getProfile(); targetSkill = null; leaderboardPage = -1; @@ -388,7 +397,8 @@ public class ScoreboardWrapper { int endPosition = page * 10; int startPosition = endPosition - 9; - loadObjective(String.format("%s (%2d - %2d)", ScoreboardManager.POWER_LEVEL, startPosition, endPosition)); + loadObjective(String.format("%s (%2d - %2d)", ScoreboardManager.POWER_LEVEL, startPosition, + endPosition)); } public void setTypeTop(PrimarySkillType skill, int page) { @@ -401,33 +411,43 @@ public class ScoreboardWrapper { int endPosition = page * 10; int startPosition = endPosition - 9; - loadObjective(String.format("%s (%2d - %2d)", ScoreboardManager.skillLabels.get(skill), startPosition, endPosition)); + loadObjective(String.format("%s (%2d - %2d)", ScoreboardManager.skillLabels.get(skill), + startPosition, endPosition)); } // Setup for after a board type change protected void loadObjective(String displayName) { //Unregister objective - McMMOScoreboardObjectiveEvent unregisterEvent = callObjectiveEvent(ScoreboardObjectiveEventReason.UNREGISTER_THIS_OBJECTIVE); + McMMOScoreboardObjectiveEvent unregisterEvent = callObjectiveEvent( + ScoreboardObjectiveEventReason.UNREGISTER_THIS_OBJECTIVE); if (!unregisterEvent.isCancelled()) { try { sidebarObjective.unregister(); } catch (IllegalStateException e) { - McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - LogUtils.debug(mcMMO.p.getLogger(), "Recovering scoreboard for player: " + player.getName()); + LogUtils.debug(mcMMO.p.getLogger(), + "Recovering scoreboard for player: " + player.getName()); - if (mmoPlayer.isDebugMode()) - NotificationManager.sendPlayerInformationChatOnlyPrefixed(player, "Scoreboard.Recovery"); + if (mmoPlayer.isDebugMode()) { + NotificationManager.sendPlayerInformationChatOnlyPrefixed(player, + "Scoreboard.Recovery"); + } initBoard(); //Start over - mcMMO.p.getFoliaLib().getScheduler().runAtEntity(player, t -> ScoreboardManager.retryLastSkillBoard(player)); + mcMMO.p.getFoliaLib().getScheduler() + .runAtEntity(player, t -> ScoreboardManager.retryLastSkillBoard(player)); } } //Register objective - McMMOScoreboardObjectiveEvent registerEvent = callObjectiveEvent(ScoreboardObjectiveEventReason.REGISTER_NEW_OBJECTIVE); - if (!registerEvent.isCancelled()) - sidebarObjective = registerEvent.getTargetBoard().registerNewObjective(ScoreboardManager.SIDEBAR_OBJECTIVE, "dummy", SIDE_OBJECTIVE); + McMMOScoreboardObjectiveEvent registerEvent = callObjectiveEvent( + ScoreboardObjectiveEventReason.REGISTER_NEW_OBJECTIVE); + if (!registerEvent.isCancelled()) { + sidebarObjective = registerEvent.getTargetBoard() + .registerNewObjective(ScoreboardManager.SIDEBAR_OBJECTIVE, "dummy", + SIDE_OBJECTIVE); + } if (displayName.length() > 32) { displayName = displayName.substring(0, 32); @@ -440,8 +460,10 @@ public class ScoreboardWrapper { sidebarObjective.setDisplaySlot(DisplaySlot.SIDEBAR); } - private McMMOScoreboardObjectiveEvent callObjectiveEvent(ScoreboardObjectiveEventReason reason) { - McMMOScoreboardObjectiveEvent event = new McMMOScoreboardObjectiveEvent(sidebarObjective, reason, scoreboard, scoreboard, player, ScoreboardEventReason.OBJECTIVE); + private McMMOScoreboardObjectiveEvent callObjectiveEvent( + ScoreboardObjectiveEventReason reason) { + McMMOScoreboardObjectiveEvent event = new McMMOScoreboardObjectiveEvent(sidebarObjective, + reason, scoreboard, scoreboard, player, ScoreboardEventReason.OBJECTIVE); player.getServer().getPluginManager().callEvent(event); return event; } @@ -460,7 +482,6 @@ public class ScoreboardWrapper { updateTask = null; } - if (sidebarType == SidebarType.NONE) { return; } @@ -472,10 +493,11 @@ public class ScoreboardWrapper { return; } - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if (mcMMOPlayer == null) + if (mmoPlayer == null) { return; + } switch (sidebarType) { case NONE: @@ -485,36 +507,50 @@ public class ScoreboardWrapper { requireNonNull(targetSkill); if (!SkillTools.isChildSkill(targetSkill)) { - int currentXP = mcMMOPlayer.getSkillXpLevel(targetSkill); + int currentXP = mmoPlayer.getSkillXpLevel(targetSkill); - sidebarObjective.getScore(ScoreboardManager.LABEL_CURRENT_XP).setScore(currentXP); - sidebarObjective.getScore(ScoreboardManager.LABEL_REMAINING_XP).setScore(mcMMOPlayer.getXpToLevel(targetSkill) - currentXP); + sidebarObjective.getScore(ScoreboardManager.LABEL_CURRENT_XP) + .setScore(currentXP); + sidebarObjective.getScore(ScoreboardManager.LABEL_REMAINING_XP) + .setScore(mmoPlayer.getXpToLevel(targetSkill) - currentXP); } else { - for (PrimarySkillType parentSkill : mcMMO.p.getSkillTools().getChildSkillParents(targetSkill)) { - sidebarObjective.getScore(ScoreboardManager.skillLabels.get(parentSkill)).setScore(mcMMOPlayer.getSkillLevel(parentSkill)); + for (PrimarySkillType parentSkill : mcMMO.p.getSkillTools() + .getChildSkillParents(targetSkill)) { + sidebarObjective.getScore(ScoreboardManager.skillLabels.get(parentSkill)) + .setScore(mmoPlayer.getSkillLevel(parentSkill)); } } - sidebarObjective.getScore(ScoreboardManager.LABEL_LEVEL).setScore(mcMMOPlayer.getSkillLevel(targetSkill)); + sidebarObjective.getScore(ScoreboardManager.LABEL_LEVEL) + .setScore(mmoPlayer.getSkillLevel(targetSkill)); if (mcMMO.p.getSkillTools().getSuperAbility(targetSkill) != null) { boolean stopUpdating; if (targetSkill == PrimarySkillType.MINING) { // Special-Case: Mining has two abilities, both with cooldowns - Score cooldownSB = sidebarObjective.getScore(ScoreboardManager.abilityLabelsSkill.get(SuperAbilityType.SUPER_BREAKER)); - Score cooldownBM = sidebarObjective.getScore(ScoreboardManager.abilityLabelsSkill.get(SuperAbilityType.BLAST_MINING)); - int secondsSB = Math.max(mcMMOPlayer.calculateTimeRemaining(SuperAbilityType.SUPER_BREAKER), 0); - int secondsBM = Math.max(mcMMOPlayer.calculateTimeRemaining(SuperAbilityType.BLAST_MINING), 0); + Score cooldownSB = sidebarObjective.getScore( + ScoreboardManager.abilityLabelsSkill.get( + SuperAbilityType.SUPER_BREAKER)); + Score cooldownBM = sidebarObjective.getScore( + ScoreboardManager.abilityLabelsSkill.get( + SuperAbilityType.BLAST_MINING)); + int secondsSB = Math.max( + mmoPlayer.calculateTimeRemaining(SuperAbilityType.SUPER_BREAKER), + 0); + int secondsBM = Math.max( + mmoPlayer.calculateTimeRemaining(SuperAbilityType.BLAST_MINING), 0); cooldownSB.setScore(secondsSB); cooldownBM.setScore(secondsBM); stopUpdating = (secondsSB == 0 && secondsBM == 0); } else { - SuperAbilityType ability = mcMMO.p.getSkillTools().getSuperAbility(targetSkill); - Score cooldown = sidebarObjective.getScore(ScoreboardManager.abilityLabelsSkill.get(ability)); - int seconds = Math.max(mcMMOPlayer.calculateTimeRemaining(ability), 0); + SuperAbilityType ability = mcMMO.p.getSkillTools() + .getSuperAbility(targetSkill); + Score cooldown = sidebarObjective.getScore( + ScoreboardManager.abilityLabelsSkill.get(ability)); + int seconds = Math.max(mmoPlayer.calculateTimeRemaining(ability), 0); cooldown.setScore(seconds); @@ -533,13 +569,14 @@ public class ScoreboardWrapper { boolean anyCooldownsActive = false; for (SuperAbilityType ability : SuperAbilityType.values()) { - int seconds = Math.max(mcMMOPlayer.calculateTimeRemaining(ability), 0); + int seconds = Math.max(mmoPlayer.calculateTimeRemaining(ability), 0); if (seconds != 0) { anyCooldownsActive = true; } - sidebarObjective.getScore(ScoreboardManager.abilityLabelsColored.get(ability)).setScore(seconds); + sidebarObjective.getScore(ScoreboardManager.abilityLabelsColored.get(ability)) + .setScore(seconds); } if (anyCooldownsActive) { @@ -556,7 +593,7 @@ public class ScoreboardWrapper { if (targetProfile != null) { newProfile = targetProfile; // offline } else if (targetPlayer == null) { - newProfile = mcMMOPlayer.getProfile(); // self + newProfile = mmoPlayer.getProfile(); // self } else { newProfile = UserManager.getPlayer(targetPlayer).getProfile(); // online } @@ -573,7 +610,8 @@ public class ScoreboardWrapper { continue; } - sidebarObjective.getScore(ScoreboardManager.skillLabels.get(skill)).setScore(level); + sidebarObjective.getScore(ScoreboardManager.skillLabels.get(skill)) + .setScore(level); } sidebarObjective.getScore(ScoreboardManager.LABEL_POWER_LEVEL).setScore(powerLevel); @@ -581,10 +619,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: 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 1dc0e9746..f3b50f4c6 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java @@ -1,5 +1,10 @@ package com.gmail.nossr50.util.skills; +import static com.gmail.nossr50.datatypes.experience.XPGainReason.PVP; +import static com.gmail.nossr50.util.AttributeMapper.MAPPED_MOVEMENT_SPEED; +import static com.gmail.nossr50.util.MobMetadataUtils.hasMobFlag; +import static com.gmail.nossr50.util.skills.ProjectileUtils.isCrossbowProjectile; + import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.datatypes.experience.XPGainReason; import com.gmail.nossr50.datatypes.interactions.NotificationType; @@ -18,13 +23,30 @@ import com.gmail.nossr50.skills.swords.SwordsManager; import com.gmail.nossr50.skills.taming.TamingManager; import com.gmail.nossr50.skills.tridents.TridentsManager; import com.gmail.nossr50.skills.unarmed.UnarmedManager; -import com.gmail.nossr50.util.*; +import com.gmail.nossr50.util.ItemUtils; +import com.gmail.nossr50.util.MetadataConstants; +import com.gmail.nossr50.util.Misc; +import com.gmail.nossr50.util.MobHealthbarUtils; +import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.NotificationManager; import com.gmail.nossr50.util.player.UserManager; +import java.util.List; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.attribute.AttributeInstance; -import org.bukkit.entity.*; +import org.bukkit.entity.AbstractArrow; +import org.bukkit.entity.AnimalTamer; +import org.bukkit.entity.Animals; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.IronGolem; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Monster; +import org.bukkit.entity.Player; +import org.bukkit.entity.Tameable; +import org.bukkit.entity.Trident; +import org.bukkit.entity.Wolf; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.inventory.ItemStack; @@ -34,13 +56,6 @@ import org.bukkit.projectiles.ProjectileSource; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.List; - -import static com.gmail.nossr50.datatypes.experience.XPGainReason.PVP; -import static com.gmail.nossr50.util.AttributeMapper.MAPPED_MOVEMENT_SPEED; -import static com.gmail.nossr50.util.MobMetadataUtils.hasMobFlag; -import static com.gmail.nossr50.util.skills.ProjectileUtils.isCrossbowProjectile; - public final class CombatUtils { private static final ThreadLocal IN_MCMO_DAMAGE @@ -58,7 +73,8 @@ public final class CombatUtils { * @param amount The amount of damage to deal. * @param attacker The {@link Entity} responsible for the damage, or null if none. */ - public static void safeDealDamage(@NotNull LivingEntity target, double amount, @Nullable Entity attacker) { + public static void safeDealDamage(@NotNull LivingEntity target, double amount, + @Nullable Entity attacker) { boolean prev = IN_MCMO_DAMAGE.get(); if (prev || target.isDead()) { @@ -84,7 +100,8 @@ public final class CombatUtils { } } - private CombatUtils() {} + private CombatUtils() { + } @Deprecated(forRemoval = true, since = "2.2.039") public static boolean isDamageLikelyFromNormalCombat(@NotNull DamageCause damageCause) { @@ -99,28 +116,29 @@ public final class CombatUtils { return livingEntity.hasPotionEffect(PotionEffectType.WEAKNESS); } - private static void processSwordCombat(@NotNull LivingEntity target, @NotNull Player player, @NotNull EntityDamageByEntityEvent event) { + private static void processSwordCombat(@NotNull LivingEntity target, @NotNull Player player, + @NotNull EntityDamageByEntityEvent event) { if (event.getCause() == DamageCause.THORNS) { return; } - final McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); //Make sure the profiles been loaded - if (mcMMOPlayer == null) { + if (mmoPlayer == null) { return; } - SwordsManager swordsManager = mcMMOPlayer.getSwordsManager(); + SwordsManager swordsManager = mmoPlayer.getSwordsManager(); double boostedDamage = event.getDamage(); if (swordsManager.canActivateAbility()) { - mcMMOPlayer.checkAbilityActivation(PrimarySkillType.SWORDS); + mmoPlayer.checkAbilityActivation(PrimarySkillType.SWORDS); } //Add Stab Damage if (swordsManager.canUseStab()) { - boostedDamage += (swordsManager.getStabDamage() * mcMMOPlayer.getAttackStrength()); + boostedDamage += (swordsManager.getStabDamage() * mmoPlayer.getAttackStrength()); } if (swordsManager.canUseSerratedStrike()) { @@ -129,7 +147,8 @@ public final class CombatUtils { if (canUseLimitBreak(player, target, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK)) { boostedDamage += (getLimitBreakDamage - (player, target, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength()); + (player, target, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK) + * mmoPlayer.getAttackStrength()); } event.setDamage(boostedDamage); @@ -138,102 +157,108 @@ public final class CombatUtils { swordsManager.processRupture(target); } - processCombatXP(mcMMOPlayer, target, PrimarySkillType.SWORDS); + processCombatXP(mmoPlayer, target, PrimarySkillType.SWORDS); - printFinalDamageDebug(player, event, mcMMOPlayer); + printFinalDamageDebug(player, event, mmoPlayer); } - private static void printFinalDamageDebug(@NotNull Player player, @NotNull EntityDamageByEntityEvent event, - @NotNull McMMOPlayer mcMMOPlayer, - @Nullable String @Nullable ...extraInfoLines) { - if (mcMMOPlayer.isDebugMode()) { - player.sendMessage("Final Damage value after mcMMO modifiers: "+ event.getFinalDamage()); - player.sendMessage("Your current attack strength: "+ player.getAttackCooldown()); + private static void printFinalDamageDebug(@NotNull Player player, + @NotNull EntityDamageByEntityEvent event, + @NotNull McMMOPlayer mmoPlayer, + @Nullable String @Nullable ... extraInfoLines) { + if (mmoPlayer.isDebugMode()) { + player.sendMessage( + "Final Damage value after mcMMO modifiers: " + event.getFinalDamage()); + player.sendMessage("Your current attack strength: " + player.getAttackCooldown()); if (extraInfoLines != null) { - for(String str : extraInfoLines) { - if (str != null) + for (String str : extraInfoLines) { + if (str != null) { player.sendMessage(str); + } } } } } - private static void processTridentCombatMelee(@NotNull LivingEntity target, @NotNull Player player, @NotNull EntityDamageByEntityEvent event) { + private static void processTridentCombatMelee(@NotNull LivingEntity target, + @NotNull Player player, @NotNull EntityDamageByEntityEvent event) { if (event.getCause() == DamageCause.THORNS) { return; } double boostedDamage = event.getDamage(); - final McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); //Make sure the profiles been loaded - if (mcMMOPlayer == null) { + if (mmoPlayer == null) { return; } - final TridentsManager tridentsManager = mcMMOPlayer.getTridentsManager(); + final TridentsManager tridentsManager = mmoPlayer.getTridentsManager(); // if (tridentsManager.canActivateAbility()) { -// mcMMOPlayer.checkAbilityActivation(PrimarySkillType.TRIDENTS); +// mmoPlayer.checkAbilityActivation(PrimarySkillType.TRIDENTS); // } if (SkillUtils.canUseSubskill(player, SubSkillType.TRIDENTS_IMPALE)) { - boostedDamage += (tridentsManager.impaleDamageBonus() * mcMMOPlayer.getAttackStrength()); + boostedDamage += (tridentsManager.impaleDamageBonus() * mmoPlayer.getAttackStrength()); } if (canUseLimitBreak(player, target, SubSkillType.TRIDENTS_TRIDENTS_LIMIT_BREAK)) { boostedDamage += (getLimitBreakDamage( - player, target, SubSkillType.TRIDENTS_TRIDENTS_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength()); + player, target, SubSkillType.TRIDENTS_TRIDENTS_LIMIT_BREAK) + * mmoPlayer.getAttackStrength()); } event.setDamage(boostedDamage); - processCombatXP(mcMMOPlayer, target, PrimarySkillType.TRIDENTS); + processCombatXP(mmoPlayer, target, PrimarySkillType.TRIDENTS); - printFinalDamageDebug(player, event, mcMMOPlayer); + printFinalDamageDebug(player, event, mmoPlayer); } private static void processTridentCombatRanged(@NotNull Trident trident, - @NotNull LivingEntity target, - @NotNull Player player, - @NotNull EntityDamageByEntityEvent event) { + @NotNull LivingEntity target, + @NotNull Player player, + @NotNull EntityDamageByEntityEvent event) { if (event.getCause() == DamageCause.THORNS) { return; } double boostedDamage = event.getDamage(); - final McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); //Make sure the profiles been loaded - if (mcMMOPlayer == null) { + if (mmoPlayer == null) { return; } - final TridentsManager tridentsManager = mcMMOPlayer.getTridentsManager(); + final TridentsManager tridentsManager = mmoPlayer.getTridentsManager(); if (SkillUtils.canUseSubskill(player, SubSkillType.TRIDENTS_IMPALE)) { boostedDamage += (tridentsManager.impaleDamageBonus()); } if (canUseLimitBreak(player, target, SubSkillType.TRIDENTS_TRIDENTS_LIMIT_BREAK)) { - boostedDamage += (getLimitBreakDamage(player, target, SubSkillType.TRIDENTS_TRIDENTS_LIMIT_BREAK)); + boostedDamage += (getLimitBreakDamage(player, target, + SubSkillType.TRIDENTS_TRIDENTS_LIMIT_BREAK)); } event.setDamage(boostedDamage); - processCombatXP(mcMMOPlayer, target, PrimarySkillType.TRIDENTS); + processCombatXP(mmoPlayer, target, PrimarySkillType.TRIDENTS); - printFinalDamageDebug(player, event, mcMMOPlayer); + printFinalDamageDebug(player, event, mmoPlayer); } private static void processCrossbowsCombat(@NotNull LivingEntity target, @NotNull Player player, - @NotNull EntityDamageByEntityEvent event, @NotNull AbstractArrow arrow) { + @NotNull EntityDamageByEntityEvent event, @NotNull AbstractArrow arrow) { double initialDamage = event.getDamage(); - final McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); //Make sure the profiles been loaded - if (mcMMOPlayer == null) { + if (mmoPlayer == null) { delayArrowMetaCleanup(arrow); return; } @@ -242,55 +267,58 @@ public final class CombatUtils { if (SkillUtils.canUseSubskill(player, SubSkillType.CROSSBOWS_POWERED_SHOT)) { //Not Additive - boostedDamage = mcMMOPlayer.getCrossbowsManager().poweredShot(initialDamage); + boostedDamage = mmoPlayer.getCrossbowsManager().poweredShot(initialDamage); } if (canUseLimitBreak(player, target, SubSkillType.CROSSBOWS_CROSSBOWS_LIMIT_BREAK)) { - boostedDamage+=getLimitBreakDamage(player, target, SubSkillType.CROSSBOWS_CROSSBOWS_LIMIT_BREAK); + boostedDamage += getLimitBreakDamage(player, target, + SubSkillType.CROSSBOWS_CROSSBOWS_LIMIT_BREAK); } double distanceMultiplier = ArcheryManager.distanceXpBonusMultiplier(target, arrow); double forceMultiplier = 1.0; event.setDamage(boostedDamage); - processCombatXP(mcMMOPlayer, target, PrimarySkillType.CROSSBOWS, forceMultiplier * distanceMultiplier); + processCombatXP(mmoPlayer, target, PrimarySkillType.CROSSBOWS, + forceMultiplier * distanceMultiplier); - printFinalDamageDebug(player, event, mcMMOPlayer, - "Distance Multiplier: "+distanceMultiplier, - "Force Multiplier: "+forceMultiplier, - "Initial Damage: "+initialDamage, - "Final Damage: "+boostedDamage); + printFinalDamageDebug(player, event, mmoPlayer, + "Distance Multiplier: " + distanceMultiplier, + "Force Multiplier: " + forceMultiplier, + "Initial Damage: " + initialDamage, + "Final Damage: " + boostedDamage); //Clean data delayArrowMetaCleanup(arrow); } private static void processMacesCombat(@NotNull LivingEntity target, - @NotNull Player player, - @NotNull EntityDamageByEntityEvent event) { + @NotNull Player player, + @NotNull EntityDamageByEntityEvent event) { if (event.getCause() == DamageCause.THORNS) { return; } double boostedDamage = event.getDamage(); - final McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); //Make sure the profiles been loaded - if (mcMMOPlayer == null) { + if (mmoPlayer == null) { return; } - final MacesManager macesManager = mcMMOPlayer.getMacesManager(); + final MacesManager macesManager = mmoPlayer.getMacesManager(); // Apply Limit Break DMG if (canUseLimitBreak(player, target, SubSkillType.MACES_MACES_LIMIT_BREAK)) { boostedDamage += (getLimitBreakDamage( - player, target, SubSkillType.MACES_MACES_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength()); + player, target, SubSkillType.MACES_MACES_LIMIT_BREAK) + * mmoPlayer.getAttackStrength()); } // Apply Crush DMG - boostedDamage += (macesManager.getCrushDamage() * mcMMOPlayer.getAttackStrength()); + boostedDamage += (macesManager.getCrushDamage() * mmoPlayer.getAttackStrength()); event.setDamage(boostedDamage); @@ -299,39 +327,39 @@ public final class CombatUtils { macesManager.processCripple(target); } - processCombatXP(mcMMOPlayer, target, PrimarySkillType.MACES); - printFinalDamageDebug(player, event, mcMMOPlayer); + processCombatXP(mmoPlayer, target, PrimarySkillType.MACES); + printFinalDamageDebug(player, event, mmoPlayer); } private static void processAxeCombat(@NotNull LivingEntity target, @NotNull Player player, - @NotNull EntityDamageByEntityEvent event) { + @NotNull EntityDamageByEntityEvent event) { if (event.getCause() == DamageCause.THORNS) { return; } double boostedDamage = event.getDamage(); - final McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); //Make sure the profiles been loaded - if (mcMMOPlayer == null) { + if (mmoPlayer == null) { return; } - final AxesManager axesManager = mcMMOPlayer.getAxesManager(); + final AxesManager axesManager = mmoPlayer.getAxesManager(); if (axesManager.canActivateAbility()) { - mcMMOPlayer.checkAbilityActivation(PrimarySkillType.AXES); + mmoPlayer.checkAbilityActivation(PrimarySkillType.AXES); } if (axesManager.canUseAxeMastery()) { - boostedDamage += axesManager.axeMastery() * mcMMOPlayer.getAttackStrength(); + boostedDamage += axesManager.axeMastery() * mmoPlayer.getAttackStrength(); } if (axesManager.canImpact(target)) { axesManager.impactCheck(target); } else if (axesManager.canGreaterImpact(target)) { - boostedDamage += axesManager.greaterImpact(target) * mcMMOPlayer.getAttackStrength(); + boostedDamage += axesManager.greaterImpact(target) * mmoPlayer.getAttackStrength(); } if (axesManager.canUseSkullSplitter(target)) { @@ -339,45 +367,51 @@ public final class CombatUtils { } if (axesManager.canCriticalHit(target)) { - boostedDamage+=(axesManager.criticalHit(target, boostedDamage) * mcMMOPlayer.getAttackStrength()); + boostedDamage += (axesManager.criticalHit(target, boostedDamage) + * mmoPlayer.getAttackStrength()); } if (canUseLimitBreak(player, target, SubSkillType.AXES_AXES_LIMIT_BREAK)) { - boostedDamage+=(getLimitBreakDamage(player, target, SubSkillType.AXES_AXES_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength()); + boostedDamage += ( + getLimitBreakDamage(player, target, SubSkillType.AXES_AXES_LIMIT_BREAK) + * mmoPlayer.getAttackStrength()); } event.setDamage(boostedDamage); - processCombatXP(mcMMOPlayer, target, PrimarySkillType.AXES); + processCombatXP(mmoPlayer, target, PrimarySkillType.AXES); - printFinalDamageDebug(player, event, mcMMOPlayer); + printFinalDamageDebug(player, event, mmoPlayer); } - private static void processUnarmedCombat(@NotNull LivingEntity target, @NotNull Player player, @NotNull EntityDamageByEntityEvent event) { + private static void processUnarmedCombat(@NotNull LivingEntity target, @NotNull Player player, + @NotNull EntityDamageByEntityEvent event) { if (event.getCause() == DamageCause.THORNS) { return; } double boostedDamage = event.getDamage(); - final McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); //Make sure the profiles been loaded - if (mcMMOPlayer == null) { + if (mmoPlayer == null) { return; } - final UnarmedManager unarmedManager = mcMMOPlayer.getUnarmedManager(); + final UnarmedManager unarmedManager = mmoPlayer.getUnarmedManager(); if (unarmedManager.canActivateAbility()) { - mcMMOPlayer.checkAbilityActivation(PrimarySkillType.UNARMED); + mmoPlayer.checkAbilityActivation(PrimarySkillType.UNARMED); } if (unarmedManager.canUseSteelArm()) { - boostedDamage+=(unarmedManager.calculateSteelArmStyleDamage() * mcMMOPlayer.getAttackStrength()); + boostedDamage += (unarmedManager.calculateSteelArmStyleDamage() + * mmoPlayer.getAttackStrength()); } if (unarmedManager.canUseBerserk()) { - boostedDamage+=(unarmedManager.berserkDamage(boostedDamage) * mcMMOPlayer.getAttackStrength()); + boostedDamage += (unarmedManager.berserkDamage(boostedDamage) + * mmoPlayer.getAttackStrength()); } if (unarmedManager.canDisarm(target)) { @@ -385,29 +419,31 @@ public final class CombatUtils { } if (canUseLimitBreak(player, target, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK)) { - boostedDamage+=(getLimitBreakDamage( - player, target, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength()); + boostedDamage += (getLimitBreakDamage( + player, target, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK) + * mmoPlayer.getAttackStrength()); } event.setDamage(boostedDamage); - processCombatXP(mcMMOPlayer, target, PrimarySkillType.UNARMED); + processCombatXP(mmoPlayer, target, PrimarySkillType.UNARMED); - printFinalDamageDebug(player, event, mcMMOPlayer); + printFinalDamageDebug(player, event, mmoPlayer); } - private static void processTamingCombat(@NotNull LivingEntity target, @Nullable Player master, @NotNull Wolf wolf, @NotNull EntityDamageByEntityEvent event) { + private static void processTamingCombat(@NotNull LivingEntity target, @Nullable Player master, + @NotNull Wolf wolf, @NotNull EntityDamageByEntityEvent event) { double initialDamage = event.getDamage(); double boostedDamage = initialDamage; if (master != null && master.isOnline() && master.isValid()) { - final McMMOPlayer mcMMOPlayer = UserManager.getPlayer(master); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(master); //Make sure the profiles been loaded - if (mcMMOPlayer == null) { + if (mmoPlayer == null) { return; } - final TamingManager tamingManager = mcMMOPlayer.getTamingManager(); + final TamingManager tamingManager = mmoPlayer.getTamingManager(); if (tamingManager.canUseFastFoodService()) { tamingManager.fastFoodService(wolf, event.getDamage()); @@ -416,33 +452,33 @@ public final class CombatUtils { tamingManager.pummel(target, wolf); if (tamingManager.canUseSharpenedClaws()) { - boostedDamage+=tamingManager.sharpenedClaws(); + boostedDamage += tamingManager.sharpenedClaws(); } if (tamingManager.canUseGore()) { - boostedDamage+=tamingManager.gore(target, initialDamage); + boostedDamage += tamingManager.gore(target, initialDamage); } event.setDamage(boostedDamage); - processCombatXP(mcMMOPlayer, target, PrimarySkillType.TAMING, 3); + processCombatXP(mmoPlayer, target, PrimarySkillType.TAMING, 3); } } private static void processArcheryCombat(@NotNull LivingEntity target, @NotNull Player player, - @NotNull EntityDamageByEntityEvent event, @NotNull AbstractArrow arrow) { + @NotNull EntityDamageByEntityEvent event, @NotNull AbstractArrow arrow) { double initialDamage = event.getDamage(); - final McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); //Make sure the profiles been loaded - if (mcMMOPlayer == null) { + if (mmoPlayer == null) { delayArrowMetaCleanup(arrow); return; } - final ArcheryManager archeryManager = mcMMOPlayer.getArcheryManager(); - + final ArcheryManager archeryManager = mmoPlayer.getArcheryManager(); + double boostedDamage = event.getDamage(); if (archeryManager.canSkillShot()) { @@ -451,31 +487,37 @@ public final class CombatUtils { } if (archeryManager.canDaze(target)) { - boostedDamage+=archeryManager.daze((Player) target); //the cast is checked by the if condition + boostedDamage += archeryManager.daze( + (Player) target); //the cast is checked by the if condition } - if (!arrow.hasMetadata(MetadataConstants.METADATA_KEY_INF_ARROW) && archeryManager.canRetrieveArrows()) { + if (!arrow.hasMetadata(MetadataConstants.METADATA_KEY_INF_ARROW) + && archeryManager.canRetrieveArrows()) { archeryManager.retrieveArrows(target, arrow); } if (canUseLimitBreak(player, target, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK)) { - boostedDamage+=getLimitBreakDamage(player, target, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK); + boostedDamage += getLimitBreakDamage(player, target, + SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK); } double distanceMultiplier = ArcheryManager.distanceXpBonusMultiplier(target, arrow); double forceMultiplier = 1.0; //Hacky Fix - some plugins spawn arrows and assign them to players after the ProjectileLaunchEvent fires - if (arrow.hasMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE)) - forceMultiplier = arrow.getMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE).get(0).asDouble(); + if (arrow.hasMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE)) { + forceMultiplier = arrow.getMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE).get(0) + .asDouble(); + } event.setDamage(boostedDamage); - processCombatXP(mcMMOPlayer, target, PrimarySkillType.ARCHERY, forceMultiplier * distanceMultiplier); + processCombatXP(mmoPlayer, target, PrimarySkillType.ARCHERY, + forceMultiplier * distanceMultiplier); - printFinalDamageDebug(player, event, mcMMOPlayer, - "Distance Multiplier: "+distanceMultiplier, - "Force Multiplier: "+forceMultiplier, - "Initial Damage: "+initialDamage, - "Final Damage: "+boostedDamage); + printFinalDamageDebug(player, event, mmoPlayer, + "Distance Multiplier: " + distanceMultiplier, + "Force Multiplier: " + forceMultiplier, + "Initial Damage: " + initialDamage, + "Final Damage: " + boostedDamage); //Clean data delayArrowMetaCleanup(arrow); } @@ -486,8 +528,8 @@ public final class CombatUtils { * @param event The event to run the combat checks on. */ public static void processCombatAttack(@NotNull EntityDamageByEntityEvent event, - @NotNull Entity painSourceRoot, - @NotNull LivingEntity target) { + @NotNull Entity painSourceRoot, + @NotNull LivingEntity target) { Entity painSource = event.getDamager(); EntityType entityType = painSource.getType(); @@ -506,19 +548,20 @@ public final class CombatUtils { return; } - final McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - final AcrobaticsManager acrobaticsManager = mcMMOPlayer.getAcrobaticsManager(); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + final AcrobaticsManager acrobaticsManager = mmoPlayer.getAcrobaticsManager(); if (acrobaticsManager.canDodge(target)) { event.setDamage(acrobaticsManager.dodgeCheck(painSourceRoot, event.getDamage())); } if (ItemUtils.isSword(player.getInventory().getItemInMainHand())) { - if (!mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.SWORDS, target)) { + if (!mcMMO.p.getSkillTools() + .canCombatSkillsTrigger(PrimarySkillType.SWORDS, target)) { return; } - final SwordsManager swordsManager = mcMMOPlayer.getSwordsManager(); + final SwordsManager swordsManager = mmoPlayer.getSwordsManager(); if (swordsManager.canUseCounterAttack(painSource)) { swordsManager.counterAttackChecks((LivingEntity) painSource, event.getDamage()); @@ -550,55 +593,65 @@ public final class CombatUtils { } if (ItemUtils.isSword(heldItem)) { - if (!mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.SWORDS, target)) { + if (!mcMMO.p.getSkillTools() + .canCombatSkillsTrigger(PrimarySkillType.SWORDS, target)) { return; } - if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.SWORDS)) { + if (mcMMO.p.getSkillTools() + .doesPlayerHaveSkillPermission(player, PrimarySkillType.SWORDS)) { processSwordCombat(target, player, event); } } else if (ItemUtils.isAxe(heldItem)) { - if (!mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.AXES, target)) { + if (!mcMMO.p.getSkillTools() + .canCombatSkillsTrigger(PrimarySkillType.AXES, target)) { return; } - if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.AXES)) { + if (mcMMO.p.getSkillTools() + .doesPlayerHaveSkillPermission(player, PrimarySkillType.AXES)) { processAxeCombat(target, player, event); } } else if (ItemUtils.isUnarmed(heldItem)) { - if (!mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.UNARMED, target)) { + if (!mcMMO.p.getSkillTools() + .canCombatSkillsTrigger(PrimarySkillType.UNARMED, target)) { return; } - if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.UNARMED)) { + if (mcMMO.p.getSkillTools() + .doesPlayerHaveSkillPermission(player, PrimarySkillType.UNARMED)) { processUnarmedCombat(target, player, event); } } else if (ItemUtils.isTrident(heldItem)) { - if (!mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.TRIDENTS, target)) { + if (!mcMMO.p.getSkillTools() + .canCombatSkillsTrigger(PrimarySkillType.TRIDENTS, target)) { return; } - if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.TRIDENTS)) { + if (mcMMO.p.getSkillTools() + .doesPlayerHaveSkillPermission(player, PrimarySkillType.TRIDENTS)) { processTridentCombatMelee(target, player, event); } } else if (ItemUtils.isMace(heldItem)) { - if (!mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.MACES, target)) { + if (!mcMMO.p.getSkillTools() + .canCombatSkillsTrigger(PrimarySkillType.MACES, target)) { return; } - if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.MACES)) { + if (mcMMO.p.getSkillTools() + .doesPlayerHaveSkillPermission(player, PrimarySkillType.MACES)) { processMacesCombat(target, player, event); } } - } - - else if (entityType == EntityType.WOLF) { + } else if (entityType == EntityType.WOLF) { Wolf wolf = (Wolf) painSource; AnimalTamer tamer = wolf.getOwner(); - if (tamer instanceof Player master && mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.TAMING, target)) { + if (tamer instanceof Player master && mcMMO.p.getSkillTools() + .canCombatSkillsTrigger(PrimarySkillType.TAMING, target)) { - if (!Misc.isNPCEntityExcludingVillagers(master) && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(master, PrimarySkillType.TAMING)) { + if (!Misc.isNPCEntityExcludingVillagers(master) && mcMMO.p.getSkillTools() + .doesPlayerHaveSkillPermission(master, PrimarySkillType.TAMING)) { processTamingCombat(target, master, wolf, event); } } @@ -607,7 +660,8 @@ public final class CombatUtils { if (projectileSource instanceof Player player) { if (!Misc.isNPCEntityExcludingVillagers(player)) { - if (mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.TRIDENTS, target)) { + if (mcMMO.p.getSkillTools() + .canCombatSkillsTrigger(PrimarySkillType.TRIDENTS, target)) { processTridentCombatRanged(trident, target, player, event); } } @@ -617,9 +671,11 @@ public final class CombatUtils { boolean isCrossbow = isCrossbowProjectile(arrow); if (projectileSource instanceof Player player) { if (!Misc.isNPCEntityExcludingVillagers(player)) { - if (!isCrossbow && mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.ARCHERY, target)) { + if (!isCrossbow && mcMMO.p.getSkillTools() + .canCombatSkillsTrigger(PrimarySkillType.ARCHERY, target)) { processArcheryCombat(target, player, event, arrow); - } else if (isCrossbow && mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.CROSSBOWS, target)) { + } else if (isCrossbow && mcMMO.p.getSkillTools() + .canCombatSkillsTrigger(PrimarySkillType.CROSSBOWS, target)) { processCrossbowsCombat(target, player, event, arrow); } } else { @@ -629,13 +685,15 @@ public final class CombatUtils { if (target.getType() != EntityType.CREEPER && !Misc.isNPCEntityExcludingVillagers(player) - && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.TAMING)) { - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + && mcMMO.p.getSkillTools() + .doesPlayerHaveSkillPermission(player, PrimarySkillType.TAMING)) { + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if (mcMMOPlayer == null) + if (mmoPlayer == null) { return; + } - TamingManager tamingManager = mcMMOPlayer.getTamingManager(); + TamingManager tamingManager = mmoPlayer.getTamingManager(); tamingManager.attackTarget(target); } } @@ -644,13 +702,16 @@ public final class CombatUtils { /** * This cleans up names from displaying in chat as hearts + * * @param entity target entity */ public static void fixNames(@NotNull LivingEntity entity) { - List metadataValue = entity.getMetadata(MetadataConstants.METADATA_KEY_OLD_NAME_KEY); + List metadataValue = entity.getMetadata( + MetadataConstants.METADATA_KEY_OLD_NAME_KEY); - if (metadataValue.size() <= 0) + if (metadataValue.size() <= 0) { return; + } OldName oldName = (OldName) metadataValue.get(0); entity.setCustomName(oldName.asString()); @@ -661,31 +722,34 @@ public final class CombatUtils { /** * Calculate and return the RAW damage bonus from Limit Break before reductions + * * @param attacker attacking player * @param defender defending living entity * @param subSkillType the specific limit break skill for calculations * @return the RAW damage bonus from Limit Break which is applied before reductions */ public static int getLimitBreakDamage(@NotNull Player attacker, @NotNull LivingEntity defender, - @NotNull SubSkillType subSkillType) { + @NotNull SubSkillType subSkillType) { if (defender instanceof Player playerDefender) { - return getLimitBreakDamageAgainstQuality(attacker, subSkillType, getArmorQualityLevel(playerDefender)); + return getLimitBreakDamageAgainstQuality(attacker, subSkillType, + getArmorQualityLevel(playerDefender)); } else { return getLimitBreakDamageAgainstQuality(attacker, subSkillType, 1000); } } /** - * Calculate the RAW daamge value of limit break based on the armor quality of the target - * PVE mobs are passed in with a value of 1000 for armor quality, hacky... I'll change it later + * Calculate the RAW daamge value of limit break based on the armor quality of the target PVE + * mobs are passed in with a value of 1000 for armor quality, hacky... I'll change it later + * * @param attacker Living entity attacker * @param subSkillType Target limit break * @param armorQualityLevel Armor quality level * @return the RAW damage boost after its been mutated by armor quality */ public static int getLimitBreakDamageAgainstQuality(@NotNull Player attacker, - @NotNull SubSkillType subSkillType, - int armorQualityLevel) { + @NotNull SubSkillType subSkillType, + int armorQualityLevel) { float rawDamageBoost = RankUtils.getRank(attacker, subSkillType); if (armorQualityLevel <= 4) { @@ -701,13 +765,14 @@ public final class CombatUtils { /** * Get the quality level of the armor of a player used for Limit Break calculations + * * @param defender target defending player * @return the armor quality of the defending player */ public static int getArmorQualityLevel(@NotNull Player defender) { int armorQualityLevel = 0; - for(ItemStack itemStack : defender.getInventory().getArmorContents()) { + for (ItemStack itemStack : defender.getInventory().getArmorContents()) { if (itemStack != null) { armorQualityLevel += getArmorQuality(itemStack); } @@ -718,6 +783,7 @@ public final class CombatUtils { /** * Get the armor quality for a specific item used for Limit Break calculations + * * @param itemStack target item stack * @return the armor quality of a specific Item Stack */ @@ -727,10 +793,12 @@ public final class CombatUtils { /** * Checks if player has access to their weapons limit break + * * @param player target entity * @return true if the player has access to the limit break */ - public static boolean canUseLimitBreak(@NotNull Player player, LivingEntity target, @NotNull SubSkillType subSkillType) { + public static boolean canUseLimitBreak(@NotNull Player player, LivingEntity target, + @NotNull SubSkillType subSkillType) { if (target instanceof Player || mcMMO.p.getAdvancedConfig().canApplyLimitBreakPVE()) { return RankUtils.hasUnlockedSubskill(player, subSkillType) && Permissions.isSubSkillEnabled(player, subSkillType); @@ -760,7 +828,8 @@ public final class CombatUtils { * @deprecated use {@link #safeDealDamage(LivingEntity, double, Entity)} instead */ @Deprecated(since = "2.2.039") - public static void dealDamage(@NotNull LivingEntity target, double damage, @Nullable Entity attacker) { + public static void dealDamage(@NotNull LivingEntity target, double damage, + @Nullable Entity attacker) { safeDealDamage(target, damage, attacker); } @@ -769,7 +838,8 @@ public final class CombatUtils { } public static void applyIgnoreDamageMetadata(@NotNull LivingEntity target) { - target.setMetadata(MetadataConstants.METADATA_KEY_CUSTOM_DAMAGE, MetadataConstants.MCMMO_METADATA_VALUE); + target.setMetadata(MetadataConstants.METADATA_KEY_CUSTOM_DAMAGE, + MetadataConstants.MCMMO_METADATA_VALUE); } public static boolean hasIgnoreDamageMetadata(@NotNull LivingEntity target) { @@ -778,14 +848,16 @@ 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 */ public static void applyAbilityAoE(@NotNull Player attacker, @NotNull LivingEntity target, - double damage, @NotNull PrimarySkillType type) { - int numberOfTargets = getTier(attacker.getInventory().getItemInMainHand()); // The higher the weapon tier, the more targets you hit + double damage, @NotNull PrimarySkillType type) { + int numberOfTargets = getTier(attacker.getInventory() + .getItemInMainHand()); // The higher the weapon tier, the more targets you hit double damageAmount = Math.max(damage, 1); for (Entity entity : target.getNearbyEntities(2.5, 2.5, 2.5)) { @@ -795,7 +867,8 @@ public final class CombatUtils { if ((ExperienceConfig.getInstance().isNPCInteractionPrevented() && Misc.isNPCEntityExcludingVillagers(entity)) - || !(entity instanceof LivingEntity livingEntity) || !shouldBeAffected(attacker, entity)) { + || !(entity instanceof LivingEntity livingEntity) || !shouldBeAffected(attacker, + entity)) { continue; } @@ -804,7 +877,8 @@ public final class CombatUtils { switch (type) { case SWORDS: if (entity instanceof Player) { - NotificationManager.sendPlayerInformation((Player)entity, NotificationType.SUBSKILL_MESSAGE, + NotificationManager.sendPlayerInformation((Player) entity, + NotificationType.SUBSKILL_MESSAGE, "Swords.Combat.SS.Struck"); } @@ -818,7 +892,8 @@ public final class CombatUtils { case AXES: if (entity instanceof Player) { - NotificationManager.sendPlayerInformation((Player) entity, NotificationType.SUBSKILL_MESSAGE, + NotificationManager.sendPlayerInformation((Player) entity, + NotificationType.SUBSKILL_MESSAGE, "Axes.Combat.SS.Struck"); } break; @@ -835,26 +910,27 @@ public final class CombatUtils { /** * Start the task that gives combat XP. * - * @param mcMMOPlayer The attacking player + * @param mmoPlayer The attacking player * @param target The defending entity * @param primarySkillType The skill being used */ - public static void processCombatXP(@NotNull McMMOPlayer mcMMOPlayer, @NotNull LivingEntity target, @NotNull PrimarySkillType primarySkillType) { - processCombatXP(mcMMOPlayer, target, primarySkillType, 1.0); + public static void processCombatXP(@NotNull McMMOPlayer mmoPlayer, @NotNull LivingEntity target, + @NotNull PrimarySkillType primarySkillType) { + processCombatXP(mmoPlayer, target, primarySkillType, 1.0); } /** * Start the task that gives combat XP. * - * @param mcMMOPlayer The attacking player + * @param mmoPlayer The attacking player * @param target The defending entity * @param primarySkillType The skill being used * @param multiplier final XP result will be multiplied by this */ - public static void processCombatXP(@NotNull McMMOPlayer mcMMOPlayer, - @NotNull LivingEntity target, - @NotNull PrimarySkillType primarySkillType, - double multiplier) { + public static void processCombatXP(@NotNull McMMOPlayer mmoPlayer, + @NotNull LivingEntity target, + @NotNull PrimarySkillType primarySkillType, + double multiplier) { double baseXP = 0; XPGainReason xpGainReason; @@ -862,14 +938,16 @@ public final class CombatUtils { if (!ExperienceConfig.getInstance().getExperienceGainsPlayerVersusPlayerEnabled() || (mcMMO.p.getPartyConfig().isPartyEnabled() - && mcMMO.p.getPartyManager().inSameParty(mcMMOPlayer.getPlayer(), (Player) target))) { + && mcMMO.p.getPartyManager() + .inSameParty(mmoPlayer.getPlayer(), defender))) { return; } xpGainReason = PVP; if (defender.isOnline() - && SkillUtils.cooldownExpired(mcMMOPlayer.getRespawnATS(), Misc.PLAYER_RESPAWN_COOLDOWN_SECONDS)) { + && SkillUtils.cooldownExpired(mmoPlayer.getRespawnATS(), + Misc.PLAYER_RESPAWN_COOLDOWN_SECONDS)) { baseXP = 20 * ExperienceConfig.getInstance().getPlayerVersusPlayerXP(); } } else { @@ -897,7 +975,8 @@ public final class CombatUtils { if (hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, target)) { baseXP = 0; - } else if (hasMobFlag(MobMetaFlagType.MOB_SPAWNER_MOB, target) || target.hasMetadata("ES")) { + } else if (hasMobFlag(MobMetaFlagType.MOB_SPAWNER_MOB, target) || target.hasMetadata( + "ES")) { baseXP *= ExperienceConfig.getInstance().getSpawnedMobXpMultiplier(); } else if (hasMobFlag(MobMetaFlagType.NETHER_PORTAL_MOB, target)) { baseXP *= ExperienceConfig.getInstance().getNetherPortalXpMultiplier(); @@ -916,7 +995,9 @@ public final class CombatUtils { baseXP *= multiplier; if (baseXP > 0) { - mcMMO.p.getFoliaLib().getScheduler().runAtEntity(target, new AwardCombatXpTask(mcMMOPlayer, primarySkillType, baseXP, target, xpGainReason)); + mcMMO.p.getFoliaLib().getScheduler().runAtEntity(target, + new AwardCombatXpTask(mmoPlayer, primarySkillType, baseXP, target, + xpGainReason)); } } @@ -930,17 +1011,20 @@ public final class CombatUtils { private static boolean shouldBeAffected(@NotNull Player player, @NotNull Entity entity) { if (entity instanceof Player defender) { //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()) { + if (!defender.getWorld().getPVP() || defender == player || UserManager.getPlayer( + defender).getGodMode()) { return false; } if (mcMMO.p.getPartyConfig().isPartyEnabled()) { if ((mcMMO.p.getPartyManager().inSameParty(player, defender) || mcMMO.p.getPartyManager().areAllies(player, defender)) - && !(Permissions.friendlyFire(player) && Permissions.friendlyFire(defender))) { + && !(Permissions.friendlyFire(player) && Permissions.friendlyFire( + defender))) { return false; } } @@ -949,7 +1033,7 @@ public final class CombatUtils { if (!player.canSee(defender)) { return false; } - + // Spectators should not be affected return defender.getGameMode() != GameMode.SPECTATOR; } else if (entity instanceof Tameable tameableEntity) { @@ -976,7 +1060,8 @@ public final class CombatUtils { * So apparently if you do more damage to a LivingEntity than its last damage int you bypass the invincibility. * So yeah, this is for that. */ - return (entity.getNoDamageTicks() > entity.getMaximumNoDamageTicks() / 2.0F) && (eventDamage <= entity.getLastDamage()); + return (entity.getNoDamageTicks() > entity.getMaximumNoDamageTicks() / 2.0F) && (eventDamage + <= entity.getLastDamage()); } /** @@ -1027,12 +1112,14 @@ public final class CombatUtils { return tier; } - public static void handleHealthbars(@NotNull Entity attacker, @NotNull LivingEntity target, double damage, @NotNull mcMMO plugin) { + public static void handleHealthbars(@NotNull Entity attacker, @NotNull LivingEntity target, + double damage, @NotNull mcMMO plugin) { if (!(attacker instanceof Player player)) { return; } - if (Misc.isNPCEntityExcludingVillagers(player) || Misc.isNPCEntityExcludingVillagers(target)) { + if (Misc.isNPCEntityExcludingVillagers(player) || Misc.isNPCEntityExcludingVillagers( + target)) { return; } @@ -1059,6 +1146,7 @@ public final class CombatUtils { * @param arrow the projectile */ public static void delayArrowMetaCleanup(@NotNull AbstractArrow arrow) { - mcMMO.p.getFoliaLib().getScheduler().runLater(() -> ProjectileUtils.cleanupProjectileMetadata(arrow), 20*120); + mcMMO.p.getFoliaLib().getScheduler() + .runLater(() -> ProjectileUtils.cleanupProjectileMetadata(arrow), 20 * 120); } } 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 a205dfdea..18791d4f2 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/ParticleEffectUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/ParticleEffectUtils.java @@ -8,7 +8,11 @@ import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.sounds.SoundManager; import com.gmail.nossr50.util.sounds.SoundType; import org.apache.commons.lang3.RandomUtils; -import org.bukkit.*; +import org.bukkit.Effect; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.SoundCategory; +import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.LivingEntity; @@ -17,7 +21,8 @@ import org.jetbrains.annotations.NotNull; public final class ParticleEffectUtils { - private ParticleEffectUtils() {} + private ParticleEffectUtils() { + } public static void playGreenThumbEffect(Location location) { World world = location.getWorld(); @@ -39,8 +44,10 @@ public final class ParticleEffectUtils { return; } - SoundManager.sendCategorizedSound(livingEntity.getLocation(), SoundType.CRIPPLE, SoundCategory.PLAYERS, 0.2F); - livingEntity.getWorld().playEffect(getParticleLocation(livingEntity), Effect.ANVIL_BREAK, null, 20); + SoundManager.sendCategorizedSound(livingEntity.getLocation(), SoundType.CRIPPLE, + SoundCategory.PLAYERS, 0.2F); + livingEntity.getWorld() + .playEffect(getParticleLocation(livingEntity), Effect.ANVIL_BREAK, null, 20); if (livingEntity instanceof Player player) { final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); @@ -93,8 +100,9 @@ public final class ParticleEffectUtils { return; } - if (location.getWorld() == null) + if (location.getWorld() == null) { return; + } location.getWorld().playEffect(location, Effect.MOBSPAWNER_FLAMES, 1); } @@ -102,8 +110,9 @@ public final class ParticleEffectUtils { public static void playSmokeEffect(Location location) { World world = location.getWorld(); - if (world == null) + if (world == null) { return; + } // Have to do it this way, because not all block directions are valid for smoke world.playEffect(location, Effect.SMOKE, BlockFace.SOUTH_EAST); @@ -124,7 +133,9 @@ public final class ParticleEffectUtils { Location location = livingEntity.getEyeLocation(); - livingEntity.getWorld().createExplosion(location.getX(), location.getY(), location.getZ(), 0F, false, false); + livingEntity.getWorld() + .createExplosion(location.getX(), location.getY(), location.getZ(), 0F, false, + false); } public static void playCallOfTheWildEffect(LivingEntity livingEntity) { @@ -132,7 +143,8 @@ public final class ParticleEffectUtils { return; } - livingEntity.getWorld().playEffect(livingEntity.getEyeLocation(), Effect.MOBSPAWNER_FLAMES, 1); + livingEntity.getWorld() + .playEffect(livingEntity.getEyeLocation(), Effect.MOBSPAWNER_FLAMES, 1); } public static void playAbilityDisabledEffect(Player player) { 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 44320b37a..176592999 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/PerksUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/PerksUtils.java @@ -14,7 +14,8 @@ 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)) { @@ -41,7 +42,8 @@ public final class PerksUtils { ticks += 4; } - final SkillActivationPerkEvent skillActivationPerkEvent = new SkillActivationPerkEvent(player, ticks, maxTicks); + final SkillActivationPerkEvent skillActivationPerkEvent = new SkillActivationPerkEvent( + player, ticks, maxTicks); Bukkit.getPluginManager().callEvent(skillActivationPerkEvent); return skillActivationPerkEvent.getTicks(); } @@ -50,11 +52,13 @@ public final class PerksUtils { double modifier = 1.0F; if (Permissions.customXpBoost(player, skill)) { - if (UserManager.getPlayer(player) != null && UserManager.getPlayer(player).isDebugMode()) { - player.sendMessage(ChatColor.GOLD + "[DEBUG] " + ChatColor.DARK_GRAY + "XP Perk Multiplier IS CUSTOM! "); + if (UserManager.getPlayer(player) != null && UserManager.getPlayer(player) + .isDebugMode()) { + player.sendMessage(ChatColor.GOLD + "[DEBUG] " + ChatColor.DARK_GRAY + + "XP Perk Multiplier IS CUSTOM! "); } - modifier = ExperienceConfig.getInstance().getCustomXpPerkBoost(); + modifier = ExperienceConfig.getInstance().getCustomXpPerkBoost(); } else if (Permissions.quadrupleXp(player, skill)) { modifier = 4; } else if (Permissions.tripleXp(player, skill)) { @@ -74,9 +78,13 @@ public final class PerksUtils { float modifiedXP = (float) (xp * modifier); if (UserManager.getPlayer(player) != null && UserManager.getPlayer(player).isDebugMode()) { - player.sendMessage(ChatColor.GOLD + "[DEBUG] " + ChatColor.RESET + "XP Perk Multiplier - " + ChatColor.GOLD + modifier); - player.sendMessage(ChatColor.GOLD + "[DEBUG] " + ChatColor.RESET + "Original XP before perk boosts " + ChatColor.RED + (double) xp); - player.sendMessage(ChatColor.GOLD + "[DEBUG] " + ChatColor.RESET + "XP AFTER PERKS " + ChatColor.DARK_RED + modifiedXP); + player.sendMessage( + ChatColor.GOLD + "[DEBUG] " + ChatColor.RESET + "XP Perk Multiplier - " + + ChatColor.GOLD + modifier); + player.sendMessage(ChatColor.GOLD + "[DEBUG] " + ChatColor.RESET + + "Original XP before perk boosts " + ChatColor.RED + (double) xp); + player.sendMessage(ChatColor.GOLD + "[DEBUG] " + ChatColor.RESET + "XP AFTER PERKS " + + ChatColor.DARK_RED + modifiedXP); } return modifiedXP; diff --git a/src/main/java/com/gmail/nossr50/util/skills/ProjectileUtils.java b/src/main/java/com/gmail/nossr50/util/skills/ProjectileUtils.java index 65dd281e2..d4e138096 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/ProjectileUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/ProjectileUtils.java @@ -1,5 +1,8 @@ package com.gmail.nossr50.util.skills; +import static com.gmail.nossr50.util.MetadataConstants.ARROW_METADATA_KEYS; +import static com.gmail.nossr50.util.MetadataConstants.MCMMO_METADATA_VALUE; + import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.MetadataConstants; import org.bukkit.block.BlockFace; @@ -11,9 +14,6 @@ import org.bukkit.plugin.Plugin; import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; -import static com.gmail.nossr50.util.MetadataConstants.ARROW_METADATA_KEYS; -import static com.gmail.nossr50.util.MetadataConstants.MCMMO_METADATA_VALUE; - public class ProjectileUtils { public static Vector getNormal(BlockFace blockFace) { @@ -47,13 +47,14 @@ public class ProjectileUtils { * @param targetArrow The arrow to which metadata is copied. */ public static void copyArrowMetadata(@NotNull Plugin pluginRef, @NotNull Arrow sourceArrow, - @NotNull Arrow targetArrow) { + @NotNull Arrow targetArrow) { ARROW_METADATA_KEYS.stream() .filter(sourceArrow::hasMetadata) .forEach(key -> { final MetadataValue metadataValue = sourceArrow.getMetadata(key).get(0); if (key.equals(MetadataConstants.METADATA_KEY_BOW_FORCE)) { - targetArrow.setMetadata(key, new FixedMetadataValue(pluginRef, metadataValue.asDouble())); + targetArrow.setMetadata(key, + new FixedMetadataValue(pluginRef, metadataValue.asDouble())); } else if (key.equals(MetadataConstants.METADATA_KEY_CROSSBOW_PROJECTILE)) { targetArrow.setMetadata(key, MCMMO_METADATA_VALUE); } else { 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 a9fba28fc..c2d258dce 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/RankUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/RankUtils.java @@ -11,41 +11,45 @@ import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.runnables.skills.SkillUnlockNotificationTask; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.UserManager; +import java.util.HashMap; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; -import java.util.HashMap; - public class RankUtils { private static HashMap> subSkillRanks; private static int count = 0; /** - * * @param plugin plugin instance ref - * @param mcMMOPlayer target player + * @param mmoPlayer target player * @param primarySkillType the skill to check * @param newLevel the new level of this skill */ - public static void executeSkillUnlockNotifications(Plugin plugin, McMMOPlayer mcMMOPlayer, PrimarySkillType primarySkillType, int newLevel) { - for(SubSkillType subSkillType : mcMMO.p.getSkillTools().getSubSkills(primarySkillType)) { - int playerRankInSkill = getRank(mcMMOPlayer.getPlayer(), subSkillType); + public static void executeSkillUnlockNotifications(Plugin plugin, McMMOPlayer mmoPlayer, + PrimarySkillType primarySkillType, int newLevel) { + for (SubSkillType subSkillType : mcMMO.p.getSkillTools().getSubSkills(primarySkillType)) { + int playerRankInSkill = getRank(mmoPlayer.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; + } //Don't send notifications if the player lacks the permission node - if (!Permissions.isSubSkillEnabled(mcMMOPlayer.getPlayer(), subSkillType)) + if (!Permissions.isSubSkillEnabled(mmoPlayer.getPlayer(), subSkillType)) { continue; + } //The players level is the exact level requirement for this skill if (newLevel == innerMap.get(playerRankInSkill)) { - SkillUnlockNotificationTask skillUnlockNotificationTask = new SkillUnlockNotificationTask(mcMMOPlayer, subSkillType, newLevel); + SkillUnlockNotificationTask skillUnlockNotificationTask = new SkillUnlockNotificationTask( + mmoPlayer, subSkillType, newLevel); - mcMMO.p.getFoliaLib().getScheduler().runAtEntityLater(mcMMOPlayer.getPlayer(), skillUnlockNotificationTask, (count * 100L)); + mcMMO.p.getFoliaLib().getScheduler() + .runAtEntityLater(mmoPlayer.getPlayer(), skillUnlockNotificationTask, + (count * 100L)); count++; } @@ -62,9 +66,9 @@ public class RankUtils { /* NEW SYSTEM */ 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());*/ @@ -73,9 +77,9 @@ public class RankUtils { 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());*/ @@ -86,17 +90,18 @@ public class RankUtils { * Populates the ranks for every skill we know about */ public static void populateRanks() { - for(SubSkillType subSkillType : SubSkillType.values()) { + for (SubSkillType subSkillType : SubSkillType.values()) { addRanks(subSkillType); } - for(AbstractSubSkill abstractSubSkill : InteractionManager.getSubSkillList()) { + for (AbstractSubSkill abstractSubSkill : InteractionManager.getSubSkillList()) { addRanks(abstractSubSkill); } } /** * Returns whether the player has unlocked the first rank in target subskill + * * @param player the player * @param subSkillType the target subskill * @return true if the player has at least one rank in the skill @@ -110,6 +115,7 @@ public class RankUtils { /** * Returns whether the player has unlocked the first rank in target subskill + * * @param player the player * @param abstractSubSkill the target subskill * @return true if the player has at least one rank in the skill @@ -123,6 +129,7 @@ public class RankUtils { /** * Returns whether the player has reached the specified rank in target subskill + * * @param rank the target rank * @param player the player * @param subSkillType the target subskill @@ -134,20 +141,24 @@ public class RankUtils { /** * Returns whether the player has reached the specified rank in target subskill + * * @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 mmoPlayer The player in question * @param subSkillType Target subskill - * @return The rank the player currently has achieved in this skill. -1 for skills without ranks. + * @return The rank the player currently has achieved in this skill. -1 for skills without + * ranks. */ public static int getRank(McMMOPlayer mmoPlayer, SubSkillType subSkillType) { return getRank(mmoPlayer.getPlayer(), subSkillType); @@ -155,44 +166,53 @@ public class RankUtils { /** * Gets the current rank of the subskill for the player + * * @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. + * @return The rank the player currently has achieved in this skill. -1 for skills without + * ranks. */ 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()); + 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; + } } return 0; //We should never reach this @@ -200,44 +220,53 @@ public class RankUtils { /** * Gets the current rank of the subskill for the player + * * @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. + * @return The rank the player currently has achieved in this skill. -1 for skills without + * ranks. */ 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()); + 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; + } } return 0; //We should never reach this @@ -245,6 +274,7 @@ public class RankUtils { /** * Adds ranks to our map + * * @param abstractSubSkill The subskill to add ranks for * @param rank The rank to add */ @@ -266,14 +296,16 @@ public class RankUtils { } private static void initMaps(String s) { - if (subSkillRanks == null) + if (subSkillRanks == null) { subSkillRanks = new HashMap<>(); + } subSkillRanks.computeIfAbsent(s, k -> new HashMap<>()); } /** * Gets the unlock level for a specific rank in a subskill + * * @param subSkillType The target subskill * @param rank The target rank * @return The level at which this rank unlocks @@ -288,6 +320,7 @@ public class RankUtils { /** * 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 */ @@ -297,6 +330,7 @@ public class RankUtils { /** * 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 */ @@ -306,6 +340,7 @@ public class RankUtils { /** * Get the highest rank of a subskill + * * @param subSkillType target subskill * @return the last rank of a subskill */ @@ -319,6 +354,7 @@ public class RankUtils { /** * Get the highest rank of a subskill + * * @param abstractSubSkill target subskill * @return the last rank of a subskill */ diff --git a/src/main/java/com/gmail/nossr50/util/skills/SkillTools.java b/src/main/java/com/gmail/nossr50/util/skills/SkillTools.java index d2da0aac8..e307c0b56 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/SkillTools.java +++ b/src/main/java/com/gmail/nossr50/util/skills/SkillTools.java @@ -13,14 +13,18 @@ import com.gmail.nossr50.util.text.StringUtils; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; +import java.util.ArrayList; +import java.util.Collections; +import java.util.EnumMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Tameable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.VisibleForTesting; -import java.util.*; - public class SkillTools { private final mcMMO pluginRef; // TODO: Java has immutable types now, switch to those @@ -46,9 +50,11 @@ public class SkillTools { static { ArrayList tempNonChildSkills = new ArrayList<>(); - for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { - if (primarySkillType != PrimarySkillType.SALVAGE && primarySkillType != PrimarySkillType.SMELTING) + for (PrimarySkillType primarySkillType : PrimarySkillType.values()) { + if (primarySkillType != PrimarySkillType.SALVAGE + && primarySkillType != PrimarySkillType.SMELTING) { tempNonChildSkills.add(primarySkillType); + } } NON_CHILD_SKILLS = ImmutableList.copyOf(tempNonChildSkills); @@ -62,11 +68,12 @@ public class SkillTools { /* * Setup subskill -> parent relationship map */ - EnumMap tempSubParentMap = new EnumMap<>(SubSkillType.class); + EnumMap tempSubParentMap = new EnumMap<>( + SubSkillType.class); //Super hacky and disgusting - for(PrimarySkillType primarySkillType1 : PrimarySkillType.values()) { - for(SubSkillType subSkillType : SubSkillType.values()) { + for (PrimarySkillType primarySkillType1 : PrimarySkillType.values()) { + for (SubSkillType subSkillType : SubSkillType.values()) { String[] splitSubSkillName = subSkillType.toString().split("_"); if (primarySkillType1.toString().equalsIgnoreCase(splitSubSkillName[0])) { @@ -82,15 +89,16 @@ public class SkillTools { * Setup primary -> (collection) subskill map */ - EnumMap> tempPrimaryChildMap = new EnumMap<>(PrimarySkillType.class); + EnumMap> tempPrimaryChildMap = new EnumMap<>( + PrimarySkillType.class); //Init the empty Hash Sets - for(PrimarySkillType primarySkillType1 : PrimarySkillType.values()) { + for (PrimarySkillType primarySkillType1 : PrimarySkillType.values()) { tempPrimaryChildMap.put(primarySkillType1, new HashSet<>()); } //Fill in the hash sets - for(SubSkillType subSkillType : SubSkillType.values()) { + for (SubSkillType subSkillType : SubSkillType.values()) { PrimarySkillType parentSkill = subSkillParentRelationshipMap.get(subSkillType); //Add this subskill as a child @@ -119,10 +127,12 @@ public class SkillTools { * Setup primary -> ability map */ - EnumMap tempAbilityParentRelationshipMap = new EnumMap<>(SuperAbilityType.class); - EnumMap tempMainActivatedAbilityChildMap = new EnumMap<>(PrimarySkillType.class); + EnumMap tempAbilityParentRelationshipMap = new EnumMap<>( + SuperAbilityType.class); + EnumMap tempMainActivatedAbilityChildMap = new EnumMap<>( + PrimarySkillType.class); - for(SuperAbilityType superAbilityType : SuperAbilityType.values()) { + for (SuperAbilityType superAbilityType : SuperAbilityType.values()) { try { PrimarySkillType parent = getSuperAbilityParent(superAbilityType); tempAbilityParentRelationshipMap.put(superAbilityType, parent); @@ -146,8 +156,9 @@ public class SkillTools { List childSkills = new ArrayList<>(); for (PrimarySkillType primarySkillType : PrimarySkillType.values()) { - if (isChildSkill(primarySkillType)) + if (isChildSkill(primarySkillType)) { childSkills.add(primarySkillType); + } } CHILD_SKILLS = ImmutableList.copyOf(childSkills); @@ -200,7 +211,8 @@ public class SkillTools { EXACT_SUBSKILL_NAMES = ImmutableSet.copyOf(buildExactSubSkillNameList()); } - private @NotNull PrimarySkillType getSuperAbilityParent(SuperAbilityType superAbilityType) throws InvalidSkillException { + private @NotNull PrimarySkillType getSuperAbilityParent(SuperAbilityType superAbilityType) + throws InvalidSkillException { return switch (superAbilityType) { case BERSERK -> PrimarySkillType.UNARMED; case GREEN_TERRA -> PrimarySkillType.HERBALISM; @@ -217,14 +229,14 @@ public class SkillTools { } /** - * Makes a list of the "nice" version of sub skill names - * Used in tab completion mostly + * Makes a list of the "nice" version of sub skill names Used in tab completion mostly + * * @return a list of formatted sub skill names */ private @NotNull ArrayList buildFormattedSubSkillNameList() { ArrayList subSkillNameList = new ArrayList<>(); - for(SubSkillType subSkillType : SubSkillType.values()) { + for (SubSkillType subSkillType : SubSkillType.values()) { subSkillNameList.add(subSkillType.getNiceNameNoSpaces(subSkillType)); } @@ -234,7 +246,7 @@ public class SkillTools { private @NotNull HashSet buildExactSubSkillNameList() { HashSet subSkillNameExactSet = new HashSet<>(); - for(SubSkillType subSkillType : SubSkillType.values()) { + for (SubSkillType subSkillType : SubSkillType.values()) { subSkillNameExactSet.add(subSkillType.toString()); } @@ -243,13 +255,14 @@ public class SkillTools { /** * Builds a list of localized {@link PrimarySkillType} names + * * @return list of localized {@link PrimarySkillType} names */ @VisibleForTesting private @NotNull ArrayList buildLocalizedPrimarySkillNames() { ArrayList localizedSkillNameList = new ArrayList<>(); - for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { + for (PrimarySkillType primarySkillType : PrimarySkillType.values()) { localizedSkillNameList.add(getLocalizedSkillName(primarySkillType)); } @@ -259,10 +272,9 @@ public class SkillTools { } /** - * Matches a string of a skill to a skill - * This is NOT case sensitive - * First it checks the locale file and tries to match by the localized name of the skill - * Then if nothing is found it checks against the hard coded "name" of the skill, which is just its name in English + * Matches a string of a skill to a skill This is NOT case sensitive First it checks the locale + * file and tries to match by the localized name of the skill Then if nothing is found it checks + * against the hard coded "name" of the skill, which is just its name in English * * @param skillName target skill name * @return the matching PrimarySkillType if one is found, otherwise null @@ -270,7 +282,8 @@ public class SkillTools { public PrimarySkillType matchSkill(String skillName) { if (!pluginRef.getGeneralConfig().getLocale().equalsIgnoreCase("en_US")) { for (PrimarySkillType type : PrimarySkillType.values()) { - if (skillName.equalsIgnoreCase(LocaleLoader.getString(StringUtils.getCapitalized(type.name()) + ".SkillName"))) { + if (skillName.equalsIgnoreCase(LocaleLoader.getString( + StringUtils.getCapitalized(type.name()) + ".SkillName"))) { return type; } } @@ -283,15 +296,17 @@ public class SkillTools { } if (!skillName.equalsIgnoreCase("all")) { - pluginRef.getLogger().warning("Invalid mcMMO skill (" + skillName + ")"); //TODO: Localize + pluginRef.getLogger() + .warning("Invalid mcMMO skill (" + skillName + ")"); //TODO: Localize } return null; } /** - * Gets the PrimarySkillStype to which a SubSkillType belongs - * Return null if it does not belong to one.. which should be impossible in most circumstances + * Gets the PrimarySkillStype to which a SubSkillType belongs Return null if it does not belong + * to one.. which should be impossible in most circumstances + * * @param subSkillType target subskill * @return the PrimarySkillType of this SubSkill, null if it doesn't exist */ @@ -300,8 +315,9 @@ public class SkillTools { } /** - * Gets the PrimarySkillStype to which a SuperAbilityType belongs - * Return null if it does not belong to one.. which should be impossible in most circumstances + * Gets the PrimarySkillStype to which a SuperAbilityType belongs Return null if it does not + * belong to one.. which should be impossible in most circumstances + * * @param superAbilityType target super ability * @return the PrimarySkillType of this SuperAbilityType, null if it doesn't exist */ @@ -310,14 +326,16 @@ public class SkillTools { } public SuperAbilityType getSuperAbility(PrimarySkillType primarySkillType) { - if (mainActivatedAbilityChildMap.get(primarySkillType) == null) + if (mainActivatedAbilityChildMap.get(primarySkillType) == null) { return null; + } return mainActivatedAbilityChildMap.get(primarySkillType); } public boolean isSuperAbilityUnlocked(PrimarySkillType primarySkillType, Player player) { - SuperAbilityType superAbilityType = mcMMO.p.getSkillTools().getSuperAbility(primarySkillType); + SuperAbilityType superAbilityType = mcMMO.p.getSkillTools() + .getSuperAbility(primarySkillType); SubSkillType subSkillType = superAbilityType.getSubSkillTypeDefinition(); return RankUtils.hasUnlockedSubskill(player, subSkillType); } @@ -360,11 +378,13 @@ public class SkillTools { /** * Get the localized name for a {@link PrimarySkillType} + * * @param primarySkillType target {@link PrimarySkillType} * @return the localized name for a {@link PrimarySkillType} */ public String getLocalizedSkillName(PrimarySkillType primarySkillType) { - return LocaleLoader.getString(StringUtils.getCapitalized(primarySkillType.toString()) + ".SkillName"); + return LocaleLoader.getString( + StringUtils.getCapitalized(primarySkillType.toString()) + ".SkillName"); } public boolean doesPlayerHaveSkillPermission(Player player, PrimarySkillType primarySkillType) { @@ -372,7 +392,9 @@ public class SkillTools { } public boolean canCombatSkillsTrigger(PrimarySkillType primarySkillType, Entity target) { - return (target instanceof Player || (target instanceof Tameable && ((Tameable) target).isTamed())) ? getPVPEnabled(primarySkillType) : getPVEEnabled(primarySkillType); + return (target instanceof Player || (target instanceof Tameable + && ((Tameable) target).isTamed())) ? getPVPEnabled(primarySkillType) + : getPVEEnabled(primarySkillType); } public String getCapitalizedPrimarySkillName(PrimarySkillType primarySkillType) { @@ -422,7 +444,8 @@ public class SkillTools { return MISC_SKILLS; } - public @NotNull ImmutableList getChildSkillParents(PrimarySkillType childSkill) + public @NotNull ImmutableList getChildSkillParents( + PrimarySkillType childSkill) throws IllegalArgumentException { switch (childSkill) { case SALVAGE -> { @@ -431,7 +454,8 @@ public class SkillTools { case SMELTING -> { return SMELTING_PARENTS; } - default -> throw new IllegalArgumentException("Skill " + childSkill + " is not a child skill"); + default -> throw new IllegalArgumentException( + "Skill " + childSkill + " is not a child skill"); } } } 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 23843c1bc..eb0307e17 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java @@ -1,5 +1,10 @@ package com.gmail.nossr50.util.skills; +import static com.gmail.nossr50.util.ItemMetadataUtils.isLegacyAbilityTool; +import static com.gmail.nossr50.util.ItemMetadataUtils.isSuperAbilityBoosted; +import static com.gmail.nossr50.util.ItemMetadataUtils.removeBonusDigSpeedOnSuperAbilityTool; +import static com.gmail.nossr50.util.PotionEffectUtil.getHastePotionEffectType; + import com.gmail.nossr50.config.HiddenConfig; import com.gmail.nossr50.datatypes.experience.XPGainReason; import com.gmail.nossr50.datatypes.experience.XPGainSource; @@ -17,6 +22,7 @@ import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.NotificationManager; import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.text.StringUtils; +import java.util.Iterator; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; @@ -30,39 +36,39 @@ import org.bukkit.potion.PotionEffect; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Iterator; - -import static com.gmail.nossr50.util.ItemMetadataUtils.*; -import static com.gmail.nossr50.util.PotionEffectUtil.getHastePotionEffectType; - public final class SkillUtils { /** - * This is a static utility class, therefore we don't want any instances of - * this class. Making the constructor private prevents accidents like that. + * This is a static utility class, therefore we don't want any instances of this class. Making + * the constructor private prevents accidents like that. */ - private SkillUtils() {} - - public static void applyXpGain(McMMOPlayer mcMMOPlayer, PrimarySkillType skill, float xp, XPGainReason xpGainReason) { - mcMMOPlayer.beginXpGain(skill, xp, xpGainReason, XPGainSource.SELF); + private SkillUtils() { } - public static void applyXpGain(McMMOPlayer mcMMOPlayer, PrimarySkillType skill, float xp, XPGainReason xpGainReason, XPGainSource xpGainSource) { - mcMMOPlayer.beginXpGain(skill, xp, xpGainReason, xpGainSource); + public static void applyXpGain(McMMOPlayer mmoPlayer, PrimarySkillType skill, float xp, + XPGainReason xpGainReason) { + mmoPlayer.beginXpGain(skill, xp, xpGainReason, XPGainSource.SELF); + } + + public static void applyXpGain(McMMOPlayer mmoPlayer, PrimarySkillType skill, float xp, + XPGainReason xpGainReason, XPGainSource xpGainSource) { + mmoPlayer.beginXpGain(skill, xp, xpGainReason, xpGainSource); } /* * Skill Stat Calculations */ - public static String[] calculateLengthDisplayValues(Player player, float skillValue, PrimarySkillType skill) { - int maxLength = mcMMO.p.getSkillTools().getSuperAbilityMaxLength(mcMMO.p.getSkillTools().getSuperAbility(skill)); + public static String[] calculateLengthDisplayValues(Player player, float skillValue, + PrimarySkillType skill) { + int maxLength = mcMMO.p.getSkillTools() + .getSuperAbilityMaxLength(mcMMO.p.getSkillTools().getSuperAbility(skill)); int abilityLengthVar = mcMMO.p.getAdvancedConfig().getAbilityLength(); int abilityLengthCap = mcMMO.p.getAdvancedConfig().getAbilityLengthCap(); int length; if (abilityLengthCap > 0) { - length = (int) Math.min(abilityLengthCap, 2 + (skillValue / abilityLengthVar)); + length = (int) Math.min(abilityLengthCap, 2 + (skillValue / abilityLengthVar)); } else { length = 2 + (int) (skillValue / abilityLengthVar); } @@ -73,20 +79,21 @@ public final 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)}; } /* * Others */ - public static int handleFoodSkills(Player player, int eventFoodLevel, SubSkillType subSkillType) { + public static int handleFoodSkills(Player player, int eventFoodLevel, + SubSkillType subSkillType) { int curRank = RankUtils.getRank(player, subSkillType); int currentFoodLevel = player.getFoodLevel(); int foodChange = eventFoodLevel - currentFoodLevel; - foodChange+=curRank; + foodChange += curRank; return currentFoodLevel + foodChange; } @@ -97,24 +104,24 @@ public final class SkillUtils { * @param deactivatedTimeStamp Time of deactivation * @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) { - return (int) (((deactivatedTimeStamp + (PerksUtils.handleCooldownPerks(player, cooldown) * Misc.TIME_CONVERSION_FACTOR)) - System.currentTimeMillis()) / Misc.TIME_CONVERSION_FACTOR); + return (int) (((deactivatedTimeStamp + (PerksUtils.handleCooldownPerks(player, cooldown) + * Misc.TIME_CONVERSION_FACTOR)) - System.currentTimeMillis()) + / Misc.TIME_CONVERSION_FACTOR); } /** - * Check if the cooldown has expired. - * This does NOT account for cooldown perks! + * Check if the cooldown has expired. This does NOT account for cooldown perks! * * @param deactivatedTimeStamp Time of deactivation 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) { - return System.currentTimeMillis() >= (deactivatedTimeStamp + cooldown) * Misc.TIME_CONVERSION_FACTOR; + return System.currentTimeMillis() + >= (deactivatedTimeStamp + cooldown) * Misc.TIME_CONVERSION_FACTOR; } /** @@ -124,15 +131,19 @@ public final class SkillUtils { * @return true if this is a valid skill, false otherwise */ public static boolean isSkill(String skillName) { - return mcMMO.p.getGeneralConfig().getLocale().equalsIgnoreCase("en_US") ? mcMMO.p.getSkillTools().matchSkill(skillName) != null : isLocalizedSkill(skillName); + return mcMMO.p.getGeneralConfig().getLocale().equalsIgnoreCase("en_US") ? + mcMMO.p.getSkillTools().matchSkill(skillName) != null : isLocalizedSkill(skillName); } - public static void sendSkillMessage(Player player, NotificationType notificationType, String key) { + public static void sendSkillMessage(Player player, NotificationType notificationType, + String key) { Location location = player.getLocation(); for (Player otherPlayer : player.getWorld().getPlayers()) { - if (otherPlayer != player && Misc.isNear(location, otherPlayer.getLocation(), Misc.SKILL_MESSAGE_MAX_SENDING_DISTANCE)) { - NotificationManager.sendNearbyPlayersInformation(otherPlayer, notificationType, key, player.getName()); + if (otherPlayer != player && Misc.isNear(location, otherPlayer.getLocation(), + Misc.SKILL_MESSAGE_MAX_SENDING_DISTANCE)) { + NotificationManager.sendNearbyPlayersInformation(otherPlayer, notificationType, key, + player.getName()); } } } @@ -141,15 +152,18 @@ public final class SkillUtils { if (HiddenConfig.getInstance().useEnchantmentBuffs()) { ItemStack heldItem = player.getInventory().getItemInMainHand(); - if (heldItem == null) + if (heldItem == null) { return; + } if (!ItemUtils.canBeSuperAbilityDigBoosted(heldItem)) { return; } - int originalDigSpeed = heldItem.getEnchantmentLevel(mcMMO.p.getEnchantmentMapper().getEfficiency()); - ItemUtils.addDigSpeedToItem(heldItem, heldItem.getEnchantmentLevel(mcMMO.p.getEnchantmentMapper().getEfficiency())); + int originalDigSpeed = heldItem.getEnchantmentLevel( + mcMMO.p.getEnchantmentMapper().getEfficiency()); + ItemUtils.addDigSpeedToItem(heldItem, + heldItem.getEnchantmentLevel(mcMMO.p.getEnchantmentMapper().getEfficiency())); //1.13.2+ will have persistent metadata for this item ItemMetadataUtils.setSuperAbilityBoostedItem(heldItem, originalDigSpeed); @@ -167,13 +181,15 @@ public final class SkillUtils { } } - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); //Not Loaded - if (mcMMOPlayer == null) + if (mmoPlayer == null) { return; + } - PrimarySkillType skill = mcMMOPlayer.getAbilityMode(SuperAbilityType.SUPER_BREAKER) ? PrimarySkillType.MINING : PrimarySkillType.EXCAVATION; + PrimarySkillType skill = mmoPlayer.getAbilityMode(SuperAbilityType.SUPER_BREAKER) + ? PrimarySkillType.MINING : PrimarySkillType.EXCAVATION; int abilityLengthVar = mcMMO.p.getAdvancedConfig().getAbilityLength(); int abilityLengthCap = mcMMO.p.getAdvancedConfig().getAbilityLengthCap(); @@ -181,14 +197,21 @@ public final class SkillUtils { int ticks; if (abilityLengthCap > 0) { - ticks = PerksUtils.handleActivationPerks(player, Math.min(abilityLengthCap, 2 + (mcMMOPlayer.getSkillLevel(skill) / abilityLengthVar)), - mcMMO.p.getSkillTools().getSuperAbilityMaxLength(mcMMO.p.getSkillTools().getSuperAbility(skill))) * Misc.TICK_CONVERSION_FACTOR; + ticks = PerksUtils.handleActivationPerks(player, Math.min(abilityLengthCap, + 2 + (mmoPlayer.getSkillLevel(skill) / abilityLengthVar)), + mcMMO.p.getSkillTools().getSuperAbilityMaxLength( + mcMMO.p.getSkillTools().getSuperAbility(skill))) + * Misc.TICK_CONVERSION_FACTOR; } else { - ticks = PerksUtils.handleActivationPerks(player, 2 + ((mcMMOPlayer.getSkillLevel(skill)) / abilityLengthVar), - mcMMO.p.getSkillTools().getSuperAbilityMaxLength(mcMMO.p.getSkillTools().getSuperAbility(skill))) * Misc.TICK_CONVERSION_FACTOR; + ticks = PerksUtils.handleActivationPerks(player, + 2 + ((mmoPlayer.getSkillLevel(skill)) / abilityLengthVar), + mcMMO.p.getSkillTools().getSuperAbilityMaxLength( + mcMMO.p.getSkillTools().getSuperAbility(skill))) + * Misc.TICK_CONVERSION_FACTOR; } - PotionEffect abilityBuff = new PotionEffect(getHastePotionEffectType(), duration + ticks, amplifier + 10); + PotionEffect abilityBuff = new PotionEffect(getHastePotionEffectType(), + duration + ticks, amplifier + 10); player.addPotionEffect(abilityBuff, true); } } @@ -200,12 +223,13 @@ public final class SkillUtils { } public static void removeAbilityBuff(@Nullable ItemStack itemStack) { - if (itemStack == null) + if (itemStack == null) { return; + } - if (!ItemUtils.canBeSuperAbilityDigBoosted(itemStack)) + if (!ItemUtils.canBeSuperAbilityDigBoosted(itemStack)) { return; - + } //1.13.2+ will have persistent metadata for this itemStack if (isLegacyAbilityTool(itemStack)) { @@ -230,27 +254,35 @@ public final class SkillUtils { } /** - * Modify the durability of an ItemStack, using Tools specific formula for unbreaking enchant damage reduction + * Modify the durability of an ItemStack, using Tools specific formula for unbreaking enchant + * damage reduction * * @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 */ - public static void handleDurabilityChange(ItemStack itemStack, double durabilityModifier, double maxDamageModifier) { + public static void handleDurabilityChange(ItemStack itemStack, double durabilityModifier, + double maxDamageModifier) { if (itemStack.hasItemMeta() && itemStack.getItemMeta().isUnbreakable()) { return; } Material type = itemStack.getType(); - short maxDurability = mcMMO.getRepairableManager().isRepairable(type) ? mcMMO.getRepairableManager().getRepairable(type).getMaximumDurability() : type.getMaxDurability(); - durabilityModifier = (int) Math.min(durabilityModifier / (itemStack.getEnchantmentLevel(mcMMO.p.getEnchantmentMapper().getUnbreaking()) + 1), maxDurability * maxDamageModifier); + short maxDurability = + mcMMO.getRepairableManager().isRepairable(type) ? mcMMO.getRepairableManager() + .getRepairable(type).getMaximumDurability() : type.getMaxDurability(); + durabilityModifier = (int) Math.min(durabilityModifier / ( + itemStack.getEnchantmentLevel(mcMMO.p.getEnchantmentMapper().getUnbreaking()) + 1), + maxDurability * maxDamageModifier); - itemStack.setDurability((short) Math.min(itemStack.getDurability() + durabilityModifier, maxDurability)); + itemStack.setDurability( + (short) Math.min(itemStack.getDurability() + durabilityModifier, maxDurability)); } private static boolean isLocalizedSkill(String skillName) { for (PrimarySkillType skill : PrimarySkillType.values()) { - if (skillName.equalsIgnoreCase(LocaleLoader.getString(StringUtils.getCapitalized(skill.toString()) + ".SkillName"))) { + if (skillName.equalsIgnoreCase(LocaleLoader.getString( + StringUtils.getCapitalized(skill.toString()) + ".SkillName"))) { return true; } } @@ -260,22 +292,29 @@ public final class SkillUtils { /** - * Modify the durability of an ItemStack, using Armor specific formula for unbreaking enchant damage reduction + * Modify the durability of an ItemStack, using Armor specific formula for unbreaking enchant + * damage reduction * * @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 */ - public static void handleArmorDurabilityChange(ItemStack itemStack, double durabilityModifier, double maxDamageModifier) { + public static void handleArmorDurabilityChange(ItemStack itemStack, double durabilityModifier, + double maxDamageModifier) { if (itemStack.hasItemMeta() && itemStack.getItemMeta().isUnbreakable()) { return; } Material type = itemStack.getType(); - short maxDurability = mcMMO.getRepairableManager().isRepairable(type) ? mcMMO.getRepairableManager().getRepairable(type).getMaximumDurability() : type.getMaxDurability(); - durabilityModifier = (int) Math.min(durabilityModifier * (0.6 + 0.4/ (itemStack.getEnchantmentLevel(mcMMO.p.getEnchantmentMapper().getUnbreaking()) + 1)), maxDurability * maxDamageModifier); + short maxDurability = + mcMMO.getRepairableManager().isRepairable(type) ? mcMMO.getRepairableManager() + .getRepairable(type).getMaximumDurability() : type.getMaxDurability(); + durabilityModifier = (int) Math.min(durabilityModifier * (0.6 + 0.4 / ( + itemStack.getEnchantmentLevel(mcMMO.p.getEnchantmentMapper().getUnbreaking()) + 1)), + maxDurability * maxDamageModifier); - itemStack.setDurability((short) Math.min(itemStack.getDurability() + durabilityModifier, maxDurability)); + itemStack.setDurability( + (short) Math.min(itemStack.getDurability() + durabilityModifier, maxDurability)); } @Nullable @@ -307,7 +346,8 @@ public final class SkillUtils { return getRepairAndSalvageQuantities(item.getType(), getRepairAndSalvageItem(item)); } - public static int getRepairAndSalvageQuantities(Material itemMaterial, Material recipeMaterial) { + public static int getRepairAndSalvageQuantities(Material itemMaterial, + Material recipeMaterial) { int quantity = 0; if (mcMMO.getMaterialMapStore().isPrismarineTool(itemMaterial)) { @@ -320,11 +360,13 @@ public final class SkillUtils { return 4; } - for(Iterator recipeIterator = Bukkit.getServer().recipeIterator(); recipeIterator.hasNext();) { + for (Iterator recipeIterator = Bukkit.getServer().recipeIterator(); + recipeIterator.hasNext(); ) { Recipe bukkitRecipe = recipeIterator.next(); - if (bukkitRecipe.getResult().getType() != itemMaterial) + if (bukkitRecipe.getResult().getType() != itemMaterial) { continue; + } if (bukkitRecipe instanceof ShapelessRecipe) { for (ItemStack ingredient : ((ShapelessRecipe) bukkitRecipe).getIngredientList()) { @@ -335,7 +377,8 @@ public final class SkillUtils { } } } else if (bukkitRecipe instanceof ShapedRecipe) { - for (ItemStack ingredient : ((ShapedRecipe) bukkitRecipe).getIngredientMap().values()) { + for (ItemStack ingredient : ((ShapedRecipe) bukkitRecipe).getIngredientMap() + .values()) { if (ingredient != null && (recipeMaterial == null || ingredient.getType() == recipeMaterial) && (ingredient.getType() == recipeMaterial)) { @@ -350,11 +393,13 @@ public final class SkillUtils { /** * Checks if a player can use a skill + * * @param player target player * @param subSkillType target subskill * @return true if the player has permission and has the skill unlocked */ public static boolean canUseSubskill(Player player, @NotNull SubSkillType subSkillType) { - return Permissions.isSubSkillEnabled(player, subSkillType) && RankUtils.hasUnlockedSubskill(player, subSkillType); + return Permissions.isSubSkillEnabled(player, subSkillType) && RankUtils.hasUnlockedSubskill( + player, subSkillType); } } 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 13b7d9555..a345f1bc7 100644 --- a/src/main/java/com/gmail/nossr50/util/sounds/SoundManager.java +++ b/src/main/java/com/gmail/nossr50/util/sounds/SoundManager.java @@ -2,15 +2,14 @@ package com.gmail.nossr50.util.sounds; import com.gmail.nossr50.config.SoundConfig; import com.gmail.nossr50.util.Misc; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import org.bukkit.Location; import org.bukkit.Sound; import org.bukkit.SoundCategory; import org.bukkit.World; import org.bukkit.entity.Player; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - public class SoundManager { private static Sound CRIPPLE_SOUND; @@ -22,15 +21,18 @@ 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)) + if (SoundConfig.getInstance().getIsEnabled(soundType)) { player.playSound(location, getSound(soundType), SoundCategory.MASTER, getVolume(soundType), getPitch(soundType)); + } } - public static void sendCategorizedSound(Location location, SoundType soundType, SoundCategory soundCategory) { + public static void sendCategorizedSound(Location location, SoundType soundType, + SoundCategory soundCategory) { if (SoundConfig.getInstance().getIsEnabled(soundType)) { final World world = location.getWorld(); if (world != null) { @@ -40,57 +42,69 @@ public class SoundManager { } } - public static void sendCategorizedSound(Location location, SoundType soundType, SoundCategory soundCategory, - float pitchModifier) { + public static void sendCategorizedSound(Location location, SoundType soundType, + SoundCategory soundCategory, + float pitchModifier) { if (SoundConfig.getInstance().getIsEnabled(soundType)) { final World world = location.getWorld(); if (world != null) { float totalPitch = Math.min(2.0F, (getPitch(soundType) + pitchModifier)); - world.playSound(location, getSound(soundType), soundCategory, getVolume(soundType), totalPitch); + world.playSound(location, getSound(soundType), soundCategory, getVolume(soundType), + totalPitch); } } } 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)); + 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) { + SoundType soundType, SoundCategory soundCategory, float pitchModifier) { float totalPitch = Math.min(2.0F, (getPitch(soundType) + pitchModifier)); - if (SoundConfig.getInstance().getIsEnabled(soundType)) - player.playSound(location, getSound(soundType), soundCategory, getVolume(soundType), totalPitch); + 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)) - world.playSound(location, getSound(soundType), getVolume(soundType), getPitch(soundType)); + if (SoundConfig.getInstance().getIsEnabled(soundType)) { + world.playSound(location, getSound(soundType), getVolume(soundType), + getPitch(soundType)); + } } public static void worldSendSoundMaxPitch(World world, Location location, SoundType soundType) { - if (SoundConfig.getInstance().getIsEnabled(soundType)) + if (SoundConfig.getInstance().getIsEnabled(soundType)) { world.playSound(location, getSound(soundType), getVolume(soundType), 2.0F); + } } /** * 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) { - return SoundConfig.getInstance().getVolume(soundType) * SoundConfig.getInstance().getMasterVolume(); + return SoundConfig.getInstance().getVolume(soundType) * SoundConfig.getInstance() + .getMasterVolume(); } private static float getPitch(SoundType soundType) { - if (soundType == SoundType.FIZZ) + if (soundType == SoundType.FIZZ) { return getFizzPitch(); - else if (soundType == SoundType.POP) + } else if (soundType == SoundType.POP) { return getPopPitch(); - else + } else { return SoundConfig.getInstance().getPitch(soundType); + } } private static Sound getSound(SoundType soundType) { @@ -123,7 +137,8 @@ public class SoundManager { final Class clazz = Class.forName(ORG_BUKKIT_SOUND); final Method valueOf = clazz.getMethod(VALUE_OF); CRIPPLE_SOUND = (Sound) valueOf.invoke(null, ITEM_MACE_SMASH_GROUND); - } catch (IllegalArgumentException | ClassNotFoundException | NoSuchMethodException | InvocationTargetException + } catch (IllegalArgumentException | ClassNotFoundException | NoSuchMethodException | + InvocationTargetException | IllegalAccessException e) { CRIPPLE_SOUND = Sound.BLOCK_ANVIL_PLACE; } 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 21c1a0d93..7a0056537 100644 --- a/src/main/java/com/gmail/nossr50/util/sounds/SoundType.java +++ b/src/main/java/com/gmail/nossr50/util/sounds/SoundType.java @@ -20,7 +20,7 @@ public enum SoundType { TIRED; public boolean usesCustomPitch() { - switch(this){ + switch (this) { case POP: case FIZZ: return true; diff --git a/src/main/java/com/gmail/nossr50/util/text/ConfigStringUtils.java b/src/main/java/com/gmail/nossr50/util/text/ConfigStringUtils.java index 0e28be1e6..32ec8f33e 100644 --- a/src/main/java/com/gmail/nossr50/util/text/ConfigStringUtils.java +++ b/src/main/java/com/gmail/nossr50/util/text/ConfigStringUtils.java @@ -1,18 +1,18 @@ package com.gmail.nossr50.util.text; +import static com.gmail.nossr50.util.text.StringUtils.getCapitalized; + import com.gmail.nossr50.datatypes.party.PartyFeature; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; import org.bukkit.Material; import org.bukkit.entity.EntityType; import org.jetbrains.annotations.NotNull; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Function; - -import static com.gmail.nossr50.util.text.StringUtils.getCapitalized; - /** - * Utility class for String operations, including formatting and caching deterministic results to improve performance. + * Utility class for String operations, including formatting and caching deterministic results to + * improve performance. */ public class ConfigStringUtils { public static final String UNDERSCORE = "_"; @@ -24,11 +24,13 @@ public class ConfigStringUtils { private static final Map configPartyFeatureStrings = new ConcurrentHashMap<>(); public static String getMaterialConfigString(Material material) { - return configMaterialStrings.computeIfAbsent(material, ConfigStringUtils::createConfigFriendlyString); + return configMaterialStrings.computeIfAbsent(material, + ConfigStringUtils::createConfigFriendlyString); } public static String getConfigEntityTypeString(EntityType entityType) { - return configEntityStrings.computeIfAbsent(entityType, ConfigStringUtils::createConfigFriendlyString); + return configEntityStrings.computeIfAbsent(entityType, + ConfigStringUtils::createConfigFriendlyString); } public static String getConfigPartyFeatureString(PartyFeature partyFeature) { @@ -45,9 +47,9 @@ public class ConfigStringUtils { if (baseString.contains(UNDERSCORE) && !baseString.contains(SPACE)) { return asConfigFormat(baseString.split(UNDERSCORE)); } else { - if(baseString.contains(SPACE)) { + if (baseString.contains(SPACE)) { return asConfigFormat(baseString.split(SPACE)); - } else{ + } else { return getCapitalized(baseString); } } diff --git a/src/main/java/com/gmail/nossr50/util/text/McMMOMessageType.java b/src/main/java/com/gmail/nossr50/util/text/McMMOMessageType.java index f4fb0d7bb..8ac40fd80 100644 --- a/src/main/java/com/gmail/nossr50/util/text/McMMOMessageType.java +++ b/src/main/java/com/gmail/nossr50/util/text/McMMOMessageType.java @@ -1,15 +1,15 @@ package com.gmail.nossr50.util.text; +import java.util.function.BiConsumer; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.MessageType; import net.kyori.adventure.identity.Identity; import net.kyori.adventure.text.Component; -import java.util.function.BiConsumer; - public enum McMMOMessageType { ACTION_BAR(Audience::sendActionBar), - SYSTEM((audience, message) -> audience.sendMessage(Identity.nil(), message, MessageType.SYSTEM)); + SYSTEM((audience, message) -> audience.sendMessage(Identity.nil(), message, + MessageType.SYSTEM)); private final BiConsumer sender; @@ -18,6 +18,6 @@ public enum McMMOMessageType { } public void send(final Audience audience, final Component message) { - this.sender.accept(audience, message); + this.sender.accept(audience, message); } } diff --git a/src/main/java/com/gmail/nossr50/util/text/StringUtils.java b/src/main/java/com/gmail/nossr50/util/text/StringUtils.java index 436261fa4..73ca90919 100644 --- a/src/main/java/com/gmail/nossr50/util/text/StringUtils.java +++ b/src/main/java/com/gmail/nossr50/util/text/StringUtils.java @@ -1,26 +1,28 @@ package com.gmail.nossr50.util.text; -import com.gmail.nossr50.datatypes.skills.SuperAbilityType; -import org.bukkit.Material; -import org.bukkit.entity.EntityType; -import org.jetbrains.annotations.NotNull; +import static java.util.Objects.requireNonNull; +import com.gmail.nossr50.datatypes.skills.SuperAbilityType; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; - -import static java.util.Objects.requireNonNull; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.jetbrains.annotations.NotNull; /** - * Utility class for String operations, including formatting and caching deterministic results to improve performance. + * Utility class for String operations, including formatting and caching deterministic results to + * improve performance. */ public class StringUtils { - protected static final DecimalFormat percent = new DecimalFormat("##0.00%", DecimalFormatSymbols.getInstance(Locale.US)); - protected static final DecimalFormat shortDecimal = new DecimalFormat("##0.0", DecimalFormatSymbols.getInstance(Locale.US)); + protected static final DecimalFormat percent = new DecimalFormat("##0.00%", + DecimalFormatSymbols.getInstance(Locale.US)); + protected static final DecimalFormat shortDecimal = new DecimalFormat("##0.0", + DecimalFormatSymbols.getInstance(Locale.US)); // Using concurrent hash maps to avoid concurrency issues (Folia) private static final Map formattedEntityStrings = new ConcurrentHashMap<>(); @@ -28,8 +30,7 @@ public class StringUtils { private static final Map formattedMaterialStrings = new ConcurrentHashMap<>(); /** - * Gets a capitalized version of the target string. - * Results are cached to improve performance. + * Gets a capitalized version of the target string. Results are cached to improve performance. * * @param target String to capitalize * @return the capitalized string @@ -38,7 +39,8 @@ public class StringUtils { if (target == null || target.isEmpty()) { return target; } - return target.substring(0, 1).toUpperCase(Locale.ENGLISH) + target.substring(1).toLowerCase(Locale.ENGLISH); + return target.substring(0, 1).toUpperCase(Locale.ENGLISH) + target.substring(1) + .toLowerCase(Locale.ENGLISH); } /** @@ -52,27 +54,29 @@ public class StringUtils { } /** - * Gets a pretty string representation of a SuperAbilityType. - * Results are cached to improve performance. + * Gets a pretty string representation of a SuperAbilityType. Results are cached to improve + * performance. * * @param superAbilityType SuperAbilityType to convert * @return Pretty string representation of the SuperAbilityType */ public static String getPrettySuperAbilityString(SuperAbilityType superAbilityType) { requireNonNull(superAbilityType, "superAbilityType cannot be null"); - return formattedSuperAbilityStrings.computeIfAbsent(superAbilityType, StringUtils::createPrettyString); + return formattedSuperAbilityStrings.computeIfAbsent(superAbilityType, + StringUtils::createPrettyString); } /** * Creates a string from an array skipping the first n elements. * - * @param args The array to iterate over when forming the string + * @param args The array to iterate over when forming the string * @param index The number of elements to skip over * @return The "trimmed" string */ public static String buildStringAfterNthElement(@NotNull String @NotNull [] args, int index) { - if (index < 0) + if (index < 0) { throw new IllegalArgumentException("Index must be greater than or equal to 0"); + } final StringBuilder trimMessage = new StringBuilder(); @@ -87,8 +91,8 @@ public class StringUtils { } /** - * Gets a pretty string representation of a Material. - * Results are cached to improve performance. + * Gets a pretty string representation of a Material. Results are cached to improve + * performance. * * @param material Material to convert * @return Pretty string representation of the Material @@ -98,8 +102,8 @@ public class StringUtils { } /** - * Gets a pretty string representation of an EntityType. - * Results are cached to improve performance. + * Gets a pretty string representation of an EntityType. Results are cached to improve + * performance. * * @param entityType EntityType to convert * @return Pretty string representation of the EntityType @@ -125,9 +129,9 @@ public class StringUtils { if (baseString.contains("_") && !baseString.contains(" ")) { return prettify(baseString.split("_")); } else { - if(baseString.contains(" ")) { + if (baseString.contains(" ")) { return prettify(baseString.split(" ")); - } else{ + } else { return getCapitalized(baseString); } } @@ -148,6 +152,7 @@ public class StringUtils { /** * Creates a pretty string from an object. + * * @param object Object to convert * @return Pretty string representation of the object */ diff --git a/src/main/java/com/gmail/nossr50/util/text/TextComponentFactory.java b/src/main/java/com/gmail/nossr50/util/text/TextComponentFactory.java index 2cbfe4b1a..16d10ed09 100644 --- a/src/main/java/com/gmail/nossr50/util/text/TextComponentFactory.java +++ b/src/main/java/com/gmail/nossr50/util/text/TextComponentFactory.java @@ -12,6 +12,9 @@ import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.RankUtils; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextComponent; @@ -24,20 +27,17 @@ import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - /** * This class handles many of the JSON components that mcMMO makes and uses */ public class TextComponentFactory { /** - * Makes a text component using strings from a locale and supports passing an undefined number of variables to the LocaleLoader + * 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 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, String... values) { @@ -49,8 +49,11 @@ public class TextComponentFactory { return getNotificationTextComponent(LocaleLoader.getString(localeKey)); } - public static Component getNotificationLevelUpTextComponent(PrimarySkillType skill, int levelsGained, int currentLevel) { - return Component.text(LocaleLoader.getString("Overhaul.Levelup", LocaleLoader.getString("Overhaul.Name." + StringUtils.getCapitalized(skill.toString())), levelsGained, currentLevel)); + public static Component getNotificationLevelUpTextComponent(PrimarySkillType skill, + int levelsGained, int currentLevel) { + return Component.text(LocaleLoader.getString("Overhaul.Levelup", LocaleLoader.getString( + "Overhaul.Name." + StringUtils.getCapitalized(skill.toString())), levelsGained, + currentLevel)); } private static TextComponent getNotificationTextComponent(String text) { @@ -64,17 +67,22 @@ public class TextComponentFactory { + subSkillType.getWikiUrl().toLowerCase(Locale.ENGLISH); } - public static void sendPlayerSubSkillWikiLink(Player player, String subskillformatted, SubSkillType subSkillType) { - if (!mcMMO.p.getGeneralConfig().getUrlLinksEnabled()) + public static void sendPlayerSubSkillWikiLink(Player player, String subskillformatted, + SubSkillType subSkillType) { + if (!mcMMO.p.getGeneralConfig().getUrlLinksEnabled()) { return; + } - TextComponent.Builder wikiLinkComponent = Component.text().content(LocaleLoader.getString("Overhaul.mcMMO.MmoInfo.Wiki")); + TextComponent.Builder wikiLinkComponent = Component.text() + .content(LocaleLoader.getString("Overhaul.mcMMO.MmoInfo.Wiki")); wikiLinkComponent.decoration(TextDecoration.UNDERLINED, true); final String subSkillWikiLink = getSubSkillWikiLink(subSkillType); wikiLinkComponent.clickEvent(ClickEvent.openUrl(subSkillWikiLink)); - TextComponent.Builder componentBuilder = Component.text().content(subskillformatted).append(Component.newline()).append(Component.text(subSkillWikiLink)).color(NamedTextColor.GRAY).decoration(TextDecoration.ITALIC, true); + TextComponent.Builder componentBuilder = Component.text().content(subskillformatted) + .append(Component.newline()).append(Component.text(subSkillWikiLink)) + .color(NamedTextColor.GRAY).decoration(TextDecoration.ITALIC, true); wikiLinkComponent.hoverEvent(HoverEvent.showText(componentBuilder.build())); @@ -82,9 +90,11 @@ public class TextComponentFactory { } public static void sendPlayerUrlHeader(Player player) { - TextComponent prefix = Component.text(LocaleLoader.getString("Overhaul.mcMMO.Url.Wrap.Prefix") + " "); + TextComponent prefix = Component.text( + LocaleLoader.getString("Overhaul.mcMMO.Url.Wrap.Prefix") + " "); /*prefix.setColor(ChatColor.DARK_AQUA);*/ - TextComponent suffix = Component.text(" " + LocaleLoader.getString("Overhaul.mcMMO.Url.Wrap.Suffix")); + TextComponent suffix = Component.text( + " " + LocaleLoader.getString("Overhaul.mcMMO.Url.Wrap.Suffix")); /*suffix.setColor(ChatColor.DARK_AQUA);*/ TextComponent emptySpace = Component.space(); @@ -108,18 +118,20 @@ public class TextComponentFactory { } /** - * Sends a player a bunch of text components that represent a list of sub-skills - * Styling and formatting is applied before sending the messages + * Sends a player a bunch of text components that represent a list of sub-skills Styling and + * formatting is applied before sending the messages * - * @param player target player + * @param player target player * @param subSkillComponents the text components representing the sub-skills by name */ - public static void sendPlayerSubSkillList(@NotNull Player player, @NotNull List subSkillComponents) { + public static void sendPlayerSubSkillList(@NotNull Player player, + @NotNull List subSkillComponents) { final Audience audience = mcMMO.getAudiences().player(player); //@ Signs, done for style Component space = Component.space(); - TextComponent atSignComponent = Component.text(LocaleLoader.getString("JSON.Hover.AtSymbolSkills")); + TextComponent atSignComponent = Component.text( + LocaleLoader.getString("JSON.Hover.AtSymbolSkills")); //Only send 3 sub-skills per line Component[][] splitSubSkills = TextUtils.splitComponentsIntoGroups(subSkillComponents, 3); @@ -141,32 +153,38 @@ public class TextComponentFactory { switch (webLinks) { case WEBSITE -> { - webTextComponent = Component.text().content(LocaleLoader.getString("JSON.Hover.AtSymbolURL")); + webTextComponent = Component.text() + .content(LocaleLoader.getString("JSON.Hover.AtSymbolURL")); TextUtils.addChildWebComponent(webTextComponent, "Web"); webTextComponent.clickEvent(getUrlClickEvent(McMMOUrl.urlWebsite)); } case SPIGOT -> { - webTextComponent = Component.text().content(LocaleLoader.getString("JSON.Hover.AtSymbolURL")); + webTextComponent = Component.text() + .content(LocaleLoader.getString("JSON.Hover.AtSymbolURL")); TextUtils.addChildWebComponent(webTextComponent, "Spigot"); webTextComponent.clickEvent(getUrlClickEvent(McMMOUrl.urlSpigot)); } case DISCORD -> { - webTextComponent = Component.text().content(LocaleLoader.getString("JSON.Hover.AtSymbolURL")); + webTextComponent = Component.text() + .content(LocaleLoader.getString("JSON.Hover.AtSymbolURL")); TextUtils.addChildWebComponent(webTextComponent, "Discord"); webTextComponent.clickEvent(getUrlClickEvent(McMMOUrl.urlDiscord)); } case PATREON -> { - webTextComponent = Component.text().content(LocaleLoader.getString("JSON.Hover.AtSymbolURL")); + webTextComponent = Component.text() + .content(LocaleLoader.getString("JSON.Hover.AtSymbolURL")); TextUtils.addChildWebComponent(webTextComponent, "Patreon"); webTextComponent.clickEvent(getUrlClickEvent(McMMOUrl.urlPatreon)); } case WIKI -> { - webTextComponent = Component.text().content(LocaleLoader.getString("JSON.Hover.AtSymbolURL")); + webTextComponent = Component.text() + .content(LocaleLoader.getString("JSON.Hover.AtSymbolURL")); TextUtils.addChildWebComponent(webTextComponent, "Wiki"); webTextComponent.clickEvent(getUrlClickEvent(McMMOUrl.urlWiki)); } case HELP_TRANSLATE -> { - webTextComponent = Component.text().content(LocaleLoader.getString("JSON.Hover.AtSymbolURL")); + webTextComponent = Component.text() + .content(LocaleLoader.getString("JSON.Hover.AtSymbolURL")); TextUtils.addChildWebComponent(webTextComponent, "Lang"); webTextComponent.clickEvent(getUrlClickEvent(McMMOUrl.urlTranslate)); } @@ -186,50 +204,67 @@ public class TextComponentFactory { case WEBSITE -> { addUrlHeaderHover(webLinks, componentBuilder); componentBuilder.append(Component.newline()).append(Component.newline()); - componentBuilder.append(Component.text(webLinks.getLocaleDescription(), NamedTextColor.GREEN)); - componentBuilder.append(Component.text("\nDev Blogs, and information related to mcMMO can be found here", NamedTextColor.GRAY)); + componentBuilder.append( + Component.text(webLinks.getLocaleDescription(), NamedTextColor.GREEN)); + componentBuilder.append(Component.text( + "\nDev Blogs, and information related to mcMMO can be found here", + NamedTextColor.GRAY)); } case SPIGOT -> { addUrlHeaderHover(webLinks, componentBuilder); componentBuilder.append(Component.newline()).append(Component.newline()); - componentBuilder.append(Component.text(webLinks.getLocaleDescription(), NamedTextColor.GREEN)); - componentBuilder.append(Component.text("\nI post regularly in the discussion thread here!", NamedTextColor.GRAY)); + componentBuilder.append( + Component.text(webLinks.getLocaleDescription(), NamedTextColor.GREEN)); + componentBuilder.append( + Component.text("\nI post regularly in the discussion thread here!", + NamedTextColor.GRAY)); } case PATREON -> { addUrlHeaderHover(webLinks, componentBuilder); componentBuilder.append(Component.newline()).append(Component.newline()); - componentBuilder.append(Component.text(webLinks.getLocaleDescription(), NamedTextColor.GREEN)); + componentBuilder.append( + Component.text(webLinks.getLocaleDescription(), NamedTextColor.GREEN)); componentBuilder.append(Component.newline()); - componentBuilder.append(Component.text("Show support by buying me a coffee :)", NamedTextColor.GRAY)); + componentBuilder.append(Component.text("Show support by buying me a coffee :)", + NamedTextColor.GRAY)); } case WIKI -> { addUrlHeaderHover(webLinks, componentBuilder); componentBuilder.append(Component.newline()).append(Component.newline()); - componentBuilder.append(Component.text(webLinks.getLocaleDescription(), NamedTextColor.GREEN)); + componentBuilder.append( + Component.text(webLinks.getLocaleDescription(), NamedTextColor.GREEN)); componentBuilder.append(Component.newline()); - componentBuilder.append(Component.text("I'm looking for more wiki staff, contact me on our discord!", NamedTextColor.DARK_GRAY)); + componentBuilder.append(Component.text( + "I'm looking for more wiki staff, contact me on our discord!", + NamedTextColor.DARK_GRAY)); } case DISCORD -> { addUrlHeaderHover(webLinks, componentBuilder); componentBuilder.append(Component.newline()).append(Component.newline()); - componentBuilder.append(Component.text(webLinks.getLocaleDescription(), NamedTextColor.GREEN)); + componentBuilder.append( + Component.text(webLinks.getLocaleDescription(), NamedTextColor.GREEN)); } case HELP_TRANSLATE -> { addUrlHeaderHover(webLinks, componentBuilder); componentBuilder.append(Component.newline()).append(Component.newline()); - componentBuilder.append(Component.text(webLinks.getLocaleDescription(), NamedTextColor.GREEN)); + componentBuilder.append( + Component.text(webLinks.getLocaleDescription(), NamedTextColor.GREEN)); componentBuilder.append(Component.newline()); - componentBuilder.append(Component.text("You can use this website to help translate mcMMO into your language!" + - "\nIf you want to know more contact me in discord.", NamedTextColor.DARK_GRAY)); + componentBuilder.append(Component.text( + "You can use this website to help translate mcMMO into your language!" + + "\nIf you want to know more contact me in discord.", + NamedTextColor.DARK_GRAY)); } } return componentBuilder.build(); } - private static void addUrlHeaderHover(McMMOWebLinks webLinks, TextComponent.Builder componentBuilder) { + private static void addUrlHeaderHover(McMMOWebLinks webLinks, + TextComponent.Builder componentBuilder) { componentBuilder.append(Component.newline()); - componentBuilder.append(Component.text(webLinks.getUrl(), NamedTextColor.GRAY, TextDecoration.ITALIC)); + componentBuilder.append( + Component.text(webLinks.getUrl(), NamedTextColor.GRAY, TextDecoration.ITALIC)); } private static ClickEvent getUrlClickEvent(String url) { @@ -242,10 +277,12 @@ public class TextComponentFactory { boolean skillUnlocked = RankUtils.hasUnlockedSubskill(player, subSkillType); - TextComponent.Builder textComponent = initNewSkillTextComponent(player, skillName, subSkillType, skillUnlocked); + TextComponent.Builder textComponent = initNewSkillTextComponent(player, skillName, + subSkillType, skillUnlocked); //Hover Event - TextUtils.addNewHoverComponentToTextComponent(textComponent, getSubSkillHoverComponent(player, subSkillType)); + TextUtils.addNewHoverComponentToTextComponent(textComponent, + getSubSkillHoverComponent(player, subSkillType)); //Insertion textComponent.insertion(skillName); @@ -253,7 +290,8 @@ public class TextComponentFactory { return textComponent.build(); } - private static TextComponent getSubSkillTextComponent(Player player, AbstractSubSkill abstractSubSkill) { + private static TextComponent getSubSkillTextComponent(Player player, + AbstractSubSkill abstractSubSkill) { //String key = abstractSubSkill.getConfigKeyName(); String skillName = abstractSubSkill.getNiceName(); @@ -262,10 +300,12 @@ public class TextComponentFactory { boolean skillUnlocked = RankUtils.hasUnlockedSubskill(player, subSkillType); - TextComponent.Builder textComponent = initNewSkillTextComponent(player, skillName, subSkillType, skillUnlocked); + TextComponent.Builder textComponent = initNewSkillTextComponent(player, skillName, + subSkillType, skillUnlocked); //Hover Event - TextUtils.addNewHoverComponentToTextComponent(textComponent, getSubSkillHoverComponent(player, abstractSubSkill)); + TextUtils.addNewHoverComponentToTextComponent(textComponent, + getSubSkillHoverComponent(player, abstractSubSkill)); //Insertion textComponent.insertion(skillName); @@ -273,15 +313,21 @@ public class TextComponentFactory { return textComponent.build(); } - private static TextComponent.Builder initNewSkillTextComponent(Player player, String skillName, SubSkillType subSkillType, boolean skillUnlocked) { + private static TextComponent.Builder initNewSkillTextComponent(Player player, String skillName, + SubSkillType subSkillType, boolean skillUnlocked) { TextComponent.Builder textComponent; if (skillUnlocked) { - if (RankUtils.getHighestRank(subSkillType) == RankUtils.getRank(player, subSkillType) && subSkillType.getNumRanks() > 1) - textComponent = Component.text().content(LocaleLoader.getString("JSON.Hover.MaxRankSkillName", skillName)); - else - textComponent = Component.text().content(LocaleLoader.getString("JSON.Hover.SkillName", skillName)); + if (RankUtils.getHighestRank(subSkillType) == RankUtils.getRank(player, subSkillType) + && subSkillType.getNumRanks() > 1) { + textComponent = Component.text() + .content(LocaleLoader.getString("JSON.Hover.MaxRankSkillName", skillName)); + } else { + textComponent = Component.text() + .content(LocaleLoader.getString("JSON.Hover.SkillName", skillName)); + } - textComponent.clickEvent(ClickEvent.runCommand("/mmoinfo " + subSkillType.getNiceNameNoSpaces(subSkillType))); + textComponent.clickEvent(ClickEvent.runCommand( + "/mmoinfo " + subSkillType.getNiceNameNoSpaces(subSkillType))); } else { textComponent = Component.text().content(LocaleLoader.getString("JSON.Hover.Mystery", @@ -292,7 +338,8 @@ public class TextComponentFactory { return textComponent; } - private static Component getSubSkillHoverComponent(Player player, AbstractSubSkill abstractSubSkill) { + private static Component getSubSkillHoverComponent(Player player, + AbstractSubSkill abstractSubSkill) { return getSubSkillHoverEventJSON(abstractSubSkill, player); } @@ -304,10 +351,11 @@ public class TextComponentFactory { * 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 Component getSubSkillHoverEventJSON(AbstractSubSkill abstractSubSkill, Player player) { + private static Component getSubSkillHoverEventJSON(AbstractSubSkill abstractSubSkill, + Player player) { String skillName = ChatColor.stripColor(abstractSubSkill.getNiceName()); /* @@ -320,11 +368,13 @@ public class TextComponentFactory { SubSkillType subSkillType = abstractSubSkill.getSubSkillType(); //SubSkillType Name - TextComponent.Builder componentBuilder = setupSkillComponentNameStyle(player, skillName, subSkillType, RankUtils.hasUnlockedSubskill(player, abstractSubSkill)); + TextComponent.Builder componentBuilder = setupSkillComponentNameStyle(player, skillName, + subSkillType, RankUtils.hasUnlockedSubskill(player, abstractSubSkill)); if (!RankUtils.hasUnlockedSubskill(player, abstractSubSkill)) { //Skill is not unlocked yet - addLocked(abstractSubSkill, ccLocked, ccLevelRequirement, ccLevelRequired, componentBuilder); + addLocked(abstractSubSkill, ccLocked, ccLevelRequirement, ccLevelRequired, + componentBuilder); } else { addSubSkillTypeToHoverEventJSON(abstractSubSkill, componentBuilder); @@ -336,10 +386,14 @@ public class TextComponentFactory { nextRank = RankUtils.getRankUnlockLevel(abstractSubSkill, curRank + 1); } - addRanked(componentBuilder, abstractSubSkill.getNumRanks(), RankUtils.getRank(player, abstractSubSkill), nextRank); + addRanked(componentBuilder, abstractSubSkill.getNumRanks(), + RankUtils.getRank(player, abstractSubSkill), nextRank); - componentBuilder.append(Component.text(LocaleLoader.getString("JSON.DescriptionHeader"))); - componentBuilder.append(Component.newline()).append(Component.text(abstractSubSkill.getDescription())).append(Component.newline()); + componentBuilder.append( + Component.text(LocaleLoader.getString("JSON.DescriptionHeader"))); + componentBuilder.append(Component.newline()) + .append(Component.text(abstractSubSkill.getDescription())) + .append(Component.newline()); //Empty line componentBuilder.append(Component.newline()).decoration(TextDecoration.BOLD, false); @@ -353,16 +407,22 @@ public class TextComponentFactory { return componentBuilder.build(); } - private static TextComponent.Builder setupSkillComponentNameStyle(Player player, String skillName, SubSkillType subSkillType, boolean skillUnlocked) { + private static TextComponent.Builder setupSkillComponentNameStyle(Player player, + String skillName, SubSkillType subSkillType, boolean skillUnlocked) { TextComponent.Builder componentBuilder; if (skillUnlocked) { - if (RankUtils.getHighestRank(subSkillType) == RankUtils.getRank(player, subSkillType) && subSkillType.getNumRanks() > 1) - componentBuilder = getNewComponentBuilder(LocaleLoader.getString("JSON.Hover.MaxRankSkillName", skillName)); - else - componentBuilder = getNewComponentBuilder(LocaleLoader.getString("JSON.Hover.SkillName", skillName)); - } else + if (RankUtils.getHighestRank(subSkillType) == RankUtils.getRank(player, subSkillType) + && subSkillType.getNumRanks() > 1) { + componentBuilder = getNewComponentBuilder( + LocaleLoader.getString("JSON.Hover.MaxRankSkillName", skillName)); + } else { + componentBuilder = getNewComponentBuilder( + LocaleLoader.getString("JSON.Hover.SkillName", skillName)); + } + } else { componentBuilder = getNewComponentBuilder(LocaleLoader.getString("JSON.Hover.Mystery", String.valueOf(RankUtils.getUnlockLevel(subSkillType)))); + } return componentBuilder; } @@ -372,33 +432,51 @@ public class TextComponentFactory { return componentBuilder; } - private static void addRanked(TextComponent.Builder componentBuilder, int numRanks, int rank, int nextRank) { + private static void addRanked(TextComponent.Builder componentBuilder, int numRanks, int rank, + int nextRank) { if (numRanks > 0) { //Rank: x - componentBuilder.append(Component.text(LocaleLoader.getString("JSON.Hover.Rank", String.valueOf(rank)))).append(Component.newline()); + componentBuilder.append( + Component.text(LocaleLoader.getString("JSON.Hover.Rank", String.valueOf(rank)))) + .append(Component.newline()); //Next Rank: x - if (nextRank > rank) - componentBuilder.append(Component.text(LocaleLoader.getString("JSON.Hover.NextRank", String.valueOf(nextRank)))).append(Component.newline()); + if (nextRank > rank) { + componentBuilder.append(Component.text( + LocaleLoader.getString("JSON.Hover.NextRank", String.valueOf(nextRank)))) + .append(Component.newline()); + } } } - private static void addLocked(SubSkillType subSkillType, TextColor ccLocked, TextColor ccLevelRequirement, TextColor ccLevelRequired, TextComponent.Builder componentBuilder) { + private static void addLocked(SubSkillType subSkillType, TextColor ccLocked, + TextColor ccLevelRequirement, TextColor ccLevelRequired, + TextComponent.Builder componentBuilder) { addLocked(ccLocked, ccLevelRequirement, componentBuilder); - componentBuilder.append(Component.text(String.valueOf(RankConfig.getInstance().getSubSkillUnlockLevel(subSkillType, 1)), ccLevelRequired)); + componentBuilder.append(Component.text( + String.valueOf(RankConfig.getInstance().getSubSkillUnlockLevel(subSkillType, 1)), + ccLevelRequired)); //componentBuilder.append(Component.newline()); } - private static void addLocked(AbstractSubSkill abstractSubSkill, TextColor ccLocked, TextColor ccLevelRequirement, TextColor ccLevelRequired, TextComponent.Builder componentBuilder) { + private static void addLocked(AbstractSubSkill abstractSubSkill, TextColor ccLocked, + TextColor ccLevelRequirement, TextColor ccLevelRequired, + TextComponent.Builder componentBuilder) { addLocked(ccLocked, ccLevelRequirement, componentBuilder); - componentBuilder.append(Component.text(String.valueOf(RankConfig.getInstance().getSubSkillUnlockLevel(abstractSubSkill, 1)), ccLevelRequired)); + componentBuilder.append(Component.text(String.valueOf( + RankConfig.getInstance().getSubSkillUnlockLevel(abstractSubSkill, 1)), + ccLevelRequired)); //componentBuilder.append(Component.newline()); } - private static void addLocked(TextColor ccLocked, TextColor ccLevelRequirement, TextComponent.Builder componentBuilder) { - componentBuilder.append(Component.text(LocaleLoader.getString("JSON.Locked"), ccLocked, TextDecoration.BOLD)); + private static void addLocked(TextColor ccLocked, TextColor ccLevelRequirement, + TextComponent.Builder componentBuilder) { + componentBuilder.append(Component.text(LocaleLoader.getString("JSON.Locked"), ccLocked, + TextDecoration.BOLD)); componentBuilder.append(Component.newline()).append(Component.newline()); - componentBuilder.append(Component.text(LocaleLoader.getString("JSON.LevelRequirement") + ": ", ccLevelRequirement)); + componentBuilder.append( + Component.text(LocaleLoader.getString("JSON.LevelRequirement") + ": ", + ccLevelRequirement)); } private static Component getSubSkillHoverEventJSON(SubSkillType subSkillType, Player player) { @@ -415,11 +493,13 @@ public class TextComponentFactory { TextColor ccLevelRequired = NamedTextColor.RED; //SubSkillType Name - TextComponent.Builder componentBuilder = setupSkillComponentNameStyle(player, skillName, subSkillType, RankUtils.hasUnlockedSubskill(player, subSkillType)); + TextComponent.Builder componentBuilder = setupSkillComponentNameStyle(player, skillName, + subSkillType, RankUtils.hasUnlockedSubskill(player, subSkillType)); if (!RankUtils.hasUnlockedSubskill(player, subSkillType)) { //Skill is not unlocked yet - addLocked(subSkillType, ccLocked, ccLevelRequirement, ccLevelRequired, componentBuilder); + addLocked(subSkillType, ccLocked, ccLevelRequirement, ccLevelRequired, + componentBuilder); } else { //addSubSkillTypeToHoverEventJSON(subSkillType, componentBuilder); @@ -437,16 +517,19 @@ public class TextComponentFactory { } componentBuilder.append(Component.newline()); - componentBuilder.append(Component.text(LocaleLoader.getString("JSON.DescriptionHeader")).color(ccDescriptionHeader)); + componentBuilder.append(Component.text(LocaleLoader.getString("JSON.DescriptionHeader")) + .color(ccDescriptionHeader)); componentBuilder.append(Component.newline()); - componentBuilder.append(Component.text(ChatColor.stripColor(subSkillType.getLocaleDescription())).color(ccDescription)); + componentBuilder.append( + Component.text(ChatColor.stripColor(subSkillType.getLocaleDescription())) + .color(ccDescription)); } return componentBuilder.build(); } private static void addSubSkillTypeToHoverEventJSON(AbstractSubSkill abstractSubSkill, - TextComponent.Builder componentBuilder) { + TextComponent.Builder componentBuilder) { if (abstractSubSkill.isSuperAbility()) { componentBuilder.append(Component.text(LocaleLoader.getString("JSON.Type.SuperAbility"), NamedTextColor.LIGHT_PURPLE, TextDecoration.BOLD)); @@ -462,18 +545,22 @@ public class TextComponentFactory { } public static void getSubSkillTextComponents(Player player, List textComponents, - PrimarySkillType parentSkill) { + PrimarySkillType parentSkill) { for (SubSkillType subSkillType : SubSkillType.values()) { if (subSkillType.getParentSkill() == parentSkill) { //TODO: Hacky rewrite later //Only some versions of MC have this skill if (subSkillType == SubSkillType.FISHING_MASTER_ANGLER - && mcMMO.getCompatibilityManager().getMasterAnglerCompatibilityLayer() == null) + && mcMMO.getCompatibilityManager().getMasterAnglerCompatibilityLayer() + == null) { continue; + } if (Permissions.isSubSkillEnabled(player, subSkillType)) { - if (!InteractionManager.hasSubSkill(subSkillType)) - textComponents.add(TextComponentFactory.getSubSkillTextComponent(player, subSkillType)); + if (!InteractionManager.hasSubSkill(subSkillType)) { + textComponents.add(TextComponentFactory.getSubSkillTextComponent(player, + subSkillType)); + } } } } @@ -481,16 +568,23 @@ public class TextComponentFactory { /* NEW SKILL SYSTEM */ for (AbstractSubSkill abstractSubSkill : InteractionManager.getSubSkillList()) { if (abstractSubSkill.getPrimarySkill() == parentSkill) { - if (Permissions.isSubSkillEnabled(player, abstractSubSkill.getSubSkillType())) - textComponents.add(TextComponentFactory.getSubSkillTextComponent(player, abstractSubSkill)); + if (Permissions.isSubSkillEnabled(player, abstractSubSkill.getSubSkillType())) { + textComponents.add(TextComponentFactory.getSubSkillTextComponent(player, + abstractSubSkill)); + } } } } - public static TextComponent getSubSkillUnlockedNotificationComponents(Player player, SubSkillType subSkillType) { - TextComponent.Builder unlockMessage = Component.text().content(LocaleLoader.getString("JSON.SkillUnlockMessage", subSkillType.getLocaleName(), RankUtils.getRank(player, subSkillType))); - unlockMessage.hoverEvent(HoverEvent.showText(getSubSkillHoverComponent(player, subSkillType))); - unlockMessage.clickEvent(ClickEvent.runCommand("/" + subSkillType.getParentSkill().toString().toLowerCase(Locale.ENGLISH))); + public static TextComponent getSubSkillUnlockedNotificationComponents(Player player, + SubSkillType subSkillType) { + TextComponent.Builder unlockMessage = Component.text().content( + LocaleLoader.getString("JSON.SkillUnlockMessage", subSkillType.getLocaleName(), + RankUtils.getRank(player, subSkillType))); + unlockMessage.hoverEvent( + HoverEvent.showText(getSubSkillHoverComponent(player, subSkillType))); + unlockMessage.clickEvent(ClickEvent.runCommand( + "/" + subSkillType.getParentSkill().toString().toLowerCase(Locale.ENGLISH))); return unlockMessage.build(); } } diff --git a/src/main/java/com/gmail/nossr50/util/text/TextUtils.java b/src/main/java/com/gmail/nossr50/util/text/TextUtils.java index 782bd5ccc..aea2a243f 100644 --- a/src/main/java/com/gmail/nossr50/util/text/TextUtils.java +++ b/src/main/java/com/gmail/nossr50/util/text/TextUtils.java @@ -1,6 +1,7 @@ package com.gmail.nossr50.util.text; import com.gmail.nossr50.mcMMO; +import java.util.List; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.ComponentBuilder; import net.kyori.adventure.text.TextComponent; @@ -13,8 +14,6 @@ import net.md_5.bungee.api.chat.BaseComponent; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.List; - public class TextUtils { private static @Nullable LegacyComponentSerializer customLegacySerializer; @@ -23,24 +22,31 @@ public class TextUtils { } /** - * Makes a single component from an array of components, can optionally add prefixes and suffixes to come before and after each component + * Makes a single component from an array of components, can optionally add prefixes and + * suffixes to come before and after each component + * * @param componentsArray target array * @return a component with optional styling built from an array */ - static @NotNull Component fromArray(@NotNull Component[] componentsArray, @Nullable Component prefixComponent, @Nullable Component suffixComponent) { + static @NotNull Component fromArray(@NotNull Component[] componentsArray, + @Nullable Component prefixComponent, @Nullable Component suffixComponent) { TextComponent.Builder componentBuilder = Component.text(); - for(Component component : componentsArray) { + for (Component component : componentsArray) { if (component == null) //Individual elements can be null + { continue; + } - if (prefixComponent != null) + if (prefixComponent != null) { componentBuilder.append(prefixComponent); + } componentBuilder.append(component); - if (suffixComponent != null) + if (suffixComponent != null) { componentBuilder.append(suffixComponent); + } } @@ -55,7 +61,8 @@ public class TextUtils { * @param groupsSize maximum size per array * @return a 2D array with components split into groups */ - static @NotNull Component[][] splitComponentsIntoGroups(@NotNull List components, int groupsSize) { + static @NotNull Component[][] splitComponentsIntoGroups(@NotNull List components, + int groupsSize) { int groupCount = (int) Math.ceil((double) components.size() / (double) groupsSize); Component[][] splitGroups = new Component[groupCount][groupsSize]; @@ -64,11 +71,12 @@ public class TextUtils { while (groupsFinished < groupCount) { //Fill group with members - for(int i = 0; i < groupsSize; i++) { - int indexOfPotentialMember = i + (groupsFinished * 3); //Groups don't always fill all members neatly + for (int i = 0; i < groupsSize; i++) { + int indexOfPotentialMember = + i + (groupsFinished * 3); //Groups don't always fill all members neatly //Some groups won't have entirely non-null elements - if (indexOfPotentialMember > components.size()-1) { + if (indexOfPotentialMember > components.size() - 1) { break; } @@ -87,12 +95,14 @@ public class TextUtils { return splitGroups; } - static void addChildWebComponent(@NotNull ComponentBuilder webTextComponent, @NotNull String childName) { + static void addChildWebComponent(@NotNull ComponentBuilder webTextComponent, + @NotNull String childName) { TextComponent childComponent = Component.text(childName).color(NamedTextColor.BLUE); webTextComponent.append(childComponent); } - static void addNewHoverComponentToTextComponent(@NotNull TextComponent.Builder textComponent, @NotNull Component baseComponent) { + static void addNewHoverComponentToTextComponent(@NotNull TextComponent.Builder textComponent, + @NotNull Component baseComponent) { textComponent.hoverEvent(HoverEvent.showText(baseComponent)); } @@ -101,7 +111,9 @@ public class TextUtils { } public static @NotNull TextComponent ofBungeeComponents(@NotNull BaseComponent[] bungeeName) { - return TextComponent.ofChildren(mcMMO.getCompatibilityManager().getBungeeSerializerCompatibilityLayer().deserialize(bungeeName)); + return TextComponent.ofChildren( + mcMMO.getCompatibilityManager().getBungeeSerializerCompatibilityLayer() + .deserialize(bungeeName)); } public static @NotNull TextComponent ofBungeeRawStrings(@NotNull String bungeeRawString) { diff --git a/src/main/java/com/gmail/nossr50/util/upgrade/UpgradeManager.java b/src/main/java/com/gmail/nossr50/util/upgrade/UpgradeManager.java index 4bb13f6eb..9855d2479 100644 --- a/src/main/java/com/gmail/nossr50/util/upgrade/UpgradeManager.java +++ b/src/main/java/com/gmail/nossr50/util/upgrade/UpgradeManager.java @@ -4,7 +4,6 @@ import com.gmail.nossr50.config.BukkitConfig; import com.gmail.nossr50.datatypes.database.UpgradeType; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.LogUtils; - import java.util.Arrays; import java.util.EnumSet; import java.util.Set; @@ -24,7 +23,6 @@ public class UpgradeManager extends BukkitConfig { * Check if the given {@link UpgradeType} is necessary. * * @param type Upgrade type to check - * * @return true if plugin data needs to have the given upgrade */ public boolean shouldUpgrade(final UpgradeType type) { @@ -32,8 +30,8 @@ public class UpgradeManager extends BukkitConfig { } /** - * Set the given {@link UpgradeType} as completed. Does nothing if - * the upgrade was applied previously. + * Set the given {@link UpgradeType} as completed. Does nothing if the upgrade was applied + * previously. * * @param type Upgrade type to set as complete */ @@ -42,14 +40,14 @@ public class UpgradeManager extends BukkitConfig { return; } - LogUtils.debug(mcMMO.p.getLogger(), "Saving upgrade status for type " + type.toString() + "..."); + LogUtils.debug(mcMMO.p.getLogger(), + "Saving upgrade status for type " + type.toString() + "..."); - config.set("Upgrades_Finished." + type.toString(), true); + config.set("Upgrades_Finished." + type, true); try { config.save(getFile()); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } } @@ -62,6 +60,7 @@ public class UpgradeManager extends BukkitConfig { } } - LogUtils.debug(mcMMO.p.getLogger(), "Needed upgrades: " + Arrays.toString(setNeededUpgrades.toArray(new UpgradeType[setNeededUpgrades.size()]))); + LogUtils.debug(mcMMO.p.getLogger(), "Needed upgrades: " + Arrays.toString( + setNeededUpgrades.toArray(new UpgradeType[setNeededUpgrades.size()]))); } } diff --git a/src/main/java/com/gmail/nossr50/worldguard/WorldGuardManager.java b/src/main/java/com/gmail/nossr50/worldguard/WorldGuardManager.java index f3ccd14ec..0aa7afbe7 100644 --- a/src/main/java/com/gmail/nossr50/worldguard/WorldGuardManager.java +++ b/src/main/java/com/gmail/nossr50/worldguard/WorldGuardManager.java @@ -1,5 +1,7 @@ package com.gmail.nossr50.worldguard; +import static org.bukkit.Bukkit.getServer; + import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.LogUtils; import com.sk89q.worldedit.bukkit.BukkitAdapter; @@ -12,62 +14,70 @@ import com.sk89q.worldguard.protection.regions.RegionQuery; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; -import static org.bukkit.Bukkit.getServer; - public class WorldGuardManager { private static WorldGuardManager instance; private WorldGuardPlugin worldGuardPluginRef; public static WorldGuardManager getInstance() { - if (instance == null) + if (instance == null) { instance = new WorldGuardManager(); + } return instance; } public boolean hasMainFlag(Player player) { - if (player == null) + if (player == null) { return false; + } BukkitPlayer localPlayer = BukkitAdapter.adapt(player); com.sk89q.worldedit.util.Location loc = localPlayer.getLocation(); //WorldGuardPlugin worldGuard = getWorldGuard(); - RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery(); + RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer() + .createQuery(); //ApplicableRegionSet set = query.getApplicableRegions(loc); - return query.testState(loc, WorldGuardPlugin.inst().wrapPlayer(player), WorldGuardFlags.MCMMO_ENABLE_WG_FLAG); + return query.testState(loc, WorldGuardPlugin.inst().wrapPlayer(player), + WorldGuardFlags.MCMMO_ENABLE_WG_FLAG); } public boolean hasXPFlag(Player player) { - if (player == null) + if (player == null) { return false; + } BukkitPlayer localPlayer = BukkitAdapter.adapt(player); com.sk89q.worldedit.util.Location loc = localPlayer.getLocation(); //WorldGuardPlugin worldGuard = getWorldGuard(); - RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery(); + RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer() + .createQuery(); //ApplicableRegionSet set = query.getApplicableRegions(loc); - return query.testState(loc, WorldGuardPlugin.inst().wrapPlayer(player), WorldGuardFlags.MCMMO_XP_WG_FLAG); + return query.testState(loc, WorldGuardPlugin.inst().wrapPlayer(player), + WorldGuardFlags.MCMMO_XP_WG_FLAG); } public boolean hasHardcoreFlag(Player player) { - if (player == null) + if (player == null) { return false; + } BukkitPlayer localPlayer = BukkitAdapter.adapt(player); com.sk89q.worldedit.util.Location loc = localPlayer.getLocation(); //WorldGuardPlugin worldGuard = getWorldGuard(); - RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery(); + RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer() + .createQuery(); //ApplicableRegionSet set = query.getApplicableRegions(loc); - return query.testState(loc, WorldGuardPlugin.inst().wrapPlayer(player), WorldGuardFlags.MCMMO_HARDCORE_WG_FLAG); + return query.testState(loc, WorldGuardPlugin.inst().wrapPlayer(player), + WorldGuardFlags.MCMMO_HARDCORE_WG_FLAG); } private WorldGuardPlugin getWorldGuard() { diff --git a/src/main/java/com/gmail/nossr50/worldguard/WorldGuardUtils.java b/src/main/java/com/gmail/nossr50/worldguard/WorldGuardUtils.java index 9cc190b7d..9ba52ad45 100644 --- a/src/main/java/com/gmail/nossr50/worldguard/WorldGuardUtils.java +++ b/src/main/java/com/gmail/nossr50/worldguard/WorldGuardUtils.java @@ -1,15 +1,14 @@ package com.gmail.nossr50.worldguard; +import static org.bukkit.Bukkit.getServer; + import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.LogUtils; import com.sk89q.worldguard.WorldGuard; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import com.sk89q.worldguard.protection.flags.registry.SimpleFlagRegistry; -import org.bukkit.plugin.Plugin; - import java.util.ArrayList; - -import static org.bukkit.Bukkit.getServer; +import org.bukkit.plugin.Plugin; public class WorldGuardUtils { private static WorldGuardPlugin worldGuardPluginRef; @@ -42,8 +41,9 @@ public class WorldGuardUtils { } public static boolean isWorldGuardLoaded() { - if (detectedIncompatibleWG) + if (detectedIncompatibleWG) { return false; + } worldGuardPluginRef = getWorldGuard(); @@ -51,14 +51,15 @@ public class WorldGuardUtils { } /** - * Gets the instance of the WG plugin if its compatible - * Results are cached + * Gets the instance of the WG plugin if its compatible Results are cached + * * @return the instance of WG plugin, null if its not compatible or isn't present */ private static WorldGuardPlugin getWorldGuard() { //WG plugin reference is already cached so just return it - if (isLoaded) + if (isLoaded) { return worldGuardPluginRef; + } //Grab WG if it exists Plugin plugin = getServer().getPluginManager().getPlugin("WorldGuard"); @@ -80,14 +81,14 @@ public class WorldGuardUtils { } } - return worldGuardPluginRef; } /** - * Checks to make sure the version of WG installed is compatible - * Does this by checking for necessary WG classes via Reflection - * This does not guarantee compatibility, but it should help reduce the chance that mcMMO tries to hook into WG and its not compatible + * Checks to make sure the version of WG installed is compatible Does this by checking for + * necessary WG classes via Reflection This does not guarantee compatibility, but it should help + * reduce the chance that mcMMO tries to hook into WG and its not compatible + * * @return true if the version of WG appears to be compatible */ private static boolean isCompatibleVersion(Plugin plugin) { @@ -101,12 +102,12 @@ public class WorldGuardUtils { markWGIncompatible(); } else { //Use Reflection to check for a class not present in all versions of WG7 - for(String classString : WGClassList) { + for (String classString : WGClassList) { try { Class checkForClass = Class.forName(classString); } catch (ClassNotFoundException | NoClassDefFoundError e) { allClassesFound = false; - mcMMO.p.getLogger().severe("Missing WorldGuard class - "+classString); + mcMMO.p.getLogger().severe("Missing WorldGuard class - " + classString); markWGIncompatible(); } } @@ -116,9 +117,11 @@ public class WorldGuardUtils { */ try { if (allClassesFound) { - if (!((SimpleFlagRegistry) WorldGuard.getInstance().getFlagRegistry()).isInitialized()) { + if (!((SimpleFlagRegistry) WorldGuard.getInstance() + .getFlagRegistry()).isInitialized()) { markWGIncompatible(); - mcMMO.p.getLogger().severe("WG did not initialize properly, this can cause errors with mcMMO so mcMMO is disabling certain features."); + mcMMO.p.getLogger() + .severe("WG did not initialize properly, this can cause errors with mcMMO so mcMMO is disabling certain features."); } } } catch (Exception e) { @@ -134,10 +137,13 @@ public class WorldGuardUtils { * Mark WG as being incompatible to avoid unnecessary operations */ private static void markWGIncompatible() { - mcMMO.p.getLogger().severe("You are using a version of WG that is not compatible with mcMMO, " + - "WG features for mcMMO will be disabled. mcMMO requires you to be using a new version of WG7 " + - "in order for it to use WG features. Not all versions of WG7 are compatible."); - mcMMO.p.getLogger().severe("mcMMO will continue to function normally, but if you wish to use WG support you must use a compatible version."); + mcMMO.p.getLogger() + .severe("You are using a version of WG that is not compatible with mcMMO, " + + "WG features for mcMMO will be disabled. mcMMO requires you to be using a new version of WG7 " + + + "in order for it to use WG features. Not all versions of WG7 are compatible."); + mcMMO.p.getLogger() + .severe("mcMMO will continue to function normally, but if you wish to use WG support you must use a compatible version."); detectedIncompatibleWG = true; } } diff --git a/src/main/java/net/shatteredlands/shatt/backup/ZipLibrary.java b/src/main/java/net/shatteredlands/shatt/backup/ZipLibrary.java index 4636b680d..0d2ec917b 100644 --- a/src/main/java/net/shatteredlands/shatt/backup/ZipLibrary.java +++ b/src/main/java/net/shatteredlands/shatt/backup/ZipLibrary.java @@ -2,7 +2,6 @@ package net.shatteredlands.shatt.backup; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.LogUtils; - import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -17,15 +16,18 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipLibrary { - private static final String BACKUP_DIRECTORY = mcMMO.getMainDirectory() + "backup" + File.separator; + private static final String BACKUP_DIRECTORY = + mcMMO.getMainDirectory() + "backup" + File.separator; private static final File BACKUP_DIR = new File(BACKUP_DIRECTORY); private static final File FLAT_FILE_DIRECTORY = new File(mcMMO.getFlatFileDirectory()); private static final File MOD_FILE_DIRECTORY = new File(mcMMO.getModDirectory()); private static final File CONFIG_FILE = new File(mcMMO.getMainDirectory() + "config.yml"); - private static final File EXPERIENCE_FILE = new File(mcMMO.getMainDirectory() + "experience.yml"); + private static final File EXPERIENCE_FILE = new File( + mcMMO.getMainDirectory() + "experience.yml"); private static final File TREASURE_FILE = new File(mcMMO.getMainDirectory() + "treasures.yml"); private static final File ADVANCED_FILE = new File(mcMMO.getMainDirectory() + "advanced.yml"); - private static final File REPAIR_FILE = new File(mcMMO.getMainDirectory() + "repair.vanilla.yml"); + private static final File REPAIR_FILE = new File( + mcMMO.getMainDirectory() + "repair.vanilla.yml"); public static void mcMMOBackup() throws IOException { if (mcMMO.p.getGeneralConfig().getUseMySQL()) { @@ -37,15 +39,15 @@ public class ZipLibrary { if (BACKUP_DIR.mkdir()) { LogUtils.debug(mcMMO.p.getLogger(), "Created Backup Directory."); } - } - catch (Exception e) { + } catch (Exception e) { mcMMO.p.getLogger().severe(e.toString()); } // Generate the proper date for the backup filename Date date = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss", Locale.US); - File fileZip = new File(BACKUP_DIRECTORY + File.separator + dateFormat.format(date) + ".zip"); + File fileZip = new File( + BACKUP_DIRECTORY + File.separator + dateFormat.format(date) + ".zip"); // Create the Source List, and add directories/etc to the file. List sources = new ArrayList<>(); @@ -94,7 +96,8 @@ public class ZipLibrary { private static void zipDir(ZipOutputStream zos, String path, File dir) throws IOException { if (!dir.canRead()) { - mcMMO.p.getLogger().severe("Cannot read " + dir.getCanonicalPath() + " (Maybe because of permissions?)"); + mcMMO.p.getLogger().severe("Cannot read " + dir.getCanonicalPath() + + " (Maybe because of permissions?)"); return; } @@ -112,7 +115,8 @@ public class ZipLibrary { private static void zipFile(ZipOutputStream zos, String path, File file) throws IOException { if (!file.canRead()) { - mcMMO.p.getLogger().severe("Cannot read " + file.getCanonicalPath() + "(File Permissions?)"); + mcMMO.p.getLogger() + .severe("Cannot read " + file.getCanonicalPath() + "(File Permissions?)"); return; } diff --git a/src/test/java/com/gmail/nossr50/MMOTestEnvironment.java b/src/test/java/com/gmail/nossr50/MMOTestEnvironment.java index 4410ceea9..f80636585 100644 --- a/src/test/java/com/gmail/nossr50/MMOTestEnvironment.java +++ b/src/test/java/com/gmail/nossr50/MMOTestEnvironment.java @@ -1,5 +1,12 @@ package com.gmail.nossr50; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.anyInt; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + import com.gmail.nossr50.api.exceptions.InvalidSkillException; import com.gmail.nossr50.config.AdvancedConfig; import com.gmail.nossr50.config.ChatConfig; @@ -11,7 +18,11 @@ import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.PlayerProfile; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; -import com.gmail.nossr50.util.*; +import com.gmail.nossr50.util.EventUtils; +import com.gmail.nossr50.util.MaterialMapStore; +import com.gmail.nossr50.util.Misc; +import com.gmail.nossr50.util.Permissions; +import com.gmail.nossr50.util.TransientEntityTracker; import com.gmail.nossr50.util.blockmeta.ChunkManager; import com.gmail.nossr50.util.compat.CompatibilityManager; import com.gmail.nossr50.util.platform.MinecraftGameVersion; @@ -20,7 +31,13 @@ import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.skills.SkillTools; import com.gmail.nossr50.util.sounds.SoundManager; -import org.bukkit.*; +import java.util.UUID; +import java.util.logging.Logger; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Server; +import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.entity.Player; @@ -32,12 +49,6 @@ import org.bukkit.plugin.PluginManager; import org.mockito.MockedStatic; import org.mockito.Mockito; -import java.util.UUID; -import java.util.logging.Logger; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; - public abstract class MMOTestEnvironment { protected MockedStatic mockedBukkit; protected MockedStatic mockedMcMMO; @@ -190,11 +201,16 @@ public abstract class MMOTestEnvironment { private void mockPermissions() { mockedPermissions = mockStatic(Permissions.class); - when(Permissions.isSubSkillEnabled(any(Player.class), any(SubSkillType.class))).thenReturn(true); - when(Permissions.canUseSubSkill(any(Player.class), any(SubSkillType.class))).thenReturn(true); - when(Permissions.isSubSkillEnabled(any(Player.class), any(SubSkillType.class))).thenReturn(true); - when(Permissions.canUseSubSkill(any(Player.class), any(SubSkillType.class))).thenReturn(true); - when(Permissions.lucky(player, PrimarySkillType.WOODCUTTING)).thenReturn(false); // player is not lucky + when(Permissions.isSubSkillEnabled(any(Player.class), any(SubSkillType.class))).thenReturn( + true); + when(Permissions.canUseSubSkill(any(Player.class), any(SubSkillType.class))).thenReturn( + true); + when(Permissions.isSubSkillEnabled(any(Player.class), any(SubSkillType.class))).thenReturn( + true); + when(Permissions.canUseSubSkill(any(Player.class), any(SubSkillType.class))).thenReturn( + true); + when(Permissions.lucky(player, PrimarySkillType.WOODCUTTING)).thenReturn( + false); // player is not lucky } private void mockRankConfig() { @@ -209,7 +225,8 @@ public abstract class MMOTestEnvironment { private void mockGeneralConfig() { generalConfig = mock(GeneralConfig.class); when(generalConfig.getTreeFellerThreshold()).thenReturn(100); - when(generalConfig.getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, Material.OAK_LOG)).thenReturn(true); + when(generalConfig.getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, + Material.OAK_LOG)).thenReturn(true); when(generalConfig.getLocale()).thenReturn("en_US"); when(mcMMO.p.getGeneralConfig()).thenReturn(generalConfig); } diff --git a/src/test/java/com/gmail/nossr50/database/FlatFileDatabaseManagerTest.java b/src/test/java/com/gmail/nossr50/database/FlatFileDatabaseManagerTest.java index c0c448bc7..6b8d79099 100644 --- a/src/test/java/com/gmail/nossr50/database/FlatFileDatabaseManagerTest.java +++ b/src/test/java/com/gmail/nossr50/database/FlatFileDatabaseManagerTest.java @@ -1,5 +1,14 @@ package com.gmail.nossr50.database; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + import com.gmail.nossr50.database.flatfile.LeaderboardStatus; import com.gmail.nossr50.datatypes.database.DatabaseType; import com.gmail.nossr50.datatypes.player.PlayerProfile; @@ -8,15 +17,12 @@ import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SuperAbilityType; import com.gmail.nossr50.util.skills.SkillTools; import com.google.common.io.Files; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - -import java.io.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; @@ -26,9 +32,13 @@ import java.util.UUID; import java.util.logging.Filter; import java.util.logging.LogRecord; import java.util.logging.Logger; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.mock; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; class FlatFileDatabaseManagerTest { @@ -94,14 +104,16 @@ class FlatFileDatabaseManagerTest { private static final String[] badUUIDDatabaseData = { "nossr50:1000:::0:1000:640:1000:1000:1000:1000:1000:1000:1000:1000:16:0:500:0:0:0:0:0::1000:0:0:0:1593543012:0:0:0:0::1000:0:0:1593806053:HEARTS:1000:0:588fe472-1c82-4c4e-9aa1-7eefccb277e3:0:0:", - "z750:2420:::0:2452:0:1983:1937:1790:3042:1138:3102:2408:3411:0:0:0:0:0:0:0:0::642:0:1617583171:0:1617165043:0:1617583004:1617563189:1616785408::2184:0:0:1617852413:HEARTS:415:0:3:5:1600906906:", //This one has an incorrect UUID representation + "z750:2420:::0:2452:0:1983:1937:1790:3042:1138:3102:2408:3411:0:0:0:0:0:0:0:0::642:0:1617583171:0:1617165043:0:1617583004:1617563189:1616785408::2184:0:0:1617852413:HEARTS:415:0:3:5:1600906906:", + //This one has an incorrect UUID representation "powerless:0:::0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0::0:0:0:0:0:0:0:0:0::0:0:0:0:HEARTS:0:0:e0d07db8-f7e8-43c7-9ded-864dfc6f3b7c:5:1600906906:" }; private static final String[] outdatedDatabaseData = { "nossr50:1000:::0:1000:640:1000:1000:1000:1000:1000:1000:1000:1000:16:0:500:0:0:0:0:0::1000:0:0:0:1593543012:0:0:0:0::1000:0:0:1593806053:HEARTS:1000:0:588fe472-1c82-4c4e-9aa1-7eefccb277e3:0:0:", "mrfloris:2420:::0:2452:0:1983:1937:1790:3042:1138:3102:2408:3411:0:0:0:0:0:0:0:0::642:0:1617583171:0:1617165043:0:1617583004:1617563189:1616785408::2184:0:0:1617852413:HEARTS:415:0:631e3896-da2a-4077-974b-d047859d76bc:5:1600906906:", - "electronicboy:0:::0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0::0:0:0:0:0:0:0:0:0::0:0:0:0:HEARTS:0:0:e0d07db8-f7e8-43c7-9ded-864dfc6f3b7c:" //This user is missing data added after UUID index + "electronicboy:0:::0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0::0:0:0:0:0:0:0:0:0::0:0:0:0:HEARTS:0:0:e0d07db8-f7e8-43c7-9ded-864dfc6f3b7c:" + //This user is missing data added after UUID index }; private static final String[] emptyLineDatabaseData = { @@ -149,14 +161,16 @@ class FlatFileDatabaseManagerTest { @Test void testUpdateLeaderboards() { - FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager( + new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); assertNotNull(flatFileDatabaseManager); assertEquals(LeaderboardStatus.UPDATED, flatFileDatabaseManager.updateLeaderboards()); } @Test void testSaveUser() { - FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager( + new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); //Make a Profile to save and check to see if it worked UUID uuid = UUID.fromString("588fe472-1c82-4c4e-9aa1-7eefccb277e3"); String playerName = "nossr50"; @@ -165,7 +179,8 @@ class FlatFileDatabaseManagerTest { //Save the zero version and see if it looks correct assertNotNull(flatFileDatabaseManager); - assertTrue(flatFileDatabaseManager.getUsersFile().exists()); //Users file should have been created from the above com.gmail.nossr50.database.FlatFileDatabaseManager.checkFileHealthAndStructure + assertTrue(flatFileDatabaseManager.getUsersFile() + .exists()); //Users file should have been created from the above com.gmail.nossr50.database.FlatFileDatabaseManager.checkFileHealthAndStructure assertNotNull(flatFileDatabaseManager.getUsersFile()); //The flatFileDatabaseManager is empty at this point, add our user @@ -173,7 +188,8 @@ class FlatFileDatabaseManagerTest { //Check for the empty profile PlayerProfile retrievedFromData = flatFileDatabaseManager.loadPlayerProfile(uuid); - assertTrue(retrievedFromData.isLoaded()); //PlayerProfile::isLoaded returns true if the data was created from the file, false if it wasn't found and a dummy profile was returned + assertTrue( + retrievedFromData.isLoaded()); //PlayerProfile::isLoaded returns true if the data was created from the file, false if it wasn't found and a dummy profile was returned assertEquals(uuid, retrievedFromData.getUniqueId()); assertEquals(playerName, retrievedFromData.getPlayerName()); @@ -183,10 +199,12 @@ class FlatFileDatabaseManagerTest { String alteredName = "changedmyname"; PlayerProfile changedNameProfile = new PlayerProfile(alteredName, uuid, 0); - assertTrue(flatFileDatabaseManager.saveUser(changedNameProfile)); //True means we saved the user + assertTrue(flatFileDatabaseManager.saveUser( + changedNameProfile)); //True means we saved the user retrievedFromData = flatFileDatabaseManager.loadPlayerProfile(uuid); - assertTrue(retrievedFromData.isLoaded()); //PlayerProfile::isLoaded returns true if the data was created from the file, false if it wasn't found and a dummy profile was returned + assertTrue( + retrievedFromData.isLoaded()); //PlayerProfile::isLoaded returns true if the data was created from the file, false if it wasn't found and a dummy profile was returned assertEquals(uuid, retrievedFromData.getUniqueId()); assertEquals(alteredName, retrievedFromData.getPlayerName()); } @@ -194,7 +212,8 @@ class FlatFileDatabaseManagerTest { @Test void testAddedMissingLastLoginValues() { File dbFile = prepareDatabaseTestResource(DB_MISSING_LAST_LOGIN); - FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(dbFile, logger, PURGE_TIME, 0, true); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(dbFile, + logger, PURGE_TIME, 0, true); List flagsFound = flatFileDatabaseManager.checkFileHealthAndStructure(); assertNotNull(flagsFound); assertTrue(flagsFound.contains(FlatFileDataFlag.LAST_LOGIN_SCHEMA_UPGRADE)); @@ -207,7 +226,8 @@ class FlatFileDatabaseManagerTest { @Test void testLoadByName() { File healthyDB = prepareDatabaseTestResource(DB_HEALTHY); - FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(healthyDB, logger, PURGE_TIME, 0, true); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(healthyDB, + logger, PURGE_TIME, 0, true); List flagsFound = flatFileDatabaseManager.checkFileHealthAndStructure(); assertNull(flagsFound); //No flags should be found @@ -225,7 +245,9 @@ class FlatFileDatabaseManagerTest { String playerName = "nossr50"; int newUserTestStartingLvl = 1337; - var flatFileDatabaseManager = new FlatFileDatabaseManager(new File(tempDir.getPath() + File.separator + TEST_FILE_NAME), logger, PURGE_TIME, newUserTestStartingLvl, true); + var flatFileDatabaseManager = new FlatFileDatabaseManager( + new File(tempDir.getPath() + File.separator + TEST_FILE_NAME), logger, PURGE_TIME, + newUserTestStartingLvl, true); flatFileDatabaseManager.checkFileHealthAndStructure(); PlayerProfile playerProfile = flatFileDatabaseManager.newUser(playerName, uuid); @@ -260,7 +282,8 @@ class FlatFileDatabaseManagerTest { File file = prepareDatabaseTestResource(DB_HEALTHY); //Existing DB int newUserTestStartingLvl = 1337; - var flatFileDatabaseManager = new FlatFileDatabaseManager(file, logger, PURGE_TIME, newUserTestStartingLvl, true); + var flatFileDatabaseManager = new FlatFileDatabaseManager(file, logger, PURGE_TIME, + newUserTestStartingLvl, true); flatFileDatabaseManager.checkFileHealthAndStructure(); PlayerProfile playerProfile = flatFileDatabaseManager.newUser(playerName, uuid); @@ -292,15 +315,16 @@ class FlatFileDatabaseManagerTest { private void checkNewUserValues(@NotNull PlayerProfile playerProfile, int startingLevel) { //Checking a new user for being zero initialized - for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { - if (SkillTools.isChildSkill(primarySkillType)) + for (PrimarySkillType primarySkillType : PrimarySkillType.values()) { + if (SkillTools.isChildSkill(primarySkillType)) { continue; + } assertEquals(startingLevel, playerProfile.getSkillLevel(primarySkillType)); assertEquals(0, playerProfile.getSkillXpLevelRaw(primarySkillType), 0); } - for(SuperAbilityType superAbilityType : SuperAbilityType.values()) { + for (SuperAbilityType superAbilityType : SuperAbilityType.values()) { assertEquals(0, playerProfile.getAbilityDATS(superAbilityType)); } @@ -312,7 +336,8 @@ class FlatFileDatabaseManagerTest { @Test void testLoadByUUID() { File dbFile = prepareDatabaseTestResource(DB_HEALTHY); - var flatFileDatabaseManager = new FlatFileDatabaseManager(dbFile, logger, PURGE_TIME, 0, true); + var flatFileDatabaseManager = new FlatFileDatabaseManager(dbFile, logger, PURGE_TIME, 0, + true); List flagsFound = flatFileDatabaseManager.checkFileHealthAndStructure(); assertNull(flagsFound); //No flags should be found @@ -326,14 +351,15 @@ class FlatFileDatabaseManagerTest { PlayerProfile profile1 = flatFileDatabaseManager.loadPlayerProfile(uuid); testHealthyDataProfileValues(playerName, uuid, profile1); - - assertFalse(flatFileDatabaseManager.loadPlayerProfile(new UUID(0, 1)).isLoaded()); //This profile should not exist and therefor will return unloaded + assertFalse(flatFileDatabaseManager.loadPlayerProfile(new UUID(0, 1)) + .isLoaded()); //This profile should not exist and therefor will return unloaded } @Test void testLoadByUUIDAndName() { File dbFile = prepareDatabaseTestResource(DB_HEALTHY); - var flatFileDatabaseManager = new FlatFileDatabaseManager(dbFile, logger, PURGE_TIME, 0, true); + var flatFileDatabaseManager = new FlatFileDatabaseManager(dbFile, logger, PURGE_TIME, 0, + true); List flagsFound = flatFileDatabaseManager.checkFileHealthAndStructure(); assertNull(flagsFound); //No flags should be found @@ -346,7 +372,8 @@ class FlatFileDatabaseManagerTest { String updatedName = "updatedName"; Player updatedNamePlayer = initMockPlayer(updatedName, uuid); - PlayerProfile updatedNameProfile = flatFileDatabaseManager.loadPlayerProfile(updatedNamePlayer); + PlayerProfile updatedNameProfile = flatFileDatabaseManager.loadPlayerProfile( + updatedNamePlayer); testHealthyDataProfileValues(updatedName, uuid, updatedNameProfile); Player shouldNotExist = initMockPlayer("doesntexist", new UUID(0, 1)); @@ -387,8 +414,10 @@ class FlatFileDatabaseManagerTest { return copyOfFile; } - private void testHealthyDataProfileValues(@NotNull String playerName, @NotNull UUID uuid, @NotNull PlayerProfile profile) { - assertTrue(profile.isLoaded()); //PlayerProfile::isLoaded returns true if the data was created from the file, false if it wasn't found and a dummy profile was returned + private void testHealthyDataProfileValues(@NotNull String playerName, @NotNull UUID uuid, + @NotNull PlayerProfile profile) { + assertTrue( + profile.isLoaded()); //PlayerProfile::isLoaded returns true if the data was created from the file, false if it wasn't found and a dummy profile was returned assertEquals(uuid, profile.getUniqueId()); assertEquals(playerName, profile.getPlayerName()); @@ -396,25 +425,30 @@ class FlatFileDatabaseManagerTest { * Player is a match and data is loaded, check values */ - for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { - if (SkillTools.isChildSkill(primarySkillType)) + for (PrimarySkillType primarySkillType : PrimarySkillType.values()) { + if (SkillTools.isChildSkill(primarySkillType)) { continue; + } - int expectedLevelHealthyDBEntryOne = getExpectedLevelHealthyDBEntryOne(primarySkillType); + int expectedLevelHealthyDBEntryOne = getExpectedLevelHealthyDBEntryOne( + primarySkillType); int skillLevel = profile.getSkillLevel(primarySkillType); assertEquals(expectedLevelHealthyDBEntryOne, skillLevel); - float expectedExperienceHealthyDBEntryOne = getExpectedExperienceHealthyDBEntryOne(primarySkillType); + float expectedExperienceHealthyDBEntryOne = getExpectedExperienceHealthyDBEntryOne( + primarySkillType); float skillXpLevelRaw = profile.getSkillXpLevelRaw(primarySkillType); assertEquals(expectedExperienceHealthyDBEntryOne, skillXpLevelRaw, 0); } //Check the other things - for(SuperAbilityType superAbilityType : SuperAbilityType.values()) { - assertEquals(getExpectedSuperAbilityDATS(superAbilityType), profile.getAbilityDATS(superAbilityType)); + for (SuperAbilityType superAbilityType : SuperAbilityType.values()) { + assertEquals(getExpectedSuperAbilityDATS(superAbilityType), + profile.getAbilityDATS(superAbilityType)); } - assertEquals(expectedChimaeraWingCd, profile.getUniqueData(UniqueDataType.CHIMAERA_WING_DATS)); + assertEquals(expectedChimaeraWingCd, + profile.getUniqueData(UniqueDataType.CHIMAERA_WING_DATS)); assertEquals(expectedScoreboardTips, profile.getScoreboardTipsShown()); assertEquals(expectedLastLogin, profile.getLastLogin()); } @@ -433,13 +467,15 @@ class FlatFileDatabaseManagerTest { case TRIDENTS_SUPER_ABILITY -> expectedTridentSuperCd; case EXPLOSIVE_SHOT -> expectedExplosiveShotCd; case MACES_SUPER_ABILITY -> expectedMacesSuperCd; - default -> throw new RuntimeException("Values not defined for super ability please add " + - "values for " + superAbilityType.toString() + " to the test"); + default -> + throw new RuntimeException("Values not defined for super ability please add " + + "values for " + superAbilityType + " to the test"); }; } - private float getExpectedExperienceHealthyDBEntryOne(@NotNull PrimarySkillType primarySkillType) { + private float getExpectedExperienceHealthyDBEntryOne( + @NotNull PrimarySkillType primarySkillType) { return switch (primarySkillType) { case ACROBATICS -> expectedExpAcrobatics; case ALCHEMY -> expectedExpAlchemy; @@ -458,8 +494,9 @@ class FlatFileDatabaseManagerTest { case UNARMED -> expectedExpUnarmed; case WOODCUTTING -> expectedExpWoodcutting; case MACES -> expectedExpMaces; - default -> - throw new RuntimeException("Values for skill not defined, please add values for " + primarySkillType.toString() + " to the test"); + default -> throw new RuntimeException( + "Values for skill not defined, please add values for " + + primarySkillType + " to the test"); }; } @@ -483,23 +520,28 @@ class FlatFileDatabaseManagerTest { case UNARMED -> expectedLvlUnarmed; case WOODCUTTING -> expectedLvlWoodcutting; case MACES -> expectedLvlMaces; - default -> - throw new RuntimeException("Values for skill not defined, please add values for " + primarySkillType.toString() + " to the test"); + default -> throw new RuntimeException( + "Values for skill not defined, please add values for " + + primarySkillType + " to the test"); }; } @Test void testOverwriteName() { - FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); - overwriteDataAndCheckForFlag(flatFileDatabaseManager, duplicateNameDatabaseData, FlatFileDataFlag.DUPLICATE_NAME); - ArrayList splitDataLines = getSplitDataFromFile(flatFileDatabaseManager.getUsersFile()); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager( + new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, duplicateNameDatabaseData, + FlatFileDataFlag.DUPLICATE_NAME); + ArrayList splitDataLines = getSplitDataFromFile( + flatFileDatabaseManager.getUsersFile()); assertNotEquals(splitDataLines.get(1)[0], splitDataLines.get(0)[0]); //Name comparison } @Test void testDataNotFound() { - FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager( + new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); //Save the zero version and see if it looks correct assertNotNull(flatFileDatabaseManager); assertTrue(flatFileDatabaseManager.getUsersFile().exists()); @@ -507,12 +549,14 @@ class FlatFileDatabaseManagerTest { //Check for the "unloaded" profile PlayerProfile retrievedFromData = flatFileDatabaseManager.loadPlayerProfile("nossr50"); - assertFalse(retrievedFromData.isLoaded()); //PlayerProfile::isLoaded returns false if data doesn't exist for the user + assertFalse( + retrievedFromData.isLoaded()); //PlayerProfile::isLoaded returns false if data doesn't exist for the user } @Test void testPurgePowerlessUsers() { - FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager( + new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); replaceDataInFile(flatFileDatabaseManager, normalDatabaseData); int purgeCount = flatFileDatabaseManager.purgePowerlessUsers(); assertEquals(purgeCount, 1); //1 User should have been purged @@ -520,7 +564,8 @@ class FlatFileDatabaseManagerTest { @Test void testCheckFileHealthAndStructure() { - FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager( + new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); replaceDataInFile(flatFileDatabaseManager, badDatabaseData); List dataFlags = flatFileDatabaseManager.checkFileHealthAndStructure(); @@ -530,49 +575,64 @@ class FlatFileDatabaseManagerTest { @Test void testFindFixableDuplicateNames() { - FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); - overwriteDataAndCheckForFlag(flatFileDatabaseManager, duplicateNameDatabaseData, FlatFileDataFlag.DUPLICATE_NAME); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager( + new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, duplicateNameDatabaseData, + FlatFileDataFlag.DUPLICATE_NAME); } @Test void testFindDuplicateUUIDs() { - FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); - overwriteDataAndCheckForFlag(flatFileDatabaseManager, duplicateUUIDDatabaseData, FlatFileDataFlag.DUPLICATE_UUID); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager( + new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, duplicateUUIDDatabaseData, + FlatFileDataFlag.DUPLICATE_UUID); } @Test() void findBadUUIDData() { - FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); - overwriteDataAndCheckForFlag(flatFileDatabaseManager, badUUIDDatabaseData, FlatFileDataFlag.BAD_UUID_DATA); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager( + new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, badUUIDDatabaseData, + FlatFileDataFlag.BAD_UUID_DATA); } @Test void testFindCorruptData() { - FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); - overwriteDataAndCheckForFlag(flatFileDatabaseManager, corruptDatabaseData, FlatFileDataFlag.CORRUPTED_OR_UNRECOGNIZABLE); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager( + new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, corruptDatabaseData, + FlatFileDataFlag.CORRUPTED_OR_UNRECOGNIZABLE); } @Test void testFindEmptyNames() { - FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); - overwriteDataAndCheckForFlag(flatFileDatabaseManager, emptyNameDatabaseData, FlatFileDataFlag.MISSING_NAME); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager( + new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, emptyNameDatabaseData, + FlatFileDataFlag.MISSING_NAME); } @Test void testFindBadValues() { - FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); - overwriteDataAndCheckForFlag(flatFileDatabaseManager, badDatabaseData, FlatFileDataFlag.BAD_VALUES); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager( + new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, badDatabaseData, + FlatFileDataFlag.BAD_VALUES); } @Test void testFindOutdatedData() { - FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); - overwriteDataAndCheckForFlag(flatFileDatabaseManager, outdatedDatabaseData, FlatFileDataFlag.INCOMPLETE); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager( + new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, outdatedDatabaseData, + FlatFileDataFlag.INCOMPLETE); } @Test void testGetDatabaseType() { - FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager( + new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); assertNotNull(flatFileDatabaseManager); assertEquals(flatFileDatabaseManager.getDatabaseType(), DatabaseType.FLATFILE); } @@ -580,20 +640,25 @@ class FlatFileDatabaseManagerTest { @Test void testReadRank() { //This is an empty DB - FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager( + new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); String rankBoyName = "rankBoy"; UUID rankBoyUUID = new UUID(1337, 1337); String rankGirlName = "rankGirl"; UUID rankGirlUUID = new UUID(7331, 7331); - PlayerProfile rankGirlProfile = addPlayerProfileWithLevelsAndSave(rankGirlName, rankGirlUUID, 100); //Rank 1 - PlayerProfile rankBoyProfile = addPlayerProfileWithLevelsAndSave(rankBoyName, rankBoyUUID, 10); //Rank 2 + PlayerProfile rankGirlProfile = addPlayerProfileWithLevelsAndSave(rankGirlName, + rankGirlUUID, 100); //Rank 1 + PlayerProfile rankBoyProfile = addPlayerProfileWithLevelsAndSave(rankBoyName, rankBoyUUID, + 10); //Rank 2 assertEquals(LeaderboardStatus.UPDATED, flatFileDatabaseManager.updateLeaderboards()); - Map rankGirlPositions = flatFileDatabaseManager.readRank(rankGirlName); - Map rankBoyPositions = flatFileDatabaseManager.readRank(rankBoyName); + Map rankGirlPositions = flatFileDatabaseManager.readRank( + rankGirlName); + Map rankBoyPositions = flatFileDatabaseManager.readRank( + rankBoyName); - for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { + for (PrimarySkillType primarySkillType : PrimarySkillType.values()) { if (primarySkillType.isChildSkill()) { assertNull(rankBoyPositions.get(primarySkillType)); assertNull(rankGirlPositions.get(primarySkillType)); @@ -603,8 +668,10 @@ class FlatFileDatabaseManagerTest { } } - assertEquals(1, flatFileDatabaseManager.readRank(rankGirlName).get(null)); //Girl should be position 1 - assertEquals(2, flatFileDatabaseManager.readRank(rankBoyName).get(null)); //Boy should be position 2 + assertEquals(1, flatFileDatabaseManager.readRank(rankGirlName) + .get(null)); //Girl should be position 1 + assertEquals(2, + flatFileDatabaseManager.readRank(rankBoyName).get(null)); //Boy should be position 2 } @Test @@ -639,12 +706,13 @@ class FlatFileDatabaseManagerTest { //This makes sure our private method is working before the tests run afterwards ArrayList dataFromFile = getSplitDataFromFile(copyOfFile); - logger.info("File Path: "+copyOfFile.getAbsolutePath()); + logger.info("File Path: " + copyOfFile.getAbsolutePath()); assertArrayEquals(BAD_FILE_LINE_ONE.split(":"), dataFromFile.get(0)); assertEquals(dataFromFile.get(22)[0], "nossr51"); assertArrayEquals(BAD_DATA_FILE_LINE_TWENTY_THREE.split(":"), dataFromFile.get(22)); - FlatFileDatabaseManager db_a = new FlatFileDatabaseManager(copyOfFile, logger, PURGE_TIME, 0, true); + FlatFileDatabaseManager db_a = new FlatFileDatabaseManager(copyOfFile, logger, PURGE_TIME, + 0, true); List flagsFound = db_a.checkFileHealthAndStructure(); assertNotNull(flagsFound); assertTrue(flagsFound.contains(FlatFileDataFlag.BAD_VALUES)); @@ -657,8 +725,9 @@ class FlatFileDatabaseManagerTest { String line; while ((line = bufferedReader.readLine()) != null) { - if (line.isEmpty()) + if (line.isEmpty()) { continue; + } String[] splitData = line.split(":"); splitDataList.add(splitData); @@ -671,8 +740,10 @@ class FlatFileDatabaseManagerTest { return splitDataList; } - private @NotNull PlayerProfile addPlayerProfileWithLevelsAndSave(String playerName, UUID uuid, int levels) { - FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + private @NotNull PlayerProfile addPlayerProfileWithLevelsAndSave(String playerName, UUID uuid, + int levels) { + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager( + new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); assertFalse(flatFileDatabaseManager.loadPlayerProfile(uuid).isLoaded()); flatFileDatabaseManager.newUser(playerName, uuid); @@ -682,17 +753,19 @@ class FlatFileDatabaseManagerTest { assertEquals(playerName, leveledProfile.getPlayerName()); assertEquals(uuid, leveledProfile.getUniqueId()); - for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { - if (SkillTools.isChildSkill(primarySkillType)) + for (PrimarySkillType primarySkillType : PrimarySkillType.values()) { + if (SkillTools.isChildSkill(primarySkillType)) { continue; + } - leveledProfile.modifySkill(primarySkillType, levels); //TODO: This method also resets XP, not cool + leveledProfile.modifySkill(primarySkillType, + levels); //TODO: This method also resets XP, not cool } flatFileDatabaseManager.saveUser(leveledProfile); leveledProfile = flatFileDatabaseManager.loadPlayerProfile(uuid); - for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { + for (PrimarySkillType primarySkillType : PrimarySkillType.values()) { if (SkillTools.isChildSkill(primarySkillType)) { continue; } @@ -703,7 +776,8 @@ class FlatFileDatabaseManagerTest { return leveledProfile; } - private void replaceDataInFile(@NotNull FlatFileDatabaseManager flatFileDatabaseManager, @NotNull String[] dataEntries) { + private void replaceDataInFile(@NotNull FlatFileDatabaseManager flatFileDatabaseManager, + @NotNull String[] dataEntries) { String filePath = flatFileDatabaseManager.getUsersFile().getAbsolutePath(); BufferedReader in = null; FileWriter out = null; @@ -711,7 +785,7 @@ class FlatFileDatabaseManagerTest { try { StringBuilder writer = new StringBuilder(); - for(String data : dataEntries) { + for (String data : dataEntries) { writer.append(data).append("\r\n"); } @@ -726,15 +800,15 @@ class FlatFileDatabaseManagerTest { if (out != null) { try { out.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } } try { - logger.info("Added the following lines to the FlatFileDatabase for the purposes of the test..."); + logger.info( + "Added the following lines to the FlatFileDatabase for the purposes of the test..."); // Open the file in = new BufferedReader(new FileReader(filePath)); String line; @@ -747,15 +821,15 @@ class FlatFileDatabaseManagerTest { if (in != null) { try { in.close(); - } - catch (IOException e) { + } catch (IOException e) { // Ignore } } } } - private void overwriteDataAndCheckForFlag(@NotNull FlatFileDatabaseManager targetDatabase, @NotNull String[] data, @NotNull FlatFileDataFlag flag) { + private void overwriteDataAndCheckForFlag(@NotNull FlatFileDatabaseManager targetDatabase, + @NotNull String[] data, @NotNull FlatFileDataFlag flag) { replaceDataInFile(targetDatabase, data); List dataFlags = targetDatabase.checkFileHealthAndStructure(); diff --git a/src/test/java/com/gmail/nossr50/database/flatfile/FlatFileDataUtilTest.java b/src/test/java/com/gmail/nossr50/database/flatfile/FlatFileDataUtilTest.java index db7fad9f5..399709a1c 100644 --- a/src/test/java/com/gmail/nossr50/database/flatfile/FlatFileDataUtilTest.java +++ b/src/test/java/com/gmail/nossr50/database/flatfile/FlatFileDataUtilTest.java @@ -1,11 +1,10 @@ package com.gmail.nossr50.database.flatfile; import com.gmail.nossr50.database.FlatFileDatabaseManager; +import java.util.HashSet; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.HashSet; - class FlatFileDataUtilTest { @Test @@ -26,7 +25,8 @@ class FlatFileDataUtilTest { @Test void testTooManyDataEntriesSplitString() { Assertions.assertThrows(AssertionError.class, () -> { - FlatFileDataContainer dataContainer = new CategorizedFlatFileData(0, new HashSet<>(), new String[FlatFileDatabaseManager.DATA_ENTRY_COUNT + 1]); + FlatFileDataContainer dataContainer = new CategorizedFlatFileData(0, new HashSet<>(), + new String[FlatFileDatabaseManager.DATA_ENTRY_COUNT + 1]); FlatFileDataUtil.getPreparedSaveDataLine(dataContainer); }); } diff --git a/src/test/java/com/gmail/nossr50/locale/LocaleLoaderTest.java b/src/test/java/com/gmail/nossr50/locale/LocaleLoaderTest.java index d7db4bee3..d1e149f4e 100644 --- a/src/test/java/com/gmail/nossr50/locale/LocaleLoaderTest.java +++ b/src/test/java/com/gmail/nossr50/locale/LocaleLoaderTest.java @@ -1,5 +1,8 @@ package com.gmail.nossr50.locale; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; import org.bukkit.ChatColor; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -7,10 +10,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; - class LocaleLoaderTest { @BeforeEach @@ -59,7 +58,8 @@ class LocaleLoaderTest { } @ParameterizedTest - @ValueSource(strings = {"&#FF0000Te�FFst", "&#FF0000Te[[RED]]st", "[[BLUE]]Te[[RED]]st", "§9Te§cst"}) + @ValueSource(strings = {"&#FF0000Te�FFst", "&#FF0000Te[[RED]]st", "[[BLUE]]Te[[RED]]st", + "§9Te§cst"}) void addColorsShouldAddRedAndBlue(String testString) { // When final String result = LocaleLoader.addColors(testString); diff --git a/src/test/java/com/gmail/nossr50/party/PartyManagerTest.java b/src/test/java/com/gmail/nossr50/party/PartyManagerTest.java index 5bf59751e..e009dfb11 100644 --- a/src/test/java/com/gmail/nossr50/party/PartyManagerTest.java +++ b/src/test/java/com/gmail/nossr50/party/PartyManagerTest.java @@ -1,22 +1,21 @@ package com.gmail.nossr50.party; -import com.gmail.nossr50.MMOTestEnvironment; -import com.gmail.nossr50.datatypes.player.McMMOPlayer; -import com.gmail.nossr50.mcMMO; -import org.bukkit.entity.Player; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - -import java.util.UUID; -import java.util.logging.Logger; - import static java.util.logging.Logger.getLogger; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.gmail.nossr50.MMOTestEnvironment; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; +import com.gmail.nossr50.mcMMO; +import java.util.UUID; +import java.util.logging.Logger; +import org.bukkit.entity.Player; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + class PartyManagerTest extends MMOTestEnvironment { private static final Logger logger = getLogger(PartyManagerTest.class.getName()); @@ -43,7 +42,7 @@ class PartyManagerTest extends MMOTestEnvironment { String partyName = "TestParty"; Player player = mock(Player.class); - McMMOPlayer mmoPlayer = mock(McMMOPlayer.class); + final McMMOPlayer mmoPlayer = mock(McMMOPlayer.class); when(mmoPlayer.getPlayer()).thenReturn(player); when(player.getUniqueId()).thenReturn(new UUID(0, 0)); @@ -59,7 +58,7 @@ class PartyManagerTest extends MMOTestEnvironment { String partyPassword = "somePassword"; Player player = mock(Player.class); - McMMOPlayer mmoPlayer = mock(McMMOPlayer.class); + final McMMOPlayer mmoPlayer = mock(McMMOPlayer.class); when(mmoPlayer.getPlayer()).thenReturn(player); when(player.getUniqueId()).thenReturn(new UUID(0, 0)); @@ -74,7 +73,7 @@ class PartyManagerTest extends MMOTestEnvironment { String partyPassword = "somePassword"; Player player = mock(Player.class); - McMMOPlayer mmoPlayer = mock(McMMOPlayer.class); + final McMMOPlayer mmoPlayer = mock(McMMOPlayer.class); when(mmoPlayer.getPlayer()).thenReturn(player); when(player.getUniqueId()).thenReturn(new UUID(0, 0)); diff --git a/src/test/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsTest.java b/src/test/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsTest.java index bbe19548b..862e6a902 100644 --- a/src/test/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsTest.java +++ b/src/test/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsTest.java @@ -1,5 +1,14 @@ package com.gmail.nossr50.skills.acrobatics; +import static java.util.logging.Logger.getLogger; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import com.gmail.nossr50.MMOTestEnvironment; import com.gmail.nossr50.api.exceptions.InvalidSkillException; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; @@ -8,6 +17,7 @@ import com.gmail.nossr50.datatypes.skills.subskills.AbstractSubSkill; import com.gmail.nossr50.datatypes.skills.subskills.acrobatics.Roll; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.skills.RankUtils; +import java.util.logging.Logger; import org.bukkit.entity.Player; import org.bukkit.event.entity.EntityDamageEvent; import org.jetbrains.annotations.NotNull; @@ -16,14 +26,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.logging.Logger; - -import static java.util.logging.Logger.getLogger; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.*; - class AcrobaticsTest extends MMOTestEnvironment { private static final Logger logger = getLogger(AcrobaticsTest.class.getName()); @@ -38,12 +40,17 @@ class AcrobaticsTest extends MMOTestEnvironment { when(advancedConfig.getMaxBonusLevel(SubSkillType.ACROBATICS_ROLL)).thenReturn(1000); when(advancedConfig.getRollDamageThreshold()).thenReturn(7D); - Mockito.when(RankUtils.getRankUnlockLevel(SubSkillType.ACROBATICS_ROLL, 1)).thenReturn(1); // needed? - Mockito.when(RankUtils.getRankUnlockLevel(SubSkillType.ACROBATICS_DODGE, 1)).thenReturn(1000); // needed? + Mockito.when(RankUtils.getRankUnlockLevel(SubSkillType.ACROBATICS_ROLL, 1)) + .thenReturn(1); // needed? + Mockito.when(RankUtils.getRankUnlockLevel(SubSkillType.ACROBATICS_DODGE, 1)) + .thenReturn(1000); // needed? - when(RankUtils.getRankUnlockLevel(SubSkillType.ACROBATICS_ROLL, 1)).thenReturn(1); // needed? - when(RankUtils.hasReachedRank(eq(1), any(Player.class), eq(SubSkillType.ACROBATICS_ROLL))).thenReturn(true); - when(RankUtils.hasReachedRank(eq(1), any(Player.class), any(AbstractSubSkill.class))).thenReturn(true); + when(RankUtils.getRankUnlockLevel(SubSkillType.ACROBATICS_ROLL, 1)).thenReturn( + 1); // needed? + when(RankUtils.hasReachedRank(eq(1), any(Player.class), + eq(SubSkillType.ACROBATICS_ROLL))).thenReturn(true); + when(RankUtils.hasReachedRank(eq(1), any(Player.class), + any(AbstractSubSkill.class))).thenReturn(true); } @AfterEach diff --git a/src/test/java/com/gmail/nossr50/skills/excavation/ExcavationTest.java b/src/test/java/com/gmail/nossr50/skills/excavation/ExcavationTest.java index 95e8be785..ac4a73bc1 100644 --- a/src/test/java/com/gmail/nossr50/skills/excavation/ExcavationTest.java +++ b/src/test/java/com/gmail/nossr50/skills/excavation/ExcavationTest.java @@ -1,11 +1,21 @@ package com.gmail.nossr50.skills.excavation; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import com.gmail.nossr50.MMOTestEnvironment; import com.gmail.nossr50.api.exceptions.InvalidSkillException; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.treasure.ExcavationTreasure; import com.gmail.nossr50.util.skills.RankUtils; +import java.util.ArrayList; +import java.util.List; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; @@ -16,28 +26,28 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.ArrayList; -import java.util.List; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.*; - class ExcavationTest extends MMOTestEnvironment { - private static final java.util.logging.Logger logger = java.util.logging.Logger.getLogger(ExcavationTest.class.getName()); + private static final java.util.logging.Logger logger = java.util.logging.Logger.getLogger( + ExcavationTest.class.getName()); @BeforeEach void setUp() throws InvalidSkillException { mockBaseEnvironment(logger); - when(rankConfig.getSubSkillUnlockLevel(SubSkillType.EXCAVATION_ARCHAEOLOGY, 1)).thenReturn(1); - when(rankConfig.getSubSkillUnlockLevel(SubSkillType.EXCAVATION_GIGA_DRILL_BREAKER, 1)).thenReturn(1); + when(rankConfig.getSubSkillUnlockLevel(SubSkillType.EXCAVATION_ARCHAEOLOGY, 1)).thenReturn( + 1); + when(rankConfig.getSubSkillUnlockLevel(SubSkillType.EXCAVATION_GIGA_DRILL_BREAKER, + 1)).thenReturn(1); // wire advanced config - when(RankUtils.getRankUnlockLevel(SubSkillType.EXCAVATION_ARCHAEOLOGY, 1)).thenReturn(1); // needed? - when(RankUtils.getRankUnlockLevel(SubSkillType.EXCAVATION_GIGA_DRILL_BREAKER, 1)).thenReturn(1); // needed? - when(RankUtils.hasReachedRank(eq(1), any(Player.class), eq(SubSkillType.EXCAVATION_ARCHAEOLOGY))).thenReturn(true); - when(RankUtils.hasReachedRank(eq(1), any(Player.class), eq(SubSkillType.EXCAVATION_GIGA_DRILL_BREAKER))).thenReturn(true); + when(RankUtils.getRankUnlockLevel(SubSkillType.EXCAVATION_ARCHAEOLOGY, 1)).thenReturn( + 1); // needed? + when(RankUtils.getRankUnlockLevel(SubSkillType.EXCAVATION_GIGA_DRILL_BREAKER, + 1)).thenReturn(1); // needed? + when(RankUtils.hasReachedRank(eq(1), any(Player.class), + eq(SubSkillType.EXCAVATION_ARCHAEOLOGY))).thenReturn(true); + when(RankUtils.hasReachedRank(eq(1), any(Player.class), + eq(SubSkillType.EXCAVATION_GIGA_DRILL_BREAKER))).thenReturn(true); // setup player and player related mocks after everything else this.player = Mockito.mock(Player.class); @@ -85,18 +95,19 @@ class ExcavationTest extends MMOTestEnvironment { excavationManager.excavationBlockCheck(block); // verify ExcavationManager.processExcavationBonusesOnBlock was called - verify(excavationManager, never()).processExcavationBonusesOnBlock(any(ExcavationTreasure.class), + verify(excavationManager, never()).processExcavationBonusesOnBlock( + any(ExcavationTreasure.class), any(Location.class)); } private List getGuaranteedTreasureDrops() { - List treasures = new ArrayList<>();; + List treasures = new ArrayList<>(); treasures.add(new ExcavationTreasure(new ItemStack(Material.CAKE), 1, 100, 1)); return treasures; } private List getImpossibleTreasureDrops() { - List treasures = new ArrayList<>();; + List treasures = new ArrayList<>(); treasures.add(new ExcavationTreasure(new ItemStack(Material.CAKE), 1, 0, 1)); return treasures; } diff --git a/src/test/java/com/gmail/nossr50/skills/tridents/TridentsTest.java b/src/test/java/com/gmail/nossr50/skills/tridents/TridentsTest.java index ae6bb191e..13c6031ae 100644 --- a/src/test/java/com/gmail/nossr50/skills/tridents/TridentsTest.java +++ b/src/test/java/com/gmail/nossr50/skills/tridents/TridentsTest.java @@ -1,7 +1,10 @@ package com.gmail.nossr50.skills.tridents; +import static java.util.logging.Logger.getLogger; + import com.gmail.nossr50.MMOTestEnvironment; import com.gmail.nossr50.api.exceptions.InvalidSkillException; +import java.util.logging.Logger; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -10,15 +13,12 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.mockito.Mockito; -import java.util.logging.Logger; - -import static java.util.logging.Logger.getLogger; - class TridentsTest extends MMOTestEnvironment { private static final Logger logger = getLogger(TridentsTest.class.getName()); TridentsManager tridentsManager; ItemStack trident; + @BeforeEach void setUp() throws InvalidSkillException { mockBaseEnvironment(logger); diff --git a/src/test/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingTest.java b/src/test/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingTest.java index 48f0717c4..7e19ac58c 100644 --- a/src/test/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingTest.java +++ b/src/test/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingTest.java @@ -1,11 +1,17 @@ package com.gmail.nossr50.skills.woodcutting; +import static java.util.logging.Logger.getLogger; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; + import com.gmail.nossr50.MMOTestEnvironment; import com.gmail.nossr50.api.exceptions.InvalidSkillException; import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.util.skills.RankUtils; +import java.util.Collections; +import java.util.logging.Logger; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Player; @@ -15,13 +21,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.Collections; -import java.util.logging.Logger; - -import static java.util.logging.Logger.getLogger; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; - class WoodcuttingTest extends MMOTestEnvironment { private static final Logger logger = getLogger(WoodcuttingTest.class.getName()); @@ -30,18 +29,27 @@ class WoodcuttingTest extends MMOTestEnvironment { @BeforeEach void setUp() throws InvalidSkillException { mockBaseEnvironment(logger); - Mockito.when(rankConfig.getSubSkillUnlockLevel(SubSkillType.WOODCUTTING_HARVEST_LUMBER, 1)).thenReturn(1); + Mockito.when(rankConfig.getSubSkillUnlockLevel(SubSkillType.WOODCUTTING_HARVEST_LUMBER, 1)) + .thenReturn(1); // wire advanced config - Mockito.when(advancedConfig.getMaximumProbability(SubSkillType.WOODCUTTING_HARVEST_LUMBER)).thenReturn(100D); - Mockito.when(advancedConfig.getMaximumProbability(SubSkillType.WOODCUTTING_CLEAN_CUTS)).thenReturn(10D); - Mockito.when(advancedConfig.getMaxBonusLevel(SubSkillType.WOODCUTTING_HARVEST_LUMBER)).thenReturn(1000); - Mockito.when(advancedConfig.getMaxBonusLevel(SubSkillType.WOODCUTTING_CLEAN_CUTS)).thenReturn(10000); + Mockito.when(advancedConfig.getMaximumProbability(SubSkillType.WOODCUTTING_HARVEST_LUMBER)) + .thenReturn(100D); + Mockito.when(advancedConfig.getMaximumProbability(SubSkillType.WOODCUTTING_CLEAN_CUTS)) + .thenReturn(10D); + Mockito.when(advancedConfig.getMaxBonusLevel(SubSkillType.WOODCUTTING_HARVEST_LUMBER)) + .thenReturn(1000); + Mockito.when(advancedConfig.getMaxBonusLevel(SubSkillType.WOODCUTTING_CLEAN_CUTS)) + .thenReturn(10000); - Mockito.when(RankUtils.getRankUnlockLevel(SubSkillType.WOODCUTTING_HARVEST_LUMBER, 1)).thenReturn(1); // needed? - Mockito.when(RankUtils.getRankUnlockLevel(SubSkillType.WOODCUTTING_CLEAN_CUTS, 1)).thenReturn(1000); // needed? - Mockito.when(RankUtils.hasReachedRank(eq(1), any(Player.class), eq(SubSkillType.WOODCUTTING_HARVEST_LUMBER))).thenReturn(true); - Mockito.when(RankUtils.hasReachedRank(eq(1), any(Player.class), eq(SubSkillType.WOODCUTTING_CLEAN_CUTS))).thenReturn(true); + Mockito.when(RankUtils.getRankUnlockLevel(SubSkillType.WOODCUTTING_HARVEST_LUMBER, 1)) + .thenReturn(1); // needed? + Mockito.when(RankUtils.getRankUnlockLevel(SubSkillType.WOODCUTTING_CLEAN_CUTS, 1)) + .thenReturn(1000); // needed? + Mockito.when(RankUtils.hasReachedRank(eq(1), any(Player.class), + eq(SubSkillType.WOODCUTTING_HARVEST_LUMBER))).thenReturn(true); + Mockito.when(RankUtils.hasReachedRank(eq(1), any(Player.class), + eq(SubSkillType.WOODCUTTING_CLEAN_CUTS))).thenReturn(true); // wire inventory this.itemInMainHand = new ItemStack(Material.DIAMOND_AXE); @@ -70,7 +78,8 @@ class WoodcuttingTest extends MMOTestEnvironment { // verify bonus drops were spawned // TODO: using at least once since triple drops can also happen // TODO: Change the test env to disallow triple drop in the future - Mockito.verify(woodcuttingManager, Mockito.atLeastOnce()).spawnHarvestLumberBonusDrops(block); + Mockito.verify(woodcuttingManager, Mockito.atLeastOnce()) + .spawnHarvestLumberBonusDrops(block); } @Test @@ -93,10 +102,12 @@ class WoodcuttingTest extends MMOTestEnvironment { Block targetBlock = Mockito.mock(Block.class); Mockito.when(targetBlock.getType()).thenReturn(Material.OAK_LOG); // wire XP - Mockito.when(ExperienceConfig.getInstance().getXp(PrimarySkillType.WOODCUTTING, Material.OAK_LOG)).thenReturn(5); + Mockito.when(ExperienceConfig.getInstance() + .getXp(PrimarySkillType.WOODCUTTING, Material.OAK_LOG)).thenReturn(5); // Verify XP increased by 5 when processing XP woodcuttingManager.processWoodcuttingBlockXP(targetBlock); - Mockito.verify(mmoPlayer, Mockito.times(1)).beginXpGain(eq(PrimarySkillType.WOODCUTTING), eq(5F), any(), any()); + Mockito.verify(mmoPlayer, Mockito.times(1)) + .beginXpGain(eq(PrimarySkillType.WOODCUTTING), eq(5F), any(), any()); } } diff --git a/src/test/java/com/gmail/nossr50/util/PotionEffectUtilTest.java b/src/test/java/com/gmail/nossr50/util/PotionEffectUtilTest.java index c8125b763..6e3b6ce88 100644 --- a/src/test/java/com/gmail/nossr50/util/PotionEffectUtilTest.java +++ b/src/test/java/com/gmail/nossr50/util/PotionEffectUtilTest.java @@ -1,5 +1,13 @@ package com.gmail.nossr50.util; +import static com.gmail.nossr50.util.PotionEffectUtil.getNauseaPotionEffectType; +import static java.util.logging.Logger.getLogger; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.compat.CompatibilityManager; import com.gmail.nossr50.util.platform.MinecraftGameVersion; @@ -10,15 +18,10 @@ import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; -import static com.gmail.nossr50.util.PotionEffectUtil.getNauseaPotionEffectType; -import static java.util.logging.Logger.getLogger; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.Mockito.*; - class PotionEffectUtilTest { private MockedStatic mockedStaticMcMMO; - private static final java.util.logging.Logger logger = getLogger(PotionEffectUtilTest.class.getName()); + private static final java.util.logging.Logger logger = getLogger( + PotionEffectUtilTest.class.getName()); @BeforeEach void setUp() { diff --git a/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java b/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java index 299496320..cbcf4cfc7 100644 --- a/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java +++ b/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java @@ -1,5 +1,12 @@ package com.gmail.nossr50.util; +import static com.gmail.nossr50.util.PotionUtil.convertLegacyNames; +import static com.gmail.nossr50.util.PotionUtil.matchPotionType; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.compat.CompatibilityManager; import com.gmail.nossr50.util.platform.MinecraftGameVersion; @@ -9,11 +16,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; -import static com.gmail.nossr50.util.PotionUtil.convertLegacyNames; -import static com.gmail.nossr50.util.PotionUtil.matchPotionType; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.*; - class PotionUtilTest { MockedStatic mockedStaticMcMMO; diff --git a/src/test/java/com/gmail/nossr50/util/blockmeta/BitSetChunkStoreTest.java b/src/test/java/com/gmail/nossr50/util/blockmeta/BitSetChunkStoreTest.java index 9e266d8d6..81993e614 100644 --- a/src/test/java/com/gmail/nossr50/util/blockmeta/BitSetChunkStoreTest.java +++ b/src/test/java/com/gmail/nossr50/util/blockmeta/BitSetChunkStoreTest.java @@ -1,20 +1,10 @@ package com.gmail.nossr50.util.blockmeta; -import com.gmail.nossr50.mcMMO; -import com.google.common.io.Files; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.junit.jupiter.api.*; -import org.mockito.MockedStatic; -import org.mockito.Mockito; - -import java.io.ByteArrayInputStream; -import java.io.DataInputStream; -import java.io.File; -import java.io.IOException; -import java.util.UUID; - -import static com.gmail.nossr50.util.blockmeta.BlockStoreTestUtils.*; +import static com.gmail.nossr50.util.blockmeta.BlockStoreTestUtils.LEGACY_WORLD_HEIGHT_MAX; +import static com.gmail.nossr50.util.blockmeta.BlockStoreTestUtils.LEGACY_WORLD_HEIGHT_MIN; +import static com.gmail.nossr50.util.blockmeta.BlockStoreTestUtils.assertChunkStoreEquals; +import static com.gmail.nossr50.util.blockmeta.BlockStoreTestUtils.assertEqualIgnoreMinMax; +import static com.gmail.nossr50.util.blockmeta.BlockStoreTestUtils.serializeChunkStore; import static com.gmail.nossr50.util.blockmeta.UserBlockTrackerTest.recursiveDelete; import static org.bukkit.Bukkit.getWorld; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -22,6 +12,23 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; +import com.gmail.nossr50.mcMMO; +import com.google.common.io.Files; +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.File; +import java.io.IOException; +import java.util.UUID; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + class BitSetChunkStoreTest { private static File tempDir; @@ -88,7 +95,8 @@ class BitSetChunkStoreTest { original.setTrue(14, 90, 12); original.setTrue(13, 89, 12); byte[] serializedBytes = serializeChunkStore(original); - final ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore(new DataInputStream(new ByteArrayInputStream(serializedBytes))); + final ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore( + new DataInputStream(new ByteArrayInputStream(serializedBytes))); assertChunkStoreEquals(original, deserialized); } @@ -101,7 +109,8 @@ class BitSetChunkStoreTest { original.setTrue(14, -64, 12); original.setTrue(13, -63, 12); byte[] serializedBytes = serializeChunkStore(original); - final ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore(new DataInputStream(new ByteArrayInputStream(serializedBytes))); + final ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore( + new DataInputStream(new ByteArrayInputStream(serializedBytes))); assertChunkStoreEquals(original, deserialized); } @@ -114,7 +123,8 @@ class BitSetChunkStoreTest { byte[] serializedBytes = serializeChunkStore(original); when(mockWorld.getMinHeight()).thenReturn(-64); - final ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore(new DataInputStream(new ByteArrayInputStream(serializedBytes))); + final ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore( + new DataInputStream(new ByteArrayInputStream(serializedBytes))); assert deserialized != null; assertEqualIgnoreMinMax(original, deserialized); } diff --git a/src/test/java/com/gmail/nossr50/util/blockmeta/BlockStoreTestUtils.java b/src/test/java/com/gmail/nossr50/util/blockmeta/BlockStoreTestUtils.java index 709a7b57f..883f6c745 100644 --- a/src/test/java/com/gmail/nossr50/util/blockmeta/BlockStoreTestUtils.java +++ b/src/test/java/com/gmail/nossr50/util/blockmeta/BlockStoreTestUtils.java @@ -1,12 +1,11 @@ package com.gmail.nossr50.util.blockmeta; -import org.jetbrains.annotations.NotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.jetbrains.annotations.NotNull; public class BlockStoreTestUtils { public static final int LEGACY_WORLD_HEIGHT_MAX = 256; @@ -14,6 +13,7 @@ public class BlockStoreTestUtils { /** * Asserts that the two ChunkStores are equal. + * * @param expected The expected ChunkStore * @param actual The actual ChunkStore */ @@ -25,10 +25,13 @@ public class BlockStoreTestUtils { static byte[] serializeChunkStore(@NotNull ChunkStore chunkStore) throws IOException { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - if (chunkStore instanceof BitSetChunkStore) - BitSetChunkStore.Serialization.writeChunkStore(new DataOutputStream(byteArrayOutputStream), chunkStore); - else - new UnitTestObjectOutputStream(byteArrayOutputStream).writeObject(chunkStore); // Serializes the class as if + if (chunkStore instanceof BitSetChunkStore) { + BitSetChunkStore.Serialization.writeChunkStore( + new DataOutputStream(byteArrayOutputStream), chunkStore); + } else { + new UnitTestObjectOutputStream(byteArrayOutputStream).writeObject( + chunkStore); // Serializes the class as if + } // it were the old // PrimitiveChunkStore return byteArrayOutputStream.toByteArray(); @@ -38,12 +41,17 @@ public class BlockStoreTestUtils { assertEquals(expected.getChunkX(), actual.getChunkX()); assertEquals(expected.getChunkZ(), actual.getChunkZ()); assertEquals(expected.getWorldId(), actual.getWorldId()); - for (int y = Math.min(actual.getChunkMin(), expected.getChunkMin()); y < Math.max(actual.getChunkMax(), expected.getChunkMax()); y++) { - if (expected.getChunkMin() > y || actual.getChunkMin() > y || expected.getChunkMax() <= y || actual.getChunkMax() <= y) + for (int y = Math.min(actual.getChunkMin(), expected.getChunkMin()); + y < Math.max(actual.getChunkMax(), expected.getChunkMax()); y++) { + if (expected.getChunkMin() > y || actual.getChunkMin() > y + || expected.getChunkMax() <= y || actual.getChunkMax() <= y) { continue; // Ignore - for (int x = 0; x < 16; x++) - for (int z = 0; z < 16; z++) + } + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { assertEquals(expected.isTrue(x, y, z), actual.isTrue(x, y, z)); + } + } } } } diff --git a/src/test/java/com/gmail/nossr50/util/blockmeta/ChunkStoreTest.java b/src/test/java/com/gmail/nossr50/util/blockmeta/ChunkStoreTest.java index f7f369076..797897f78 100644 --- a/src/test/java/com/gmail/nossr50/util/blockmeta/ChunkStoreTest.java +++ b/src/test/java/com/gmail/nossr50/util/blockmeta/ChunkStoreTest.java @@ -1,22 +1,33 @@ package com.gmail.nossr50.util.blockmeta; -import com.gmail.nossr50.mcMMO; -import com.google.common.io.Files; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.junit.jupiter.api.*; -import org.mockito.MockedStatic; -import org.mockito.Mockito; - -import java.io.*; -import java.util.UUID; - -import static com.gmail.nossr50.util.blockmeta.BlockStoreTestUtils.*; +import static com.gmail.nossr50.util.blockmeta.BlockStoreTestUtils.LEGACY_WORLD_HEIGHT_MAX; +import static com.gmail.nossr50.util.blockmeta.BlockStoreTestUtils.LEGACY_WORLD_HEIGHT_MIN; +import static com.gmail.nossr50.util.blockmeta.BlockStoreTestUtils.assertChunkStoreEquals; +import static com.gmail.nossr50.util.blockmeta.BlockStoreTestUtils.serializeChunkStore; import static com.gmail.nossr50.util.blockmeta.UserBlockTrackerTest.recursiveDelete; import static org.bukkit.Bukkit.getWorld; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; +import com.gmail.nossr50.mcMMO; +import com.google.common.io.Files; +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.util.UUID; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + class ChunkStoreTest { private static File tempDir; @@ -65,7 +76,8 @@ class ChunkStoreTest { original.setTrue(14, 90, 12); original.setTrue(13, 89, 12); byte[] serializedBytes = serializeChunkStore(original); - ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore(new DataInputStream(new ByteArrayInputStream(serializedBytes))); + ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore( + new DataInputStream(new ByteArrayInputStream(serializedBytes))); assert deserialized != null; assertChunkStoreEquals(original, deserialized); } @@ -83,7 +95,8 @@ class ChunkStoreTest { } region.close(); region = new McMMOSimpleRegionFile(file, 0, 0); - try (DataInputStream is = region.getInputStream(original.getChunkX(), original.getChunkZ())) { + try (DataInputStream is = region.getInputStream(original.getChunkX(), + original.getChunkZ())) { Assertions.assertNotNull(is); ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore(is); assert deserialized != null; diff --git a/src/test/java/com/gmail/nossr50/util/blockmeta/LegacyChunkStore.java b/src/test/java/com/gmail/nossr50/util/blockmeta/LegacyChunkStore.java index b21cf2594..d01b71e53 100644 --- a/src/test/java/com/gmail/nossr50/util/blockmeta/LegacyChunkStore.java +++ b/src/test/java/com/gmail/nossr50/util/blockmeta/LegacyChunkStore.java @@ -1,13 +1,12 @@ package com.gmail.nossr50.util.blockmeta; -import org.bukkit.World; -import org.jetbrains.annotations.NotNull; - import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.UUID; +import org.bukkit.World; +import org.jetbrains.annotations.NotNull; /** * Used for unit testing upgrades from the old ChunkStore class. @@ -71,24 +70,27 @@ class LegacyChunkStore implements ChunkStore, Serializable { @Override public void setTrue(int x, int y, int z) { - if (y >= store[0][0].length || y < 0) + if (y >= store[0][0].length || y < 0) { return; + } store[x][z][y] = true; dirty = true; } @Override public void setFalse(int x, int y, int z) { - if (y >= store[0][0].length || y < 0) + if (y >= store[0][0].length || y < 0) { return; + } store[x][z][y] = false; dirty = true; } @Override public void set(int x, int y, int z, boolean value) { - if (y >= store[0][0].length || y < 0) + if (y >= store[0][0].length || y < 0) { return; + } store[x][z][y] = value; dirty = true; } @@ -120,7 +122,8 @@ class LegacyChunkStore implements ChunkStore, Serializable { dirty = false; } - private void readObject(@NotNull ObjectInputStream in) throws IOException, ClassNotFoundException { + private void readObject(@NotNull ObjectInputStream in) + throws IOException, ClassNotFoundException { throw new UnsupportedOperationException(); } diff --git a/src/test/java/com/gmail/nossr50/util/blockmeta/UnitTestObjectOutputStream.java b/src/test/java/com/gmail/nossr50/util/blockmeta/UnitTestObjectOutputStream.java index d7eb1c140..5ad834517 100644 --- a/src/test/java/com/gmail/nossr50/util/blockmeta/UnitTestObjectOutputStream.java +++ b/src/test/java/com/gmail/nossr50/util/blockmeta/UnitTestObjectOutputStream.java @@ -1,10 +1,9 @@ package com.gmail.nossr50.util.blockmeta; -import org.jetbrains.annotations.NotNull; - import java.io.IOException; import java.io.ObjectOutputStream; import java.io.OutputStream; +import org.jetbrains.annotations.NotNull; class UnitTestObjectOutputStream extends ObjectOutputStream { @@ -15,8 +14,9 @@ class UnitTestObjectOutputStream extends ObjectOutputStream { @Override public void writeUTF(@NotNull String str) throws IOException { // Pretend to be the old class - if (str.equals(LegacyChunkStore.class.getName())) + if (str.equals(LegacyChunkStore.class.getName())) { str = "com.gmail.nossr50.util.blockmeta.chunkmeta.PrimitiveChunkStore"; + } super.writeUTF(str); } diff --git a/src/test/java/com/gmail/nossr50/util/blockmeta/UserBlockTrackerTest.java b/src/test/java/com/gmail/nossr50/util/blockmeta/UserBlockTrackerTest.java index 553b82a1b..d9279d05a 100644 --- a/src/test/java/com/gmail/nossr50/util/blockmeta/UserBlockTrackerTest.java +++ b/src/test/java/com/gmail/nossr50/util/blockmeta/UserBlockTrackerTest.java @@ -1,20 +1,5 @@ package com.gmail.nossr50.util.blockmeta; -import com.gmail.nossr50.mcMMO; -import com.gmail.nossr50.util.BlockUtils; -import com.google.common.io.Files; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.jetbrains.annotations.NotNull; -import org.junit.jupiter.api.*; -import org.mockito.MockedStatic; -import org.mockito.Mockito; - -import java.io.File; -import java.io.IOException; -import java.util.UUID; - import static com.gmail.nossr50.util.blockmeta.BlockStoreTestUtils.LEGACY_WORLD_HEIGHT_MAX; import static com.gmail.nossr50.util.blockmeta.BlockStoreTestUtils.LEGACY_WORLD_HEIGHT_MIN; import static org.bukkit.Bukkit.getWorld; @@ -23,9 +8,28 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; +import com.gmail.nossr50.mcMMO; +import com.gmail.nossr50.util.BlockUtils; +import com.google.common.io.Files; +import java.io.File; +import java.io.IOException; +import java.util.UUID; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.jetbrains.annotations.NotNull; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + /** - * Could be a lot better. But some tests are better than none! Tests the major things, still kinda unit-testy. Verifies - * that the serialization isn't completely broken. + * Could be a lot better. But some tests are better than none! Tests the major things, still kinda + * unit-testy. Verifies that the serialization isn't completely broken. */ class UserBlockTrackerTest { private static File tempDir; @@ -61,7 +65,7 @@ class UserBlockTrackerTest { when(mockWorld.getMinHeight()).thenReturn(LEGACY_WORLD_HEIGHT_MIN); when(mockWorld.getMaxHeight()).thenReturn(LEGACY_WORLD_HEIGHT_MAX); } - + @AfterEach void teardownMock() { bukkitMock.close(); @@ -76,11 +80,13 @@ class UserBlockTrackerTest { // Top Block int illegalMaxHeight = 256 + 1; final Block illegalHeightBlock = initMockBlock(1337, illegalMaxHeight, -1337); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> hashChunkManager.setIneligible(illegalHeightBlock)); + Assertions.assertThrows(IndexOutOfBoundsException.class, + () -> hashChunkManager.setIneligible(illegalHeightBlock)); int illegalMinHeight = -65; final Block otherIllegalHeightBlock = initMockBlock(1337, illegalMinHeight, -1337); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> hashChunkManager.setIneligible(otherIllegalHeightBlock)); + Assertions.assertThrows(IndexOutOfBoundsException.class, + () -> hashChunkManager.setIneligible(otherIllegalHeightBlock)); } @Test @@ -138,23 +144,34 @@ class UserBlockTrackerTest { void testSimpleRegionRejectsOutOfBounds() { File file = new File(tempDir, "SimpleRegionRoundTrip.region"); McMMOSimpleRegionFile region = new McMMOSimpleRegionFile(file, 0, 0); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> region.getOutputStream(-1, 0)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> region.getOutputStream(0, -1)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> region.getOutputStream(32, 0)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> region.getOutputStream(0, 32)); + Assertions.assertThrows(IndexOutOfBoundsException.class, + () -> region.getOutputStream(-1, 0)); + Assertions.assertThrows(IndexOutOfBoundsException.class, + () -> region.getOutputStream(0, -1)); + Assertions.assertThrows(IndexOutOfBoundsException.class, + () -> region.getOutputStream(32, 0)); + Assertions.assertThrows(IndexOutOfBoundsException.class, + () -> region.getOutputStream(0, 32)); region.close(); } @Test void testChunkStoreRejectsOutOfBounds() { ChunkStore chunkStore = new BitSetChunkStore(mockWorld, 0, 0); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(-1, 0, 0)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(0, -1, 0)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(0, 0, -1)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(16, 0, 0)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(0, mockWorld.getMaxHeight()+1, 0)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(0, mockWorld.getMinHeight()-1, 0)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(0, 0, 16)); + Assertions.assertThrows(IndexOutOfBoundsException.class, + () -> chunkStore.setTrue(-1, 0, 0)); + Assertions.assertThrows(IndexOutOfBoundsException.class, + () -> chunkStore.setTrue(0, -1, 0)); + Assertions.assertThrows(IndexOutOfBoundsException.class, + () -> chunkStore.setTrue(0, 0, -1)); + Assertions.assertThrows(IndexOutOfBoundsException.class, + () -> chunkStore.setTrue(16, 0, 0)); + Assertions.assertThrows(IndexOutOfBoundsException.class, + () -> chunkStore.setTrue(0, mockWorld.getMaxHeight() + 1, 0)); + Assertions.assertThrows(IndexOutOfBoundsException.class, + () -> chunkStore.setTrue(0, mockWorld.getMinHeight() - 1, 0)); + Assertions.assertThrows(IndexOutOfBoundsException.class, + () -> chunkStore.setTrue(0, 0, 16)); } @Test diff --git a/src/test/java/com/gmail/nossr50/util/platform/MinecraftGameVersionTest.java b/src/test/java/com/gmail/nossr50/util/platform/MinecraftGameVersionTest.java index 11c0d4060..84c9adda2 100644 --- a/src/test/java/com/gmail/nossr50/util/platform/MinecraftGameVersionTest.java +++ b/src/test/java/com/gmail/nossr50/util/platform/MinecraftGameVersionTest.java @@ -1,6 +1,12 @@ package com.gmail.nossr50.util.platform; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.gmail.nossr50.mcMMO; +import java.util.logging.Logger; +import java.util.stream.Stream; import org.bukkit.Bukkit; import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.Test; @@ -10,11 +16,6 @@ import org.junit.jupiter.params.provider.MethodSource; import org.mockito.MockedStatic; import org.mockito.Mockito; -import java.util.logging.Logger; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.*; - class MinecraftGameVersionTest { @Test @@ -81,7 +82,8 @@ class MinecraftGameVersionTest { * we will just simulate some "Spigot" version here, so that the test can * continue successfully. */ - String serverSoftwareVersion = "git-Spigot-12345-abcdef (MC: " + major + '.' + minor + '.' + patch + ')'; + String serverSoftwareVersion = + "git-Spigot-12345-abcdef (MC: " + major + '.' + minor + '.' + patch + ')'; // Set up a mock plugin for logging. mcMMO plugin = Mockito.mock(mcMMO.class); @@ -111,19 +113,19 @@ class MinecraftGameVersionTest { * These samples were taken directly from the historical * data of CraftBukkit's pom.xml file: * https://hub.spigotmc.org/stash/projects/SPIGOT/repos/craftbukkit/browse/pom.xml - * + * * We should be safe to assume that forks follow these conventions and do not mess * with this version number (Spigot, Paper and Tuinity do at least). */ return Stream.of( - Arguments.of("1.13.2-R0.1-SNAPSHOT", 1, 13, 2), - Arguments.of("1.13-R0.2-SNAPSHOT", 1, 13, 0), - Arguments.of("1.13.2-R0.1-SNAPSHOT", 1, 13, 2), - Arguments.of("1.13-pre7-R0.1-SNAPSHOT", 1, 13, 0), - Arguments.of("1.14-pre5-SNAPSHOT", 1, 14, 0), - Arguments.of("1.15-R0.1-SNAPSHOT", 1, 15, 0), - Arguments.of("1.16.5-R0.1-SNAPSHOT", 1, 16, 5), - Arguments.of("1.17-R0.1-SNAPSHOT", 1, 17, 0) + Arguments.of("1.13.2-R0.1-SNAPSHOT", 1, 13, 2), + Arguments.of("1.13-R0.2-SNAPSHOT", 1, 13, 0), + Arguments.of("1.13.2-R0.1-SNAPSHOT", 1, 13, 2), + Arguments.of("1.13-pre7-R0.1-SNAPSHOT", 1, 13, 0), + Arguments.of("1.14-pre5-SNAPSHOT", 1, 14, 0), + Arguments.of("1.15-R0.1-SNAPSHOT", 1, 15, 0), + Arguments.of("1.16.5-R0.1-SNAPSHOT", 1, 16, 5), + Arguments.of("1.17-R0.1-SNAPSHOT", 1, 17, 0) ); } diff --git a/src/test/java/com/gmail/nossr50/util/random/ProbabilityTest.java b/src/test/java/com/gmail/nossr50/util/random/ProbabilityTest.java index 0a128cd52..b9ebaac79 100644 --- a/src/test/java/com/gmail/nossr50/util/random/ProbabilityTest.java +++ b/src/test/java/com/gmail/nossr50/util/random/ProbabilityTest.java @@ -1,14 +1,15 @@ package com.gmail.nossr50.util.random; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.*; - class ProbabilityTest { private static Stream provideProbabilitiesForWithinExpectations() { @@ -48,6 +49,7 @@ class ProbabilityTest { Arguments.of(Probability.ofPercent(1000), 100) ); } + @Test void testAlwaysWinConstructor() { for (int i = 0; i < 100000; i++) { diff --git a/src/test/java/com/gmail/nossr50/util/random/ProbabilityTestUtils.java b/src/test/java/com/gmail/nossr50/util/random/ProbabilityTestUtils.java index 32dadfbbd..6a6efcd4a 100644 --- a/src/test/java/com/gmail/nossr50/util/random/ProbabilityTestUtils.java +++ b/src/test/java/com/gmail/nossr50/util/random/ProbabilityTestUtils.java @@ -3,7 +3,8 @@ package com.gmail.nossr50.util.random; import static org.junit.jupiter.api.Assertions.assertEquals; public class ProbabilityTestUtils { - public static void assertProbabilityExpectations(double expectedWinPercent, Probability probability) { + public static void assertProbabilityExpectations(double expectedWinPercent, + Probability probability) { double iterations = 2.0e7; //20 million double winCount = 0; for (int i = 0; i < iterations; i++) { @@ -15,7 +16,8 @@ public class ProbabilityTestUtils { double successPercent = (winCount / iterations) * 100; System.out.println("Wins: " + winCount); System.out.println("Fails: " + (iterations - winCount)); - System.out.println("Percentage succeeded: " + successPercent + ", Expected: " + expectedWinPercent); + System.out.println( + "Percentage succeeded: " + successPercent + ", Expected: " + expectedWinPercent); assertEquals(expectedWinPercent, successPercent, 0.035D); System.out.println("Variance is within tolerance levels!"); } diff --git a/src/test/java/com/gmail/nossr50/util/random/ProbabilityUtilTest.java b/src/test/java/com/gmail/nossr50/util/random/ProbabilityUtilTest.java index a78a3ffa7..324ffacb1 100644 --- a/src/test/java/com/gmail/nossr50/util/random/ProbabilityUtilTest.java +++ b/src/test/java/com/gmail/nossr50/util/random/ProbabilityUtilTest.java @@ -1,7 +1,23 @@ package com.gmail.nossr50.util.random; +import static com.gmail.nossr50.datatypes.skills.PrimarySkillType.ACROBATICS; +import static com.gmail.nossr50.datatypes.skills.PrimarySkillType.MINING; +import static com.gmail.nossr50.datatypes.skills.SubSkillType.ACROBATICS_DODGE; +import static com.gmail.nossr50.datatypes.skills.SubSkillType.AXES_ARMOR_IMPACT; +import static com.gmail.nossr50.datatypes.skills.SubSkillType.AXES_GREATER_IMPACT; +import static com.gmail.nossr50.datatypes.skills.SubSkillType.MINING_DOUBLE_DROPS; +import static com.gmail.nossr50.datatypes.skills.SubSkillType.TAMING_FAST_FOOD_SERVICE; +import static com.gmail.nossr50.datatypes.skills.SubSkillType.UNARMED_ARROW_DEFLECT; +import static com.gmail.nossr50.util.random.ProbabilityTestUtils.assertProbabilityExpectations; +import static com.gmail.nossr50.util.random.ProbabilityUtil.calculateCurrentSkillProbability; +import static java.util.logging.Logger.getLogger; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + import com.gmail.nossr50.MMOTestEnvironment; import com.gmail.nossr50.datatypes.skills.SubSkillType; +import java.util.logging.Logger; +import java.util.stream.Stream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -9,18 +25,6 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import java.util.logging.Logger; -import java.util.stream.Stream; - -import static com.gmail.nossr50.datatypes.skills.PrimarySkillType.ACROBATICS; -import static com.gmail.nossr50.datatypes.skills.PrimarySkillType.MINING; -import static com.gmail.nossr50.datatypes.skills.SubSkillType.*; -import static com.gmail.nossr50.util.random.ProbabilityTestUtils.assertProbabilityExpectations; -import static com.gmail.nossr50.util.random.ProbabilityUtil.calculateCurrentSkillProbability; -import static java.util.logging.Logger.getLogger; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.when; - class ProbabilityUtilTest extends MMOTestEnvironment { private static final Logger logger = getLogger(ProbabilityUtilTest.class.getName()); @@ -52,7 +56,8 @@ class ProbabilityUtilTest extends MMOTestEnvironment { @ParameterizedTest @MethodSource("staticChanceSkills") - void staticChanceSkillsShouldSucceedAsExpected(SubSkillType subSkillType, double expectedWinPercent) + void staticChanceSkillsShouldSucceedAsExpected(SubSkillType subSkillType, + double expectedWinPercent) throws InvalidStaticChance { Probability staticRandomChance = ProbabilityUtil.getStaticRandomChance(subSkillType); assertProbabilityExpectations(expectedWinPercent, staticRandomChance); @@ -64,8 +69,8 @@ class ProbabilityUtilTest extends MMOTestEnvironment { when(advancedConfig.getMaximumProbability(UNARMED_ARROW_DEFLECT)).thenReturn(20D); when(advancedConfig.getMaxBonusLevel(UNARMED_ARROW_DEFLECT)).thenReturn(0); - @SuppressWarnings("all") - final Probability probability = ProbabilityUtil.getSkillProbability(UNARMED_ARROW_DEFLECT, mmoPlayer); + @SuppressWarnings("all") final Probability probability = ProbabilityUtil.getSkillProbability( + UNARMED_ARROW_DEFLECT, mmoPlayer); assertEquals(0.2D, probability.getValue()); assertProbabilityExpectations(20, probability); } @@ -91,10 +96,12 @@ class ProbabilityUtilTest extends MMOTestEnvironment { @ParameterizedTest @MethodSource("provideSkillProbabilityTestData") - void testCalculateCurrentSkillProbability(double skillLevel, double floor, double ceiling, double maxBonusLevel, - double expectedValue) { + void testCalculateCurrentSkillProbability(double skillLevel, double floor, double ceiling, + double maxBonusLevel, + double expectedValue) { // When - final Probability probability = calculateCurrentSkillProbability(skillLevel, floor, ceiling, maxBonusLevel); + final Probability probability = calculateCurrentSkillProbability(skillLevel, floor, ceiling, + maxBonusLevel); // Then assertEquals(expectedValue, probability.getValue()); @@ -108,7 +115,8 @@ class ProbabilityUtilTest extends MMOTestEnvironment { mmoPlayer.modifySkill(ACROBATICS, 500); // When & Then - final String[] rngDisplayValues = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, ACROBATICS_DODGE); + final String[] rngDisplayValues = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + ACROBATICS_DODGE); assertEquals("10.00%", rngDisplayValues[0]); } @@ -120,7 +128,8 @@ class ProbabilityUtilTest extends MMOTestEnvironment { mmoPlayer.modifySkill(ACROBATICS, 1000); // When & then - final String[] rngDisplayValues = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, ACROBATICS_DODGE); + final String[] rngDisplayValues = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + ACROBATICS_DODGE); assertEquals("20.00%", rngDisplayValues[0]); } @@ -132,7 +141,8 @@ class ProbabilityUtilTest extends MMOTestEnvironment { mmoPlayer.modifySkill(ACROBATICS, 0); // When & then - final String[] rngDisplayValues = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, ACROBATICS_DODGE); + final String[] rngDisplayValues = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + ACROBATICS_DODGE); assertEquals("0.00%", rngDisplayValues[0]); } @@ -144,7 +154,8 @@ class ProbabilityUtilTest extends MMOTestEnvironment { mmoPlayer.modifySkill(MINING, 100); // When & Then - final String[] rngDisplayValues = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, MINING_DOUBLE_DROPS); + final String[] rngDisplayValues = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + MINING_DOUBLE_DROPS); assertEquals("10.00%", rngDisplayValues[0]); } @@ -156,7 +167,8 @@ class ProbabilityUtilTest extends MMOTestEnvironment { mmoPlayer.modifySkill(MINING, 500); // When & Then - final String[] rngDisplayValues = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, MINING_DOUBLE_DROPS); + final String[] rngDisplayValues = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + MINING_DOUBLE_DROPS); assertEquals("50.00%", rngDisplayValues[0]); } @@ -168,7 +180,8 @@ class ProbabilityUtilTest extends MMOTestEnvironment { mmoPlayer.modifySkill(MINING, 1000); // When & Then - final String[] rngDisplayValues = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, MINING_DOUBLE_DROPS); + final String[] rngDisplayValues = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, + MINING_DOUBLE_DROPS); assertEquals("100.00%", rngDisplayValues[0]); } diff --git a/src/test/java/com/gmail/nossr50/util/text/StringUtilsTest.java b/src/test/java/com/gmail/nossr50/util/text/StringUtilsTest.java index 5754c782f..1656229e7 100644 --- a/src/test/java/com/gmail/nossr50/util/text/StringUtilsTest.java +++ b/src/test/java/com/gmail/nossr50/util/text/StringUtilsTest.java @@ -1,13 +1,19 @@ package com.gmail.nossr50.util.text; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import com.gmail.nossr50.datatypes.skills.SuperAbilityType; import org.bukkit.Material; import org.bukkit.entity.EntityType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; - class StringUtilsTest { @BeforeEach @@ -17,20 +23,23 @@ class StringUtilsTest { } /** - * Utility method to clear all caches in StringUtils. - * Reflection is used since the caches are private. + * Utility method to clear all caches in StringUtils. Reflection is used since the caches are + * private. */ private void clearCaches() { try { - java.lang.reflect.Field entityCache = StringUtils.class.getDeclaredField("formattedEntityStrings"); + java.lang.reflect.Field entityCache = StringUtils.class.getDeclaredField( + "formattedEntityStrings"); entityCache.setAccessible(true); ((java.util.Map) entityCache.get(null)).clear(); - java.lang.reflect.Field superAbilityCache = StringUtils.class.getDeclaredField("formattedSuperAbilityStrings"); + java.lang.reflect.Field superAbilityCache = StringUtils.class.getDeclaredField( + "formattedSuperAbilityStrings"); superAbilityCache.setAccessible(true); ((java.util.Map) superAbilityCache.get(null)).clear(); - java.lang.reflect.Field materialCache = StringUtils.class.getDeclaredField("formattedMaterialStrings"); + java.lang.reflect.Field materialCache = StringUtils.class.getDeclaredField( + "formattedMaterialStrings"); materialCache.setAccessible(true); ((java.util.Map) materialCache.get(null)).clear(); } catch (NoSuchFieldException | IllegalAccessException e) { diff --git a/src/test/java/com/gmail/nossr50/util/text/TextUtilsTest.java b/src/test/java/com/gmail/nossr50/util/text/TextUtilsTest.java index c58157179..5f02eb356 100644 --- a/src/test/java/com/gmail/nossr50/util/text/TextUtilsTest.java +++ b/src/test/java/com/gmail/nossr50/util/text/TextUtilsTest.java @@ -6,13 +6,12 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** - * This Unit Test checks if Adventure was set up correctly and works as expected. - * Normally, we can rely on this to be the case. However sometimes our dependencies - * lack so far behind that things stop working correctly. - * This test ensures that basic functionality is guaranteed to work as we would expect. - * + * This Unit Test checks if Adventure was set up correctly and works as expected. Normally, we can + * rely on this to be the case. However sometimes our dependencies lack so far behind that things + * stop working correctly. This test ensures that basic functionality is guaranteed to work as we + * would expect. + *

* See https://github.com/mcMMO-Dev/mcMMO/pull/4446 - * */ class TextUtilsTest {