From 9b3c8a9df24184b8a1a64204b052a4ff690389d4 Mon Sep 17 00:00:00 2001 From: md678685 <1917406+md678685@users.noreply.github.com> Date: Sat, 3 Oct 2020 18:46:05 +0100 Subject: [PATCH] Reformat and fix Checkstyle violations --- .../AlternativeCommandsHandler.java | 20 +- .../earth2me/essentials/AsyncTeleport.java | 88 ++-- .../essentials/AsyncTimedTeleport.java | 20 +- .../src/com/earth2me/essentials/Backup.java | 12 +- .../earth2me/essentials/ChargeException.java | 1 - .../earth2me/essentials/CommandSource.java | 8 +- .../src/com/earth2me/essentials/Console.java | 46 +- .../com/earth2me/essentials/Enchantments.java | 62 ++- .../com/earth2me/essentials/Essentials.java | 190 ++++--- .../essentials/EssentialsBlockListener.java | 2 +- .../earth2me/essentials/EssentialsConf.java | 302 +++++------ .../essentials/EssentialsEntityListener.java | 46 +- .../essentials/EssentialsPlayerListener.java | 213 ++++---- .../essentials/EssentialsPluginListener.java | 5 +- .../essentials/EssentialsServerListener.java | 27 +- .../earth2me/essentials/EssentialsTimer.java | 23 +- .../essentials/EssentialsUpgrade.java | 313 +++++------ .../essentials/EssentialsUserConf.java | 5 +- .../com/earth2me/essentials/ExecuteTimer.java | 9 +- .../src/com/earth2me/essentials/I18n.java | 88 ++-- .../com/earth2me/essentials/IEssentials.java | 3 - .../essentials/IEssentialsModule.java | 1 - .../com/earth2me/essentials/ISettings.java | 19 +- .../src/com/earth2me/essentials/ITarget.java | 3 +- .../src/com/earth2me/essentials/IUser.java | 31 +- .../src/com/earth2me/essentials/Jails.java | 38 +- .../src/com/earth2me/essentials/Kit.java | 49 +- .../src/com/earth2me/essentials/Kits.java | 20 +- .../earth2me/essentials/LocationTarget.java | 5 +- .../com/earth2me/essentials/ManagedFile.java | 34 +- .../earth2me/essentials/MetaItemStack.java | 179 ++++--- .../src/com/earth2me/essentials/Mob.java | 102 ++-- .../com/earth2me/essentials/MobCompat.java | 226 ++++---- .../src/com/earth2me/essentials/MobData.java | 105 ++-- .../earth2me/essentials/PlayerExtension.java | 1 - .../com/earth2me/essentials/PlayerList.java | 33 +- .../com/earth2me/essentials/PlayerTarget.java | 5 +- .../src/com/earth2me/essentials/Potions.java | 11 +- .../earth2me/essentials/RandomTeleport.java | 71 +-- .../src/com/earth2me/essentials/Settings.java | 414 +++++++-------- .../src/com/earth2me/essentials/SpawnMob.java | 74 +-- .../essentials/TNTExplodeListener.java | 1 - .../src/com/earth2me/essentials/Teleport.java | 87 ++-- .../earth2me/essentials/TimedTeleport.java | 15 +- .../src/com/earth2me/essentials/Trade.java | 235 ++++----- .../src/com/earth2me/essentials/UUIDMap.java | 35 +- .../src/com/earth2me/essentials/User.java | 136 ++--- .../src/com/earth2me/essentials/UserData.java | 319 ++++++------ .../src/com/earth2me/essentials/UserMap.java | 88 ++-- .../src/com/earth2me/essentials/Warps.java | 63 ++- .../src/com/earth2me/essentials/Worth.java | 19 +- .../com/earth2me/essentials/api/Economy.java | 349 +++++-------- .../essentials/api/IAsyncTeleport.java | 83 ++- .../com/earth2me/essentials/api/II18n.java | 1 - .../com/earth2me/essentials/api/IItemDb.java | 13 +- .../com/earth2me/essentials/api/IJails.java | 17 +- .../com/earth2me/essentials/api/IReload.java | 1 - .../earth2me/essentials/api/ITeleport.java | 11 - .../com/earth2me/essentials/api/IWarps.java | 14 +- .../essentials/api/InvalidNameException.java | 3 +- .../essentials/api/InvalidWorldException.java | 1 - .../api/NoLoanPermittedException.java | 1 - .../api/UserDoesNotExistException.java | 5 +- .../essentials/commands/Commandafk.java | 19 +- .../essentials/commands/Commandback.java | 21 +- .../essentials/commands/Commandbackup.java | 1 - .../essentials/commands/Commandbalance.java | 5 +- .../commands/Commandbalancetop.java | 69 +-- .../essentials/commands/Commandban.java | 9 +- .../essentials/commands/Commandbanip.java | 13 +- .../essentials/commands/Commandbigtree.java | 5 +- .../essentials/commands/Commandbook.java | 19 +- .../essentials/commands/Commandbreak.java | 1 - .../essentials/commands/Commandbroadcast.java | 1 - .../commands/Commandbroadcastworld.java | 17 +- .../essentials/commands/Commandburn.java | 5 +- .../commands/Commandclearinventory.java | 125 ++--- .../Commandclearinventoryconfirmtoggle.java | 7 +- .../essentials/commands/Commandcompass.java | 3 +- .../essentials/commands/Commandcondense.java | 56 +- .../essentials/commands/Commandcreatekit.java | 38 +- .../commands/Commandcustomtext.java | 3 +- .../essentials/commands/Commanddelhome.java | 23 +- .../essentials/commands/Commanddeljail.java | 5 +- .../essentials/commands/Commanddelkit.java | 1 - .../essentials/commands/Commanddelwarp.java | 1 - .../essentials/commands/Commanddepth.java | 3 +- .../essentials/commands/Commanddisposal.java | 2 +- .../essentials/commands/Commandeco.java | 34 +- .../essentials/commands/Commandeditsign.java | 22 +- .../essentials/commands/Commandenchant.java | 21 +- .../commands/Commandenderchest.java | 2 +- .../commands/Commandessentials.java | 89 ++-- .../essentials/commands/Commandexp.java | 77 ++- .../essentials/commands/Commandext.java | 3 +- .../essentials/commands/Commandfeed.java | 5 +- .../essentials/commands/Commandfireball.java | 48 +- .../essentials/commands/Commandfirework.java | 38 +- .../essentials/commands/Commandfly.java | 8 +- .../essentials/commands/Commandgamemode.java | 14 +- .../essentials/commands/Commandgc.java | 25 +- .../essentials/commands/Commandgetpos.java | 3 +- .../essentials/commands/Commandgive.java | 19 +- .../essentials/commands/Commandgod.java | 3 +- .../essentials/commands/Commandhat.java | 19 +- .../essentials/commands/Commandheal.java | 7 +- .../essentials/commands/Commandhelp.java | 11 +- .../essentials/commands/Commandhelpop.java | 3 +- .../essentials/commands/Commandhome.java | 35 +- .../essentials/commands/Commandignore.java | 13 +- .../essentials/commands/Commandinfo.java | 1 - .../essentials/commands/Commandinvsee.java | 4 +- .../essentials/commands/Commanditem.java | 8 +- .../essentials/commands/Commanditemdb.java | 9 +- .../essentials/commands/Commanditemlore.java | 20 +- .../essentials/commands/Commanditemname.java | 8 +- .../essentials/commands/Commandjails.java | 1 - .../essentials/commands/Commandjump.java | 6 +- .../essentials/commands/Commandkick.java | 5 +- .../essentials/commands/Commandkickall.java | 3 +- .../essentials/commands/Commandkill.java | 3 +- .../essentials/commands/Commandkit.java | 13 +- .../commands/Commandkittycannon.java | 40 +- .../essentials/commands/Commandlightning.java | 3 +- .../essentials/commands/Commandlist.java | 32 +- .../essentials/commands/Commandmail.java | 66 ++- .../essentials/commands/Commandme.java | 23 +- .../essentials/commands/Commandmore.java | 7 +- .../essentials/commands/Commandmotd.java | 1 - .../essentials/commands/Commandmsg.java | 18 +- .../essentials/commands/Commandmsgtoggle.java | 3 +- .../essentials/commands/Commandmute.java | 19 +- .../essentials/commands/Commandnear.java | 21 +- .../essentials/commands/Commandnick.java | 11 +- .../essentials/commands/Commandnuke.java | 7 +- .../essentials/commands/Commandpay.java | 15 +- .../commands/Commandpayconfirmtoggle.java | 2 +- .../essentials/commands/Commandpaytoggle.java | 6 +- .../essentials/commands/Commandpotion.java | 28 +- .../essentials/commands/Commandpowertool.java | 27 +- .../commands/Commandpowertooltoggle.java | 1 - .../essentials/commands/Commandptime.java | 26 +- .../essentials/commands/Commandpweather.java | 22 +- .../essentials/commands/Commandr.java | 7 +- .../essentials/commands/Commandrealname.java | 5 +- .../essentials/commands/Commandrecipe.java | 25 +- .../essentials/commands/Commandremove.java | 74 ++- .../essentials/commands/Commandrepair.java | 17 +- .../essentials/commands/Commandrest.java | 2 +- .../essentials/commands/Commandrtoggle.java | 6 +- .../essentials/commands/Commandrules.java | 1 - .../essentials/commands/Commandseen.java | 51 +- .../essentials/commands/Commandsell.java | 27 +- .../essentials/commands/Commandsethome.java | 5 +- .../essentials/commands/Commandsetjail.java | 1 - .../essentials/commands/Commandsettpr.java | 7 +- .../essentials/commands/Commandsetwarp.java | 3 +- .../essentials/commands/Commandsetworth.java | 5 +- .../essentials/commands/Commandshowkit.java | 2 +- .../essentials/commands/Commandskull.java | 10 +- .../essentials/commands/Commandsocialspy.java | 3 +- .../essentials/commands/Commandspawner.java | 11 +- .../essentials/commands/Commandspawnmob.java | 11 +- .../essentials/commands/Commandspeed.java | 25 +- .../essentials/commands/Commandsudo.java | 10 +- .../essentials/commands/Commandsuicide.java | 5 +- .../essentials/commands/Commandtempban.java | 5 +- .../essentials/commands/Commandtempbanip.java | 14 +- .../essentials/commands/Commandthunder.java | 5 +- .../essentials/commands/Commandtime.java | 33 +- .../commands/Commandtogglejail.java | 9 +- .../essentials/commands/Commandtop.java | 9 +- .../essentials/commands/Commandtp.java | 9 +- .../essentials/commands/Commandtpa.java | 13 +- .../essentials/commands/Commandtpaall.java | 9 +- .../essentials/commands/Commandtpacancel.java | 14 +- .../essentials/commands/Commandtpaccept.java | 9 +- .../essentials/commands/Commandtpahere.java | 5 +- .../essentials/commands/Commandtpall.java | 7 +- .../essentials/commands/Commandtpauto.java | 3 +- .../essentials/commands/Commandtpdeny.java | 1 - .../essentials/commands/Commandtphere.java | 3 +- .../essentials/commands/Commandtpo.java | 5 +- .../essentials/commands/Commandtpoffline.java | 22 +- .../essentials/commands/Commandtpohere.java | 3 +- .../essentials/commands/Commandtppos.java | 21 +- .../essentials/commands/Commandtpr.java | 11 +- .../essentials/commands/Commandtptoggle.java | 3 +- .../essentials/commands/Commandtree.java | 8 +- .../essentials/commands/Commandunban.java | 3 +- .../essentials/commands/Commandunbanip.java | 6 +- .../essentials/commands/Commandunlimited.java | 9 +- .../essentials/commands/Commandvanish.java | 7 +- .../essentials/commands/Commandwarp.java | 3 +- .../essentials/commands/Commandweather.java | 9 +- .../essentials/commands/Commandwhois.java | 21 +- .../essentials/commands/Commandworkbench.java | 3 +- .../essentials/commands/Commandworld.java | 13 +- .../essentials/commands/Commandworth.java | 23 +- .../commands/EssentialsCommand.java | 124 +++-- .../commands/EssentialsLoopCommand.java | 31 +- .../commands/EssentialsToggleCommand.java | 21 +- .../commands/IEssentialsCommand.java | 1 - .../commands/NoChargeException.java | 1 - .../commands/NotEnoughArgumentsException.java | 1 - .../commands/PlayerExemptException.java | 2 +- .../commands/QuietAbortException.java | 3 +- .../commands/WarpNotFoundException.java | 2 +- .../essentials/craftbukkit/BanLookup.java | 15 +- .../essentials/craftbukkit/FakeWorld.java | 294 ++++++----- .../craftbukkit/InventoryWorkaround.java | 65 ++- .../essentials/craftbukkit/SetExpFix.java | 11 +- .../essentials/items/AbstractItemDb.java | 143 ++--- .../essentials/items/CustomItemResolver.java | 28 +- .../earth2me/essentials/items/FlatItemDb.java | 88 ++-- .../essentials/items/LegacyItemDb.java | 62 +-- .../messaging/IMessageRecipient.java | 33 +- .../messaging/SimpleMessageRecipient.java | 47 +- .../earth2me/essentials/metrics/Metrics.java | 377 +++++++------- .../essentials/metrics/MetricsWrapper.java | 60 +-- .../essentials/perm/IPermissionsHandler.java | 1 - .../essentials/perm/PermissionsHandler.java | 37 +- .../perm/impl/AbstractVaultHandler.java | 20 +- .../perm/impl/ConfigPermissionsHandler.java | 1 - .../perm/impl/LuckPermsHandler.java | 10 +- .../perm/impl/ModernVaultHandler.java | 3 +- .../perm/impl/SuperpermsHandler.java | 12 +- .../essentials/register/payment/Method.java | 28 +- .../essentials/register/payment/Methods.java | 63 ++- .../register/payment/methods/VaultEco.java | 107 ++-- .../earth2me/essentials/settings/Jails.java | 7 +- .../earth2me/essentials/settings/Spawns.java | 6 +- .../essentials/signs/EssentialsSign.java | 174 ++++--- .../essentials/signs/SignBalance.java | 1 - .../essentials/signs/SignBlockListener.java | 43 +- .../earth2me/essentials/signs/SignBuy.java | 11 +- .../essentials/signs/SignDisposal.java | 3 +- .../essentials/signs/SignEnchant.java | 13 +- .../essentials/signs/SignEntityListener.java | 7 +- .../essentials/signs/SignException.java | 1 - .../earth2me/essentials/signs/SignFree.java | 7 +- .../essentials/signs/SignGameMode.java | 3 +- .../earth2me/essentials/signs/SignHeal.java | 1 - .../earth2me/essentials/signs/SignInfo.java | 7 +- .../earth2me/essentials/signs/SignKit.java | 9 +- .../earth2me/essentials/signs/SignMail.java | 3 +- .../essentials/signs/SignPlayerListener.java | 8 +- .../essentials/signs/SignProtection.java | 32 +- .../earth2me/essentials/signs/SignRepair.java | 5 +- .../earth2me/essentials/signs/SignSell.java | 11 +- .../essentials/signs/SignSpawnmob.java | 11 +- .../earth2me/essentials/signs/SignTime.java | 1 - .../earth2me/essentials/signs/SignTrade.java | 21 +- .../earth2me/essentials/signs/SignWarp.java | 5 +- .../essentials/signs/SignWeather.java | 1 - .../AbstractDelayedYamlFileReader.java | 9 +- .../AbstractDelayedYamlFileWriter.java | 5 +- .../storage/AsyncStorageObjectHolder.java | 11 +- .../essentials/storage/BukkitConstructor.java | 38 +- .../earth2me/essentials/storage/Comment.java | 14 +- .../essentials/storage/EnchantmentLevel.java | 3 +- .../storage/IStorageObjectHolder.java | 1 - .../essentials/storage/IStorageReader.java | 1 - .../essentials/storage/IStorageWriter.java | 1 - .../earth2me/essentials/storage/ListType.java | 5 +- .../essentials/storage/MapKeyType.java | 7 +- .../essentials/storage/MapValueType.java | 7 +- .../storage/ObjectLoadException.java | 3 +- .../essentials/storage/StorageObject.java | 1 - .../essentials/storage/YamlStorageReader.java | 11 +- .../essentials/storage/YamlStorageWriter.java | 17 +- .../essentials/textreader/BookInput.java | 25 +- .../essentials/textreader/BookPager.java | 33 +- .../essentials/textreader/HelpInput.java | 21 +- .../earth2me/essentials/textreader/IText.java | 1 - .../textreader/KeywordReplacer.java | 135 ++--- .../textreader/SimpleTextInput.java | 7 +- .../textreader/SimpleTextPager.java | 4 +- .../essentials/textreader/TextInput.java | 29 +- .../essentials/textreader/TextPager.java | 23 +- .../earth2me/essentials/utils/DateUtil.java | 42 +- .../essentials/utils/DescParseTickFormat.java | 28 +- .../earth2me/essentials/utils/EnumUtil.java | 38 +- .../earth2me/essentials/utils/FloatUtil.java | 12 +- .../earth2me/essentials/utils/FormatUtil.java | 87 ++-- .../essentials/utils/LocationUtil.java | 91 ++-- .../essentials/utils/MaterialUtil.java | 51 +- .../earth2me/essentials/utils/NumberUtil.java | 17 +- .../earth2me/essentials/utils/StringUtil.java | 32 +- .../essentials/utils/VersionUtil.java | 45 +- Essentials/src/net/ess3/api/Economy.java | 1 - Essentials/src/net/ess3/api/II18n.java | 1 - Essentials/src/net/ess3/api/IItemDb.java | 15 +- Essentials/src/net/ess3/api/IJails.java | 1 - Essentials/src/net/ess3/api/IReload.java | 1 - Essentials/src/net/ess3/api/ISettings.java | 1 - Essentials/src/net/ess3/api/ITeleport.java | 1 - Essentials/src/net/ess3/api/IUser.java | 1 - Essentials/src/net/ess3/api/IWarps.java | 1 - .../net/ess3/api/InvalidNameException.java | 3 +- .../net/ess3/api/InvalidWorldException.java | 1 - .../src/net/ess3/api/MaxMoneyException.java | 1 - .../ess3/api/NoLoanPermittedException.java | 1 - Essentials/src/net/ess3/api/PluginKey.java | 20 +- .../ess3/api/UserDoesNotExistException.java | 3 +- .../ess3/api/events/AfkStatusChangeEvent.java | 7 +- .../ess3/api/events/FlyStatusChangeEvent.java | 2 +- .../ess3/api/events/GodStatusChangeEvent.java | 5 +- .../api/events/IgnoreStatusChangeEvent.java | 2 +- .../api/events/JailStatusChangeEvent.java | 5 +- .../net/ess3/api/events/KitClaimEvent.java | 22 +- .../ess3/api/events/LocalChatSpyEvent.java | 20 +- .../api/events/MuteStatusChangeEvent.java | 9 +- .../net/ess3/api/events/NickChangeEvent.java | 5 +- .../events/PrivateMessagePreSendEvent.java | 19 +- .../api/events/PrivateMessageSentEvent.java | 20 +- .../net/ess3/api/events/SignBreakEvent.java | 3 +- .../net/ess3/api/events/SignCreateEvent.java | 3 +- .../src/net/ess3/api/events/SignEvent.java | 17 +- .../ess3/api/events/SignInteractEvent.java | 3 +- .../net/ess3/api/events/StateChangeEvent.java | 19 +- .../ess3/api/events/StatusChangeEvent.java | 7 +- .../net/ess3/api/events/TPARequestEvent.java | 22 +- .../api/events/UserBalanceUpdateEvent.java | 18 +- .../api/events/UserRandomTeleportEvent.java | 23 +- .../api/events/UserTeleportHomeEvent.java | 18 +- .../net/ess3/api/events/UserWarpEvent.java | 28 +- .../api/events/VanishStatusChangeEvent.java | 4 +- .../api/events/teleport/PreTeleportEvent.java | 2 +- .../api/events/teleport/TeleportEvent.java | 6 +- .../events/teleport/TeleportWarmupEvent.java | 6 +- .../com/earth2me/essentials/EconomyTest.java | 58 +-- .../com/earth2me/essentials/FakeServer.java | 427 ++++++++------- .../earth2me/essentials/MessagingTest.java | 40 +- .../com/earth2me/essentials/StorageTest.java | 17 +- .../com/earth2me/essentials/ToggleTest.java | 87 ++-- .../com/earth2me/essentials/UserTest.java | 25 +- .../com/earth2me/essentials/UtilTest.java | 24 +- .../essentials/utils/FormatUtilTest.java | 15 +- .../essentials/antibuild/AntiBuildConfig.java | 1 - .../antibuild/EssentialsAntiBuild.java | 10 +- .../EssentialsAntiBuildListener.java | 39 +- .../antibuild/EssentialsConnect.java | 9 +- .../essentials/antibuild/IAntiBuild.java | 1 - .../earth2me/essentials/chat/ChatStore.java | 3 +- .../essentials/chat/EssentialsChat.java | 2 - .../essentials/chat/EssentialsChatPlayer.java | 5 +- .../EssentialsChatPlayerListenerHighest.java | 1 - .../EssentialsChatPlayerListenerLowest.java | 15 +- .../EssentialsChatPlayerListenerNormal.java | 17 +- .../essentials/geoip/EssentialsGeoIP.java | 13 +- .../geoip/EssentialsGeoIPPlayerListener.java | 97 ++-- .../essentials/protect/EmergencyListener.java | 3 +- .../essentials/protect/EssentialsConnect.java | 9 +- .../essentials/protect/EssentialsProtect.java | 8 +- .../EssentialsProtectBlockListener.java | 18 +- ...ssentialsProtectBlockListener_1_16_R1.java | 6 +- .../EssentialsProtectEntityListener.java | 13 +- ...ntialsProtectEntityListener_1_13_2_R1.java | 3 - ...sentialsProtectEntityListener_1_14_R1.java | 5 +- .../EssentialsProtectWeatherListener.java | 1 - .../earth2me/essentials/protect/IProtect.java | 1 - .../essentials/protect/ProtectConfig.java | 1 - .../essentials/spawn/Commandsetspawn.java | 3 +- .../essentials/spawn/Commandspawn.java | 11 +- .../essentials/spawn/EssentialsSpawn.java | 13 +- .../spawn/EssentialsSpawnPlayerListener.java | 18 +- .../essentials/spawn/IEssentialsSpawn.java | 4 - .../essentials/spawn/SpawnStorage.java | 9 +- .../essentials/xmpp/Commandsetxmpp.java | 3 +- .../earth2me/essentials/xmpp/Commandxmpp.java | 1 - .../essentials/xmpp/Commandxmppspy.java | 7 +- .../essentials/xmpp/EssentialsXMPP.java | 16 +- .../xmpp/EssentialsXMPPPlayerListener.java | 7 +- .../essentials/xmpp/IEssentialsXMPP.java | 1 - .../earth2me/essentials/xmpp/UserManager.java | 17 +- .../earth2me/essentials/xmpp/XMPPManager.java | 52 +- .../earth2me/essentials/OfflinePlayer.java | 492 +++++++++--------- .../net/ess3/provider/ProviderListener.java | 4 +- .../ess3/provider/SpawnerItemProvider.java | 34 +- .../providers/BasePotionDataProvider.java | 54 +- .../BlockMetaSpawnerItemProvider.java | 12 +- .../providers/BukkitSpawnerBlockProvider.java | 4 +- .../providers/FlatSpawnEggProvider.java | 8 +- .../providers/LegacyPotionMetaProvider.java | 4 +- .../providers/LegacySpawnEggProvider.java | 6 +- .../src/net/ess3/nms/refl/ReflUtil.java | 113 ++-- .../src/net/ess3/nms/refl/SpawnEggRefl.java | 108 ++-- .../providers/ReflServerStateProvider.java | 8 +- .../refl/providers/ReflSpawnEggProvider.java | 8 +- .../providers/ReflSpawnerBlockProvider.java | 30 +- .../providers/PaperRecipeBookListener.java | 4 +- 392 files changed, 5889 insertions(+), 5862 deletions(-) diff --git a/Essentials/src/com/earth2me/essentials/AlternativeCommandsHandler.java b/Essentials/src/com/earth2me/essentials/AlternativeCommandsHandler.java index 452ee46a5..91e7d0329 100644 --- a/Essentials/src/com/earth2me/essentials/AlternativeCommandsHandler.java +++ b/Essentials/src/com/earth2me/essentials/AlternativeCommandsHandler.java @@ -6,11 +6,15 @@ import org.bukkit.command.PluginCommand; import org.bukkit.command.PluginCommandYamlParser; import org.bukkit.plugin.Plugin; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; - public class AlternativeCommandsHandler { private static final Logger LOGGER = Logger.getLogger("Essentials"); private final transient Map> altcommands = new HashMap<>(); @@ -19,7 +23,7 @@ public class AlternativeCommandsHandler { public AlternativeCommandsHandler(final IEssentials ess) { this.ess = ess; - for (Plugin plugin : ess.getServer().getPluginManager().getPlugins()) { + for (final Plugin plugin : ess.getServer().getPluginManager().getPlugins()) { if (plugin.isEnabled()) { addPlugin(plugin); } @@ -33,7 +37,7 @@ public class AlternativeCommandsHandler { final List commands = PluginCommandYamlParser.parse(plugin); final String pluginName = plugin.getDescription().getName().toLowerCase(Locale.ENGLISH); - for (Command command : commands) { + for (final Command command : commands) { final PluginCommand pc = (PluginCommand) command; final List labels = new ArrayList<>(pc.getAliases()); labels.add(pc.getName()); @@ -45,10 +49,10 @@ public class AlternativeCommandsHandler { if (reg == null || !reg.getPlugin().equals(plugin)) { continue; } - for (String label : labels) { - List plugincommands = altcommands.computeIfAbsent(label.toLowerCase(Locale.ENGLISH), k -> new ArrayList<>()); + for (final String label : labels) { + final List plugincommands = altcommands.computeIfAbsent(label.toLowerCase(Locale.ENGLISH), k -> new ArrayList<>()); boolean found = false; - for (PluginCommand pc2 : plugincommands) { + for (final PluginCommand pc2 : plugincommands) { if (pc2.getPlugin().equals(plugin)) { found = true; break; @@ -81,7 +85,7 @@ public class AlternativeCommandsHandler { return commands.get(0); } // return the first command that is not an alias - for (PluginCommand command : commands) { + for (final PluginCommand command : commands) { if (command.getName().equalsIgnoreCase(label)) { return command; } diff --git a/Essentials/src/com/earth2me/essentials/AsyncTeleport.java b/Essentials/src/com/earth2me/essentials/AsyncTeleport.java index 860e56036..03a7f4426 100644 --- a/Essentials/src/com/earth2me/essentials/AsyncTeleport.java +++ b/Essentials/src/com/earth2me/essentials/AsyncTeleport.java @@ -25,7 +25,6 @@ import java.util.concurrent.ExecutionException; import static com.earth2me.essentials.I18n.tl; - public class AsyncTeleport implements IAsyncTeleport { private final IUser teleportOwner; private final IEssentials ess; @@ -33,30 +32,24 @@ public class AsyncTeleport implements IAsyncTeleport { private TeleportType tpType; - public AsyncTeleport(IUser user, IEssentials ess) { + public AsyncTeleport(final IUser user, final IEssentials ess) { this.teleportOwner = user; this.ess = ess; tpType = TeleportType.NORMAL; } - public enum TeleportType { - TPA, - BACK, - NORMAL - } - - public void cooldown(boolean check) throws Throwable { - CompletableFuture exceptionFuture = new CompletableFuture<>(); + public void cooldown(final boolean check) throws Throwable { + final CompletableFuture exceptionFuture = new CompletableFuture<>(); if (cooldown(check, exceptionFuture)) { try { exceptionFuture.get(); - } catch (ExecutionException e) { + } catch (final ExecutionException e) { throw e.getCause(); } } } - public boolean cooldown(boolean check, CompletableFuture future) { + public boolean cooldown(final boolean check, final CompletableFuture future) { final Calendar time = new GregorianCalendar(); if (teleportOwner.getLastTeleportTimestamp() > 0) { // Take the current time, and remove the delay from it. @@ -93,7 +86,7 @@ public class AsyncTeleport implements IAsyncTeleport { private boolean cooldownApplies() { boolean applies = true; - String globalBypassPerm = "essentials.teleport.cooldown.bypass"; + final String globalBypassPerm = "essentials.teleport.cooldown.bypass"; switch (tpType) { case NORMAL: applies = !teleportOwner.isAuthorized(globalBypassPerm); @@ -111,15 +104,14 @@ public class AsyncTeleport implements IAsyncTeleport { } private void warnUser(final IUser user, final double delay) { - Calendar c = new GregorianCalendar(); + final Calendar c = new GregorianCalendar(); c.add(Calendar.SECOND, (int) delay); c.add(Calendar.MILLISECOND, (int) ((delay * 1000.0) % 1000.0)); user.sendMessage(tl("dontMoveMessage", DateUtil.formatDateDiff(c.getTimeInMillis()))); } - @Override - public void now(Location loc, boolean cooldown, TeleportCause cause, CompletableFuture future) { + public void now(final Location loc, final boolean cooldown, final TeleportCause cause, final CompletableFuture future) { if (cooldown && cooldown(false, future)) { return; } @@ -128,7 +120,7 @@ public class AsyncTeleport implements IAsyncTeleport { } @Override - public void now(Player entity, boolean cooldown, TeleportCause cause, CompletableFuture future) { + public void now(final Player entity, final boolean cooldown, final TeleportCause cause, final CompletableFuture future) { if (cooldown && cooldown(false, future)) { future.complete(false); return; @@ -142,12 +134,12 @@ public class AsyncTeleport implements IAsyncTeleport { }); } - private void runOnMain(Runnable runnable) throws ExecutionException, InterruptedException { + private void runOnMain(final Runnable runnable) throws ExecutionException, InterruptedException { if (Bukkit.isPrimaryThread()) { runnable.run(); return; } - CompletableFuture taskLock = new CompletableFuture<>(); + final CompletableFuture taskLock = new CompletableFuture<>(); Bukkit.getScheduler().runTask(ess, () -> { runnable.run(); taskLock.complete(new Object()); @@ -155,10 +147,10 @@ public class AsyncTeleport implements IAsyncTeleport { taskLock.get(); } - protected void nowAsync(IUser teleportee, ITarget target, TeleportCause cause, CompletableFuture future) { + protected void nowAsync(final IUser teleportee, final ITarget target, final TeleportCause cause, final CompletableFuture future) { cancel(false); - PreTeleportEvent event = new PreTeleportEvent(teleportee, cause, target); + final PreTeleportEvent event = new PreTeleportEvent(teleportee, cause, target); Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { return; @@ -173,7 +165,7 @@ public class AsyncTeleport implements IAsyncTeleport { try { runOnMain(() -> teleportee.getBase().eject()); //EntityDismountEvent requires a sync context. - } catch (ExecutionException | InterruptedException e) { + } catch (final ExecutionException | InterruptedException e) { future.completeExceptionally(e); return; } @@ -195,7 +187,7 @@ public class AsyncTeleport implements IAsyncTeleport { try { //There's a chance the safer location is outside the loaded chunk so still teleport async here. PaperLib.teleportAsync(teleportee.getBase(), LocationUtil.getSafeDestination(ess, teleportee, loc), cause); - } catch (Exception e) { + } catch (final Exception e) { future.completeExceptionally(e); return; } @@ -221,24 +213,24 @@ public class AsyncTeleport implements IAsyncTeleport { } @Override - public void teleport(Location loc, Trade chargeFor, TeleportCause cause, CompletableFuture future) { + public void teleport(final Location loc, final Trade chargeFor, final TeleportCause cause, final CompletableFuture future) { teleport(teleportOwner, new LocationTarget(loc), chargeFor, cause, future); } @Override - public void teleport(Player entity, Trade chargeFor, TeleportCause cause, CompletableFuture future) { + public void teleport(final Player entity, final Trade chargeFor, final TeleportCause cause, final CompletableFuture future) { teleportOwner.sendMessage(tl("teleportToPlayer", entity.getDisplayName())); teleport(teleportOwner, new PlayerTarget(entity), chargeFor, cause, future); } @Override - public void teleportPlayer(IUser otherUser, Location loc, Trade chargeFor, TeleportCause cause, CompletableFuture future) { + public void teleportPlayer(final IUser otherUser, final Location loc, final Trade chargeFor, final TeleportCause cause, final CompletableFuture future) { teleport(otherUser, new LocationTarget(loc), chargeFor, cause, future); } @Override - public void teleportPlayer(IUser otherUser, Player entity, Trade chargeFor, TeleportCause cause, CompletableFuture future) { - ITarget target = new PlayerTarget(entity); + public void teleportPlayer(final IUser otherUser, final Player entity, final Trade chargeFor, final TeleportCause cause, final CompletableFuture future) { + final ITarget target = new PlayerTarget(entity); teleport(otherUser, target, chargeFor, cause, future); future.thenAccept(success -> { if (success) { @@ -248,10 +240,10 @@ public class AsyncTeleport implements IAsyncTeleport { }); } - private void teleport(IUser teleportee, ITarget target, Trade chargeFor, TeleportCause cause, CompletableFuture future) { + private void teleport(final IUser teleportee, final ITarget target, final Trade chargeFor, final TeleportCause cause, final CompletableFuture future) { double delay = ess.getSettings().getTeleportDelay(); - TeleportWarmupEvent event = new TeleportWarmupEvent(teleportee, cause, target, delay); + final TeleportWarmupEvent event = new TeleportWarmupEvent(teleportee, cause, target, delay); Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { return; @@ -295,10 +287,10 @@ public class AsyncTeleport implements IAsyncTeleport { initTimer((long) (delay * 1000.0), teleportee, target, cashCharge, cause, false); } - private void teleportOther(IUser teleporter, IUser teleportee, ITarget target, Trade chargeFor, TeleportCause cause, CompletableFuture future) { + private void teleportOther(final IUser teleporter, final IUser teleportee, final ITarget target, final Trade chargeFor, final TeleportCause cause, final CompletableFuture future) { double delay = ess.getSettings().getTeleportDelay(); - TeleportWarmupEvent event = new TeleportWarmupEvent(teleportee, cause, target, delay); + final TeleportWarmupEvent event = new TeleportWarmupEvent(teleportee, cause, target, delay); Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { return; @@ -347,10 +339,10 @@ public class AsyncTeleport implements IAsyncTeleport { } @Override - public void respawn(Trade chargeFor, TeleportCause cause, CompletableFuture future) { + public void respawn(final Trade chargeFor, final TeleportCause cause, final CompletableFuture future) { double delay = ess.getSettings().getTeleportDelay(); - TeleportWarmupEvent event = new TeleportWarmupEvent(teleportOwner, cause, null, delay); + final TeleportWarmupEvent event = new TeleportWarmupEvent(teleportOwner, cause, null, delay); Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { return; @@ -382,7 +374,7 @@ public class AsyncTeleport implements IAsyncTeleport { initTimer((long) (delay * 1000.0), teleportOwner, null, chargeFor, cause, true); } - void respawnNow(IUser teleportee, TeleportCause cause, CompletableFuture future) { + void respawnNow(final IUser teleportee, final TeleportCause cause, final CompletableFuture future) { final Player player = teleportee.getBase(); PaperLib.getBedSpawnLocationAsync(player, true).thenAccept(location -> { if (location != null) { @@ -399,18 +391,18 @@ public class AsyncTeleport implements IAsyncTeleport { } @Override - public void warp(IUser otherUser, String warp, Trade chargeFor, TeleportCause cause, CompletableFuture future) { - UserWarpEvent event = new UserWarpEvent(otherUser, warp, chargeFor); + public void warp(final IUser otherUser, String warp, final Trade chargeFor, final TeleportCause cause, final CompletableFuture future) { + final UserWarpEvent event = new UserWarpEvent(otherUser, warp, chargeFor); Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { return; } warp = event.getWarp(); - Location loc; + final Location loc; try { loc = ess.getWarps().getWarp(warp); - } catch (WarpNotFoundException | InvalidWorldException e) { + } catch (final WarpNotFoundException | InvalidWorldException e) { future.completeExceptionally(e); return; } @@ -422,12 +414,12 @@ public class AsyncTeleport implements IAsyncTeleport { } @Override - public void back(Trade chargeFor, CompletableFuture future) { + public void back(final Trade chargeFor, final CompletableFuture future) { back(teleportOwner, chargeFor, future); } @Override - public void back(IUser teleporter, Trade chargeFor, CompletableFuture future) { + public void back(final IUser teleporter, final Trade chargeFor, final CompletableFuture future) { tpType = TeleportType.BACK; final Location loc = teleportOwner.getLastLocation(); teleportOwner.sendMessage(tl("backUsageMsg", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); @@ -435,23 +427,29 @@ public class AsyncTeleport implements IAsyncTeleport { } @Override - public void back(CompletableFuture future) { + public void back(final CompletableFuture future) { nowAsync(teleportOwner, new LocationTarget(teleportOwner.getLastLocation()), TeleportCause.COMMAND, future); } - public void setTpType(TeleportType tpType) { + public void setTpType(final TeleportType tpType) { this.tpType = tpType; } //If we need to cancelTimer a pending teleportPlayer call this method - private void cancel(boolean notifyUser) { + private void cancel(final boolean notifyUser) { if (timedTeleport != null) { timedTeleport.cancelTimer(notifyUser); timedTeleport = null; } } - private void initTimer(long delay, IUser teleportUser, ITarget target, Trade chargeFor, TeleportCause cause, boolean respawn) { + private void initTimer(final long delay, final IUser teleportUser, final ITarget target, final Trade chargeFor, final TeleportCause cause, final boolean respawn) { timedTeleport = new AsyncTimedTeleport(teleportOwner, ess, this, delay, teleportUser, target, chargeFor, cause, respawn); } + + public enum TeleportType { + TPA, + BACK, + NORMAL + } } diff --git a/Essentials/src/com/earth2me/essentials/AsyncTimedTeleport.java b/Essentials/src/com/earth2me/essentials/AsyncTimedTeleport.java index 86c91c057..260625e86 100644 --- a/Essentials/src/com/earth2me/essentials/AsyncTimedTeleport.java +++ b/Essentials/src/com/earth2me/essentials/AsyncTimedTeleport.java @@ -10,17 +10,14 @@ import java.util.concurrent.CompletableFuture; import static com.earth2me.essentials.I18n.tl; - public class AsyncTimedTeleport implements Runnable { private static final double MOVE_CONSTANT = 0.3; private final IUser teleportOwner; private final IEssentials ess; private final AsyncTeleport teleport; private final UUID timer_teleportee; - private int timer_task; private final long timer_started; // time this task was initiated private final long timer_delay; // how long to delay the teleportPlayer - private double timer_health; // note that I initially stored a clone of the location for reference, but... // when comparing locations, I got incorrect mismatches (rounding errors, looked like) // so, the X/Y/Z values are stored instead and rounded off @@ -32,8 +29,10 @@ public class AsyncTimedTeleport implements Runnable { private final boolean timer_canMove; private final Trade timer_chargeFor; private final TeleportCause timer_cause; + private int timer_task; + private double timer_health; - AsyncTimedTeleport(IUser user, IEssentials ess, AsyncTeleport teleport, long delay, IUser teleportUser, ITarget target, Trade chargeFor, TeleportCause cause, boolean respawn) { + AsyncTimedTeleport(final IUser user, final IEssentials ess, final AsyncTeleport teleport, final long delay, final IUser teleportUser, final ITarget target, final Trade chargeFor, final TeleportCause cause, final boolean respawn) { this.teleportOwner = user; this.ess = ess; this.teleport = teleport; @@ -84,12 +83,12 @@ public class AsyncTimedTeleport implements Runnable { @Override public void run() { - timer_health = teleportUser.getBase().getHealth(); // in case user healed, then later gets injured + timer_health = teleportUser.getBase().getHealth(); // in case user healed, then later gets injured final long now = System.currentTimeMillis(); if (now > timer_started + timer_delay) { try { teleport.cooldown(false); - } catch (Throwable ex) { + } catch (final Throwable ex) { teleportOwner.sendMessage(tl("cooldownWithMessage", ex.getMessage())); if (teleportOwner != teleportUser) { teleportUser.sendMessage(tl("cooldownWithMessage", ex.getMessage())); @@ -99,7 +98,7 @@ public class AsyncTimedTeleport implements Runnable { cancelTimer(false); teleportUser.sendMessage(tl("teleportationCommencing")); - CompletableFuture future = new CompletableFuture<>(); + final CompletableFuture future = new CompletableFuture<>(); future.exceptionally(e -> { ess.showError(teleportOwner.getSource(), e, "\\ teleport"); return false; @@ -116,23 +115,24 @@ public class AsyncTimedTeleport implements Runnable { if (timer_chargeFor != null) { try { timer_chargeFor.charge(teleportOwner); - } catch (ChargeException ex) { + } catch (final ChargeException ex) { ess.showError(teleportOwner.getSource(), ex, "\\ teleport"); } } }); - } catch (Exception ex) { + } catch (final Exception ex) { ess.showError(teleportOwner.getSource(), ex, "\\ teleport"); } } } } + ess.scheduleSyncDelayedTask(new DelayedTeleportTask()); } //If we need to cancelTimer a pending teleportPlayer call this method - void cancelTimer(boolean notifyUser) { + void cancelTimer(final boolean notifyUser) { if (timer_task == -1) { return; } diff --git a/Essentials/src/com/earth2me/essentials/Backup.java b/Essentials/src/com/earth2me/essentials/Backup.java index 9b481de05..96d683d74 100644 --- a/Essentials/src/com/earth2me/essentials/Backup.java +++ b/Essentials/src/com/earth2me/essentials/Backup.java @@ -14,15 +14,14 @@ import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; - public class Backup implements Runnable { private static final Logger LOGGER = Logger.getLogger("Essentials"); private transient final Server server; private transient final IEssentials ess; + private final AtomicBoolean pendingShutdown = new AtomicBoolean(false); private transient boolean running = false; private transient int taskId = -1; private transient boolean active = false; - private final AtomicBoolean pendingShutdown = new AtomicBoolean(false); private transient CompletableFuture taskLock = null; public Backup(final IEssentials ess) { @@ -60,7 +59,7 @@ public class Backup implements Runnable { return taskLock; } - public void setPendingShutdown(boolean shutdown) { + public void setPendingShutdown(final boolean shutdown) { pendingShutdown.set(shutdown); } @@ -95,7 +94,7 @@ public class Backup implements Runnable { final Process child = childBuilder.start(); ess.runTaskAsynchronously(() -> { try { - try (BufferedReader reader = new BufferedReader(new InputStreamReader(child.getInputStream()))) { + try (final BufferedReader reader = new BufferedReader(new InputStreamReader(child.getInputStream()))) { String line; do { line = reader.readLine(); @@ -104,12 +103,12 @@ public class Backup implements Runnable { } } while (line != null); } - } catch (IOException ex) { + } catch (final IOException ex) { LOGGER.log(Level.SEVERE, null, ex); } }); child.waitFor(); - } catch (InterruptedException | IOException ex) { + } catch (final InterruptedException | IOException ex) { LOGGER.log(Level.SEVERE, null, ex); } finally { class BackupEnableSaveTask implements Runnable { @@ -124,6 +123,7 @@ public class Backup implements Runnable { LOGGER.log(Level.INFO, tl("backupFinished")); } } + if (!pendingShutdown.get()) { ess.scheduleSyncDelayedTask(new BackupEnableSaveTask()); } diff --git a/Essentials/src/com/earth2me/essentials/ChargeException.java b/Essentials/src/com/earth2me/essentials/ChargeException.java index 1c2644aab..adba3669d 100644 --- a/Essentials/src/com/earth2me/essentials/ChargeException.java +++ b/Essentials/src/com/earth2me/essentials/ChargeException.java @@ -1,6 +1,5 @@ package com.earth2me.essentials; - public class ChargeException extends Exception { public ChargeException(final String message) { super(message); diff --git a/Essentials/src/com/earth2me/essentials/CommandSource.java b/Essentials/src/com/earth2me/essentials/CommandSource.java index 2340c6ed1..3d7036495 100644 --- a/Essentials/src/com/earth2me/essentials/CommandSource.java +++ b/Essentials/src/com/earth2me/essentials/CommandSource.java @@ -3,7 +3,6 @@ package com.earth2me.essentials; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; - public class CommandSource { protected CommandSender sender; @@ -22,7 +21,7 @@ public class CommandSource { return null; } - public final net.ess3.api.IUser getUser(IEssentials ess) { + public final net.ess3.api.IUser getUser(final IEssentials ess) { if (sender instanceof Player) { return ess.getUser((Player) sender); } @@ -37,14 +36,13 @@ public class CommandSource { return this.sender = base; } - - public void sendMessage(String message) { + public void sendMessage(final String message) { if (!message.isEmpty()) { sender.sendMessage(message); } } - public boolean isAuthorized(String permission, IEssentials ess) { + public boolean isAuthorized(final String permission, final IEssentials ess) { return !(sender instanceof Player) || getUser(ess).isAuthorized(permission); } diff --git a/Essentials/src/com/earth2me/essentials/Console.java b/Essentials/src/com/earth2me/essentials/Console.java index 2b442d2c8..7b2ba8056 100644 --- a/Essentials/src/com/earth2me/essentials/Console.java +++ b/Essentials/src/com/earth2me/essentials/Console.java @@ -2,76 +2,82 @@ package com.earth2me.essentials; import com.earth2me.essentials.messaging.IMessageRecipient; import com.earth2me.essentials.messaging.SimpleMessageRecipient; - import org.bukkit.Server; import org.bukkit.command.CommandSender; - public final class Console implements IMessageRecipient { public static final String NAME = "Console"; private static Console instance; // Set in essentials - + private final IEssentials ess; private final IMessageRecipient messageRecipient; + private Console(final IEssentials ess) { + this.ess = ess; + this.messageRecipient = new SimpleMessageRecipient(ess, this); + } + public static Console getInstance() { return instance; } - static void setInstance(IEssentials ess) { // Called in Essentials#onEnable() + static void setInstance(final IEssentials ess) { // Called in Essentials#onEnable() instance = new Console(ess); } - + /** * @deprecated Use {@link Console#getCommandSender()} */ @Deprecated - public static CommandSender getCommandSender(Server server) throws Exception { + public static CommandSender getCommandSender(final Server server) throws Exception { return server.getConsoleSender(); } - private Console(IEssentials ess) { - this.ess = ess; - this.messageRecipient = new SimpleMessageRecipient(ess, this); - } - public CommandSender getCommandSender() { return ess.getServer().getConsoleSender(); } - @Override public String getName() { + @Override + public String getName() { return Console.NAME; } - @Override public String getDisplayName() { + @Override + public String getDisplayName() { return Console.NAME; } - @Override public void sendMessage(String message) { + @Override + public void sendMessage(final String message) { getCommandSender().sendMessage(message); } - @Override public boolean isReachable() { + @Override + public boolean isReachable() { return true; } - + /* ================================ * >> DELEGATE METHODS * ================================ */ - @Override public MessageResponse sendMessage(IMessageRecipient recipient, String message) { + @Override + public MessageResponse sendMessage(final IMessageRecipient recipient, final String message) { return this.messageRecipient.sendMessage(recipient, message); } - @Override public MessageResponse onReceiveMessage(IMessageRecipient sender, String message) { + @Override + public MessageResponse onReceiveMessage(final IMessageRecipient sender, final String message) { return this.messageRecipient.onReceiveMessage(sender, message); } - @Override public IMessageRecipient getReplyRecipient() { + @Override + public IMessageRecipient getReplyRecipient() { return this.messageRecipient.getReplyRecipient(); } - @Override public void setReplyRecipient(IMessageRecipient recipient) { + @Override + public void setReplyRecipient(final IMessageRecipient recipient) { this.messageRecipient.setReplyRecipient(recipient); } } diff --git a/Essentials/src/com/earth2me/essentials/Enchantments.java b/Essentials/src/com/earth2me/essentials/Enchantments.java index 33bb8d29d..f4f12e97d 100644 --- a/Essentials/src/com/earth2me/essentials/Enchantments.java +++ b/Essentials/src/com/earth2me/essentials/Enchantments.java @@ -9,8 +9,7 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; - -public class Enchantments { +public final class Enchantments { private static final Map ENCHANTMENTS = new HashMap<>(); private static final Map ALIASENCHANTMENTS = new HashMap<>(); private static boolean isFlat; @@ -152,76 +151,78 @@ public class Enchantments { // 1.8 try { - Enchantment depthStrider = Enchantment.getByName("DEPTH_STRIDER"); + final Enchantment depthStrider = Enchantment.getByName("DEPTH_STRIDER"); if (depthStrider != null) { ENCHANTMENTS.put("depthstrider", depthStrider); ALIASENCHANTMENTS.put("depth", depthStrider); ALIASENCHANTMENTS.put("strider", depthStrider); } - } catch (IllegalArgumentException ignored) {} + } catch (final IllegalArgumentException ignored) { + } // 1.9 try { - Enchantment frostWalker = Enchantment.getByName("FROST_WALKER"); + final Enchantment frostWalker = Enchantment.getByName("FROST_WALKER"); if (frostWalker != null) { ENCHANTMENTS.put("frostwalker", frostWalker); ALIASENCHANTMENTS.put("frost", frostWalker); ALIASENCHANTMENTS.put("walker", frostWalker); } - Enchantment mending = Enchantment.getByName("MENDING"); + final Enchantment mending = Enchantment.getByName("MENDING"); if (mending != null) { ENCHANTMENTS.put("mending", mending); } - } catch (IllegalArgumentException ignored) {} + } catch (final IllegalArgumentException ignored) { + } // 1.11 try { - Enchantment bindingCurse = Enchantment.getByName("BINDING_CURSE"); + final Enchantment bindingCurse = Enchantment.getByName("BINDING_CURSE"); if (bindingCurse != null) { ENCHANTMENTS.put("bindingcurse", bindingCurse); ALIASENCHANTMENTS.put("bindcurse", bindingCurse); ALIASENCHANTMENTS.put("binding", bindingCurse); ALIASENCHANTMENTS.put("bind", bindingCurse); } - Enchantment vanishingCurse = Enchantment.getByName("VANISHING_CURSE"); + final Enchantment vanishingCurse = Enchantment.getByName("VANISHING_CURSE"); if (vanishingCurse != null) { ENCHANTMENTS.put("vanishingcurse", vanishingCurse); ALIASENCHANTMENTS.put("vanishcurse", vanishingCurse); ALIASENCHANTMENTS.put("vanishing", vanishingCurse); ALIASENCHANTMENTS.put("vanish", vanishingCurse); } - Enchantment sweeping = Enchantment.getByName("SWEEPING_EDGE"); + final Enchantment sweeping = Enchantment.getByName("SWEEPING_EDGE"); if (sweeping != null) { ENCHANTMENTS.put("sweepingedge", sweeping); ALIASENCHANTMENTS.put("sweepedge", sweeping); ALIASENCHANTMENTS.put("sweeping", sweeping); } - } catch (IllegalArgumentException ignored) {} - + } catch (final IllegalArgumentException ignored) { + } try { // 1.13 - Enchantment loyalty = Enchantment.getByName("LOYALTY"); + final Enchantment loyalty = Enchantment.getByName("LOYALTY"); if (loyalty != null) { ENCHANTMENTS.put("loyalty", loyalty); ALIASENCHANTMENTS.put("loyal", loyalty); ALIASENCHANTMENTS.put("return", loyalty); } - Enchantment impaling = Enchantment.getByName("IMPALING"); + final Enchantment impaling = Enchantment.getByName("IMPALING"); if (impaling != null) { ENCHANTMENTS.put("impaling", impaling); ALIASENCHANTMENTS.put("impale", impaling); ALIASENCHANTMENTS.put("oceandamage", impaling); ALIASENCHANTMENTS.put("oceandmg", impaling); } - Enchantment riptide = Enchantment.getByName("RIPTIDE"); + final Enchantment riptide = Enchantment.getByName("RIPTIDE"); if (riptide != null) { ENCHANTMENTS.put("riptide", riptide); ALIASENCHANTMENTS.put("rip", riptide); ALIASENCHANTMENTS.put("tide", riptide); ALIASENCHANTMENTS.put("launch", riptide); } - Enchantment channelling = Enchantment.getByName("CHANNELING"); + final Enchantment channelling = Enchantment.getByName("CHANNELING"); if (channelling != null) { ENCHANTMENTS.put("channelling", channelling); ALIASENCHANTMENTS.put("chanelling", channelling); @@ -229,48 +230,53 @@ public class Enchantments { ALIASENCHANTMENTS.put("chaneling", channelling); ALIASENCHANTMENTS.put("channel", channelling); } - } catch (IllegalArgumentException ignored) {} - + } catch (final IllegalArgumentException ignored) { + } try { // 1.14 - Enchantment multishot = Enchantment.getByName("MULTISHOT"); + final Enchantment multishot = Enchantment.getByName("MULTISHOT"); if (multishot != null) { ENCHANTMENTS.put("multishot", multishot); ALIASENCHANTMENTS.put("tripleshot", multishot); } - Enchantment quickCharge = Enchantment.getByName("QUICK_CHARGE"); + final Enchantment quickCharge = Enchantment.getByName("QUICK_CHARGE"); if (quickCharge != null) { ENCHANTMENTS.put("quickcharge", quickCharge); ALIASENCHANTMENTS.put("quickdraw", quickCharge); ALIASENCHANTMENTS.put("fastcharge", quickCharge); ALIASENCHANTMENTS.put("fastdraw", quickCharge); } - Enchantment piercing = Enchantment.getByName("PIERCING"); + final Enchantment piercing = Enchantment.getByName("PIERCING"); if (piercing != null) { ENCHANTMENTS.put("piercing", piercing); } - } catch (IllegalArgumentException ignored) {} + } catch (final IllegalArgumentException ignored) { + } try { // 1.16 - Enchantment soulspeed = Enchantment.getByName("SOUL_SPEED"); + final Enchantment soulspeed = Enchantment.getByName("SOUL_SPEED"); if (soulspeed != null) { ENCHANTMENTS.put("soulspeed", soulspeed); ALIASENCHANTMENTS.put("soilspeed", soulspeed); ALIASENCHANTMENTS.put("sandspeed", soulspeed); } - } catch (IllegalArgumentException ignored) {} + } catch (final IllegalArgumentException ignored) { + } try { - Class namespacedKeyClass = Class.forName("org.bukkit.NamespacedKey"); - Class enchantmentClass = Class.forName("org.bukkit.enchantments.Enchantment"); + final Class namespacedKeyClass = Class.forName("org.bukkit.NamespacedKey"); + final Class enchantmentClass = Class.forName("org.bukkit.enchantments.Enchantment"); enchantmentClass.getDeclaredMethod("getByKey", namespacedKeyClass); isFlat = true; - } catch (ClassNotFoundException | NoSuchMethodException e) { + } catch (final ClassNotFoundException | NoSuchMethodException e) { isFlat = false; } } - public static Enchantment getByName(String name) { + private Enchantments() { + } + + public static Enchantment getByName(final String name) { Enchantment enchantment = null; if (isFlat) { // 1.13+ only enchantment = Enchantment.getByKey(NamespacedKey.minecraft(name.toLowerCase())); diff --git a/Essentials/src/com/earth2me/essentials/Essentials.java b/Essentials/src/com/earth2me/essentials/Essentials.java index a72d744ab..0fa4b8909 100644 --- a/Essentials/src/com/earth2me/essentials/Essentials.java +++ b/Essentials/src/com/earth2me/essentials/Essentials.java @@ -17,7 +17,12 @@ */ package com.earth2me.essentials; -import com.earth2me.essentials.commands.*; +import com.earth2me.essentials.commands.Commandhat; +import com.earth2me.essentials.commands.EssentialsCommand; +import com.earth2me.essentials.commands.IEssentialsCommand; +import com.earth2me.essentials.commands.NoChargeException; +import com.earth2me.essentials.commands.NotEnoughArgumentsException; +import com.earth2me.essentials.commands.QuietAbortException; import com.earth2me.essentials.items.AbstractItemDb; import com.earth2me.essentials.items.CustomItemResolver; import com.earth2me.essentials.items.FlatItemDb; @@ -34,9 +39,11 @@ import com.earth2me.essentials.textreader.SimpleTextInput; import com.earth2me.essentials.utils.DateUtil; import com.earth2me.essentials.utils.VersionUtil; import io.papermc.lib.PaperLib; +import net.ess3.api.Economy; import net.ess3.api.IEssentials; +import net.ess3.api.IItemDb; +import net.ess3.api.IJails; import net.ess3.api.ISettings; -import net.ess3.api.*; import net.ess3.nms.refl.providers.ReflServerStateProvider; import net.ess3.nms.refl.providers.ReflSpawnEggProvider; import net.ess3.nms.refl.providers.ReflSpawnerBlockProvider; @@ -46,12 +53,23 @@ import net.ess3.provider.ServerStateProvider; import net.ess3.provider.SpawnEggProvider; import net.ess3.provider.SpawnerBlockProvider; import net.ess3.provider.SpawnerItemProvider; -import net.ess3.provider.providers.*; +import net.ess3.provider.providers.BasePotionDataProvider; +import net.ess3.provider.providers.BlockMetaSpawnerItemProvider; +import net.ess3.provider.providers.BukkitSpawnerBlockProvider; +import net.ess3.provider.providers.FlatSpawnEggProvider; +import net.ess3.provider.providers.LegacyPotionMetaProvider; +import net.ess3.provider.providers.LegacySpawnEggProvider; +import net.ess3.provider.providers.PaperRecipeBookListener; +import net.ess3.provider.providers.PaperServerStateProvider; import org.bukkit.Bukkit; import org.bukkit.Server; import org.bukkit.World; import org.bukkit.block.Block; -import org.bukkit.command.*; +import org.bukkit.command.BlockCommandSender; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.PluginCommand; +import org.bukkit.command.TabCompleter; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.EventHandler; @@ -76,18 +94,24 @@ import org.yaml.snakeyaml.error.YAMLException; import java.io.File; import java.io.IOException; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; import java.util.function.Predicate; import java.util.logging.Level; import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; - public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { private static final Logger LOGGER = Logger.getLogger("Essentials"); - private transient ISettings settings; private final transient TNTExplodeListener tntListener = new TNTExplodeListener(this); + private final transient Set vanishedPlayers = new LinkedHashSet<>(); + private transient ISettings settings; private transient Jails jails; private transient Warps warps; private transient Worth worth; @@ -95,7 +119,6 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { private transient Backup backup; private transient AbstractItemDb itemDb; private transient CustomItemResolver customItemResolver; - private transient final Methods paymentMethod = new Methods(); private transient PermissionsHandler permissionsHandler; private transient AlternativeCommandsHandler alternativeCommandsHandler; private transient UserMap userMap; @@ -103,7 +126,6 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { private transient I18n i18n; private transient MetricsWrapper metrics; private transient EssentialsTimer timer; - private final transient Set vanishedPlayers = new LinkedHashSet<>(); private transient SpawnerItemProvider spawnerItemProvider; private transient SpawnerBlockProvider spawnerBlockProvider; private transient SpawnEggProvider spawnEggProvider; @@ -113,11 +135,15 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { private transient Kits kits; private transient RandomTeleport randomTeleport; - public Essentials() { - + static { + // TODO: improve legacy code + Methods.init(); } - protected Essentials(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) { + public Essentials() { + } + + protected Essentials(final JavaPluginLoader loader, final PluginDescriptionFile description, final File dataFolder, final File file) { super(loader, description, dataFolder, file); } @@ -125,6 +151,18 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { super(new JavaPluginLoader(server), new PluginDescriptionFile("Essentials", "", "com.earth2me.essentials.Essentials"), null, null); } + private static void addDefaultBackPermissionsToWorld(final World w) { + final String permName = "essentials.back.into." + w.getName(); + + Permission p = Bukkit.getPluginManager().getPermission(permName); + if (p == null) { + p = new Permission(permName, + "Allows access to /back when the destination location is within world " + w.getName(), + PermissionDefault.TRUE); + Bukkit.getPluginManager().addPermission(p); + } + } + @Override public ISettings getSettings() { return settings; @@ -174,7 +212,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { } final PluginManager pm = getServer().getPluginManager(); - for (Plugin plugin : pm.getPlugins()) { + for (final Plugin plugin : pm.getPlugins()) { if (plugin.getDescription().getName().startsWith("Essentials") && !plugin.getDescription().getVersion().equals(this.getDescription().getVersion()) && !plugin.getDescription().getName().equals("EssentialsAntiCheat")) { getLogger().warning(tl("versionMismatch", plugin.getDescription().getName())); } @@ -225,7 +263,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { try { itemDb.registerResolver(this, "custom_items", customItemResolver); confList.add(customItemResolver); - } catch (Exception e) { + } catch (final Exception e) { e.printStackTrace(); customItemResolver = null; } @@ -277,7 +315,8 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { ((Cancellable) event).setCancelled(true); } }); - } catch (ClassNotFoundException ignored) {} + } catch (final ClassNotFoundException ignored) { + } } execTimer.mark("Init(Providers)"); @@ -286,7 +325,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { // The item spawn blacklist is loaded with all other settings, before the item // DB, but it depends on the item DB, so we need to reload it again here: ((Settings) settings)._lateLoadItemSpawnBlacklist(); - } catch (YAMLException exception) { + } catch (final YAMLException exception) { if (pm.getPlugin("EssentialsUpdate") != null) { LOGGER.log(Level.SEVERE, tl("essentialsHelp2")); } else { @@ -308,7 +347,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { Economy.setEss(this); execTimer.mark("RegHandler"); - for (World w : Bukkit.getWorlds()) + for (final World w : Bukkit.getWorlds()) addDefaultBackPermissionsToWorld(w); metrics = new MetricsWrapper(this, 858, true); @@ -317,9 +356,9 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { if (getSettings().isDebug()) { LOGGER.log(Level.INFO, "Essentials load {0}", timeroutput); } - } catch (NumberFormatException ex) { + } catch (final NumberFormatException ex) { handleCrash(ex); - } catch (Error ex) { + } catch (final Error ex) { handleCrash(ex); throw ex; } @@ -331,7 +370,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { // We don't use any of the bukkit config writing, as this breaks our config file formatting. } - private void registerListeners(PluginManager pm) { + private void registerListeners(final PluginManager pm) { HandlerList.unregisterAll(this); if (getSettings().isDebug()) { @@ -377,12 +416,12 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { @Override public void onDisable() { - boolean stopping = getServerStateProvider().isStopping(); + final boolean stopping = getServerStateProvider().isStopping(); if (!stopping) { LOGGER.log(Level.SEVERE, tl("serverReloading")); } getBackup().setPendingShutdown(true); - for (User user : getOnlineUsers()) { + for (final User user : getOnlineUsers()) { if (user.isVanished()) { user.setVanished(false); user.sendMessage(tl("unvanishedReload")); @@ -422,14 +461,14 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { public void reload() { Trade.closeLog(); - for (IConf iConf : confList) { + for (final IConf iConf : confList) { iConf.reloadConfig(); execTimer.mark("Reload(" + iConf.getClass().getSimpleName() + ")"); } i18n.updateLocale(settings.getLocale()); - for (String commandName : this.getDescription().getCommands().keySet()) { - Command command = this.getCommand(commandName); + for (final String commandName : this.getDescription().getCommands().keySet()) { + final Command command = this.getCommand(commandName); if (command != null) { command.setDescription(tl(commandName + "CommandDescription")); command.setUsage(tl(commandName + "CommandUsage")); @@ -441,9 +480,9 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { } @Override - public List onTabComplete(CommandSender sender, Command command, String commandLabel, String[] args) { + public List onTabComplete(final CommandSender sender, final Command command, final String commandLabel, final String[] args) { return onTabCompleteEssentials(sender, command, commandLabel, args, Essentials.class.getClassLoader(), - "com.earth2me.essentials.commands.Command", "essentials.", null); + "com.earth2me.essentials.commands.Command", "essentials.", null); } @Override @@ -454,7 +493,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { final PluginCommand pc = alternativeCommandsHandler.getAlternative(commandLabel); if (pc != null) { try { - TabCompleter completer = pc.getTabCompleter(); + final TabCompleter completer = pc.getTabCompleter(); if (completer != null) { return completer.onTabComplete(cSender, command, commandLabel, args); } @@ -471,19 +510,19 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { user = getUser((Player) cSender); } - CommandSource sender = new CommandSource(cSender); + final CommandSource sender = new CommandSource(cSender); // Check for disabled commands if (getSettings().isCommandDisabled(commandLabel)) { return Collections.emptyList(); } - IEssentialsCommand cmd; + final IEssentialsCommand cmd; try { cmd = (IEssentialsCommand) classLoader.loadClass(commandPath + command.getName()).newInstance(); cmd.setEssentials(this); cmd.setEssentialsModule(module); - } catch (Exception ex) { + } catch (final Exception ex) { sender.sendMessage(tl("commandNotLoaded", commandLabel)); LOGGER.log(Level.SEVERE, tl("commandNotLoaded", commandLabel), ex); return Collections.emptyList(); @@ -505,13 +544,13 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { } else { return cmd.tabComplete(getServer(), user, commandLabel, command, args); } - } catch (Exception ex) { + } catch (final Exception ex) { showError(sender, ex, commandLabel); // Tab completion shouldn't fail LOGGER.log(Level.SEVERE, tl("commandFailed", commandLabel), ex); return Collections.emptyList(); } - } catch (Throwable ex) { + } catch (final Throwable ex) { LOGGER.log(Level.SEVERE, tl("commandFailed", commandLabel), ex); return Collections.emptyList(); } @@ -547,19 +586,19 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { if (cSender instanceof Player) { user = getUser((Player) cSender); } else if (cSender instanceof BlockCommandSender) { - BlockCommandSender bsender = (BlockCommandSender) cSender; + final BlockCommandSender bsender = (BlockCommandSender) cSender; bSenderBlock = bsender.getBlock(); } if (bSenderBlock != null) { if (getSettings().logCommandBlockCommands()) { - Bukkit.getLogger().log(Level.INFO, "CommandBlock at {0},{1},{2} issued server command: /{3} {4}", new Object[]{bSenderBlock.getX(), bSenderBlock.getY(), bSenderBlock.getZ(), commandLabel, EssentialsCommand.getFinalArg(args, 0)}); + Bukkit.getLogger().log(Level.INFO, "CommandBlock at {0},{1},{2} issued server command: /{3} {4}", new Object[] {bSenderBlock.getX(), bSenderBlock.getY(), bSenderBlock.getZ(), commandLabel, EssentialsCommand.getFinalArg(args, 0)}); } } else if (user == null) { - Bukkit.getLogger().log(Level.INFO, "{0} issued server command: /{1} {2}", new Object[]{cSender.getName(), commandLabel, EssentialsCommand.getFinalArg(args, 0)}); + Bukkit.getLogger().log(Level.INFO, "{0} issued server command: /{1} {2}", new Object[] {cSender.getName(), commandLabel, EssentialsCommand.getFinalArg(args, 0)}); } - CommandSource sender = new CommandSource(cSender); + final CommandSource sender = new CommandSource(cSender); // New mail notification if (user != null && !getSettings().isCommandDisabled("mail") && !command.getName().equals("mail") && user.isAuthorized("essentials.mail")) { @@ -578,12 +617,12 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { return true; } - IEssentialsCommand cmd; + final IEssentialsCommand cmd; try { cmd = (IEssentialsCommand) classLoader.loadClass(commandPath + command.getName()).newInstance(); cmd.setEssentials(this); cmd.setEssentialsModule(module); - } catch (Exception ex) { + } catch (final Exception ex) { sender.sendMessage(tl("commandNotLoaded", commandLabel)); LOGGER.log(Level.SEVERE, tl("commandNotLoaded", commandLabel), ex); return true; @@ -613,9 +652,9 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { cmd.run(getServer(), user, commandLabel, command, args); } return true; - } catch (NoChargeException | QuietAbortException ex) { + } catch (final NoChargeException | QuietAbortException ex) { return true; - } catch (NotEnoughArgumentsException ex) { + } catch (final NotEnoughArgumentsException ex) { sender.sendMessage(command.getDescription()); sender.sendMessage(command.getUsage().replaceAll("", commandLabel)); if (!ex.getMessage().isEmpty()) { @@ -625,21 +664,21 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { ex.getCause().printStackTrace(); } return true; - } catch (Exception ex) { + } catch (final Exception ex) { showError(sender, ex, commandLabel); if (settings.isDebug()) { ex.printStackTrace(); } return true; } - } catch (Throwable ex) { + } catch (final Throwable ex) { LOGGER.log(Level.SEVERE, tl("commandFailed", commandLabel), ex); return true; } } public void cleanupOpenInventories() { - for (User user : getOnlineUsers()) { + for (final User user : getOnlineUsers()) { if (user.isRecipeSee()) { user.getBase().getOpenInventory().getTopInventory().clear(); user.getBase().getOpenInventory().close(); @@ -767,7 +806,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { return user; } - private void handleCrash(Throwable exception) { + private void handleCrash(final Throwable exception) { final PluginManager pm = getServer().getPluginManager(); LOGGER.log(Level.SEVERE, exception.toString()); exception.printStackTrace(); @@ -777,7 +816,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { event.getPlayer().sendMessage("Essentials failed to load, read the log file."); } }, this); - for (Player player : getOnlinePlayers()) { + for (final Player player : getOnlinePlayers()) { player.sendMessage("Essentials failed to load, read the log file."); } this.setEnabled(false); @@ -799,11 +838,6 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { confList.add(listener); } - @Override - public Methods getPaymentMethod() { - return paymentMethod; - } - @Override public int broadcastMessage(final String message) { return broadcastMessage(null, null, message, true, u -> false); @@ -832,7 +866,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { IText broadcast = new SimpleTextInput(message); final Collection players = getOnlinePlayers(); - for (Player player : players) { + for (final Player player : players) { final User user = getUser(player); if ((permission == null && (sender == null || !user.isIgnoredPlayer(sender))) || (permission != null && user.isAuthorized(permission))) { if (shouldExclude.test(user)) { @@ -841,7 +875,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { if (keywords) { broadcast = new KeywordReplacer(broadcast, new CommandSource(player), this, false); } - for (String messageText : broadcast.getLines()) { + for (final String messageText : broadcast.getLines()) { user.sendMessage(messageText); } } @@ -932,8 +966,8 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { @Override public Iterable getOnlineUsers() { - List onlineUsers = new ArrayList<>(); - for (Player player : getOnlinePlayers()) { + final List onlineUsers = new ArrayList<>(); + for (final Player player : getOnlinePlayers()) { onlineUsers.add(getUser(player)); } return onlineUsers; @@ -969,22 +1003,28 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { return serverStateProvider; } - private static void addDefaultBackPermissionsToWorld(World w) { - String permName = "essentials.back.into." + w.getName(); + private AbstractItemDb getItemDbFromConfig() { + final String setting = settings.getItemDbType(); - Permission p = Bukkit.getPluginManager().getPermission(permName); - if (p == null) { - p = new Permission(permName, - "Allows access to /back when the destination location is within world " + w.getName(), - PermissionDefault.TRUE); - Bukkit.getPluginManager().addPermission(p); + if (setting.equalsIgnoreCase("json")) { + return new FlatItemDb(this); + } else if (setting.equalsIgnoreCase("csv")) { + return new LegacyItemDb(this); + } else { + final VersionUtil.BukkitVersion version = VersionUtil.getServerBukkitVersion(); + + if (version.isHigherThanOrEqualTo(VersionUtil.v1_13_0_R01)) { + return new FlatItemDb(this); + } else { + return new LegacyItemDb(this); + } } } private static class EssentialsWorldListener implements Listener, Runnable { private transient final IEssentials ess; - public EssentialsWorldListener(final IEssentials ess) { + EssentialsWorldListener(final IEssentials ess) { this.ess = ess; } @@ -994,7 +1034,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { ess.getJails().onReload(); ess.getWarps().reloadConfig(); - for (IConf iConf : ((Essentials) ess).confList) { + for (final IConf iConf : ((Essentials) ess).confList) { if (iConf instanceof IEssentialsModule) { iConf.reloadConfig(); } @@ -1005,7 +1045,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { public void onWorldUnload(final WorldUnloadEvent event) { ess.getJails().onReload(); ess.getWarps().reloadConfig(); - for (IConf iConf : ((Essentials) ess).confList) { + for (final IConf iConf : ((Essentials) ess).confList) { if (iConf instanceof IEssentialsModule) { iConf.reloadConfig(); } @@ -1017,22 +1057,4 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { ess.reload(); } } - - private AbstractItemDb getItemDbFromConfig() { - final String setting = settings.getItemDbType(); - - if (setting.equalsIgnoreCase("json")) { - return new FlatItemDb(this); - } else if (setting.equalsIgnoreCase("csv")) { - return new LegacyItemDb(this); - } else { - VersionUtil.BukkitVersion version = VersionUtil.getServerBukkitVersion(); - - if (version.isHigherThanOrEqualTo(VersionUtil.v1_13_0_R01)) { - return new FlatItemDb(this); - } else { - return new LegacyItemDb(this); - } - } - } } diff --git a/Essentials/src/com/earth2me/essentials/EssentialsBlockListener.java b/Essentials/src/com/earth2me/essentials/EssentialsBlockListener.java index 7d2c8ef38..d40f3d8cf 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsBlockListener.java +++ b/Essentials/src/com/earth2me/essentials/EssentialsBlockListener.java @@ -15,7 +15,6 @@ import org.bukkit.inventory.ItemStack; import java.util.Locale; - public class EssentialsBlockListener implements Listener { private final transient IEssentials ess; @@ -56,6 +55,7 @@ public class EssentialsBlockListener implements Listener { user.getBase().updateInventory(); } } + ess.scheduleSyncDelayedTask(new UnlimitedItemSpawnTask()); } } diff --git a/Essentials/src/com/earth2me/essentials/EssentialsConf.java b/Essentials/src/com/earth2me/essentials/EssentialsConf.java index 0e4b856f8..611fe9189 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsConf.java +++ b/Essentials/src/com/earth2me/essentials/EssentialsConf.java @@ -2,8 +2,11 @@ package com.earth2me.essentials; import com.google.common.io.Files; import net.ess3.api.InvalidWorldException; +import org.bukkit.Location; +import org.bukkit.Material; import org.bukkit.OfflinePlayer; -import org.bukkit.*; +import org.bukkit.Server; +import org.bukkit.World; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; @@ -11,7 +14,14 @@ import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; -import java.io.*; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.OutputStreamWriter; import java.math.BigDecimal; import java.math.MathContext; import java.nio.Buffer; @@ -21,7 +31,13 @@ import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CoderResult; import java.nio.charset.StandardCharsets; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -33,23 +49,33 @@ import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; - public class EssentialsConf extends YamlConfiguration { protected static final Logger LOGGER = Logger.getLogger("Essentials"); - protected final File configFile; - protected String templateName = null; protected static final Charset UTF8 = StandardCharsets.UTF_8; - private Class resourceClass = EssentialsConf.class; private static final ExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadExecutor(); + protected final File configFile; private final AtomicInteger pendingDiskWrites = new AtomicInteger(0); private final AtomicBoolean transaction = new AtomicBoolean(false); + private final byte[] bytebuffer = new byte[1024]; + protected String templateName = null; + private Class resourceClass = EssentialsConf.class; public EssentialsConf(final File configFile) { super(); this.configFile = configFile.getAbsoluteFile(); } - private final byte[] bytebuffer = new byte[1024]; + public static BigDecimal toBigDecimal(final String input, final BigDecimal def) { + if (input == null || input.isEmpty()) { + return def; + } else { + try { + return new BigDecimal(input, MathContext.DECIMAL128); + } catch (final NumberFormatException | ArithmeticException e) { + return def; + } + } + } public synchronized void load() { if (pendingDiskWrites.get() != 0) { @@ -70,16 +96,16 @@ public class EssentialsConf extends YamlConfiguration { input.close(); configFile.delete(); } - } catch (IOException ex) { + } catch (final IOException ex) { LOGGER.log(Level.SEVERE, null, ex); } finally { try { input.close(); - } catch (IOException ex) { + } catch (final IOException ex) { LOGGER.log(Level.SEVERE, null, ex); } } - } catch (FileNotFoundException ex) { + } catch (final FileNotFoundException ex) { LOGGER.log(Level.SEVERE, null, ex); } } @@ -97,10 +123,9 @@ public class EssentialsConf extends YamlConfiguration { } } - try { - try (FileInputStream inputStream = new FileInputStream(configFile)) { - long startSize = configFile.length(); + try (final FileInputStream inputStream = new FileInputStream(configFile)) { + final long startSize = configFile.length(); if (startSize > Integer.MAX_VALUE) { throw new InvalidConfigurationException("File too big"); } @@ -108,8 +133,8 @@ public class EssentialsConf extends YamlConfiguration { int length; while ((length = inputStream.read(bytebuffer)) != -1) { if (length > buffer.remaining()) { - ByteBuffer resize = ByteBuffer.allocate(buffer.capacity() + length - buffer.remaining()); - int resizePosition = buffer.position(); + final ByteBuffer resize = ByteBuffer.allocate(buffer.capacity() + length - buffer.remaining()); + final int resizePosition = buffer.position(); // Fix builds compiled against Java 9+ breaking on Java 8 ((Buffer) buffer).rewind(); resize.put(buffer); @@ -140,10 +165,10 @@ public class EssentialsConf extends YamlConfiguration { ((Buffer) data).rewind(); super.loadFromString(data.subSequence(0, end).toString()); } - } catch (IOException ex) { + } catch (final IOException ex) { LOGGER.log(Level.SEVERE, ex.getMessage(), ex); - } catch (InvalidConfigurationException ex) { - File broken = new File(configFile.getAbsolutePath() + ".broken." + System.currentTimeMillis()); + } catch (final InvalidConfigurationException ex) { + final File broken = new File(configFile.getAbsolutePath() + ".broken." + System.currentTimeMillis()); configFile.renameTo(broken); LOGGER.log(Level.SEVERE, "The file " + configFile.toString() + " is broken, it has been renamed to " + broken.toString(), ex.getCause()); } @@ -175,28 +200,28 @@ public class EssentialsConf extends YamlConfiguration { return; } ostr = new FileOutputStream(configFile); - byte[] buffer = new byte[1024]; + final byte[] buffer = new byte[1024]; int length = 0; length = istr.read(buffer); while (length > 0) { ostr.write(buffer, 0, length); length = istr.read(buffer); } - } catch (IOException ex) { + } catch (final IOException ex) { LOGGER.log(Level.SEVERE, tl("failedToWriteConfig", configFile.toString()), ex); } finally { try { if (istr != null) { istr.close(); } - } catch (IOException ex) { + } catch (final IOException ex) { Logger.getLogger(EssentialsConf.class.getName()).log(Level.SEVERE, null, ex); } try { if (ostr != null) { ostr.close(); } - } catch (IOException ex) { + } catch (final IOException ex) { LOGGER.log(Level.SEVERE, tl("failedToCloseConfig", configFile.toString()), ex); } } @@ -227,7 +252,7 @@ public class EssentialsConf extends YamlConfiguration { public void save() { try { save(configFile); - } catch (IOException ex) { + } catch (final IOException ex) { LOGGER.log(Level.SEVERE, ex.getMessage(), ex); } } @@ -247,11 +272,11 @@ public class EssentialsConf extends YamlConfiguration { //This needs fixed to discard outstanding save requests. public synchronized void forceSave() { try { - Future future = delayedSave(configFile); + final Future future = delayedSave(configFile); if (future != null) { future.get(); } - } catch (InterruptedException | ExecutionException ex) { + } catch (final InterruptedException | ExecutionException ex) { LOGGER.log(Level.SEVERE, ex.getMessage(), ex); } } @@ -276,60 +301,6 @@ public class EssentialsConf extends YamlConfiguration { return EXECUTOR_SERVICE.submit(new WriteRunner(configFile, data, pendingDiskWrites)); } - - private static class WriteRunner implements Runnable { - private final File configFile; - private final String data; - private final AtomicInteger pendingDiskWrites; - - private WriteRunner(final File configFile, final String data, final AtomicInteger pendingDiskWrites) { - this.configFile = configFile; - this.data = data; - this.pendingDiskWrites = pendingDiskWrites; - } - - @Override - public void run() { - //long startTime = System.nanoTime(); - synchronized (configFile) { - if (pendingDiskWrites.get() > 1) { - // Writes can be skipped, because they are stored in a queue (in the executor). - // Only the last is actually written. - pendingDiskWrites.decrementAndGet(); - //LOGGER.log(Level.INFO, configFile + " skipped writing in " + (System.nanoTime() - startTime) + " nsec."); - return; - } - try { - Files.createParentDirs(configFile); - - if (!configFile.exists()) { - try { - LOGGER.log(Level.INFO, tl("creatingEmptyConfig", configFile.toString())); - if (!configFile.createNewFile()) { - LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString())); - return; - } - } catch (IOException ex) { - LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString()), ex); - return; - } - } - - try (FileOutputStream fos = new FileOutputStream(configFile)) { - try (OutputStreamWriter writer = new OutputStreamWriter(fos, UTF8)) { - writer.write(data); - } - } - } catch (IOException e) { - LOGGER.log(Level.SEVERE, e.getMessage(), e); - } finally { - //LOGGER.log(Level.INFO, configFile + " written to disk in " + (System.nanoTime() - startTime) + " nsec."); - pendingDiskWrites.decrementAndGet(); - } - } - } - } - public boolean hasProperty(final String path) { return isSet(path); } @@ -361,7 +332,7 @@ public class EssentialsConf extends YamlConfiguration { final ItemStack stack = new ItemStack(Material.valueOf(getString(path + ".type", "AIR")), getInt(path + ".amount", 1), (short) getInt(path + ".damage", 0)); final ConfigurationSection enchants = getConfigurationSection(path + ".enchant"); if (enchants != null) { - for (String enchant : enchants.getKeys(false)) { + for (final String enchant : enchants.getKeys(false)) { final Enchantment enchantment = Enchantment.getByName(enchant.toUpperCase(Locale.ENGLISH)); if (enchantment == null) { continue; @@ -373,8 +344,8 @@ public class EssentialsConf extends YamlConfiguration { return stack; /* * , - * (byte)getInt(path + ".data", 0) - */ + * (byte)getInt(path + ".data", 0) + */ } public void setProperty(final String path, final ItemStack stack) { @@ -382,10 +353,10 @@ public class EssentialsConf extends YamlConfiguration { map.put("type", stack.getType().toString()); map.put("amount", stack.getAmount()); map.put("damage", stack.getDurability()); - Map enchantments = stack.getEnchantments(); + final Map enchantments = stack.getEnchantments(); if (!enchantments.isEmpty()) { - Map enchant = new HashMap<>(); - for (Map.Entry entry : enchantments.entrySet()) { + final Map enchant = new HashMap<>(); + for (final Map.Entry entry : enchantments.entrySet()) { enchant.put(entry.getKey().getName().toLowerCase(Locale.ENGLISH), entry.getValue()); } map.put("enchant", enchant); @@ -395,15 +366,15 @@ public class EssentialsConf extends YamlConfiguration { set(path, map); } - public void setProperty(String path, List object) { + public void setProperty(final String path, final List object) { set(path, new ArrayList(object)); } - public void setProperty(String path, Map object) { + public void setProperty(final String path, final Map object) { set(path, new LinkedHashMap(object)); } - public Object getProperty(String path) { + public Object getProperty(final String path) { return get(path); } @@ -411,21 +382,21 @@ public class EssentialsConf extends YamlConfiguration { set(path, bigDecimal.toString()); } - public void setProperty(String path, Object object) { + public void setProperty(final String path, final Object object) { set(path, object); } - public void removeProperty(String path) { + public void removeProperty(final String path) { set(path, null); } @Override - public synchronized Object get(String path) { + public synchronized Object get(final String path) { return super.get(path); } @Override - public synchronized Object get(String path, Object def) { + public synchronized Object get(final String path, final Object def) { return super.get(path, def); } @@ -434,50 +405,38 @@ public class EssentialsConf extends YamlConfiguration { return toBigDecimal(input, def); } - public static BigDecimal toBigDecimal(final String input, final BigDecimal def) { - if (input == null || input.isEmpty()) { - return def; - } else { - try { - return new BigDecimal(input, MathContext.DECIMAL128); - } catch (NumberFormatException | ArithmeticException e) { - return def; - } - } - } - @Override - public synchronized boolean getBoolean(String path) { + public synchronized boolean getBoolean(final String path) { return super.getBoolean(path); } @Override - public synchronized boolean getBoolean(String path, boolean def) { + public synchronized boolean getBoolean(final String path, final boolean def) { return super.getBoolean(path, def); } @Override - public synchronized List getBooleanList(String path) { + public synchronized List getBooleanList(final String path) { return super.getBooleanList(path); } @Override - public synchronized List getByteList(String path) { + public synchronized List getByteList(final String path) { return super.getByteList(path); } @Override - public synchronized List getCharacterList(String path) { + public synchronized List getCharacterList(final String path) { return super.getCharacterList(path); } @Override - public synchronized ConfigurationSection getConfigurationSection(String path) { + public synchronized ConfigurationSection getConfigurationSection(final String path) { return super.getConfigurationSection(path); } @Override - public synchronized double getDouble(String path) { + public synchronized double getDouble(final String path) { return super.getDouble(path); } @@ -487,52 +446,52 @@ public class EssentialsConf extends YamlConfiguration { } @Override - public synchronized List getDoubleList(String path) { + public synchronized List getDoubleList(final String path) { return super.getDoubleList(path); } @Override - public synchronized List getFloatList(String path) { + public synchronized List getFloatList(final String path) { return super.getFloatList(path); } @Override - public synchronized int getInt(String path) { + public synchronized int getInt(final String path) { return super.getInt(path); } @Override - public synchronized int getInt(String path, int def) { + public synchronized int getInt(final String path, final int def) { return super.getInt(path, def); } @Override - public synchronized List getIntegerList(String path) { + public synchronized List getIntegerList(final String path) { return super.getIntegerList(path); } @Override - public synchronized ItemStack getItemStack(String path, ItemStack def) { + public synchronized ItemStack getItemStack(final String path, final ItemStack def) { return super.getItemStack(path, def); } @Override - public synchronized Set getKeys(boolean deep) { + public synchronized Set getKeys(final boolean deep) { return super.getKeys(deep); } @Override - public synchronized List getList(String path) { + public synchronized List getList(final String path) { return super.getList(path); } @Override - public synchronized List getList(String path, List def) { + public synchronized List getList(final String path, final List def) { return super.getList(path, def); } @Override - public synchronized long getLong(String path) { + public synchronized long getLong(final String path) { return super.getLong(path); } @@ -542,7 +501,7 @@ public class EssentialsConf extends YamlConfiguration { } @Override - public synchronized List getLongList(String path) { + public synchronized List getLongList(final String path) { return super.getLongList(path); } @@ -551,112 +510,165 @@ public class EssentialsConf extends YamlConfiguration { } @Override - public synchronized List> getMapList(String path) { + public synchronized List> getMapList(final String path) { return super.getMapList(path); } @Override - public synchronized OfflinePlayer getOfflinePlayer(String path) { + public synchronized OfflinePlayer getOfflinePlayer(final String path) { return super.getOfflinePlayer(path); } @Override - public synchronized OfflinePlayer getOfflinePlayer(String path, OfflinePlayer def) { + public synchronized OfflinePlayer getOfflinePlayer(final String path, final OfflinePlayer def) { return super.getOfflinePlayer(path, def); } @Override - public synchronized List getShortList(String path) { + public synchronized List getShortList(final String path) { return super.getShortList(path); } @Override - public synchronized String getString(String path) { + public synchronized String getString(final String path) { return super.getString(path); } @Override - public synchronized String getString(String path, String def) { + public synchronized String getString(final String path, final String def) { return super.getString(path, def); } @Override - public synchronized List getStringList(String path) { + public synchronized List getStringList(final String path) { return super.getStringList(path); } @Override - public synchronized Map getValues(boolean deep) { + public synchronized Map getValues(final boolean deep) { return super.getValues(deep); } @Override - public synchronized Vector getVector(String path) { + public synchronized Vector getVector(final String path) { return super.getVector(path); } @Override - public synchronized Vector getVector(String path, Vector def) { + public synchronized Vector getVector(final String path, final Vector def) { return super.getVector(path, def); } @Override - public synchronized boolean isBoolean(String path) { + public synchronized boolean isBoolean(final String path) { return super.isBoolean(path); } @Override - public synchronized boolean isConfigurationSection(String path) { + public synchronized boolean isConfigurationSection(final String path) { return super.isConfigurationSection(path); } @Override - public synchronized boolean isDouble(String path) { + public synchronized boolean isDouble(final String path) { return super.isDouble(path); } @Override - public synchronized boolean isInt(String path) { + public synchronized boolean isInt(final String path) { return super.isInt(path); } @Override - public synchronized boolean isItemStack(String path) { + public synchronized boolean isItemStack(final String path) { return super.isItemStack(path); } @Override - public synchronized boolean isList(String path) { + public synchronized boolean isList(final String path) { return super.isList(path); } @Override - public synchronized boolean isLong(String path) { + public synchronized boolean isLong(final String path) { return super.isLong(path); } @Override - public synchronized boolean isOfflinePlayer(String path) { + public synchronized boolean isOfflinePlayer(final String path) { return super.isOfflinePlayer(path); } @Override - public synchronized boolean isSet(String path) { + public synchronized boolean isSet(final String path) { return super.isSet(path); } @Override - public synchronized boolean isString(String path) { + public synchronized boolean isString(final String path) { return super.isString(path); } @Override - public synchronized boolean isVector(String path) { + public synchronized boolean isVector(final String path) { return super.isVector(path); } @Override - public synchronized void set(String path, Object value) { + public synchronized void set(final String path, final Object value) { super.set(path, value); } + + private static final class WriteRunner implements Runnable { + private final File configFile; + private final String data; + private final AtomicInteger pendingDiskWrites; + + private WriteRunner(final File configFile, final String data, final AtomicInteger pendingDiskWrites) { + this.configFile = configFile; + this.data = data; + this.pendingDiskWrites = pendingDiskWrites; + } + + @Override + public void run() { + //long startTime = System.nanoTime(); + synchronized (configFile) { + if (pendingDiskWrites.get() > 1) { + // Writes can be skipped, because they are stored in a queue (in the executor). + // Only the last is actually written. + pendingDiskWrites.decrementAndGet(); + //LOGGER.log(Level.INFO, configFile + " skipped writing in " + (System.nanoTime() - startTime) + " nsec."); + return; + } + try { + Files.createParentDirs(configFile); + + if (!configFile.exists()) { + try { + LOGGER.log(Level.INFO, tl("creatingEmptyConfig", configFile.toString())); + if (!configFile.createNewFile()) { + LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString())); + return; + } + } catch (final IOException ex) { + LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString()), ex); + return; + } + } + + try (final FileOutputStream fos = new FileOutputStream(configFile)) { + try (final OutputStreamWriter writer = new OutputStreamWriter(fos, UTF8)) { + writer.write(data); + } + } + } catch (final IOException e) { + LOGGER.log(Level.SEVERE, e.getMessage(), e); + } finally { + //LOGGER.log(Level.INFO, configFile + " written to disk in " + (System.nanoTime() - startTime) + " nsec."); + pendingDiskWrites.decrementAndGet(); + } + } + } + } } diff --git a/Essentials/src/com/earth2me/essentials/EssentialsEntityListener.java b/Essentials/src/com/earth2me/essentials/EssentialsEntityListener.java index 52e430efa..f0a0068ca 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsEntityListener.java +++ b/Essentials/src/com/earth2me/essentials/EssentialsEntityListener.java @@ -5,12 +5,26 @@ import net.ess3.api.IEssentials; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.*; +import org.bukkit.entity.Ageable; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; 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.EntityCombustByEntityEvent; +import org.bukkit.event.entity.EntityCombustEvent; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityRegainHealthEvent; import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; +import org.bukkit.event.entity.EntityShootBowEvent; +import org.bukkit.event.entity.EntityTargetEvent; +import org.bukkit.event.entity.FoodLevelChangeEvent; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.entity.PotionSplashEvent; import org.bukkit.inventory.ItemStack; import java.util.List; @@ -20,13 +34,12 @@ import java.util.regex.Pattern; import static com.earth2me.essentials.I18n.tl; - public class EssentialsEntityListener implements Listener { private static final Logger LOGGER = Logger.getLogger("Essentials"); private static final transient Pattern powertoolPlayer = Pattern.compile("\\{player\\}"); private final IEssentials ess; - public EssentialsEntityListener(IEssentials ess) { + public EssentialsEntityListener(final IEssentials ess) { this.ess = ess; } @@ -42,7 +55,7 @@ public class EssentialsEntityListener implements Listener { } else if (eDefend instanceof Ageable) { final ItemStack hand = attacker.getBase().getItemInHand(); if (ess.getSettings().isMilkBucketEasterEggEnabled() - && hand != null && hand.getType() == Material.MILK_BUCKET) { + && hand != null && hand.getType() == Material.MILK_BUCKET) { ((Ageable) eDefend).setBaby(); hand.setType(Material.BUCKET); attacker.getBase().setItemInHand(hand); @@ -99,6 +112,7 @@ public class EssentialsEntityListener implements Listener { LOGGER.log(Level.INFO, String.format("[PT] %s issued server command: /%s", attacker.getName(), command)); } } + ess.scheduleSyncDelayedTask(new PowerToolInteractTask()); event.setCancelled(true); @@ -128,9 +142,9 @@ public class EssentialsEntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR) public void onEntityCombustByEntity(final EntityCombustByEntityEvent event) { if (event.getCombuster() instanceof Arrow && event.getEntity() instanceof Player) { - Arrow combuster = (Arrow) event.getCombuster(); + final Arrow combuster = (Arrow) event.getCombuster(); if (combuster.getShooter() instanceof Player) { - Player shooter = (Player) combuster.getShooter(); + final Player shooter = (Player) combuster.getShooter(); if (shooter.hasMetadata("NPC")) { return; } @@ -147,7 +161,7 @@ public class EssentialsEntityListener implements Listener { @EventHandler(priority = EventPriority.LOWEST) public void onPlayerDeathEvent(final PlayerDeathEvent event) { - Entity entity = event.getEntity(); + final Entity entity = event.getEntity(); if (entity.hasMetadata("NPC")) { return; } @@ -180,10 +194,10 @@ public class EssentialsEntityListener implements Listener { if (user.isAuthorized("essentials.keepinv")) { event.setKeepInventory(true); event.getDrops().clear(); - ISettings.KeepInvPolicy vanish = ess.getSettings().getVanishingItemsPolicy(); - ISettings.KeepInvPolicy bind = ess.getSettings().getBindingItemsPolicy(); + final ISettings.KeepInvPolicy vanish = ess.getSettings().getVanishingItemsPolicy(); + final ISettings.KeepInvPolicy bind = ess.getSettings().getBindingItemsPolicy(); if (VersionUtil.getServerBukkitVersion().isHigherThanOrEqualTo(VersionUtil.v1_11_2_R01) && (vanish != ISettings.KeepInvPolicy.KEEP || bind != ISettings.KeepInvPolicy.KEEP)) { - for (ItemStack stack : event.getEntity().getInventory()) { + for (final ItemStack stack : event.getEntity().getInventory()) { if (stack != null) { if (stack.getEnchantments().containsKey(Enchantment.VANISHING_CURSE)) { if (vanish == ISettings.KeepInvPolicy.DELETE) { @@ -203,9 +217,9 @@ public class EssentialsEntityListener implements Listener { } } } - ItemStack[] armor = event.getEntity().getInventory().getArmorContents(); + final ItemStack[] armor = event.getEntity().getInventory().getArmorContents(); for (int i = 0; i < armor.length; i++) { - ItemStack stack = armor[i]; + final ItemStack stack = armor[i]; if (stack != null) { if (stack.getEnchantments().containsKey(Enchantment.VANISHING_CURSE)) { if (vanish == ISettings.KeepInvPolicy.DELETE) { @@ -257,7 +271,7 @@ public class EssentialsEntityListener implements Listener { @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onPotionSplashEvent(final PotionSplashEvent event) { - for (LivingEntity entity : event.getAffectedEntities()) { + for (final LivingEntity entity : event.getAffectedEntities()) { if (entity instanceof Player && ess.getUser((Player) entity).isGodModeEnabled()) { event.setIntensity(entity, 0d); } @@ -265,7 +279,7 @@ public class EssentialsEntityListener implements Listener { } @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onEntityShootBow(EntityShootBowEvent event) { + public void onEntityShootBow(final EntityShootBowEvent event) { if (event.getEntity() instanceof Player) { final User user = ess.getUser((Player) event.getEntity()); if (user.isAfk()) { @@ -275,7 +289,7 @@ public class EssentialsEntityListener implements Listener { } @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onEntityTarget(EntityTargetEvent event) { + public void onEntityTarget(final EntityTargetEvent event) { if (event.getTarget() instanceof Player) { final User user = ess.getUser((Player) event.getTarget()); if (user.isVanished()) { diff --git a/Essentials/src/com/earth2me/essentials/EssentialsPlayerListener.java b/Essentials/src/com/earth2me/essentials/EssentialsPlayerListener.java index 58e999aaf..77e784dfe 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsPlayerListener.java +++ b/Essentials/src/com/earth2me/essentials/EssentialsPlayerListener.java @@ -12,7 +12,12 @@ import com.earth2me.essentials.utils.VersionUtil; import io.papermc.lib.PaperLib; import net.ess3.api.IEssentials; import net.ess3.api.events.AfkStatusChangeEvent; -import org.bukkit.*; +import org.bukkit.BanEntry; +import org.bukkit.BanList; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; import org.bukkit.command.PluginCommand; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; @@ -23,8 +28,21 @@ import org.bukkit.event.inventory.ClickType; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryType; -import org.bukkit.event.player.*; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.PlayerBucketEmptyEvent; +import org.bukkit.event.player.PlayerChangedWorldEvent; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.player.PlayerCommandSendEvent; +import org.bukkit.event.player.PlayerEggThrowEvent; +import org.bukkit.event.player.PlayerFishEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerLoginEvent.Result; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; @@ -34,15 +52,21 @@ import org.bukkit.inventory.PlayerInventory; import java.io.IOException; import java.lang.management.ManagementFactory; import java.text.NumberFormat; -import java.util.*; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; import java.util.Map.Entry; +import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import static com.earth2me.essentials.I18n.tl; - public class EssentialsPlayerListener implements Listener { private static final Logger LOGGER = Logger.getLogger("Essentials"); private final transient IEssentials ess; @@ -55,7 +79,7 @@ public class EssentialsPlayerListener implements Listener { try { Class.forName("org.bukkit.event.entity.EntityPickupItemEvent"); return true; - } catch (ClassNotFoundException ignored) { + } catch (final ClassNotFoundException ignored) { return false; } } @@ -64,7 +88,7 @@ public class EssentialsPlayerListener implements Listener { try { Class.forName("org.bukkit.event.player.PlayerCommandSendEvent"); return true; - } catch (ClassNotFoundException ignored) { + } catch (final ClassNotFoundException ignored) { return false; } } @@ -73,7 +97,7 @@ public class EssentialsPlayerListener implements Listener { try { Class.forName("org.bukkit.event.player.PlayerPickupArrowEvent"); return true; - } catch (ClassNotFoundException ignored) { + } catch (final ClassNotFoundException ignored) { return false; } } @@ -113,7 +137,7 @@ public class EssentialsPlayerListener implements Listener { if (user.isMuted()) { event.setCancelled(true); - String dateDiff = user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : null; + final String dateDiff = user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : null; if (dateDiff == null) { user.sendMessage(user.hasMuteReason() ? tl("voiceSilencedReason", user.getMuteReason()) : tl("voiceSilenced")); } else { @@ -130,7 +154,7 @@ public class EssentialsPlayerListener implements Listener { it.remove(); } } - } catch (UnsupportedOperationException ex) { + } catch (final UnsupportedOperationException ex) { if (ess.getSettings().isDebug()) { ess.getLogger().log(Level.INFO, "Ignore could not block chat due to custom chat plugin event.", ex); } else { @@ -172,7 +196,7 @@ public class EssentialsPlayerListener implements Listener { to.setZ(from.getZ()); try { event.setTo(LocationUtil.getSafeDestination(to)); - } catch (Exception ex) { + } catch (final Exception ex) { event.setTo(to); } return; @@ -192,10 +216,10 @@ public class EssentialsPlayerListener implements Listener { } else if (ess.getSettings().isCustomQuitMessage() && event.getQuitMessage() != null) { final Player player = event.getPlayer(); final String msg = ess.getSettings().getCustomQuitMessage() - .replace("{PLAYER}", player.getDisplayName()) - .replace("{USERNAME}", player.getName()) - .replace("{ONLINE}", NumberFormat.getInstance().format(ess.getOnlinePlayers().size())) - .replace("{UPTIME}", DateUtil.formatDateDiff(ManagementFactory.getRuntimeMXBean().getStartTime())); + .replace("{PLAYER}", player.getDisplayName()) + .replace("{USERNAME}", player.getName()) + .replace("{ONLINE}", NumberFormat.getInstance().format(ess.getOnlinePlayers().size())) + .replace("{UPTIME}", DateUtil.formatDateDiff(ManagementFactory.getRuntimeMXBean().getStartTime())); event.setQuitMessage(msg.isEmpty() ? null : msg); } @@ -212,10 +236,10 @@ public class EssentialsPlayerListener implements Listener { user.getBase().getOpenInventory().getTopInventory().clear(); } - ArrayList viewers = new ArrayList<>(user.getBase().getInventory().getViewers()); - for (HumanEntity viewer : viewers) { + final ArrayList viewers = new ArrayList<>(user.getBase().getInventory().getViewers()); + for (final HumanEntity viewer : viewers) { if (viewer instanceof Player) { - User uviewer = ess.getUser((Player) viewer); + final User uviewer = ess.getUser((Player) viewer); if (uviewer.isInvSee()) { uviewer.getBase().closeInventory(); } @@ -280,8 +304,8 @@ public class EssentialsPlayerListener implements Listener { updateCompass(user); if (!ess.getVanishedPlayersNew().isEmpty() && !user.isAuthorized("essentials.vanish.see")) { - for (String p : ess.getVanishedPlayersNew()) { - Player toVanish = ess.getServer().getPlayerExact(p); + for (final String p : ess.getVanishedPlayersNew()) { + final Player toVanish = ess.getServer().getPlayerExact(p); if (toVanish != null && toVanish.isOnline()) { user.getBase().hidePlayer(toVanish); if (ess.getSettings().isDebug()) { @@ -302,11 +326,11 @@ public class EssentialsPlayerListener implements Listener { } else if (message == null || hideJoinQuitMessages()) { //NOOP } else if (ess.getSettings().isCustomJoinMessage()) { - String msg = ess.getSettings().getCustomJoinMessage() - .replace("{PLAYER}", player.getDisplayName()).replace("{USERNAME}", player.getName()) - .replace("{UNIQUE}", NumberFormat.getInstance().format(ess.getUserMap().getUniqueUsers())) - .replace("{ONLINE}", NumberFormat.getInstance().format(ess.getOnlinePlayers().size())) - .replace("{UPTIME}", DateUtil.formatDateDiff(ManagementFactory.getRuntimeMXBean().getStartTime())); + final String msg = ess.getSettings().getCustomJoinMessage() + .replace("{PLAYER}", player.getDisplayName()).replace("{USERNAME}", player.getName()) + .replace("{UNIQUE}", NumberFormat.getInstance().format(ess.getUserMap().getUniqueUsers())) + .replace("{ONLINE}", NumberFormat.getInstance().format(ess.getOnlinePlayers().size())) + .replace("{UPTIME}", DateUtil.formatDateDiff(ManagementFactory.getRuntimeMXBean().getStartTime())); if (!msg.isEmpty()) { ess.getServer().broadcastMessage(msg); } @@ -314,8 +338,8 @@ public class EssentialsPlayerListener implements Listener { ess.getServer().broadcastMessage(message); } - int motdDelay = ess.getSettings().getMotdDelay() / 50; - DelayMotdTask motdTask = new DelayMotdTask(user); + final int motdDelay = ess.getSettings().getMotdDelay() / 50; + final DelayMotdTask motdTask = new DelayMotdTask(user); if (motdDelay > 0) { ess.scheduleSyncDelayedTask(motdTask, motdDelay); } else { @@ -368,7 +392,7 @@ public class EssentialsPlayerListener implements Listener { class DelayMotdTask implements Runnable { private final User user; - public DelayMotdTask(User user) { + DelayMotdTask(final User user) { this.user = user; } @@ -379,7 +403,7 @@ public class EssentialsPlayerListener implements Listener { if (!ess.getSettings().isCommandDisabled("motd")) { try { tempInput = new TextInput(user.getSource(), "motd", true, ess); - } catch (IOException ex) { + } catch (final IOException ex) { if (ess.getSettings().isDebug()) { LOGGER.log(Level.WARNING, ex.getMessage(), ex); } else { @@ -407,7 +431,7 @@ public class EssentialsPlayerListener implements Listener { private void updateCompass(final User user) { if (ess.getSettings().isCompassTowardsHomePerm() && !user.isAuthorized("essentials.home.compass")) return; - Location loc = user.getHome(user.getLocation()); + final Location loc = user.getHome(user.getLocation()); if (loc == null) { PaperLib.getBedSpawnLocationAsync(user.getBase(), false).thenAccept(location -> { if (location != null) { @@ -421,42 +445,34 @@ public class EssentialsPlayerListener implements Listener { @EventHandler(priority = EventPriority.LOW) public void onPlayerLoginBanned(final PlayerLoginEvent event) { - switch (event.getResult()) { - case KICK_BANNED: - BanEntry banEntry = ess.getServer().getBanList(BanList.Type.NAME).getBanEntry(event.getPlayer().getName()); - if (banEntry != null) { - Date banExpiry = banEntry.getExpiration(); - if (banExpiry != null) { - String expiry = DateUtil.formatDateDiff(banExpiry.getTime()); - event.setKickMessage(tl("tempbanJoin", expiry, banEntry.getReason())); - } else { - event.setKickMessage(tl("banJoin", banEntry.getReason())); - } + if (event.getResult() == Result.KICK_BANNED) { + BanEntry banEntry = ess.getServer().getBanList(BanList.Type.NAME).getBanEntry(event.getPlayer().getName()); + if (banEntry != null) { + final Date banExpiry = banEntry.getExpiration(); + if (banExpiry != null) { + final String expiry = DateUtil.formatDateDiff(banExpiry.getTime()); + event.setKickMessage(tl("tempbanJoin", expiry, banEntry.getReason())); } else { - banEntry = ess.getServer().getBanList(BanList.Type.IP).getBanEntry(event.getAddress().getHostAddress()); - if (banEntry != null) { - event.setKickMessage(tl("banIpJoin", banEntry.getReason())); - } + event.setKickMessage(tl("banJoin", banEntry.getReason())); } - break; - default: - break; + } else { + banEntry = ess.getServer().getBanList(BanList.Type.IP).getBanEntry(event.getAddress().getHostAddress()); + if (banEntry != null) { + event.setKickMessage(tl("banIpJoin", banEntry.getReason())); + } + } } } @EventHandler(priority = EventPriority.HIGH) public void onPlayerLogin(final PlayerLoginEvent event) { - switch (event.getResult()) { - case KICK_FULL: - final User kfuser = ess.getUser(event.getPlayer()); - if (kfuser.isAuthorized("essentials.joinfullserver")) { - event.allow(); - return; - } - event.disallow(Result.KICK_FULL, tl("serverFull")); - break; - default: - break; + if (event.getResult() == Result.KICK_FULL) { + final User kfuser = ess.getUser(event.getPlayer()); + if (kfuser.isAuthorized("essentials.joinfullserver")) { + event.allow(); + return; + } + event.disallow(Result.KICK_FULL, tl("serverFull")); } } @@ -465,10 +481,10 @@ public class EssentialsPlayerListener implements Listener { final boolean backListener = ess.getSettings().registerBackInListener(); final boolean teleportInvulnerability = ess.getSettings().isTeleportInvulnerability(); if (backListener || teleportInvulnerability) { - Player player = event.getPlayer(); - if (player.hasMetadata("NPC")) { - return; - } + final Player player = event.getPlayer(); + if (player.hasMetadata("NPC")) { + return; + } final User user = ess.getUser(player); //There is TeleportCause.COMMMAND but plugins have to actively pass the cause in on their teleports. if (user.isAuthorized("essentials.back.onteleport") && backListener && (event.getCause() == TeleportCause.PLUGIN || event.getCause() == TeleportCause.COMMAND)) { @@ -504,14 +520,14 @@ public class EssentialsPlayerListener implements Listener { final Player player = event.getPlayer(); final String cmd = event.getMessage().toLowerCase(Locale.ENGLISH).split(" ")[0].replace("/", "").toLowerCase(Locale.ENGLISH); - PluginCommand pluginCommand = ess.getServer().getPluginCommand(cmd); + final PluginCommand pluginCommand = ess.getServer().getPluginCommand(cmd); if (ess.getSettings().getSocialSpyCommands().contains(cmd) || ess.getSettings().getSocialSpyCommands().contains("*")) { if (pluginCommand == null - || (!pluginCommand.getName().equals("msg") && !pluginCommand.getName().equals("r"))) { // /msg and /r are handled in SimpleMessageRecipient - User user = ess.getUser(player); + || (!pluginCommand.getName().equals("msg") && !pluginCommand.getName().equals("r"))) { // /msg and /r are handled in SimpleMessageRecipient + final User user = ess.getUser(player); if (!user.isAuthorized("essentials.chat.spy.exempt")) { - for (User spyer : ess.getOnlineUsers()) { + for (final User spyer : ess.getOnlineUsers()) { if (spyer.isSocialSpyEnabled() && !player.equals(spyer.getBase())) { if (user.isMuted() && ess.getSettings().getSocialSpyListenMutedPlayers()) { spyer.sendMessage(tl("socialSpyMutedPrefix") + player.getDisplayName() + ": " + event.getMessage()); @@ -527,7 +543,7 @@ public class EssentialsPlayerListener implements Listener { final User user = ess.getUser(player); if (user.isMuted() && (ess.getSettings().getMuteCommands().contains(cmd) || ess.getSettings().getMuteCommands().contains("*"))) { event.setCancelled(true); - String dateDiff = user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : null; + final String dateDiff = user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : null; if (dateDiff == null) { player.sendMessage(user.hasMuteReason() ? tl("voiceSilencedReason", user.getMuteReason()) : tl("voiceSilenced")); } else { @@ -545,8 +561,10 @@ public class EssentialsPlayerListener implements Listener { switch (pluginCommand.getName()) { case "afk": update = false; + // fall through case "vanish": broadcast = false; + break; } } @@ -555,18 +573,18 @@ public class EssentialsPlayerListener implements Listener { } if (ess.getSettings().isCommandCooldownsEnabled() && pluginCommand != null - && !user.isAuthorized("essentials.commandcooldowns.bypass")) { - int argStartIndex = event.getMessage().indexOf(" "); - String args = argStartIndex == -1 ? "" // No arguments present - : " " + event.getMessage().substring(argStartIndex); // arguments start at argStartIndex; substring from there. - String fullCommand = pluginCommand.getName() + args; + && !user.isAuthorized("essentials.commandcooldowns.bypass")) { + final int argStartIndex = event.getMessage().indexOf(" "); + final String args = argStartIndex == -1 ? "" // No arguments present + : " " + event.getMessage().substring(argStartIndex); // arguments start at argStartIndex; substring from there. + final String fullCommand = pluginCommand.getName() + args; // Used to determine whether a user already has an existing cooldown // If so, no need to check for (and write) new ones. boolean cooldownFound = false; // Iterate over a copy of getCommandCooldowns in case of concurrent modifications - for (Entry entry : new HashMap<>(user.getCommandCooldowns()).entrySet()) { + for (final Entry entry : new HashMap<>(user.getCommandCooldowns()).entrySet()) { // Remove any expired cooldowns if (entry.getValue() <= System.currentTimeMillis()) { user.clearCommandCooldown(entry.getKey()); @@ -574,7 +592,7 @@ public class EssentialsPlayerListener implements Listener { } else if (entry.getKey().matcher(fullCommand).matches()) { // User's current cooldown hasn't expired, inform and terminate cooldown code. if (entry.getValue() > System.currentTimeMillis()) { - String commandCooldownTime = DateUtil.formatDateDiff(entry.getValue()); + final String commandCooldownTime = DateUtil.formatDateDiff(entry.getValue()); user.sendMessage(tl("commandCooldown", commandCooldownTime)); cooldownFound = true; event.setCancelled(true); @@ -584,13 +602,13 @@ public class EssentialsPlayerListener implements Listener { } if (!cooldownFound) { - Entry cooldownEntry = ess.getSettings().getCommandCooldownEntry(fullCommand); + final Entry cooldownEntry = ess.getSettings().getCommandCooldownEntry(fullCommand); if (cooldownEntry != null) { if (ess.getSettings().isDebug()) { ess.getLogger().info("Applying " + cooldownEntry.getValue() + "ms cooldown on /" + fullCommand + " for" + user.getName() + "."); } - Date expiry = new Date(System.currentTimeMillis() + cooldownEntry.getValue()); + final Date expiry = new Date(System.currentTimeMillis() + cooldownEntry.getValue()); user.addCommandCooldown(cooldownEntry.getKey(), expiry, ess.getSettings().isCommandCooldownPersistent(fullCommand)); } } @@ -603,9 +621,9 @@ public class EssentialsPlayerListener implements Listener { if (ess.getSettings().isWorldChangeFlyResetEnabled()) { if (user.getBase().getGameMode() != GameMode.CREATIVE - // COMPAT: String compare for 1.7.10 - && !user.getBase().getGameMode().name().equals("SPECTATOR") - && !user.isAuthorized("essentials.fly")) { + // COMPAT: String compare for 1.7.10 + && !user.getBase().getGameMode().name().equals("SPECTATOR") + && !user.isAuthorized("essentials.fly")) { user.getBase().setFallDistance(0f); user.getBase().setAllowFlight(false); } @@ -656,7 +674,7 @@ public class EssentialsPlayerListener implements Listener { switch (event.getAction()) { case RIGHT_CLICK_BLOCK: if (!event.isCancelled() && MaterialUtil.isBed(event.getClickedBlock().getType()) && ess.getSettings().getUpdateBedAtDaytime()) { - User player = ess.getUser(event.getPlayer()); + final User player = ess.getUser(event.getPlayer()); if (player.isAuthorized("essentials.sethome.bed") && player.getWorld().getEnvironment().equals(World.Environment.NORMAL)) { player.getBase().setBedSpawnLocation(event.getClickedBlock().getLocation()); // In 1.15 and above, vanilla sends its own bed spawn message. @@ -674,6 +692,7 @@ public class EssentialsPlayerListener implements Listener { break; } } + // fall through case LEFT_CLICK_BLOCK: if (event.getItem() != null && event.getItem().getType() != Material.AIR) { final User user = ess.getUser(event.getPlayer()); @@ -702,7 +721,7 @@ public class EssentialsPlayerListener implements Listener { class DelayedClickJumpTask implements Runnable { @Override public void run() { - Location loc = user.getLocation(); + final Location loc = user.getLocation(); loc.setX(otarget.getX()); loc.setZ(otarget.getZ()); while (LocationUtil.isBlockDamaging(loc.getWorld(), loc.getBlockX(), loc.getBlockY() - 1, loc.getBlockZ())) { @@ -711,8 +730,9 @@ public class EssentialsPlayerListener implements Listener { PaperLib.teleportAsync(user.getBase(), loc, TeleportCause.PLUGIN); } } + ess.scheduleSyncDelayedTask(new DelayedClickJumpTask()); - } catch (Exception ex) { + } catch (final Exception ex) { if (ess.getSettings().isDebug()) { LOGGER.log(Level.WARNING, ex.getMessage(), ex); } @@ -741,6 +761,7 @@ public class EssentialsPlayerListener implements Listener { LOGGER.log(Level.INFO, String.format("[PT] %s issued server command: /%s", user.getName(), command)); } } + ess.scheduleSyncDelayedTask(new PowerToolUseTask()); } @@ -773,12 +794,12 @@ public class EssentialsPlayerListener implements Listener { } } else if (type == InventoryType.ENDER_CHEST) { final User user = ess.getUser((Player) event.getWhoClicked()); - if (user.isEnderSee() && (!user.isAuthorized("essentials.enderchest.modify"))) { + if (user.isEnderSee() && !user.isAuthorized("essentials.enderchest.modify")) { event.setCancelled(true); refreshPlayer = user.getBase(); } } else if (type == InventoryType.WORKBENCH) { - User user = ess.getUser((Player) event.getWhoClicked()); + final User user = ess.getUser((Player) event.getWhoClicked()); if (user.isRecipeSee()) { event.setCancelled(true); refreshPlayer = user.getBase(); @@ -792,9 +813,9 @@ public class EssentialsPlayerListener implements Listener { } } else if (clickedInventory != null && clickedInventory.getType() == InventoryType.PLAYER) { if (ess.getSettings().isDirectHatAllowed() && event.getClick() == ClickType.LEFT && event.getSlot() == 39 - && event.getCursor().getType() != Material.AIR && event.getCursor().getType().getMaxDurability() == 0 - && !MaterialUtil.isSkull(event.getCursor().getType()) - && ess.getUser(event.getWhoClicked()).isAuthorized("essentials.hat") && !ess.getUser(event.getWhoClicked()).isAuthorized("essentials.hat.prevent-type." + event.getCursor().getType().name().toLowerCase())) { + && event.getCursor().getType() != Material.AIR && event.getCursor().getType().getMaxDurability() == 0 + && !MaterialUtil.isSkull(event.getCursor().getType()) + && ess.getUser(event.getWhoClicked()).isAuthorized("essentials.hat") && !ess.getUser(event.getWhoClicked()).isAuthorized("essentials.hat.prevent-type." + event.getCursor().getType().name().toLowerCase())) { event.setCancelled(true); final PlayerInventory inv = (PlayerInventory) clickedInventory; final ItemStack head = inv.getHelmet(); @@ -848,7 +869,7 @@ public class EssentialsPlayerListener implements Listener { user.updateActivityOnInteract(true); } - private final class ArrowPickupListener implements Listener { + private static final class ArrowPickupListener implements Listener { @EventHandler(priority = EventPriority.LOW) public void onArrowPickup(final org.bukkit.event.player.PlayerPickupArrowEvent event) { if (event.getItem().hasMetadata(Commandfireball.FIREBALL_META_KEY)) { @@ -884,14 +905,14 @@ public class EssentialsPlayerListener implements Listener { private final class CommandSendListener implements Listener { @EventHandler(priority = EventPriority.NORMAL) public void onCommandSend(final PlayerCommandSendEvent event) { - User user = ess.getUser(event.getPlayer()); + final User user = ess.getUser(event.getPlayer()); - Set checked = new HashSet<>(); - Set toRemove = new HashSet<>(); + final Set checked = new HashSet<>(); + final Set toRemove = new HashSet<>(); event.getCommands().removeIf(label -> { if (isEssentialsCommand(label)) { - PluginCommand command = ess.getServer().getPluginCommand(label); + final PluginCommand command = ess.getServer().getPluginCommand(label); if (!checked.contains(command)) { checked.add(command); if (!user.isAuthorized(command.getName().equals("r") ? "essentials.msg" : "essentials." + command.getName())) { @@ -914,12 +935,12 @@ public class EssentialsPlayerListener implements Listener { * - The plugin command is from a plugin in an essentials-controlled package * - There is no known alternative OR the alternative is overridden by Essentials */ - private boolean isEssentialsCommand(String label) { - PluginCommand command = ess.getServer().getPluginCommand(label); + private boolean isEssentialsCommand(final String label) { + final PluginCommand command = ess.getServer().getPluginCommand(label); return command != null - && (command.getPlugin() == ess || command.getPlugin().getClass().getName().startsWith("com.earth2me.essentials")) - && (ess.getSettings().isCommandOverridden(label) || (ess.getAlternativeCommandsHandler().getAlternative(label) == null)); + && (command.getPlugin() == ess || command.getPlugin().getClass().getName().startsWith("com.earth2me.essentials")) + && (ess.getSettings().isCommandOverridden(label) || (ess.getAlternativeCommandsHandler().getAlternative(label) == null)); } } } diff --git a/Essentials/src/com/earth2me/essentials/EssentialsPluginListener.java b/Essentials/src/com/earth2me/essentials/EssentialsPluginListener.java index ddda2343f..93c9abb1f 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsPluginListener.java +++ b/Essentials/src/com/earth2me/essentials/EssentialsPluginListener.java @@ -10,7 +10,6 @@ import org.bukkit.event.server.PluginEnableEvent; import java.util.logging.Level; - public class EssentialsPluginListener implements Listener, IConf { private final transient IEssentials ess; @@ -27,7 +26,7 @@ public class EssentialsPluginListener implements Listener, IConf { ess.getPermissionsHandler().checkPermissions(); ess.getAlternativeCommandsHandler().addPlugin(event.getPlugin()); if (!Methods.hasMethod() && Methods.setMethod(ess.getServer().getPluginManager())) { - ess.getLogger().log(Level.INFO, "Payment method found (" + Methods.getMethod().getLongName() + " version: " + ess.getPaymentMethod().getMethod().getVersion() + ")"); + ess.getLogger().log(Level.INFO, "Payment method found (" + Methods.getMethod().getLongName() + " version: " + Methods.getMethod().getVersion() + ")"); } } @@ -39,7 +38,7 @@ public class EssentialsPluginListener implements Listener, IConf { ess.getPermissionsHandler().checkPermissions(); ess.getAlternativeCommandsHandler().removePlugin(event.getPlugin()); // Check to see if the plugin thats being disabled is the one we are using - if (ess.getPaymentMethod() != null && Methods.hasMethod() && Methods.checkDisabled(event.getPlugin())) { + if (Methods.hasMethod() && Methods.checkDisabled(event.getPlugin())) { Methods.reset(); ess.getLogger().log(Level.INFO, "Payment method was disabled. No longer accepting payments."); } diff --git a/Essentials/src/com/earth2me/essentials/EssentialsServerListener.java b/Essentials/src/com/earth2me/essentials/EssentialsServerListener.java index bcc13effd..419f025dd 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsServerListener.java +++ b/Essentials/src/com/earth2me/essentials/EssentialsServerListener.java @@ -15,7 +15,6 @@ import java.util.Iterator; import java.util.List; import java.util.logging.Level; - public class EssentialsServerListener implements Listener { private static final List ignoredSLPECallers = Arrays.asList( ".LegacyPingHandler.channelRead(", // CB responding to pings from pre-Netty clients @@ -24,9 +23,9 @@ public class EssentialsServerListener implements Listener { ); private final transient IEssentials ess; + private final boolean isPaperSample; private boolean unsupportedLogged = false; private boolean npeWarned = false; - private final boolean isPaperSample; private Method setSampleText; private Method getSampleText; @@ -52,34 +51,34 @@ public class EssentialsServerListener implements Listener { public void onServerListPing(final ServerListPingEvent event) throws Exception { if (isPaperSample) { try { - List playerNames = (List) getSampleText.invoke(event, null); + final List playerNames = (List) getSampleText.invoke(event, null); playerNames.removeIf(player -> ess.getUser(player).isVanished()); setSampleText.invoke(event, playerNames); - } catch (IllegalAccessException | InvocationTargetException | ClassCastException e) { + } catch (final IllegalAccessException | InvocationTargetException | ClassCastException e) { if (!unsupportedLogged && shouldWarnSLPECaller(e)) { ess.getLogger().log(Level.WARNING, "Unable to hide players from server list ping " - + "using Paper 1.12 method!", e); + + "using Paper 1.12 method!", e); unsupportedLogged = true; } - } catch (NullPointerException e) { + } catch (final NullPointerException e) { if (!npeWarned && shouldWarnSLPECaller(e)) { npeWarned = true; - Exception ex = new Exception("A plugin has fired a ServerListPingEvent " - + "without implementing Paper's methods. Point the author to https://git.io/v7Xzl."); + final Exception ex = new Exception("A plugin has fired a ServerListPingEvent " + + "without implementing Paper's methods. Point the author to https://git.io/v7Xzl."); ex.setStackTrace(e.getStackTrace()); throw ex; } } } else { try { - Iterator iterator = event.iterator(); + final Iterator iterator = event.iterator(); while (iterator.hasNext()) { - Player player = iterator.next(); + final Player player = iterator.next(); if (ess.getUser(player).isVanished()) { iterator.remove(); } } - } catch (UnsupportedOperationException e) { + } catch (final UnsupportedOperationException e) { if (!unsupportedLogged && shouldWarnSLPECaller(e)) { ess.getLogger().log(Level.WARNING, "Could not hide vanished players while handling " + event.getClass().getName(), e); unsupportedLogged = true; @@ -96,16 +95,16 @@ public class EssentialsServerListener implements Listener { * @param throwable A throwable caught by a catch block * @return Whether or not to send a warning about this particular caller */ - private boolean shouldWarnSLPECaller(Throwable throwable) { + private boolean shouldWarnSLPECaller(final Throwable throwable) { final int maxStackDepth = 20; // Limit the depth when searching through the stack trace int depth = 0; - for (StackTraceElement element : throwable.getStackTrace()) { + for (final StackTraceElement element : throwable.getStackTrace()) { depth++; if (depth > maxStackDepth) { break; } - for (String ignoredString : ignoredSLPECallers) { + for (final String ignoredString : ignoredSLPECallers) { if (element.toString().contains(ignoredString)) { return false; // We know about this error and should ignore it, so don't warn } diff --git a/Essentials/src/com/earth2me/essentials/EssentialsTimer.java b/Essentials/src/com/earth2me/essentials/EssentialsTimer.java index 6e56ab918..ef311aa81 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsTimer.java +++ b/Essentials/src/com/earth2me/essentials/EssentialsTimer.java @@ -3,19 +3,24 @@ package com.earth2me.essentials; import net.ess3.api.IEssentials; import org.bukkit.entity.Player; -import java.util.*; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.Set; +import java.util.UUID; import java.util.logging.Level; - public class EssentialsTimer implements Runnable { private final transient IEssentials ess; private final transient Set onlineUsers = new HashSet<>(); // Field is necessary for hidden users - private transient long lastPoll = System.nanoTime(); private final LinkedList history = new LinkedList<>(); + @SuppressWarnings("FieldCanBeLocal") + private final long maxTime = 10 * 1000000; + @SuppressWarnings("FieldCanBeLocal") + private final long tickInterval = 50; + private transient long lastPoll = System.nanoTime(); private int skip1 = 0; private int skip2 = 0; - private final long maxTime = 10 * 1000000; - private final long tickInterval = 50; EssentialsTimer(final IEssentials ess) { this.ess = ess; @@ -33,13 +38,13 @@ public class EssentialsTimer implements Runnable { if (history.size() > 10) { history.remove(); } - double tps = tickInterval * 1000000.0 / timeSpent; + final double tps = tickInterval * 1000000.0 / timeSpent; if (tps <= 21) { history.add(tps); } lastPoll = startTime; int count = 0; - for (Player player : ess.getOnlinePlayers()) { + for (final Player player : ess.getOnlinePlayers()) { count++; if (skip1 > 0) { skip1--; @@ -56,7 +61,7 @@ public class EssentialsTimer implements Runnable { onlineUsers.add(user.getBase().getUniqueId()); user.setLastOnlineActivity(currentTime); user.checkActivity(); - } catch (Exception e) { + } catch (final Exception e) { ess.getLogger().log(Level.WARNING, "EssentialsTimer Error:", e); } } @@ -96,7 +101,7 @@ public class EssentialsTimer implements Runnable { public double getAverageTPS() { double avg = 0; - for (Double f : history) { + for (final Double f : history) { if (f != null) { avg += f; } diff --git a/Essentials/src/com/earth2me/essentials/EssentialsUpgrade.java b/Essentials/src/com/earth2me/essentials/EssentialsUpgrade.java index 479da4e94..7c3b5b84f 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsUpgrade.java +++ b/Essentials/src/com/earth2me/essentials/EssentialsUpgrade.java @@ -14,12 +14,29 @@ import org.bukkit.Location; import org.bukkit.World; import org.bukkit.configuration.ConfigurationSection; -import java.io.*; +import java.io.BufferedInputStream; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileFilter; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; import java.math.BigInteger; import java.security.DigestInputStream; import java.security.MessageDigest; import java.text.DecimalFormat; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; @@ -27,9 +44,13 @@ import java.util.regex.Pattern; import static com.earth2me.essentials.I18n.tl; - public class EssentialsUpgrade { private final static Logger LOGGER = Logger.getLogger("Essentials"); + private static final FileFilter YML_FILTER = pathname -> pathname.isFile() && pathname.getName().endsWith(".yml"); + private static final String PATTERN_CONFIG_UUID_REGEX = "(?mi)^uuid:\\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\\s*$"; + private static final Pattern PATTERN_CONFIG_UUID = Pattern.compile(PATTERN_CONFIG_UUID_REGEX); + private static final String PATTERN_CONFIG_NAME_REGEX = "(?mi)^lastAccountName:\\s*[\"\']?(\\w+)[\"\']?\\s*$"; + private static final Pattern PATTERN_CONFIG_NAME = Pattern.compile(PATTERN_CONFIG_NAME_REGEX); private final transient IEssentials ess; private final transient EssentialsConf doneFile; @@ -42,8 +63,91 @@ public class EssentialsUpgrade { doneFile.load(); } + public static void uuidFileConvert(final IEssentials ess, final Boolean ignoreUFCache) { + ess.getLogger().info("Starting Essentials UUID userdata conversion"); + + final File userdir = new File(ess.getDataFolder(), "userdata"); + if (!userdir.exists()) { + return; + } + + int countFiles = 0; + int countFails = 0; + int countEssCache = 0; + int countBukkit = 0; + + ess.getLogger().info("Found " + userdir.list().length + " files to convert..."); + + for (final String string : userdir.list()) { + if (!string.endsWith(".yml") || string.length() < 5) { + continue; + } + + final int showProgress = countFiles % 250; + + if (showProgress == 0) { + ess.getUserMap().getUUIDMap().forceWriteUUIDMap(); + ess.getLogger().info("Converted " + countFiles + "/" + userdir.list().length); + } + + countFiles++; + + final String name = string.substring(0, string.length() - 4); + final EssentialsUserConf config; + UUID uuid = null; + try { + uuid = UUID.fromString(name); + } catch (final IllegalArgumentException ex) { + final File file = new File(userdir, string); + final EssentialsConf conf = new EssentialsConf(file); + conf.load(); + conf.setProperty("lastAccountName", name); + conf.save(); + + final String uuidConf = ignoreUFCache ? "force-uuid" : "uuid"; + + final String uuidString = conf.getString(uuidConf, null); + + for (int i = 0; i < 4; i++) { + try { + uuid = UUID.fromString(uuidString); + countEssCache++; + break; + } catch (final Exception ex2) { + if (conf.getBoolean("npc", false)) { + uuid = UUID.nameUUIDFromBytes(("NPC:" + name).getBytes(Charsets.UTF_8)); + break; + } + + final org.bukkit.OfflinePlayer player = ess.getServer().getOfflinePlayer(name); + uuid = player.getUniqueId(); + } + + if (uuid != null) { + countBukkit++; + break; + } + } + + if (uuid != null) { + conf.forceSave(); + config = new EssentialsUserConf(name, uuid, new File(userdir, uuid + ".yml")); + config.convertLegacyFile(); + ess.getUserMap().trackUUID(uuid, name, false); + continue; + } + countFails++; + } + } + ess.getUserMap().getUUIDMap().forceWriteUUIDMap(); + + ess.getLogger().info("Converted " + countFiles + "/" + countFiles + ". Conversion complete."); + ess.getLogger().info("Converted via cache: " + countEssCache + " :: Converted via lookup: " + countBukkit + " :: Failed to convert: " + countFails); + ess.getLogger().info("To rerun the conversion type /essentials uuidconvert"); + } + public void convertIgnoreList() { - Pattern pattern = Pattern.compile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"); + final Pattern pattern = Pattern.compile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"); if (doneFile.getBoolean("updateUsersIgnoreListUUID", false)) { return; } @@ -56,7 +160,7 @@ public class EssentialsUpgrade { } final File[] userFiles = userdataFolder.listFiles(); - for (File file : userFiles) { + for (final File file : userFiles) { if (!file.isFile() || !file.getName().endsWith(".yml")) { continue; } @@ -64,8 +168,8 @@ public class EssentialsUpgrade { try { config.load(); if (config.hasProperty("ignore")) { - List migratedIgnores = new ArrayList<>(); - for (String name : Collections.synchronizedList(config.getStringList("ignore"))) { + final List migratedIgnores = new ArrayList<>(); + for (final String name : Collections.synchronizedList(config.getStringList("ignore"))) { if (name == null) { continue; } @@ -73,7 +177,7 @@ public class EssentialsUpgrade { LOGGER.info("Detected already migrated ignore list!"); return; } - User user = ess.getOfflineUser(name); + final User user = ess.getOfflineUser(name); if (user != null && user.getBase() != null) { migratedIgnores.add(user.getBase().getUniqueId().toString()); } @@ -82,7 +186,7 @@ public class EssentialsUpgrade { config.setProperty("ignore", migratedIgnores); config.forceSave(); } - } catch (RuntimeException ex) { + } catch (final RuntimeException ex) { LOGGER.log(Level.INFO, "File: " + file.toString()); throw ex; } @@ -93,23 +197,23 @@ public class EssentialsUpgrade { } public void convertKits() { - Kits kits = ess.getKits(); - EssentialsConf config = kits.getConfig(); + final Kits kits = ess.getKits(); + final EssentialsConf config = kits.getConfig(); if (doneFile.getBoolean("kitsyml", false)) { return; } LOGGER.info("Attempting to convert old kits in config.yml to new kits.yml"); - ConfigurationSection section = ess.getSettings().getKitSection(); + final ConfigurationSection section = ess.getSettings().getKitSection(); if (section == null) { LOGGER.info("No kits found to migrate."); return; } - Map legacyKits = ess.getSettings().getKitSection().getValues(true); + final Map legacyKits = ess.getSettings().getKitSection().getValues(true); - for (Map.Entry entry : legacyKits.entrySet()) { + for (final Map.Entry entry : legacyKits.entrySet()) { LOGGER.info("Converting " + entry.getKey()); config.set("kits." + entry.getKey(), entry.getValue()); } @@ -120,7 +224,7 @@ public class EssentialsUpgrade { LOGGER.info("Done converting kits."); } - private void moveMotdRulesToFile(String name) { + private void moveMotdRulesToFile(final String name) { if (doneFile.getBoolean("move" + name + "ToFile", false)) { return; } @@ -135,26 +239,26 @@ public class EssentialsUpgrade { } final EssentialsConf conf = new EssentialsConf(configFile); conf.load(); - List lines = conf.getStringList(name); + final List lines = conf.getStringList(name); if (lines != null && !lines.isEmpty()) { if (!file.createNewFile()) { throw new IOException("Failed to create file " + file); } - PrintWriter writer = new PrintWriter(file); + final PrintWriter writer = new PrintWriter(file); - for (String line : lines) { + for (final String line : lines) { writer.println(line); } writer.close(); } doneFile.setProperty("move" + name + "ToFile", true); doneFile.save(); - } catch (IOException e) { + } catch (final IOException e) { LOGGER.log(Level.SEVERE, tl("upgradingFilesError"), e); } } - private void removeLinesFromConfig(File file, String regex, String info) throws Exception { + private void removeLinesFromConfig(final File file, final String regex, final String info) throws Exception { boolean needUpdate = false; final BufferedReader bReader = new BufferedReader(new FileReader(file)); final File tempFile = File.createTempFile("essentialsupgrade", ".tmp.yml", ess.getDataFolder()); @@ -205,7 +309,7 @@ public class EssentialsUpgrade { } final File[] userFiles = userdataFolder.listFiles(); - for (File file : userFiles) { + for (final File file : userFiles) { if (!file.isFile() || !file.getName().endsWith(".yml")) { continue; } @@ -217,16 +321,16 @@ public class EssentialsUpgrade { if (powertools == null) { continue; } - for (Map.Entry entry : powertools.entrySet()) { + for (final Map.Entry entry : powertools.entrySet()) { if (entry.getValue() instanceof String) { - List temp = new ArrayList<>(); + final List temp = new ArrayList<>(); temp.add((String) entry.getValue()); powertools.put(entry.getKey(), temp); } } config.forceSave(); } - } catch (RuntimeException ex) { + } catch (final RuntimeException ex) { LOGGER.log(Level.INFO, "File: " + file.toString()); throw ex; } @@ -245,7 +349,7 @@ public class EssentialsUpgrade { } final File[] userFiles = userdataFolder.listFiles(); - for (File file : userFiles) { + for (final File file : userFiles) { if (!file.isFile() || !file.getName().endsWith(".yml")) { continue; } @@ -260,14 +364,14 @@ public class EssentialsUpgrade { config.setProperty("homes.home", defloc); } - Set worlds = config.getConfigurationSection("home.worlds").getKeys(false); + final Set worlds = config.getConfigurationSection("home.worlds").getKeys(false); Location loc; String worldName; if (worlds == null) { continue; } - for (String world : worlds) { + for (final String world : worlds) { if (defworld.equalsIgnoreCase(world)) { continue; } @@ -284,7 +388,7 @@ public class EssentialsUpgrade { config.forceSave(); } - } catch (RuntimeException ex) { + } catch (final RuntimeException ex) { LOGGER.log(Level.INFO, "File: " + file.toString()); throw ex; } @@ -302,7 +406,7 @@ public class EssentialsUpgrade { return; } final File[] listOfFiles = usersFolder.listFiles(); - for (File listOfFile : listOfFiles) { + for (final File listOfFile : listOfFiles) { final String filename = listOfFile.getName(); if (!listOfFile.isFile() || !filename.endsWith(".yml")) { continue; @@ -338,12 +442,12 @@ public class EssentialsUpgrade { return null; } - public Location getFakeLocation(EssentialsConf config, String path) { - String worldName = config.getString((path != null ? path + "." : "") + "world"); + public Location getFakeLocation(final EssentialsConf config, final String path) { + final String worldName = config.getString((path != null ? path + "." : "") + "world"); if (worldName == null || worldName.isEmpty()) { return null; } - World world = getFakeWorld(worldName); + final World world = getFakeWorld(worldName); if (world == null) { return null; } @@ -363,21 +467,21 @@ public class EssentialsUpgrade { oldconfigs.add(new BigInteger("c33bc9b8ee003861611bbc2f48eb6f4f", 16)); // jul 24 oldconfigs.add(new BigInteger("6ff17925430735129fc2a02f830c1daa", 16)); // crlf - MessageDigest digest = ManagedFile.getDigest(); + final MessageDigest digest = ManagedFile.getDigest(); final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); final byte[] buffer = new byte[1024]; - try (DigestInputStream dis = new DigestInputStream(bis, digest)) { + try (final DigestInputStream dis = new DigestInputStream(bis, digest)) { while (dis.read(buffer) != -1) { } } - BigInteger hash = new BigInteger(1, digest.digest()); + final BigInteger hash = new BigInteger(1, digest.digest()); if (oldconfigs.contains(hash) && !file.delete()) { throw new IOException("Could not delete file " + file.toString()); } doneFile.setProperty("deleteOldItemsCsv", true); doneFile.save(); - } catch (IOException ex) { + } catch (final IOException ex) { Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); } } @@ -395,19 +499,19 @@ public class EssentialsUpgrade { config.load(); if (!config.hasProperty("spawns")) { final Spawns spawns = new Spawns(); - Set keys = config.getKeys(false); - for (String group : keys) { - Location loc = getFakeLocation(config, group); + final Set keys = config.getKeys(false); + for (final String group : keys) { + final Location loc = getFakeLocation(config, group); spawns.getSpawns().put(group.toLowerCase(Locale.ENGLISH), loc); } if (!configFile.renameTo(new File(ess.getDataFolder(), "spawn.yml.old"))) { throw new Exception(tl("fileRenameError", "spawn.yml")); } - try (PrintWriter writer = new PrintWriter(configFile)) { + try (final PrintWriter writer = new PrintWriter(configFile)) { new YamlStorageWriter(writer).save(spawns); } } - } catch (Exception ex) { + } catch (final Exception ex) { Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); } } @@ -427,19 +531,19 @@ public class EssentialsUpgrade { config.load(); if (!config.hasProperty("jails")) { final com.earth2me.essentials.settings.Jails jails = new com.earth2me.essentials.settings.Jails(); - Set keys = config.getKeys(false); - for (String jailName : keys) { - Location loc = getFakeLocation(config, jailName); + final Set keys = config.getKeys(false); + for (final String jailName : keys) { + final Location loc = getFakeLocation(config, jailName); jails.getJails().put(jailName.toLowerCase(Locale.ENGLISH), loc); } if (!configFile.renameTo(new File(ess.getDataFolder(), "jail.yml.old"))) { throw new Exception(tl("fileRenameError", "jail.yml")); } - try (PrintWriter writer = new PrintWriter(configFile)) { + try (final PrintWriter writer = new PrintWriter(configFile)) { new YamlStorageWriter(writer).save(jails); } } - } catch (Exception ex) { + } catch (final Exception ex) { Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); } } @@ -460,7 +564,7 @@ public class EssentialsUpgrade { return; } - Boolean ignoreUFCache = doneFile.getBoolean("ignore-userfiles-cache", false); + final Boolean ignoreUFCache = doneFile.getBoolean("ignore-userfiles-cache", false); final File userdir = new File(ess.getDataFolder(), "userdata"); if (!userdir.exists()) { @@ -469,7 +573,7 @@ public class EssentialsUpgrade { int countFiles = 0; int countReqFiles = 0; - for (String string : userdir.list()) { + for (final String string : userdir.list()) { if (!string.endsWith(".yml") || string.length() < 5) { continue; } @@ -481,7 +585,7 @@ public class EssentialsUpgrade { try { uuid = UUID.fromString(name); - } catch (IllegalArgumentException ex) { + } catch (final IllegalArgumentException ex) { countReqFiles++; } @@ -499,7 +603,7 @@ public class EssentialsUpgrade { try { Thread.sleep(15000); - } catch (InterruptedException ex) { + } catch (final InterruptedException ex) { // NOOP } @@ -509,89 +613,6 @@ public class EssentialsUpgrade { doneFile.save(); } - public static void uuidFileConvert(IEssentials ess, Boolean ignoreUFCache) { - ess.getLogger().info("Starting Essentials UUID userdata conversion"); - - final File userdir = new File(ess.getDataFolder(), "userdata"); - if (!userdir.exists()) { - return; - } - - int countFiles = 0; - int countFails = 0; - int countEssCache = 0; - int countBukkit = 0; - - ess.getLogger().info("Found " + userdir.list().length + " files to convert..."); - - for (String string : userdir.list()) { - if (!string.endsWith(".yml") || string.length() < 5) { - continue; - } - - final int showProgress = countFiles % 250; - - if (showProgress == 0) { - ess.getUserMap().getUUIDMap().forceWriteUUIDMap(); - ess.getLogger().info("Converted " + countFiles + "/" + userdir.list().length); - } - - countFiles++; - - String name = string.substring(0, string.length() - 4); - EssentialsUserConf config; - UUID uuid = null; - try { - uuid = UUID.fromString(name); - } catch (IllegalArgumentException ex) { - File file = new File(userdir, string); - EssentialsConf conf = new EssentialsConf(file); - conf.load(); - conf.setProperty("lastAccountName", name); - conf.save(); - - String uuidConf = ignoreUFCache ? "force-uuid" : "uuid"; - - String uuidString = conf.getString(uuidConf, null); - - for (int i = 0; i < 4; i++) { - try { - uuid = UUID.fromString(uuidString); - countEssCache++; - break; - } catch (Exception ex2) { - if (conf.getBoolean("npc", false)) { - uuid = UUID.nameUUIDFromBytes(("NPC:" + name).getBytes(Charsets.UTF_8)); - break; - } - - org.bukkit.OfflinePlayer player = ess.getServer().getOfflinePlayer(name); - uuid = player.getUniqueId(); - } - - if (uuid != null) { - countBukkit++; - break; - } - } - - if (uuid != null) { - conf.forceSave(); - config = new EssentialsUserConf(name, uuid, new File(userdir, uuid + ".yml")); - config.convertLegacyFile(); - ess.getUserMap().trackUUID(uuid, name, false); - continue; - } - countFails++; - } - } - ess.getUserMap().getUUIDMap().forceWriteUUIDMap(); - - ess.getLogger().info("Converted " + countFiles + "/" + countFiles + ". Conversion complete."); - ess.getLogger().info("Converted via cache: " + countEssCache + " :: Converted via lookup: " + countBukkit + " :: Failed to convert: " + countFails); - ess.getLogger().info("To rerun the conversion type /essentials uuidconvert"); - } - public void banFormatChange() { if (doneFile.getBoolean("banFormatChange", false)) { return; @@ -608,7 +629,7 @@ public class EssentialsUpgrade { ess.getLogger().info("Found " + userdir.list().length + " files to convert..."); - for (String string : userdir.list()) { + for (final String string : userdir.list()) { if (!string.endsWith(".yml") || string.length() < 5) { continue; } @@ -629,7 +650,7 @@ public class EssentialsUpgrade { try { banReason = conf.getConfigurationSection("ban").getString("reason"); - } catch (NullPointerException n) { + } catch (final NullPointerException n) { banReason = null; } @@ -641,7 +662,7 @@ public class EssentialsUpgrade { } else { banTimeout = 0L; } - } catch (NumberFormatException n) { + } catch (final NumberFormatException n) { banTimeout = 0L; } @@ -658,7 +679,7 @@ public class EssentialsUpgrade { ess.getLogger().info("Ban format update complete."); } - private void updateBan(String playerName, String banReason, Long banTimeout) { + private void updateBan(final String playerName, final String banReason, final Long banTimeout) { if (banTimeout == 0) { Bukkit.getBanList(BanList.Type.NAME).addBan(playerName, banReason, null, Console.NAME); } else { @@ -666,26 +687,18 @@ public class EssentialsUpgrade { } } - private static final FileFilter YML_FILTER = pathname -> pathname.isFile() && pathname.getName().endsWith(".yml"); - - private static final String PATTERN_CONFIG_UUID_REGEX = "(?mi)^uuid:\\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\\s*$"; - private static final Pattern PATTERN_CONFIG_UUID = Pattern.compile(PATTERN_CONFIG_UUID_REGEX); - - private static final String PATTERN_CONFIG_NAME_REGEX = "(?mi)^lastAccountName:\\s*[\"\']?(\\w+)[\"\']?\\s*$"; - private static final Pattern PATTERN_CONFIG_NAME = Pattern.compile(PATTERN_CONFIG_NAME_REGEX); - private void repairUserMap() { if (doneFile.getBoolean("userMapRepaired", false)) { return; } ess.getLogger().info("Starting usermap repair"); - File userdataFolder = new File(ess.getDataFolder(), "userdata"); + final File userdataFolder = new File(ess.getDataFolder(), "userdata"); if (!userdataFolder.isDirectory()) { ess.getLogger().warning("Missing userdata folder, aborting"); return; } - File[] files = userdataFolder.listFiles(YML_FILTER); + final File[] files = userdataFolder.listFiles(YML_FILTER); final DecimalFormat format = new DecimalFormat("#0.00"); final Map names = Maps.newHashMap(); @@ -701,7 +714,7 @@ public class EssentialsUpgrade { try { // ".yml" ending has 4 chars... uuid = UUID.fromString(filename.substring(0, filename.length() - 4)); - } catch (IllegalArgumentException ignored) { + } catch (final IllegalArgumentException ignored) { } } @@ -709,7 +722,7 @@ public class EssentialsUpgrade { if (uuidMatcher.find()) { try { uuid = UUID.fromString(uuidMatcher.group(1)); - } catch (IllegalArgumentException ignored) { + } catch (final IllegalArgumentException ignored) { } } @@ -728,7 +741,7 @@ public class EssentialsUpgrade { if (index % 1000 == 0) { ess.getLogger().info("Reading: " + format.format((100d * (double) index) / files.length) - + "%"); + + "%"); } } catch (final IOException e) { ess.getLogger().log(Level.SEVERE, "Error while reading file: ", e); diff --git a/Essentials/src/com/earth2me/essentials/EssentialsUserConf.java b/Essentials/src/com/earth2me/essentials/EssentialsUserConf.java index b1539b3b4..86ca5fd23 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsUserConf.java +++ b/Essentials/src/com/earth2me/essentials/EssentialsUserConf.java @@ -10,7 +10,6 @@ import java.util.Locale; import java.util.UUID; import java.util.logging.Level; - public class EssentialsUserConf extends EssentialsConf { public final String username; public final UUID uuid; @@ -32,7 +31,7 @@ public class EssentialsUserConf extends EssentialsConf { final File file = new File(configFile.getParentFile(), username + ".yml"); try { Files.move(file, new File(configFile.getParentFile(), uuid + ".yml")); - } catch (IOException ex) { + } catch (final IOException ex) { Bukkit.getLogger().log(Level.WARNING, "Failed to migrate user: " + username, ex); } @@ -56,7 +55,7 @@ public class EssentialsUserConf extends EssentialsConf { public void convertAltFile() { try { Files.move(getAltFile(), new File(configFile.getParentFile(), uuid + ".yml")); - } catch (IOException ex) { + } catch (final IOException ex) { Bukkit.getLogger().log(Level.WARNING, "Failed to migrate user: " + username, ex); } } diff --git a/Essentials/src/com/earth2me/essentials/ExecuteTimer.java b/Essentials/src/com/earth2me/essentials/ExecuteTimer.java index 6e35a9f70..e6fce959f 100644 --- a/Essentials/src/com/earth2me/essentials/ExecuteTimer.java +++ b/Essentials/src/com/earth2me/essentials/ExecuteTimer.java @@ -6,12 +6,10 @@ import java.util.ArrayList; import java.util.List; import java.util.Locale; - public class ExecuteTimer { private final transient List times; private final transient DecimalFormat decimalFormat = new DecimalFormat("#0.000", DecimalFormatSymbols.getInstance(Locale.US)); - public ExecuteTimer() { times = new ArrayList<>(); } @@ -37,7 +35,7 @@ public class ExecuteTimer { long time2 = 0; double duration; - for (ExecuteRecord pair : times) { + for (final ExecuteRecord pair : times) { mark = pair.getMark(); time2 = pair.getTime(); if (time1 > 0) { @@ -54,12 +52,11 @@ public class ExecuteTimer { return output.toString(); } - private static class ExecuteRecord { private final String mark; private final long time; - public ExecuteRecord(final String mark, final long time) { + ExecuteRecord(final String mark, final long time) { this.mark = mark; this.time = time; } @@ -72,4 +69,4 @@ public class ExecuteTimer { return time; } } -} \ No newline at end of file +} diff --git a/Essentials/src/com/earth2me/essentials/I18n.java b/Essentials/src/com/earth2me/essentials/I18n.java index e9ef0eadc..00e1764bb 100644 --- a/Essentials/src/com/earth2me/essentials/I18n.java +++ b/Essentials/src/com/earth2me/essentials/I18n.java @@ -2,38 +2,48 @@ package com.earth2me.essentials; import net.ess3.api.IEssentials; -import java.io.*; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; import java.text.MessageFormat; -import java.util.*; +import java.util.Enumeration; +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.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; - public class I18n implements net.ess3.api.II18n { - private static I18n instance; private static final String MESSAGES = "messages"; - private final transient Locale defaultLocale = Locale.getDefault(); - private transient Locale currentLocale = defaultLocale; - private transient ResourceBundle customBundle; - private transient ResourceBundle localeBundle; - private final transient ResourceBundle defaultBundle; - private transient Map messageFormatCache = new HashMap<>(); - private final transient IEssentials ess; private static final Pattern NODOUBLEMARK = Pattern.compile("''"); private static final ResourceBundle NULL_BUNDLE = new ResourceBundle() { public Enumeration getKeys() { return null; } - protected Object handleGetObject(String key) { + protected Object handleGetObject(final String key) { return null; } }; + private static I18n instance; + private final transient Locale defaultLocale = Locale.getDefault(); + private final transient ResourceBundle defaultBundle; + private final transient IEssentials ess; + private transient Locale currentLocale = defaultLocale; + private transient ResourceBundle customBundle; + private transient ResourceBundle localeBundle; + private transient Map messageFormatCache = new HashMap<>(); public I18n(final IEssentials ess) { this.ess = ess; @@ -42,6 +52,21 @@ public class I18n implements net.ess3.api.II18n { customBundle = NULL_BUNDLE; } + public static String tl(final String string, final Object... objects) { + if (instance == null) { + return ""; + } + if (objects.length == 0) { + return NODOUBLEMARK.matcher(instance.translate(string)).replaceAll("'"); + } else { + return instance.format(string, objects); + } + } + + public static String capitalCase(final String input) { + return input == null || input.length() == 0 ? input : input.toUpperCase(Locale.ENGLISH).charAt(0) + input.toLowerCase(Locale.ENGLISH).substring(1); + } + public void onEnable() { instance = this; } @@ -59,33 +84,22 @@ public class I18n implements net.ess3.api.II18n { try { try { return customBundle.getString(string); - } catch (MissingResourceException ex) { + } catch (final MissingResourceException ex) { return localeBundle.getString(string); } - } catch (MissingResourceException ex) { + } catch (final MissingResourceException ex) { Logger.getLogger("Essentials").log(Level.WARNING, String.format("Missing translation key \"%s\" in translation file %s", ex.getKey(), localeBundle.getLocale().toString()), ex); return defaultBundle.getString(string); } } - public static String tl(final String string, final Object... objects) { - if (instance == null) { - return ""; - } - if (objects.length == 0) { - return NODOUBLEMARK.matcher(instance.translate(string)).replaceAll("'"); - } else { - return instance.format(string, objects); - } - } - public String format(final String string, final Object... objects) { String format = translate(string); MessageFormat messageFormat = messageFormatCache.get(format); if (messageFormat == null) { try { messageFormat = new MessageFormat(format); - } catch (IllegalArgumentException e) { + } catch (final IllegalArgumentException e) { ess.getLogger().log(Level.SEVERE, "Invalid Translation key for '" + string + "': " + e.getMessage()); format = format.replaceAll("\\{(\\D*?)\\}", "\\[$1\\]"); messageFormat = new MessageFormat(format); @@ -114,21 +128,17 @@ public class I18n implements net.ess3.api.II18n { try { localeBundle = ResourceBundle.getBundle(MESSAGES, currentLocale, new UTF8PropertiesControl()); - } catch (MissingResourceException ex) { + } catch (final MissingResourceException ex) { localeBundle = NULL_BUNDLE; } try { customBundle = ResourceBundle.getBundle(MESSAGES, currentLocale, new FileResClassLoader(I18n.class.getClassLoader(), ess), new UTF8PropertiesControl()); - } catch (MissingResourceException ex) { + } catch (final MissingResourceException ex) { customBundle = NULL_BUNDLE; } } - public static String capitalCase(final String input) { - return input == null || input.length() == 0 ? input : input.toUpperCase(Locale.ENGLISH).charAt(0) + input.toLowerCase(Locale.ENGLISH).substring(1); - } - /** * Attempts to load properties files from the plugin directory before falling back to the jar. */ @@ -146,7 +156,8 @@ public class I18n implements net.ess3.api.II18n { if (file.exists()) { try { return file.toURI().toURL(); - } catch (MalformedURLException ignored) {} + } catch (final MalformedURLException ignored) { + } } return null; } @@ -157,7 +168,8 @@ public class I18n implements net.ess3.api.II18n { if (file.exists()) { try { return new FileInputStream(file); - } catch (FileNotFoundException ignored) {} + } catch (final FileNotFoundException ignored) { + } } return null; } @@ -168,14 +180,14 @@ public class I18n implements net.ess3.api.II18n { * Java 9 fixes this by defaulting to UTF-8 for .properties files. */ private static class UTF8PropertiesControl extends ResourceBundle.Control { - public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IOException { - String resourceName = toResourceName(toBundleName(baseName, locale), "properties"); + public ResourceBundle newBundle(final String baseName, final Locale locale, final String format, final ClassLoader loader, final boolean reload) throws IOException { + final String resourceName = toResourceName(toBundleName(baseName, locale), "properties"); ResourceBundle bundle = null; InputStream stream = null; if (reload) { - URL url = loader.getResource(resourceName); + final URL url = loader.getResource(resourceName); if (url != null) { - URLConnection connection = url.openConnection(); + final URLConnection connection = url.openConnection(); if (connection != null) { connection.setUseCaches(false); stream = connection.getInputStream(); diff --git a/Essentials/src/com/earth2me/essentials/IEssentials.java b/Essentials/src/com/earth2me/essentials/IEssentials.java index 4646f638d..f17d9c131 100644 --- a/Essentials/src/com/earth2me/essentials/IEssentials.java +++ b/Essentials/src/com/earth2me/essentials/IEssentials.java @@ -4,7 +4,6 @@ import com.earth2me.essentials.api.IItemDb; import com.earth2me.essentials.api.IJails; import com.earth2me.essentials.api.IWarps; import com.earth2me.essentials.perm.PermissionsHandler; -import com.earth2me.essentials.register.payment.Methods; import net.ess3.provider.ServerStateProvider; import net.ess3.provider.SpawnerBlockProvider; import net.ess3.provider.SpawnerItemProvider; @@ -69,8 +68,6 @@ public interface IEssentials extends Plugin { RandomTeleport getRandomTeleport(); - Methods getPaymentMethod(); - BukkitTask runTaskAsynchronously(Runnable run); BukkitTask runTaskLaterAsynchronously(Runnable run, long delay); diff --git a/Essentials/src/com/earth2me/essentials/IEssentialsModule.java b/Essentials/src/com/earth2me/essentials/IEssentialsModule.java index 9efad58de..d43c94770 100644 --- a/Essentials/src/com/earth2me/essentials/IEssentialsModule.java +++ b/Essentials/src/com/earth2me/essentials/IEssentialsModule.java @@ -1,5 +1,4 @@ package com.earth2me.essentials; - public interface IEssentialsModule { } diff --git a/Essentials/src/com/earth2me/essentials/ISettings.java b/Essentials/src/com/earth2me/essentials/ISettings.java index 61e8d4969..6f429cf89 100644 --- a/Essentials/src/com/earth2me/essentials/ISettings.java +++ b/Essentials/src/com/earth2me/essentials/ISettings.java @@ -16,7 +16,6 @@ import java.util.Set; import java.util.function.Predicate; import java.util.regex.Pattern; - public interface ISettings extends IConf { boolean areSignsDisabled(); @@ -143,6 +142,8 @@ public interface ISettings extends IConf { boolean isDebug(); + void setDebug(boolean debug); + boolean isEcoDisabled(); @Deprecated @@ -216,14 +217,6 @@ public interface ISettings extends IConf { boolean hasJoinQuitMessagePlayerCount(); - enum KeepInvPolicy { - KEEP, - DELETE, - DROP - } - - void setDebug(boolean debug); - Set getNoGodWorlds(); boolean getUpdateBedAtDaytime(); @@ -365,7 +358,7 @@ public interface ISettings extends IConf { boolean allowOldIdSigns(); boolean isWaterSafe(); - + boolean isSafeUsermap(); boolean logCommandBlockCommands(); @@ -382,4 +375,10 @@ public interface ISettings extends IConf { boolean infoAfterDeath(); + enum KeepInvPolicy { + KEEP, + DELETE, + DROP + } + } diff --git a/Essentials/src/com/earth2me/essentials/ITarget.java b/Essentials/src/com/earth2me/essentials/ITarget.java index d96e368de..5b04704a1 100644 --- a/Essentials/src/com/earth2me/essentials/ITarget.java +++ b/Essentials/src/com/earth2me/essentials/ITarget.java @@ -2,7 +2,6 @@ package com.earth2me.essentials; import org.bukkit.Location; - public interface ITarget { Location getLocation(); -} \ No newline at end of file +} diff --git a/Essentials/src/com/earth2me/essentials/IUser.java b/Essentials/src/com/earth2me/essentials/IUser.java index d840eae1d..f442ae580 100644 --- a/Essentials/src/com/earth2me/essentials/IUser.java +++ b/Essentials/src/com/earth2me/essentials/IUser.java @@ -16,7 +16,6 @@ import java.util.Map; import java.util.Set; import java.util.regex.Pattern; - public interface IUser { boolean isAuthorized(String node); @@ -67,9 +66,6 @@ public interface IUser { void setMoney(final BigDecimal value) throws MaxMoneyException; - @Deprecated - void setAfk(final boolean set); - void setAfk(final boolean set, final AfkStatusChangeEvent.Cause cause); /** @@ -77,7 +73,6 @@ public interface IUser { * supported plugins. Use isVanished() if you want to check if a user is vanished by Essentials. * * @return If the user is hidden or not - * * @see IUser#isVanished() */ boolean isHidden(); @@ -106,7 +101,6 @@ public interface IUser { * plugin. * * @return If the user is vanished or not - * * @see IUser#isHidden() */ boolean isVanished(); @@ -150,10 +144,13 @@ public interface IUser { boolean isAfk(); - void setIgnoreMsg(boolean ignoreMsg); + @Deprecated + void setAfk(final boolean set); boolean isIgnoreMsg(); + void setIgnoreMsg(boolean ignoreMsg); + void setConfigProperty(String node, Object object); Set getConfigKeys(); @@ -161,13 +158,13 @@ public interface IUser { Map getConfigMap(); Map getConfigMap(String node); - + Map getCommandCooldowns(); Date getCommandCooldownExpiry(String label); - + void addCommandCooldown(Pattern pattern, Date expiresAt, boolean save); - + boolean clearCommandCooldown(Pattern pattern); /* @@ -184,19 +181,19 @@ public interface IUser { String getAfkMessage(); void setAfkMessage(final String message); - + long getAfkSince(); - + boolean isAcceptingPay(); - + void setAcceptingPay(boolean acceptingPay); - + boolean isPromptingPayConfirm(); - + void setPromptingPayConfirm(boolean prompt); - + boolean isPromptingClearConfirm(); - + void setPromptingClearConfirm(boolean prompt); boolean isLastMessageReplyRecipient(); diff --git a/Essentials/src/com/earth2me/essentials/Jails.java b/Essentials/src/com/earth2me/essentials/Jails.java index b14d87f89..b78ff0345 100644 --- a/Essentials/src/com/earth2me/essentials/Jails.java +++ b/Essentials/src/com/earth2me/essentials/Jails.java @@ -16,19 +16,26 @@ import org.bukkit.event.block.BlockDamageEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; -import org.bukkit.event.player.*; +import org.bukkit.event.player.PlayerGameModeChangeEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.plugin.PluginManager; import java.io.File; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Locale; import java.util.concurrent.CompletableFuture; import java.util.logging.Level; import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; - public class Jails extends AsyncStorageObjectHolder implements net.ess3.api.IJails { private static final transient Logger LOGGER = Bukkit.getLogger(); private static transient boolean enabled = false; @@ -81,7 +88,7 @@ public class Jails extends AsyncStorageObjectHolder future) throws Exception { + public void sendToJail(final IUser user, final String jail, final CompletableFuture future) throws Exception { acquireReadLock(); try { if (user.getBase().isOnline()) { - Location loc = getJail(jail); + final Location loc = getJail(jail); user.getAsyncTeleport().now(loc, false, TeleportCause.COMMAND, future); - future.thenAccept(success -> { - user.setJail(jail); - }); + future.thenAccept(success -> user.setJail(jail)); return; } user.setJail(jail); @@ -170,12 +175,11 @@ public class Jails extends AsyncStorageObjectHolder future = new CompletableFuture<>(); + final CompletableFuture future = new CompletableFuture<>(); future.exceptionally(ex -> { if (ess.getSettings().isDebug()) { LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex); @@ -290,7 +294,7 @@ public class Jails extends AsyncStorageObjectHolder itemList = new ArrayList<>(); final Object kitItems = kit.get("items"); if (kitItems instanceof List) { - for (Object item : (List) kitItems) { + for (final Object item : (List) kitItems) { if (item instanceof String) { itemList.add(item.toString()); continue; @@ -137,7 +139,7 @@ public class Kit { return itemList; } throw new Exception("Invalid item list"); - } catch (Exception e) { + } catch (final Exception e) { ess.getLogger().log(Level.WARNING, "Error parsing kit " + kitName + ": " + e.getMessage()); throw new Exception(tl("kitError2"), e); } @@ -149,10 +151,10 @@ public class Kit { public boolean expandItems(final User user, final List items) throws Exception { try { - IText input = new SimpleTextInput(items); - IText output = new KeywordReplacer(input, user.getSource(), ess, true, true); + final IText input = new SimpleTextInput(items); + final IText output = new KeywordReplacer(input, user.getSource(), ess, true, true); - KitClaimEvent event = new KitClaimEvent(user, this); + final KitClaimEvent event = new KitClaimEvent(user, this); Bukkit.getPluginManager().callEvent(event); if (event.isCancelled()) { return false; @@ -161,10 +163,10 @@ public class Kit { boolean spew = false; final boolean allowUnsafe = ess.getSettings().allowUnsafeEnchantments(); final boolean currencyIsSuffix = ess.getSettings().isCurrencySymbolSuffixed(); - List itemList = new ArrayList<>(); - List commandQueue = new ArrayList<>(); - List moneyQueue = new ArrayList<>(); - for (String kitItem : output.getLines()) { + final List itemList = new ArrayList<>(); + final List commandQueue = new ArrayList<>(); + final List moneyQueue = new ArrayList<>(); + for (final String kitItem : output.getLines()) { if (!currencyIsSuffix ? kitItem.startsWith(ess.getSettings().getCurrencySymbol()) : kitItem.endsWith(ess.getSettings().getCurrencySymbol())) { moneyQueue.add(NumberUtil.sanitizeCurrencyString(kitItem, ess)); continue; @@ -172,7 +174,7 @@ public class Kit { if (kitItem.startsWith("/")) { String command = kitItem.substring(1); - String name = user.getName(); + final String name = user.getName(); command = command.replace("{player}", name); commandQueue.add(command); continue; @@ -191,11 +193,10 @@ public class Kit { // We pass a null sender here because kits should not do perm checks metaStack.parseStringMeta(null, allowUnsafe, parts, 2, ess); } - + itemList.add(metaStack.getItemStack()); } - - + final Map overfilled; final boolean allowOversizedStacks = user.isAuthorized("essentials.oversizedstacks"); final boolean isDropItemsIfFull = ess.getSettings().isDropItemsIfFull(); @@ -205,7 +206,7 @@ public class Kit { } else { overfilled = InventoryWorkaround.addItems(user.getBase().getInventory(), itemList.toArray(new ItemStack[0])); } - for (ItemStack itemStack : overfilled.values()) { + for (final ItemStack itemStack : overfilled.values()) { int spillAmount = itemStack.getAmount(); if (!allowOversizedStacks) { itemStack.setAmount(Math.min(spillAmount, itemStack.getMaxStackSize())); @@ -232,20 +233,20 @@ public class Kit { // Process money & command queues // Done after all items have been processed so commands are not run and money is not given if // an error occurs during the item giving process - for (String valueString : moneyQueue) { - BigDecimal value = new BigDecimal(valueString.trim()); - Trade t = new Trade(value, ess); + for (final String valueString : moneyQueue) { + final BigDecimal value = new BigDecimal(valueString.trim()); + final Trade t = new Trade(value, ess); t.pay(user, OverflowType.DROP); } - for (String cmd : commandQueue) { + for (final String cmd : commandQueue) { Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd); } if (spew) { user.sendMessage(tl("kitInvFull")); } - } catch (Exception e) { + } catch (final Exception e) { user.getBase().updateInventory(); ess.getLogger().log(Level.WARNING, e.getMessage()); throw new Exception(tl("kitError2"), e); diff --git a/Essentials/src/com/earth2me/essentials/Kits.java b/Essentials/src/com/earth2me/essentials/Kits.java index c266f7151..19c0c7b95 100644 --- a/Essentials/src/com/earth2me/essentials/Kits.java +++ b/Essentials/src/com/earth2me/essentials/Kits.java @@ -35,7 +35,7 @@ public class Kits implements IConf { if (config.isConfigurationSection("kits")) { final ConfigurationSection section = config.getConfigurationSection("kits"); final ConfigurationSection newSection = new MemoryConfiguration(); - for (String kitItem : section.getKeys(false)) { + for (final String kitItem : section.getKeys(false)) { if (section.isConfigurationSection(kitItem)) { newSection.set(kitItem.toLowerCase(Locale.ENGLISH), section.getConfigurationSection(kitItem)); } @@ -71,11 +71,11 @@ public class Kits implements IConf { } // Tries to find an existing kit name that matches the given name, ignoring case. Returns null if no match. - public String matchKit(String name) { + public String matchKit(final String name) { if (config.isConfigurationSection("kits")) { final ConfigurationSection section = config.getConfigurationSection("kits"); if (section != null) { - for (String kitName : section.getKeys(false)) { + for (final String kitName : section.getKeys(false)) { if (kitName.equalsIgnoreCase(name)) { return kitName; } @@ -85,7 +85,7 @@ public class Kits implements IConf { return null; } - public void addKit(String name, List lines, long delay) { + public void addKit(final String name, final List lines, final long delay) { // Will overwrite but w/e config.set("kits." + name + ".delay", delay); config.set("kits." + name + ".items", lines); @@ -93,7 +93,7 @@ public class Kits implements IConf { config.save(); } - public void removeKit(String name) { + public void removeKit(final String name) { config.set("kits." + name, null); kits = _getKits(); config.save(); @@ -103,19 +103,19 @@ public class Kits implements IConf { try { final ConfigurationSection kits = config.getConfigurationSection("kits"); final StringBuilder list = new StringBuilder(); - for (String kitItem : kits.getKeys(false)) { + for (final String kitItem : kits.getKeys(false)) { if (user == null) { list.append(" ").append(capitalCase(kitItem)); } else if (user.isAuthorized("essentials.kits." + kitItem.toLowerCase(Locale.ENGLISH))) { String cost = ""; String name = capitalCase(kitItem); - BigDecimal costPrice = new Trade("kit-" + kitItem.toLowerCase(Locale.ENGLISH), ess).getCommandCost(user); + final BigDecimal costPrice = new Trade("kit-" + kitItem.toLowerCase(Locale.ENGLISH), ess).getCommandCost(user); if (costPrice.signum() > 0) { cost = tl("kitCost", NumberUtil.displayCurrency(costPrice, ess)); } - Kit kit = new Kit(kitItem, ess); - double nextUse = kit.getNextUse(user); + final Kit kit = new Kit(kitItem, ess); + final double nextUse = kit.getNextUse(user); if (nextUse == -1 && ess.getSettings().isSkippingUsedOneTimeKitsFromKitList()) { continue; } else if (nextUse != 0) { @@ -126,7 +126,7 @@ public class Kits implements IConf { } } return list.toString().trim(); - } catch (Exception ex) { + } catch (final Exception ex) { throw new Exception(tl("kitError"), ex); } diff --git a/Essentials/src/com/earth2me/essentials/LocationTarget.java b/Essentials/src/com/earth2me/essentials/LocationTarget.java index 5d3ca71a1..18255fe20 100644 --- a/Essentials/src/com/earth2me/essentials/LocationTarget.java +++ b/Essentials/src/com/earth2me/essentials/LocationTarget.java @@ -2,11 +2,10 @@ package com.earth2me.essentials; import org.bukkit.Location; - public class LocationTarget implements ITarget { private final Location location; - LocationTarget(Location location) { + LocationTarget(final Location location) { this.location = location; } @@ -14,4 +13,4 @@ public class LocationTarget implements ITarget { public Location getLocation() { return location; } -} \ No newline at end of file +} diff --git a/Essentials/src/com/earth2me/essentials/ManagedFile.java b/Essentials/src/com/earth2me/essentials/ManagedFile.java index 197244270..3d1fda60b 100644 --- a/Essentials/src/com/earth2me/essentials/ManagedFile.java +++ b/Essentials/src/com/earth2me/essentials/ManagedFile.java @@ -3,7 +3,16 @@ package com.earth2me.essentials; import net.ess3.api.IEssentials; import org.bukkit.Bukkit; -import java.io.*; +import java.io.BufferedInputStream; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; import java.math.BigInteger; import java.security.DigestInputStream; import java.security.DigestOutputStream; @@ -16,7 +25,6 @@ import java.util.logging.Level; import static com.earth2me.essentials.I18n.tl; - public class ManagedFile { private static final int BUFFERSIZE = 1024 * 8; private final transient File file; @@ -29,7 +37,7 @@ public class ManagedFile { if (checkForVersion(file, ess.getDescription().getVersion()) && !file.delete()) { throw new IOException("Could not delete file " + file.toString()); } - } catch (IOException ex) { + } catch (final IOException ex) { Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); } } @@ -37,17 +45,17 @@ public class ManagedFile { if (!file.exists()) { try { copyResourceAscii("/" + filename, file); - } catch (IOException ex) { + } catch (final IOException ex) { Bukkit.getLogger().log(Level.SEVERE, tl("itemsCsvNotLoaded", filename), ex); } } } public static void copyResourceAscii(final String resourceName, final File file) throws IOException { - try (InputStreamReader reader = new InputStreamReader(ManagedFile.class.getResourceAsStream(resourceName))) { + try (final InputStreamReader reader = new InputStreamReader(ManagedFile.class.getResourceAsStream(resourceName))) { final MessageDigest digest = getDigest(); - try (DigestOutputStream digestStream = new DigestOutputStream(new FileOutputStream(file), digest)) { - try (OutputStreamWriter writer = new OutputStreamWriter(digestStream)) { + try (final DigestOutputStream digestStream = new DigestOutputStream(new FileOutputStream(file), digest)) { + try (final OutputStreamWriter writer = new OutputStreamWriter(digestStream)) { final char[] buffer = new char[BUFFERSIZE]; do { final int length = reader.read(buffer); @@ -72,7 +80,7 @@ public class ManagedFile { if (file.length() < 33) { return false; } - try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) { + try (final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) { final byte[] buffer = new byte[(int) file.length()]; int position = 0; do { @@ -86,7 +94,7 @@ public class ManagedFile { if (bais.skip(file.length() - 33) != file.length() - 33) { return false; } - try (BufferedReader reader = new BufferedReader(new InputStreamReader(bais))) { + try (final BufferedReader reader = new BufferedReader(new InputStreamReader(bais))) { String hash = reader.readLine(); if (hash != null && hash.matches("#[a-f0-9]{32}")) { hash = hash.substring(1); @@ -97,7 +105,7 @@ public class ManagedFile { if (!versioncheck.equalsIgnoreCase(version)) { bais.reset(); final MessageDigest digest = getDigest(); - try (DigestInputStream digestStream = new DigestInputStream(bais, digest)) { + try (final DigestInputStream digestStream = new DigestInputStream(bais, digest)) { final byte[] bytes = new byte[(int) file.length() - 33]; digestStream.read(bytes); final BigInteger correct = new BigInteger(hash, 16); @@ -119,14 +127,14 @@ public class ManagedFile { public static MessageDigest getDigest() throws IOException { try { return MessageDigest.getInstance("MD5"); - } catch (NoSuchAlgorithmException ex) { + } catch (final NoSuchAlgorithmException ex) { throw new IOException(ex); } } public List getLines() { try { - try (BufferedReader reader = new BufferedReader(new FileReader(file))) { + try (final BufferedReader reader = new BufferedReader(new FileReader(file))) { final List lines = new ArrayList<>(); do { final String line = reader.readLine(); @@ -138,7 +146,7 @@ public class ManagedFile { } while (true); return lines; } - } catch (IOException ex) { + } catch (final IOException ex) { Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); return Collections.emptyList(); } diff --git a/Essentials/src/com/earth2me/essentials/MetaItemStack.java b/Essentials/src/com/earth2me/essentials/MetaItemStack.java index 9a42efec6..7280d322e 100644 --- a/Essentials/src/com/earth2me/essentials/MetaItemStack.java +++ b/Essentials/src/com/earth2me/essentials/MetaItemStack.java @@ -19,28 +19,44 @@ import org.bukkit.block.banner.PatternType; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.*; +import org.bukkit.inventory.meta.BannerMeta; +import org.bukkit.inventory.meta.BlockStateMeta; +import org.bukkit.inventory.meta.BookMeta; +import org.bukkit.inventory.meta.EnchantmentStorageMeta; +import org.bukkit.inventory.meta.FireworkMeta; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.LeatherArmorMeta; +import org.bukkit.inventory.meta.PotionMeta; +import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.potion.Potion; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import java.lang.reflect.Method; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; import java.util.logging.Level; import java.util.regex.Pattern; import static com.earth2me.essentials.I18n.tl; - public class MetaItemStack { private static final Map colorMap = new HashMap<>(); private static final Map fireworkShape = new HashMap<>(); + private static int bukkitUnbreakableSupport = -1; + private static Method spigotMethod; + private static Method setUnbreakableMethod; + private static boolean useNewSkullMethod = true; static { - for (DyeColor color : DyeColor.values()) { + for (final DyeColor color : DyeColor.values()) { colorMap.put(color.name(), color); } - for (FireworkEffect.Type type : FireworkEffect.Type.values()) { + for (final FireworkEffect.Type type : FireworkEffect.Type.values()) { fireworkShape.put(type.name(), type); } } @@ -63,6 +79,24 @@ public class MetaItemStack { this.stack = stack.clone(); } + private static void setSkullOwner(final IEssentials ess, final ItemStack stack, final String owner) { + if (!(stack.getItemMeta() instanceof SkullMeta)) return; + + final SkullMeta meta = (SkullMeta) stack.getItemMeta(); + if (useNewSkullMethod) { + try { + meta.setOwningPlayer(ess.getServer().getOfflinePlayer(owner)); + stack.setItemMeta(meta); + return; + } catch (final NoSuchMethodError e) { + useNewSkullMethod = false; + } + } + + meta.setOwner(owner); + stack.setItemMeta(meta); + } + public ItemStack getItemStack() { return stack; } @@ -101,9 +135,9 @@ public class MetaItemStack { try { ess.getServer().getUnsafe().modifyItemStack(stack.clone(), "{}"); return true; - } catch (NoSuchMethodError nsme) { + } catch (final NoSuchMethodError nsme) { return true; - } catch (Throwable npe) { + } catch (final Throwable npe) { if (ess.getSettings().isDebug()) { ess.getLogger().log(Level.INFO, "Itemstack is invalid", npe); } @@ -111,17 +145,17 @@ public class MetaItemStack { } } - public void parseStringMeta(final CommandSource sender, final boolean allowUnsafe, String[] string, int fromArg, final IEssentials ess) throws Exception { + public void parseStringMeta(final CommandSource sender, final boolean allowUnsafe, final String[] string, final int fromArg, final IEssentials ess) throws Exception { if (string[fromArg].startsWith("{") && hasMetaPermission(sender, "vanilla", false, true, ess)) { try { stack = ess.getServer().getUnsafe().modifyItemStack(stack, Joiner.on(' ').join(Arrays.asList(string).subList(fromArg, string.length))); - } catch (NullPointerException npe) { + } catch (final NullPointerException npe) { if (ess.getSettings().isDebug()) { ess.getLogger().log(Level.INFO, "Itemstack is invalid", npe); } - } catch (NoSuchMethodError nsme) { + } catch (final NoSuchMethodError nsme) { throw new Exception(tl("noMetaJson"), nsme); - } catch (Throwable throwable) { + } catch (final Throwable throwable) { throw new Exception(throwable.getMessage(), throwable); } } else { @@ -132,8 +166,8 @@ public class MetaItemStack { if (!hasMetaPermission(sender, "firework", true, true, ess)) { throw new Exception(tl("noMetaFirework")); } - FireworkEffect effect = builder.build(); - FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta(); + final FireworkEffect effect = builder.build(); + final FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta(); fmeta.addEffect(effect); if (fmeta.getEffects().size() > 1 && !hasMetaPermission(sender, "firework-multiple", true, true, ess)) { throw new Exception(tl("multipleCharges")); @@ -149,7 +183,7 @@ public class MetaItemStack { return; } - Material WRITTEN_BOOK = EnumUtil.getMaterial("WRITTEN_BOOK"); + final Material WRITTEN_BOOK = EnumUtil.getMaterial("WRITTEN_BOOK"); if (split.length > 1 && split[0].equalsIgnoreCase("name") && hasMetaPermission(sender, "name", false, true, ess)) { final String displayName = FormatUtil.replaceFormat(split[1].replace('_', ' ')); @@ -158,14 +192,14 @@ public class MetaItemStack { stack.setItemMeta(meta); } else if (split.length > 1 && (split[0].equalsIgnoreCase("lore") || split[0].equalsIgnoreCase("desc")) && hasMetaPermission(sender, "lore", false, true, ess)) { final List lore = new ArrayList<>(); - for (String line : split[1].split("(? 1 && (split[0].equalsIgnoreCase("player") || split[0].equalsIgnoreCase("owner")) && hasMetaPermission(sender, "head", false, true, ess)) { if (MaterialUtil.isPlayerHead(stack.getType(), stack.getDurability())) { @@ -179,7 +213,7 @@ public class MetaItemStack { final IText input = new BookInput("book", true, ess); final BookPager pager = new BookPager(input); - List pages = pager.getPages(split[1]); + final List pages = pager.getPages(split[1]); meta.setPages(pages); stack.setItemMeta(meta); } else if (split.length > 1 && split[0].equalsIgnoreCase("author") && stack.getType() == WRITTEN_BOOK && hasMetaPermission(sender, "author", false, true, ess)) { @@ -192,7 +226,7 @@ public class MetaItemStack { final BookMeta meta = (BookMeta) stack.getItemMeta(); meta.setTitle(title); stack.setItemMeta(meta); - } else if (split.length > 1 && split[0].equalsIgnoreCase("power") && (MaterialUtil.isFirework(stack.getType()))&& hasMetaPermission(sender, "firework-power", false, true, ess)) { + } else if (split.length > 1 && split[0].equalsIgnoreCase("power") && MaterialUtil.isFirework(stack.getType()) && hasMetaPermission(sender, "firework-power", false, true, ess)) { final int power = NumberUtil.isInt(split[1]) ? Integer.parseInt(split[1]) : 0; final FireworkMeta meta = (FireworkMeta) stack.getItemMeta(); meta.setPower(power > 3 ? 4 : power); @@ -217,7 +251,7 @@ public class MetaItemStack { if (color.length == 1 && (NumberUtil.isInt(color[0]) || color[0].startsWith("#"))) { // Either integer or hexadecimal final LeatherArmorMeta meta = (LeatherArmorMeta) stack.getItemMeta(); - String input = color[0]; + final String input = color[0]; if (input.startsWith("#")) { // Hex meta.setColor(Color.fromRGB( Integer.valueOf(input.substring(1, 3), 16), @@ -243,16 +277,16 @@ public class MetaItemStack { } public void addItemFlags(final String string) throws Exception { - String[] separate = splitPattern.split(string, 2); + final String[] separate = splitPattern.split(string, 2); if (separate.length != 2) { throw new Exception(tl("invalidItemFlagMeta", string)); } - String[] split = separate[1].split(","); - ItemMeta meta = stack.getItemMeta(); + final String[] split = separate[1].split(","); + final ItemMeta meta = stack.getItemMeta(); - for (String s : split) { - for (ItemFlag flag : ItemFlag.values()) { + for (final String s : split) { + for (final ItemFlag flag : ItemFlag.values()) { if (s.equalsIgnoreCase(flag.name())) { meta.addItemFlags(flag); } @@ -267,7 +301,7 @@ public class MetaItemStack { } public void addFireworkMeta(final CommandSource sender, final boolean allowShortName, final String string, final IEssentials ess) throws Exception { - if (MaterialUtil.isFirework(stack.getType())) { + if (MaterialUtil.isFirework(stack.getType())) { final String[] split = splitPattern.split(string, 2); if (split.length < 2) { return; @@ -278,8 +312,8 @@ public class MetaItemStack { if (!hasMetaPermission(sender, "firework", true, true, ess)) { throw new Exception(tl("noMetaFirework")); } - FireworkEffect effect = builder.build(); - FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta(); + final FireworkEffect effect = builder.build(); + final FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta(); fmeta.addEffect(effect); if (fmeta.getEffects().size() > 1 && !hasMetaPermission(sender, "firework-multiple", true, true, ess)) { throw new Exception(tl("multipleCharges")); @@ -288,9 +322,9 @@ public class MetaItemStack { builder = FireworkEffect.builder(); } - List primaryColors = new ArrayList<>(); - String[] colors = split[1].split(","); - for (String color : colors) { + final List primaryColors = new ArrayList<>(); + final String[] colors = split[1].split(","); + for (final String color : colors) { if (colorMap.containsKey(color.toUpperCase())) { validFirework = true; primaryColors.add(colorMap.get(color.toUpperCase()).getFireworkColor()); @@ -301,7 +335,7 @@ public class MetaItemStack { builder.withColor(primaryColors); } else if (split[0].equalsIgnoreCase("shape") || split[0].equalsIgnoreCase("type") || (allowShortName && (split[0].equalsIgnoreCase("s") || split[0].equalsIgnoreCase("t")))) { FireworkEffect.Type finalEffect = null; - split[1] = (split[1].equalsIgnoreCase("large") ? "BALL_LARGE" : split[1]); + split[1] = split[1].equalsIgnoreCase("large") ? "BALL_LARGE" : split[1]; if (fireworkShape.containsKey(split[1].toUpperCase())) { finalEffect = fireworkShape.get(split[1].toUpperCase()); } else { @@ -311,9 +345,9 @@ public class MetaItemStack { builder.with(finalEffect); } } else if (split[0].equalsIgnoreCase("fade") || (allowShortName && split[0].equalsIgnoreCase("f"))) { - List fadeColors = new ArrayList<>(); - String[] colors = split[1].split(","); - for (String color : colors) { + final List fadeColors = new ArrayList<>(); + final String[] colors = split[1].split(","); + for (final String color : colors) { if (colorMap.containsKey(color.toUpperCase())) { fadeColors.add(colorMap.get(color.toUpperCase()).getFireworkColor()); } else { @@ -324,8 +358,8 @@ public class MetaItemStack { builder.withFade(fadeColors); } } else if (split[0].equalsIgnoreCase("effect") || (allowShortName && split[0].equalsIgnoreCase("e"))) { - String[] effects = split[1].split(","); - for (String effect : effects) { + final String[] effects = split[1].split(","); + for (final String effect : effects) { if (effect.equalsIgnoreCase("twinkle")) { builder.flicker(true); } else if (effect.equalsIgnoreCase("trail")) { @@ -386,7 +420,7 @@ public class MetaItemStack { } if (isValidPotion()) { - PotionMeta pmeta = (PotionMeta) stack.getItemMeta(); + final PotionMeta pmeta = (PotionMeta) stack.getItemMeta(); pEffect = pEffectType.createEffect(duration, power); if (pmeta.getCustomEffects().size() > 1 && !hasMetaPermission(sender, "potions.multiple", true, false, ess)) { throw new Exception(tl("multiplePotionEffects")); @@ -400,7 +434,7 @@ public class MetaItemStack { stack.setType(Material.POTION); } } else { - Potion potion = Potion.fromItemStack(stack); + final Potion potion = Potion.fromItemStack(stack); potion.setSplash(isSplashPotion); potion.apply(stack); } @@ -419,7 +453,7 @@ public class MetaItemStack { if (split.length > 1) { try { level = Integer.parseInt(split[1]); - } catch (NumberFormatException ex) { + } catch (final NumberFormatException ex) { level = -1; } } @@ -436,15 +470,14 @@ public class MetaItemStack { } try { if (stack.getType().equals(Material.ENCHANTED_BOOK)) { - EnchantmentStorageMeta meta = (EnchantmentStorageMeta) stack.getItemMeta(); + final EnchantmentStorageMeta meta = (EnchantmentStorageMeta) stack.getItemMeta(); if (level == 0) { meta.removeStoredEnchant(enchantment); } else { meta.addStoredEnchant(enchantment, level, allowUnsafe); } stack.setItemMeta(meta); - } else // all other material types besides ENCHANTED_BOOK - { + } else { // all other material types besides ENCHANTED_BOOK if (level == 0) { stack.removeEnchantment(enchantment); } else { @@ -455,7 +488,7 @@ public class MetaItemStack { } } } - } catch (Exception ex) { + } catch (final Exception ex) { throw new Exception("Enchantment " + enchantment.getName() + ": " + ex.getMessage(), ex); } } @@ -485,16 +518,17 @@ public class MetaItemStack { PatternType patternType = null; try { patternType = PatternType.valueOf(split[0]); - } catch (Exception ignored ) {} + } catch (final Exception ignored) { + } final BannerMeta meta = (BannerMeta) stack.getItemMeta(); if (split[0].equalsIgnoreCase("basecolor")) { - Color color = Color.fromRGB(Integer.parseInt(split[1])); + final Color color = Color.fromRGB(Integer.parseInt(split[1])); meta.setBaseColor(DyeColor.getByColor(color)); } else if (patternType != null) { - PatternType type = PatternType.valueOf(split[0]); - DyeColor color = DyeColor.getByColor(Color.fromRGB(Integer.parseInt(split[1]))); - org.bukkit.block.banner.Pattern pattern = new org.bukkit.block.banner.Pattern(color, type); + final PatternType type = PatternType.valueOf(split[0]); + final DyeColor color = DyeColor.getByColor(Color.fromRGB(Integer.parseInt(split[1]))); + final org.bukkit.block.banner.Pattern pattern = new org.bukkit.block.banner.Pattern(color, type); meta.addPattern(pattern); } @@ -509,18 +543,19 @@ public class MetaItemStack { PatternType patternType = null; try { patternType = PatternType.valueOf(split[0]); - } catch (Exception ignored ) {} + } catch (final Exception ignored) { + } // Hacky fix for accessing Shield meta - https://github.com/drtshock/Essentials/pull/745#issuecomment-234843795 - BlockStateMeta meta = (BlockStateMeta) stack.getItemMeta(); - Banner banner = (Banner) meta.getBlockState(); + final BlockStateMeta meta = (BlockStateMeta) stack.getItemMeta(); + final Banner banner = (Banner) meta.getBlockState(); if (split[0].equalsIgnoreCase("basecolor")) { - Color color = Color.fromRGB(Integer.parseInt(split[1])); + final Color color = Color.fromRGB(Integer.parseInt(split[1])); banner.setBaseColor(DyeColor.getByColor(color)); } else if (patternType != null) { - PatternType type = PatternType.valueOf(split[0]); - DyeColor color = DyeColor.getByColor(Color.fromRGB(Integer.parseInt(split[1]))); - org.bukkit.block.banner.Pattern pattern = new org.bukkit.block.banner.Pattern(color, type); + final PatternType type = PatternType.valueOf(split[0]); + final DyeColor color = DyeColor.getByColor(Color.fromRGB(Integer.parseInt(split[1]))); + final org.bukkit.block.banner.Pattern pattern = new org.bukkit.block.banner.Pattern(color, type); banner.addPattern(pattern); } banner.update(); @@ -547,18 +582,14 @@ public class MetaItemStack { } } - private static int bukkitUnbreakableSupport = -1; - private static Method spigotMethod; - private static Method setUnbreakableMethod; - - private void setUnbreakable(ItemStack is, boolean unbreakable) { - ItemMeta meta = is.getItemMeta(); + private void setUnbreakable(final ItemStack is, final boolean unbreakable) { + final ItemMeta meta = is.getItemMeta(); try { if (bukkitUnbreakableSupport == -1) { try { ItemMeta.class.getDeclaredMethod("setUnbreakable", boolean.class); bukkitUnbreakableSupport = 1; - } catch (NoSuchMethodException | SecurityException ex) { + } catch (final NoSuchMethodException | SecurityException ex) { bukkitUnbreakableSupport = 0; } } @@ -570,7 +601,7 @@ public class MetaItemStack { spigotMethod = meta.getClass().getDeclaredMethod("spigot"); spigotMethod.setAccessible(true); } - Object itemStackSpigot = spigotMethod.invoke(meta); + final Object itemStackSpigot = spigotMethod.invoke(meta); if (setUnbreakableMethod == null) { setUnbreakableMethod = itemStackSpigot.getClass().getDeclaredMethod("setUnbreakable", Boolean.TYPE); setUnbreakableMethod.setAccessible(true); @@ -578,28 +609,8 @@ public class MetaItemStack { setUnbreakableMethod.invoke(itemStackSpigot, unbreakable); } is.setItemMeta(meta); - } catch (Throwable t) { + } catch (final Throwable t) { t.printStackTrace(); } } - - private static boolean useNewSkullMethod = true; - - private static void setSkullOwner(final IEssentials ess, final ItemStack stack, final String owner) { - if (!(stack.getItemMeta() instanceof SkullMeta)) return; - - SkullMeta meta = (SkullMeta) stack.getItemMeta(); - if (useNewSkullMethod) { - try { - meta.setOwningPlayer(ess.getServer().getOfflinePlayer(owner)); - stack.setItemMeta(meta); - return; - } catch (NoSuchMethodError e) { - useNewSkullMethod = false; - } - } - - meta.setOwner(owner); - stack.setItemMeta(meta); - } } diff --git a/Essentials/src/com/earth2me/essentials/Mob.java b/Essentials/src/com/earth2me/essentials/Mob.java index 5bfb30a35..70e42d2fa 100644 --- a/Essentials/src/com/earth2me/essentials/Mob.java +++ b/Essentials/src/com/earth2me/essentials/Mob.java @@ -4,15 +4,19 @@ import com.earth2me.essentials.utils.EnumUtil; import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.World; -import org.bukkit.entity.*; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; -import java.util.*; +import java.util.Collections; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; - // Suffixes can be appended on the end of a mob name to make it plural // Entities without a suffix, will default to 's' public enum Mob { @@ -101,42 +105,11 @@ public enum Mob { ; public static final Logger logger = Logger.getLogger("Essentials"); - - Mob(String n, Enemies en, String s, EntityType type) { - this.suffix = s; - this.name = n; - this.type = en; - this.bukkitType = type; - } - - Mob(String n, Enemies en, EntityType type) { - this.name = n; - this.type = en; - this.bukkitType = type; - } - - Mob(String n, Enemies en, String s, String typeName) { - this.suffix = s; - this.name = n; - this.type = en; - bukkitType = EnumUtil.getEntityType(typeName); - } - - Mob(String n, Enemies en, String typeName) { - this.name = n; - this.type = en; - bukkitType = EnumUtil.getEntityType(typeName); - } - - public String suffix = "s"; - final public String name; - final public Enemies type; - final private EntityType bukkitType; private static final Map hashMap = new HashMap<>(); private static final Map bukkitMap = new HashMap<>(); static { - for (Mob mob : Mob.values()) { + for (final Mob mob : Mob.values()) { hashMap.put(mob.name.toLowerCase(Locale.ENGLISH), mob); if (mob.bukkitType != null) { bukkitMap.put(mob.bukkitType, mob); @@ -144,10 +117,49 @@ public enum Mob { } } + final public String name; + final public Enemies type; + final private EntityType bukkitType; + public String suffix = "s"; + + Mob(final String n, final Enemies en, final String s, final EntityType type) { + this.suffix = s; + this.name = n; + this.type = en; + this.bukkitType = type; + } + + Mob(final String n, final Enemies en, final EntityType type) { + this.name = n; + this.type = en; + this.bukkitType = type; + } + + Mob(final String n, final Enemies en, final String s, final String typeName) { + this.suffix = s; + this.name = n; + this.type = en; + bukkitType = EnumUtil.getEntityType(typeName); + } + + Mob(final String n, final Enemies en, final String typeName) { + this.name = n; + this.type = en; + bukkitType = EnumUtil.getEntityType(typeName); + } + public static Set getMobList() { return Collections.unmodifiableSet(hashMap.keySet()); } + public static Mob fromName(final String name) { + return hashMap.get(name.toLowerCase(Locale.ENGLISH)); + } + + public static Mob fromBukkitType(final EntityType type) { + return bukkitMap.get(type); + } + public Entity spawn(final World world, final Server server, final Location loc) throws MobException { final Entity entity = world.spawn(loc, this.bukkitType.getEntityClass()); if (entity == null) { @@ -157,6 +169,9 @@ public enum Mob { return entity; } + public EntityType getType() { + return bukkitType; + } public enum Enemies { FRIENDLY("friendly"), @@ -164,26 +179,13 @@ public enum Mob { ENEMY("enemy"), ADULT_ENEMY("adult_enemy"); + final protected String type; + Enemies(final String type) { this.type = type; } - - final protected String type; } - public EntityType getType() { - return bukkitType; - } - - public static Mob fromName(final String name) { - return hashMap.get(name.toLowerCase(Locale.ENGLISH)); - } - - public static Mob fromBukkitType(final EntityType type) { - return bukkitMap.get(type); - } - - public static class MobException extends Exception { private static final long serialVersionUID = 1L; } diff --git a/Essentials/src/com/earth2me/essentials/MobCompat.java b/Essentials/src/com/earth2me/essentials/MobCompat.java index 9107ba32c..e54e20800 100644 --- a/Essentials/src/com/earth2me/essentials/MobCompat.java +++ b/Essentials/src/com/earth2me/essentials/MobCompat.java @@ -18,9 +18,10 @@ import java.lang.reflect.Method; import static com.earth2me.essentials.utils.EnumUtil.getEntityType; -public class MobCompat { +public final class MobCompat { // Constants for mob interfaces added in later versions + @SuppressWarnings("rawtypes") public static final Class RAIDER = ReflUtil.getClassCached("org.bukkit.entity.Raider"); // Constants for mobs added in later versions @@ -38,6 +39,119 @@ public class MobCompat { public static final EntityType CAT = getEntityType("CAT", "OCELOT"); public static final EntityType ZOMBIFIED_PIGLIN = getEntityType("ZOMBIFIED_PIGLIN", "PIG_ZOMBIE"); + private MobCompat() { + } + + // Older cats are Ocelots, whereas 1.14+ cats are Cats + public static void setCatType(final Entity entity, final CatType type) { + if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_14_R01)) { + ((Ocelot) entity).setCatType(Ocelot.Type.valueOf(type.ocelotTypeName)); + } else { + final Class cat = ReflUtil.getClassCached("org.bukkit.entity.Cat"); + final Class catType = ReflUtil.getClassCached("org.bukkit.entity.Cat$Type"); + final Method setCatType = ReflUtil.getMethodCached(cat, "setCatType", catType); + try { + setCatType.invoke(entity, EnumUtil.valueOf(catType, type.catTypeName)); + } catch (final Exception e) { + e.printStackTrace(); + } + } + } + + // Older villagers have professions and careers, 1.14+ villagers only have professions + public static void setVillagerProfession(final Entity entity, final VillagerProfession profession) { + if (!(entity instanceof Villager)) { + return; + } + final Villager villager = (Villager) entity; + villager.setProfession(profession.asEnum()); + if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_14_R01)) { + final Class villagerCareer = ReflUtil.getClassCached("org.bukkit.entity.Villager$Career"); + final Method setCareer = ReflUtil.getMethodCached(Villager.class, "setCareer", villagerCareer); + try { + setCareer.invoke(entity, EnumUtil.valueOf(villagerCareer, profession.oldCareer)); + } catch (final Exception e) { + e.printStackTrace(); + } + } + } + + // Only 1.14+ villagers have biome variants + public static void setVillagerType(final Entity entity, final String type) { + if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_14_R01)) { + return; + } + if (entity instanceof Villager) { + ((Villager) entity).setVillagerType(Villager.Type.valueOf(type)); + } + } + + // Llamas only exist in 1.11+ + public static void setLlamaColor(final Entity entity, final String color) { + if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_11_R01)) { + return; + } + if (entity instanceof Llama) { + ((Llama) entity).setColor(Llama.Color.valueOf(color)); + } + } + + // Parrots only exist in 1.12+ + public static void setParrotVariant(final Entity entity, final String variant) { + if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_12_0_R01)) { + return; + } + if (entity instanceof Parrot) { + ((Parrot) entity).setVariant(Parrot.Variant.valueOf(variant)); + } + } + + // Tropical fish only exist in 1.13+ + public static void setTropicalFishPattern(final Entity entity, final String pattern) { + if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_12_0_R01)) { + return; + } + if (entity instanceof TropicalFish) { + ((TropicalFish) entity).setPattern(TropicalFish.Pattern.valueOf(pattern)); + } + } + + // Mushroom cow variant API only exists in 1.14+ + public static void setMooshroomVariant(final Entity entity, final String variant) { + if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_14_R01)) { + return; + } + if (entity instanceof MushroomCow) { + ((MushroomCow) entity).setVariant(MushroomCow.Variant.valueOf(variant)); + } + } + + // Pandas only exists in 1.14+ + public static void setPandaGene(final Entity entity, final String gene, final boolean mainGene) { + if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_14_R01)) { + return; + } + if (entity instanceof Panda) { + final Panda panda = (Panda) entity; + final Panda.Gene pandaGene = Panda.Gene.valueOf(gene); + if (mainGene) { + panda.setMainGene(pandaGene); + } else { + panda.setHiddenGene(pandaGene); + } + } + } + + // Foxes only exist in 1.14+ + public static void setFoxType(final Entity entity, final String type) { + if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_14_R01)) { + return; + } + if (entity instanceof Fox) { + ((Fox) entity).setFoxType(Fox.Type.valueOf(type)); + } + } + public enum CatType { // These are (loosely) Mojang names for the cats SIAMESE("SIAMESE", "SIAMESE_CAT"), @@ -102,114 +216,4 @@ public class MobCompat { } } - // Older cats are Ocelots, whereas 1.14+ cats are Cats - public static void setCatType(final Entity entity, final CatType type) { - if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_14_R01)) { - ((Ocelot) entity).setCatType(Ocelot.Type.valueOf(type.ocelotTypeName)); - } else { - Class cat = ReflUtil.getClassCached("org.bukkit.entity.Cat"); - Class catType = ReflUtil.getClassCached("org.bukkit.entity.Cat$Type"); - Method setCatType = ReflUtil.getMethodCached(cat, "setCatType", catType); - try { - setCatType.invoke(entity, EnumUtil.valueOf(catType, type.catTypeName)); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - // Older villagers have professions and careers, 1.14+ villagers only have professions - public static void setVillagerProfession(final Entity entity, final VillagerProfession profession) { - if (!(entity instanceof Villager)) { - return; - } - Villager villager = (Villager) entity; - villager.setProfession(profession.asEnum()); - if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_14_R01)) { - Class villagerCareer = ReflUtil.getClassCached("org.bukkit.entity.Villager$Career"); - Method setCareer = ReflUtil.getMethodCached(Villager.class, "setCareer", villagerCareer); - try { - setCareer.invoke(entity, EnumUtil.valueOf(villagerCareer, profession.oldCareer)); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - // Only 1.14+ villagers have biome variants - public static void setVillagerType(final Entity entity, final String type) { - if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_14_R01)) { - return; - } - if (entity instanceof Villager) { - ((Villager) entity).setVillagerType(Villager.Type.valueOf(type)); - } - } - - // Llamas only exist in 1.11+ - public static void setLlamaColor(final Entity entity, final String color) { - if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_11_R01)) { - return; - } - if (entity instanceof Llama) { - ((Llama) entity).setColor(Llama.Color.valueOf(color)); - } - } - - // Parrots only exist in 1.12+ - public static void setParrotVariant(final Entity entity, final String variant) { - if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_12_0_R01)) { - return; - } - if (entity instanceof Parrot) { - ((Parrot) entity).setVariant(Parrot.Variant.valueOf(variant)); - } - } - - // Tropical fish only exist in 1.13+ - public static void setTropicalFishPattern(final Entity entity, final String pattern) { - if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_12_0_R01)) { - return; - } - if (entity instanceof TropicalFish) { - ((TropicalFish) entity).setPattern(TropicalFish.Pattern.valueOf(pattern)); - } - } - - // Mushroom cow variant API only exists in 1.14+ - public static void setMooshroomVariant(final Entity entity, final String variant) { - if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_14_R01)) { - return; - } - if (entity instanceof MushroomCow) { - ((MushroomCow) entity).setVariant(MushroomCow.Variant.valueOf(variant)); - } - } - - // Pandas only exists in 1.14+ - public static void setPandaGene(final Entity entity, final String gene, final boolean mainGene) { - if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_14_R01)) { - return; - } - if (entity instanceof Panda) { - Panda panda = (Panda) entity; - Panda.Gene pandaGene = Panda.Gene.valueOf(gene); - if (mainGene) { - panda.setMainGene(pandaGene); - } else { - panda.setHiddenGene(pandaGene); - } - } - } - - // Foxes only exist in 1.14+ - public static void setFoxType(final Entity entity, final String type) { - if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_14_R01)) { - return; - } - if (entity instanceof Fox) { - ((Fox) entity).setFoxType(Fox.Type.valueOf(type)); - } - } - } diff --git a/Essentials/src/com/earth2me/essentials/MobData.java b/Essentials/src/com/earth2me/essentials/MobData.java index 67653e4d9..5d9c6b137 100644 --- a/Essentials/src/com/earth2me/essentials/MobData.java +++ b/Essentials/src/com/earth2me/essentials/MobData.java @@ -5,18 +5,38 @@ import com.earth2me.essentials.utils.EnumUtil; import com.earth2me.essentials.utils.StringUtil; import org.bukkit.DyeColor; import org.bukkit.Material; -import org.bukkit.entity.*; +import org.bukkit.entity.Ageable; +import org.bukkit.entity.Creeper; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.ExperienceOrb; +import org.bukkit.entity.Horse; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Phantom; +import org.bukkit.entity.Pig; +import org.bukkit.entity.Player; +import org.bukkit.entity.Raider; +import org.bukkit.entity.Slime; +import org.bukkit.entity.Tameable; +import org.bukkit.entity.TropicalFish; +import org.bukkit.entity.Wolf; +import org.bukkit.entity.Zombie; import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.ItemStack; import org.bukkit.material.Colorable; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Random; import java.util.logging.Logger; import java.util.stream.Collectors; import static com.earth2me.essentials.I18n.tl; - public enum MobData { BABY_AGEABLE("baby", Ageable.class, Data.BABY, true), @@ -165,29 +185,7 @@ public enum MobData { TROPICAL_FISH_PATTERN_COLOR("fish_pattern_color", Arrays.stream(DyeColor.values()).map(color -> color.name().toLowerCase(Locale.ENGLISH) + "pattern").collect(Collectors.toList()), MobCompat.TROPICAL_FISH, Data.FISH_PATTERN_COLOR, true), ; - - public enum Data { - ADULT, - BABY, - CHEST, - ADULTZOMBIE, - BABYZOMBIE, - HORSESADDLE, - PIGSADDLE, - ELECTRIFIED, - ANGRY, - TAMED, - COLORABLE, - EXP, - SIZE, - RAID_LEADER, - FISH_BODY_COLOR, - FISH_PATTERN_COLOR, - } - - public static final Logger logger = Logger.getLogger("Essentials"); - final private String nickname; final private List suggestions; final private Object type; @@ -195,7 +193,7 @@ public enum MobData { final private boolean isPublic; private String matched; - MobData(String n, Object type, Object value, boolean isPublic) { + MobData(final String n, final Object type, final Object value, final boolean isPublic) { this.nickname = n; this.matched = n; this.suggestions = Collections.singletonList(n); @@ -204,7 +202,7 @@ public enum MobData { this.isPublic = isPublic; } - MobData(String n, List s, Object type, Object value, boolean isPublic) { + MobData(final String n, final List s, final Object type, final Object value, final boolean isPublic) { this.nickname = n; this.matched = n; this.suggestions = s; @@ -213,9 +211,9 @@ public enum MobData { this.isPublic = isPublic; } - public static LinkedHashMap getPossibleData(final Entity spawned, boolean publicOnly) { - LinkedHashMap mobList = new LinkedHashMap<>(); - for (MobData data : MobData.values()) { + public static LinkedHashMap getPossibleData(final Entity spawned, final boolean publicOnly) { + final LinkedHashMap mobList = new LinkedHashMap<>(); + for (final MobData data : MobData.values()) { if (data.type == null || (publicOnly && !data.isPublic)) { continue; } @@ -230,10 +228,10 @@ public enum MobData { } public static List getValidHelp(final Entity spawned) { - List output = new ArrayList<>(); - LinkedHashMap posData = getPossibleData(spawned, true); + final List output = new ArrayList<>(); + final LinkedHashMap posData = getPossibleData(spawned, true); - for (MobData data : posData.values()) { + for (final MobData data : posData.values()) { output.add(StringUtil.joinList(data.suggestions)); } return output; @@ -244,9 +242,9 @@ public enum MobData { return null; } - LinkedHashMap posData = getPossibleData(spawned, false); - for (MobData data : posData.values()) { - for (String suggestion : data.suggestions) { + final LinkedHashMap posData = getPossibleData(spawned, false); + for (final MobData data : posData.values()) { + for (final String suggestion : data.suggestions) { if (name.contains(suggestion)) { return data; } @@ -273,14 +271,14 @@ public enum MobData { } else if (this.value.equals(Data.ELECTRIFIED)) { ((Creeper) spawned).setPowered(true); } else if (this.value.equals(Data.HORSESADDLE)) { - final Horse horse = ((Horse) spawned); + final Horse horse = (Horse) spawned; horse.setTamed(true); horse.setOwner(target); horse.getInventory().setSaddle(new ItemStack(Material.SADDLE, 1)); } else if (this.value.equals(Data.PIGSADDLE)) { ((Pig) spawned).setSaddle(true); } else if (this.value.equals(Data.TAMED)) { - final Tameable tameable = ((Tameable) spawned); + final Tameable tameable = (Tameable) spawned; tameable.setTamed(true); tameable.setOwner(target); } else if (this.value.equals(Data.COLORABLE)) { @@ -293,26 +291,26 @@ public enum MobData { ((Colorable) spawned).setColor(DyeColor.valueOf(color)); } this.matched = rawData; - } catch (Exception e) { + } catch (final Exception e) { throw new Exception(tl("sheepMalformedColor"), e); } } else if (this.value.equals(Data.EXP)) { try { ((ExperienceOrb) spawned).setExperience(Integer.parseInt(rawData)); this.matched = rawData; - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { throw new Exception(tl("invalidNumber"), e); } } else if (this.value.equals(Data.SIZE)) { try { - int size = Integer.parseInt(rawData); + final int size = Integer.parseInt(rawData); if (spawned instanceof Slime) { ((Slime) spawned).setSize(size); } else if (spawned.getType() == MobCompat.PHANTOM) { ((Phantom) spawned).setSize(size); } this.matched = rawData; - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { throw new Exception(tl("slimeMalformedSize"), e); } } else if (this.value instanceof Horse.Color) { @@ -335,7 +333,7 @@ public enum MobData { } else if (this.value.equals(Data.RAID_LEADER)) { ((Raider) spawned).setPatrolLeader(true); } else if (this.value.equals(Data.FISH_BODY_COLOR)) { - for (String match : TROPICAL_FISH_BODY_COLOR.suggestions) { + for (final String match : TROPICAL_FISH_BODY_COLOR.suggestions) { if (rawData.contains(match)) { this.matched = match; final String color = match.substring(0, match.indexOf("body")).toUpperCase(Locale.ENGLISH); @@ -344,7 +342,7 @@ public enum MobData { } } } else if (this.value.equals(Data.FISH_PATTERN_COLOR)) { - for (String match : TROPICAL_FISH_PATTERN_COLOR.suggestions) { + for (final String match : TROPICAL_FISH_PATTERN_COLOR.suggestions) { if (rawData.contains(match)) { this.matched = match; final String color = match.substring(0, match.indexOf("pattern")).toUpperCase(Locale.ENGLISH); @@ -384,4 +382,23 @@ public enum MobData { logger.warning("Unknown mob data type: " + this.toString()); } } + + public enum Data { + ADULT, + BABY, + CHEST, + ADULTZOMBIE, + BABYZOMBIE, + HORSESADDLE, + PIGSADDLE, + ELECTRIFIED, + ANGRY, + TAMED, + COLORABLE, + EXP, + SIZE, + RAID_LEADER, + FISH_BODY_COLOR, + FISH_PATTERN_COLOR, + } } diff --git a/Essentials/src/com/earth2me/essentials/PlayerExtension.java b/Essentials/src/com/earth2me/essentials/PlayerExtension.java index 211f6ee9c..23bbb5a3a 100644 --- a/Essentials/src/com/earth2me/essentials/PlayerExtension.java +++ b/Essentials/src/com/earth2me/essentials/PlayerExtension.java @@ -5,7 +5,6 @@ import org.bukkit.Server; import org.bukkit.World; import org.bukkit.entity.Player; - public class PlayerExtension { protected Player base; diff --git a/Essentials/src/com/earth2me/essentials/PlayerList.java b/Essentials/src/com/earth2me/essentials/PlayerList.java index 9e4f90092..423e7146f 100644 --- a/Essentials/src/com/earth2me/essentials/PlayerList.java +++ b/Essentials/src/com/earth2me/essentials/PlayerList.java @@ -4,18 +4,27 @@ import com.earth2me.essentials.utils.FormatUtil; import org.bukkit.ChatColor; import org.bukkit.Server; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; import static com.earth2me.essentials.I18n.tl; +public final class PlayerList { + + private PlayerList() { + } -public class PlayerList { // Cosmetic list formatting public static String listUsers(final IEssentials ess, final List users, final String seperator) { final StringBuilder groupString = new StringBuilder(); Collections.sort(users); boolean needComma = false; - for (User user : users) { + for (final User user : users) { if (needComma) { groupString.append(seperator); } @@ -38,10 +47,10 @@ public class PlayerList { // Produce a user summary: There are 5 out of maximum 10 players online. public static String listSummary(final IEssentials ess, final User user, final boolean showHidden) { - Server server = ess.getServer(); + final Server server = ess.getServer(); int playerHidden = 0; int hiddenCount = 0; - for (User onlinePlayer : ess.getOnlineUsers()) { + for (final User onlinePlayer : ess.getOnlineUsers()) { if (onlinePlayer.isHidden() || (user != null && !user.getBase().canSee(onlinePlayer.getBase()))) { playerHidden++; if (showHidden || user != null && user.getBase().canSee(onlinePlayer.getBase())) { @@ -49,7 +58,7 @@ public class PlayerList { } } } - String online; + final String online; if (hiddenCount > 0) { online = tl("listAmountHidden", ess.getOnlinePlayers().size() - playerHidden, hiddenCount, server.getMaxPlayers()); } else { @@ -61,12 +70,12 @@ public class PlayerList { // Build the basic player list, divided by groups. public static Map> getPlayerLists(final IEssentials ess, final IUser sender, final boolean showHidden) { final Map> playerList = new HashMap<>(); - for (User onlineUser : ess.getOnlineUsers()) { + for (final User onlineUser : ess.getOnlineUsers()) { if ((sender == null && !showHidden && onlineUser.isHidden()) || (sender != null && !showHidden && !sender.getBase().canSee(onlineUser.getBase()))) { continue; } final String group = FormatUtil.stripFormat(FormatUtil.stripEssentialsFormat(onlineUser.getGroup().toLowerCase())); - List list = playerList.computeIfAbsent(group, k -> new ArrayList<>()); + final List list = playerList.computeIfAbsent(group, k -> new ArrayList<>()); list.add(onlineUser); } return playerList; @@ -76,15 +85,15 @@ public class PlayerList { public static List getMergedList(final IEssentials ess, final Map> playerList, final String groupName) { final Set configGroups = ess.getSettings().getListGroupConfig().keySet(); final List users = new ArrayList<>(); - for (String configGroup : configGroups) { + for (final String configGroup : configGroups) { if (configGroup.equalsIgnoreCase(groupName)) { - String[] groupValues = ess.getSettings().getListGroupConfig().get(configGroup).toString().trim().split(" "); + final String[] groupValues = ess.getSettings().getListGroupConfig().get(configGroup).toString().trim().split(" "); for (String groupValue : groupValues) { groupValue = groupValue.toLowerCase(Locale.ENGLISH); if (groupValue.isEmpty()) { continue; } - List u = playerList.get(groupValue.trim()); + final List u = playerList.get(groupValue.trim()); if (u == null || u.isEmpty()) { continue; } @@ -106,7 +115,7 @@ public class PlayerList { if (users.isEmpty()) { throw new Exception(tl("groupDoesNotExist")); } - String displayGroupName = Character.toTitleCase(groupName.charAt(0)) + + final String displayGroupName = Character.toTitleCase(groupName.charAt(0)) + groupName.substring(1); return outputFormat(displayGroupName, listUsers(ess, users, ", ")); } diff --git a/Essentials/src/com/earth2me/essentials/PlayerTarget.java b/Essentials/src/com/earth2me/essentials/PlayerTarget.java index d582f612e..e13b1cb25 100644 --- a/Essentials/src/com/earth2me/essentials/PlayerTarget.java +++ b/Essentials/src/com/earth2me/essentials/PlayerTarget.java @@ -4,11 +4,10 @@ import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; - public class PlayerTarget implements ITarget { private final String name; - public PlayerTarget(Player entity) { + public PlayerTarget(final Player entity) { this.name = entity.getName(); } @@ -16,4 +15,4 @@ public class PlayerTarget implements ITarget { public Location getLocation() { return Bukkit.getServer().getPlayerExact(name).getLocation(); } -} \ No newline at end of file +} diff --git a/Essentials/src/com/earth2me/essentials/Potions.java b/Essentials/src/com/earth2me/essentials/Potions.java index e86842f87..b174a03c1 100644 --- a/Essentials/src/com/earth2me/essentials/Potions.java +++ b/Essentials/src/com/earth2me/essentials/Potions.java @@ -9,8 +9,7 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; - -public class Potions { +public final class Potions { private static final Map POTIONS = new HashMap<>(); private static final Map ALIASPOTIONS = new HashMap<>(); @@ -124,10 +123,14 @@ public class Potions { POTIONS.put("luck", PotionEffectType.LUCK); POTIONS.put("unluck", PotionEffectType.UNLUCK); - } catch (Throwable ignored) {} + } catch (final Throwable ignored) { + } } - public static PotionEffectType getByName(String name) { + private Potions() { + } + + public static PotionEffectType getByName(final String name) { PotionEffectType peffect; if (NumberUtil.isInt(name)) { peffect = PotionEffectType.getById(Integer.parseInt(name)); diff --git a/Essentials/src/com/earth2me/essentials/RandomTeleport.java b/Essentials/src/com/earth2me/essentials/RandomTeleport.java index 29b9b3d84..d9e928858 100644 --- a/Essentials/src/com/earth2me/essentials/RandomTeleport.java +++ b/Essentials/src/com/earth2me/essentials/RandomTeleport.java @@ -18,15 +18,15 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; public class RandomTeleport implements IConf { + private static final Random RANDOM = new Random(); + private static final int HIGHEST_BLOCK_Y_OFFSET = VersionUtil.getServerBukkitVersion().isHigherThanOrEqualTo(VersionUtil.v1_15_R01) ? 1 : 0; private final IEssentials essentials; private final EssentialsConf config; private final ConcurrentLinkedQueue cachedLocations = new ConcurrentLinkedQueue<>(); - private static final Random RANDOM = new Random(); - private static final int HIGHEST_BLOCK_Y_OFFSET = VersionUtil.getServerBukkitVersion().isHigherThanOrEqualTo(VersionUtil.v1_15_R01) ? 1 : 0; public RandomTeleport(final IEssentials essentials) { this.essentials = essentials; - File file = new File(essentials.getDataFolder(), "tpr.yml"); + final File file = new File(essentials.getDataFolder(), "tpr.yml"); config = new EssentialsConf(file); config.setTemplateName("/tpr.yml"); config.options().copyHeader(true); @@ -41,19 +41,19 @@ public class RandomTeleport implements IConf { public Location getCenter() { try { - Location center = config.getLocation("center", essentials.getServer()); + final Location center = config.getLocation("center", essentials.getServer()); if (center != null) { return center; } - } catch (InvalidWorldException ignored) { + } catch (final InvalidWorldException ignored) { } - Location center = essentials.getServer().getWorlds().get(0).getWorldBorder().getCenter(); + final Location center = essentials.getServer().getWorlds().get(0).getWorldBorder().getCenter(); center.setY(center.getWorld().getHighestBlockYAt(center) + 1); setCenter(center); return center; } - public void setCenter(Location center) { + public void setCenter(final Location center) { config.setProperty("center", center); config.save(); } @@ -62,7 +62,7 @@ public class RandomTeleport implements IConf { return config.getDouble("min-range", 0d); } - public void setMinRange(double minRange) { + public void setMinRange(final double minRange) { config.setProperty("min-range", minRange); config.save(); } @@ -71,18 +71,18 @@ public class RandomTeleport implements IConf { return config.getDouble("max-range", getCenter().getWorld().getWorldBorder().getSize() / 2); } - public void setMaxRange(double maxRange) { + public void setMaxRange(final double maxRange) { config.setProperty("max-range", maxRange); config.save(); } public Set getExcludedBiomes() { - List biomeNames = config.getStringList("excluded-biomes"); - Set excludedBiomes = new HashSet<>(); - for (String biomeName : biomeNames) { + final List biomeNames = config.getStringList("excluded-biomes"); + final Set excludedBiomes = new HashSet<>(); + for (final String biomeName : biomeNames) { try { excludedBiomes.add(Biome.valueOf(biomeName.toUpperCase())); - } catch (IllegalArgumentException ignored) { + } catch (final IllegalArgumentException ignored) { } } return excludedBiomes; @@ -105,14 +105,14 @@ public class RandomTeleport implements IConf { } // Get a random location; cached if possible. Otherwise on demand. - public CompletableFuture getRandomLocation(Location center, double minRange, double maxRange) { - int findAttempts = this.getFindAttempts(); - Queue cachedLocations = this.getCachedLocations(); + public CompletableFuture getRandomLocation(final Location center, final double minRange, final double maxRange) { + final int findAttempts = this.getFindAttempts(); + final Queue cachedLocations = this.getCachedLocations(); // Try to build up the cache if it is below the threshold if (cachedLocations.size() < this.getCacheThreshold()) { cacheRandomLocations(center, minRange, maxRange); } - CompletableFuture future = new CompletableFuture<>(); + final CompletableFuture future = new CompletableFuture<>(); // Return a random location immediately if one is available, otherwise try to find one now if (cachedLocations.isEmpty()) { attemptRandomLocation(findAttempts, center, minRange, maxRange).thenAccept(future::complete); @@ -123,7 +123,7 @@ public class RandomTeleport implements IConf { } // Prompts caching random valid locations, up to a maximum number of attempts - public void cacheRandomLocations(Location center, double minRange, double maxRange) { + public void cacheRandomLocations(final Location center, final double minRange, final double maxRange) { essentials.getServer().getScheduler().scheduleSyncDelayedTask(essentials, () -> { for (int i = 0; i < this.getFindAttempts(); ++i) { calculateRandomLocation(center, minRange, maxRange).thenAccept(location -> { @@ -136,8 +136,8 @@ public class RandomTeleport implements IConf { } // Recursively attempt to find a random location. After a maximum number of attempts, the center is returned. - private CompletableFuture attemptRandomLocation(int attempts, Location center, double minRange, double maxRange) { - CompletableFuture future = new CompletableFuture<>(); + private CompletableFuture attemptRandomLocation(final int attempts, final Location center, final double minRange, final double maxRange) { + final CompletableFuture future = new CompletableFuture<>(); if (attempts > 0) { calculateRandomLocation(center, minRange, maxRange).thenAccept(location -> { if (isValidRandomLocation(location)) { @@ -153,13 +153,14 @@ public class RandomTeleport implements IConf { } // Calculates a random location asynchronously. - private CompletableFuture calculateRandomLocation(Location center, double minRange, double maxRange) { - CompletableFuture future = new CompletableFuture<>(); + private CompletableFuture calculateRandomLocation(final Location center, final double minRange, final double maxRange) { + final CompletableFuture future = new CompletableFuture<>(); // Find an equally distributed offset by randomly rotating a point inside a rectangle about the origin - double rectX = RANDOM.nextDouble() * (maxRange - minRange) + minRange; - double rectZ = RANDOM.nextDouble() * (maxRange + minRange) - minRange; - double offsetX, offsetZ; - int transform = RANDOM.nextInt(4); + final double rectX = RANDOM.nextDouble() * (maxRange - minRange) + minRange; + final double rectZ = RANDOM.nextDouble() * (maxRange + minRange) - minRange; + final double offsetX; + final double offsetZ; + final int transform = RANDOM.nextInt(4); if (transform == 0) { offsetX = rectX; offsetZ = rectZ; @@ -173,13 +174,13 @@ public class RandomTeleport implements IConf { offsetX = rectZ; offsetZ = -rectX; } - Location location = new Location( - center.getWorld(), - center.getX() + offsetX, - center.getWorld().getMaxHeight(), - center.getZ() + offsetZ, - 360 * RANDOM.nextFloat() - 180, - 0 + final Location location = new Location( + center.getWorld(), + center.getX() + offsetX, + center.getWorld().getMaxHeight(), + center.getZ() + offsetZ, + 360 * RANDOM.nextFloat() - 180, + 0 ); PaperLib.getChunkAtAsync(location).thenAccept(chunk -> { if (World.Environment.NETHER.equals(center.getWorld().getEnvironment())) { @@ -193,7 +194,7 @@ public class RandomTeleport implements IConf { } // Returns an appropriate elevation for a given location in the nether, or -1 if none is found - private double getNetherYAt(Location location) { + private double getNetherYAt(final Location location) { for (int y = 32; y < location.getWorld().getMaxHeight() / 2; ++y) { if (!LocationUtil.isBlockUnsafe(location.getWorld(), location.getBlockX(), y, location.getBlockZ())) { return y; @@ -202,7 +203,7 @@ public class RandomTeleport implements IConf { return -1; } - private boolean isValidRandomLocation(Location location) { + private boolean isValidRandomLocation(final Location location) { return location.getBlockY() > 0 && !this.getExcludedBiomes().contains(location.getBlock().getBiome()); } } diff --git a/Essentials/src/com/earth2me/essentials/Settings.java b/Essentials/src/com/earth2me/essentials/Settings.java index 14dbaba74..605b82f59 100644 --- a/Essentials/src/com/earth2me/essentials/Settings.java +++ b/Essentials/src/com/earth2me/essentials/Settings.java @@ -43,13 +43,94 @@ import java.util.regex.PatternSyntaxException; import static com.earth2me.essentials.I18n.tl; - public class Settings implements net.ess3.api.ISettings { - private final transient EssentialsConf config; private static final Logger logger = Logger.getLogger("Essentials"); + private static final BigDecimal MAXMONEY = new BigDecimal("10000000000000"); + private static final BigDecimal MINMONEY = new BigDecimal("-10000000000000"); + private final transient EssentialsConf config; private final transient IEssentials ess; + private final Map chatFormats = Collections.synchronizedMap(new HashMap<>()); + private int chatRadius = 0; + // #easteregg + private char chatShout = '!'; + // #easteregg + private char chatQuestion = '?'; + private boolean teleportSafety; + private boolean forceDisableTeleportSafety; + private Set disabledCommands = new HashSet<>(); + private ConfigurationSection commandCosts; + private Set socialSpyCommands = new HashSet<>(); + private Set muteCommands = new HashSet<>(); + private String nicknamePrefix = "~"; + private String operatorColor = null; + private List itemSpawnBl = new ArrayList<>(); + private List enabledSigns = new ArrayList<>(); + private boolean signsEnabled = false; + private boolean warnOnBuildDisallow; + private boolean debug = false; + private boolean configDebug = false; + // #easteregg + private boolean economyDisabled = false; + private BigDecimal maxMoney = MAXMONEY; + private BigDecimal minMoney = MINMONEY; + private boolean economyLog = false; + // #easteregg + private boolean economyLogUpdate = false; + private boolean changeDisplayName = true; + private boolean changePlayerListName = false; + private boolean prefixsuffixconfigured = false; + private boolean addprefixsuffix = false; + private boolean essentialsChatActive = false; + // #easteregg + private boolean disablePrefix = false; + // #easteregg + private boolean disableSuffix = false; + private boolean getFreezeAfkPlayers; + private boolean cancelAfkOnMove; + private boolean cancelAfkOnInteract; + private boolean sleepIgnoresAfkPlayers; + private String afkListName; + private boolean isAfkListName; + private boolean broadcastAfkMessage; + private KeepInvPolicy vanishingItemPolicy; + private KeepInvPolicy bindingItemPolicy; + private Set noGodWorlds = new HashSet<>(); + private boolean registerBackInListener; + private boolean disableItemPickupWhileAfk; + private long teleportInvulnerabilityTime; + private boolean teleportInvulnerability; + private long loginAttackDelay; + private int signUsePerSecond; + private int mailsPerMinute; + // #easteregg + private long economyLagWarning; + // #easteregg + private long permissionsLagWarning; + private boolean allowSilentJoin; + private String customJoinMessage; + private boolean isCustomJoinMessage; + private String customQuitMessage; + private boolean isCustomQuitMessage; + private List spawnOnJoinGroups; + private Map commandCooldowns; + private boolean npcsInBalanceRanking = false; + private NumberFormat currencyFormat; + private List unprotectedSigns = Collections.emptyList(); + private List defaultEnabledConfirmCommands; + private boolean teleportBackWhenFreedFromJail; + private boolean isCompassTowardsHomePerm; + private boolean isAllowWorldInBroadcastworld; + private String itemDbType; // #EasterEgg - admins can manually switch items provider if they want + private boolean forceEnableRecipe; // https://github.com/EssentialsX/Essentials/issues/1397 + private boolean allowOldIdSigns; + private boolean isWaterSafe; + private boolean isSafeUsermap; + private boolean logCommandBlockCommands; + private Set> nickBlacklist; + private double maxProjectileSpeed; + private boolean removeEffectsOnHeal; - public Settings(IEssentials ess) { + public Settings(final IEssentials ess) { this.ess = ess; config = new EssentialsConf(new File(ess.getDataFolder(), "config.yml")); config.setTemplateName("/config.yml"); @@ -86,7 +167,7 @@ public class Settings implements net.ess3.api.ISettings { final Set homeList = getMultipleHomes(); if (homeList != null) { - for (String set : homeList) { + for (final String set : homeList) { if (user.isAuthorized("essentials.sethome.multiple." + set) && (limit < getHomeLimit(set))) { limit = getHomeLimit(set); } @@ -100,8 +181,6 @@ public class Settings implements net.ess3.api.ISettings { return config.getInt("sethome-multiple." + set, config.getInt("sethome-multiple.default", 3)); } - private int chatRadius = 0; - private int _getChatRadius() { return config.getInt("chat.radius", config.getInt("chat-radius", 0)); } @@ -116,9 +195,6 @@ public class Settings implements net.ess3.api.ISettings { return config.getInt("near-radius", 200); } - // #easteregg - private char chatShout = '!'; - private char _getChatShout() { return config.getString("chat.shout", "!").charAt(0); } @@ -128,9 +204,6 @@ public class Settings implements net.ess3.api.ISettings { return chatShout; } - // #easteregg - private char chatQuestion = '?'; - private char _getChatQuestion() { return config.getString("chat.question", "?").charAt(0); } @@ -140,8 +213,6 @@ public class Settings implements net.ess3.api.ISettings { return chatQuestion; } - private boolean teleportSafety; - public boolean _isTeleportSafetyEnabled() { return config.getBoolean("teleport-safety", true); } @@ -151,8 +222,6 @@ public class Settings implements net.ess3.api.ISettings { return teleportSafety; } - private boolean forceDisableTeleportSafety; - private boolean _isForceDisableTeleportSafety() { return config.getBoolean("force-disable-teleport-safety", false); } @@ -202,19 +271,17 @@ public class Settings implements net.ess3.api.ISettings { return isCommandDisabled(cmd.getName()); } - private Set disabledCommands = new HashSet<>(); - @Override - public boolean isCommandDisabled(String label) { + public boolean isCommandDisabled(final String label) { return disabledCommands.contains(label); } private Set getDisabledCommands() { - Set disCommands = new HashSet<>(); - for (String c : config.getStringList("disabled-commands")) { + final Set disCommands = new HashSet<>(); + for (final String c : config.getStringList("disabled-commands")) { disCommands.add(c.toLowerCase(Locale.ENGLISH)); } - for (String c : config.getKeys(false)) { + for (final String c : config.getKeys(false)) { if (c.startsWith("disable-")) { disCommands.add(c.substring(8).toLowerCase(Locale.ENGLISH)); } @@ -223,8 +290,8 @@ public class Settings implements net.ess3.api.ISettings { } @Override - public boolean isPlayerCommand(String label) { - for (String c : config.getStringList("player-commands")) { + public boolean isPlayerCommand(final String label) { + for (final String c : config.getStringList("player-commands")) { if (!c.equalsIgnoreCase(label)) { continue; } @@ -234,8 +301,8 @@ public class Settings implements net.ess3.api.ISettings { } @Override - public boolean isCommandOverridden(String name) { - for (String c : config.getStringList("overridden-commands")) { + public boolean isCommandOverridden(final String name) { + for (final String c : config.getStringList("overridden-commands")) { if (!c.equalsIgnoreCase(name)) { continue; } @@ -244,10 +311,8 @@ public class Settings implements net.ess3.api.ISettings { return config.getBoolean("override-" + name.toLowerCase(Locale.ENGLISH), false); } - private ConfigurationSection commandCosts; - @Override - public BigDecimal getCommandCost(IEssentialsCommand cmd) { + public BigDecimal getCommandCost(final IEssentialsCommand cmd) { return getCommandCost(cmd.getName()); } @@ -255,7 +320,7 @@ public class Settings implements net.ess3.api.ISettings { if (config.isConfigurationSection("command-costs")) { final ConfigurationSection section = config.getConfigurationSection("command-costs"); final ConfigurationSection newSection = new MemoryConfiguration(); - for (String command : section.getKeys(false)) { + for (final String command : section.getKeys(false)) { if (command.charAt(0) == '/') { ess.getLogger().warning("Invalid command cost. '" + command + "' should not start with '/'."); } @@ -264,11 +329,11 @@ public class Settings implements net.ess3.api.ISettings { } else if (section.isInt(command)) { newSection.set(command.toLowerCase(Locale.ENGLISH), (double) section.getInt(command)); } else if (section.isString(command)) { - String costString = section.getString(command); + final String costString = section.getString(command); try { - double cost = Double.parseDouble(costString.trim().replace(getCurrencySymbol(), "").replaceAll("\\W", "")); + final double cost = Double.parseDouble(costString.trim().replace(getCurrencySymbol(), "").replaceAll("\\W", "")); newSection.set(command.toLowerCase(Locale.ENGLISH), cost); - } catch (NumberFormatException ex) { + } catch (final NumberFormatException ex) { ess.getLogger().warning("Invalid command cost for: " + command + " (" + costString + ")"); } @@ -290,13 +355,11 @@ public class Settings implements net.ess3.api.ISettings { return BigDecimal.ZERO; } - private Set socialSpyCommands = new HashSet<>(); - private Set _getSocialSpyCommands() { - Set socialspyCommands = new HashSet<>(); + final Set socialspyCommands = new HashSet<>(); if (config.isList("socialspy-commands")) { - for (String c : config.getStringList("socialspy-commands")) { + for (final String c : config.getStringList("socialspy-commands")) { socialspyCommands.add(c.toLowerCase(Locale.ENGLISH)); } } else { @@ -316,12 +379,10 @@ public class Settings implements net.ess3.api.ISettings { return config.getBoolean("socialspy-listen-muted-players", true); } - private Set muteCommands = new HashSet<>(); - private Set _getMuteCommands() { - Set muteCommands = new HashSet<>(); + final Set muteCommands = new HashSet<>(); if (config.isList("mute-commands")) { - for (String s : config.getStringList("mute-commands")) { + for (final String s : config.getStringList("mute-commands")) { muteCommands.add(s.toLowerCase(Locale.ENGLISH)); } } @@ -334,8 +395,6 @@ public class Settings implements net.ess3.api.ISettings { return muteCommands; } - private String nicknamePrefix = "~"; - private String _getNicknamePrefix() { return config.getString("nickname-prefix", "~"); } @@ -361,12 +420,12 @@ public class Settings implements net.ess3.api.ISettings { } @Override - public Map getKit(String name) { + public Map getKit(final String name) { return ess.getKits().getKit(name); } @Override - public void addKit(String name, List lines, long delay) { + public void addKit(final String name, final List lines, final long delay) { ess.getKits().addKit(name, lines, delay); } @@ -380,15 +439,13 @@ public class Settings implements net.ess3.api.ISettings { return config.getBoolean("skip-used-one-time-kits-from-kit-list", false); } - private String operatorColor = null; - @Override public String getOperatorColor() { return operatorColor; } private String _getOperatorColor() { - String colorName = config.getString("ops-name-color", null); + final String colorName = config.getString("ops-name-color", null); if (colorName == null) { return ChatColor.RED.toString(); @@ -398,15 +455,15 @@ public class Settings implements net.ess3.api.ISettings { try { return FormatUtil.parseHexColor(colorName); - } catch (NumberFormatException ignored) { + } catch (final NumberFormatException ignored) { } try { return ChatColor.valueOf(colorName.toUpperCase(Locale.ENGLISH)).toString(); - } catch (IllegalArgumentException ignored) { + } catch (final IllegalArgumentException ignored) { } - ChatColor lastResort = ChatColor.getByChar(colorName); + final ChatColor lastResort = ChatColor.getByChar(colorName); if (lastResort != null) { return lastResort.toString(); } @@ -453,10 +510,8 @@ public class Settings implements net.ess3.api.ISettings { return config.getBoolean("backup.always-run", false); } - private final Map chatFormats = Collections.synchronizedMap(new HashMap<>()); - @Override - public String getChatFormat(String group) { + public String getChatFormat(final String group) { String mFormat = chatFormats.get(group); if (mFormat == null) { mFormat = config.getString("chat.group-formats." + (group == null ? "Default" : group), config.getString("chat.format", "&7[{GROUP}]&r {DISPLAYNAME}&7:&r {MESSAGE}")); @@ -510,12 +565,12 @@ public class Settings implements net.ess3.api.ISettings { @Override public Map getListGroupConfig() { if (config.isConfigurationSection("list")) { - Map values = config.getConfigurationSection("list").getValues(false); + final Map values = config.getConfigurationSection("list").getValues(false); if (!values.isEmpty()) { return values; } } - Map defaultMap = new HashMap<>(); + final Map defaultMap = new HashMap<>(); if (config.getBoolean("sort-list-by-groups", false)) { defaultMap.put("ListByGroup", "ListByGroup"); } else { @@ -601,8 +656,6 @@ public class Settings implements net.ess3.api.ISettings { itemSpawnBl = _getItemSpawnBlacklist(); } - private List itemSpawnBl = new ArrayList<>(); - @Override public List itemSpawnBlacklist() { return itemSpawnBl; @@ -623,16 +676,13 @@ public class Settings implements net.ess3.api.ISettings { try { final ItemStack iStack = itemDb.get(itemName); epItemSpwn.add(iStack.getType()); - } catch (Exception ex) { + } catch (final Exception ex) { logger.log(Level.SEVERE, tl("unknownItemInList", itemName, "item-spawn-blacklist"), ex); } } return epItemSpwn; } - private List enabledSigns = new ArrayList<>(); - private boolean signsEnabled = false; - @Override public List enabledSigns() { return enabledSigns; @@ -641,7 +691,7 @@ public class Settings implements net.ess3.api.ISettings { private List _getEnabledSigns() { this.signsEnabled = false; // Ensure boolean resets on reload. - List newSigns = new ArrayList<>(); + final List newSigns = new ArrayList<>(); for (String signName : config.getStringList("enabledSigns")) { signName = signName.trim().toUpperCase(Locale.ENGLISH); @@ -654,7 +704,7 @@ public class Settings implements net.ess3.api.ISettings { } try { newSigns.add(Signs.valueOf(signName).getSign()); - } catch (Exception ex) { + } catch (final Exception ex) { logger.log(Level.SEVERE, tl("unknownItemInList", signName, "enabledSigns")); continue; } @@ -663,8 +713,6 @@ public class Settings implements net.ess3.api.ISettings { return newSigns; } - private boolean warnOnBuildDisallow; - private boolean _warnOnBuildDisallow() { return config.getBoolean("protect.disable.warn-on-build-disallow", false); } @@ -674,9 +722,6 @@ public class Settings implements net.ess3.api.ISettings { return warnOnBuildDisallow; } - private boolean debug = false; - private boolean configDebug = false; - private boolean _isDebug() { return config.getBoolean("debug", false); } @@ -686,6 +731,11 @@ public class Settings implements net.ess3.api.ISettings { return debug || configDebug; } + @Override + public void setDebug(final boolean debug) { + this.debug = debug; + } + @Override public boolean warnOnSmite() { return config.getBoolean("warn-on-smite", true); @@ -716,19 +766,16 @@ public class Settings implements net.ess3.api.ISettings { // #easteregg @Override @Deprecated - public boolean isTradeInStacks(int id) { + public boolean isTradeInStacks(final int id) { return config.getBoolean("trade-in-stacks-" + id, false); } // #easteregg @Override - public boolean isTradeInStacks(Material type) { + public boolean isTradeInStacks(final Material type) { return config.getBoolean("trade-in-stacks." + type.toString().toLowerCase().replace("_", ""), false); } - // #easteregg - private boolean economyDisabled = false; - public boolean _isEcoDisabled() { return config.getBoolean("disable-eco", false); } @@ -753,12 +800,13 @@ public class Settings implements net.ess3.api.ISettings { } Material mat = EnumUtil.getMaterial(itemName.toUpperCase()); - + if (mat == null) { try { - ItemStack itemStack = ess.getItemDb().get(itemName); + final ItemStack itemStack = ess.getItemDb().get(itemName); mat = itemStack.getType(); - } catch (Exception ignored) {} + } catch (final Exception ignored) { + } } if (mat == null) { @@ -776,13 +824,10 @@ public class Settings implements net.ess3.api.ISettings { } @Override - public boolean getProtectBoolean(final String configName, boolean def) { + public boolean getProtectBoolean(final String configName, final boolean def) { return config.getBoolean(configName, def); } - private static final BigDecimal MAXMONEY = new BigDecimal("10000000000000"); - private BigDecimal maxMoney = MAXMONEY; - private BigDecimal _getMaxMoney() { return config.getBigDecimal("max-money", MAXMONEY); } @@ -792,9 +837,6 @@ public class Settings implements net.ess3.api.ISettings { return maxMoney; } - private static final BigDecimal MINMONEY = new BigDecimal("-10000000000000"); - private BigDecimal minMoney = MINMONEY; - private BigDecimal _getMinMoney() { BigDecimal min = config.getBigDecimal("min-money", MINMONEY); if (min.signum() > 0) { @@ -808,8 +850,6 @@ public class Settings implements net.ess3.api.ISettings { return minMoney; } - private boolean economyLog = false; - @Override public boolean isEcoLogEnabled() { return economyLog; @@ -819,9 +859,6 @@ public class Settings implements net.ess3.api.ISettings { return config.getBoolean("economy-log-enabled", false); } - // #easteregg - private boolean economyLogUpdate = false; - @Override public boolean isEcoLogUpdateEnabled() { return economyLogUpdate; @@ -841,8 +878,6 @@ public class Settings implements net.ess3.api.ISettings { return config.getBoolean("remove-god-on-disconnect", false); } - private boolean changeDisplayName = true; - private boolean _changeDisplayName() { return config.getBoolean("change-displayname", true); } @@ -852,8 +887,6 @@ public class Settings implements net.ess3.api.ISettings { return changeDisplayName; } - private boolean changePlayerListName = false; - private boolean _changePlayerListName() { return config.getBoolean("change-playerlist", false); } @@ -868,10 +901,6 @@ public class Settings implements net.ess3.api.ISettings { return config.getBoolean("use-bukkit-permissions", false); } - private boolean prefixsuffixconfigured = false; - private boolean addprefixsuffix = false; - private boolean essentialsChatActive = false; - private boolean _addPrefixSuffix() { return config.getBoolean("add-prefix-suffix", false); } @@ -881,7 +910,7 @@ public class Settings implements net.ess3.api.ISettings { } @Override - public void setEssentialsChatActive(boolean essentialsChatActive) { + public void setEssentialsChatActive(final boolean essentialsChatActive) { this.essentialsChatActive = essentialsChatActive; } @@ -890,9 +919,6 @@ public class Settings implements net.ess3.api.ISettings { return prefixsuffixconfigured ? addprefixsuffix : essentialsChatActive; } - // #easteregg - private boolean disablePrefix = false; - private boolean _disablePrefix() { return config.getBoolean("disablePrefix", false); } @@ -902,9 +928,6 @@ public class Settings implements net.ess3.api.ISettings { return disablePrefix; } - // #easteregg - private boolean disableSuffix = false; - private boolean _disableSuffix() { return config.getBoolean("disableSuffix", false); } @@ -924,8 +947,6 @@ public class Settings implements net.ess3.api.ISettings { return config.getLong("auto-afk-kick", -1); } - private boolean getFreezeAfkPlayers; - @Override public boolean getFreezeAfkPlayers() { return getFreezeAfkPlayers; @@ -935,8 +956,6 @@ public class Settings implements net.ess3.api.ISettings { return config.getBoolean("freeze-afk-players", false); } - private boolean cancelAfkOnMove; - @Override public boolean cancelAfkOnMove() { return cancelAfkOnMove; @@ -946,8 +965,6 @@ public class Settings implements net.ess3.api.ISettings { return config.getBoolean("cancel-afk-on-move", true); } - private boolean cancelAfkOnInteract; - @Override public boolean cancelAfkOnInteract() { return cancelAfkOnInteract; @@ -957,8 +974,6 @@ public class Settings implements net.ess3.api.ISettings { return config.getBoolean("cancel-afk-on-interact", true); } - private boolean sleepIgnoresAfkPlayers; - @Override public boolean sleepIgnoresAfkPlayers() { return sleepIgnoresAfkPlayers; @@ -968,9 +983,6 @@ public class Settings implements net.ess3.api.ISettings { return config.getBoolean("sleep-ignores-afk-players", true); } - private String afkListName; - private boolean isAfkListName; - public String _getAfkListName() { return FormatUtil.replaceFormat(config.getString("afk-list-name", "none")); } @@ -985,8 +997,6 @@ public class Settings implements net.ess3.api.ISettings { return afkListName; } - private boolean broadcastAfkMessage; - @Override public boolean broadcastAfkMessage() { return broadcastAfkMessage; @@ -1001,13 +1011,11 @@ public class Settings implements net.ess3.api.ISettings { return config.getBoolean("death-messages", true); } - private KeepInvPolicy vanishingItemPolicy; - public KeepInvPolicy _getVanishingItemsPolicy() { - String value = config.getString("vanishing-items-policy", "keep").toLowerCase(Locale.ENGLISH); + final String value = config.getString("vanishing-items-policy", "keep").toLowerCase(Locale.ENGLISH); try { return KeepInvPolicy.valueOf(value.toUpperCase(Locale.ENGLISH)); - } catch (IllegalArgumentException e) { + } catch (final IllegalArgumentException e) { return KeepInvPolicy.KEEP; } } @@ -1017,13 +1025,11 @@ public class Settings implements net.ess3.api.ISettings { return vanishingItemPolicy; } - private KeepInvPolicy bindingItemPolicy; - public KeepInvPolicy _getBindingItemsPolicy() { - String value = config.getString("binding-items-policy", "keep").toLowerCase(Locale.ENGLISH); + final String value = config.getString("binding-items-policy", "keep").toLowerCase(Locale.ENGLISH); try { return KeepInvPolicy.valueOf(value.toUpperCase(Locale.ENGLISH)); - } catch (IllegalArgumentException e) { + } catch (final IllegalArgumentException e) { return KeepInvPolicy.KEEP; } } @@ -1033,18 +1039,11 @@ public class Settings implements net.ess3.api.ISettings { return bindingItemPolicy; } - private Set noGodWorlds = new HashSet<>(); - @Override public Set getNoGodWorlds() { return noGodWorlds; } - @Override - public void setDebug(final boolean debug) { - this.debug = debug; - } - @Override public boolean getRepairEnchanted() { return config.getBoolean("repair-enchanted", true); @@ -1065,8 +1064,6 @@ public class Settings implements net.ess3.api.ISettings { return config.getBoolean("world-home-permissions", false); } - private boolean registerBackInListener; - @Override public boolean registerBackInListener() { return registerBackInListener; @@ -1076,8 +1073,6 @@ public class Settings implements net.ess3.api.ISettings { return config.getBoolean("register-back-in-listener", false); } - private boolean disableItemPickupWhileAfk; - @Override public boolean getDisableItemPickupWhileAfk() { return disableItemPickupWhileAfk; @@ -1087,7 +1082,7 @@ public class Settings implements net.ess3.api.ISettings { return config.getBoolean("disable-item-pickup-while-afk", false); } - private EventPriority getPriority(String priority) { + private EventPriority getPriority(final String priority) { if ("none".equals(priority)) { return null; } @@ -1111,13 +1106,13 @@ public class Settings implements net.ess3.api.ISettings { @Override public EventPriority getRespawnPriority() { - String priority = config.getString("respawn-listener-priority", "normal").toLowerCase(Locale.ENGLISH); + final String priority = config.getString("respawn-listener-priority", "normal").toLowerCase(Locale.ENGLISH); return getPriority(priority); } @Override public EventPriority getSpawnJoinPriority() { - String priority = config.getString("spawn-join-listener-priority", "normal").toLowerCase(Locale.ENGLISH); + final String priority = config.getString("spawn-join-listener-priority", "normal").toLowerCase(Locale.ENGLISH); return getPriority(priority); } @@ -1126,8 +1121,6 @@ public class Settings implements net.ess3.api.ISettings { return config.getLong("tpa-accept-cancellation", 120); } - private long teleportInvulnerabilityTime; - private long _getTeleportInvulnerability() { return config.getLong("teleport-invulnerability", 0) * 1000; } @@ -1137,10 +1130,8 @@ public class Settings implements net.ess3.api.ISettings { return teleportInvulnerabilityTime; } - private boolean teleportInvulnerability; - private boolean _isTeleportInvulnerability() { - return (config.getLong("teleport-invulnerability", 0) > 0); + return config.getLong("teleport-invulnerability", 0) > 0; } @Override @@ -1148,8 +1139,6 @@ public class Settings implements net.ess3.api.ISettings { return teleportInvulnerability; } - private long loginAttackDelay; - private long _getLoginAttackDelay() { return config.getLong("login-attack-delay", 0) * 1000; } @@ -1159,8 +1148,6 @@ public class Settings implements net.ess3.api.ISettings { return loginAttackDelay; } - private int signUsePerSecond; - private int _getSignUsePerSecond() { final int perSec = config.getInt("sign-use-per-second", 4); return perSec > 0 ? perSec : 1; @@ -1173,18 +1160,16 @@ public class Settings implements net.ess3.api.ISettings { @Override public double getMaxFlySpeed() { - double maxSpeed = config.getDouble("max-fly-speed", 0.8); + final double maxSpeed = config.getDouble("max-fly-speed", 0.8); return maxSpeed > 1.0 ? 1.0 : Math.abs(maxSpeed); } @Override public double getMaxWalkSpeed() { - double maxSpeed = config.getDouble("max-walk-speed", 0.8); + final double maxSpeed = config.getDouble("max-walk-speed", 0.8); return maxSpeed > 1.0 ? 1.0 : Math.abs(maxSpeed); } - private int mailsPerMinute; - private int _getMailsPerMinute() { return config.getInt("mails-per-minute", 1000); } @@ -1194,9 +1179,6 @@ public class Settings implements net.ess3.api.ISettings { return mailsPerMinute; } - // #easteregg - private long economyLagWarning; - private long _getEconomyLagWarning() { // Default to 25ms return (long) (config.getDouble("economy-lag-warning", 25.0) * 1000000); @@ -1207,9 +1189,6 @@ public class Settings implements net.ess3.api.ISettings { return economyLagWarning; } - // #easteregg - private long permissionsLagWarning; - private long _getPermissionsLagWarning() { // Default to 25ms return (long) (config.getDouble("permissions-lag-warning", 25.0) * 1000000); @@ -1245,8 +1224,6 @@ public class Settings implements net.ess3.api.ISettings { return config.getBoolean("hide-displayname-in-vanish", false); } - private boolean allowSilentJoin; - public boolean _allowSilentJoinQuit() { return config.getBoolean("allow-silent-join-quit", false); } @@ -1256,9 +1233,6 @@ public class Settings implements net.ess3.api.ISettings { return allowSilentJoin; } - private String customJoinMessage; - private boolean isCustomJoinMessage; - public String _getCustomJoinMessage() { return FormatUtil.replaceFormat(config.getString("custom-join-message", "none")); } @@ -1273,9 +1247,6 @@ public class Settings implements net.ess3.api.ISettings { return isCustomJoinMessage; } - private String customQuitMessage; - private boolean isCustomQuitMessage; - public String _getCustomQuitMessage() { return FormatUtil.replaceFormat(config.getString("custom-quit-message", "none")); } @@ -1313,15 +1284,17 @@ public class Settings implements net.ess3.api.ISettings { // #easteregg @Override public int getMaxUserCacheCount() { - long count = Runtime.getRuntime().maxMemory() / 1024 / 96; + final long count = Runtime.getRuntime().maxMemory() / 1024 / 96; return config.getInt("max-user-cache-count", (int) count); } - @Override public boolean isLastMessageReplyRecipient() { + @Override + public boolean isLastMessageReplyRecipient() { return config.getBoolean("last-message-reply-recipient", false); } - @Override public BigDecimal getMinimumPayAmount() { + @Override + public BigDecimal getMinimumPayAmount() { return new BigDecimal(config.getString("minimum-pay-amount", "0.001")); } @@ -1330,15 +1303,18 @@ public class Settings implements net.ess3.api.ISettings { return config.getBoolean("pay-excludes-ignore-list", false); } - @Override public long getLastMessageReplyRecipientTimeout() { + @Override + public long getLastMessageReplyRecipientTimeout() { return config.getLong("last-message-reply-recipient-timeout", 180); } - @Override public boolean isMilkBucketEasterEggEnabled() { + @Override + public boolean isMilkBucketEasterEggEnabled() { return config.getBoolean("milk-bucket-easter-egg", true); } - @Override public boolean isSendFlyEnableOnJoin() { + @Override + public boolean isSendFlyEnableOnJoin() { return config.getBoolean("send-fly-enable-on-join", true); } @@ -1352,10 +1328,8 @@ public class Settings implements net.ess3.api.ISettings { return !this.spawnOnJoinGroups.isEmpty(); } - private List spawnOnJoinGroups; - public List _getSpawnOnJoinGroups() { - List def = Collections.emptyList(); + final List def = Collections.emptyList(); if (config.isSet("spawn-on-join")) { if (config.isList("spawn-on-join")) { return new ArrayList<>(config.getStringList("spawn-on-join")); @@ -1364,7 +1338,7 @@ public class Settings implements net.ess3.api.ISettings { return config.getBoolean("spawn-on-join") ? Collections.singletonList("*") : def; } // Take whatever the value is, convert to string and add it to a list as a single value. - String val = config.get("spawn-on-join").toString(); + final String val = config.get("spawn-on-join").toString(); return !val.isEmpty() ? Collections.singletonList(val) : def; } else { return def; @@ -1377,8 +1351,8 @@ public class Settings implements net.ess3.api.ISettings { } @Override - public boolean isUserInSpawnOnJoinGroup(IUser user) { - for (String group : this.spawnOnJoinGroups) { + public boolean isUserInSpawnOnJoinGroup(final IUser user) { + for (final String group : this.spawnOnJoinGroups) { if (group.equals("*") || user.inGroup(group)) { return true; } @@ -1391,14 +1365,12 @@ public class Settings implements net.ess3.api.ISettings { return config.getBoolean("teleport-to-center", true); } - private Map commandCooldowns; - private Map _getCommandCooldowns() { if (!config.isConfigurationSection("command-cooldowns")) { return null; } - ConfigurationSection section = config.getConfigurationSection("command-cooldowns"); - Map result = new LinkedHashMap<>(); + final ConfigurationSection section = config.getConfigurationSection("command-cooldowns"); + final Map result = new LinkedHashMap<>(); for (String cmdEntry : section.getKeys(false)) { Pattern pattern = null; @@ -1408,7 +1380,7 @@ public class Settings implements net.ess3.api.ISettings { if (cmdEntry.startsWith("^")) { try { pattern = Pattern.compile(cmdEntry.substring(1)); - } catch (PatternSyntaxException e) { + } catch (final PatternSyntaxException e) { ess.getLogger().warning("Command cooldown error: " + e.getMessage()); } } else { @@ -1416,8 +1388,8 @@ public class Settings implements net.ess3.api.ISettings { if (cmdEntry.startsWith("\\^")) { cmdEntry = cmdEntry.substring(1); } - String cmd = cmdEntry - .replaceAll("\\*", ".*"); // Wildcards are accepted as asterisk * as known universally. + final String cmd = cmdEntry + .replaceAll("\\*", ".*"); // Wildcards are accepted as asterisk * as known universally. pattern = Pattern.compile(cmd + "( .*)?"); // This matches arguments, if present, to "ignore" them from the feature. } @@ -1428,14 +1400,14 @@ public class Settings implements net.ess3.api.ISettings { if (value instanceof String) { try { value = Double.parseDouble(value.toString()); - } catch (NumberFormatException ignored) { + } catch (final NumberFormatException ignored) { } } if (!(value instanceof Number)) { ess.getLogger().warning("Command cooldown error: '" + value + "' is not a valid cooldown"); continue; } - double cooldown = ((Number) value).doubleValue(); + final double cooldown = ((Number) value).doubleValue(); if (cooldown < 1) { ess.getLogger().warning("Command cooldown with very short " + cooldown + " cooldown."); } @@ -1451,17 +1423,17 @@ public class Settings implements net.ess3.api.ISettings { } @Override - public long getCommandCooldownMs(String label) { - Entry result = getCommandCooldownEntry(label); + public long getCommandCooldownMs(final String label) { + final Entry result = getCommandCooldownEntry(label); return result != null ? result.getValue() : -1; // return cooldown in milliseconds } @Override - public Entry getCommandCooldownEntry(String label) { + public Entry getCommandCooldownEntry(final String label) { if (isCommandCooldownsEnabled()) { - for (Entry entry : this.commandCooldowns.entrySet()) { + for (final Entry entry : this.commandCooldowns.entrySet()) { // Check if label matches current pattern (command-cooldown in config) - boolean matches = entry.getKey().matcher(label).matches(); + final boolean matches = entry.getKey().matcher(label).matches(); if (isDebug()) { ess.getLogger().info(String.format("Checking command '%s' against cooldown '%s': %s", label, entry.getKey(), matches)); } @@ -1475,13 +1447,11 @@ public class Settings implements net.ess3.api.ISettings { } @Override - public boolean isCommandCooldownPersistent(String label) { + public boolean isCommandCooldownPersistent(final String label) { // TODO: enable per command cooldown specification for persistence. return config.getBoolean("command-cooldown-persistence", true); } - private boolean npcsInBalanceRanking = false; - private boolean _isNpcsInBalanceRanking() { return config.getBoolean("npcs-in-balance-ranking", false); } @@ -1491,13 +1461,11 @@ public class Settings implements net.ess3.api.ISettings { return npcsInBalanceRanking; } - private NumberFormat currencyFormat; - private NumberFormat _getCurrencyFormat() { - String currencyFormatString = config.getString("currency-format", "#,##0.00"); + final String currencyFormatString = config.getString("currency-format", "#,##0.00"); - String symbolLocaleString = config.getString("currency-symbol-format-locale"); - DecimalFormatSymbols decimalFormatSymbols; + final String symbolLocaleString = config.getString("currency-symbol-format-locale"); + final DecimalFormatSymbols decimalFormatSymbols; if (symbolLocaleString != null) { decimalFormatSymbols = DecimalFormatSymbols.getInstance(Locale.forLanguageTag(symbolLocaleString)); } else { @@ -1505,7 +1473,7 @@ public class Settings implements net.ess3.api.ISettings { decimalFormatSymbols = DecimalFormatSymbols.getInstance(Locale.US); } - DecimalFormat currencyFormat = new DecimalFormat(currencyFormatString, decimalFormatSymbols); + final DecimalFormat currencyFormat = new DecimalFormat(currencyFormatString, decimalFormatSymbols); currencyFormat.setRoundingMode(RoundingMode.FLOOR); // Updates NumberUtil#PRETTY_FORMAT field so that all of Essentials can follow a single format. @@ -1518,15 +1486,13 @@ public class Settings implements net.ess3.api.ISettings { return this.currencyFormat; } - private List unprotectedSigns = Collections.emptyList(); - @Override public List getUnprotectedSignNames() { return this.unprotectedSigns; } private List _getUnprotectedSign() { - List newSigns = new ArrayList<>(); + final List newSigns = new ArrayList<>(); for (String signName : config.getStringList("unprotected-sign-names")) { signName = signName.trim().toUpperCase(Locale.ENGLISH); @@ -1535,7 +1501,7 @@ public class Settings implements net.ess3.api.ISettings { } try { newSigns.add(Signs.valueOf(signName).getSign()); - } catch (Exception ex) { + } catch (final Exception ex) { logger.log(Level.SEVERE, tl("unknownItemInList", signName, "unprotected-sign-names")); } } @@ -1592,10 +1558,8 @@ public class Settings implements net.ess3.api.ISettings { return config.getBoolean("world-change-speed-reset", true); } - private List defaultEnabledConfirmCommands; - private List _getDefaultEnabledConfirmCommands() { - List commands = config.getStringList("default-enabled-confirm-commands"); + final List commands = config.getStringList("default-enabled-confirm-commands"); for (int i = 0; i < commands.size(); i++) { commands.set(i, commands.get(i).toLowerCase()); } @@ -1606,14 +1570,12 @@ public class Settings implements net.ess3.api.ISettings { public List getDefaultEnabledConfirmCommands() { return defaultEnabledConfirmCommands; } - + @Override - public boolean isConfirmCommandEnabledByDefault(String commandName) { + public boolean isConfirmCommandEnabledByDefault(final String commandName) { return getDefaultEnabledConfirmCommands().contains(commandName.toLowerCase()); } - private boolean teleportBackWhenFreedFromJail; - private boolean _isTeleportBackWhenFreedFromJail() { return config.getBoolean("teleport-back-when-freed-from-jail", true); } @@ -1623,8 +1585,6 @@ public class Settings implements net.ess3.api.ISettings { return teleportBackWhenFreedFromJail; } - private boolean isCompassTowardsHomePerm; - private boolean _isCompassTowardsHomePerm() { return config.getBoolean("compass-towards-home-perm", false); } @@ -1634,8 +1594,6 @@ public class Settings implements net.ess3.api.ISettings { return isCompassTowardsHomePerm; } - private boolean isAllowWorldInBroadcastworld; - private boolean _isAllowWorldInBroadcastworld() { return config.getBoolean("allow-world-in-broadcastworld", false); } @@ -1645,8 +1603,6 @@ public class Settings implements net.ess3.api.ISettings { return isAllowWorldInBroadcastworld; } - private String itemDbType; // #EasterEgg - admins can manually switch items provider if they want - private String _getItemDbType() { return config.getString("item-db-type", "auto"); } @@ -1656,10 +1612,6 @@ public class Settings implements net.ess3.api.ISettings { return itemDbType; } - private boolean forceEnableRecipe; // https://github.com/EssentialsX/Essentials/issues/1397 - - private boolean allowOldIdSigns; - private boolean _allowOldIdSigns() { return config.getBoolean("allow-old-id-signs", false); } @@ -1669,10 +1621,8 @@ public class Settings implements net.ess3.api.ISettings { return allowOldIdSigns; } - private boolean isWaterSafe; - private boolean _isWaterSafe() { - boolean _isWaterSafe = config.getBoolean("is-water-safe", false); + final boolean _isWaterSafe = config.getBoolean("is-water-safe", false); LocationUtil.setIsWaterSafe(_isWaterSafe); return _isWaterSafe; @@ -1682,8 +1632,6 @@ public class Settings implements net.ess3.api.ISettings { public boolean isWaterSafe() { return isWaterSafe; } - - private boolean isSafeUsermap; private boolean _isSafeUsermap() { return config.getBoolean("safe-usermap-names", true); @@ -1694,8 +1642,6 @@ public class Settings implements net.ess3.api.ISettings { return isSafeUsermap; } - private boolean logCommandBlockCommands; - private boolean _logCommandBlockCommands() { return config.getBoolean("log-command-block-commands", true); } @@ -1705,15 +1651,13 @@ public class Settings implements net.ess3.api.ISettings { return logCommandBlockCommands; } - private Set> nickBlacklist; - private Set> _getNickBlacklist() { - Set> blacklist = new HashSet<>(); + final Set> blacklist = new HashSet<>(); config.getStringList("nick-blacklist").forEach(entry -> { try { blacklist.add(Pattern.compile(entry).asPredicate()); - } catch (PatternSyntaxException e) { + } catch (final PatternSyntaxException e) { logger.warning("Invalid nickname blacklist regex: " + entry); } }); @@ -1726,8 +1670,6 @@ public class Settings implements net.ess3.api.ISettings { return nickBlacklist; } - private double maxProjectileSpeed; - private double _getMaxProjectileSpeed() { return config.getDouble("max-projectile-speed", 8); } @@ -1737,8 +1679,6 @@ public class Settings implements net.ess3.api.ISettings { return maxProjectileSpeed; } - private boolean removeEffectsOnHeal; - private boolean _isRemovingEffectsOnHeal() { return config.getBoolean("remove-effects-on-heal", true); } diff --git a/Essentials/src/com/earth2me/essentials/SpawnMob.java b/Essentials/src/com/earth2me/essentials/SpawnMob.java index e9e100629..b706545ee 100644 --- a/Essentials/src/com/earth2me/essentials/SpawnMob.java +++ b/Essentials/src/com/earth2me/essentials/SpawnMob.java @@ -10,16 +10,25 @@ import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.block.Block; -import org.bukkit.entity.*; +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.PigZombie; +import org.bukkit.entity.Zombie; import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.ItemStack; -import java.util.*; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; import static com.earth2me.essentials.I18n.tl; - -public class SpawnMob { +public final class SpawnMob { private static final Material GOLDEN_HELMET = EnumUtil.getMaterial("GOLDEN_HELMET", "GOLD_HELMET"); private static final Material GOLDEN_CHESTPLATE = EnumUtil.getMaterial("GOLDEN_CHESTPLATE", "GOLD_CHESTPLATE"); @@ -27,10 +36,13 @@ public class SpawnMob { private static final Material GOLDEN_BOOTS = EnumUtil.getMaterial("GOLDEN_BOOTS", "GOLD_BOOTS"); private static final Material GOLDEN_SWORD = EnumUtil.getMaterial("GOLDEN_SWORD", "GOLD_SWORD"); + private SpawnMob() { + } + public static String mobList(final User user) { final Set mobList = Mob.getMobList(); final Set availableList = new HashSet<>(); - for (String mob : mobList) { + for (final String mob : mobList) { if (user.isAuthorized("essentials.spawnmob." + mob.toLowerCase(Locale.ENGLISH))) { availableList.add(mob); } @@ -42,24 +54,24 @@ public class SpawnMob { } public static List mobParts(final String mobString) { - String[] mobParts = mobString.split(","); + final String[] mobParts = mobString.split(","); - List mobs = new ArrayList<>(); + final List mobs = new ArrayList<>(); - for (String mobPart : mobParts) { - String[] mobDatas = mobPart.split(":"); + for (final String mobPart : mobParts) { + final String[] mobDatas = mobPart.split(":"); mobs.add(mobDatas[0]); } return mobs; } public static List mobData(final String mobString) { - String[] mobParts = mobString.split(","); + final String[] mobParts = mobString.split(","); - List mobData = new ArrayList<>(); + final List mobData = new ArrayList<>(); - for (String mobPart : mobParts) { - String[] mobDatas = mobPart.split(":"); + for (final String mobPart : mobParts) { + final String[] mobDatas = mobPart.split(":"); if (mobDatas.length == 1) { if (mobPart.contains(":")) { mobData.add(""); @@ -75,7 +87,7 @@ public class SpawnMob { } // This method spawns a mob where the user is looking, owned by user - public static void spawnmob(final IEssentials ess, final Server server, final User user, final List parts, final List data, int mobCount) throws Exception { + public static void spawnmob(final IEssentials ess, final Server server, final User user, final List parts, final List data, final int mobCount) throws Exception { final Block block = LocationUtil.getTarget(user.getBase()).getBlock(); if (block == null) { throw new Exception(tl("unableToSpawnMob")); @@ -84,7 +96,7 @@ public class SpawnMob { } // This method spawns a mob at target, owned by target - public static void spawnmob(final IEssentials ess, final Server server, final CommandSource sender, final User target, final List parts, final List data, int mobCount) throws Exception { + public static void spawnmob(final IEssentials ess, final Server server, final CommandSource sender, final User target, final List parts, final List data, final int mobCount) throws Exception { spawnmob(ess, server, sender, target, target.getLocation(), parts, data, mobCount); } @@ -92,8 +104,8 @@ public class SpawnMob { public static void spawnmob(final IEssentials ess, final Server server, final CommandSource sender, final User target, final Location loc, final List parts, final List data, int mobCount) throws Exception { final Location sloc = LocationUtil.getSafeDestination(loc); - for (String part : parts) { - Mob mob = Mob.fromName(part); + for (final String part : parts) { + final Mob mob = Mob.fromName(part); checkSpawnable(ess, sender, mob); } @@ -112,22 +124,22 @@ public class SpawnMob { sender.sendMessage(tl("mobSpawnLimit")); } - Mob mob = Mob.fromName(parts.get(0)); // Get the first mob + final Mob mob = Mob.fromName(parts.get(0)); // Get the first mob try { for (int i = 0; i < mobCount; i++) { spawnMob(ess, server, sender, target, sloc, parts, data); } sender.sendMessage(mobCount * parts.size() + " " + mob.name.toLowerCase(Locale.ENGLISH) + mob.suffix + " " + tl("spawned")); - } catch (MobException e1) { + } catch (final MobException e1) { throw new Exception(tl("unableToSpawnMob"), e1); - } catch (NumberFormatException e2) { + } catch (final NumberFormatException e2) { throw new Exception(tl("numberRequired"), e2); - } catch (NullPointerException np) { + } catch (final NullPointerException np) { throw new Exception(tl("soloMob"), np); } } - private static void spawnMob(final IEssentials ess, final Server server, final CommandSource sender, final User target, final Location sloc, List parts, List data) throws Exception { + private static void spawnMob(final IEssentials ess, final Server server, final CommandSource sender, final User target, final Location sloc, final List parts, final List data) throws Exception { Mob mob; Entity spawnedMob = null; Entity spawnedMount; @@ -143,10 +155,10 @@ public class SpawnMob { } } - int next = (i + 1); - if (next < parts.size()) //If it's the last mob in the list, don't set the mount - { - Mob mMob = Mob.fromName(parts.get(next)); + final int next = i + 1; + // If it's the last mob in the list, don't set the mount + if (next < parts.size()) { + final Mob mMob = Mob.fromName(parts.get(next)); spawnedMount = mMob.spawn(sloc.getWorld(), server, sloc); defaultMobData(mMob.getType(), spawnedMount); @@ -161,7 +173,7 @@ public class SpawnMob { } } - private static void checkSpawnable(IEssentials ess, CommandSource sender, Mob mob) throws Exception { + private static void checkSpawnable(final IEssentials ess, final CommandSource sender, final Mob mob) throws Exception { if (mob == null || mob.getType() == null) { throw new Exception(tl("invalidMob")); } @@ -238,7 +250,7 @@ public class SpawnMob { } if (type == MobCompat.ZOMBIFIED_PIGLIN) { - final PigZombie zombie = ((PigZombie) spawned); + final PigZombie zombie = (PigZombie) spawned; setVillager(zombie, false); final EntityEquipment invent = zombie.getEquipment(); @@ -247,7 +259,7 @@ public class SpawnMob { } if (type == EntityType.ZOMBIE) { - final Zombie zombie = ((Zombie) spawned); + final Zombie zombie = (Zombie) spawned; setVillager(zombie, false); } @@ -257,10 +269,10 @@ public class SpawnMob { } @SuppressWarnings("deprecation") - private static void setVillager(Zombie zombie, boolean villager) { + private static void setVillager(final Zombie zombie, final boolean villager) { try { zombie.setVillager(villager); - } catch (Exception ignored) { + } catch (final Exception ignored) { } } } diff --git a/Essentials/src/com/earth2me/essentials/TNTExplodeListener.java b/Essentials/src/com/earth2me/essentials/TNTExplodeListener.java index b0239ae69..8c3c4a015 100644 --- a/Essentials/src/com/earth2me/essentials/TNTExplodeListener.java +++ b/Essentials/src/com/earth2me/essentials/TNTExplodeListener.java @@ -7,7 +7,6 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityExplodeEvent; - public class TNTExplodeListener implements Listener, Runnable { private final transient IEssentials ess; private transient boolean enabled = false; diff --git a/Essentials/src/com/earth2me/essentials/Teleport.java b/Essentials/src/com/earth2me/essentials/Teleport.java index 0400f8201..d98488210 100644 --- a/Essentials/src/com/earth2me/essentials/Teleport.java +++ b/Essentials/src/com/earth2me/essentials/Teleport.java @@ -21,7 +21,6 @@ import java.util.GregorianCalendar; import static com.earth2me.essentials.I18n.tl; - /** * @deprecated This API is not asynchronous. Use {@link com.earth2me.essentials.AsyncTeleport AsyncTeleport} */ @@ -34,20 +33,14 @@ public class Teleport implements ITeleport { private TeleportType tpType; @Deprecated - public Teleport(IUser user, IEssentials ess) { + public Teleport(final IUser user, final IEssentials ess) { this.teleportOwner = user; this.ess = ess; tpType = TeleportType.NORMAL; } - public enum TeleportType { - TPA, - BACK, - NORMAL - } - @Deprecated - public void cooldown(boolean check) throws Exception { + public void cooldown(final boolean check) throws Exception { final Calendar time = new GregorianCalendar(); if (teleportOwner.getLastTeleportTimestamp() > 0) { // Take the current time, and remove the delay from it. @@ -67,7 +60,7 @@ public class Teleport implements ITeleport { teleportOwner.setLastTeleportTimestamp(time.getTimeInMillis()); return; } else if (lastTime > earliestLong - && cooldownApplies()) { + && cooldownApplies()) { time.setTimeInMillis(lastTime); time.add(Calendar.SECOND, (int) cooldown); time.add(Calendar.MILLISECOND, (int) ((cooldown * 1000.0) % 1000.0)); @@ -83,18 +76,18 @@ public class Teleport implements ITeleport { @Deprecated private boolean cooldownApplies() { boolean applies = true; - String globalBypassPerm = "essentials.teleport.cooldown.bypass"; + final String globalBypassPerm = "essentials.teleport.cooldown.bypass"; switch (tpType) { case NORMAL: applies = !teleportOwner.isAuthorized(globalBypassPerm); break; case BACK: applies = !(teleportOwner.isAuthorized(globalBypassPerm) && - teleportOwner.isAuthorized("essentials.teleport.cooldown.bypass.back")); + teleportOwner.isAuthorized("essentials.teleport.cooldown.bypass.back")); break; case TPA: applies = !(teleportOwner.isAuthorized(globalBypassPerm) && - teleportOwner.isAuthorized("essentials.teleport.cooldown.bypass.tpa")); + teleportOwner.isAuthorized("essentials.teleport.cooldown.bypass.tpa")); break; } return applies; @@ -102,7 +95,7 @@ public class Teleport implements ITeleport { @Deprecated private void warnUser(final IUser user, final double delay) { - Calendar c = new GregorianCalendar(); + final Calendar c = new GregorianCalendar(); c.add(Calendar.SECOND, (int) delay); c.add(Calendar.MILLISECOND, (int) ((delay * 1000.0) % 1000.0)); user.sendMessage(tl("dontMoveMessage", DateUtil.formatDateDiff(c.getTimeInMillis()))); @@ -111,7 +104,7 @@ public class Teleport implements ITeleport { //The now function is used when you want to skip tp delay when teleporting someone to a location or player. @Override @Deprecated - public void now(Location loc, boolean cooldown, TeleportCause cause) throws Exception { + public void now(final Location loc, final boolean cooldown, final TeleportCause cause) throws Exception { if (cooldown) { cooldown(false); } @@ -121,7 +114,7 @@ public class Teleport implements ITeleport { @Override @Deprecated - public void now(Player entity, boolean cooldown, TeleportCause cause) throws Exception { + public void now(final Player entity, final boolean cooldown, final TeleportCause cause) throws Exception { if (cooldown) { cooldown(false); } @@ -131,11 +124,11 @@ public class Teleport implements ITeleport { } @Deprecated - protected void now(IUser teleportee, ITarget target, TeleportCause cause) throws Exception { + protected void now(final IUser teleportee, final ITarget target, final TeleportCause cause) throws Exception { cancel(false); Location loc = target.getLocation(); - PreTeleportEvent event = new PreTeleportEvent(teleportee, cause, target); + final PreTeleportEvent event = new PreTeleportEvent(teleportee, cause, target); Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { return; @@ -178,21 +171,21 @@ public class Teleport implements ITeleport { //This method is nolonger used internally and will be removed. @Deprecated @Override - public void teleport(Location loc, Trade chargeFor) throws Exception { + public void teleport(final Location loc, final Trade chargeFor) throws Exception { teleport(loc, chargeFor, TeleportCause.PLUGIN); } @Override @Deprecated - public void teleport(Location loc, Trade chargeFor, TeleportCause cause) throws Exception { + public void teleport(final Location loc, final Trade chargeFor, final TeleportCause cause) throws Exception { teleport(teleportOwner, new LocationTarget(loc), chargeFor, cause); } //This is used when teleporting to a player @Override @Deprecated - public void teleport(Player entity, Trade chargeFor, TeleportCause cause) throws Exception { - ITarget target = new PlayerTarget(entity); + public void teleport(final Player entity, final Trade chargeFor, final TeleportCause cause) throws Exception { + final ITarget target = new PlayerTarget(entity); teleportOwner.sendMessage(tl("teleportToPlayer", entity.getDisplayName())); teleport(teleportOwner, target, chargeFor, cause); } @@ -200,25 +193,25 @@ public class Teleport implements ITeleport { //This is used when teleporting to stored location @Override @Deprecated - public void teleportPlayer(IUser teleportee, Location loc, Trade chargeFor, TeleportCause cause) throws Exception { + public void teleportPlayer(final IUser teleportee, final Location loc, final Trade chargeFor, final TeleportCause cause) throws Exception { teleport(teleportee, new LocationTarget(loc), chargeFor, cause); } //This is used on /tphere @Override @Deprecated - public void teleportPlayer(IUser teleportee, Player entity, Trade chargeFor, TeleportCause cause) throws Exception { - ITarget target = new PlayerTarget(entity); + public void teleportPlayer(final IUser teleportee, final Player entity, final Trade chargeFor, final TeleportCause cause) throws Exception { + final ITarget target = new PlayerTarget(entity); teleport(teleportee, target, chargeFor, cause); teleportee.sendMessage(tl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ())); teleportOwner.sendMessage(tl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ())); } @Deprecated - private void teleport(IUser teleportee, ITarget target, Trade chargeFor, TeleportCause cause) throws Exception { + private void teleport(final IUser teleportee, final ITarget target, final Trade chargeFor, final TeleportCause cause) throws Exception { double delay = ess.getSettings().getTeleportDelay(); - TeleportWarmupEvent event = new TeleportWarmupEvent(teleportee, cause, target, delay); + final TeleportWarmupEvent event = new TeleportWarmupEvent(teleportee, cause, target, delay); Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { return; @@ -253,10 +246,10 @@ public class Teleport implements ITeleport { } @Deprecated - private void teleportOther(IUser teleporter, IUser teleportee, ITarget target, Trade chargeFor, TeleportCause cause) throws Exception { + private void teleportOther(final IUser teleporter, final IUser teleportee, final ITarget target, final Trade chargeFor, final TeleportCause cause) throws Exception { double delay = ess.getSettings().getTeleportDelay(); - TeleportWarmupEvent event = new TeleportWarmupEvent(teleporter, teleportee, cause, target, delay); + final TeleportWarmupEvent event = new TeleportWarmupEvent(teleporter, teleportee, cause, target, delay); Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { return; @@ -277,9 +270,9 @@ public class Teleport implements ITeleport { cooldown(true); if (delay <= 0 || teleporter == null - || teleporter.isAuthorized("essentials.teleport.timer.bypass") - || teleportOwner.isAuthorized("essentials.teleport.timer.bypass") - || teleportee.isAuthorized("essentials.teleport.timer.bypass")) { + || teleporter.isAuthorized("essentials.teleport.timer.bypass") + || teleportOwner.isAuthorized("essentials.teleport.timer.bypass") + || teleportee.isAuthorized("essentials.teleport.timer.bypass")) { cooldown(false); now(teleportee, target, cause); if (teleporter != null && cashCharge != null) { @@ -296,10 +289,10 @@ public class Teleport implements ITeleport { //The respawn function is a wrapper used to handle tp fallback, on /jail and /home @Override @Deprecated - public void respawn(final Trade chargeFor, TeleportCause cause) throws Exception { + public void respawn(final Trade chargeFor, final TeleportCause cause) throws Exception { double delay = ess.getSettings().getTeleportDelay(); - TeleportWarmupEvent event = new TeleportWarmupEvent(teleportOwner, cause, null, delay); + final TeleportWarmupEvent event = new TeleportWarmupEvent(teleportOwner, cause, null, delay); Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { return; @@ -325,9 +318,9 @@ public class Teleport implements ITeleport { } @Deprecated - void respawnNow(IUser teleportee, TeleportCause cause) throws Exception { + void respawnNow(final IUser teleportee, final TeleportCause cause) throws Exception { final Player player = teleportee.getBase(); - Location bed = player.getBedSpawnLocation(); + final Location bed = player.getBedSpawnLocation(); if (bed != null) { now(teleportee, new LocationTarget(bed), cause); } else { @@ -343,15 +336,15 @@ public class Teleport implements ITeleport { //The warp function is a wrapper used to teleportPlayer a player to a /warp @Override @Deprecated - public void warp(IUser teleportee, String warp, Trade chargeFor, TeleportCause cause) throws Exception { - UserWarpEvent event = new UserWarpEvent(teleportee, warp, chargeFor); + public void warp(final IUser teleportee, String warp, final Trade chargeFor, final TeleportCause cause) throws Exception { + final UserWarpEvent event = new UserWarpEvent(teleportee, warp, chargeFor); Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { return; } warp = event.getWarp(); - Location loc = ess.getWarps().getWarp(warp); + final Location loc = ess.getWarps().getWarp(warp); teleportee.sendMessage(tl("warpingTo", warp, loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); if (!teleportee.equals(teleportOwner)) { teleportOwner.sendMessage(tl("warpingTo", warp, loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); @@ -362,14 +355,14 @@ public class Teleport implements ITeleport { //The back function is a wrapper used to teleportPlayer a player /back to their previous location. @Override @Deprecated - public void back(Trade chargeFor) throws Exception { + public void back(final Trade chargeFor) throws Exception { back(teleportOwner, chargeFor); } //This function is a wrapper over the other back function for cases where another player performs back for them @Override @Deprecated - public void back(IUser teleporter, Trade chargeFor) throws Exception { + public void back(final IUser teleporter, final Trade chargeFor) throws Exception { tpType = TeleportType.BACK; final Location loc = teleportOwner.getLastLocation(); teleportOwner.sendMessage(tl("backUsageMsg", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); @@ -384,13 +377,13 @@ public class Teleport implements ITeleport { } @Deprecated - public void setTpType(TeleportType tpType) { + public void setTpType(final TeleportType tpType) { this.tpType = tpType; } //If we need to cancelTimer a pending teleportPlayer call this method @Deprecated - private void cancel(boolean notifyUser) { + private void cancel(final boolean notifyUser) { if (timedTeleport != null) { timedTeleport.cancelTimer(notifyUser); timedTeleport = null; @@ -398,7 +391,13 @@ public class Teleport implements ITeleport { } @Deprecated - private void initTimer(long delay, IUser teleportUser, ITarget target, Trade chargeFor, TeleportCause cause, boolean respawn) { + private void initTimer(final long delay, final IUser teleportUser, final ITarget target, final Trade chargeFor, final TeleportCause cause, final boolean respawn) { timedTeleport = new TimedTeleport(teleportOwner, ess, this, delay, teleportUser, target, chargeFor, cause, respawn); } + + public enum TeleportType { + TPA, + BACK, + NORMAL + } } diff --git a/Essentials/src/com/earth2me/essentials/TimedTeleport.java b/Essentials/src/com/earth2me/essentials/TimedTeleport.java index a015f0690..9e731918b 100644 --- a/Essentials/src/com/earth2me/essentials/TimedTeleport.java +++ b/Essentials/src/com/earth2me/essentials/TimedTeleport.java @@ -16,10 +16,8 @@ public class TimedTeleport implements Runnable { private final IEssentials ess; private final Teleport teleport; private final UUID timer_teleportee; - private int timer_task; private final long timer_started; // time this task was initiated private final long timer_delay; // how long to delay the teleportPlayer - private double timer_health; // note that I initially stored a clone of the location for reference, but... // when comparing locations, I got incorrect mismatches (rounding errors, looked like) // so, the X/Y/Z values are stored instead and rounded off @@ -31,8 +29,10 @@ public class TimedTeleport implements Runnable { private final boolean timer_canMove; private final Trade timer_chargeFor; private final TeleportCause timer_cause; + private int timer_task; + private double timer_health; - TimedTeleport(IUser user, IEssentials ess, Teleport teleport, long delay, IUser teleportUser, ITarget target, Trade chargeFor, TeleportCause cause, boolean respawn) { + TimedTeleport(final IUser user, final IEssentials ess, final Teleport teleport, final long delay, final IUser teleportUser, final ITarget target, final Trade chargeFor, final TeleportCause cause, final boolean respawn) { this.teleportOwner = user; this.ess = ess; this.teleport = teleport; @@ -83,12 +83,12 @@ public class TimedTeleport implements Runnable { @Override public void run() { - timer_health = teleportUser.getBase().getHealth(); // in case user healed, then later gets injured + timer_health = teleportUser.getBase().getHealth(); // in case user healed, then later gets injured final long now = System.currentTimeMillis(); if (now > timer_started + timer_delay) { try { teleport.cooldown(false); - } catch (Exception ex) { + } catch (final Exception ex) { teleportOwner.sendMessage(tl("cooldownWithMessage", ex.getMessage())); if (teleportOwner != teleportUser) { teleportUser.sendMessage(tl("cooldownWithMessage", ex.getMessage())); @@ -110,17 +110,18 @@ public class TimedTeleport implements Runnable { timer_chargeFor.charge(teleportOwner); } - } catch (Exception ex) { + } catch (final Exception ex) { ess.showError(teleportOwner.getSource(), ex, "\\ teleport"); } } } } + ess.scheduleSyncDelayedTask(new DelayedTeleportTask()); } //If we need to cancelTimer a pending teleportPlayer call this method - void cancelTimer(boolean notifyUser) { + void cancelTimer(final boolean notifyUser) { if (timer_task == -1) { return; } diff --git a/Essentials/src/com/earth2me/essentials/Trade.java b/Essentials/src/com/earth2me/essentials/Trade.java index b364867a6..34779982f 100644 --- a/Essentials/src/com/earth2me/essentials/Trade.java +++ b/Essentials/src/com/earth2me/essentials/Trade.java @@ -25,8 +25,8 @@ import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; - public class Trade { + private static FileWriter fw = null; private final transient String command; private final transient Trade fallbackTrade; private final transient BigDecimal money; @@ -34,20 +34,6 @@ public class Trade { private final transient Integer exp; private final transient IEssentials ess; - - public enum TradeType { - MONEY, - EXP, - ITEM - } - - - public enum OverflowType { - ABORT, - DROP, - RETURN - } - public Trade(final String command, final IEssentials ess) { this(command, null, null, null, null, ess); } @@ -82,22 +68,115 @@ public class Trade { this.ess = ess; } + public static void log(final String type, final String subtype, final String event, final String sender, final Trade charge, final String receiver, final Trade pay, final Location loc, final IEssentials ess) { + //isEcoLogUpdateEnabled() - This refers to log entries with no location, ie API updates #EasterEgg + //isEcoLogEnabled() - This refers to log entries with with location, ie /pay /sell and eco signs. + + if ((loc == null && !ess.getSettings().isEcoLogUpdateEnabled()) || (loc != null && !ess.getSettings().isEcoLogEnabled())) { + return; + } + if (fw == null) { + try { + fw = new FileWriter(new File(ess.getDataFolder(), "trade.log"), true); + } catch (final IOException ex) { + Logger.getLogger("Essentials").log(Level.SEVERE, null, ex); + } + } + final StringBuilder sb = new StringBuilder(); + sb.append(type).append(",").append(subtype).append(",").append(event).append(",\""); + sb.append(DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date())); + sb.append("\",\""); + if (sender != null) { + sb.append(sender); + } + sb.append("\","); + if (charge == null) { + sb.append("\"\",\"\",\"\""); + } else { + if (charge.getItemStack() != null) { + sb.append(charge.getItemStack().getAmount()).append(","); + sb.append(charge.getItemStack().getType().toString()).append(","); + sb.append(charge.getItemStack().getDurability()); + } + if (charge.getMoney() != null) { + sb.append(charge.getMoney()).append(","); + sb.append("money").append(","); + sb.append(ess.getSettings().getCurrencySymbol()); + } + if (charge.getExperience() != null) { + sb.append(charge.getExperience()).append(","); + sb.append("exp").append(","); + sb.append("\"\""); + } + } + sb.append(",\""); + if (receiver != null) { + sb.append(receiver); + } + sb.append("\","); + if (pay == null) { + sb.append("\"\",\"\",\"\""); + } else { + if (pay.getItemStack() != null) { + sb.append(pay.getItemStack().getAmount()).append(","); + sb.append(pay.getItemStack().getType().toString()).append(","); + sb.append(pay.getItemStack().getDurability()); + } + if (pay.getMoney() != null) { + sb.append(pay.getMoney()).append(","); + sb.append("money").append(","); + sb.append(ess.getSettings().getCurrencySymbol()); + } + if (pay.getExperience() != null) { + sb.append(pay.getExperience()).append(","); + sb.append("exp").append(","); + sb.append("\"\""); + } + } + if (loc == null) { + sb.append(",\"\",\"\",\"\",\"\""); + } else { + sb.append(",\""); + sb.append(loc.getWorld().getName()).append("\","); + sb.append(loc.getBlockX()).append(","); + sb.append(loc.getBlockY()).append(","); + sb.append(loc.getBlockZ()).append(","); + } + sb.append("\n"); + try { + fw.write(sb.toString()); + fw.flush(); + } catch (final IOException ex) { + Logger.getLogger("Essentials").log(Level.SEVERE, null, ex); + } + } + + public static void closeLog() { + if (fw != null) { + try { + fw.close(); + } catch (final IOException ex) { + Logger.getLogger("Essentials").log(Level.SEVERE, null, ex); + } + fw = null; + } + } + public void isAffordableFor(final IUser user) throws ChargeException { - CompletableFuture future = new CompletableFuture<>(); + final CompletableFuture future = new CompletableFuture<>(); isAffordableFor(user, future); if (future.isCompletedExceptionally()) { try { future.get(); - } catch (InterruptedException e) { //If this happens, we have bigger problems... + } catch (final InterruptedException e) { //If this happens, we have bigger problems... e.printStackTrace(); - } catch (ExecutionException e) { + } catch (final ExecutionException e) { throw (ChargeException) e.getCause(); } } } - - public void isAffordableFor(final IUser user, CompletableFuture future) { + public void isAffordableFor(final IUser user, final CompletableFuture future) { if (ess.getSettings().isDebug()) { ess.getLogger().log(Level.INFO, "checking if " + user.getName() + " can afford charge."); } @@ -112,7 +191,7 @@ public class Trade { return; } - BigDecimal money; + final BigDecimal money; if (command != null && !command.isEmpty() && (money = getCommandCost(user)).signum() > 0 && !user.canAfford(money)) { future.completeExceptionally(new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(money, ess)))); return; @@ -136,7 +215,7 @@ public class Trade { } if (getItemStack() != null) { // This stores the would be overflow - Map overFlow = InventoryWorkaround.addAllItems(user.getBase().getInventory(), getItemStack()); + final Map overFlow = InventoryWorkaround.addAllItems(user.getBase().getInventory(), getItemStack()); if (overFlow != null) { switch (type) { @@ -157,12 +236,11 @@ public class Trade { } return returnStack; - case DROP: // Pay the users the items directly, and drop the rest, will always return no overflow. final Map leftOver = InventoryWorkaround.addItems(user.getBase().getInventory(), getItemStack()); final Location loc = user.getBase().getLocation(); - for (ItemStack loStack : leftOver.values()) { + for (final ItemStack loStack : leftOver.values()) { final int maxStackSize = loStack.getType().getMaxStackSize(); final int stacks = loStack.getAmount() / maxStackSize; final int leftover = loStack.getAmount() % maxStackSize; @@ -181,6 +259,7 @@ public class Trade { if (ess.getSettings().isDebug()) { ess.getLogger().log(Level.INFO, "paying " + user.getName() + " partial itemstack " + getItemStack().toString() + " and dropping overflow " + leftOver.get(0).toString()); } + break; } } else if (ess.getSettings().isDebug()) { ess.getLogger().log(Level.INFO, "paying " + user.getName() + " itemstack " + getItemStack().toString()); @@ -194,20 +273,20 @@ public class Trade { } public void charge(final IUser user) throws ChargeException { - CompletableFuture future = new CompletableFuture<>(); + final CompletableFuture future = new CompletableFuture<>(); charge(user, future); if (future.isCompletedExceptionally()) { try { future.get(); - } catch (InterruptedException e) { //If this happens, we have bigger problems... + } catch (final InterruptedException e) { //If this happens, we have bigger problems... e.printStackTrace(); - } catch (ExecutionException e) { + } catch (final ExecutionException e) { throw (ChargeException) e.getCause(); } } } - public void charge(final IUser user, CompletableFuture future) { + public void charge(final IUser user, final CompletableFuture future) { if (ess.getSettings().isDebug()) { ess.getLogger().log(Level.INFO, "attempting to charge user " + user.getName()); } @@ -298,99 +377,15 @@ public class Trade { return cost; } - private static FileWriter fw = null; - - public static void log(String type, String subtype, String event, String sender, Trade charge, String receiver, Trade pay, Location loc, IEssentials ess) { - //isEcoLogUpdateEnabled() - This refers to log entries with no location, ie API updates #EasterEgg - //isEcoLogEnabled() - This refers to log entries with with location, ie /pay /sell and eco signs. - - if ((loc == null && !ess.getSettings().isEcoLogUpdateEnabled()) || (loc != null && !ess.getSettings().isEcoLogEnabled())) { - return; - } - if (fw == null) { - try { - fw = new FileWriter(new File(ess.getDataFolder(), "trade.log"), true); - } catch (IOException ex) { - Logger.getLogger("Essentials").log(Level.SEVERE, null, ex); - } - } - StringBuilder sb = new StringBuilder(); - sb.append(type).append(",").append(subtype).append(",").append(event).append(",\""); - sb.append(DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date())); - sb.append("\",\""); - if (sender != null) { - sb.append(sender); - } - sb.append("\","); - if (charge == null) { - sb.append("\"\",\"\",\"\""); - } else { - if (charge.getItemStack() != null) { - sb.append(charge.getItemStack().getAmount()).append(","); - sb.append(charge.getItemStack().getType().toString()).append(","); - sb.append(charge.getItemStack().getDurability()); - } - if (charge.getMoney() != null) { - sb.append(charge.getMoney()).append(","); - sb.append("money").append(","); - sb.append(ess.getSettings().getCurrencySymbol()); - } - if (charge.getExperience() != null) { - sb.append(charge.getExperience()).append(","); - sb.append("exp").append(","); - sb.append("\"\""); - } - } - sb.append(",\""); - if (receiver != null) { - sb.append(receiver); - } - sb.append("\","); - if (pay == null) { - sb.append("\"\",\"\",\"\""); - } else { - if (pay.getItemStack() != null) { - sb.append(pay.getItemStack().getAmount()).append(","); - sb.append(pay.getItemStack().getType().toString()).append(","); - sb.append(pay.getItemStack().getDurability()); - } - if (pay.getMoney() != null) { - sb.append(pay.getMoney()).append(","); - sb.append("money").append(","); - sb.append(ess.getSettings().getCurrencySymbol()); - } - if (pay.getExperience() != null) { - sb.append(pay.getExperience()).append(","); - sb.append("exp").append(","); - sb.append("\"\""); - } - } - if (loc == null) { - sb.append(",\"\",\"\",\"\",\"\""); - } else { - sb.append(",\""); - sb.append(loc.getWorld().getName()).append("\","); - sb.append(loc.getBlockX()).append(","); - sb.append(loc.getBlockY()).append(","); - sb.append(loc.getBlockZ()).append(","); - } - sb.append("\n"); - try { - fw.write(sb.toString()); - fw.flush(); - } catch (IOException ex) { - Logger.getLogger("Essentials").log(Level.SEVERE, null, ex); - } + public enum TradeType { + MONEY, + EXP, + ITEM } - public static void closeLog() { - if (fw != null) { - try { - fw.close(); - } catch (IOException ex) { - Logger.getLogger("Essentials").log(Level.SEVERE, null, ex); - } - fw = null; - } + public enum OverflowType { + ABORT, + DROP, + RETURN } } diff --git a/Essentials/src/com/earth2me/essentials/UUIDMap.java b/Essentials/src/com/earth2me/essentials/UUIDMap.java index 7779335c5..be24d8f99 100644 --- a/Essentials/src/com/earth2me/essentials/UUIDMap.java +++ b/Essentials/src/com/earth2me/essentials/UUIDMap.java @@ -3,27 +3,32 @@ package com.earth2me.essentials; import com.google.common.io.Files; import org.bukkit.Bukkit; -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.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.UUID; -import java.util.concurrent.*; +import java.util.concurrent.ConcurrentSkipListMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.regex.Pattern; - public class UUIDMap { + private static final ScheduledExecutorService writeScheduler = Executors.newScheduledThreadPool(1); + private static boolean pendingWrite; + private static boolean loading = false; private final transient net.ess3.api.IEssentials ess; private final File userList; private final transient Pattern splitPattern = Pattern.compile(","); - - private static boolean pendingWrite; - private static final ScheduledExecutorService writeScheduler = Executors.newScheduledThreadPool(1); private final Runnable writeTaskRunnable; - private static boolean loading = false; - public UUIDMap(final net.ess3.api.IEssentials ess) { this.ess = ess; userList = new File(ess.getDataFolder(), "usermap.csv"); @@ -32,7 +37,7 @@ public class UUIDMap { if (pendingWrite) { try { new WriteRunner(ess.getDataFolder(), userList, ess.getUserMap().getNames()).run(); - } catch (Throwable t) { // bad code to prevent task from being suppressed + } catch (final Throwable t) { // bad code to prevent task from being suppressed t.printStackTrace(); } } @@ -58,7 +63,7 @@ public class UUIDMap { history.clear(); loading = true; - try (BufferedReader reader = new BufferedReader(new FileReader(userList))) { + try (final BufferedReader reader = new BufferedReader(new FileReader(userList))) { while (true) { final String line = reader.readLine(); if (line == null) { @@ -84,7 +89,7 @@ public class UUIDMap { } } loading = false; - } catch (IOException ex) { + } catch (final IOException ex) { Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); } } @@ -106,7 +111,7 @@ public class UUIDMap { writeScheduler.shutdown(); } - private static class WriteRunner implements Runnable { + private static final class WriteRunner implements Runnable { private final File location; private final File endFile; private final Map names; @@ -129,19 +134,19 @@ public class UUIDMap { configFile = File.createTempFile("usermap", ".tmp.csv", location); final BufferedWriter bWriter = new BufferedWriter(new FileWriter(configFile)); - for (Map.Entry entry : names.entrySet()) { + for (final Map.Entry entry : names.entrySet()) { bWriter.write(entry.getKey() + "," + entry.getValue().toString()); bWriter.newLine(); } bWriter.close(); Files.move(configFile, endFile); - } catch (IOException ex) { + } catch (final IOException ex) { try { if (configFile != null && configFile.exists()) { Files.move(configFile, new File(endFile.getParentFile(), "usermap.bak.csv")); } - } catch (Exception ex2) { + } catch (final Exception ex2) { Bukkit.getLogger().log(Level.SEVERE, ex2.getMessage(), ex2); } Bukkit.getLogger().log(Level.WARNING, ex.getMessage(), ex); diff --git a/Essentials/src/com/earth2me/essentials/User.java b/Essentials/src/com/earth2me/essentials/User.java index 4cb279061..6fcd74b9a 100644 --- a/Essentials/src/com/earth2me/essentials/User.java +++ b/Essentials/src/com/earth2me/essentials/User.java @@ -38,16 +38,16 @@ import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; - public class User extends UserData implements Comparable, IMessageRecipient, net.ess3.api.IUser { private static final Logger logger = Logger.getLogger("Essentials"); private final IMessageRecipient messageRecipient; + private transient final AsyncTeleport teleport; + private transient final Teleport legacyTeleport; + private final Map confirmingPayments = new WeakHashMap<>(); private transient UUID teleportRequester; private transient boolean teleportRequestHere; private transient Location teleportLocation; private transient boolean vanished; - private transient final AsyncTeleport teleport; - private transient final Teleport legacyTeleport; private transient long teleportRequestTime; private transient long lastOnlineActivity; private transient long lastThrottledAction; @@ -62,7 +62,6 @@ public class User extends UserData implements Comparable, IMessageRecipien private boolean ignoreMsg = false; private String afkMessage; private long afkSince; - private final Map confirmingPayments = new WeakHashMap<>(); private String confirmingClearCommand; private long lastNotifiedAboutMailsMs; private String lastHomeConfirmation; @@ -118,7 +117,7 @@ public class User extends UserData implements Comparable, IMessageRecipien try { return ess.getPermissionsHandler().hasPermission(base, node); - } catch (Exception ex) { + } catch (final Exception ex) { if (ess.getSettings().isDebug()) { ess.getLogger().log(Level.SEVERE, "Permission System Error: " + ess.getPermissionsHandler().getName() + " returned: " + ex.getMessage(), ex); } else { @@ -136,7 +135,7 @@ public class User extends UserData implements Comparable, IMessageRecipien try { return ess.getPermissionsHandler().isPermissionSet(base, node); - } catch (Exception ex) { + } catch (final Exception ex) { if (ess.getSettings().isDebug()) { ess.getLogger().log(Level.SEVERE, "Permission System Error: " + ess.getPermissionsHandler().getName() + " returned: " + ex.getMessage(), ex); } else { @@ -173,7 +172,7 @@ public class User extends UserData implements Comparable, IMessageRecipien giveMoney(value, initiator, UserBalanceUpdateEvent.Cause.UNKNOWN); } - public void giveMoney(final BigDecimal value, final CommandSource initiator, UserBalanceUpdateEvent.Cause cause) throws MaxMoneyException { + public void giveMoney(final BigDecimal value, final CommandSource initiator, final UserBalanceUpdateEvent.Cause cause) throws MaxMoneyException { if (value.signum() == 0) { return; } @@ -189,7 +188,7 @@ public class User extends UserData implements Comparable, IMessageRecipien payUser(reciever, value, UserBalanceUpdateEvent.Cause.UNKNOWN); } - public void payUser(final User reciever, final BigDecimal value, UserBalanceUpdateEvent.Cause cause) throws Exception { + public void payUser(final User reciever, final BigDecimal value, final UserBalanceUpdateEvent.Cause cause) throws Exception { if (value.compareTo(BigDecimal.ZERO) < 1) { throw new Exception(tl("payMustBePositive")); } @@ -214,13 +213,13 @@ public class User extends UserData implements Comparable, IMessageRecipien takeMoney(value, initiator, UserBalanceUpdateEvent.Cause.UNKNOWN); } - public void takeMoney(final BigDecimal value, final CommandSource initiator, UserBalanceUpdateEvent.Cause cause) { + public void takeMoney(final BigDecimal value, final CommandSource initiator, final UserBalanceUpdateEvent.Cause cause) { if (value.signum() == 0) { return; } try { setMoney(getMoney().subtract(value), cause); - } catch (MaxMoneyException ex) { + } catch (final MaxMoneyException ex) { ess.getLogger().log(Level.WARNING, "Invalid call to takeMoney, total balance can't be more than the max-money limit.", ex); } sendMessage(tl("takenFromAccount", NumberUtil.displayCurrency(value, ess))); @@ -240,9 +239,9 @@ public class User extends UserData implements Comparable, IMessageRecipien } final BigDecimal remainingBalance = getMoney().subtract(cost); if (!permcheck || isAuthorized("essentials.eco.loan")) { - return (remainingBalance.compareTo(ess.getSettings().getMinMoney()) >= 0); + return remainingBalance.compareTo(ess.getSettings().getMinMoney()) >= 0; } - return (remainingBalance.signum() >= 0); + return remainingBalance.signum() >= 0; } public void dispose() { @@ -261,7 +260,8 @@ public class User extends UserData implements Comparable, IMessageRecipien if (ess.getSettings().permissionBasedItemSpawn()) { final String name = material.toString().toLowerCase(Locale.ENGLISH).replace("_", ""); - if (isAuthorized("essentials.itemspawn.item-all") || isAuthorized("essentials.itemspawn.item-" + name)) return true; + if (isAuthorized("essentials.itemspawn.item-all") || isAuthorized("essentials.itemspawn.item-" + name)) + return true; if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_13_0_R01)) { final int id = material.getId(); @@ -297,7 +297,7 @@ public class User extends UserData implements Comparable, IMessageRecipien @Override public boolean hasOutstandingTeleportRequest() { if (getTeleportRequest() != null) { // Player has outstanding teleport request. - long timeout = ess.getSettings().getTpaAcceptCancellation(); + final long timeout = ess.getSettings().getTpaAcceptCancellation(); if (timeout != 0) { if ((System.currentTimeMillis() - getTeleportRequestTime()) / 1000 <= timeout) { // Player has outstanding request return true; @@ -338,13 +338,13 @@ public class User extends UserData implements Comparable, IMessageRecipien /** * Needed for backwards compatibility. */ - public String getNick(boolean longnick, final boolean withPrefix, final boolean withSuffix) { + public String getNick(final boolean longnick, final boolean withPrefix, final boolean withSuffix) { return getNick(withPrefix, withSuffix); } public String getNick(final boolean withPrefix, final boolean withSuffix) { final StringBuilder prefix = new StringBuilder(); - String nickname; + final String nickname; String suffix = ""; final String nick = getNickname(); if (ess.getSettings().isCommandDisabled("nick") || nick == null || nick.isEmpty() || nick.equals(getName())) { @@ -363,7 +363,7 @@ public class User extends UserData implements Comparable, IMessageRecipien prefix.insert(0, opPrefix); suffix = "§r"; } - } catch (Exception e) { + } catch (final Exception e) { if (ess.getSettings().isDebug()) { e.printStackTrace(); } @@ -402,10 +402,10 @@ public class User extends UserData implements Comparable, IMessageRecipien if (isAfk()) { updateAfkListName(); } else if (ess.getSettings().changePlayerListName()) { - String name = getNick(ess.getSettings().isAddingPrefixInPlayerlist(), ess.getSettings().isAddingSuffixInPlayerlist()); + final String name = getNick(ess.getSettings().isAddingPrefixInPlayerlist(), ess.getSettings().isAddingSuffixInPlayerlist()); try { this.getBase().setPlayerListName(name); - } catch (IllegalArgumentException e) { + } catch (final IllegalArgumentException e) { if (ess.getSettings().isDebug()) { logger.log(Level.INFO, "Playerlist for " + name + " was not updated. Name clashed with another online player."); } @@ -452,6 +452,11 @@ public class User extends UserData implements Comparable, IMessageRecipien return value; } + @Override + public void setMoney(final BigDecimal value) throws MaxMoneyException { + setMoney(value, UserBalanceUpdateEvent.Cause.UNKNOWN); + } + private BigDecimal _getMoney() { if (ess.getSettings().isEcoDisabled()) { if (ess.getSettings().isDebug()) { @@ -467,18 +472,13 @@ public class User extends UserData implements Comparable, IMessageRecipien } final Method.MethodAccount account = Methods.getMethod().getAccount(this.getName()); return BigDecimal.valueOf(account.balance()); - } catch (Exception ignored) { + } catch (final Exception ignored) { } } return super.getMoney(); } - @Override - public void setMoney(final BigDecimal value) throws MaxMoneyException { - setMoney(value, UserBalanceUpdateEvent.Cause.UNKNOWN); - } - - public void setMoney(final BigDecimal value, UserBalanceUpdateEvent.Cause cause) throws MaxMoneyException { + public void setMoney(final BigDecimal value, final UserBalanceUpdateEvent.Cause cause) throws MaxMoneyException { if (ess.getSettings().isEcoDisabled()) { if (ess.getSettings().isDebug()) { ess.getLogger().info("Internal economy functions disabled, aborting balance change."); @@ -487,9 +487,9 @@ public class User extends UserData implements Comparable, IMessageRecipien } final BigDecimal oldBalance = _getMoney(); - UserBalanceUpdateEvent updateEvent = new UserBalanceUpdateEvent(this.getBase(), oldBalance, value, cause); + final UserBalanceUpdateEvent updateEvent = new UserBalanceUpdateEvent(this.getBase(), oldBalance, value, cause); ess.getServer().getPluginManager().callEvent(updateEvent); - BigDecimal newBalance = updateEvent.getNewBalance(); + final BigDecimal newBalance = updateEvent.getNewBalance(); if (Methods.hasMethod()) { try { @@ -499,7 +499,7 @@ public class User extends UserData implements Comparable, IMessageRecipien } final Method.MethodAccount account = Methods.getMethod().getAccount(this.getName()); account.set(newBalance.doubleValue()); - } catch (Exception ignored) { + } catch (final Exception ignored) { } } super.setMoney(newBalance, true); @@ -513,7 +513,7 @@ public class User extends UserData implements Comparable, IMessageRecipien if (Methods.hasMethod() && !super.getMoney().equals(value)) { try { super.setMoney(value, false); - } catch (MaxMoneyException ex) { + } catch (final MaxMoneyException ex) { // We don't want to throw any errors here, just updating a cache } } @@ -525,7 +525,7 @@ public class User extends UserData implements Comparable, IMessageRecipien } @Override - public void setAfk(boolean set, AfkStatusChangeEvent.Cause cause) { + public void setAfk(final boolean set, final AfkStatusChangeEvent.Cause cause) { final AfkStatusChangeEvent afkEvent = new AfkStatusChangeEvent(this, set, cause); ess.getServer().getPluginManager().callEvent(afkEvent); if (afkEvent.isCancelled()) { @@ -547,8 +547,8 @@ public class User extends UserData implements Comparable, IMessageRecipien private void updateAfkListName() { if (ess.getSettings().isAfkListName()) { - if(isAfk()) { - String afkName = ess.getSettings().getAfkListName().replace("{PLAYER}", getDisplayName()).replace("{USERNAME}", getName()); + if (isAfk()) { + final String afkName = ess.getSettings().getAfkListName().replace("{PLAYER}", getDisplayName()).replace("{USERNAME}", getName()); getBase().setPlayerListName(afkName); } else { getBase().setPlayerListName(null); @@ -562,7 +562,7 @@ public class User extends UserData implements Comparable, IMessageRecipien return toggleAfk(AfkStatusChangeEvent.Cause.UNKNOWN); } - public boolean toggleAfk(AfkStatusChangeEvent.Cause cause) { + public boolean toggleAfk(final AfkStatusChangeEvent.Cause cause) { setAfk(!isAfk(), cause); return isAfk(); } @@ -572,10 +572,6 @@ public class User extends UserData implements Comparable, IMessageRecipien return hidden; } - public boolean isHidden(final Player player) { - return hidden || !player.canSee(getBase()); - } - @Override public void setHidden(final boolean hidden) { this.hidden = hidden; @@ -584,6 +580,10 @@ public class User extends UserData implements Comparable, IMessageRecipien } } + public boolean isHidden(final Player player) { + return hidden || !player.canSee(getBase()); + } + //Returns true if status expired during this check public boolean checkJailTimeout(final long currentTime) { if (getJailTimeout() > 0 && getJailTimeout() < currentTime && isJailed()) { @@ -596,7 +596,7 @@ public class User extends UserData implements Comparable, IMessageRecipien sendMessage(tl("haveBeenReleased")); setJail(null); if (ess.getSettings().isTeleportBackWhenFreedFromJail()) { - CompletableFuture future = new CompletableFuture<>(); + final CompletableFuture future = new CompletableFuture<>(); getAsyncTeleport().back(future); future.exceptionally(e -> { getAsyncTeleport().respawn(null, TeleportCause.PLUGIN, new CompletableFuture<>()); @@ -614,7 +614,7 @@ public class User extends UserData implements Comparable, IMessageRecipien if (getMuteTimeout() > 0 && getMuteTimeout() < currentTime && isMuted()) { final MuteStatusChangeEvent event = new MuteStatusChangeEvent(this, null, false, getMuteTimeout(), getMuteReason()); ess.getServer().getPluginManager().callEvent(event); - + if (!event.isCancelled()) { setMuteTimeout(0); sendMessage(tl("canTalkAgain")); @@ -631,7 +631,7 @@ public class User extends UserData implements Comparable, IMessageRecipien updateActivity(broadcast, AfkStatusChangeEvent.Cause.UNKNOWN); } - public void updateActivity(final boolean broadcast, AfkStatusChangeEvent.Cause cause) { + public void updateActivity(final boolean broadcast, final AfkStatusChangeEvent.Cause cause) { if (isAfk()) { setAfk(false, cause); if (broadcast && !isHidden()) { @@ -651,13 +651,13 @@ public class User extends UserData implements Comparable, IMessageRecipien } public void updateActivityOnMove(final boolean broadcast) { - if(ess.getSettings().cancelAfkOnMove()) { + if (ess.getSettings().cancelAfkOnMove()) { updateActivity(broadcast, AfkStatusChangeEvent.Cause.MOVE); } } public void updateActivityOnInteract(final boolean broadcast) { - if(ess.getSettings().cancelAfkOnInteract()) { + if (ess.getSettings().cancelAfkOnInteract()) { updateActivity(broadcast, AfkStatusChangeEvent.Cause.INTERACT); } } @@ -677,8 +677,7 @@ public class User extends UserData implements Comparable, IMessageRecipien lastActivity = 0; this.getBase().kickPlayer(kickReason); - - for (User user : ess.getOnlineUsers()) { + for (final User user : ess.getOnlineUsers()) { if (user.isAuthorized("essentials.kick.notify")) { user.sendMessage(tl("playerKicked", Console.NAME, getName(), kickReason)); } @@ -803,7 +802,7 @@ public class User extends UserData implements Comparable, IMessageRecipien } @Override - public void setIgnoreMsg(boolean ignoreMsg) { + public void setIgnoreMsg(final boolean ignoreMsg) { this.ignoreMsg = ignoreMsg; } @@ -816,7 +815,7 @@ public class User extends UserData implements Comparable, IMessageRecipien public void setVanished(final boolean set) { vanished = set; if (set) { - for (User user : ess.getOnlineUsers()) { + for (final User user : ess.getOnlineUsers()) { if (!user.isAuthorized("essentials.vanish.see")) { user.getBase().hidePlayer(getBase()); } @@ -827,7 +826,7 @@ public class User extends UserData implements Comparable, IMessageRecipien this.getBase().addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, Integer.MAX_VALUE, 1, false)); } } else { - for (Player p : ess.getOnlinePlayers()) { + for (final Player p : ess.getOnlinePlayers()) { p.showPlayer(getBase()); } setHidden(false); @@ -848,7 +847,7 @@ public class User extends UserData implements Comparable, IMessageRecipien public boolean isSignThrottled() { final long minTime = lastThrottledAction + (1000 / ess.getSettings().getSignUsePerSecond()); - return (System.currentTimeMillis() < minTime); + return System.currentTimeMillis() < minTime; } public void updateThrottle() { @@ -859,7 +858,7 @@ public class User extends UserData implements Comparable, IMessageRecipien return rightClickJump; } - public void setRightClickJump(boolean rightClickJump) { + public void setRightClickJump(final boolean rightClickJump) { this.rightClickJump = rightClickJump; } @@ -872,12 +871,12 @@ public class User extends UserData implements Comparable, IMessageRecipien return recipeSee; } - public void setRecipeSee(boolean recipeSee) { + public void setRecipeSee(final boolean recipeSee) { this.recipeSee = recipeSee; } @Override - public void sendMessage(String message) { + public void sendMessage(final String message) { if (!message.isEmpty()) { base.sendMessage(message); } @@ -911,24 +910,29 @@ public class User extends UserData implements Comparable, IMessageRecipien public String getName() { return this.getBase().getName(); } - - @Override public boolean isReachable() { + + @Override + public boolean isReachable() { return getBase().isOnline(); } - @Override public MessageResponse sendMessage(IMessageRecipient recipient, String message) { + @Override + public MessageResponse sendMessage(final IMessageRecipient recipient, final String message) { return this.messageRecipient.sendMessage(recipient, message); } - @Override public MessageResponse onReceiveMessage(IMessageRecipient sender, String message) { + @Override + public MessageResponse onReceiveMessage(final IMessageRecipient sender, final String message) { return this.messageRecipient.onReceiveMessage(sender, message); } - @Override public IMessageRecipient getReplyRecipient() { + @Override + public IMessageRecipient getReplyRecipient() { return this.messageRecipient.getReplyRecipient(); } - @Override public void setReplyRecipient(IMessageRecipient recipient) { + @Override + public void setReplyRecipient(final IMessageRecipient recipient) { this.messageRecipient.setReplyRecipient(recipient); } @@ -938,7 +942,7 @@ public class User extends UserData implements Comparable, IMessageRecipien } @Override - public void setAfkMessage(String message) { + public void setAfkMessage(final String message) { if (isAfk()) { this.afkMessage = message; } @@ -957,8 +961,8 @@ public class User extends UserData implements Comparable, IMessageRecipien public String getConfirmingClearCommand() { return confirmingClearCommand; } - - public void setConfirmingClearCommand(String command) { + + public void setConfirmingClearCommand(final String command) { this.confirmingClearCommand = command; } @@ -969,15 +973,15 @@ public class User extends UserData implements Comparable, IMessageRecipien if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_9_R01)) { return getBase().getInventory().getItemInHand(); } else { - PlayerInventory inventory = getBase().getInventory(); + final PlayerInventory inventory = getBase().getInventory(); return inventory.getItemInMainHand() != null ? inventory.getItemInMainHand() : inventory.getItemInOffHand(); } } - + public void notifyOfMail() { - List mails = getMails(); + final List mails = getMails(); if (mails != null && !mails.isEmpty()) { - int notifyPlayerOfMailCooldown = ess.getSettings().getNotifyPlayerOfMailCooldown() * 1000; + final int notifyPlayerOfMailCooldown = ess.getSettings().getNotifyPlayerOfMailCooldown() * 1000; if (System.currentTimeMillis() - lastNotifiedAboutMailsMs >= notifyPlayerOfMailCooldown) { sendMessage(tl("youHaveNewMail", mails.size())); lastNotifiedAboutMailsMs = System.currentTimeMillis(); @@ -989,7 +993,7 @@ public class User extends UserData implements Comparable, IMessageRecipien return lastHomeConfirmation; } - public void setLastHomeConfirmation(String lastHomeConfirmation) { + public void setLastHomeConfirmation(final String lastHomeConfirmation) { this.lastHomeConfirmation = lastHomeConfirmation; } diff --git a/Essentials/src/com/earth2me/essentials/UserData.java b/Essentials/src/com/earth2me/essentials/UserData.java index 163537264..0e04a7768 100644 --- a/Essentials/src/com/earth2me/essentials/UserData.java +++ b/Essentials/src/com/earth2me/essentials/UserData.java @@ -14,22 +14,67 @@ import org.bukkit.inventory.ItemStack; import java.io.File; import java.math.BigDecimal; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; import java.util.Map.Entry; +import java.util.Set; +import java.util.UUID; import java.util.regex.Pattern; import java.util.stream.Collectors; import static com.earth2me.essentials.I18n.tl; - public abstract class UserData extends PlayerExtension implements IConf { protected final transient IEssentials ess; private final EssentialsUserConf config; + private BigDecimal money; + private Map homes; + private String nickname; + private Set unlimited; + private Map powertools; + private Location lastLocation; + private Location logoutLocation; + private long lastTeleportTimestamp; + private long lastHealTimestamp; + private String jail; + private List mails; + private boolean teleportEnabled; + private boolean autoTeleportEnabled; + private List ignoredPlayers; + private boolean godmode; + private boolean muted; + private String muteReason; + private long muteTimeout; + private boolean jailed; + private long jailTimeout; + private long lastLogin; + private long lastLogout; + private String lastLoginAddress; + private boolean afk; + private boolean newplayer; + private String geolocation; + private boolean isSocialSpyEnabled; + private boolean isNPC; + private String lastAccountName = null; + private boolean arePowerToolsEnabled; + private Map kitTimestamps; + // Pattern, Date. Pattern for less pattern creations + private Map commandCooldowns; + private boolean acceptingPay = true; // players accept pay by default + private Boolean confirmPay; + private Boolean confirmClear; + private boolean lastMessageReplyRecipient; - protected UserData(Player base, IEssentials ess) { + protected UserData(final Player base, final IEssentials ess) { super(base); this.ess = ess; - File folder = new File(ess.getDataFolder(), "userdata"); + final File folder = new File(ess.getDataFolder(), "userdata"); if (!folder.exists()) { folder.mkdirs(); } @@ -37,7 +82,7 @@ public abstract class UserData extends PlayerExtension implements IConf { String filename; try { filename = base.getUniqueId().toString(); - } catch (Throwable ex) { + } catch (final Throwable ex) { ess.getLogger().warning("Falling back to old username system for " + base.getName()); filename = base.getName(); } @@ -97,12 +142,10 @@ public abstract class UserData extends PlayerExtension implements IConf { lastMessageReplyRecipient = _getLastMessageReplyRecipient(); } - private BigDecimal money; - private BigDecimal _getMoney() { BigDecimal result = ess.getSettings().getStartingBalance(); - BigDecimal maxMoney = ess.getSettings().getMaxMoney(); - BigDecimal minMoney = ess.getSettings().getMinMoney(); + final BigDecimal maxMoney = ess.getSettings().getMaxMoney(); + final BigDecimal minMoney = ess.getSettings().getMinMoney(); // NPC banks are not actual player banks, as such they do not have player starting balance. if (isNPC()) { @@ -125,9 +168,9 @@ public abstract class UserData extends PlayerExtension implements IConf { return money; } - public void setMoney(BigDecimal value, boolean throwError) throws MaxMoneyException { - BigDecimal maxMoney = ess.getSettings().getMaxMoney(); - BigDecimal minMoney = ess.getSettings().getMinMoney(); + public void setMoney(final BigDecimal value, final boolean throwError) throws MaxMoneyException { + final BigDecimal maxMoney = ess.getSettings().getMaxMoney(); + final BigDecimal minMoney = ess.getSettings().getMinMoney(); if (value.compareTo(maxMoney) > 0) { if (throwError) { throw new MaxMoneyException(); @@ -143,8 +186,6 @@ public abstract class UserData extends PlayerExtension implements IConf { stopTransaction(); } - private Map homes; - private Map _getHomes() { if (config.isConfigurationSection("homes")) { return config.getConfigurationSection("homes").getValues(false); @@ -156,14 +197,14 @@ public abstract class UserData extends PlayerExtension implements IConf { if (NumberUtil.isInt(search)) { try { search = getHomes().get(Integer.parseInt(search) - 1); - } catch (NumberFormatException | IndexOutOfBoundsException ignored) { + } catch (final NumberFormatException | IndexOutOfBoundsException ignored) { } } return search; } - public Location getHome(String name) throws Exception { - String search = getHomeName(name); + public Location getHome(final String name) throws Exception { + final String search = getHomeName(name); return config.getLocation("homes." + search, this.getBase().getServer()); } @@ -173,7 +214,7 @@ public abstract class UserData extends PlayerExtension implements IConf { return null; } Location loc; - for (String home : getHomes()) { + for (final String home : getHomes()) { loc = config.getLocation("homes." + home, this.getBase().getServer()); if (world.getWorld() == loc.getWorld()) { return loc; @@ -182,7 +223,7 @@ public abstract class UserData extends PlayerExtension implements IConf { } loc = config.getLocation("homes." + getHomes().get(0), this.getBase().getServer()); return loc; - } catch (InvalidWorldException ex) { + } catch (final InvalidWorldException ex) { return null; } } @@ -191,7 +232,7 @@ public abstract class UserData extends PlayerExtension implements IConf { return new ArrayList<>(homes.keySet()); } - public void setHome(String name, Location loc) { + public void setHome(String name, final Location loc) { //Invalid names will corrupt the yaml name = StringUtil.safeString(name); homes.put(name, loc); @@ -199,7 +240,7 @@ public abstract class UserData extends PlayerExtension implements IConf { config.save(); } - public void delHome(String name) throws Exception { + public void delHome(final String name) throws Exception { String search = getHomeName(name); if (!homes.containsKey(search)) { search = StringUtil.safeString(search); @@ -217,12 +258,10 @@ public abstract class UserData extends PlayerExtension implements IConf { return config.hasProperty("home"); } - public boolean hasHome(String name) { + public boolean hasHome(final String name) { return config.hasProperty("homes." + name); } - private String nickname; - public String _getNickname() { return config.getString("nickname"); } @@ -231,20 +270,18 @@ public abstract class UserData extends PlayerExtension implements IConf { return nickname; } - public void setNickname(String nick) { + public void setNickname(final String nick) { nickname = nick; config.setProperty("nickname", nick); config.save(); } - private Set unlimited; - private Set _getUnlimited() { - Set retlist = new HashSet<>(); - List configList = config.getStringList("unlimited"); - for(String s : configList) { - Material mat = Material.matchMaterial(s); - if(mat != null) { + final Set retlist = new HashSet<>(); + final List configList = config.getStringList("unlimited"); + for (final String s : configList) { + final Material mat = Material.matchMaterial(s); + if (mat != null) { retlist.add(mat); } } @@ -256,12 +293,12 @@ public abstract class UserData extends PlayerExtension implements IConf { return unlimited; } - public boolean hasUnlimited(ItemStack stack) { + public boolean hasUnlimited(final ItemStack stack) { return unlimited.contains(stack.getType()); } - public void setUnlimited(ItemStack stack, boolean state) { - boolean wasUpdated; + public void setUnlimited(final ItemStack stack, final boolean state) { + final boolean wasUpdated; if (state) { wasUpdated = unlimited.add(stack.getType()); } else { @@ -278,8 +315,6 @@ public abstract class UserData extends PlayerExtension implements IConf { config.save(); } - private Map powertools; - private Map _getPowertools() { if (config.isConfigurationSection("powertools")) { return config.getConfigurationSection("powertools").getValues(false); @@ -294,16 +329,16 @@ public abstract class UserData extends PlayerExtension implements IConf { } @SuppressWarnings("unchecked") - public List getPowertool(ItemStack stack) { + public List getPowertool(final ItemStack stack) { return (List) powertools.get(stack.getType().name().toLowerCase(Locale.ENGLISH)); } @SuppressWarnings("unchecked") - public List getPowertool(Material material) { + public List getPowertool(final Material material) { return (List) powertools.get(material.name().toLowerCase(Locale.ENGLISH)); } - public void setPowertool(ItemStack stack, List commandList) { + public void setPowertool(final ItemStack stack, final List commandList) { if (commandList == null || commandList.isEmpty()) { powertools.remove(stack.getType().name().toLowerCase(Locale.ENGLISH)); } else { @@ -317,12 +352,10 @@ public abstract class UserData extends PlayerExtension implements IConf { return !powertools.isEmpty(); } - private Location lastLocation; - private Location _getLastLocation() { try { return config.getLocation("lastlocation", this.getBase().getServer()); - } catch (InvalidWorldException e) { + } catch (final InvalidWorldException e) { return null; } } @@ -331,7 +364,7 @@ public abstract class UserData extends PlayerExtension implements IConf { return lastLocation; } - public void setLastLocation(Location loc) { + public void setLastLocation(final Location loc) { if (loc == null || loc.getWorld() == null) { return; } @@ -340,12 +373,10 @@ public abstract class UserData extends PlayerExtension implements IConf { config.save(); } - private Location logoutLocation; - private Location _getLogoutLocation() { try { return config.getLocation("logoutlocation", this.getBase().getServer()); - } catch (InvalidWorldException e) { + } catch (final InvalidWorldException e) { return null; } } @@ -354,7 +385,7 @@ public abstract class UserData extends PlayerExtension implements IConf { return logoutLocation; } - public void setLogoutLocation(Location loc) { + public void setLogoutLocation(final Location loc) { if (loc == null || loc.getWorld() == null) { return; } @@ -363,8 +394,6 @@ public abstract class UserData extends PlayerExtension implements IConf { config.save(); } - private long lastTeleportTimestamp; - private long _getLastTeleportTimestamp() { return config.getLong("timestamps.lastteleport", 0); } @@ -373,14 +402,12 @@ public abstract class UserData extends PlayerExtension implements IConf { return lastTeleportTimestamp; } - public void setLastTeleportTimestamp(long time) { + public void setLastTeleportTimestamp(final long time) { lastTeleportTimestamp = time; config.setProperty("timestamps.lastteleport", time); config.save(); } - private long lastHealTimestamp; - private long _getLastHealTimestamp() { return config.getLong("timestamps.lastheal", 0); } @@ -389,14 +416,12 @@ public abstract class UserData extends PlayerExtension implements IConf { return lastHealTimestamp; } - public void setLastHealTimestamp(long time) { + public void setLastHealTimestamp(final long time) { lastHealTimestamp = time; config.setProperty("timestamps.lastheal", time); config.save(); } - private String jail; - private String _getJail() { return config.getString("jail"); } @@ -405,7 +430,7 @@ public abstract class UserData extends PlayerExtension implements IConf { return jail; } - public void setJail(String jail) { + public void setJail(final String jail) { if (jail == null || jail.isEmpty()) { this.jail = null; config.removeProperty("jail"); @@ -416,8 +441,6 @@ public abstract class UserData extends PlayerExtension implements IConf { config.save(); } - private List mails; - private List _getMails() { return config.getStringList("mail"); } @@ -437,13 +460,11 @@ public abstract class UserData extends PlayerExtension implements IConf { config.save(); } - public void addMail(String mail) { + public void addMail(final String mail) { mails.add(mail); setMails(mails); } - private boolean teleportEnabled; - private boolean _getTeleportEnabled() { return config.getBoolean("teleportenabled", true); } @@ -452,14 +473,12 @@ public abstract class UserData extends PlayerExtension implements IConf { return teleportEnabled; } - public void setTeleportEnabled(boolean set) { + public void setTeleportEnabled(final boolean set) { teleportEnabled = set; config.setProperty("teleportenabled", set); config.save(); } - private boolean autoTeleportEnabled; - private boolean _getAutoTeleportEnabled() { return config.getBoolean("teleportauto", false); } @@ -468,29 +487,28 @@ public abstract class UserData extends PlayerExtension implements IConf { return autoTeleportEnabled; } - public void setAutoTeleportEnabled(boolean set) { + public void setAutoTeleportEnabled(final boolean set) { autoTeleportEnabled = set; config.setProperty("teleportauto", set); config.save(); } - private List ignoredPlayers; - public List _getIgnoredPlayers() { - List players = new ArrayList<>(); - for (String uuid : config.getStringList("ignore")) { + final List players = new ArrayList<>(); + for (final String uuid : config.getStringList("ignore")) { try { players.add(UUID.fromString(uuid)); - } catch (IllegalArgumentException ignored) {} + } catch (final IllegalArgumentException ignored) { + } } return Collections.synchronizedList(players); } @Deprecated - public void setIgnoredPlayers(List players) { - List uuids = new ArrayList<>(); - for (String player : players) { - User user = ess.getOfflineUser(player); + public void setIgnoredPlayers(final List players) { + final List uuids = new ArrayList<>(); + for (final String player : players) { + final User user = ess.getOfflineUser(player); if (user == null) { return; } @@ -499,14 +517,14 @@ public abstract class UserData extends PlayerExtension implements IConf { setIgnoredPlayerUUIDs(uuids); } - public void setIgnoredPlayerUUIDs(List players) { + public void setIgnoredPlayerUUIDs(final List players) { if (players == null || players.isEmpty()) { ignoredPlayers = Collections.synchronizedList(new ArrayList<>()); config.removeProperty("ignore"); } else { ignoredPlayers = players; - List uuids = new ArrayList<>(); - for (UUID uuid : players) { + final List uuids = new ArrayList<>(); + for (final UUID uuid : players) { uuids.add(uuid.toString()); } config.setProperty("ignore", uuids); @@ -523,12 +541,12 @@ public abstract class UserData extends PlayerExtension implements IConf { return isIgnoredPlayer(user); } - public boolean isIgnoredPlayer(IUser user) { + public boolean isIgnoredPlayer(final IUser user) { return ignoredPlayers.contains(user.getBase().getUniqueId()) && !user.isIgnoreExempt(); } - public void setIgnoredPlayer(IUser user, boolean set) { - UUID uuid = user.getBase().getUniqueId(); + public void setIgnoredPlayer(final IUser user, final boolean set) { + final UUID uuid = user.getBase().getUniqueId(); if (set) { if (!ignoredPlayers.contains(uuid)) { ignoredPlayers.add(uuid); @@ -539,8 +557,6 @@ public abstract class UserData extends PlayerExtension implements IConf { setIgnoredPlayerUUIDs(ignoredPlayers); } - private boolean godmode; - private boolean _getGodModeEnabled() { return config.getBoolean("godmode", false); } @@ -549,15 +565,12 @@ public abstract class UserData extends PlayerExtension implements IConf { return godmode; } - public void setGodModeEnabled(boolean set) { + public void setGodModeEnabled(final boolean set) { godmode = set; config.setProperty("godmode", set); config.save(); } - private boolean muted; - private String muteReason; - public boolean _getMuted() { return config.getBoolean("muted", false); } @@ -570,7 +583,7 @@ public abstract class UserData extends PlayerExtension implements IConf { return muted; } - public void setMuted(boolean set) { + public void setMuted(final boolean set) { muted = set; config.setProperty("muted", set); config.save(); @@ -584,7 +597,7 @@ public abstract class UserData extends PlayerExtension implements IConf { return muteReason; } - public void setMuteReason(String reason) { + public void setMuteReason(final String reason) { if (reason == null) { config.removeProperty("muteReason"); muteReason = null; @@ -595,12 +608,10 @@ public abstract class UserData extends PlayerExtension implements IConf { config.save(); } - public boolean hasMuteReason(){ + public boolean hasMuteReason() { return muteReason != null; } - private long muteTimeout; - private long _getMuteTimeout() { return config.getLong("timestamps.mute", 0); } @@ -609,14 +620,12 @@ public abstract class UserData extends PlayerExtension implements IConf { return muteTimeout; } - public void setMuteTimeout(long time) { + public void setMuteTimeout(final long time) { muteTimeout = time; config.setProperty("timestamps.mute", time); config.save(); } - private boolean jailed; - private boolean _getJailed() { return config.getBoolean("jailed", false); } @@ -625,20 +634,18 @@ public abstract class UserData extends PlayerExtension implements IConf { return jailed; } - public void setJailed(boolean set) { + public void setJailed(final boolean set) { jailed = set; config.setProperty("jailed", set); config.save(); } public boolean toggleJailed() { - boolean ret = !isJailed(); + final boolean ret = !isJailed(); setJailed(ret); return ret; } - private long jailTimeout; - private long _getJailTimeout() { return config.getLong("timestamps.jail", 0); } @@ -647,14 +654,12 @@ public abstract class UserData extends PlayerExtension implements IConf { return jailTimeout; } - public void setJailTimeout(long time) { + public void setJailTimeout(final long time) { jailTimeout = time; config.setProperty("timestamps.jail", time); config.save(); } - private long lastLogin; - private long _getLastLogin() { return config.getLong("timestamps.login", 0); } @@ -663,12 +668,7 @@ public abstract class UserData extends PlayerExtension implements IConf { return lastLogin; } - private void _setLastLogin(long time) { - lastLogin = time; - config.setProperty("timestamps.login", time); - } - - public void setLastLogin(long time) { + public void setLastLogin(final long time) { _setLastLogin(time); if (base.getAddress() != null && base.getAddress().getAddress() != null) { _setLastLoginAddress(base.getAddress().getAddress().getHostAddress()); @@ -676,7 +676,10 @@ public abstract class UserData extends PlayerExtension implements IConf { config.save(); } - private long lastLogout; + private void _setLastLogin(final long time) { + lastLogin = time; + config.setProperty("timestamps.login", time); + } private long _getLastLogout() { return config.getLong("timestamps.logout", 0); @@ -686,14 +689,12 @@ public abstract class UserData extends PlayerExtension implements IConf { return lastLogout; } - public void setLastLogout(long time) { + public void setLastLogout(final long time) { lastLogout = time; config.setProperty("timestamps.logout", time); config.save(); } - private String lastLoginAddress; - private String _getLastLoginAddress() { return config.getString("ipAddress", ""); } @@ -702,13 +703,11 @@ public abstract class UserData extends PlayerExtension implements IConf { return lastLoginAddress; } - private void _setLastLoginAddress(String address) { + private void _setLastLoginAddress(final String address) { lastLoginAddress = address; config.setProperty("ipAddress", address); } - private boolean afk; - private boolean _getAfk() { return config.getBoolean("afk", false); } @@ -717,15 +716,12 @@ public abstract class UserData extends PlayerExtension implements IConf { return afk; } - public void _setAfk(boolean set) { + public void _setAfk(final boolean set) { afk = set; config.setProperty("afk", set); config.save(); } - private boolean newplayer; - private String geolocation; - private String _getGeoLocation() { return config.getString("geolocation"); } @@ -734,7 +730,7 @@ public abstract class UserData extends PlayerExtension implements IConf { return geolocation; } - public void setGeoLocation(String geolocation) { + public void setGeoLocation(final String geolocation) { if (geolocation == null || geolocation.isEmpty()) { this.geolocation = null; config.removeProperty("geolocation"); @@ -745,8 +741,6 @@ public abstract class UserData extends PlayerExtension implements IConf { config.save(); } - private boolean isSocialSpyEnabled; - private boolean _isSocialSpyEnabled() { return config.getBoolean("socialspy", false); } @@ -755,14 +749,12 @@ public abstract class UserData extends PlayerExtension implements IConf { return isSocialSpyEnabled; } - public void setSocialSpyEnabled(boolean status) { + public void setSocialSpyEnabled(final boolean status) { isSocialSpyEnabled = status; config.setProperty("socialspy", status); config.save(); } - private boolean isNPC; - private boolean _isNPC() { return config.getBoolean("npc", false); } @@ -771,43 +763,39 @@ public abstract class UserData extends PlayerExtension implements IConf { return isNPC; } - private String lastAccountName = null; + public void setNPC(final boolean set) { + isNPC = set; + config.setProperty("npc", set); + config.save(); + } public String getLastAccountName() { return lastAccountName; } - public String _getLastAccountName() { - return config.getString("lastAccountName", null); - } - - public void setLastAccountName(String lastAccountName) { + public void setLastAccountName(final String lastAccountName) { this.lastAccountName = lastAccountName; config.setProperty("lastAccountName", lastAccountName); config.save(); ess.getUserMap().trackUUID(getConfigUUID(), lastAccountName, true); } - public void setNPC(boolean set) { - isNPC = set; - config.setProperty("npc", set); - config.save(); + public String _getLastAccountName() { + return config.getString("lastAccountName", null); } - private boolean arePowerToolsEnabled; - public boolean arePowerToolsEnabled() { return arePowerToolsEnabled; } - public void setPowerToolsEnabled(boolean set) { + public void setPowerToolsEnabled(final boolean set) { arePowerToolsEnabled = set; config.setProperty("powertoolsenabled", set); config.save(); } public boolean togglePowerToolsEnabled() { - boolean ret = !arePowerToolsEnabled(); + final boolean ret = !arePowerToolsEnabled(); setPowerToolsEnabled(ret); return ret; } @@ -816,14 +804,12 @@ public abstract class UserData extends PlayerExtension implements IConf { return config.getBoolean("powertoolsenabled", true); } - private Map kitTimestamps; - private Map _getKitTimestamps() { if (config.isConfigurationSection("timestamps.kits")) { final ConfigurationSection section = config.getConfigurationSection("timestamps.kits"); final Map timestamps = new HashMap<>(); - for (String command : section.getKeys(false)) { + for (final String command : section.getKeys(false)) { if (section.isLong(command)) { timestamps.put(command.toLowerCase(Locale.ENGLISH), section.getLong(command)); } else if (section.isInt(command)) { @@ -850,7 +836,7 @@ public abstract class UserData extends PlayerExtension implements IConf { config.save(); } - public void setConfigProperty(String node, Object object) { + public void setConfigProperty(String node, final Object object) { final String prefix = "info."; node = prefix + node; if (object instanceof Map) { @@ -881,27 +867,24 @@ public abstract class UserData extends PlayerExtension implements IConf { return new HashMap<>(); } - public Map getConfigMap(String node) { + public Map getConfigMap(final String node) { if (config.isConfigurationSection("info." + node)) { return config.getConfigurationSection("info." + node).getValues(true); } return new HashMap<>(); } - // Pattern, Date. Pattern for less pattern creations - private Map commandCooldowns; - private Map _getCommandCooldowns() { if (!config.contains("timestamps.command-cooldowns")) { return null; } // See saveCommandCooldowns() for deserialization explanation - List> section = config.getMapList("timestamps.command-cooldowns"); - HashMap result = new HashMap<>(); - for (Map map : section) { - Pattern pattern = Pattern.compile(map.get("pattern").toString()); - long expiry = ((Number) map.get("expiry")).longValue(); + final List> section = config.getMapList("timestamps.command-cooldowns"); + final HashMap result = new HashMap<>(); + for (final Map map : section) { + final Pattern pattern = Pattern.compile(map.get("pattern").toString()); + final long expiry = ((Number) map.get("expiry")).longValue(); result.put(pattern, expiry); } return result; @@ -914,9 +897,9 @@ public abstract class UserData extends PlayerExtension implements IConf { return Collections.unmodifiableMap(this.commandCooldowns); } - public Date getCommandCooldownExpiry(String label) { + public Date getCommandCooldownExpiry(final String label) { if (commandCooldowns != null) { - for (Entry entry : this.commandCooldowns.entrySet()) { + for (final Entry entry : this.commandCooldowns.entrySet()) { if (entry.getKey().matcher(label).matches()) { return new Date(entry.getValue()); } @@ -925,7 +908,7 @@ public abstract class UserData extends PlayerExtension implements IConf { return null; } - public void addCommandCooldown(Pattern pattern, Date expiresAt, boolean save) { + public void addCommandCooldown(final Pattern pattern, final Date expiresAt, final boolean save) { if (this.commandCooldowns == null) { this.commandCooldowns = new HashMap<>(); } @@ -935,12 +918,12 @@ public abstract class UserData extends PlayerExtension implements IConf { } } - public boolean clearCommandCooldown(Pattern pattern) { + public boolean clearCommandCooldown(final Pattern pattern) { if (this.commandCooldowns == null) { return false; // false for no modification } - if(this.commandCooldowns.remove(pattern) != null) { + if (this.commandCooldowns.remove(pattern) != null) { saveCommandCooldowns(); return true; } @@ -954,14 +937,14 @@ public abstract class UserData extends PlayerExtension implements IConf { // When serializing patterns (which commonly include full stops .) Bukkit/Essentials config framework // interprets it as a path separator, thus it breaks up the regex into sub nodes causing invalid syntax. // Thus each command cooldown is instead stored as a Map of {pattern: .., expiry: ..} to work around this. - List serialized = new ArrayList<>(); - for (Entry entry : this.commandCooldowns.entrySet()) { + final List serialized = new ArrayList<>(); + for (final Entry entry : this.commandCooldowns.entrySet()) { // Don't save expired cooldowns if (entry.getValue() < System.currentTimeMillis()) { continue; } - Map map = ImmutableMap.builder() + final Map map = ImmutableMap.builder() .put("pattern", entry.getKey().pattern()) .put("expiry", entry.getValue()) .build(); @@ -971,8 +954,6 @@ public abstract class UserData extends PlayerExtension implements IConf { save(); } - private boolean acceptingPay = true; // players accept pay by default - public boolean _getAcceptingPay() { return config.getBoolean("acceptingPay", true); } @@ -981,14 +962,12 @@ public abstract class UserData extends PlayerExtension implements IConf { return acceptingPay; } - public void setAcceptingPay(boolean acceptingPay) { + public void setAcceptingPay(final boolean acceptingPay) { this.acceptingPay = acceptingPay; config.setProperty("acceptingPay", acceptingPay); save(); } - private Boolean confirmPay; - private Boolean _getConfirmPay() { return (Boolean) config.get("confirm-pay"); } @@ -997,14 +976,12 @@ public abstract class UserData extends PlayerExtension implements IConf { return confirmPay != null ? confirmPay : ess.getSettings().isConfirmCommandEnabledByDefault("pay"); } - public void setPromptingPayConfirm(boolean prompt) { + public void setPromptingPayConfirm(final boolean prompt) { this.confirmPay = prompt; config.setProperty("confirm-pay", prompt); save(); } - private Boolean confirmClear; - private Boolean _getConfirmClear() { return (Boolean) config.get("confirm-clear"); } @@ -1013,14 +990,12 @@ public abstract class UserData extends PlayerExtension implements IConf { return confirmClear != null ? confirmClear : ess.getSettings().isConfirmCommandEnabledByDefault("clearinventory"); } - public void setPromptingClearConfirm(boolean prompt) { + public void setPromptingClearConfirm(final boolean prompt) { this.confirmClear = prompt; config.setProperty("confirm-clear", prompt); save(); } - private boolean lastMessageReplyRecipient; - private boolean _getLastMessageReplyRecipient() { return config.getBoolean("last-message-reply-recipient", ess.getSettings().isLastMessageReplyRecipient()); } @@ -1029,7 +1004,7 @@ public abstract class UserData extends PlayerExtension implements IConf { return this.lastMessageReplyRecipient; } - public void setLastMessageReplyRecipient(boolean enabled) { + public void setLastMessageReplyRecipient(final boolean enabled) { this.lastMessageReplyRecipient = enabled; config.setProperty("last-message-reply-recipient", enabled); save(); diff --git a/Essentials/src/com/earth2me/essentials/UserMap.java b/Essentials/src/com/earth2me/essentials/UserMap.java index e634a87de..753bcc4ca 100644 --- a/Essentials/src/com/earth2me/essentials/UserMap.java +++ b/Essentials/src/com/earth2me/essentials/UserMap.java @@ -13,22 +13,26 @@ import org.bukkit.entity.Player; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.UUID; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.ExecutionException; import java.util.regex.Pattern; - public class UserMap extends CacheLoader implements IConf { + private static boolean legacy = false; + private static Method getLegacy; private final transient IEssentials ess; private final transient ConcurrentSkipListSet keys = new ConcurrentSkipListSet<>(); private final transient ConcurrentSkipListMap names = new ConcurrentSkipListMap<>(); private final transient ConcurrentSkipListMap> history = new ConcurrentSkipListMap<>(); private final UUIDMap uuidMap; - private final transient Cache users; - private static boolean legacy = false; + private final Pattern validUserPattern = Pattern.compile("^[a-zA-Z0-9_]{2,16}$"); public UserMap(final IEssentials ess) { super(); @@ -36,11 +40,11 @@ public class UserMap extends CacheLoader implements IConf { uuidMap = new UUIDMap(ess); //RemovalListener remListener = new UserMapRemovalListener(); //users = CacheBuilder.newBuilder().maximumSize(ess.getSettings().getMaxUserCacheCount()).softValues().removalListener(remListener).build(this); - CacheBuilder cacheBuilder = CacheBuilder.newBuilder(); - int maxCount = ess.getSettings().getMaxUserCacheCount(); + final CacheBuilder cacheBuilder = CacheBuilder.newBuilder(); + final int maxCount = ess.getSettings().getMaxUserCacheCount(); try { cacheBuilder.maximumSize(maxCount); - } catch (NoSuchMethodError nsme) { + } catch (final NoSuchMethodError nsme) { legacy = true; legacyMaximumSize(cacheBuilder, maxCount); } @@ -61,14 +65,14 @@ public class UserMap extends CacheLoader implements IConf { } keys.clear(); users.invalidateAll(); - for (String string : userdir.list()) { + for (final String string : userdir.list()) { if (!string.endsWith(".yml")) { continue; } final String name = string.substring(0, string.length() - 4); try { keys.add(UUID.fromString(name)); - } catch (IllegalArgumentException ex) { + } catch (final IllegalArgumentException ex) { //Ignore these users till they rejoin. } } @@ -92,12 +96,12 @@ public class UserMap extends CacheLoader implements IConf { final File userFile = getUserFileFromString(sanitizedName); if (userFile.exists()) { ess.getLogger().info("Importing user " + name + " to usermap."); - User user = new User(new OfflinePlayer(sanitizedName, ess.getServer()), ess); + final User user = new User(new OfflinePlayer(sanitizedName, ess.getServer()), ess); trackUUID(user.getBase().getUniqueId(), user.getName(), true); return user; } return null; - } catch (UncheckedExecutionException ex) { + } catch (final UncheckedExecutionException ex) { return null; } } @@ -109,12 +113,12 @@ public class UserMap extends CacheLoader implements IConf { } else { return legacyCacheGet(uuid); } - } catch (ExecutionException | UncheckedExecutionException ex) { + } catch (final ExecutionException | UncheckedExecutionException ex) { return null; } } - public void trackUUID(final UUID uuid, final String name, boolean replace) { + public void trackUUID(final UUID uuid, final String name, final boolean replace) { if (uuid != null) { keys.add(uuid); if (name != null && name.length() > 0) { @@ -139,7 +143,7 @@ public class UserMap extends CacheLoader implements IConf { @Override public User load(final String stringUUID) throws Exception { - UUID uuid = UUID.fromString(stringUUID); + final UUID uuid = UUID.fromString(stringUUID); Player player = ess.getServer().getPlayer(uuid); if (player != null) { final User user = new User(player, ess); @@ -175,7 +179,7 @@ public class UserMap extends CacheLoader implements IConf { ess.getLogger().warning("Name collection is null, cannot remove user."); return; } - UUID uuid = names.get(name); + final UUID uuid = names.get(name); if (uuid != null) { keys.remove(uuid); users.invalidate(uuid.toString()); @@ -207,6 +211,18 @@ public class UserMap extends CacheLoader implements IConf { public UUIDMap getUUIDMap() { return uuidMap; } + // class UserMapRemovalListener implements RemovalListener + // { + // @Override + // public void onRemoval(final RemovalNotification notification) + // { + // Object value = notification.getValue(); + // if (value != null) + // { + // ((User)value).cleanup(); + // } + // } + // } private File getUserFileFromID(final UUID uuid) { final File userFolder = new File(ess.getDataFolder(), "userdata"); @@ -217,20 +233,6 @@ public class UserMap extends CacheLoader implements IConf { final File userFolder = new File(ess.getDataFolder(), "userdata"); return new File(userFolder, StringUtil.sanitizeFileName(name) + ".yml"); } -// class UserMapRemovalListener implements RemovalListener -// { -// @Override -// public void onRemoval(final RemovalNotification notification) -// { -// Object value = notification.getValue(); -// if (value != null) -// { -// ((User)value).cleanup(); -// } -// } -// } - - private final Pattern validUserPattern = Pattern.compile("^[a-zA-Z0-9_]{2,16}$"); @SuppressWarnings("deprecation") public User getUserFromBukkit(String name) { @@ -242,14 +244,14 @@ public class UserMap extends CacheLoader implements IConf { if (name == null || !validUserPattern.matcher(name).matches()) { return null; } - org.bukkit.OfflinePlayer offlinePlayer = ess.getServer().getOfflinePlayer(name); + final org.bukkit.OfflinePlayer offlinePlayer = ess.getServer().getOfflinePlayer(name); if (offlinePlayer == null) { return null; } - UUID uuid; + final UUID uuid; try { uuid = offlinePlayer.getUniqueId(); - } catch (UnsupportedOperationException | NullPointerException e) { + } catch (final UnsupportedOperationException | NullPointerException e) { return null; } // This is how Bukkit generates fake UUIDs @@ -261,12 +263,10 @@ public class UserMap extends CacheLoader implements IConf { } } - private static Method getLegacy; - - private User legacyCacheGet(UUID uuid) { + private User legacyCacheGet(final UUID uuid) { if (getLegacy == null) { - Class usersClass = users.getClass(); - for (Method m : usersClass.getDeclaredMethods()) { + final Class usersClass = users.getClass(); + for (final Method m : usersClass.getDeclaredMethods()) { if (m.getName().equals("get")) { getLegacy = m; getLegacy.setAccessible(true); @@ -276,25 +276,25 @@ public class UserMap extends CacheLoader implements IConf { } try { return (User) getLegacy.invoke(users, uuid.toString()); - } catch (IllegalAccessException | InvocationTargetException e) { + } catch (final IllegalAccessException | InvocationTargetException e) { return null; } } - private void legacyMaximumSize(CacheBuilder builder, int maxCount) { + private void legacyMaximumSize(final CacheBuilder builder, final int maxCount) { try { - Method maxSizeLegacy = builder.getClass().getDeclaredMethod("maximumSize", Integer.TYPE); + final Method maxSizeLegacy = builder.getClass().getDeclaredMethod("maximumSize", Integer.TYPE); maxSizeLegacy.setAccessible(true); maxSizeLegacy.invoke(builder, maxCount); - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + } catch (final NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { e.printStackTrace(); } } @SuppressWarnings("unchecked") - private Cache legacyBuild(CacheBuilder builder) { + private Cache legacyBuild(final CacheBuilder builder) { Method build = null; - for (Method method : builder.getClass().getDeclaredMethods()) { + for (final Method method : builder.getClass().getDeclaredMethods()) { if (method.getName().equals("build")) { build = method; break; @@ -305,7 +305,7 @@ public class UserMap extends CacheLoader implements IConf { assert build != null; build.setAccessible(true); legacyUsers = (Cache) build.invoke(builder, this); - } catch (IllegalAccessException | InvocationTargetException e) { + } catch (final IllegalAccessException | InvocationTargetException e) { legacyUsers = null; } return legacyUsers; diff --git a/Essentials/src/com/earth2me/essentials/Warps.java b/Essentials/src/com/earth2me/essentials/Warps.java index 3aa173870..ef7a9a7c3 100644 --- a/Essentials/src/com/earth2me/essentials/Warps.java +++ b/Essentials/src/com/earth2me/essentials/Warps.java @@ -6,13 +6,20 @@ import net.ess3.api.InvalidNameException; import net.ess3.api.InvalidWorldException; import org.bukkit.Location; import org.bukkit.Server; + import java.io.File; import java.io.IOException; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; -import static com.earth2me.essentials.I18n.tl; +import static com.earth2me.essentials.I18n.tl; public class Warps implements IConf, net.ess3.api.IWarps { private static final Logger logger = Logger.getLogger("Essentials"); @@ -20,7 +27,7 @@ public class Warps implements IConf, net.ess3.api.IWarps { private final File warpsFolder; private final Server server; - public Warps(Server server, File dataFolder) { + public Warps(final Server server, final File dataFolder) { this.server = server; warpsFolder = new File(dataFolder, "warps"); if (!warpsFolder.exists()) { @@ -37,7 +44,7 @@ public class Warps implements IConf, net.ess3.api.IWarps { @Override public Collection getList() { final List keys = new ArrayList<>(); - for (StringIgnoreCase stringIgnoreCase : warpPoints.keySet()) { + for (final StringIgnoreCase stringIgnoreCase : warpPoints.keySet()) { keys.add(stringIgnoreCase.getString()); } keys.sort(String.CASE_INSENSITIVE_ORDER); @@ -45,8 +52,8 @@ public class Warps implements IConf, net.ess3.api.IWarps { } @Override - public Location getWarp(String warp) throws WarpNotFoundException, InvalidWorldException { - EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp)); + public Location getWarp(final String warp) throws WarpNotFoundException, InvalidWorldException { + final EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp)); if (conf == null) { throw new WarpNotFoundException(); } @@ -54,16 +61,16 @@ public class Warps implements IConf, net.ess3.api.IWarps { } @Override - public void setWarp(String name, Location loc) throws Exception { + public void setWarp(final String name, final Location loc) throws Exception { setWarp(null, name, loc); } - + @Override - public void setWarp(IUser user, String name, Location loc) throws Exception { - String filename = StringUtil.sanitizeFileName(name); + public void setWarp(final IUser user, final String name, final Location loc) throws Exception { + final String filename = StringUtil.sanitizeFileName(name); EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name)); if (conf == null) { - File confFile = new File(warpsFolder, filename + ".yml"); + final File confFile = new File(warpsFolder, filename + ".yml"); if (confFile.exists()) { throw new Exception(tl("similarWarpExist")); } @@ -75,28 +82,28 @@ public class Warps implements IConf, net.ess3.api.IWarps { if (user != null) conf.setProperty("lastowner", user.getBase().getUniqueId().toString()); try { conf.saveWithError(); - } catch (IOException ex) { + } catch (final IOException ex) { throw new IOException(tl("invalidWarpName")); } } - + @Override - public UUID getLastOwner(String warp) throws WarpNotFoundException { - EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp)); + public UUID getLastOwner(final String warp) throws WarpNotFoundException { + final EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp)); if (conf == null) { throw new WarpNotFoundException(); } UUID uuid = null; try { uuid = UUID.fromString(conf.getString("lastowner")); + } catch (final Exception ignored) { } - catch (Exception ignored) {} return uuid; } - + @Override - public void removeWarp(String name) throws Exception { - EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name)); + public void removeWarp(final String name) throws Exception { + final EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name)); if (conf == null) { throw new Exception(tl("warpNotExist")); } @@ -109,19 +116,19 @@ public class Warps implements IConf, net.ess3.api.IWarps { @Override public final void reloadConfig() { warpPoints.clear(); - File[] listOfFiles = warpsFolder.listFiles(); + final File[] listOfFiles = warpsFolder.listFiles(); if (listOfFiles.length >= 1) { - for (File listOfFile : listOfFiles) { - String filename = listOfFile.getName(); + for (final File listOfFile : listOfFiles) { + final String filename = listOfFile.getName(); if (listOfFile.isFile() && filename.endsWith(".yml")) { try { - EssentialsConf conf = new EssentialsConf(listOfFile); + final EssentialsConf conf = new EssentialsConf(listOfFile); conf.load(); - String name = conf.getString("name"); + final String name = conf.getString("name"); if (name != null) { warpPoints.put(new StringIgnoreCase(name), conf); } - } catch (Exception ex) { + } catch (final Exception ex) { logger.log(Level.WARNING, tl("loadWarpError", filename), ex); } } @@ -131,7 +138,7 @@ public class Warps implements IConf, net.ess3.api.IWarps { //This is here for future 3.x api support. Not implemented here becasue storage is handled differently @Override - public File getWarpFile(String name) throws InvalidNameException { + public File getWarpFile(final String name) throws InvalidNameException { throw new UnsupportedOperationException("Not supported yet."); } @@ -143,7 +150,7 @@ public class Warps implements IConf, net.ess3.api.IWarps { private static class StringIgnoreCase { private final String string; - public StringIgnoreCase(String string) { + StringIgnoreCase(final String string) { this.string = string; } @@ -153,7 +160,7 @@ public class Warps implements IConf, net.ess3.api.IWarps { } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { if (o instanceof StringIgnoreCase) { return getString().equalsIgnoreCase(((StringIgnoreCase) o).getString()); } diff --git a/Essentials/src/com/earth2me/essentials/Worth.java b/Essentials/src/com/earth2me/essentials/Worth.java index 804797dd3..9beea1918 100644 --- a/Essentials/src/com/earth2me/essentials/Worth.java +++ b/Essentials/src/com/earth2me/essentials/Worth.java @@ -12,11 +12,10 @@ import java.util.Locale; import static com.earth2me.essentials.I18n.tl; - public class Worth implements IConf { private final EssentialsConf config; - public Worth(File dataFolder) { + public Worth(final File dataFolder) { config = new EssentialsConf(new File(dataFolder, "worth.yml")); config.setTemplateName("/worth.yml"); config.load(); @@ -29,10 +28,10 @@ public class Worth implements IConf { * @param itemStack The item stack to look up in the config. * @return The price from the config. */ - public BigDecimal getPrice(IEssentials ess, ItemStack itemStack) { + public BigDecimal getPrice(final IEssentials ess, final ItemStack itemStack) { BigDecimal result; - String itemname = itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); + final String itemname = itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); // Check for matches with data value from stack // Note that we always default to BigDecimal.ONE.negate(), equivalent to -1 @@ -73,7 +72,7 @@ public class Worth implements IConf { * @return The amount of items to sell from the player's inventory. * @throws Exception Thrown if trying to sell air or an invalid amount. */ - public int getAmount(IEssentials ess, User user, ItemStack is, String[] args, boolean isBulkSell) throws Exception { + public int getAmount(final IEssentials ess, final User user, final ItemStack is, final String[] args, final boolean isBulkSell) throws Exception { if (is == null || is.getType() == Material.AIR) { throw new Exception(tl("itemSellAir")); } @@ -83,7 +82,7 @@ public class Worth implements IConf { if (args.length > 1) { try { amount = Integer.parseInt(args[1].replaceAll("[^0-9]", "")); - } catch (NumberFormatException ex) { + } catch (final NumberFormatException ex) { throw new NotEnoughArgumentsException(ex); } if (args[1].startsWith("-")) { @@ -91,15 +90,15 @@ public class Worth implements IConf { } } - boolean stack = args.length > 1 && args[1].endsWith("s"); - boolean requireStack = ess.getSettings().isTradeInStacks(is.getType()); + final boolean stack = args.length > 1 && args[1].endsWith("s"); + final boolean requireStack = ess.getSettings().isTradeInStacks(is.getType()); if (requireStack && !stack) { throw new Exception(tl("itemMustBeStacked")); } int max = 0; - for (ItemStack s : user.getBase().getInventory().getContents()) { + for (final ItemStack s : user.getBase().getInventory().getContents()) { if (s == null || !s.isSimilar(is)) { continue; } @@ -136,7 +135,7 @@ public class Worth implements IConf { * @param itemStack A stack of the item to save. * @param price The new price of the item. */ - public void setPrice(IEssentials ess, ItemStack itemStack, double price) { + public void setPrice(final IEssentials ess, final ItemStack itemStack, final double price) { String path = "worth." + itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); // Spigot 1.13+ throws an exception if a 1.13+ plugin even *attempts* to do set data. diff --git a/Essentials/src/com/earth2me/essentials/api/Economy.java b/Essentials/src/com/earth2me/essentials/api/Economy.java index 84bc66fa7..0a7f88b24 100644 --- a/Essentials/src/com/earth2me/essentials/api/Economy.java +++ b/Essentials/src/com/earth2me/essentials/api/Economy.java @@ -18,36 +18,35 @@ import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; - /** * You should use Vault instead of directly using this class. */ public class Economy { - public Economy() { - } - - private static final Logger logger = Logger.getLogger("Essentials"); - private static IEssentials ess; - private static final String noCallBeforeLoad = "Essentials API is called before Essentials is loaded."; public static final MathContext MATH_CONTEXT = MathContext.DECIMAL128; + private static final Logger logger = Logger.getLogger("Essentials"); + private static final String noCallBeforeLoad = "Essentials API is called before Essentials is loaded."; + private static IEssentials ess; + + protected Economy() { + } /** * @param aEss the ess to set */ - public static void setEss(IEssentials aEss) { + public static void setEss(final IEssentials aEss) { ess = aEss; } private static void createNPCFile(String name) { - File folder = new File(ess.getDataFolder(), "userdata"); + final File folder = new File(ess.getDataFolder(), "userdata"); name = StringUtil.safeString(name); if (!folder.exists()) { if (!folder.mkdirs()) { throw new RuntimeException("Error while creating userdata directory!"); } } - UUID npcUUID = UUID.nameUUIDFromBytes(("NPC:" + name).getBytes(Charsets.UTF_8)); - EssentialsUserConf npcConfig = new EssentialsUserConf(name, npcUUID, new File(folder, npcUUID.toString() + ".yml")); + final UUID npcUUID = UUID.nameUUIDFromBytes(("NPC:" + name).getBytes(Charsets.UTF_8)); + final EssentialsUserConf npcConfig = new EssentialsUserConf(name, npcUUID, new File(folder, npcUUID.toString() + ".yml")); npcConfig.load(); npcConfig.setProperty("npc", true); npcConfig.setProperty("lastAccountName", name); @@ -56,12 +55,12 @@ public class Economy { ess.getUserMap().trackUUID(npcUUID, name, false); } - private static void deleteNPC(String name) { - User user = ess.getUser(name); + private static void deleteNPC(final String name) { + final User user = ess.getUser(name); user.reset(); } - private static User getUserByName(String name) { + private static User getUserByName(final String name) { if (ess == null) { throw new RuntimeException(noCallBeforeLoad); } @@ -76,7 +75,7 @@ public class Economy { via Vault during player join. See: https://github.com/EssentialsX/Essentials/issues/2400 */ - Player player = ess.getServer().getPlayerExact(name); + final Player player = ess.getServer().getPlayerExact(name); if (player != null) { user = ess.getUser(player.getUniqueId()); if (user != null) { @@ -88,7 +87,7 @@ public class Economy { return user; } - private static User getUserByUUID(UUID uuid) { + private static User getUserByUUID(final UUID uuid) { if (ess == null) { throw new RuntimeException(noCallBeforeLoad); } @@ -101,16 +100,14 @@ public class Economy { /** * Returns the balance of a user * - * @deprecated Use {@link Economy#getMoneyExact(UUID)} or {@link Economy#getMoneyExact(User)} * @param name Name of the user - * * @return balance - * * @throws UserDoesNotExistException + * @deprecated Use {@link Economy#getMoneyExact(UUID)} or {@link Economy#getMoneyExact(User)} */ @Deprecated - public static double getMoney(String name) throws UserDoesNotExistException { - BigDecimal exactAmount = getMoneyExact(name); + public static double getMoney(final String name) throws UserDoesNotExistException { + final BigDecimal exactAmount = getMoneyExact(name); double amount = exactAmount.doubleValue(); if (new BigDecimal(amount).compareTo(exactAmount) > 0) { // closest double is bigger than the exact amount @@ -121,29 +118,29 @@ public class Economy { } /** - * @deprecated Usernames can change, use {@link Economy#getMoneyExact(UUID)} or {@link Economy#getMoneyExact(User)} * @param name Name of user * @return Exact balance of user * @throws UserDoesNotExistException + * @deprecated Usernames can change, use {@link Economy#getMoneyExact(UUID)} or {@link Economy#getMoneyExact(User)} */ @Deprecated - public static BigDecimal getMoneyExact(String name) throws UserDoesNotExistException { - User user = getUserByName(name); + public static BigDecimal getMoneyExact(final String name) throws UserDoesNotExistException { + final User user = getUserByName(name); if (user == null) { throw new UserDoesNotExistException(name); } return getMoneyExact(user); } - public static BigDecimal getMoneyExact(UUID uuid) throws UserDoesNotExistException { - User user = getUserByUUID(uuid); + public static BigDecimal getMoneyExact(final UUID uuid) throws UserDoesNotExistException { + final User user = getUserByUUID(uuid); if (user == null) { throw new UserDoesNotExistException(uuid); } return getMoneyExact(user); } - public static BigDecimal getMoneyExact(User user) { + public static BigDecimal getMoneyExact(final User user) { if (user == null) { throw new IllegalArgumentException("Economy user cannot be null"); } @@ -153,19 +150,17 @@ public class Economy { /** * Sets the balance of a user * - * @deprecated Use {@link Economy#setMoney(UUID, BigDecimal)} or {@link Economy#setMoney(User, BigDecimal)} - * * @param name Name of the user * @param balance The balance you want to set - * * @throws UserDoesNotExistException If a user by that name does not exists * @throws NoLoanPermittedException If the user is not allowed to have a negative balance + * @deprecated Use {@link Economy#setMoney(UUID, BigDecimal)} or {@link Economy#setMoney(User, BigDecimal)} */ @Deprecated - public static void setMoney(String name, double balance) throws UserDoesNotExistException, NoLoanPermittedException { + public static void setMoney(final String name, final double balance) throws UserDoesNotExistException, NoLoanPermittedException { try { setMoney(name, BigDecimal.valueOf(balance)); - } catch (ArithmeticException e) { + } catch (final ArithmeticException e) { logger.log(Level.WARNING, "Failed to set balance of " + name + " to " + balance + ": " + e.getMessage(), e); } } @@ -173,17 +168,15 @@ public class Economy { /** * Sets the balance of a user * - * @deprecated Usernames can change use {@link Economy#setMoney(UUID, BigDecimal)} or {@link Economy#setMoney(User, BigDecimal)} - * * @param name Name of user * @param balance The balance you want to set - * * @throws UserDoesNotExistException If a user by that name does not exist * @throws NoLoanPermittedException If the user is not allowed to have a negative balance + * @deprecated Usernames can change use {@link Economy#setMoney(UUID, BigDecimal)} or {@link Economy#setMoney(User, BigDecimal)} */ @Deprecated - public static void setMoney(String name, BigDecimal balance) throws UserDoesNotExistException, NoLoanPermittedException { - User user = getUserByName(name); + public static void setMoney(final String name, final BigDecimal balance) throws UserDoesNotExistException, NoLoanPermittedException { + final User user = getUserByName(name); if (user == null) { throw new UserDoesNotExistException(name); } @@ -195,12 +188,11 @@ public class Economy { * * @param uuid UUID of user * @param balance The balance you want to set - * * @throws UserDoesNotExistException If a user by that uuid does not exist * @throws NoLoanPermittedException If the user is not allowed to have a negative balance */ - public static void setMoney(UUID uuid, BigDecimal balance) throws NoLoanPermittedException, UserDoesNotExistException { - User user = getUserByUUID(uuid); + public static void setMoney(final UUID uuid, final BigDecimal balance) throws NoLoanPermittedException, UserDoesNotExistException { + final User user = getUserByUUID(uuid); if (user == null) { throw new UserDoesNotExistException(uuid); } @@ -212,10 +204,9 @@ public class Economy { * * @param user User * @param balance The balance you want to set - * * @throws NoLoanPermittedException If the user is not allowed to have a negative balance */ - public static void setMoney(User user, BigDecimal balance) throws NoLoanPermittedException { + public static void setMoney(final User user, final BigDecimal balance) throws NoLoanPermittedException { if (user == null) { throw new IllegalArgumentException("Economy user cannot be null"); } @@ -227,7 +218,7 @@ public class Economy { } try { user.setMoney(balance, UserBalanceUpdateEvent.Cause.API); - } catch (MaxMoneyException ex) { + } catch (final MaxMoneyException ex) { //TODO: Update API to show max balance errors } Trade.log("API", "Set", "API", user.getName(), new Trade(balance, ess), null, null, null, ess); @@ -235,20 +226,19 @@ public class Economy { /** * Adds money to the balance of a user - * + *

* Use {@link Economy#add(UUID, BigDecimal)} or {@link Economy#add(User, BigDecimal)} * * @param name Name of the user * @param amount The money you want to add - * * @throws UserDoesNotExistException If a user by that name does not exists * @throws NoLoanPermittedException If the user is not allowed to have a negative balance */ @Deprecated - public static void add(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException { + public static void add(final String name, final double amount) throws UserDoesNotExistException, NoLoanPermittedException { try { add(name, BigDecimal.valueOf(amount)); - } catch (ArithmeticException e) { + } catch (final ArithmeticException e) { logger.log(Level.WARNING, "Failed to add " + amount + " to balance of " + name + ": " + e.getMessage(), e); } } @@ -256,18 +246,16 @@ public class Economy { /** * Adds money to the balance of a user * - * @deprecated Usernames can change, use {@link Economy#add(UUID, BigDecimal)} or {@link Economy#add(User, BigDecimal)} - * * @param name Name of the user * @param amount The amount of money to be added to the user's account - * * @throws UserDoesNotExistException If a user by that name does not exist * @throws NoLoanPermittedException If the user is not allowed to have a negative balance * @throws ArithmeticException + * @deprecated Usernames can change, use {@link Economy#add(UUID, BigDecimal)} or {@link Economy#add(User, BigDecimal)} */ @Deprecated - public static void add(String name, BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException { - User user = getUserByName(name); + public static void add(final String name, final BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException { + final User user = getUserByName(name); if (user == null) { throw new UserDoesNotExistException(name); } @@ -279,13 +267,12 @@ public class Economy { * * @param uuid UUID of the user * @param amount The money you want to add - * * @throws UserDoesNotExistException If a user by that uuid does not exist * @throws NoLoanPermittedException If the user is not allowed to have a negative balance * @throws ArithmeticException */ - public static void add(UUID uuid, BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, UserDoesNotExistException { - User user = getUserByUUID(uuid); + public static void add(final UUID uuid, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, UserDoesNotExistException { + final User user = getUserByUUID(uuid); if (user == null) { throw new UserDoesNotExistException(uuid); } @@ -295,19 +282,17 @@ public class Economy { /** * Adds money to the balance of a user * - * @deprecated Usernames can change, use {@link Economy#add(UUID, BigDecimal)} or {@link Economy#add(User, BigDecimal)} - * * @param user User * @param amount The money you want to add - * - * @throws NoLoanPermittedException If the user is not allowed to have a negative balance + * @throws NoLoanPermittedException If the user is not allowed to have a negative balance * @throws ArithmeticException + * @deprecated Usernames can change, use {@link Economy#add(UUID, BigDecimal)} or {@link Economy#add(User, BigDecimal)} */ - public static void add(User user, BigDecimal amount) throws NoLoanPermittedException, ArithmeticException { + public static void add(final User user, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException { if (user == null) { throw new IllegalArgumentException("Economy user cannot be null"); } - BigDecimal result = getMoneyExact(user).add(amount, MATH_CONTEXT); + final BigDecimal result = getMoneyExact(user).add(amount, MATH_CONTEXT); setMoney(user, result); Trade.log("API", "Add", "API", user.getName(), new Trade(amount, ess), null, null, null, ess); } @@ -315,19 +300,17 @@ public class Economy { /** * Subtracts money from the balance of a user * - * @deprecated Use {@link Economy#subtract(UUID, BigDecimal)} or {@link Economy#subtract(User, BigDecimal)} - * * @param name Name of the user * @param amount The money you want to subtract - * * @throws UserDoesNotExistException If a user by that name does not exists * @throws NoLoanPermittedException If the user is not allowed to have a negative balance + * @deprecated Use {@link Economy#subtract(UUID, BigDecimal)} or {@link Economy#subtract(User, BigDecimal)} */ @Deprecated - public static void subtract(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException { + public static void subtract(final String name, final double amount) throws UserDoesNotExistException, NoLoanPermittedException { try { substract(name, BigDecimal.valueOf(amount)); - } catch (ArithmeticException e) { + } catch (final ArithmeticException e) { logger.log(Level.WARNING, "Failed to subtract " + amount + " of balance of " + name + ": " + e.getMessage(), e); } } @@ -335,18 +318,16 @@ public class Economy { /** * Subtracts money from the balance of a user * - * @deprecated Usernames can change, use {@link Economy#subtract(UUID, BigDecimal)} or {@link Economy#subtract(User, BigDecimal)} - * * @param name Name of the user * @param amount The money you want to subtract - * * @throws UserDoesNotExistException If a user by that name does not exist * @throws NoLoanPermittedException If the user is not allowed to have a negative balance * @throws ArithmeticException + * @deprecated Usernames can change, use {@link Economy#subtract(UUID, BigDecimal)} or {@link Economy#subtract(User, BigDecimal)} */ @Deprecated - public static void substract(String name, BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException { - BigDecimal result = getMoneyExact(name).subtract(amount, MATH_CONTEXT); + public static void substract(final String name, final BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException { + final BigDecimal result = getMoneyExact(name).subtract(amount, MATH_CONTEXT); setMoney(name, result); Trade.log("API", "Subtract", "API", name, new Trade(amount, ess), null, null, null, ess); } @@ -356,13 +337,12 @@ public class Economy { * * @param uuid UUID of the user * @param amount The money you want to subtract - * * @throws UserDoesNotExistException If a user by that UUID does not exist * @throws NoLoanPermittedException If the user is not allowed to have a negative balance * @throws ArithmeticException */ - public static void subtract(UUID uuid, BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, UserDoesNotExistException { - User user = getUserByUUID(uuid); + public static void subtract(final UUID uuid, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, UserDoesNotExistException { + final User user = getUserByUUID(uuid); if (user == null) { throw new UserDoesNotExistException(uuid); } @@ -374,15 +354,14 @@ public class Economy { * * @param user User * @param amount The money you want to subtract - * * @throws NoLoanPermittedException If the user is not allowed to have a negative balance * @throws ArithmeticException */ - public static void subtract(User user, BigDecimal amount) throws NoLoanPermittedException, ArithmeticException { + public static void subtract(final User user, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException { if (user == null) { throw new IllegalArgumentException("Economy user cannot be null"); } - BigDecimal result = getMoneyExact(user).subtract(amount, MATH_CONTEXT); + final BigDecimal result = getMoneyExact(user).subtract(amount, MATH_CONTEXT); setMoney(user, result); Trade.log("API", "Subtract", "API", user.getName(), new Trade(amount, ess), null, null, null, ess); } @@ -390,19 +369,17 @@ public class Economy { /** * Divides the balance of a user by a value * - * @deprecated Use {@link Economy#divide(UUID, BigDecimal)} or {@link Economy#divide(User, BigDecimal)} - * - * @param name Name of the user + * @param name Name of the user * @param amount The balance is divided by this value - * * @throws UserDoesNotExistException If a user by that name does not exists * @throws NoLoanPermittedException If the user is not allowed to have a negative balance + * @deprecated Use {@link Economy#divide(UUID, BigDecimal)} or {@link Economy#divide(User, BigDecimal)} */ @Deprecated - public static void divide(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException { + public static void divide(final String name, final double amount) throws UserDoesNotExistException, NoLoanPermittedException { try { divide(name, BigDecimal.valueOf(amount)); - } catch (ArithmeticException e) { + } catch (final ArithmeticException e) { logger.log(Level.WARNING, "Failed to divide balance of " + name + " by " + amount + ": " + e.getMessage(), e); } } @@ -410,18 +387,16 @@ public class Economy { /** * Divides the balance of a user by a value * - * @deprecated Usernames can change, use {@link Economy#divide(UUID, BigDecimal)} or {@link Economy#divide(User, BigDecimal)} - * * @param name Name of the user * @param amount The balance is divided by this value - * * @throws UserDoesNotExistException If a user by that name does not exist * @throws NoLoanPermittedException If the user is not allowed to have a negative balance * @throws ArithmeticException + * @deprecated Usernames can change, use {@link Economy#divide(UUID, BigDecimal)} or {@link Economy#divide(User, BigDecimal)} */ @Deprecated - public static void divide(String name, BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException { - User user = getUserByName(name); + public static void divide(final String name, final BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException { + final User user = getUserByName(name); if (user == null) { throw new UserDoesNotExistException(name); } @@ -433,13 +408,12 @@ public class Economy { * * @param uuid Name of the user * @param amount The balance is divided by this value - * * @throws UserDoesNotExistException If a user by that UUID does not exist * @throws NoLoanPermittedException If the user is not allowed to have a negative balance * @throws ArithmeticException */ - public static void divide(UUID uuid, BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, UserDoesNotExistException { - User user = getUserByUUID(uuid); + public static void divide(final UUID uuid, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, UserDoesNotExistException { + final User user = getUserByUUID(uuid); if (user == null) { throw new UserDoesNotExistException(uuid); } @@ -451,15 +425,14 @@ public class Economy { * * @param user Name of the user * @param amount The balance is divided by this value - * - * @throws NoLoanPermittedException If the user is not allowed to have a negative balance + * @throws NoLoanPermittedException If the user is not allowed to have a negative balance * @throws ArithmeticException */ - public static void divide(User user, BigDecimal amount) throws NoLoanPermittedException, ArithmeticException { + public static void divide(final User user, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException { if (user == null) { throw new IllegalArgumentException("Economy user cannot be null"); } - BigDecimal result = getMoneyExact(user).divide(amount, MATH_CONTEXT); + final BigDecimal result = getMoneyExact(user).divide(amount, MATH_CONTEXT); setMoney(user, result); Trade.log("API", "Divide", "API", user.getName(), new Trade(amount, ess), null, null, null, ess); } @@ -467,19 +440,17 @@ public class Economy { /** * Multiplies the balance of a user by a value * - * @deprecated Use {@link Economy#multiply(UUID, BigDecimal)} or {@link Economy#multiply(User, BigDecimal)} - * - * @param name Name of the user + * @param name Name of the user * @param amount The balance is multiplied by this value - * * @throws UserDoesNotExistException If a user by that name does not exists * @throws NoLoanPermittedException If the user is not allowed to have a negative balance + * @deprecated Use {@link Economy#multiply(UUID, BigDecimal)} or {@link Economy#multiply(User, BigDecimal)} */ @Deprecated - public static void multiply(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException { + public static void multiply(final String name, final double amount) throws UserDoesNotExistException, NoLoanPermittedException { try { multiply(name, BigDecimal.valueOf(amount)); - } catch (ArithmeticException e) { + } catch (final ArithmeticException e) { logger.log(Level.WARNING, "Failed to multiply balance of " + name + " by " + amount + ": " + e.getMessage(), e); } } @@ -487,18 +458,16 @@ public class Economy { /** * Multiplies the balance of a user by a value * - * @deprecated Usernames can change, use {@link Economy#multiply(UUID, BigDecimal)} or {@link Economy#multiply(User, BigDecimal)} - * * @param name Name of the user * @param amount The balance is multiplied by the this value - * * @throws UserDoesNotExistException If a user by that name does not exist * @throws NoLoanPermittedException If the user is not allowed to have a negative balance * @throws ArithmeticException + * @deprecated Usernames can change, use {@link Economy#multiply(UUID, BigDecimal)} or {@link Economy#multiply(User, BigDecimal)} */ @Deprecated - public static void multiply(String name, BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException { - User user = getUserByName(name); + public static void multiply(final String name, final BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException { + final User user = getUserByName(name); if (user == null) { throw new UserDoesNotExistException(name); } @@ -510,13 +479,12 @@ public class Economy { * * @param uuid Name of the user * @param amount The balance is multiplied by the this value - * * @throws UserDoesNotExistException If a user by that uuid does not exist * @throws NoLoanPermittedException If the user is not allowed to have a negative balance * @throws ArithmeticException */ - public static void multiply(UUID uuid, BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, UserDoesNotExistException { - User user = getUserByUUID(uuid); + public static void multiply(final UUID uuid, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException, UserDoesNotExistException { + final User user = getUserByUUID(uuid); if (user == null) { throw new UserDoesNotExistException(uuid); } @@ -528,15 +496,14 @@ public class Economy { * * @param user Name of the user * @param amount The balance is multiplied by the this value - * - * @throws NoLoanPermittedException If the user is not allowed to have a negative balance + * @throws NoLoanPermittedException If the user is not allowed to have a negative balance * @throws ArithmeticException */ - public static void multiply(User user, BigDecimal amount) throws NoLoanPermittedException, ArithmeticException { + public static void multiply(final User user, final BigDecimal amount) throws NoLoanPermittedException, ArithmeticException { if (user == null) { throw new IllegalArgumentException("Economy user cannot be null"); } - BigDecimal result = getMoneyExact(user).multiply(amount, MATH_CONTEXT); + final BigDecimal result = getMoneyExact(user).multiply(amount, MATH_CONTEXT); setMoney(user, result); Trade.log("API", "Multiply", "API", user.getName(), new Trade(amount, ess), null, null, null, ess); } @@ -544,15 +511,13 @@ public class Economy { /** * Resets the balance of a user to the starting balance * - * @deprecated Usernames can change, use {@link Economy#resetBalance(UUID)} or {@link Economy#resetBalance(User)} - * * @param name Name of the user - * * @throws UserDoesNotExistException If a user by that name does not exists * @throws NoLoanPermittedException If the user is not allowed to have a negative balance + * @deprecated Usernames can change, use {@link Economy#resetBalance(UUID)} or {@link Economy#resetBalance(User)} */ @Deprecated - public static void resetBalance(String name) throws UserDoesNotExistException, NoLoanPermittedException { + public static void resetBalance(final String name) throws UserDoesNotExistException, NoLoanPermittedException { if (ess == null) { throw new RuntimeException(noCallBeforeLoad); } @@ -564,12 +529,11 @@ public class Economy { * Resets the balance of a user to the starting balance * * @param uuid UUID of the user - * * @throws UserDoesNotExistException If a user by that UUID does not exists * @throws NoLoanPermittedException If the user is not allowed to have a negative balance */ - public static void resetBalance(UUID uuid) throws NoLoanPermittedException, UserDoesNotExistException { - User user = getUserByUUID(uuid); + public static void resetBalance(final UUID uuid) throws NoLoanPermittedException, UserDoesNotExistException { + final User user = getUserByUUID(uuid); if (user == null) { throw new UserDoesNotExistException(uuid); } @@ -580,10 +544,9 @@ public class Economy { * Resets the balance of a user to the starting balance * * @param user User - * - * @throws NoLoanPermittedException If the user is not allowed to have a negative balance + * @throws NoLoanPermittedException If the user is not allowed to have a negative balance */ - public static void resetBalance(User user) throws NoLoanPermittedException { + public static void resetBalance(final User user) throws NoLoanPermittedException { if (ess == null) { throw new RuntimeException(noCallBeforeLoad); } @@ -595,38 +558,32 @@ public class Economy { } /** - * @deprecated Use {@link Economy#hasEnough(UUID, BigDecimal)} or {@link Economy#hasEnough(User, BigDecimal)} - * * @param name Name of the user * @param amount The amount of money the user should have - * * @return true, if the user has more or an equal amount of money - * * @throws UserDoesNotExistException If a user by that name does not exists + * @deprecated Use {@link Economy#hasEnough(UUID, BigDecimal)} or {@link Economy#hasEnough(User, BigDecimal)} */ @Deprecated - public static boolean hasEnough(String name, double amount) throws UserDoesNotExistException { + public static boolean hasEnough(final String name, final double amount) throws UserDoesNotExistException { try { return hasEnough(name, BigDecimal.valueOf(amount)); - } catch (ArithmeticException e) { + } catch (final ArithmeticException e) { logger.log(Level.WARNING, "Failed to compare balance of " + name + " with " + amount + ": " + e.getMessage(), e); return false; } } /** - * @deprecated Usernames can change, use {@link Economy#hasEnough(UUID, BigDecimal)} or {@link Economy#hasEnough(User, BigDecimal)} - * * @param name Name of the user * @param amount The amount of money the user should have - * * @return true, if the user has more or an equal amount of money - * * @throws UserDoesNotExistException If a user by that name does not exist * @throws ArithmeticException + * @deprecated Usernames can change, use {@link Economy#hasEnough(UUID, BigDecimal)} or {@link Economy#hasEnough(User, BigDecimal)} */ - public static boolean hasEnough(String name, BigDecimal amount) throws UserDoesNotExistException, ArithmeticException { - User user = getUserByName(name); + public static boolean hasEnough(final String name, final BigDecimal amount) throws UserDoesNotExistException, ArithmeticException { + final User user = getUserByName(name); if (user == null) { throw new UserDoesNotExistException(name); } @@ -636,14 +593,12 @@ public class Economy { /** * @param uuid UUID of the user * @param amount The amount of money the user should have - * * @return true, if the user has more or an equal amount of money - * * @throws UserDoesNotExistException If a user by that UUID does not exist * @throws ArithmeticException */ - public static boolean hasEnough(UUID uuid, BigDecimal amount) throws ArithmeticException, UserDoesNotExistException { - User user = getUserByUUID(uuid); + public static boolean hasEnough(final UUID uuid, final BigDecimal amount) throws ArithmeticException, UserDoesNotExistException { + final User user = getUserByUUID(uuid); if (user == null) { throw new UserDoesNotExistException(uuid); } @@ -653,12 +608,10 @@ public class Economy { /** * @param user User * @param amount The amount of money the user should have - * * @return true, if the user has more or an equal amount of money - * * @throws ArithmeticException */ - public static boolean hasEnough(User user, BigDecimal amount) throws ArithmeticException { + public static boolean hasEnough(final User user, final BigDecimal amount) throws ArithmeticException { if (user == null) { throw new IllegalArgumentException("Economy user cannot be null"); } @@ -666,39 +619,33 @@ public class Economy { } /** - * @deprecated Use {@link Economy#hasMore(UUID, BigDecimal)} or {@link Economy#hasMore(User, BigDecimal)} - * * @param name Name of the user * @param amount The amount of money the user should have - * * @return true, if the user has more money - * * @throws UserDoesNotExistException If a user by that name does not exists + * @deprecated Use {@link Economy#hasMore(UUID, BigDecimal)} or {@link Economy#hasMore(User, BigDecimal)} */ @Deprecated - public static boolean hasMore(String name, double amount) throws UserDoesNotExistException { + public static boolean hasMore(final String name, final double amount) throws UserDoesNotExistException { try { return hasMore(name, BigDecimal.valueOf(amount)); - } catch (ArithmeticException e) { + } catch (final ArithmeticException e) { logger.log(Level.WARNING, "Failed to compare balance of " + name + " with " + amount + ": " + e.getMessage(), e); return false; } } /** - * @deprecated Usernames can change, use {@link Economy#hasMore(UUID, BigDecimal)} or {@link Economy#hasMore(User, BigDecimal)} - * * @param name Name of the user * @param amount The amount of money the user should have - * * @return true, if the user has more money - * * @throws UserDoesNotExistException If a user by that name does not exists * @throws ArithmeticException + * @deprecated Usernames can change, use {@link Economy#hasMore(UUID, BigDecimal)} or {@link Economy#hasMore(User, BigDecimal)} */ @Deprecated - public static boolean hasMore(String name, BigDecimal amount) throws UserDoesNotExistException, ArithmeticException { - User user = getUserByName(name); + public static boolean hasMore(final String name, final BigDecimal amount) throws UserDoesNotExistException, ArithmeticException { + final User user = getUserByName(name); if (user == null) { throw new UserDoesNotExistException(name); } @@ -708,14 +655,12 @@ public class Economy { /** * @param uuid UUID of the user * @param amount The amount of money the user should have - * * @return true, if the user has more money - * * @throws UserDoesNotExistException If a user by that UUID does not exists * @throws ArithmeticException */ - public static boolean hasMore(UUID uuid, BigDecimal amount) throws ArithmeticException, UserDoesNotExistException { - User user = getUserByUUID(uuid); + public static boolean hasMore(final UUID uuid, final BigDecimal amount) throws ArithmeticException, UserDoesNotExistException { + final User user = getUserByUUID(uuid); if (user == null) { throw new UserDoesNotExistException(uuid); } @@ -725,12 +670,10 @@ public class Economy { /** * @param user User * @param amount The amount of money the user should have - * * @return true, if the user has more money - * * @throws ArithmeticException */ - public static boolean hasMore(User user, BigDecimal amount) throws ArithmeticException { + public static boolean hasMore(final User user, final BigDecimal amount) throws ArithmeticException { if (user == null) { throw new IllegalArgumentException("Economy user cannot be null"); } @@ -738,39 +681,33 @@ public class Economy { } /** - * @deprecated Use {@link Economy#hasLess(UUID, BigDecimal)} or {@link Economy#hasLess(User, BigDecimal)} - * * @param name Name of the user * @param amount The amount of money the user should not have - * * @return true, if the user has less money - * * @throws UserDoesNotExistException If a user by that name does not exists + * @deprecated Use {@link Economy#hasLess(UUID, BigDecimal)} or {@link Economy#hasLess(User, BigDecimal)} */ @Deprecated - public static boolean hasLess(String name, double amount) throws UserDoesNotExistException { + public static boolean hasLess(final String name, final double amount) throws UserDoesNotExistException { try { return hasLess(name, BigDecimal.valueOf(amount)); - } catch (ArithmeticException e) { + } catch (final ArithmeticException e) { logger.log(Level.WARNING, "Failed to compare balance of " + name + " with " + amount + ": " + e.getMessage(), e); return false; } } /** - * @deprecated Usernames can change, use {@link Economy#hasLess(UUID, BigDecimal)} or {@link Economy#hasLess(User, BigDecimal)} - * * @param name Name of the user * @param amount The amount of money the user should not have - * * @return true, if the user has less money - * * @throws UserDoesNotExistException If a user by that name does not exist * @throws ArithmeticException + * @deprecated Usernames can change, use {@link Economy#hasLess(UUID, BigDecimal)} or {@link Economy#hasLess(User, BigDecimal)} */ @Deprecated - public static boolean hasLess(String name, BigDecimal amount) throws UserDoesNotExistException, ArithmeticException { - User user = getUserByName(name); + public static boolean hasLess(final String name, final BigDecimal amount) throws UserDoesNotExistException, ArithmeticException { + final User user = getUserByName(name); if (user == null) { throw new UserDoesNotExistException(name); } @@ -780,14 +717,12 @@ public class Economy { /** * @param uuid UUID of the user * @param amount The amount of money the user should not have - * * @return true, if the user has less money - * * @throws UserDoesNotExistException If a user by that UUID does not exist * @throws ArithmeticException */ - public static boolean hasLess(UUID uuid, BigDecimal amount) throws ArithmeticException, UserDoesNotExistException { - User user = getUserByUUID(uuid); + public static boolean hasLess(final UUID uuid, final BigDecimal amount) throws ArithmeticException, UserDoesNotExistException { + final User user = getUserByUUID(uuid); if (user == null) { throw new UserDoesNotExistException(uuid); } @@ -797,12 +732,10 @@ public class Economy { /** * @param user User * @param amount The amount of money the user should not have - * * @return true, if the user has less money - * * @throws ArithmeticException */ - public static boolean hasLess(User user, BigDecimal amount) throws ArithmeticException { + public static boolean hasLess(final User user, final BigDecimal amount) throws ArithmeticException { if (user == null) { throw new IllegalArgumentException("Economy user cannot be null"); } @@ -811,18 +744,15 @@ public class Economy { /** * Test if the user has a negative balance - * - * @deprecated Usernames can change, use {@link Economy#isNegative(UUID)} or {@link Economy#isNegative(User)} * * @param name Name of the user - * * @return true, if the user has a negative balance - * * @throws UserDoesNotExistException If a user by that name does not exists + * @deprecated Usernames can change, use {@link Economy#isNegative(UUID)} or {@link Economy#isNegative(User)} */ @Deprecated - public static boolean isNegative(String name) throws UserDoesNotExistException { - User user = getUserByName(name); + public static boolean isNegative(final String name) throws UserDoesNotExistException { + final User user = getUserByName(name); if (user == null) { throw new UserDoesNotExistException(name); } @@ -831,15 +761,13 @@ public class Economy { /** * Test if the user has a negative balance - * - * @param uuid UUID of the user - * - * @return true, if the user has a negative balance * + * @param uuid UUID of the user + * @return true, if the user has a negative balance * @throws UserDoesNotExistException If a user by that UUID does not exists */ - public static boolean isNegative(UUID uuid) throws UserDoesNotExistException { - User user = getUserByUUID(uuid); + public static boolean isNegative(final UUID uuid) throws UserDoesNotExistException { + final User user = getUserByUUID(uuid); if (user == null) { throw new UserDoesNotExistException(uuid); } @@ -848,12 +776,11 @@ public class Economy { /** * Test if the user has a negative balance - * - * @param user User * + * @param user User * @return true, if the user has a negative balance */ - public static boolean isNegative(User user) { + public static boolean isNegative(final User user) { if (user == null) { throw new IllegalArgumentException("Economy user cannot be null"); } @@ -864,20 +791,19 @@ public class Economy { * Formats the amount of money like all other Essentials functions. Example: $100000 or $12345.67 * * @param amount The amount of money - * * @return Formatted money */ @Deprecated - public static String format(double amount) { + public static String format(final double amount) { try { return format(BigDecimal.valueOf(amount)); - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { logger.log(Level.WARNING, "Failed to display " + amount + ": " + e.getMessage(), e); return "NaN"; } } - public static String format(BigDecimal amount) { + public static String format(final BigDecimal amount) { if (ess == null) { throw new RuntimeException(noCallBeforeLoad); } @@ -887,14 +813,12 @@ public class Economy { /** * Test if a player exists to avoid the UserDoesNotExistException * - * @deprecated Essentials is moving away from username based economy methods. This may be removed in the future. - * * @param name Name of the user - * * @return true, if the user exists + * @deprecated Essentials is moving away from username based economy methods. This may be removed in the future. */ @Deprecated - public static boolean playerExists(String name) { + public static boolean playerExists(final String name) { return getUserByName(name) != null; } @@ -902,10 +826,9 @@ public class Economy { * Test if a player exists to avoid the UserDoesNotExistException * * @param uuid UUID of the user - * * @return true, if the user exists */ - public static boolean playerExists(UUID uuid) { + public static boolean playerExists(final UUID uuid) { return getUserByUUID(uuid) != null; } @@ -913,13 +836,11 @@ public class Economy { * Test if a player is a npc * * @param name Name of the player - * * @return true, if it's a npc - * * @throws UserDoesNotExistException */ - public static boolean isNPC(String name) throws UserDoesNotExistException { - User user = getUserByName(name); + public static boolean isNPC(final String name) throws UserDoesNotExistException { + final User user = getUserByName(name); if (user == null) { throw new UserDoesNotExistException(name); } @@ -930,11 +851,10 @@ public class Economy { * Creates dummy files for a npc, if there is no player yet with that name. * * @param name Name of the player - * * @return true, if a new npc was created */ - public static boolean createNPC(String name) { - User user = getUserByName(name); + public static boolean createNPC(final String name) { + final User user = getUserByName(name); if (user == null) { createNPCFile(name); return true; @@ -946,11 +866,10 @@ public class Economy { * Deletes a user, if it is marked as npc. * * @param name Name of the player - * * @throws UserDoesNotExistException */ - public static void removeNPC(String name) throws UserDoesNotExistException { - User user = getUserByName(name); + public static void removeNPC(final String name) throws UserDoesNotExistException { + final User user = getUserByName(name); if (user == null) { throw new UserDoesNotExistException(name); } diff --git a/Essentials/src/com/earth2me/essentials/api/IAsyncTeleport.java b/Essentials/src/com/earth2me/essentials/api/IAsyncTeleport.java index 7847986a3..f92ef47db 100644 --- a/Essentials/src/com/earth2me/essentials/api/IAsyncTeleport.java +++ b/Essentials/src/com/earth2me/essentials/api/IAsyncTeleport.java @@ -8,96 +8,95 @@ import org.bukkit.event.player.PlayerTeleportEvent; import java.util.concurrent.CompletableFuture; - public interface IAsyncTeleport { /** * Used to skip teleportPlayer delay when teleporting someone to a location or player. * - * @param loc - Where should the player end up - * @param cooldown - If cooldown should be enforced - * @param cause - The reported teleportPlayer cause - * @param future - Future which is completed with the success status of the execution + * @param loc - Where should the player end up + * @param cooldown - If cooldown should be enforced + * @param cause - The reported teleportPlayer cause + * @param future - Future which is completed with the success status of the execution */ void now(Location loc, boolean cooldown, PlayerTeleportEvent.TeleportCause cause, CompletableFuture future); /** * Used to skip teleportPlayer delay when teleporting someone to a location or player. * - * @param entity - Where should the player end up - * @param cooldown - If cooldown should be enforced - * @param cause - The reported teleportPlayer cause - * @param future - Future which is completed with the success status of the execution + * @param entity - Where should the player end up + * @param cooldown - If cooldown should be enforced + * @param cause - The reported teleportPlayer cause + * @param future - Future which is completed with the success status of the execution */ void now(Player entity, boolean cooldown, PlayerTeleportEvent.TeleportCause cause, CompletableFuture future); /** * Teleport a player to a specific location * - * @param loc - Where should the player end up - * @param chargeFor - What the user will be charged if teleportPlayer is successful - * @param cause - The reported teleportPlayer cause. - * @param future - Future which is completed with the success status of the execution + * @param loc - Where should the player end up + * @param chargeFor - What the user will be charged if teleportPlayer is successful + * @param cause - The reported teleportPlayer cause. + * @param future - Future which is completed with the success status of the execution */ void teleport(Location loc, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause, CompletableFuture future); /** * Teleport a player to a specific player * - * @param entity - Where should the player end up - * @param chargeFor - What the user will be charged if teleportPlayer is successful - * @param cause - The reported teleportPlayer cause - * @param future - Future which is completed with the success status of the execution + * @param entity - Where should the player end up + * @param chargeFor - What the user will be charged if teleportPlayer is successful + * @param cause - The reported teleportPlayer cause + * @param future - Future which is completed with the success status of the execution */ void teleport(Player entity, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause, CompletableFuture future); /** * Teleport a player to a specific location * - * @param otherUser - Which user will be teleported - * @param loc - Where should the player end up - * @param chargeFor - What the user will be charged if teleportPlayer is successful - * @param cause - The reported teleportPlayer cause - * @param future - Future which is completed with the success status of the execution + * @param otherUser - Which user will be teleported + * @param loc - Where should the player end up + * @param chargeFor - What the user will be charged if teleportPlayer is successful + * @param cause - The reported teleportPlayer cause + * @param future - Future which is completed with the success status of the execution */ void teleportPlayer(IUser otherUser, Location loc, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause, CompletableFuture future); /** * Teleport a player to a specific player * - * @param otherUser - Which user will be teleported - * @param entity - Where should the player end up - * @param chargeFor - What the user will be charged if teleportPlayer is successful - * @param cause - The reported teleportPlayer cause - * @param future - Future which is completed with the success status of the execution + * @param otherUser - Which user will be teleported + * @param entity - Where should the player end up + * @param chargeFor - What the user will be charged if teleportPlayer is successful + * @param cause - The reported teleportPlayer cause + * @param future - Future which is completed with the success status of the execution */ void teleportPlayer(IUser otherUser, Player entity, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause, CompletableFuture future); /** * Teleport wrapper used to handle tp fallback on /jail and /home * - * @param chargeFor - What the user will be charged if teleportPlayer is successful - * @param cause - The reported teleportPlayer cause - * @param future - Future which is completed with the success status of the execution + * @param chargeFor - What the user will be charged if teleportPlayer is successful + * @param cause - The reported teleportPlayer cause + * @param future - Future which is completed with the success status of the execution */ void respawn(final Trade chargeFor, PlayerTeleportEvent.TeleportCause cause, CompletableFuture future); /** * Teleport wrapper used to handle /warp teleports * - * @param otherUser - Which user will be teleported - * @param warp - The name of the warp the user will be teleported too. - * @param chargeFor - What the user will be charged if teleportPlayer is successful - * @param cause - The reported teleportPlayer cause - * @param future - Future which is completed with the success status of the execution + * @param otherUser - Which user will be teleported + * @param warp - The name of the warp the user will be teleported too. + * @param chargeFor - What the user will be charged if teleportPlayer is successful + * @param cause - The reported teleportPlayer cause + * @param future - Future which is completed with the success status of the execution */ void warp(IUser otherUser, String warp, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause, CompletableFuture future); /** * Teleport wrapper used to handle /back teleports * - * @param chargeFor - What the user will be charged if teleportPlayer is successful - * @param future - Future which is completed with the success status of the execution + * @param chargeFor - What the user will be charged if teleportPlayer is successful + * @param future - Future which is completed with the success status of the execution */ void back(Trade chargeFor, CompletableFuture future); @@ -106,17 +105,17 @@ public interface IAsyncTeleport { * are executed by a different player with this * instance of teleport as a target. * - * @param teleporter - The user performing the /back command. - * This value may be {@code null} to indicate console. - * @param chargeFor - What the {@code teleporter} will be charged if teleportPlayer is successful - * @param future - Future which is completed with the success status of the execution + * @param teleporter - The user performing the /back command. + * This value may be {@code null} to indicate console. + * @param chargeFor - What the {@code teleporter} will be charged if teleportPlayer is successful + * @param future - Future which is completed with the success status of the execution */ void back(IUser teleporter, Trade chargeFor, CompletableFuture future); /** * Teleport wrapper used to handle throwing user home after a jail sentence * - * @param future - Future which is completed with the success status of the execution + * @param future - Future which is completed with the success status of the execution */ void back(CompletableFuture future); diff --git a/Essentials/src/com/earth2me/essentials/api/II18n.java b/Essentials/src/com/earth2me/essentials/api/II18n.java index 4adb9a958..c6da43943 100644 --- a/Essentials/src/com/earth2me/essentials/api/II18n.java +++ b/Essentials/src/com/earth2me/essentials/api/II18n.java @@ -2,7 +2,6 @@ package com.earth2me.essentials.api; import java.util.Locale; - public interface II18n { /** * Gets the current locale setting diff --git a/Essentials/src/com/earth2me/essentials/api/IItemDb.java b/Essentials/src/com/earth2me/essentials/api/IItemDb.java index f61da9bbc..d9143f2d5 100644 --- a/Essentials/src/com/earth2me/essentials/api/IItemDb.java +++ b/Essentials/src/com/earth2me/essentials/api/IItemDb.java @@ -11,13 +11,12 @@ import java.util.Collection; import java.util.List; import java.util.Locale; - public interface IItemDb { /** * Create a stack from the given name with the given quantity. * - * @param name Item name to look up in the database + * @param name Item name to look up in the database * @param quantity Quantity of the item stack * @return The requested item stack * @throws Exception if the item stack cannot be created @@ -30,7 +29,7 @@ public interface IItemDb { /** * Create a stack from the given name with the maximum stack size for that material. - * + *

* Note that this will always check against resolver functions from other plugins as well. * To avoid this behaviour, use net.ess3.api.IItemDb#get(String name, boolean useResolvers). * @@ -46,7 +45,7 @@ public interface IItemDb { * @param item Item stack whose names to find * @return Comma-separated list of up to 15 item names */ - default String names(ItemStack item) { + default String names(final ItemStack item) { List nameList = nameList(item); if (nameList.size() > 15) { @@ -107,7 +106,7 @@ public interface IItemDb { * @return Updated material */ @Deprecated - default Material getFromLegacyId(int id) { + default Material getFromLegacyId(final int id) { return getFromLegacy(id, (byte) 0); } @@ -129,7 +128,7 @@ public interface IItemDb { * @param item Legacy ID in colon syntax. * @return Material if an appropriate material exists, else null. */ - default Material getFromLegacy(String item) { + default Material getFromLegacy(final String item) { final String[] split = item.split(":"); if (!NumberUtil.isInt(split[0])) return null; @@ -148,7 +147,7 @@ public interface IItemDb { * Convert legacy ID and damage value to Material. Used for conversion from item IDs to * modern names. * - * @param id Legacy ID + * @param id Legacy ID * @param damage Damage value * @return Material */ diff --git a/Essentials/src/com/earth2me/essentials/api/IJails.java b/Essentials/src/com/earth2me/essentials/api/IJails.java index b776faa19..a1e1ee4a9 100644 --- a/Essentials/src/com/earth2me/essentials/api/IJails.java +++ b/Essentials/src/com/earth2me/essentials/api/IJails.java @@ -6,15 +6,12 @@ import org.bukkit.Location; import java.util.Collection; import java.util.concurrent.CompletableFuture; - public interface IJails extends IReload { /** * Gets the location of the jail with the given name * * @param jailName The name of the jail - * * @return the location of the jail - * * @throws Exception if the jail does not exist */ Location getJail(String jailName) throws Exception; @@ -23,7 +20,6 @@ public interface IJails extends IReload { * Gets a list of jails by names * * @return a list of jails, if there are none the list will be empty - * * @throws Exception */ Collection getList() throws Exception; @@ -39,7 +35,6 @@ public interface IJails extends IReload { * Remove the jail with the given name * * @param jail the jail to remove - * * @throws Exception if the jail does not exist */ void removeJail(String jail) throws Exception; @@ -47,12 +42,10 @@ public interface IJails extends IReload { /** * Attempts to send the given user to the given jail * - * @deprecated Use {@link IJails#sendToJail(IUser, String, CompletableFuture)} - * * @param user the user to send to jail * @param jail the jail to send the user to - * * @throws Exception if the user is offline or jail does not exist + * @deprecated Use {@link IJails#sendToJail(IUser, String, CompletableFuture)} */ @Deprecated void sendToJail(IUser user, String jail) throws Exception; @@ -60,10 +53,9 @@ public interface IJails extends IReload { /** * Attempts to send the given user to the given jail * - * @param user the user to send to jail - * @param jail the jail to send the user to - * @param future Future which is completed with the success status of the execution - * + * @param user the user to send to jail + * @param jail the jail to send the user to + * @param future Future which is completed with the success status of the execution * @throws Exception if the user is offline or jail does not exist */ void sendToJail(IUser user, String jail, CompletableFuture future) throws Exception; @@ -73,7 +65,6 @@ public interface IJails extends IReload { * * @param jailName the name of the jail being set * @param loc the location of the jail being set - * * @throws Exception */ void setJail(String jailName, Location loc) throws Exception; diff --git a/Essentials/src/com/earth2me/essentials/api/IReload.java b/Essentials/src/com/earth2me/essentials/api/IReload.java index 49528e053..c2a9ed13f 100644 --- a/Essentials/src/com/earth2me/essentials/api/IReload.java +++ b/Essentials/src/com/earth2me/essentials/api/IReload.java @@ -1,6 +1,5 @@ package com.earth2me.essentials.api; - public interface IReload { void onReload(); } diff --git a/Essentials/src/com/earth2me/essentials/api/ITeleport.java b/Essentials/src/com/earth2me/essentials/api/ITeleport.java index 5993b2a8a..a80b75717 100644 --- a/Essentials/src/com/earth2me/essentials/api/ITeleport.java +++ b/Essentials/src/com/earth2me/essentials/api/ITeleport.java @@ -6,7 +6,6 @@ import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerTeleportEvent; - /** * @deprecated This API is not asynchronous. Use {@link com.earth2me.essentials.api.IAsyncTeleport IAsyncTeleport} */ @@ -17,7 +16,6 @@ public interface ITeleport { * @param loc - Where should the player end up * @param cooldown - If cooldown should be enforced * @param cause - The reported teleportPlayer cause - * * @throws Exception */ @Deprecated @@ -29,7 +27,6 @@ public interface ITeleport { * @param entity - Where should the player end up * @param cooldown - If cooldown should be enforced * @param cause - The reported teleportPlayer cause - * * @throws Exception */ @Deprecated @@ -44,7 +41,6 @@ public interface ITeleport { * @param loc - Where should the player end up * @param chargeFor - What the user will be charged if teleportPlayer is successful * @param cause - The reported teleportPlayer cause - * * @throws Exception */ @Deprecated @@ -56,7 +52,6 @@ public interface ITeleport { * @param entity - Where should the player end up * @param chargeFor - What the user will be charged if teleportPlayer is successful * @param cause - The reported teleportPlayer cause - * * @throws Exception */ @Deprecated @@ -69,7 +64,6 @@ public interface ITeleport { * @param loc - Where should the player end up * @param chargeFor - What the user will be charged if teleportPlayer is successful * @param cause - The reported teleportPlayer cause - * * @throws Exception */ @Deprecated @@ -82,7 +76,6 @@ public interface ITeleport { * @param entity - Where should the player end up * @param chargeFor - What the user will be charged if teleportPlayer is successful * @param cause - The reported teleportPlayer cause - * * @throws Exception */ @Deprecated @@ -93,7 +86,6 @@ public interface ITeleport { * * @param chargeFor - What the user will be charged if teleportPlayer is successful * @param cause - The reported teleportPlayer cause - * * @throws Exception */ @Deprecated @@ -106,7 +98,6 @@ public interface ITeleport { * @param warp - The name of the warp the user will be teleported too. * @param chargeFor - What the user will be charged if teleportPlayer is successful * @param cause - The reported teleportPlayer cause - * * @throws Exception */ @Deprecated @@ -116,7 +107,6 @@ public interface ITeleport { * Teleport wrapper used to handle /back teleports * * @param chargeFor - What the user will be charged if teleportPlayer is successful - * * @throws Exception */ @Deprecated @@ -130,7 +120,6 @@ public interface ITeleport { * @param teleporter - The user performing the /back command. * This value may be {@code null} to indicate console. * @param chargeFor - What the {@code teleporter} will be charged if teleportPlayer is successful - * * @throws Exception */ @Deprecated diff --git a/Essentials/src/com/earth2me/essentials/api/IWarps.java b/Essentials/src/com/earth2me/essentials/api/IWarps.java index 72345edc2..c5f46229e 100644 --- a/Essentials/src/com/earth2me/essentials/api/IWarps.java +++ b/Essentials/src/com/earth2me/essentials/api/IWarps.java @@ -9,15 +9,12 @@ import java.io.File; import java.util.Collection; import java.util.UUID; - public interface IWarps extends IConf { /** * Get a warp by name * * @param warp - Warp name - * * @return - Location the warp is set to - * * @throws WarpNotFoundException When the warp is not found * @throws InvalidWorldException When the world the warp is in is not found */ @@ -41,7 +38,6 @@ public interface IWarps extends IConf { * Delete a warp from the warp DB * * @param name - Name of warp - * * @throws Exception */ void removeWarp(String name) throws Exception; @@ -51,7 +47,6 @@ public interface IWarps extends IConf { * * @param name - Name of warp * @param loc - Location of warp - * * @throws Exception */ void setWarp(String name, Location loc) throws Exception; @@ -62,19 +57,18 @@ public interface IWarps extends IConf { * @param user - User of warp * @param name - Name of warp * @param loc - Location of warp - * * @throws Exception */ void setWarp(IUser user, String name, Location loc) throws Exception; - + /** * Gets Lastowner UUID - * - * @param warp - Name of warp * + * @param warp - Name of warp * @throws WarpNotFoundException */ UUID getLastOwner(String warp) throws WarpNotFoundException; + /** * Check to see if the file is empty * @@ -86,9 +80,7 @@ public interface IWarps extends IConf { * Get a warp file note: this is not yet implemented, as 3.x uses different storage methods * * @param name - name of file - * * @return - an instance of the file - * * @throws InvalidNameException - When the file is not found */ File getWarpFile(String name) throws net.ess3.api.InvalidNameException; diff --git a/Essentials/src/com/earth2me/essentials/api/InvalidNameException.java b/Essentials/src/com/earth2me/essentials/api/InvalidNameException.java index 66df7af53..0036ced55 100644 --- a/Essentials/src/com/earth2me/essentials/api/InvalidNameException.java +++ b/Essentials/src/com/earth2me/essentials/api/InvalidNameException.java @@ -1,6 +1,5 @@ package com.earth2me.essentials.api; - public class InvalidNameException extends Exception { /** * NOTE: This is not implemented yet, just here for future 3.x api support Allow serialization of the @@ -8,7 +7,7 @@ public class InvalidNameException extends Exception { */ private static final long serialVersionUID = 1485321420293663139L; - public InvalidNameException(Throwable thrwbl) { + public InvalidNameException(final Throwable thrwbl) { super(thrwbl); } } diff --git a/Essentials/src/com/earth2me/essentials/api/InvalidWorldException.java b/Essentials/src/com/earth2me/essentials/api/InvalidWorldException.java index 6e22640c9..a2b3fbe7d 100644 --- a/Essentials/src/com/earth2me/essentials/api/InvalidWorldException.java +++ b/Essentials/src/com/earth2me/essentials/api/InvalidWorldException.java @@ -2,7 +2,6 @@ package com.earth2me.essentials.api; import static com.earth2me.essentials.I18n.tl; - public class InvalidWorldException extends Exception { private final String world; diff --git a/Essentials/src/com/earth2me/essentials/api/NoLoanPermittedException.java b/Essentials/src/com/earth2me/essentials/api/NoLoanPermittedException.java index a52ad0bea..b0527a1c3 100644 --- a/Essentials/src/com/earth2me/essentials/api/NoLoanPermittedException.java +++ b/Essentials/src/com/earth2me/essentials/api/NoLoanPermittedException.java @@ -1,6 +1,5 @@ package com.earth2me.essentials.api; - public class NoLoanPermittedException extends net.ess3.api.NoLoanPermittedException { } diff --git a/Essentials/src/com/earth2me/essentials/api/UserDoesNotExistException.java b/Essentials/src/com/earth2me/essentials/api/UserDoesNotExistException.java index e3316162b..c2889dd7b 100644 --- a/Essentials/src/com/earth2me/essentials/api/UserDoesNotExistException.java +++ b/Essentials/src/com/earth2me/essentials/api/UserDoesNotExistException.java @@ -4,13 +4,12 @@ import java.util.UUID; import static com.earth2me.essentials.I18n.tl; - public class UserDoesNotExistException extends Exception { - public UserDoesNotExistException(String name) { + public UserDoesNotExistException(final String name) { super(tl("userDoesNotExist", name)); } - public UserDoesNotExistException(UUID uuid) { + public UserDoesNotExistException(final UUID uuid) { super(tl("uuidDoesNotExist", uuid.toString())); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandafk.java b/Essentials/src/com/earth2me/essentials/commands/Commandafk.java index 154bb8de0..c4f273586 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandafk.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandafk.java @@ -11,45 +11,44 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandafk extends EssentialsCommand { public Commandafk() { super("afk"); } @Override - public void run(Server server, User user, String commandLabel, String[] args) throws Exception { + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { if (args.length > 0 && user.isAuthorized("essentials.afk.others")) { User afkUser = user; // if no player found, but message specified, set command executor to target user String message; try { afkUser = getPlayer(server, user, args, 0); message = args.length > 1 ? getFinalArg(args, 1) : null; - } catch (PlayerNotFoundException e) { + } catch (final PlayerNotFoundException e) { message = getFinalArg(args, 0); } toggleAfk(user, afkUser, message); } else { - String message = args.length > 0 ? getFinalArg(args, 0) : null; + final String message = args.length > 0 ? getFinalArg(args, 0) : null; toggleAfk(user, user, message); } } @Override - public void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception { + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { if (args.length > 0) { - User afkUser = getPlayer(server, args, 0, true, false); - String message = args.length > 1 ? getFinalArg(args, 1) : null; + final User afkUser = getPlayer(server, args, 0, true, false); + final String message = args.length > 1 ? getFinalArg(args, 1) : null; toggleAfk(null, afkUser, message); } else { throw new NotEnoughArgumentsException(); } } - private void toggleAfk(User sender, User user, String message) throws Exception { + private void toggleAfk(final User sender, final User user, final String message) throws Exception { if (message != null && sender != null) { if (sender.isMuted()) { - String dateDiff = sender.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(sender.getMuteTimeout()) : null; + final String dateDiff = sender.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(sender.getMuteTimeout()) : null; if (dateDiff == null) { throw new Exception(sender.hasMuteReason() ? tl("voiceSilencedReason", sender.getMuteReason()) : tl("voiceSilenced")); } @@ -91,7 +90,7 @@ public class Commandafk extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1 && sender.isAuthorized("essentials.afk.others", ess)) { return getPlayers(server, sender); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandback.java b/Essentials/src/com/earth2me/essentials/commands/Commandback.java index 5a8bf986b..186d24c3c 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandback.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandback.java @@ -10,15 +10,14 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandback extends EssentialsCommand { public Commandback() { super("back"); } @Override - protected void run(Server server, User user, String commandLabel, String[] args) throws Exception { - CommandSource sender = user.getSource(); + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + final CommandSource sender = user.getSource(); if (args.length > 0 && user.isAuthorized("essentials.back.others")) { parseOthers(server, sender, args, commandLabel); return; @@ -28,7 +27,7 @@ public class Commandback extends EssentialsCommand { } @Override - protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception { + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { if (args.length == 0) { throw new NotEnoughArgumentsException(); } @@ -36,18 +35,18 @@ public class Commandback extends EssentialsCommand { parseOthers(server, sender, args, commandLabel); } - private void parseOthers(Server server, CommandSource sender, String[] args, String commandLabel) throws Exception { - User player = getPlayer(server, args, 0, true, false); + private void parseOthers(final Server server, final CommandSource sender, final String[] args, final String commandLabel) throws Exception { + final User player = getPlayer(server, args, 0, true, false); sender.sendMessage(tl("backOther", player.getName())); teleportBack(sender, player, commandLabel); } - private void teleportBack(CommandSource sender, User user, String commandLabel) throws Exception { + private void teleportBack(final CommandSource sender, final User user, final String commandLabel) throws Exception { if (user.getLastLocation() == null) { throw new Exception(tl("noLocationFound")); } - String lastWorldName = user.getLastLocation().getWorld().getName(); + final String lastWorldName = user.getLastLocation().getWorld().getName(); User requester = null; if (sender.isPlayer()) { @@ -65,11 +64,11 @@ public class Commandback extends EssentialsCommand { if (requester == null) { user.getAsyncTeleport().back(null, null, getNewExceptionFuture(sender, commandLabel)); } else if (!requester.equals(user)) { - Trade charge = new Trade(this.getName(), this.ess); + final Trade charge = new Trade(this.getName(), this.ess); charge.isAffordableFor(requester); user.getAsyncTeleport().back(requester, charge, getNewExceptionFuture(sender, commandLabel)); } else { - Trade charge = new Trade(this.getName(), this.ess); + final Trade charge = new Trade(this.getName(), this.ess); charge.isAffordableFor(user); user.getAsyncTeleport().back(charge, getNewExceptionFuture(sender, commandLabel)); } @@ -77,7 +76,7 @@ public class Commandback extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (user.isAuthorized("essentials.back.others") && args.length == 1) { return getPlayers(server, user); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java b/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java index 801794625..5b7b77a2e 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java @@ -6,7 +6,6 @@ import org.bukkit.Server; import static com.earth2me.essentials.I18n.tl; - public class Commandbackup extends EssentialsCommand { public Commandbackup() { super("backup"); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java b/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java index 9323c2a7e..bcf1cb72d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java @@ -10,7 +10,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandbalance extends EssentialsCommand { public Commandbalance() { super("balance"); @@ -22,7 +21,7 @@ public class Commandbalance extends EssentialsCommand { throw new NotEnoughArgumentsException(); } - User target = getPlayer(server, args, 0, false, true); + final User target = getPlayer(server, args, 0, false, true); sender.sendMessage(tl("balanceOther", target.isHidden() ? target.getName() : target.getDisplayName(), NumberUtil.displayCurrency(target.getMoney(), ess))); } @@ -39,7 +38,7 @@ public class Commandbalance extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1 && sender.isAuthorized("essentials.balance.others", ess)) { return getPlayers(server, sender); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbalancetop.java b/Essentials/src/com/earth2me/essentials/commands/Commandbalancetop.java index 1344b679f..b2cfc07b3 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbalancetop.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbalancetop.java @@ -10,22 +10,35 @@ import org.bukkit.Server; import java.math.BigDecimal; import java.text.DateFormat; -import java.util.*; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; import java.util.concurrent.locks.ReentrantReadWriteLock; import static com.earth2me.essentials.I18n.tl; - public class Commandbalancetop extends EssentialsCommand { + public static final int MINUSERS = 50; + private static final int CACHETIME = 2 * 60 * 1000; + private static final SimpleTextInput cache = new SimpleTextInput(); + private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); + private static long cacheage = 0; + public Commandbalancetop() { super("balancetop"); } - private static final int CACHETIME = 2 * 60 * 1000; - public static final int MINUSERS = 50; - private static final SimpleTextInput cache = new SimpleTextInput(); - private static long cacheage = 0; - private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); + private static void outputCache(final CommandSource sender, final int page) { + final Calendar cal = Calendar.getInstance(); + cal.setTimeInMillis(cacheage); + final DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); + sender.sendMessage(tl("balanceTop", format.format(cal.getTime()))); + new TextPager(cache).showPage(Integer.toString(page), null, "balancetop", sender); + } @Override protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { @@ -34,7 +47,7 @@ public class Commandbalancetop extends EssentialsCommand { if (args.length > 0) { try { page = Integer.parseInt(args[0]); - } catch (NumberFormatException ex) { + } catch (final NumberFormatException ex) { if (args[0].equalsIgnoreCase("force") && (!sender.isPlayer() || ess.getUser(sender.getPlayer()).isAuthorized("essentials.balancetop.force"))) { force = true; } @@ -62,20 +75,24 @@ public class Commandbalancetop extends EssentialsCommand { } - private static void outputCache(final CommandSource sender, int page) { - final Calendar cal = Calendar.getInstance(); - cal.setTimeInMillis(cacheage); - final DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); - sender.sendMessage(tl("balanceTop", format.format(cal.getTime()))); - new TextPager(cache).showPage(Integer.toString(page), null, "balancetop", sender); + @Override + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { + if (args.length == 1) { + final List options = Lists.newArrayList("1"); + if (!sender.isPlayer() || ess.getUser(sender.getPlayer()).isAuthorized("essentials.balancetop.force")) { + options.add("force"); + } + return options; + } else { + return Collections.emptyList(); + } } - private class Calculator implements Runnable { private final transient Viewer viewer; private final boolean force; - public Calculator(final Viewer viewer, final boolean force) { + Calculator(final Viewer viewer, final boolean force) { this.viewer = viewer; this.force = force; } @@ -93,7 +110,7 @@ public class Commandbalancetop extends EssentialsCommand { ess.getLogger().info("Internal economy functions disabled, aborting baltop."); } } else { - for (UUID u : ess.getUserMap().getAllUniqueUsers()) { + for (final UUID u : ess.getUserMap().getAllUniqueUsers()) { final User user = ess.getUserMap().getUser(u); if (user != null) { if (!ess.getSettings().isNpcsInBalanceRanking() && user.isNPC()) { @@ -116,7 +133,7 @@ public class Commandbalancetop extends EssentialsCommand { cache.getLines().add(tl("serverTotal", NumberUtil.displayCurrency(totalMoney, ess))); int pos = 1; - for (Map.Entry entry : sortedEntries) { + for (final Map.Entry entry : sortedEntries) { cache.getLines().add(tl("balanceTopLine", pos, entry.getKey(), NumberUtil.displayCurrency(entry.getValue(), ess))); pos++; } @@ -129,14 +146,13 @@ public class Commandbalancetop extends EssentialsCommand { } } - private class Viewer implements Runnable { private final transient CommandSource sender; private final transient int page; private final transient boolean force; private final transient String commandLabel; - public Viewer(final CommandSource sender, final String commandLabel, final int page, final boolean force) { + Viewer(final CommandSource sender, final String commandLabel, final int page, final boolean force) { this.sender = sender; this.page = page; this.force = force; @@ -157,17 +173,4 @@ public class Commandbalancetop extends EssentialsCommand { ess.runTaskAsynchronously(new Calculator(new Viewer(sender, commandLabel, page, false), force)); } } - - @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { - if (args.length == 1) { - List options = Lists.newArrayList("1"); - if (!sender.isPlayer() || ess.getUser(sender.getPlayer()).isAuthorized("essentials.balancetop.force")) { - options.add("force"); - } - return options; - } else { - return Collections.emptyList(); - } - } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandban.java b/Essentials/src/com/earth2me/essentials/commands/Commandban.java index 22dd6ff82..282f185da 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandban.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandban.java @@ -14,7 +14,6 @@ import java.util.logging.Level; import static com.earth2me.essentials.I18n.tl; - public class Commandban extends EssentialsCommand { public Commandban() { super("ban"); @@ -29,7 +28,7 @@ public class Commandban extends EssentialsCommand { User user; try { user = getPlayer(server, args, 0, true, true); - } catch (PlayerNotFoundException e) { + } catch (final PlayerNotFoundException e) { nomatch = true; user = ess.getUser(new OfflinePlayer(args[0], ess.getServer())); } @@ -42,7 +41,7 @@ public class Commandban extends EssentialsCommand { } final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME; - String banReason; + final String banReason; if (args.length > 1) { banReason = FormatUtil.replaceFormat(getFinalArg(args, 1).replace("\\n", "\n").replace("|", "\n")); } else { @@ -51,7 +50,7 @@ public class Commandban extends EssentialsCommand { ess.getServer().getBanList(BanList.Type.NAME).addBan(user.getName(), banReason, null, senderName); - String banDisplay = tl("banFormat", banReason, senderName); + final String banDisplay = tl("banFormat", banReason, senderName); user.getBase().kickPlayer(banDisplay); server.getLogger().log(Level.INFO, tl("playerBanned", senderName, user.getName(), banDisplay)); @@ -64,7 +63,7 @@ public class Commandban extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { return getPlayers(server, sender); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbanip.java b/Essentials/src/com/earth2me/essentials/commands/Commandbanip.java index 1ba6bb56e..98e1d6274 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbanip.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbanip.java @@ -14,7 +14,6 @@ import java.util.logging.Level; import static com.earth2me.essentials.I18n.tl; - public class Commandbanip extends EssentialsCommand { public Commandbanip() { super("banip"); @@ -33,9 +32,9 @@ public class Commandbanip extends EssentialsCommand { ipAddress = args[0]; } else { try { - User player = getPlayer(server, args, 0, true, true); + final User player = getPlayer(server, args, 0, true, true); ipAddress = player.getLastLoginAddress(); - } catch (PlayerNotFoundException ex) { + } catch (final PlayerNotFoundException ex) { ipAddress = args[0]; } } @@ -44,19 +43,19 @@ public class Commandbanip extends EssentialsCommand { throw new PlayerNotFoundException(); } - String banReason; + final String banReason; if (args.length > 1) { banReason = FormatUtil.replaceFormat(getFinalArg(args, 1).replace("\\n", "\n").replace("|", "\n")); } else { banReason = tl("defaultBanReason"); } - String banDisplay = tl("banFormat", banReason, senderName); + final String banDisplay = tl("banFormat", banReason, senderName); ess.getServer().getBanList(BanList.Type.IP).addBan(ipAddress, banReason, null, senderName); server.getLogger().log(Level.INFO, tl("playerBanIpAddress", senderName, ipAddress, banReason)); - for (Player player : ess.getServer().getOnlinePlayers()) { + for (final Player player : ess.getServer().getOnlinePlayers()) { if (player.getAddress().getAddress().getHostAddress().equalsIgnoreCase(ipAddress)) { player.kickPlayer(banDisplay); } @@ -66,7 +65,7 @@ public class Commandbanip extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { // TODO: Also list IP addresses? return getPlayers(server, sender); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java b/Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java index b4d5066e9..99219083a 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java @@ -12,7 +12,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandbigtree extends EssentialsCommand { public Commandbigtree() { super("bigtree"); @@ -20,7 +19,7 @@ public class Commandbigtree extends EssentialsCommand { @Override public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { - TreeType tree; + final TreeType tree; if (args.length > 0 && args[0].equalsIgnoreCase("redwood")) { tree = TreeType.TALL_REDWOOD; } else if (args.length > 0 && args[0].equalsIgnoreCase("tree")) { @@ -46,7 +45,7 @@ public class Commandbigtree extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { return Lists.newArrayList("redwood", "tree", "jungle", "darkoak"); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbook.java b/Essentials/src/com/earth2me/essentials/commands/Commandbook.java index ea2934716..f2f4ebe5e 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbook.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbook.java @@ -14,7 +14,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandbook extends EssentialsCommand { private static final Material WRITABLE_BOOK = EnumUtil.getMaterial("WRITABLE_BOOK", "BOOK_AND_QUILL"); @@ -28,7 +27,7 @@ public class Commandbook extends EssentialsCommand { final ItemStack item = user.getItemInHand(); final String player = user.getName(); if (item.getType() == Material.WRITTEN_BOOK) { - BookMeta bmeta = (BookMeta) item.getItemMeta(); + final BookMeta bmeta = (BookMeta) item.getItemMeta(); if (args.length > 1 && args[0].equalsIgnoreCase("author")) { if (user.isAuthorized("essentials.book.author") && (isAuthor(bmeta, player) || user.isAuthorized("essentials.book.others"))) { @@ -48,7 +47,7 @@ public class Commandbook extends EssentialsCommand { } } else { if (isAuthor(bmeta, player) || user.isAuthorized("essentials.book.others")) { - ItemStack newItem = new ItemStack(WRITABLE_BOOK, item.getAmount()); + final ItemStack newItem = new ItemStack(WRITABLE_BOOK, item.getAmount()); newItem.setItemMeta(bmeta); InventoryWorkaround.setItemInMainHand(user.getBase(), newItem); user.sendMessage(tl("editBookContents")); @@ -57,11 +56,11 @@ public class Commandbook extends EssentialsCommand { } } } else if (item.getType() == WRITABLE_BOOK) { - BookMeta bmeta = (BookMeta) item.getItemMeta(); + final BookMeta bmeta = (BookMeta) item.getItemMeta(); if (!user.isAuthorized("essentials.book.author")) { bmeta.setAuthor(player); } - ItemStack newItem = new ItemStack(Material.WRITTEN_BOOK, item.getAmount()); + final ItemStack newItem = new ItemStack(Material.WRITTEN_BOOK, item.getAmount()); newItem.setItemMeta(bmeta); InventoryWorkaround.setItemInMainHand(user.getBase(), newItem); user.sendMessage(tl("bookLocked")); @@ -70,16 +69,16 @@ public class Commandbook extends EssentialsCommand { } } - private boolean isAuthor(BookMeta bmeta, String player) { - String author = bmeta.getAuthor(); + private boolean isAuthor(final BookMeta bmeta, final String player) { + final String author = bmeta.getAuthor(); return author != null && author.equalsIgnoreCase(player); } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { // Right now, we aren't testing what's held in the player's hand - we could, but it's not necessarily worth it if (args.length == 1) { - List options = Lists.newArrayList("sign", "unsign"); // sign and unsign aren't real, but work + final List options = Lists.newArrayList("sign", "unsign"); // sign and unsign aren't real, but work if (user.isAuthorized("essentials.book.author")) { options.add("author"); } @@ -88,7 +87,7 @@ public class Commandbook extends EssentialsCommand { } return options; } else if (args.length == 2 && args[0].equalsIgnoreCase("author") && user.isAuthorized("essentials.book.author")) { - List options = getPlayers(server, user); + final List options = getPlayers(server, user); options.add("Herobrine"); // #EasterEgg return options; } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbreak.java b/Essentials/src/com/earth2me/essentials/commands/Commandbreak.java index 66bab8988..755711f85 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbreak.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbreak.java @@ -8,7 +8,6 @@ import org.bukkit.event.block.BlockBreakEvent; import static com.earth2me.essentials.I18n.tl; - public class Commandbreak extends EssentialsCommand { public Commandbreak() { super("break"); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbroadcast.java b/Essentials/src/com/earth2me/essentials/commands/Commandbroadcast.java index 90cb28439..73681ce90 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbroadcast.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbroadcast.java @@ -6,7 +6,6 @@ import org.bukkit.Server; import static com.earth2me.essentials.I18n.tl; - public class Commandbroadcast extends EssentialsCommand { public Commandbroadcast() { super("broadcast"); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbroadcastworld.java b/Essentials/src/com/earth2me/essentials/commands/Commandbroadcastworld.java index 3ddbcf189..b062824b4 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbroadcastworld.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbroadcastworld.java @@ -17,7 +17,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandbroadcastworld extends EssentialsCommand { public Commandbroadcastworld() { @@ -33,7 +32,7 @@ public class Commandbroadcastworld extends EssentialsCommand { World world = user.getWorld(); String message = getFinalArg(args, 0); if (args.length > 1 && ess.getSettings().isAllowWorldInBroadcastworld()) { - World argWorld = ess.getWorld(args[0]); + final World argWorld = ess.getWorld(args[0]); if (argWorld != null) { world = argWorld; message = getFinalArg(args, 1); @@ -49,7 +48,7 @@ public class Commandbroadcastworld extends EssentialsCommand { throw new NotEnoughArgumentsException("world"); } - World world = ess.getWorld(args[0]); + final World world = ess.getWorld(args[0]); if (world == null) { throw new Exception(tl("invalidWorld")); } @@ -63,15 +62,15 @@ public class Commandbroadcastworld extends EssentialsCommand { sendToWorld(world, tl("broadcast", FormatUtil.replaceFormat(message).replace("\\n", "\n"), name)); } - private void sendToWorld(World world, String message) { + private void sendToWorld(final World world, final String message) { IText broadcast = new SimpleTextInput(message); final Collection players = ess.getOnlinePlayers(); - for (Player player : players) { + for (final Player player : players) { if (player.getWorld().equals(world)) { final User user = ess.getUser(player); broadcast = new KeywordReplacer(broadcast, new CommandSource(player), ess, false); - for (String messageText : broadcast.getLines()) { + for (final String messageText : broadcast.getLines()) { user.sendMessage(messageText); } } @@ -79,10 +78,10 @@ public class Commandbroadcastworld extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1 && (!sender.isPlayer() || ess.getSettings().isAllowWorldInBroadcastworld())) { - List worlds = Lists.newArrayList(); - for (World world : server.getWorlds()) { + final List worlds = Lists.newArrayList(); + for (final World world : server.getWorlds()) { worlds.add(world.getName()); } return worlds; diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandburn.java b/Essentials/src/com/earth2me/essentials/commands/Commandburn.java index 6ab5aef7f..a9b9bf54c 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandburn.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandburn.java @@ -9,7 +9,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandburn extends EssentialsCommand { public Commandburn() { super("burn"); @@ -21,13 +20,13 @@ public class Commandburn extends EssentialsCommand { throw new NotEnoughArgumentsException(); } - User user = getPlayer(server, sender, args, 0); + final User user = getPlayer(server, sender, args, 0); user.getBase().setFireTicks(Integer.parseInt(args[1]) * 20); sender.sendMessage(tl("burnMsg", user.getDisplayName(), Integer.parseInt(args[1]))); } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { return getPlayers(server, sender); } else if (args.length == 2) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java b/Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java index ab5e18246..5a2ebda1f 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java @@ -11,35 +11,40 @@ import org.bukkit.Server; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; import static com.earth2me.essentials.I18n.tl; - public class Commandclearinventory extends EssentialsCommand { + private static final int BASE_AMOUNT = 100000; + private static final int EXTENDED_CAP = 8; + public Commandclearinventory() { super("clearinventory"); } - private static final int BASE_AMOUNT = 100000; - private static final int EXTENDED_CAP = 8; - @Override - public void run(Server server, User user, String commandLabel, String[] args) throws Exception { + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { parseCommand(server, user.getSource(), commandLabel, args, user.isAuthorized("essentials.clearinventory.others"), - user.isAuthorized("essentials.clearinventory.all") || user.isAuthorized("essentials.clearinventory.multiple")); + user.isAuthorized("essentials.clearinventory.all") || user.isAuthorized("essentials.clearinventory.multiple")); } @Override - protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception { + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { parseCommand(server, sender, commandLabel, args, true, true); } - private void parseCommand(Server server, CommandSource sender, String commandLabel, String[] args, boolean allowOthers, boolean allowAll) - throws Exception { + private void parseCommand(final Server server, final CommandSource sender, final String commandLabel, final String[] args, final boolean allowOthers, final boolean allowAll) + throws Exception { Collection players = new ArrayList<>(); - User senderUser = ess.getUser(sender.getPlayer()); + final User senderUser = ess.getUser(sender.getPlayer()); String previousClearCommand = ""; int offset = 0; @@ -64,9 +69,8 @@ public class Commandclearinventory extends EssentialsCommand { throw new PlayerNotFoundException(); } - // Confirm - String formattedCommand = formatCommand(commandLabel, args); + final String formattedCommand = formatCommand(commandLabel, args); if (senderUser != null && senderUser.isPromptingClearConfirm()) { if (!formattedCommand.equals(previousClearCommand)) { senderUser.setConfirmingClearCommand(formattedCommand); @@ -75,71 +79,48 @@ public class Commandclearinventory extends EssentialsCommand { } } - for (Player player : players) { + for (final Player player : players) { clearHandler(sender, player, args, offset, players.size() < EXTENDED_CAP); } } - private static class Item { - private final Material material; - private final short data; - - public Item(Material material, short data) { - this.material = material; - this.data = data; - } - - public Material getMaterial() { - return material; - } - - public short getData() { - return data; - } - } - - private enum ClearHandlerType { - ALL_EXCEPT_ARMOR, ALL_INCLUDING_ARMOR, SPECIFIC_ITEM - } - - protected void clearHandler(CommandSource sender, Player player, String[] args, int offset, boolean showExtended) { + protected void clearHandler(final CommandSource sender, final Player player, final String[] args, final int offset, final boolean showExtended) { ClearHandlerType type = ClearHandlerType.ALL_EXCEPT_ARMOR; final Set items = new HashSet<>(); int amount = -1; - if (args.length > (offset + 1) && NumberUtil.isInt(args[(offset + 1)])) { - amount = Integer.parseInt(args[(offset + 1)]); + if (args.length > (offset + 1) && NumberUtil.isInt(args[offset + 1])) { + amount = Integer.parseInt(args[offset + 1]); } if (args.length > offset) { if (args[offset].equalsIgnoreCase("**")) { type = ClearHandlerType.ALL_INCLUDING_ARMOR; } else if (!args[offset].equalsIgnoreCase("*")) { final String[] split = args[offset].split(","); - for (String item : split) { + for (final String item : split) { final String[] itemParts = item.split(":"); short data; try { data = Short.parseShort(itemParts[1]); - } catch (Exception e) { + } catch (final Exception e) { data = 0; } try { items.add(new Item(ess.getItemDb().get(itemParts[0]).getType(), data)); - } catch (Exception ignored) {} + } catch (final Exception ignored) { + } } type = ClearHandlerType.SPECIFIC_ITEM; } } - if (type == ClearHandlerType.ALL_EXCEPT_ARMOR) - { + if (type == ClearHandlerType.ALL_EXCEPT_ARMOR) { if (showExtended) { sender.sendMessage(tl("inventoryClearingAllItems", player.getDisplayName())); } InventoryWorkaround.clearInventoryNoArmor(player.getInventory()); InventoryWorkaround.setItemInOffHand(player, null); - } else if (type == ClearHandlerType.ALL_INCLUDING_ARMOR) - { + } else if (type == ClearHandlerType.ALL_INCLUDING_ARMOR) { if (showExtended) { sender.sendMessage(tl("inventoryClearingAllArmor", player.getDisplayName())); } @@ -147,16 +128,16 @@ public class Commandclearinventory extends EssentialsCommand { InventoryWorkaround.setItemInOffHand(player, null); player.getInventory().setArmorContents(null); } else { - for (Item item : items) { - ItemStack stack = new ItemStack(item.getMaterial()); + for (final Item item : items) { + final ItemStack stack = new ItemStack(item.getMaterial()); if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_13_0_R01)) { stack.setDurability(item.getData()); } - if (amount == -1) // amount -1 means all items will be cleared - { + // amount -1 means all items will be cleared + if (amount == -1) { stack.setAmount(BASE_AMOUNT); - ItemStack removedStack = player.getInventory().removeItem(stack).get(0); - final int removedAmount = (BASE_AMOUNT - removedStack.getAmount()); + final ItemStack removedStack = player.getInventory().removeItem(stack).get(0); + final int removedAmount = BASE_AMOUNT - removedStack.getAmount(); if (removedAmount > 0 || showExtended) { sender.sendMessage(tl("inventoryClearingStack", removedAmount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName())); } @@ -176,17 +157,17 @@ public class Commandclearinventory extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (user.isAuthorized("essentials.clearinventory.others")) { if (args.length == 1) { - List options = getPlayers(server, user); + final List options = getPlayers(server, user); if (user.isAuthorized("essentials.clearinventory.all") || user.isAuthorized("essentials.clearinventory.multiple")) { // Assume that nobody will have the 'all' permission without the 'others' permission options.add("*"); } return options; } else if (args.length == 2) { - List items = new ArrayList<>(getItems()); + final List items = new ArrayList<>(getItems()); items.add("*"); items.add("**"); return items; @@ -195,7 +176,7 @@ public class Commandclearinventory extends EssentialsCommand { } } else { if (args.length == 1) { - List items = new ArrayList<>(getItems()); + final List items = new ArrayList<>(getItems()); items.add("*"); items.add("**"); return items; @@ -206,13 +187,13 @@ public class Commandclearinventory extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { - List options = getPlayers(server, sender); + final List options = getPlayers(server, sender); options.add("*"); return options; } else if (args.length == 2) { - List items = new ArrayList<>(getItems()); + final List items = new ArrayList<>(getItems()); items.add("*"); items.add("**"); return items; @@ -221,7 +202,29 @@ public class Commandclearinventory extends EssentialsCommand { } } - private String formatCommand(String commandLabel, String[] args) { + private String formatCommand(final String commandLabel, final String[] args) { return "/" + commandLabel + " " + StringUtil.joinList(" ", args); } -} \ No newline at end of file + + private enum ClearHandlerType { + ALL_EXCEPT_ARMOR, ALL_INCLUDING_ARMOR, SPECIFIC_ITEM + } + + private static class Item { + private final Material material; + private final short data; + + Item(final Material material, final short data) { + this.material = material; + this.data = data; + } + + public Material getMaterial() { + return material; + } + + public short getData() { + return data; + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandclearinventoryconfirmtoggle.java b/Essentials/src/com/earth2me/essentials/commands/Commandclearinventoryconfirmtoggle.java index e7b3e9072..489d31ce4 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandclearinventoryconfirmtoggle.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandclearinventoryconfirmtoggle.java @@ -1,11 +1,10 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; - import com.earth2me.essentials.User; - import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; + public class Commandclearinventoryconfirmtoggle extends EssentialsCommand { public Commandclearinventoryconfirmtoggle() { @@ -13,7 +12,7 @@ public class Commandclearinventoryconfirmtoggle extends EssentialsCommand { } @Override - public void run(Server server, User user, String commandLabel, String[] args) throws Exception { + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { boolean confirmingClear = !user.isPromptingClearConfirm(); if (commandLabel.toLowerCase().endsWith("on")) { confirmingClear = true; diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandcompass.java b/Essentials/src/com/earth2me/essentials/commands/Commandcompass.java index 65525d18a..9891fbd79 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandcompass.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandcompass.java @@ -5,7 +5,6 @@ import org.bukkit.Server; import static com.earth2me.essentials.I18n.tl; - public class Commandcompass extends EssentialsCommand { public Commandcompass() { super("compass"); @@ -14,7 +13,7 @@ public class Commandcompass extends EssentialsCommand { @Override public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { final int bearing = (int) (user.getLocation().getYaw() + 180 + 360) % 360; - String dir; + final String dir; if (bearing < 23) { dir = tl("north"); } else if (bearing < 68) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandcondense.java b/Essentials/src/com/earth2me/essentials/commands/Commandcondense.java index b04477b1b..7fd64cb20 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandcondense.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandcondense.java @@ -12,18 +12,24 @@ import org.bukkit.inventory.Recipe; import org.bukkit.inventory.ShapedRecipe; import org.bukkit.inventory.ShapelessRecipe; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; import static com.earth2me.essentials.I18n.tl; - public class Commandcondense extends EssentialsCommand { + private final Map condenseList = new HashMap<>(); + public Commandcondense() { super("condense"); } - private final Map condenseList = new HashMap<>(); - @Override public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { List is = new ArrayList<>(); @@ -32,7 +38,7 @@ public class Commandcondense extends EssentialsCommand { if (args.length > 0) { is = ess.getItemDb().getMatching(user, args); } else { - for (ItemStack stack : user.getBase().getInventory().getContents()) { + for (final ItemStack stack : user.getBase().getInventory().getContents()) { if (stack == null || stack.getType() == Material.AIR) { continue; } @@ -65,7 +71,7 @@ public class Commandcondense extends EssentialsCommand { if (validateReverse) { boolean pass = false; - for (Recipe revRecipe : ess.getServer().getRecipesFor(input)) { + for (final Recipe revRecipe : ess.getServer().getRecipesFor(input)) { if (getStackOnRecipeMatch(revRecipe, result) != null) { pass = true; break; @@ -84,7 +90,7 @@ public class Commandcondense extends EssentialsCommand { } } - int output = ((amount / input.getAmount()) * result.getAmount()); + final int output = (amount / input.getAmount()) * result.getAmount(); amount -= amount % input.getAmount(); if (amount > 0) { @@ -106,7 +112,7 @@ public class Commandcondense extends EssentialsCommand { } final Iterator intr = ess.getServer().recipeIterator(); - List bestRecipes = new ArrayList<>(); + final List bestRecipes = new ArrayList<>(); while (intr.hasNext()) { final Recipe recipe = intr.next(); final Collection recipeItems = getStackOnRecipeMatch(recipe, stack); @@ -122,7 +128,7 @@ public class Commandcondense extends EssentialsCommand { if (bestRecipes.size() > 1) { bestRecipes.sort(SimpleRecipeComparator.INSTANCE); } - SimpleRecipe recipe = bestRecipes.get(0); + final SimpleRecipe recipe = bestRecipes.get(0); condenseList.put(stack, recipe); return recipe; } @@ -134,23 +140,23 @@ public class Commandcondense extends EssentialsCommand { final Collection inputList; if (recipe instanceof ShapedRecipe) { - ShapedRecipe sRecipe = (ShapedRecipe) recipe; + final ShapedRecipe sRecipe = (ShapedRecipe) recipe; if (sRecipe.getShape().length != sRecipe.getShape()[0].length()) { // Only accept square recipes return null; } inputList = sRecipe.getIngredientMap().values(); } else if (recipe instanceof ShapelessRecipe) { - ShapelessRecipe slRecipe = (ShapelessRecipe) recipe; + final ShapelessRecipe slRecipe = (ShapelessRecipe) recipe; inputList = slRecipe.getIngredientList(); } else { return null; } boolean match = true; - Iterator iter = inputList.iterator(); + final Iterator iter = inputList.iterator(); while (iter.hasNext()) { - ItemStack inputSlot = iter.next(); + final ItemStack inputSlot = iter.next(); if (inputSlot == null) { iter.remove(); continue; @@ -170,12 +176,20 @@ public class Commandcondense extends EssentialsCommand { return null; } + @Override + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { + if (args.length == 1) { + return getMatchingItems(args[0]); + } else { + return Collections.emptyList(); + } + } - private static class SimpleRecipe implements Recipe { + private static final class SimpleRecipe implements Recipe { private final ItemStack result; private final ItemStack input; - private SimpleRecipe(ItemStack result, ItemStack input) { + private SimpleRecipe(final ItemStack result, final ItemStack input) { this.result = result; this.input = input; } @@ -190,20 +204,12 @@ public class Commandcondense extends EssentialsCommand { } } - @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { - if (args.length == 1) { - return getMatchingItems(args[0]); - } else { - return Collections.emptyList(); - } - } - private static class SimpleRecipeComparator implements Comparator { private static final SimpleRecipeComparator INSTANCE = new SimpleRecipeComparator(); + @Override - public int compare(SimpleRecipe o1, SimpleRecipe o2) { + public int compare(final SimpleRecipe o1, final SimpleRecipe o2) { return Integer.compare(o2.getInput().getAmount(), o1.getInput().getAmount()); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandcreatekit.java b/Essentials/src/com/earth2me/essentials/commands/Commandcreatekit.java index 52fd4ca81..8a7e3e10d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandcreatekit.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandcreatekit.java @@ -1,14 +1,12 @@ package com.earth2me.essentials.commands; -import com.google.common.base.Charsets; -import com.google.common.io.CharStreams; -import com.google.gson.Gson; -import com.google.gson.JsonObject; - import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.DateUtil; - +import com.google.common.base.Charsets; +import com.google.common.io.CharStreams; +import com.google.gson.Gson; +import com.google.gson.JsonObject; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.configuration.ConfigurationSection; @@ -57,13 +55,13 @@ public class Commandcreatekit extends EssentialsCommand { } // Command handler will auto fail if this fails. - long delay = Long.parseLong(args[1]); - String kitname = args[0]; - ItemStack[] items = user.getBase().getInventory().getContents(); - List list = new ArrayList<>(); - for (ItemStack is : items) { + final long delay = Long.parseLong(args[1]); + final String kitname = args[0]; + final ItemStack[] items = user.getBase().getInventory().getContents(); + final List list = new ArrayList<>(); + for (final ItemStack is : items) { if (is != null && is.getType() != null && is.getType() != Material.AIR) { - String serialized = ess.getItemDb().serialize(is); + final String serialized = ess.getItemDb().serialize(is); list.add(serialized); } } @@ -72,7 +70,7 @@ public class Commandcreatekit extends EssentialsCommand { ess.getKits().addKit(kitname, list, delay); user.sendMessage(tl("createdKit", kitname, list.size(), delay)); } else { - ConfigurationSection config = new MemoryConfiguration(); + final ConfigurationSection config = new MemoryConfiguration(); config.set("kits." + kitname + ".delay", delay); config.set("kits." + kitname + ".items", list); @@ -87,28 +85,28 @@ public class Commandcreatekit extends EssentialsCommand { private void uploadPaste(final CommandSource sender, final String kitName, final long delay, final String contents) { executorService.submit(() -> { try { - HttpURLConnection connection = (HttpURLConnection) new URL(PASTE_UPLOAD_URL).openConnection(); + final HttpURLConnection connection = (HttpURLConnection) new URL(PASTE_UPLOAD_URL).openConnection(); connection.setRequestMethod("POST"); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("User-Agent", "EssentialsX plugin"); - try (OutputStream os = connection.getOutputStream()) { + try (final OutputStream os = connection.getOutputStream()) { os.write(contents.getBytes(Charsets.UTF_8)); } // Error if (connection.getResponseCode() >= 400) { sender.sendMessage(tl("createKitFailed", kitName)); - String message = CharStreams.toString(new InputStreamReader(connection.getErrorStream(), Charsets.UTF_8)); + final String message = CharStreams.toString(new InputStreamReader(connection.getErrorStream(), Charsets.UTF_8)); ess.getLogger().severe("Error creating kit: " + message); return; } // Read URL - JsonObject object = GSON.fromJson(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8), JsonObject.class); - String pasteUrl = PASTE_URL + object.get("key").getAsString(); + final JsonObject object = GSON.fromJson(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8), JsonObject.class); + final String pasteUrl = PASTE_URL + object.get("key").getAsString(); connection.disconnect(); - String separator = tl("createKitSeparator"); + final String separator = tl("createKitSeparator"); String delayFormat = "0"; if (delay > 0) { delayFormat = DateUtil.formatDateDiff(System.currentTimeMillis() + (delay * 1000)); @@ -119,7 +117,7 @@ public class Commandcreatekit extends EssentialsCommand { if (ess.getSettings().isDebug()) { ess.getLogger().info(sender.getSender().getName() + " created a kit: " + pasteUrl); } - } catch (Exception e) { + } catch (final Exception e) { sender.sendMessage(tl("createKitFailed", kitName)); e.printStackTrace(); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandcustomtext.java b/Essentials/src/com/earth2me/essentials/commands/Commandcustomtext.java index bd17a300f..9ec1fcde2 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandcustomtext.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandcustomtext.java @@ -8,7 +8,6 @@ import com.earth2me.essentials.textreader.TextPager; import com.earth2me.essentials.utils.NumberUtil; import org.bukkit.Server; - public class Commandcustomtext extends EssentialsCommand { public Commandcustomtext() { super("customtext"); @@ -24,7 +23,7 @@ public class Commandcustomtext extends EssentialsCommand { final IText output = new KeywordReplacer(input, sender, ess); final TextPager pager = new TextPager(output); String chapter = commandLabel; - String page; + final String page; if (commandLabel.equalsIgnoreCase("customtext") && args.length > 0 && !NumberUtil.isInt(commandLabel)) { chapter = args[0]; diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddelhome.java b/Essentials/src/com/earth2me/essentials/commands/Commanddelhome.java index 1a8e606b1..93e0cfdaa 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanddelhome.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanddelhome.java @@ -12,21 +12,20 @@ import java.util.Locale; import static com.earth2me.essentials.I18n.tl; - public class Commanddelhome extends EssentialsCommand { public Commanddelhome() { super("delhome"); } @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, String[] args) throws Exception { + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } User user = ess.getUser(sender.getPlayer()); - String name; - String[] expandedArg; + final String name; + final String[] expandedArg; //Allowing both formats /sethome khobbits house | /sethome khobbits:house final String[] nameParts = args[0].split(":"); @@ -55,20 +54,20 @@ public class Commanddelhome extends EssentialsCommand { @Override protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { - IUser user = sender.getUser(ess); - boolean canDelOthers = sender.isAuthorized("essentials.delhome.others", ess); + final IUser user = sender.getUser(ess); + final boolean canDelOthers = sender.isAuthorized("essentials.delhome.others", ess); if (args.length == 1) { - List homes = sender.isPlayer() ? new ArrayList<>() : user.getHomes(); + final List homes = sender.isPlayer() ? new ArrayList<>() : user.getHomes(); if (canDelOthers) { - int sepIndex = args[0].indexOf(':'); + final int sepIndex = args[0].indexOf(':'); if (sepIndex < 0) { getPlayers(server, sender).forEach(player -> homes.add(player + ":")); } else { - String namePart = args[0].substring(0, sepIndex); - User otherUser; + final String namePart = args[0].substring(0, sepIndex); + final User otherUser; try { - otherUser = getPlayer(server, new String[]{namePart}, 0, true, true); - } catch (Exception ex) { + otherUser = getPlayer(server, new String[] {namePart}, 0, true, true); + } catch (final Exception ex) { return homes; } otherUser.getHomes().forEach(home -> homes.add(namePart + ":" + home)); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java b/Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java index e35d5194a..25180ffab 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java @@ -2,11 +2,12 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; import org.bukkit.Server; + import java.util.ArrayList; import java.util.Collections; import java.util.List; -import static com.earth2me.essentials.I18n.tl; +import static com.earth2me.essentials.I18n.tl; public class Commanddeljail extends EssentialsCommand { public Commanddeljail() { @@ -32,7 +33,7 @@ public class Commanddeljail extends EssentialsCommand { if (args.length == 1) { try { return new ArrayList<>(ess.getJails().getList()); - } catch (Exception e) { + } catch (final Exception e) { return Collections.emptyList(); } } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddelkit.java b/Essentials/src/com/earth2me/essentials/commands/Commanddelkit.java index 975dc8f6a..d14280e87 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanddelkit.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanddelkit.java @@ -10,7 +10,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commanddelkit extends EssentialsCommand { public Commanddelkit() { super("delkit"); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java b/Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java index 3f759839d..df938bd5a 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java @@ -9,7 +9,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commanddelwarp extends EssentialsCommand { public Commanddelwarp() { super("delwarp"); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddepth.java b/Essentials/src/com/earth2me/essentials/commands/Commanddepth.java index 84de07e10..281970966 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanddepth.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanddepth.java @@ -5,7 +5,6 @@ import org.bukkit.Server; import static com.earth2me.essentials.I18n.tl; - public class Commanddepth extends EssentialsCommand { public Commanddepth() { super("depth"); @@ -17,7 +16,7 @@ public class Commanddepth extends EssentialsCommand { if (depth > 0) { user.sendMessage(tl("depthAboveSea", depth)); } else if (depth < 0) { - user.sendMessage(tl("depthBelowSea", (-depth))); + user.sendMessage(tl("depthBelowSea", -depth)); } else { user.sendMessage(tl("depth")); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddisposal.java b/Essentials/src/com/earth2me/essentials/commands/Commanddisposal.java index 3239b5d80..52ef3d099 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanddisposal.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanddisposal.java @@ -12,7 +12,7 @@ public class Commanddisposal extends EssentialsCommand { } @Override - protected void run(Server server, User user, String commandLabel, String[] args) throws Exception { + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { user.sendMessage(tl("openingDisposal")); user.getBase().openInventory(ess.getServer().createInventory(user.getBase(), 36, tl("disposal"))); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandeco.java b/Essentials/src/com/earth2me/essentials/commands/Commandeco.java index 10c672cbf..a619841c3 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandeco.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandeco.java @@ -16,7 +16,6 @@ import java.util.Locale; import static com.earth2me.essentials.I18n.tl; - public class Commandeco extends EssentialsLoopCommand { public Commandeco() { @@ -29,14 +28,14 @@ public class Commandeco extends EssentialsLoopCommand { throw new NotEnoughArgumentsException(); } - EcoCommands cmd; - boolean isPercent; - BigDecimal amount; + final EcoCommands cmd; + final boolean isPercent; + final BigDecimal amount; try { cmd = EcoCommands.valueOf(args[0].toUpperCase(Locale.ENGLISH)); isPercent = cmd != EcoCommands.RESET && args[2].endsWith("%"); amount = (cmd == EcoCommands.RESET) ? ess.getSettings().getStartingBalance() : new BigDecimal(args[2].replaceAll("[^0-9\\.]", "")); - } catch (Exception ex) { + } catch (final Exception ex) { throw new NotEnoughArgumentsException(ex); } @@ -61,10 +60,10 @@ public class Commandeco extends EssentialsLoopCommand { } case RESET: case SET: { - BigDecimal minBal = ess.getSettings().getMinMoney(); - BigDecimal maxBal = ess.getSettings().getMaxMoney(); - boolean underMin = (userAmount.compareTo(minBal) < 0); - boolean aboveMax = (userAmount.compareTo(maxBal) > 0); + final BigDecimal minBal = ess.getSettings().getMinMoney(); + final BigDecimal maxBal = ess.getSettings().getMaxMoney(); + final boolean underMin = userAmount.compareTo(minBal) < 0; + final boolean aboveMax = userAmount.compareTo(maxBal) > 0; player.setMoney(underMin ? minBal : aboveMax ? maxBal : userAmount, UserBalanceUpdateEvent.Cause.COMMAND_ECO); player.sendMessage(tl("setBal", NumberUtil.displayCurrency(player.getMoney(), ess))); sender.sendMessage(tl("setBalOthers", player.getDisplayName(), NumberUtil.displayCurrency(player.getMoney(), ess))); @@ -74,21 +73,16 @@ public class Commandeco extends EssentialsLoopCommand { }); } - - private enum EcoCommands { - GIVE, TAKE, SET, RESET - } - @Override - protected void updatePlayer(Server server, CommandSource sender, User user, String[] args) throws NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException { + protected void updatePlayer(final Server server, final CommandSource sender, final User user, final String[] args) throws NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException { } @Override - protected List getTabCompleteOptions(Server server, final CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { - List options = Lists.newArrayList(); - for (EcoCommands command : EcoCommands.values()) { + final List options = Lists.newArrayList(); + for (final EcoCommands command : EcoCommands.values()) { options.add(command.name().toLowerCase(Locale.ENGLISH)); } return options; @@ -104,4 +98,8 @@ public class Commandeco extends EssentialsLoopCommand { return Collections.emptyList(); } } + + private enum EcoCommands { + GIVE, TAKE, SET, RESET + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandeditsign.java b/Essentials/src/com/earth2me/essentials/commands/Commandeditsign.java index 514e800c8..f923406a3 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandeditsign.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandeditsign.java @@ -20,20 +20,20 @@ public class Commandeditsign extends EssentialsCommand { } @Override - protected void run(Server server, User user, String commandLabel, String[] args) throws Exception { + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { if (args.length == 0 || (args.length > 1 && !NumberUtil.isInt(args[1]))) { throw new NotEnoughArgumentsException(); } - Block target = user.getBase().getTargetBlock(null, 5); //5 is a good number + final Block target = user.getBase().getTargetBlock(null, 5); //5 is a good number if (!(target.getState() instanceof Sign)) { throw new Exception(tl("editsignCommandTarget")); } - Sign sign = (Sign) target.getState(); + final Sign sign = (Sign) target.getState(); try { if (args[0].equalsIgnoreCase("set") && args.length > 2) { - int line = Integer.parseInt(args[1]) - 1; - String text = FormatUtil.formatString(user, "essentials.editsign", getFinalArg(args, 2)).trim(); + final int line = Integer.parseInt(args[1]) - 1; + final String text = FormatUtil.formatString(user, "essentials.editsign", getFinalArg(args, 2)).trim(); if (ChatColor.stripColor(text).length() > 15 && !user.isAuthorized("essentials.editsign.unlimited")) { throw new Exception(tl("editsignCommandLimit")); } @@ -48,7 +48,7 @@ public class Commandeditsign extends EssentialsCommand { sign.update(); user.sendMessage(tl("editsignCommandClear")); } else { - int line = Integer.parseInt(args[1]) - 1; + final int line = Integer.parseInt(args[1]) - 1; sign.setLine(line, ""); sign.update(); user.sendMessage(tl("editsignCommandClearLine", line + 1)); @@ -56,22 +56,22 @@ public class Commandeditsign extends EssentialsCommand { } else { throw new NotEnoughArgumentsException(); } - } catch (IndexOutOfBoundsException e) { + } catch (final IndexOutOfBoundsException e) { throw new Exception(tl("editsignCommandNoLine")); } } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { return Lists.newArrayList("set", "clear"); } else if (args.length == 2) { return Lists.newArrayList("1", "2", "3", "4"); } else if (args.length == 3 && args[0].equalsIgnoreCase("set") && NumberUtil.isPositiveInt(args[1])) { - int line = Integer.parseInt(args[1]); - Block target = user.getBase().getTargetBlock(null, 5); + final int line = Integer.parseInt(args[1]); + final Block target = user.getBase().getTargetBlock(null, 5); if (target.getState() instanceof Sign && line <= 4) { - Sign sign = (Sign) target.getState(); + final Sign sign = (Sign) target.getState(); return Lists.newArrayList(FormatUtil.unformatString(user, "essentials.editsign", sign.getLine(line - 1))); } return Collections.emptyList(); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandenchant.java b/Essentials/src/com/earth2me/essentials/commands/Commandenchant.java index c4e90f365..c5fbe25ca 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandenchant.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandenchant.java @@ -11,11 +11,16 @@ import org.bukkit.Server; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; import static com.earth2me.essentials.I18n.tl; - public class Commandenchant extends EssentialsCommand { public Commandenchant() { super("enchant"); @@ -31,7 +36,7 @@ public class Commandenchant extends EssentialsCommand { if (args.length == 0) { final Set usableEnchants = new TreeSet<>(); - for (Map.Entry entry : Enchantments.entrySet()) { + for (final Map.Entry entry : Enchantments.entrySet()) { final String name = entry.getValue().getName().toLowerCase(Locale.ENGLISH); if (usableEnchants.contains(name) || (user.isAuthorized("essentials.enchantments." + name) && entry.getValue().canEnchantItem(stack))) { usableEnchants.add(entry.getKey()); @@ -44,7 +49,7 @@ public class Commandenchant extends EssentialsCommand { if (args.length > 1) { try { level = Integer.parseInt(args[1]); - } catch (NumberFormatException ex) { + } catch (final NumberFormatException ex) { throw new NotEnoughArgumentsException(); } } @@ -67,13 +72,13 @@ public class Commandenchant extends EssentialsCommand { if (args.length == 1) { return new ArrayList<>(Enchantments.keySet()); } else if (args.length == 2) { - Enchantment enchantment = Enchantments.getByName(args[0]); + final Enchantment enchantment = Enchantments.getByName(args[0]); if (enchantment == null) { return Collections.emptyList(); } - int min = enchantment.getStartLevel(); - int max = enchantment.getMaxLevel(); - List options = Lists.newArrayList(); + final int min = enchantment.getStartLevel(); + final int max = enchantment.getMaxLevel(); + final List options = Lists.newArrayList(); for (int i = min; i <= max; i++) { options.add(Integer.toString(i)); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandenderchest.java b/Essentials/src/com/earth2me/essentials/commands/Commandenderchest.java index 8c6cb6f22..478e72092 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandenderchest.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandenderchest.java @@ -24,7 +24,7 @@ public class Commandenderchest extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1 && user.isAuthorized("essentials.enderchest.others")) { return getPlayers(server, user); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java b/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java index c1a4cbf48..0b2684eb4 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java @@ -4,7 +4,11 @@ import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.EssentialsUpgrade; import com.earth2me.essentials.User; import com.earth2me.essentials.UserMap; -import com.earth2me.essentials.utils.*; +import com.earth2me.essentials.utils.DateUtil; +import com.earth2me.essentials.utils.EnumUtil; +import com.earth2me.essentials.utils.FloatUtil; +import com.earth2me.essentials.utils.NumberUtil; +import com.earth2me.essentials.utils.VersionUtil; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; @@ -16,7 +20,13 @@ import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginManager; import org.bukkit.scheduler.BukkitRunnable; -import java.util.*; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; import java.util.function.Supplier; import static com.earth2me.essentials.I18n.tl; @@ -28,15 +38,8 @@ public class Commandessentials extends EssentialsCommand { private static final Sound MOO_SOUND = EnumUtil.valueOf(Sound.class, "COW_IDLE", "ENTITY_COW_MILK"); private static final String NYAN_TUNE = "1D#,1E,2F#,,2A#,1E,1D#,1E,2F#,2B,2D#,2E,2D#,2A#,2B,,2F#,,1D#,1E,2F#,2B,2C#,2A#,2B,2C#,2E,2D#,2E,2C#,,2F#,,2G#,,1D,1D#,,1C#,1D,1C#,1B,,1B,,1C#,,1D,,1D,1C#,1B,1C#,1D#,2F#,2G#,1D#,2F#,1C#,1D#,1B,1C#,1B,1D#,,2F#,,2G#,1D#,2F#,1C#,1D#,1B,1D,1D#,1D,1C#,1B,1C#,1D,,1B,1C#,1D#,2F#,1C#,1D,1C#,1B,1C#,,1B,,1C#,,2F#,,2G#,,1D,1D#,,1C#,1D,1C#,1B,,1B,,1C#,,1D,,1D,1C#,1B,1C#,1D#,2F#,2G#,1D#,2F#,1C#,1D#,1B,1C#,1B,1D#,,2F#,,2G#,1D#,2F#,1C#,1D#,1B,1D,1D#,1D,1C#,1B,1C#,1D,,1B,1C#,1D#,2F#,1C#,1D,1C#,1B,1C#,,1B,,1B,,1B,,1F#,1G#,1B,,1F#,1G#,1B,1C#,1D#,1B,1E,1D#,1E,2F#,1B,,1B,,1F#,1G#,1B,1E,1D#,1C#,1B,,,,1F#,1B,,1F#,1G#,1B,,1F#,1G#,1B,1B,1C#,1D#,1B,1F#,1G#,1F#,1B,,1B,1A#,1B,1F#,1G#,1B,1E,1D#,1E,2F#,1B,,1A#,,1B,,1F#,1G#,1B,,1F#,1G#,1B,1C#,1D#,1B,1E,1D#,1E,2F#,1B,,1B,,1F#,1G#,1B,1F#,1E,1D#,1C#,1B,,,,1F#,1B,,1F#,1G#,1B,,1F#,1G#,1B,1B,1C#,1D#,1B,1F#,1G#,1F#,1B,,1B,1A#,1B,1F#,1G#,1B,1E,1D#,1E,2F#,1B,,1A#,,1B,,1F#,1G#,1B,,1F#,1G#,1B,1C#,1D#,1B,1E,1D#,1E,2F#,1B,,1B,,1F#,1G#,1B,1F#,1E,1D#,1C#,1B,,,,1F#,1B,,1F#,1G#,1B,,1F#,1G#,1B,1B,1C#,1D#,1B,1F#,1G#,1F#,1B,,1B,1A#,1B,1F#,1G#,1B,1E,1D#,1E,2F#,1B,,1A#,,1B,,1F#,1G#,1B,,1F#,1G#,1B,1C#,1D#,1B,1E,1D#,1E,2F#,1B,,1B,,1F#,1G#,1B,1F#,1E,1D#,1C#,1B,,,,1F#,1B,,1F#,1G#,1B,,1F#,1G#,1B,1B,1C#,1D#,1B,1F#,1G#,1F#,1B,,1B,1A#,1B,1F#,1G#,1B,1E,1D#,1E,2F#,1B,,1A#,,1B,,1F#,1G#,1B,,1F#,1G#,1B,1C#,1D#,1B,1E,1D#,1E,2F#,1B,,1B,,1F#,1G#,1B,1F#,1E,1D#,1C#,1B,,,,1F#,1B,,1F#,1G#,1B,,1F#,1G#,1B,1B,1C#,1D#,1B,1F#,1G#,1F#,1B,,1B,1A#,1B,1F#,1G#,1B,1E,1D#,1E,2F#,1B,,1B,,"; - private static final String[] CONSOLE_MOO = new String[]{" (__)", " (oo)", " /------\\/", " / | ||", " * /\\---/\\", " ~~ ~~", "....\"Have you mooed today?\"..."}; - private static final String[] PLAYER_MOO = new String[]{" (__)", " (oo)", " /------\\/", " / | | |", " * /\\---/\\", " ~~ ~~", "....\"Have you mooed today?\"..."}; - - public Commandessentials() { - super("essentials"); - } - - private transient TuneRunnable currentTune = null; - + private static final String[] CONSOLE_MOO = new String[] {" (__)", " (oo)", " /------\\/", " / | ||", " * /\\---/\\", " ~~ ~~", "....\"Have you mooed today?\"..."}; + private static final String[] PLAYER_MOO = new String[] {" (__)", " (oo)", " /------\\/", " / | | |", " * /\\---/\\", " ~~ ~~", "....\"Have you mooed today?\"..."}; private static final List versionPlugins = Arrays.asList( "Vault", // API "Reserve", // API @@ -51,7 +54,6 @@ public class Commandessentials extends EssentialsCommand { "GroupManager", // permissions (unsupported) "bPermissions" // permissions (unsupported) ); - private static final List officialPlugins = Arrays.asList( "EssentialsAntiBuild", "EssentialsChat", @@ -60,12 +62,16 @@ public class Commandessentials extends EssentialsCommand { "EssentialsSpawn", "EssentialsXMPP" ); - private static final List warnPlugins = Arrays.asList( "PermissionsEx", "GroupManager", "bPremissions" ); + private transient TuneRunnable currentTune = null; + + public Commandessentials() { + super("essentials"); + } @Override public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { @@ -73,23 +79,23 @@ public class Commandessentials extends EssentialsCommand { showUsage(sender); } - switch(args[0]) { + switch (args[0]) { // Info commands case "debug": case "verbose": runDebug(server, sender, commandLabel, args); break; - + case "ver": case "version": runVersion(server, sender, commandLabel, args); break; - + case "cmd": case "commands": runCommands(server, sender, commandLabel, args); break; - + // Data commands case "reload": runReload(server, sender, commandLabel, args); @@ -106,7 +112,7 @@ public class Commandessentials extends EssentialsCommand { case "uuidtest": runUUIDTest(server, sender, commandLabel, args); break; - + // "#EasterEgg" case "nya": case "nyan": @@ -116,7 +122,8 @@ public class Commandessentials extends EssentialsCommand { runMoo(server, sender, commandLabel, args); break; default: - showUsage(sender); + showUsage(sender); + break; } } @@ -128,7 +135,7 @@ public class Commandessentials extends EssentialsCommand { // Lists commands that are being handed over to other plugins. private void runCommands(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { final StringBuilder disabledCommands = new StringBuilder(); - for (Map.Entry entry : ess.getAlternativeCommandsHandler().disabledCommands().entrySet()) { + for (final Map.Entry entry : ess.getAlternativeCommandsHandler().disabledCommands().entrySet()) { if (disabledCommands.length() > 0) { disabledCommands.append("\n"); } @@ -177,10 +184,10 @@ public class Commandessentials extends EssentialsCommand { // Cow farts. private void runMoo(final Server server, final CommandSource sender, final String command, final String[] args) { if (args.length == 2 && args[1].equals("moo")) { - for (String s : CONSOLE_MOO) { + for (final String s : CONSOLE_MOO) { logger.info(s); } - for (Player player : ess.getOnlinePlayers()) { + for (final Player player : ess.getOnlinePlayers()) { player.sendMessage(PLAYER_MOO); player.playSound(player.getLocation(), MOO_SOUND, 1, 1.0f); } @@ -213,8 +220,8 @@ public class Commandessentials extends EssentialsCommand { final UserMap userMap = ess.getUserMap(); ess.runTaskAsynchronously(() -> { - long currTime = System.currentTimeMillis(); - for (UUID u : userMap.getAllUniqueUsers()) { + final long currTime = System.currentTimeMillis(); + for (final UUID u : userMap.getAllUniqueUsers()) { final User user = ess.getUserMap().getUser(u); if (user == null) { continue; @@ -232,10 +239,10 @@ public class Commandessentials extends EssentialsCommand { continue; } - long timeDiff = currTime - lastLog; - long milliDays = daysArg * 24L * 60L * 60L * 1000L; - int homeCount = user.getHomes().size(); - double moneyCount = user.getMoney().doubleValue(); + final long timeDiff = currTime - lastLog; + final long milliDays = daysArg * 24L * 60L * 60L * 1000L; + final int homeCount = user.getHomes().size(); + final double moneyCount = user.getMoney().doubleValue(); if ((lastLog == 0) || (timeDiff < milliDays) || (homeCount > homesArg) || (moneyCount > moneyArg)) { continue; @@ -256,7 +263,7 @@ public class Commandessentials extends EssentialsCommand { private void runUUIDConvert(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { sender.sendMessage("Starting Essentials UUID userdata conversion; this may lag the server."); - Boolean ignoreUFCache = (args.length > 2 && args[1].toLowerCase(Locale.ENGLISH).contains("ignore")); + final Boolean ignoreUFCache = args.length > 2 && args[1].toLowerCase(Locale.ENGLISH).contains("ignore"); EssentialsUpgrade.uuidFileConvert(ess, ignoreUFCache); sender.sendMessage("UUID conversion complete. Check your server log for more information."); @@ -267,22 +274,22 @@ public class Commandessentials extends EssentialsCommand { if (args.length < 2) { throw new Exception("/ uuidtest "); } - String name = args[1]; + final String name = args[1]; sender.sendMessage("Looking up UUID for " + name); UUID onlineUUID = null; - for (Player player : ess.getOnlinePlayers()) { + for (final Player player : ess.getOnlinePlayers()) { if (player.getName().equalsIgnoreCase(name)) { onlineUUID = player.getUniqueId(); break; } } - UUID essUUID = ess.getUserMap().getUser(name).getConfigUUID(); + final UUID essUUID = ess.getUserMap().getUser(name).getConfigUUID(); - org.bukkit.OfflinePlayer player = ess.getServer().getOfflinePlayer(name); - UUID bukkituuid = player.getUniqueId(); + final org.bukkit.OfflinePlayer player = ess.getServer().getOfflinePlayer(name); + final UUID bukkituuid = player.getUniqueId(); sender.sendMessage("Bukkit Lookup: " + bukkituuid.toString()); if (onlineUUID != null && onlineUUID != bukkituuid) { @@ -293,10 +300,10 @@ public class Commandessentials extends EssentialsCommand { sender.sendMessage("Essentials config: " + essUUID.toString()); } - UUID npcuuid = UUID.nameUUIDFromBytes(("NPC:" + name).getBytes(Charsets.UTF_8)); + final UUID npcuuid = UUID.nameUUIDFromBytes(("NPC:" + name).getBytes(Charsets.UTF_8)); sender.sendMessage("NPC UUID: " + npcuuid.toString()); - UUID offlineuuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)); + final UUID offlineuuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)); sender.sendMessage("Offline Mode UUID: " + offlineuuid.toString()); } @@ -314,10 +321,10 @@ public class Commandessentials extends EssentialsCommand { sender.sendMessage(tl(isServerSupported ? "versionOutputFine" : "versionOutputWarn", "Server", server.getBukkitVersion() + " " + server.getVersion())); sender.sendMessage(tl("versionOutputFine", "EssentialsX", essVer)); - for (Plugin plugin : pm.getPlugins()) { + for (final Plugin plugin : pm.getPlugins()) { final PluginDescriptionFile desc = plugin.getDescription(); String name = desc.getName(); - String version = desc.getVersion(); + final String version = desc.getVersion(); if (name.startsWith("Essentials") && !name.equalsIgnoreCase("Essentials")) { if (officialPlugins.contains(name)) { @@ -367,7 +374,7 @@ public class Commandessentials extends EssentialsCommand { @Override protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { - List options = Lists.newArrayList(); + final List options = Lists.newArrayList(); options.add("debug"); options.add("commands"); options.add("version"); @@ -409,7 +416,7 @@ public class Commandessentials extends EssentialsCommand { return Collections.emptyList(); } - + private static class TuneRunnable extends BukkitRunnable { private static final Map noteMap = ImmutableMap.builder() .put("1F#", 0.5f) @@ -460,7 +467,7 @@ public class Commandessentials extends EssentialsCommand { return; } - for (Player onlinePlayer : players.get()) { + for (final Player onlinePlayer : players.get()) { onlinePlayer.playSound(onlinePlayer.getLocation(), sound, 1, noteMap.get(note)); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandexp.java b/Essentials/src/com/earth2me/essentials/commands/Commandexp.java index 0c14e71f9..fdf93da62 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandexp.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandexp.java @@ -15,7 +15,6 @@ import java.util.Locale; import static com.earth2me.essentials.I18n.tl; - public class Commandexp extends EssentialsLoopCommand { public Commandexp() { super("exp"); @@ -23,7 +22,7 @@ public class Commandexp extends EssentialsLoopCommand { @Override public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { - IUser user = sender.getUser(ess); + final IUser user = sender.getUser(ess); if (args.length == 0 || (args.length < 2 && user == null)) { if (user == null) { throw new NotEnoughArgumentsException(); @@ -32,10 +31,10 @@ public class Commandexp extends EssentialsLoopCommand { return; } - ExpCommands cmd; + final ExpCommands cmd; try { cmd = ExpCommands.valueOf(args[0].toUpperCase(Locale.ENGLISH)); - } catch (Exception ex) { + } catch (final Exception ex) { throw new NotEnoughArgumentsException(ex); } @@ -47,7 +46,7 @@ public class Commandexp extends EssentialsLoopCommand { switch (cmd) { case SET: { if (args.length == 3 && cmd.hasOtherPermission(user)) { - loopOnlinePlayersConsumer(server,sender, false, true, args[1], player -> setExp(sender, player, args[2], false)); + loopOnlinePlayersConsumer(server, sender, false, true, args[1], player -> setExp(sender, player, args[2], false)); } else if (args.length == 2 && user != null) { setExp(sender, user, args[1], false); } else { @@ -99,32 +98,6 @@ public class Commandexp extends EssentialsLoopCommand { throw new NotEnoughArgumentsException(); //Should never happen but in the impossible chance it does... } - private enum ExpCommands { - SET, - GIVE, - TAKE, - RESET, - SHOW(false); - - private final boolean permCheck; - - ExpCommands() { - permCheck = true; - } - - ExpCommands(boolean perm) { - permCheck = perm; - } - - boolean hasPermission(IUser user) { - return user == null || !permCheck || user.isAuthorized("essentials.exp." + name().toLowerCase(Locale.ENGLISH)); - } - - boolean hasOtherPermission(IUser user) { - return user == null || user.isAuthorized("essentials.exp." + name().toLowerCase(Locale.ENGLISH) + ".others"); - } - } - private void showExp(final CommandSource sender, final IUser target) { sender.sendMessage(tl("exp", target.getDisplayName(), SetExpFix.getTotalExperience(target.getBase()), target.getBase().getLevel(), SetExpFix.getExpUntilNextLevel(target.getBase()))); } @@ -162,14 +135,14 @@ public class Commandexp extends EssentialsLoopCommand { } @Override - protected void updatePlayer(Server server, CommandSource sender, User user, String[] args) { + protected void updatePlayer(final Server server, final CommandSource sender, final User user, final String[] args) { } @Override protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { - List options = Lists.newArrayList("show"); - for (ExpCommands cmd : ExpCommands.values()) { + final List options = Lists.newArrayList("show"); + for (final ExpCommands cmd : ExpCommands.values()) { if (cmd.hasPermission(user)) { options.add(cmd.name().toLowerCase(Locale.ENGLISH)); } @@ -177,7 +150,7 @@ public class Commandexp extends EssentialsLoopCommand { return options; } else if (args.length == 2) { if ((args[0].equalsIgnoreCase("set") && user.isAuthorized("essentials.exp.set")) || (args[0].equalsIgnoreCase("give") && user.isAuthorized("essentials.exp.give")) || (args[0].equalsIgnoreCase("take") && user.isAuthorized("essentials.exp.take"))) { - String levellessArg = args[1].toLowerCase(Locale.ENGLISH).replaceAll("l", ""); + final String levellessArg = args[1].toLowerCase(Locale.ENGLISH).replaceAll("l", ""); if (NumberUtil.isInt(levellessArg)) { return Lists.newArrayList(levellessArg + "l"); } @@ -186,7 +159,7 @@ public class Commandexp extends EssentialsLoopCommand { return getPlayers(server, user); } } else if (args.length == 3 && !(args[0].equalsIgnoreCase("show") || args[0].equalsIgnoreCase("reset"))) { - String levellessArg = args[2].toLowerCase(Locale.ENGLISH).replaceAll("l", ""); + final String levellessArg = args[2].toLowerCase(Locale.ENGLISH).replaceAll("l", ""); if (NumberUtil.isInt(levellessArg)) { return Lists.newArrayList(levellessArg + "l"); } @@ -197,14 +170,14 @@ public class Commandexp extends EssentialsLoopCommand { @Override protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { - List list = new ArrayList<>(); - for (ExpCommands cmd : ExpCommands.values()) { + final List list = new ArrayList<>(); + for (final ExpCommands cmd : ExpCommands.values()) { list.add(cmd.name().toLowerCase(Locale.ENGLISH)); } return list; } else if (args.length == 2) { if (args[0].equalsIgnoreCase("set") || args[0].equalsIgnoreCase("give")) { - String levellessArg = args[1].toLowerCase(Locale.ENGLISH).replace("l", ""); + final String levellessArg = args[1].toLowerCase(Locale.ENGLISH).replace("l", ""); if (NumberUtil.isInt(levellessArg)) { return Lists.newArrayList(levellessArg, args[1] + "l"); } else { @@ -219,4 +192,30 @@ public class Commandexp extends EssentialsLoopCommand { return Collections.emptyList(); } } + + private enum ExpCommands { + SET, + GIVE, + TAKE, + RESET, + SHOW(false); + + private final boolean permCheck; + + ExpCommands() { + permCheck = true; + } + + ExpCommands(final boolean perm) { + permCheck = perm; + } + + boolean hasPermission(final IUser user) { + return user == null || !permCheck || user.isAuthorized("essentials.exp." + name().toLowerCase(Locale.ENGLISH)); + } + + boolean hasOtherPermission(final IUser user) { + return user == null || user.isAuthorized("essentials.exp." + name().toLowerCase(Locale.ENGLISH) + ".others"); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandext.java b/Essentials/src/com/earth2me/essentials/commands/Commandext.java index 7baf48475..9f9a54c16 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandext.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandext.java @@ -10,7 +10,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandext extends EssentialsLoopCommand { public Commandext() { super("ext"); @@ -47,7 +46,7 @@ public class Commandext extends EssentialsLoopCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { return getPlayers(server, sender); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandfeed.java b/Essentials/src/com/earth2me/essentials/commands/Commandfeed.java index 8f868a19d..ca4b5e0e1 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandfeed.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandfeed.java @@ -11,7 +11,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandfeed extends EssentialsLoopCommand { public Commandfeed() { super("feed"); @@ -46,7 +45,7 @@ public class Commandfeed extends EssentialsLoopCommand { try { feedPlayer(player.getBase()); sender.sendMessage(tl("feedOther", player.getDisplayName())); - } catch (QuietAbortException e) { + } catch (final QuietAbortException e) { //Handle Quietly } } @@ -66,7 +65,7 @@ public class Commandfeed extends EssentialsLoopCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1 && sender.isAuthorized("essentials.feed.others", ess)) { return getPlayers(server, sender); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandfireball.java b/Essentials/src/com/earth2me/essentials/commands/Commandfireball.java index 1e548dfdb..c506b3ecb 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandfireball.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandfireball.java @@ -6,7 +6,19 @@ import com.earth2me.essentials.utils.VersionUtil; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.bukkit.Server; -import org.bukkit.entity.*; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.DragonFireball; +import org.bukkit.entity.Egg; +import org.bukkit.entity.Fireball; +import org.bukkit.entity.LargeFireball; +import org.bukkit.entity.LingeringPotion; +import org.bukkit.entity.Projectile; +import org.bukkit.entity.SmallFireball; +import org.bukkit.entity.Snowball; +import org.bukkit.entity.SplashPotion; +import org.bukkit.entity.ThrownExpBottle; +import org.bukkit.entity.Trident; +import org.bukkit.entity.WitherSkull; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.util.Vector; @@ -24,20 +36,20 @@ public class Commandfireball extends EssentialsCommand { private static final Map> types; static { - ImmutableMap.Builder> builder = ImmutableMap.>builder() - .put("fireball", Fireball.class) - .put("small", SmallFireball.class) - .put("large", LargeFireball.class) - .put("arrow", Arrow.class) - .put("skull", WitherSkull.class) - .put("egg", Egg.class) - .put("snowball", Snowball.class) - .put("expbottle", ThrownExpBottle.class); + final ImmutableMap.Builder> builder = ImmutableMap.>builder() + .put("fireball", Fireball.class) + .put("small", SmallFireball.class) + .put("large", LargeFireball.class) + .put("arrow", Arrow.class) + .put("skull", WitherSkull.class) + .put("egg", Egg.class) + .put("snowball", Snowball.class) + .put("expbottle", ThrownExpBottle.class); if (VersionUtil.getServerBukkitVersion().isHigherThanOrEqualTo(VersionUtil.v1_9_R01)) { builder.put("dragon", DragonFireball.class) - .put("splashpotion", SplashPotion.class) - .put("lingeringpotion", LingeringPotion.class); + .put("splashpotion", SplashPotion.class) + .put("lingeringpotion", LingeringPotion.class); } if (VersionUtil.getServerBukkitVersion().isHigherThanOrEqualTo(VersionUtil.v1_13_0_R01)) { @@ -53,15 +65,15 @@ public class Commandfireball extends EssentialsCommand { @Override protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { - String type = args.length > 0 && types.containsKey(args[0]) ? args[0] : "fireball"; + final String type = args.length > 0 && types.containsKey(args[0]) ? args[0] : "fireball"; double speed = 2; - boolean ride = args.length > 2 && args[2].equalsIgnoreCase("ride") && user.isAuthorized("essentials.fireball.ride"); + final boolean ride = args.length > 2 && args[2].equalsIgnoreCase("ride") && user.isAuthorized("essentials.fireball.ride"); if (args.length > 1) { try { speed = FloatUtil.parseDouble(args[1]); speed = Double.max(0, Double.min(speed, ess.getSettings().getMaxProjectileSpeed())); - } catch (Exception ignored) { + } catch (final Exception ignored) { } } @@ -70,7 +82,7 @@ public class Commandfireball extends EssentialsCommand { } final Vector direction = user.getBase().getEyeLocation().getDirection().multiply(speed); - Projectile projectile = user.getWorld().spawn(user.getBase().getEyeLocation().add(direction.getX(), direction.getY(), direction.getZ()), types.get(type)); + final Projectile projectile = user.getWorld().spawn(user.getBase().getEyeLocation().add(direction.getX(), direction.getY(), direction.getZ()), types.get(type)); projectile.setShooter(user.getBase()); projectile.setVelocity(direction); projectile.setMetadata(FIREBALL_META_KEY, new FixedMetadataValue(ess, true)); @@ -84,8 +96,8 @@ public class Commandfireball extends EssentialsCommand { protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { return types.keySet().stream() - .filter(type -> user.isAuthorized("essentials.fireball." + type)) - .collect(Collectors.toList()); + .filter(type -> user.isAuthorized("essentials.fireball." + type)) + .collect(Collectors.toList()); } else if (args.length == 2) { return Lists.newArrayList("1", "2", "3", "4", "5"); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandfirework.java b/Essentials/src/com/earth2me/essentials/commands/Commandfirework.java index 198b896e0..2c4bef3fa 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandfirework.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandfirework.java @@ -53,20 +53,20 @@ public class Commandfirework extends EssentialsCommand { } if (args[0].equalsIgnoreCase("clear")) { - FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta(); + final FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta(); fmeta.clearEffects(); stack.setItemMeta(fmeta); user.sendMessage(tl("fireworkEffectsCleared")); - } else if (args.length > 1 && (args[0].equalsIgnoreCase("power") || (args[0].equalsIgnoreCase("p")))) { - FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta(); + } else if (args.length > 1 && (args[0].equalsIgnoreCase("power") || args[0].equalsIgnoreCase("p"))) { + final FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta(); try { - int power = Integer.parseInt(args[1]); + final int power = Integer.parseInt(args[1]); fmeta.setPower(power > 3 ? 4 : power); - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { throw new Exception(tl("invalidFireworkFormat", args[1], args[0])); } stack.setItemMeta(fmeta); - } else if ((args[0].equalsIgnoreCase("fire") || (args[0].equalsIgnoreCase("f"))) && user.isAuthorized("essentials.firework.fire")) { + } else if ((args[0].equalsIgnoreCase("fire") || args[0].equalsIgnoreCase("f")) && user.isAuthorized("essentials.firework.fire")) { int amount = 1; boolean direction = false; if (args.length > 1) { @@ -82,8 +82,8 @@ public class Commandfirework extends EssentialsCommand { } } for (int i = 0; i < amount; i++) { - Firework firework = (Firework) user.getWorld().spawnEntity(user.getLocation(), EntityType.FIREWORK); - FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta(); + final Firework firework = (Firework) user.getWorld().spawnEntity(user.getLocation(), EntityType.FIREWORK); + final FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta(); if (direction) { final Vector vector = user.getBase().getEyeLocation().getDirection().multiply(0.070); if (fmeta.getPower() > 1) { @@ -95,18 +95,18 @@ public class Commandfirework extends EssentialsCommand { } } else { final MetaItemStack mStack = new MetaItemStack(stack); - for (String arg : args) { + for (final String arg : args) { try { mStack.addFireworkMeta(user.getSource(), true, arg, ess); - } catch (Exception e) { + } catch (final Exception e) { user.sendMessage(tl("fireworkSyntax")); throw e; } } if (mStack.isValidFirework()) { - FireworkMeta fmeta = (FireworkMeta) mStack.getItemStack().getItemMeta(); - FireworkEffect effect = mStack.getFireworkBuilder().build(); + final FireworkMeta fmeta = (FireworkMeta) mStack.getItemStack().getItemMeta(); + final FireworkEffect effect = mStack.getFireworkBuilder().build(); if (fmeta.getEffects().size() > 0 && !user.isAuthorized("essentials.firework.multiple")) { throw new Exception(tl("multipleCharges")); } @@ -120,18 +120,18 @@ public class Commandfirework extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { // Note: this enforces an order of color fade shape effect, which the actual command doesn't have. But that's fine. if (args.length == 1) { - List options = Lists.newArrayList(); + final List options = Lists.newArrayList(); if (args[0].startsWith("color:")) { - String prefix; + final String prefix; if (args[0].contains(",")) { prefix = args[0].substring(0, args[0].lastIndexOf(',') + 1); } else { prefix = "color:"; } - for (DyeColor color : DyeColor.values()) { + for (final DyeColor color : DyeColor.values()) { options.add(prefix + color.name().toLowerCase() + ","); } return options; @@ -149,17 +149,17 @@ public class Commandfirework extends EssentialsCommand { } else if (args[0].equals("fire")) { return Lists.newArrayList("1"); } else if (args[0].startsWith("color:")) { - List options = Lists.newArrayList(); + final List options = Lists.newArrayList(); if (!args[1].startsWith("fade:")) { args[1] = "fade:"; } - String prefix; + final String prefix; if (args[1].contains(",")) { prefix = args[1].substring(0, args[1].lastIndexOf(',') + 1); } else { prefix = "fade:"; } - for (DyeColor color : DyeColor.values()) { + for (final DyeColor color : DyeColor.values()) { options.add(prefix + color.name().toLowerCase() + ","); } return options; diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandfly.java b/Essentials/src/com/earth2me/essentials/commands/Commandfly.java index f1cb5b661..e4303c217 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandfly.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandfly.java @@ -2,8 +2,8 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.User; -import org.bukkit.Server; import net.ess3.api.events.FlyStatusChangeEvent; +import org.bukkit.Server; import static com.earth2me.essentials.I18n.tl; @@ -23,14 +23,14 @@ public class Commandfly extends EssentialsToggleCommand { } @Override - void togglePlayer(CommandSource sender, User user, Boolean enabled) { + void togglePlayer(final CommandSource sender, final User user, Boolean enabled) { if (enabled == null) { enabled = !user.getBase().getAllowFlight(); } - FlyStatusChangeEvent event = new FlyStatusChangeEvent(user, sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null, enabled); + final FlyStatusChangeEvent event = new FlyStatusChangeEvent(user, sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null, enabled); ess.getServer().getPluginManager().callEvent(event); - + if (!event.isCancelled()) { user.getBase().setFallDistance(0f); user.getBase().setAllowFlight(enabled); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgamemode.java b/Essentials/src/com/earth2me/essentials/commands/Commandgamemode.java index fa9f07476..112b2a202 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgamemode.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgamemode.java @@ -13,8 +13,9 @@ import java.util.Locale; import static com.earth2me.essentials.I18n.tl; - public class Commandgamemode extends EssentialsLoopCommand { + private final List STANDARD_OPTIONS = ImmutableList.of("creative", "survival", "adventure", "spectator", "toggle"); + public Commandgamemode() { super("gamemode"); } @@ -42,7 +43,7 @@ public class Commandgamemode extends EssentialsLoopCommand { } else { try { gameMode = matchGameMode(args[0].toLowerCase(Locale.ENGLISH)); - } catch (NotEnoughArgumentsException e) { + } catch (final NotEnoughArgumentsException e) { if (user.isAuthorized("essentials.gamemode.others")) { loopOnlinePlayersConsumer(server, user.getSource(), false, true, args[0], player -> setUserGamemode(user.getSource(), matchGameMode(commandLabel), player)); return; @@ -79,7 +80,7 @@ public class Commandgamemode extends EssentialsLoopCommand { } // essentials.gamemode will let them change to any but essentials.gamemode.survival would only let them change to survival. - private boolean isProhibitedChange(IUser user, GameMode to) { + private boolean isProhibitedChange(final IUser user, final GameMode to) { return user != null && !user.isAuthorized("essentials.gamemode.all") && !user.isAuthorized("essentials.gamemode." + to.name().toLowerCase()); } @@ -100,7 +101,6 @@ public class Commandgamemode extends EssentialsLoopCommand { return mode; } - private final List STANDARD_OPTIONS = ImmutableList.of("creative", "survival", "adventure", "spectator", "toggle"); @Override protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { @@ -108,7 +108,7 @@ public class Commandgamemode extends EssentialsLoopCommand { // Direct command? Don't ask for the mode matchGameMode(commandLabel); return getPlayers(server, sender); - } catch (NotEnoughArgumentsException e) { + } catch (final NotEnoughArgumentsException e) { return STANDARD_OPTIONS; } } else if (args.length == 2) { @@ -125,7 +125,7 @@ public class Commandgamemode extends EssentialsLoopCommand { // Direct command? matchGameMode(commandLabel); isDirectGamemodeCommand = true; - } catch (NotEnoughArgumentsException ex) { + } catch (final NotEnoughArgumentsException ex) { isDirectGamemodeCommand = false; } if (args.length == 1) { @@ -142,7 +142,7 @@ public class Commandgamemode extends EssentialsLoopCommand { } @Override - protected void updatePlayer(Server server, CommandSource sender, User user, String[] args) { + protected void updatePlayer(final Server server, final CommandSource sender, final User user, final String[] args) { } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgc.java b/Essentials/src/com/earth2me/essentials/commands/Commandgc.java index 1d79213d1..4a9d1cbb0 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgc.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgc.java @@ -3,7 +3,11 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.utils.DateUtil; import com.earth2me.essentials.utils.NumberUtil; -import org.bukkit.*; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Chunk; +import org.bukkit.Server; +import org.bukkit.World; import java.lang.management.ManagementFactory; import java.util.List; @@ -11,7 +15,6 @@ import java.util.logging.Level; import static com.earth2me.essentials.I18n.tl; - public class Commandgc extends EssentialsCommand { public Commandgc() { super("gc"); @@ -19,8 +22,8 @@ public class Commandgc extends EssentialsCommand { @Override protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { - double tps = ess.getTimer().getAverageTPS(); - ChatColor color; + final double tps = ess.getTimer().getAverageTPS(); + final ChatColor color; if (tps >= 18.0) { color = ChatColor.GREEN; } else if (tps >= 15.0) { @@ -31,12 +34,12 @@ public class Commandgc extends EssentialsCommand { sender.sendMessage(tl("uptime", DateUtil.formatDateDiff(ManagementFactory.getRuntimeMXBean().getStartTime()))); sender.sendMessage(tl("tps", "" + color + NumberUtil.formatDouble(tps))); - sender.sendMessage(tl("gcmax", (Runtime.getRuntime().maxMemory() / 1024 / 1024))); - sender.sendMessage(tl("gctotal", (Runtime.getRuntime().totalMemory() / 1024 / 1024))); - sender.sendMessage(tl("gcfree", (Runtime.getRuntime().freeMemory() / 1024 / 1024))); + sender.sendMessage(tl("gcmax", Runtime.getRuntime().maxMemory() / 1024 / 1024)); + sender.sendMessage(tl("gctotal", Runtime.getRuntime().totalMemory() / 1024 / 1024)); + sender.sendMessage(tl("gcfree", Runtime.getRuntime().freeMemory() / 1024 / 1024)); - List worlds = server.getWorlds(); - for (World w : worlds) { + final List worlds = server.getWorlds(); + for (final World w : worlds) { String worldType = "World"; switch (w.getEnvironment()) { case NETHER: @@ -50,10 +53,10 @@ public class Commandgc extends EssentialsCommand { int tileEntities = 0; try { - for (Chunk chunk : w.getLoadedChunks()) { + for (final Chunk chunk : w.getLoadedChunks()) { tileEntities += chunk.getTileEntities().length; } - } catch (java.lang.ClassCastException ex) { + } catch (final java.lang.ClassCastException ex) { Bukkit.getLogger().log(Level.SEVERE, "Corrupted chunk data on world " + w, ex); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java b/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java index 2bb961a40..98676933b 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java @@ -10,7 +10,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandgetpos extends EssentialsCommand { public Commandgetpos() { super("getpos"); @@ -48,7 +47,7 @@ public class Commandgetpos extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1 && sender.isAuthorized("essentials.getpos.others", ess)) { return getPlayers(server, sender); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgive.java b/Essentials/src/com/earth2me/essentials/commands/Commandgive.java index 8833ac0ff..58310a1a2 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgive.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgive.java @@ -18,7 +18,6 @@ import java.util.Map; import static com.earth2me.essentials.I18n.tl; - public class Commandgive extends EssentialsLoopCommand { public Commandgive() { super("give"); @@ -48,11 +47,11 @@ public class Commandgive extends EssentialsLoopCommand { } else if (ess.getSettings().getOversizedStackSize() > 0 && sender.isAuthorized("essentials.oversizedstacks", ess)) { stack.setAmount(ess.getSettings().getOversizedStackSize()); } - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { throw new NotEnoughArgumentsException(); } - MetaItemStack metaStack = new MetaItemStack(stack); + final MetaItemStack metaStack = new MetaItemStack(stack); if (!metaStack.canSpawn(ess)) { throw new Exception(tl("unableToSpawnItem", itemname)); } @@ -63,7 +62,7 @@ public class Commandgive extends EssentialsLoopCommand { allowUnsafe = false; } - int metaStart = NumberUtil.isInt(args[3]) ? 4 : 3; + final int metaStart = NumberUtil.isInt(args[3]) ? 4 : 3; if (args.length > metaStart) { metaStack.parseStringMeta(sender, allowUnsafe, args, metaStart, ess); @@ -77,11 +76,11 @@ public class Commandgive extends EssentialsLoopCommand { } final String itemName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' '); - boolean isDropItemsIfFull = ess.getSettings().isDropItemsIfFull(); + final boolean isDropItemsIfFull = ess.getSettings().isDropItemsIfFull(); final ItemStack finalStack = stack; loopOnlinePlayersConsumer(server, sender, false, true, args[0], player -> { sender.sendMessage(tl("giveSpawn", finalStack.getAmount(), itemName, player.getDisplayName())); - Map leftovers; + final Map leftovers; if (player.isAuthorized("essentials.oversizedstacks")) { leftovers = InventoryWorkaround.addOversizedItems(player.getBase().getInventory(), ess.getSettings().getOversizedStackSize(), finalStack); @@ -89,9 +88,9 @@ public class Commandgive extends EssentialsLoopCommand { leftovers = InventoryWorkaround.addItems(player.getBase().getInventory(), finalStack); } - for (ItemStack item : leftovers.values()) { + for (final ItemStack item : leftovers.values()) { if (isDropItemsIfFull) { - World w = player.getWorld(); + final World w = player.getWorld(); w.dropItemNaturally(player.getLocation(), item); } else { sender.sendMessage(tl("giveSpawnFailure", item.getAmount(), itemName, player.getDisplayName())); @@ -109,7 +108,7 @@ public class Commandgive extends EssentialsLoopCommand { } else if (args.length == 2) { return getItems(); } else if (args.length == 3) { - return Lists.newArrayList("1", "64"); // TODO: get actual max size + return Lists.newArrayList("1", "64"); // TODO: get actual max size } else if (args.length == 4) { return Lists.newArrayList("0"); } else { @@ -118,7 +117,7 @@ public class Commandgive extends EssentialsLoopCommand { } @Override - protected void updatePlayer(Server server, CommandSource sender, User user, String[] args) { + protected void updatePlayer(final Server server, final CommandSource sender, final User user, final String[] args) { } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgod.java b/Essentials/src/com/earth2me/essentials/commands/Commandgod.java index 63b670b6e..1ea09d838 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgod.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgod.java @@ -7,7 +7,6 @@ import org.bukkit.Server; import static com.earth2me.essentials.I18n.tl; - public class Commandgod extends EssentialsToggleCommand { public Commandgod() { super("god", "essentials.god.others"); @@ -24,7 +23,7 @@ public class Commandgod extends EssentialsToggleCommand { } @Override - void togglePlayer(CommandSource sender, User user, Boolean enabled) { + void togglePlayer(final CommandSource sender, final User user, Boolean enabled) { if (enabled == null) { enabled = !user.isGodModeEnabled(); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandhat.java b/Essentials/src/com/earth2me/essentials/commands/Commandhat.java index 43b14f173..9799694bd 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandhat.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandhat.java @@ -19,30 +19,29 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandhat extends EssentialsCommand { - public Commandhat() { - super("hat"); - } - /** * The prefix for hat prevention commands */ private static final String PERM_PREFIX = "essentials.hat.prevent-type."; + public Commandhat() { + super("hat"); + } + /** * Register permissions used by this command. * * @param toRegister The plugin manager to register permissions in. */ - public static void registerPermissionsIfNecessary(PluginManager toRegister) { - Permission hatPerm = toRegister.getPermission(PERM_PREFIX + "*"); + public static void registerPermissionsIfNecessary(final PluginManager toRegister) { + final Permission hatPerm = toRegister.getPermission(PERM_PREFIX + "*"); if (hatPerm != null) { return; } - ImmutableMap.Builder children = ImmutableMap.builder(); - for (Material mat : Material.values()) { + final ImmutableMap.Builder children = ImmutableMap.builder(); + for (final Material mat : Material.values()) { final String matPerm = PERM_PREFIX + mat.name().toLowerCase(); children.put(matPerm, true); toRegister.addPermission(new Permission(matPerm, "Prevent using " + mat + " as a type of hat.", PermissionDefault.FALSE)); @@ -103,4 +102,4 @@ public class Commandhat extends EssentialsCommand { return Collections.emptyList(); } } -} \ No newline at end of file +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandheal.java b/Essentials/src/com/earth2me/essentials/commands/Commandheal.java index 47f1f1547..63a25ace9 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandheal.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandheal.java @@ -13,7 +13,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandheal extends EssentialsLoopCommand { public Commandheal() { super("heal"); @@ -68,18 +67,18 @@ public class Commandheal extends EssentialsLoopCommand { player.setFireTicks(0); user.sendMessage(tl("heal")); if (ess.getSettings().isRemovingEffectsOnHeal()) { - for (PotionEffect effect : player.getActivePotionEffects()) { + for (final PotionEffect effect : player.getActivePotionEffects()) { player.removePotionEffect(effect.getType()); } } sender.sendMessage(tl("healOther", user.getDisplayName())); - } catch (QuietAbortException e) { + } catch (final QuietAbortException e) { //Handle Quietly } } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1 && sender.isAuthorized("essentials.heal.others", ess)) { return getPlayers(server, sender); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandhelp.java b/Essentials/src/com/earth2me/essentials/commands/Commandhelp.java index bdfbaeb92..400785b5f 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandhelp.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandhelp.java @@ -2,7 +2,11 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.User; -import com.earth2me.essentials.textreader.*; +import com.earth2me.essentials.textreader.HelpInput; +import com.earth2me.essentials.textreader.IText; +import com.earth2me.essentials.textreader.KeywordReplacer; +import com.earth2me.essentials.textreader.TextInput; +import com.earth2me.essentials.textreader.TextPager; import com.earth2me.essentials.utils.NumberUtil; import org.bukkit.Server; @@ -12,7 +16,6 @@ import java.util.Locale; import static com.earth2me.essentials.I18n.tl; - public class Commandhelp extends EssentialsCommand { public Commandhelp() { super("help"); @@ -20,7 +23,7 @@ public class Commandhelp extends EssentialsCommand { @Override protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { - IText output; + final IText output; String pageStr = args.length > 0 ? args[0] : null; String chapterPageStr = args.length > 1 ? args[1] : null; String command = commandLabel; @@ -52,7 +55,7 @@ public class Commandhelp extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { return getCommands(server); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java b/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java index 3760a908a..491ef3ced 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java @@ -12,7 +12,6 @@ import java.util.logging.Level; import static com.earth2me.essentials.I18n.tl; - public class Commandhelpop extends EssentialsCommand { public Commandhelpop() { super("helpop"); @@ -43,7 +42,7 @@ public class Commandhelpop extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { return Collections.emptyList(); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandhome.java b/Essentials/src/com/earth2me/essentials/commands/Commandhome.java index 7c507f68f..cdff5774f 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandhome.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandhome.java @@ -17,7 +17,6 @@ import java.util.concurrent.CompletableFuture; import static com.earth2me.essentials.I18n.tl; - public class Commandhome extends EssentialsCommand { public Commandhome() { super("home"); @@ -29,7 +28,7 @@ public class Commandhome extends EssentialsCommand { final Trade charge = new Trade(this.getName(), ess); User player = user; String homeName = ""; - String[] nameParts; + final String[] nameParts; if (args.length > 0) { nameParts = args[0].split(":"); if (nameParts[0].length() == args[0].length() || !user.isAuthorized("essentials.home.others")) { @@ -47,9 +46,9 @@ public class Commandhome extends EssentialsCommand { throw new Exception(tl("bedOffline")); } PaperLib.getBedSpawnLocationAsync(player.getBase(), true).thenAccept(location -> { - CompletableFuture future = getNewExceptionFuture(user.getSource(), commandLabel); + final CompletableFuture future = getNewExceptionFuture(user.getSource(), commandLabel); if (location != null) { - UserTeleportHomeEvent event = new UserTeleportHomeEvent(user, "bed", location, UserTeleportHomeEvent.HomeType.BED); + final UserTeleportHomeEvent event = new UserTeleportHomeEvent(user, "bed", location, UserTeleportHomeEvent.HomeType.BED); server.getPluginManager().callEvent(event); if (event.isCancelled()) { return; @@ -67,14 +66,14 @@ public class Commandhome extends EssentialsCommand { throw new NoChargeException(); } goHome(user, player, homeName.toLowerCase(Locale.ENGLISH), charge, getNewExceptionFuture(user.getSource(), commandLabel)); - } catch (NotEnoughArgumentsException e) { + } catch (final NotEnoughArgumentsException e) { final User finalPlayer = player; - CompletableFuture message = new CompletableFuture<>(); + final CompletableFuture message = new CompletableFuture<>(); message.thenAccept(bed -> { final List homes = finalPlayer.getHomes(); if (homes.isEmpty() && finalPlayer.equals(user)) { if (ess.getSettings().isSpawnIfNoHome()) { - UserTeleportHomeEvent event = new UserTeleportHomeEvent(user, null, bed != null ? bed : finalPlayer.getWorld().getSpawnLocation(), bed != null ? UserTeleportHomeEvent.HomeType.BED : UserTeleportHomeEvent.HomeType.SPAWN); + final UserTeleportHomeEvent event = new UserTeleportHomeEvent(user, null, bed != null ? bed : finalPlayer.getWorld().getSpawnLocation(), bed != null ? UserTeleportHomeEvent.HomeType.BED : UserTeleportHomeEvent.HomeType.SPAWN); server.getPluginManager().callEvent(event); if (!event.isCancelled()) { user.getAsyncTeleport().respawn(charge, TeleportCause.COMMAND, getNewExceptionFuture(user.getSource(), commandLabel)); @@ -87,7 +86,7 @@ public class Commandhome extends EssentialsCommand { } else if (homes.size() == 1 && finalPlayer.equals(user)) { try { goHome(user, finalPlayer, homes.get(0), charge, getNewExceptionFuture(user.getSource(), commandLabel)); - } catch (Exception exception) { + } catch (final Exception exception) { showError(user.getBase(), exception, commandLabel); } } else { @@ -121,7 +120,7 @@ public class Commandhome extends EssentialsCommand { return Integer.toString(ess.getSettings().getHomeLimit(player)); } - private void goHome(final User user, final User player, final String home, final Trade charge, CompletableFuture future) throws Exception { + private void goHome(final User user, final User player, final String home, final Trade charge, final CompletableFuture future) throws Exception { if (home.length() < 1) { throw new NotEnoughArgumentsException(); } @@ -132,7 +131,7 @@ public class Commandhome extends EssentialsCommand { if (user.getWorld() != loc.getWorld() && ess.getSettings().isWorldHomePermissions() && !user.isAuthorized("essentials.worlds." + loc.getWorld().getName())) { throw new Exception(tl("noPerm", "essentials.worlds." + loc.getWorld().getName())); } - UserTeleportHomeEvent event = new UserTeleportHomeEvent(user, home, loc, UserTeleportHomeEvent.HomeType.HOME); + final UserTeleportHomeEvent event = new UserTeleportHomeEvent(user, home, loc, UserTeleportHomeEvent.HomeType.HOME); user.getServer().getPluginManager().callEvent(event); if (!event.isCancelled()) { user.getAsyncTeleport().teleport(loc, charge, TeleportCause.COMMAND, future); @@ -146,23 +145,23 @@ public class Commandhome extends EssentialsCommand { @Override protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { - boolean canVisitOthers = user.isAuthorized("essentials.home.others"); - boolean canVisitBed = user.isAuthorized("essentials.home.bed"); + final boolean canVisitOthers = user.isAuthorized("essentials.home.others"); + final boolean canVisitBed = user.isAuthorized("essentials.home.bed"); if (args.length == 1) { - List homes = user.getHomes(); + final List homes = user.getHomes(); if (canVisitBed) { homes.add("bed"); } if (canVisitOthers) { - int sepIndex = args[0].indexOf(':'); + final int sepIndex = args[0].indexOf(':'); if (sepIndex < 0) { getPlayers(server, user).forEach(player -> homes.add(player + ":")); } else { - String namePart = args[0].substring(0, sepIndex); - User otherUser; + final String namePart = args[0].substring(0, sepIndex); + final User otherUser; try { - otherUser = getPlayer(server, new String[]{namePart}, 0, true, true); - } catch (Exception ex) { + otherUser = getPlayer(server, new String[] {namePart}, 0, true, true); + } catch (final Exception ex) { return homes; } otherUser.getHomes().forEach(home -> homes.add(namePart + ":" + home)); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandignore.java b/Essentials/src/com/earth2me/essentials/commands/Commandignore.java index 9dcb45089..4d3cd58e0 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandignore.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandignore.java @@ -9,7 +9,6 @@ import java.util.UUID; import static com.earth2me.essentials.I18n.tl; - public class Commandignore extends EssentialsCommand { public Commandignore() { super("ignore"); @@ -18,14 +17,14 @@ public class Commandignore extends EssentialsCommand { @Override protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { if (args.length == 0) { - StringBuilder sb = new StringBuilder(); - for (UUID uuid : user._getIgnoredPlayers()) { - User curUser = ess.getUser(uuid); + final StringBuilder sb = new StringBuilder(); + for (final UUID uuid : user._getIgnoredPlayers()) { + final User curUser = ess.getUser(uuid); if (curUser != null && curUser.getName() != null && !curUser.getName().trim().isEmpty()) { sb.append(curUser.getName()).append(" "); } } - String ignoredList = sb.toString().trim(); + final String ignoredList = sb.toString().trim(); user.sendMessage(ignoredList.length() > 0 ? tl("ignoredList", ignoredList) : tl("noIgnored")); return; } @@ -33,7 +32,7 @@ public class Commandignore extends EssentialsCommand { User player; try { player = getPlayer(server, args, 0, true, true); - } catch (PlayerNotFoundException ex) { + } catch (final PlayerNotFoundException ex) { player = ess.getOfflineUser(args[0]); } if (player == null) { @@ -52,7 +51,7 @@ public class Commandignore extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { return getPlayers(server, user); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandinfo.java b/Essentials/src/com/earth2me/essentials/commands/Commandinfo.java index 585f4767a..bdd94c078 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandinfo.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandinfo.java @@ -6,7 +6,6 @@ import com.earth2me.essentials.textreader.TextInput; import com.earth2me.essentials.textreader.TextPager; import org.bukkit.Server; - public class Commandinfo extends EssentialsCommand { public Commandinfo() { super("info"); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java b/Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java index 3215f6c92..8064096c0 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java @@ -21,7 +21,7 @@ public class Commandinvsee extends EssentialsCommand { } final User invUser = getPlayer(server, user, args, 0); - Inventory inv; + final Inventory inv; if (args.length > 1 && user.isAuthorized("essentials.invsee.equip")) { inv = server.createInventory(invUser.getBase(), 9, "Equipped"); @@ -38,7 +38,7 @@ public class Commandinvsee extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { return getPlayers(server, user); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanditem.java b/Essentials/src/com/earth2me/essentials/commands/Commanditem.java index 25403804b..8eccbe43b 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanditem.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanditem.java @@ -14,7 +14,6 @@ import java.util.Locale; import static com.earth2me.essentials.I18n.tl; - public class Commanditem extends EssentialsCommand { public Commanditem() { super("item"); @@ -41,11 +40,11 @@ public class Commanditem extends EssentialsCommand { } else if (ess.getSettings().getOversizedStackSize() > 0 && user.isAuthorized("essentials.oversizedstacks")) { stack.setAmount(ess.getSettings().getOversizedStackSize()); } - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { throw new NotEnoughArgumentsException(); } - MetaItemStack metaStack = new MetaItemStack(stack); + final MetaItemStack metaStack = new MetaItemStack(stack); if (!metaStack.canSpawn(ess)) { throw new Exception(tl("unableToSpawnItem", itemname)); } @@ -58,7 +57,6 @@ public class Commanditem extends EssentialsCommand { stack = metaStack.getItemStack(); } - if (stack.getType() == Material.AIR) { throw new Exception(tl("cantSpawnItem", "Air")); } @@ -78,7 +76,7 @@ public class Commanditem extends EssentialsCommand { if (args.length == 1) { return getItems(); } else if (args.length == 2) { - return Lists.newArrayList("1", "64"); // TODO: get actual max size + return Lists.newArrayList("1", "64"); // TODO: get actual max size } else if (args.length == 3) { return Lists.newArrayList("0"); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanditemdb.java b/Essentials/src/com/earth2me/essentials/commands/Commanditemdb.java index 51aee3a2b..45a2f55bc 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanditemdb.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanditemdb.java @@ -11,14 +11,13 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commanditemdb extends EssentialsCommand { public Commanditemdb() { super("itemdb"); } @Override - protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception { + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { ItemStack itemStack = null; boolean itemHeld = false; if (args.length == 0) { @@ -47,8 +46,8 @@ public class Commanditemdb extends EssentialsCommand { } if (itemHeld && itemStack.getType() != Material.AIR) { - int maxuses = itemStack.getType().getMaxDurability(); - int durability = ((maxuses + 1) - itemStack.getDurability()); + final int maxuses = itemStack.getType().getMaxDurability(); + final int durability = (maxuses + 1) - itemStack.getDurability(); if (maxuses != 0) { sender.sendMessage(tl("durability", Integer.toString(durability))); } @@ -60,7 +59,7 @@ public class Commanditemdb extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { return getItems(); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanditemlore.java b/Essentials/src/com/earth2me/essentials/commands/Commanditemlore.java index 2780cccc6..598fc8ea8 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanditemlore.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanditemlore.java @@ -21,8 +21,8 @@ public class Commanditemlore extends EssentialsCommand { } @Override - protected void run(Server server, User user, String commandLabel, String[] args) throws Exception { - ItemStack item = user.getBase().getItemInHand(); + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + final ItemStack item = user.getBase().getItemInHand(); if (item.getType().name().contains("AIR")) { throw new Exception(tl("itemloreInvalidItem")); } @@ -31,10 +31,10 @@ public class Commanditemlore extends EssentialsCommand { throw new NotEnoughArgumentsException(); } - ItemMeta im = item.getItemMeta(); + final ItemMeta im = item.getItemMeta(); if (args[0].equalsIgnoreCase("add") && args.length > 1) { - String line = FormatUtil.formatString(user, "essentials.itemlore", getFinalArg(args, 1)).trim(); - List lore = im.hasLore() ? im.getLore() : new ArrayList<>(); + final String line = FormatUtil.formatString(user, "essentials.itemlore", getFinalArg(args, 1)).trim(); + final List lore = im.hasLore() ? im.getLore() : new ArrayList<>(); lore.add(line); im.setLore(lore); item.setItemMeta(im); @@ -48,12 +48,12 @@ public class Commanditemlore extends EssentialsCommand { throw new Exception(tl("itemloreNoLore")); } - int line = Integer.parseInt(args[1]); - String newLine = FormatUtil.formatString(user, "essentials.itemlore", getFinalArg(args, 2)).trim(); - List lore = im.getLore(); + final int line = Integer.parseInt(args[1]); + final String newLine = FormatUtil.formatString(user, "essentials.itemlore", getFinalArg(args, 2)).trim(); + final List lore = im.getLore(); try { lore.set(line - 1, newLine); - } catch (Exception e) { + } catch (final Exception e) { throw new Exception(tl("itemloreNoLine", line), e); } im.setLore(lore); @@ -65,7 +65,7 @@ public class Commanditemlore extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { return Lists.newArrayList("add", "set", "clear"); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanditemname.java b/Essentials/src/com/earth2me/essentials/commands/Commanditemname.java index 3b1621b68..0fec9064d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanditemname.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanditemname.java @@ -12,14 +12,14 @@ import java.util.Locale; import static com.earth2me.essentials.I18n.tl; public class Commanditemname extends EssentialsCommand { - + public Commanditemname() { super("itemname"); } @Override - protected void run(Server server, User user, String commandLabel, String[] args) throws Exception { - ItemStack item = user.getBase().getItemInHand(); + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + final ItemStack item = user.getBase().getItemInHand(); if (item.getType() == Material.AIR) { user.sendMessage(tl("itemnameInvalidItem", item.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' '))); return; @@ -30,7 +30,7 @@ public class Commanditemname extends EssentialsCommand { name = null; } - ItemMeta im = item.getItemMeta(); + final ItemMeta im = item.getItemMeta(); im.setDisplayName(name); item.setItemMeta(im); user.sendMessage(name == null ? tl("itemnameClear") : tl("itemnameSuccess", name)); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandjails.java b/Essentials/src/com/earth2me/essentials/commands/Commandjails.java index b2713ab8a..2abd5002a 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandjails.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandjails.java @@ -6,7 +6,6 @@ import org.bukkit.Server; import static com.earth2me.essentials.I18n.tl; - public class Commandjails extends EssentialsCommand { public Commandjails() { super("jails"); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandjump.java b/Essentials/src/com/earth2me/essentials/commands/Commandjump.java index b5927ba68..5a4cb7f63 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandjump.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandjump.java @@ -32,7 +32,7 @@ public class Commandjump extends EssentialsCommand { return; } - Location loc; + final Location loc; final Location cloc = user.getLocation(); try { @@ -40,7 +40,7 @@ public class Commandjump extends EssentialsCommand { loc.setYaw(cloc.getYaw()); loc.setPitch(cloc.getPitch()); loc.setY(loc.getY() + 1); - } catch (NullPointerException ex) { + } catch (final NullPointerException ex) { throw new Exception(tl("jumpError"), ex); } @@ -52,7 +52,7 @@ public class Commandjump extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1 && user.isAuthorized("essentials.jump.lock")) { // XXX these actually do the same thing return Lists.newArrayList("lock", "unlock"); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkick.java b/Essentials/src/com/earth2me/essentials/commands/Commandkick.java index 8d45893fb..2d6bf0eb1 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkick.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkick.java @@ -12,7 +12,6 @@ import java.util.logging.Level; import static com.earth2me.essentials.I18n.tl; - public class Commandkick extends EssentialsCommand { public Commandkick() { super("kick"); @@ -26,7 +25,7 @@ public class Commandkick extends EssentialsCommand { final User target = getPlayer(server, args, 0, true, false); if (sender.isPlayer()) { - User user = ess.getUser(sender.getPlayer()); + final User user = ess.getUser(sender.getPlayer()); if (target.isHidden(sender.getPlayer()) && !user.canInteractVanished() && !sender.getPlayer().canSee(target.getBase())) { throw new PlayerNotFoundException(); } @@ -47,7 +46,7 @@ public class Commandkick extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { return getPlayers(server, sender); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java b/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java index 303adfc5d..3d10aeb6e 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java @@ -7,7 +7,6 @@ import org.bukkit.entity.Player; import static com.earth2me.essentials.I18n.tl; - public class Commandkickall extends EssentialsCommand { public Commandkickall() { super("kickall"); @@ -18,7 +17,7 @@ public class Commandkickall extends EssentialsCommand { String kickReason = args.length > 0 ? getFinalArg(args, 0) : tl("kickDefault"); kickReason = FormatUtil.replaceFormat(kickReason.replace("\\n", "\n").replace("|", "\n")); - for (Player onlinePlayer : ess.getOnlinePlayers()) { + for (final Player onlinePlayer : ess.getOnlinePlayers()) { if (!sender.isPlayer() || !onlinePlayer.getName().equalsIgnoreCase(sender.getPlayer().getName())) { if (!ess.getUser(onlinePlayer).isAuthorized("essentials.kickall.exempt")) { onlinePlayer.kickPlayer(kickReason); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkill.java b/Essentials/src/com/earth2me/essentials/commands/Commandkill.java index 6bbfb89b6..4c2103bcf 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkill.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkill.java @@ -11,7 +11,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandkill extends EssentialsLoopCommand { public Commandkill() { super("kill"); @@ -43,7 +42,7 @@ public class Commandkill extends EssentialsLoopCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { return getPlayers(server, sender); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkit.java b/Essentials/src/com/earth2me/essentials/commands/Commandkit.java index f8dbdc14f..445e4064d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkit.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkit.java @@ -14,7 +14,6 @@ import java.util.logging.Level; import static com.earth2me.essentials.I18n.tl; - public class Commandkit extends EssentialsCommand { public Commandkit() { super("kit"); @@ -56,14 +55,14 @@ public class Commandkit extends EssentialsCommand { throw new Exception(tl("kitNotFound")); } - List kits = new ArrayList<>(); + final List kits = new ArrayList<>(); for (final String kitName : kitNames.split(",")) { if (kitName.isEmpty()) { throw new Exception(tl("kitNotFound")); } - Kit kit = new Kit(kitName, ess); + final Kit kit = new Kit(kitName, ess); kit.checkPerms(userFrom); kit.checkDelay(userFrom); kit.checkAffordable(userFrom); @@ -86,11 +85,11 @@ public class Commandkit extends EssentialsCommand { userTo.sendMessage(tl("kitReceive", kit.getName())); - } catch (NoChargeException ex) { + } catch (final NoChargeException ex) { if (ess.getSettings().isDebug()) { ess.getLogger().log(Level.INFO, "Soft kit error, abort spawning " + kit.getName(), ex); } - } catch (Exception ex) { + } catch (final Exception ex) { ess.showError(userFrom.getSource(), ex, "\\ kit: " + kit.getName()); } } @@ -99,9 +98,9 @@ public class Commandkit extends EssentialsCommand { @Override protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { - List options = new ArrayList<>(); + final List options = new ArrayList<>(); // TODO: Move all of this to its own method - for (String kitName : ess.getKits().getKits().getKeys(false)) { + for (final String kitName : ess.getKits().getKits().getKeys(false)) { if (!user.isAuthorized("essentials.kits." + kitName)) { // Only check perm, not time or money continue; } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkittycannon.java b/Essentials/src/com/earth2me/essentials/commands/Commandkittycannon.java index 341d4e0f0..e40234f52 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkittycannon.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkittycannon.java @@ -19,6 +19,26 @@ public class Commandkittycannon extends EssentialsCommand { super("kittycannon"); } + private static Ocelot spawnOcelot(final Server server, final User user) throws Mob.MobException { + final Ocelot ocelot = (Ocelot) Mob.OCELOT.spawn(user.getWorld(), server, user.getBase().getEyeLocation()); + final int i = random.nextInt(Ocelot.Type.values().length); + ocelot.setCatType(Ocelot.Type.values()[i]); + ((Tameable) ocelot).setTamed(true); + ocelot.setBaby(); + ocelot.setVelocity(user.getBase().getEyeLocation().getDirection().multiply(2)); + return ocelot; + } + + private static Entity spawnCat(final Server server, final User user) throws Mob.MobException { + final Cat cat = (Cat) Mob.CAT.spawn(user.getWorld(), server, user.getBase().getEyeLocation()); + final int i = random.nextInt(Cat.Type.values().length); + cat.setCatType(Cat.Type.values()[i]); + cat.setTamed(true); + cat.setBaby(); + cat.setVelocity(user.getBase().getEyeLocation().getDirection().multiply(2)); + return cat; + } + @Override protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { final Entity ocelot = Mob.CAT.getType() == null ? spawnOcelot(server, user) : spawnCat(server, user); @@ -29,24 +49,4 @@ public class Commandkittycannon extends EssentialsCommand { }, 20); } - - private static Ocelot spawnOcelot(Server server, User user) throws Mob.MobException { - final Ocelot ocelot = (Ocelot) Mob.OCELOT.spawn(user.getWorld(), server, user.getBase().getEyeLocation()); - final int i = random.nextInt(Ocelot.Type.values().length); - ocelot.setCatType(Ocelot.Type.values()[i]); - ((Tameable) ocelot).setTamed(true); - ocelot.setBaby(); - ocelot.setVelocity(user.getBase().getEyeLocation().getDirection().multiply(2)); - return ocelot; - } - - private static Entity spawnCat(Server server, User user) throws Mob.MobException { - final Cat cat = (Cat) Mob.CAT.spawn(user.getWorld(), server, user.getBase().getEyeLocation()); - final int i = random.nextInt(Cat.Type.values().length); - cat.setCatType(Cat.Type.values()[i]); - cat.setTamed(true); - cat.setBaby(); - cat.setVelocity(user.getBase().getEyeLocation().getDirection().multiply(2)); - return cat; - } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandlightning.java b/Essentials/src/com/earth2me/essentials/commands/Commandlightning.java index 9b99ea166..aca9555ee 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandlightning.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandlightning.java @@ -11,7 +11,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandlightning extends EssentialsLoopCommand { public Commandlightning() { super("lightning"); @@ -31,7 +30,7 @@ public class Commandlightning extends EssentialsLoopCommand { if (args.length > 1) { try { power = Integer.parseInt(args[1]); - } catch (NumberFormatException ignored) { + } catch (final NumberFormatException ignored) { } } final int finalPower = power; diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandlist.java b/Essentials/src/com/earth2me/essentials/commands/Commandlist.java index 1c79a088f..69fec590c 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandlist.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandlist.java @@ -7,11 +7,15 @@ import com.earth2me.essentials.utils.FormatUtil; import com.earth2me.essentials.utils.NumberUtil; import org.bukkit.Server; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; import static com.earth2me.essentials.I18n.tl; - public class Commandlist extends EssentialsCommand { public Commandlist() { super("list"); @@ -36,14 +40,14 @@ public class Commandlist extends EssentialsCommand { } // Output the standard /list output, when no group is specified - private void sendGroupedList(CommandSource sender, String commandLabel, Map> playerList) { + private void sendGroupedList(final CommandSource sender, final String commandLabel, final Map> playerList) { final Set configGroups = ess.getSettings().getListGroupConfig().keySet(); final List asterisk = new ArrayList<>(); // Loop through the custom defined groups and display them - for (String oConfigGroup : configGroups) { - String groupValue = ess.getSettings().getListGroupConfig().get(oConfigGroup).toString().trim(); - String configGroup = oConfigGroup.toLowerCase(); + for (final String oConfigGroup : configGroups) { + final String groupValue = ess.getSettings().getListGroupConfig().get(oConfigGroup).toString().trim(); + final String configGroup = oConfigGroup.toLowerCase(); // If the group value is an asterisk, then skip it, and handle it later if (groupValue.equals("*")) { @@ -57,7 +61,7 @@ public class Commandlist extends EssentialsCommand { continue; } - List outputUserList; + final List outputUserList; final List matchedList = playerList.get(configGroup); // If the group value is an int, then we might need to truncate it @@ -65,7 +69,7 @@ public class Commandlist extends EssentialsCommand { if (matchedList != null && !matchedList.isEmpty()) { playerList.remove(configGroup); outputUserList = new ArrayList<>(matchedList); - int limit = Integer.parseInt(groupValue); + final int limit = Integer.parseInt(groupValue); if (matchedList.size() > limit) { sender.sendMessage(PlayerList.outputFormat(oConfigGroup, tl("groupNumber", matchedList.size(), commandLabel, FormatUtil.stripFormat(configGroup)))); } else { @@ -85,25 +89,25 @@ public class Commandlist extends EssentialsCommand { sender.sendMessage(PlayerList.outputFormat(oConfigGroup, PlayerList.listUsers(ess, outputUserList, ", "))); } - Set var = playerList.keySet(); + final Set var = playerList.keySet(); String[] onlineGroups = var.toArray(new String[0]); Arrays.sort(onlineGroups, String.CASE_INSENSITIVE_ORDER); // If we have an asterisk group, then merge all remaining groups if (!asterisk.isEmpty()) { - List asteriskUsers = new ArrayList<>(); - for (String onlineGroup : onlineGroups) { + final List asteriskUsers = new ArrayList<>(); + for (final String onlineGroup : onlineGroups) { asteriskUsers.addAll(playerList.get(onlineGroup)); } - for (String key : asterisk) { + for (final String key : asterisk) { playerList.put(key, asteriskUsers); } onlineGroups = asterisk.toArray(new String[0]); } // If we have any groups remaining after the custom groups loop through and display them - for (String onlineGroup : onlineGroups) { - List users = playerList.get(onlineGroup); + for (final String onlineGroup : onlineGroups) { + final List users = playerList.get(onlineGroup); String groupName = asterisk.isEmpty() ? users.get(0).getGroup() : onlineGroup; if (ess.getPermissionsHandler().getName().equals("ConfigPermissions")) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmail.java b/Essentials/src/com/earth2me/essentials/commands/Commandmail.java index 637d50ead..d966d91db 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmail.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmail.java @@ -17,7 +17,6 @@ import java.util.UUID; import static com.earth2me.essentials.I18n.tl; - public class Commandmail extends EssentialsCommand { private static int mailsPerMinute = 0; private static long timestamp = 0; @@ -35,7 +34,7 @@ public class Commandmail extends EssentialsCommand { throw new NoChargeException(); } - IText input = new SimpleTextInput(mail); + final IText input = new SimpleTextInput(mail); final TextPager pager = new TextPager(input); pager.showPage(args.length > 1 ? args[1] : null, null, commandLabel + " " + args[0], user.getSource()); @@ -48,21 +47,21 @@ public class Commandmail extends EssentialsCommand { } if (user.isMuted()) { - String dateDiff = user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : null; + final String dateDiff = user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : null; if (dateDiff == null) { throw new Exception(user.hasMuteReason() ? tl("voiceSilencedReason", user.getMuteReason()) : tl("voiceSilenced")); } throw new Exception(user.hasMuteReason() ? tl("voiceSilencedReasonTime", dateDiff, user.getMuteReason()) : tl("voiceSilencedTime", dateDiff)); } - User u; + final User u; try { u = getPlayer(server, args[1], true, true); - } catch (PlayerNotFoundException e) { + } catch (final PlayerNotFoundException e) { throw new Exception(tl("playerNeverOnServer", args[1])); } - String mail = tl("mailFormat", user.getName(), FormatUtil.formatMessage(user, "essentials.mail", StringUtil.sanitizeString(FormatUtil.stripFormat(getFinalArg(args, 2))))); + final String mail = tl("mailFormat", user.getName(), FormatUtil.formatMessage(user, "essentials.mail", StringUtil.sanitizeString(FormatUtil.stripFormat(getFinalArg(args, 2))))); if (mail.length() > 1000) { throw new Exception(tl("mailTooLong")); } @@ -88,7 +87,7 @@ public class Commandmail extends EssentialsCommand { throw new Exception(tl("noPerm", "essentials.mail.sendall")); } ess.runTaskAsynchronously(new SendAll(tl("mailFormat", user.getName(), - FormatUtil.formatMessage(user, "essentials.mail", StringUtil.sanitizeString(FormatUtil.stripFormat(getFinalArg(args, 1))))))); + FormatUtil.formatMessage(user, "essentials.mail", StringUtil.sanitizeString(FormatUtil.stripFormat(getFinalArg(args, 1))))))); user.sendMessage(tl("mailSent")); return; } @@ -106,16 +105,16 @@ public class Commandmail extends EssentialsCommand { } @Override - protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception { + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { if (args.length >= 1 && "read".equalsIgnoreCase(args[0])) { throw new Exception(tl("onlyPlayers", commandLabel + " read")); } else if (args.length >= 1 && "clear".equalsIgnoreCase(args[0])) { throw new Exception(tl("onlyPlayers", commandLabel + " clear")); } else if (args.length >= 3 && "send".equalsIgnoreCase(args[0])) { - User u; + final User u; try { u = getPlayer(server, args[1], true, true); - } catch (PlayerNotFoundException e) { + } catch (final PlayerNotFoundException e) { throw new Exception(tl("playerNeverOnServer", args[1])); } u.addMail(tl("mailFormat", "Server", FormatUtil.replaceFormat(getFinalArg(args, 2)))); @@ -127,10 +126,10 @@ public class Commandmail extends EssentialsCommand { return; } else if (args.length >= 2) { //allow sending from console without "send" argument, since it's the only thing the console can do - User u; + final User u; try { u = getPlayer(server, args[0], true, true); - } catch (PlayerNotFoundException e) { + } catch (final PlayerNotFoundException e) { throw new Exception(tl("playerNeverOnServer", args[0])); } u.addMail(tl("mailFormat", "Server", FormatUtil.replaceFormat(getFinalArg(args, 1)))); @@ -140,29 +139,10 @@ public class Commandmail extends EssentialsCommand { throw new NotEnoughArgumentsException(); } - - private class SendAll implements Runnable { - String message; - - public SendAll(String message) { - this.message = message; - } - - @Override - public void run() { - for (UUID userid : ess.getUserMap().getAllUniqueUsers()) { - User user = ess.getUserMap().getUser(userid); - if (user != null) { - user.addMail(message); - } - } - } - } - @Override protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { - List options = Lists.newArrayList("read", "clear"); + final List options = Lists.newArrayList("read", "clear"); if (user.isAuthorized("essentials.mail.send")) { options.add("send"); } @@ -174,11 +154,11 @@ public class Commandmail extends EssentialsCommand { return getPlayers(server, user); } else if (args.length == 2 && args[0].equalsIgnoreCase("read")) { final List mail = user.getMails(); - int pages = mail.size() / 9 + (mail.size() % 9 > 0 ? 1 : 0); + final int pages = mail.size() / 9 + (mail.size() % 9 > 0 ? 1 : 0); if (pages == 0) { return Lists.newArrayList("0"); } else { - List options = Lists.newArrayList("1"); + final List options = Lists.newArrayList("1"); if (pages > 1) { options.add(String.valueOf(pages)); } @@ -203,4 +183,22 @@ public class Commandmail extends EssentialsCommand { return Collections.emptyList(); } } + + private class SendAll implements Runnable { + final String message; + + SendAll(final String message) { + this.message = message; + } + + @Override + public void run() { + for (final UUID userid : ess.getUserMap().getAllUniqueUsers()) { + final User user = ess.getUserMap().getUser(userid); + if (user != null) { + user.addMail(message); + } + } + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandme.java b/Essentials/src/com/earth2me/essentials/commands/Commandme.java index 9ce633be4..36d9a289d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandme.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandme.java @@ -17,16 +17,15 @@ import java.util.Set; import static com.earth2me.essentials.I18n.tl; - public class Commandme extends EssentialsCommand { public Commandme() { super("me"); } @Override - public void run(Server server, User user, String commandLabel, String[] args) throws Exception { + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { if (user.isMuted()) { - String dateDiff = user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : null; + final String dateDiff = user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : null; if (dateDiff == null) { throw new Exception(user.hasMuteReason() ? tl("voiceSilencedReason", user.getMuteReason()) : tl("voiceSilenced")); } @@ -41,18 +40,18 @@ public class Commandme extends EssentialsCommand { message = FormatUtil.formatMessage(user, "essentials.chat", message); user.setDisplayNick(); - int radius = ess.getSettings().getChatRadius(); - String toSend = tl("action", user.getDisplayName(), message); + final int radius = ess.getSettings().getChatRadius(); + final String toSend = tl("action", user.getDisplayName(), message); if (radius < 1) { ess.broadcastMessage(user, toSend); return; } - World world = user.getWorld(); - Location loc = user.getLocation(); - Set outList = new HashSet<>(); + final World world = user.getWorld(); + final Location loc = user.getLocation(); + final Set outList = new HashSet<>(); - for (Player player : Bukkit.getOnlinePlayers()) { + for (final Player player : Bukkit.getOnlinePlayers()) { final User onlineUser = ess.getUser(player); if (!onlineUser.equals(user)) { boolean abort = false; @@ -83,13 +82,13 @@ public class Commandme extends EssentialsCommand { user.sendMessage(tl("localNoOne")); } - for (Player onlinePlayer : outList) { + for (final Player onlinePlayer : outList) { onlinePlayer.sendMessage(toSend); } } @Override - public void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception { + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } @@ -101,7 +100,7 @@ public class Commandme extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { return Collections.emptyList(); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmore.java b/Essentials/src/com/earth2me/essentials/commands/Commandmore.java index 63630e39d..275f061c2 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmore.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmore.java @@ -10,7 +10,6 @@ import java.util.Locale; import static com.earth2me.essentials.I18n.tl; - public class Commandmore extends EssentialsCommand { public Commandmore() { super("more"); @@ -23,8 +22,8 @@ public class Commandmore extends EssentialsCommand { throw new Exception(tl("cantSpawnItem", "Air")); } - boolean canOversized = user.isAuthorized("essentials.oversizedstacks"); - if (stack.getAmount() >= ((canOversized) ? ess.getSettings().getOversizedStackSize() : stack.getMaxStackSize())) { + final boolean canOversized = user.isAuthorized("essentials.oversizedstacks"); + if (stack.getAmount() >= (canOversized ? ess.getSettings().getOversizedStackSize() : stack.getMaxStackSize())) { throw new Exception(tl("fullStack")); } @@ -40,7 +39,7 @@ public class Commandmore extends EssentialsCommand { } newStackSize += Integer.parseInt(args[0]); - if (newStackSize > ((canOversized) ? ess.getSettings().getOversizedStackSize() : stack.getMaxStackSize())) { + if (newStackSize > (canOversized ? ess.getSettings().getOversizedStackSize() : stack.getMaxStackSize())) { user.sendMessage(tl(canOversized ? "fullStackDefaultOversize" : "fullStackDefault", canOversized ? ess.getSettings().getOversizedStackSize() : stack.getMaxStackSize())); newStackSize = canOversized ? ess.getSettings().getOversizedStackSize() : stack.getMaxStackSize(); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmotd.java b/Essentials/src/com/earth2me/essentials/commands/Commandmotd.java index b766dc8c3..190bc830f 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmotd.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmotd.java @@ -6,7 +6,6 @@ import com.earth2me.essentials.textreader.TextInput; import com.earth2me.essentials.textreader.TextPager; import org.bukkit.Server; - public class Commandmotd extends EssentialsCommand { public Commandmotd() { super("motd"); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmsg.java b/Essentials/src/com/earth2me/essentials/commands/Commandmsg.java index 0e75f7881..55284921d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmsg.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmsg.java @@ -18,17 +18,17 @@ public class Commandmsg extends EssentialsLoopCommand { } @Override - public void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception { + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 2) { throw new NotEnoughArgumentsException(); } String message = getFinalArg(args, 1); - boolean canWildcard = sender.isAuthorized("essentials.msg.multiple", ess); + final boolean canWildcard = sender.isAuthorized("essentials.msg.multiple", ess); if (sender.isPlayer()) { - User user = ess.getUser(sender.getPlayer()); + final User user = ess.getUser(sender.getPlayer()); if (user.isMuted()) { - String dateDiff = user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : null; + final String dateDiff = user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : null; if (dateDiff == null) { throw new Exception(user.hasMuteReason() ? tl("voiceSilencedReason", user.getMuteReason()) : tl("voiceSilenced")); } @@ -41,26 +41,26 @@ public class Commandmsg extends EssentialsLoopCommand { // Sending messages to console if (args[0].equalsIgnoreCase(Console.NAME)) { - IMessageRecipient messageSender = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : Console.getInstance(); + final IMessageRecipient messageSender = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : Console.getInstance(); messageSender.sendMessage(Console.getInstance(), message); return; } - loopOnlinePlayers(server, sender, false, canWildcard, args[0], new String[]{message}); + loopOnlinePlayers(server, sender, false, canWildcard, args[0], new String[] {message}); } @Override protected void updatePlayer(final Server server, final CommandSource sender, final User messageReceiver, final String[] args) { - IMessageRecipient messageSender = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : Console.getInstance(); + final IMessageRecipient messageSender = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : Console.getInstance(); messageSender.sendMessage(messageReceiver, args[0]); // args[0] is the message. } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { return getPlayers(server, sender); } else { - return null; // It's a chat message, use the default chat handler + return null; // It's a chat message, use the default chat handler } } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmsgtoggle.java b/Essentials/src/com/earth2me/essentials/commands/Commandmsgtoggle.java index be9bcd022..07548c73f 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmsgtoggle.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmsgtoggle.java @@ -6,7 +6,6 @@ import org.bukkit.Server; import static com.earth2me.essentials.I18n.tl; - public class Commandmsgtoggle extends EssentialsToggleCommand { public Commandmsgtoggle() { super("msgtoggle", "essentials.msgtoggle.others"); @@ -23,7 +22,7 @@ public class Commandmsgtoggle extends EssentialsToggleCommand { } @Override - void togglePlayer(CommandSource sender, User user, Boolean enabled) { + void togglePlayer(final CommandSource sender, final User user, Boolean enabled) { if (enabled == null) { enabled = !user.isIgnoreMsg(); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmute.java b/Essentials/src/com/earth2me/essentials/commands/Commandmute.java index ccb68503b..ab960c4ff 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmute.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmute.java @@ -13,7 +13,6 @@ import java.util.logging.Level; import static com.earth2me.essentials.I18n.tl; - public class Commandmute extends EssentialsCommand { public Commandmute() { super("mute"); @@ -28,7 +27,7 @@ public class Commandmute extends EssentialsCommand { User user; try { user = getPlayer(server, args, 0, true, true); - } catch (PlayerNotFoundException e) { + } catch (final PlayerNotFoundException e) { nomatch = true; user = ess.getUser(new OfflinePlayer(args[0], ess.getServer())); } @@ -37,11 +36,11 @@ public class Commandmute extends EssentialsCommand { throw new Exception(tl("muteExemptOffline")); } } else if (user.isAuthorized("essentials.mute.exempt")) { - throw new Exception(tl("muteExempt")); + throw new Exception(tl("muteExempt")); } long muteTimestamp = 0; - String time; + final String time; String muteReason = null; if (args.length > 1) { @@ -49,21 +48,21 @@ public class Commandmute extends EssentialsCommand { try { muteTimestamp = DateUtil.parseDateDiff(time, true); muteReason = getFinalArg(args, 2); - } catch (Exception e) { + } catch (final Exception e) { muteReason = getFinalArg(args, 1); } final long maxMuteLength = ess.getSettings().getMaxMute() * 1000; - if (maxMuteLength > 0 && ((muteTimestamp - GregorianCalendar.getInstance().getTimeInMillis()) > maxMuteLength) && sender.isPlayer() && !(ess.getUser(sender.getPlayer()).isAuthorized("essentials.mute.unlimited"))) { + if (maxMuteLength > 0 && ((muteTimestamp - GregorianCalendar.getInstance().getTimeInMillis()) > maxMuteLength) && sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.mute.unlimited")) { sender.sendMessage(tl("oversizedMute")); throw new NoChargeException(); } } - + final boolean willMute = (args.length > 1) || !user.getMuted(); final User controller = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null; final MuteStatusChangeEvent event = new MuteStatusChangeEvent(user, controller, willMute, muteTimestamp, muteReason); ess.getServer().getPluginManager().callEvent(event); - + if (!event.isCancelled()) { if (muteReason != null) { user.setMuteReason(muteReason.isEmpty() ? null : muteReason); @@ -76,7 +75,7 @@ public class Commandmute extends EssentialsCommand { } user.setMuteTimeout(muteTimestamp); final boolean muted = user.getMuted(); - String muteTime = DateUtil.formatDateDiff(muteTimestamp); + final String muteTime = DateUtil.formatDateDiff(muteTimestamp); if (nomatch) { sender.sendMessage(tl("userUnknown", user.getName())); @@ -124,7 +123,7 @@ public class Commandmute extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { return getPlayers(server, sender); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandnear.java b/Essentials/src/com/earth2me/essentials/commands/Commandnear.java index aa5aeb910..a2ce6c178 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandnear.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandnear.java @@ -15,7 +15,6 @@ import java.util.Queue; import static com.earth2me.essentials.I18n.tl; - public class Commandnear extends EssentialsCommand { public Commandnear() { super("near"); @@ -36,16 +35,16 @@ public class Commandnear extends EssentialsCommand { if (args.length > 0) { try { radius = Long.parseLong(args[0]); - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { try { otherUser = getPlayer(server, user, args, 0); - } catch (Exception ignored) { + } catch (final Exception ignored) { } } if (args.length > 1 && otherUser != null) { try { radius = Long.parseLong(args[1]); - } catch (NumberFormatException ignored) { + } catch (final NumberFormatException ignored) { } } } @@ -73,7 +72,7 @@ public class Commandnear extends EssentialsCommand { if (args.length > 1) { try { radius = Long.parseLong(args[1]); - } catch (NumberFormatException ignored) { + } catch (final NumberFormatException ignored) { } } sender.sendMessage(tl("nearbyPlayers", getLocal(otherUser, radius))); @@ -84,11 +83,11 @@ public class Commandnear extends EssentialsCommand { final World world = loc.getWorld(); final StringBuilder output = new StringBuilder(); final long radiusSquared = radius * radius; - boolean showHidden = user.canInteractVanished(); + final boolean showHidden = user.canInteractVanished(); - Queue nearbyPlayers = new PriorityQueue<>((o1, o2) -> (int) (o1.getLocation().distanceSquared(loc) - o2.getLocation().distanceSquared(loc))); + final Queue nearbyPlayers = new PriorityQueue<>((o1, o2) -> (int) (o1.getLocation().distanceSquared(loc) - o2.getLocation().distanceSquared(loc))); - for (User player : ess.getOnlineUsers()) { + for (final User player : ess.getOnlineUsers()) { if (!player.equals(user) && !player.isAuthorized("essentials.near.exclude") && (!player.isHidden(user.getBase()) || showHidden || user.getBase().canSee(player.getBase()))) { final Location playerLoc = player.getLocation(); if (playerLoc.getWorld() != world) { @@ -106,7 +105,7 @@ public class Commandnear extends EssentialsCommand { if (output.length() > 0) { output.append(", "); } - User nearbyPlayer = nearbyPlayers.poll(); + final User nearbyPlayer = nearbyPlayers.poll(); if (nearbyPlayer == null) { continue; } @@ -117,7 +116,7 @@ public class Commandnear extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (user.isAuthorized("essentials.near.others")) { if (args.length == 1) { return getPlayers(server, user); @@ -136,7 +135,7 @@ public class Commandnear extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { return getPlayers(server, sender); } else if (args.length == 2) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandnick.java b/Essentials/src/com/earth2me/essentials/commands/Commandnick.java index 38a73ada3..0f069fce4 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandnick.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandnick.java @@ -15,7 +15,6 @@ import java.util.function.Predicate; import static com.earth2me.essentials.I18n.tl; - public class Commandnick extends EssentialsLoopCommand { public Commandnick() { super("nick"); @@ -71,14 +70,14 @@ public class Commandnick extends EssentialsLoopCommand { } private String formatNickname(final User user, final String nick) throws Exception { - String newNick = user == null ? FormatUtil.replaceFormat(nick) : FormatUtil.formatString(user, "essentials.nick", nick); + final String newNick = user == null ? FormatUtil.replaceFormat(nick) : FormatUtil.formatString(user, "essentials.nick", nick); if (!newNick.matches("^[a-zA-Z_0-9\u00a7]+$") && user != null && !user.isAuthorized("essentials.nick.allowunsafe")) { throw new Exception(tl("nickNamesAlpha")); } else if (getNickLength(newNick) > ess.getSettings().getMaxNickLength()) { throw new Exception(tl("nickTooLong")); } else if (FormatUtil.stripFormat(newNick).length() < 1) { throw new Exception(tl("nickNamesAlpha")); - } else if (user != null && (user.isAuthorized("essentials.nick.changecolors") && !user.isAuthorized("essentials.nick.changecolors.bypass")) && !FormatUtil.stripFormat(newNick).equals(user.getName())) { + } else if (user != null && user.isAuthorized("essentials.nick.changecolors") && !user.isAuthorized("essentials.nick.changecolors.bypass") && !FormatUtil.stripFormat(newNick).equals(user.getName())) { throw new Exception(tl("nickNamesOnlyColorChanges")); } else if (user != null && !user.isAuthorized("essentials.nick.blacklist.bypass") && isNickBanned(newNick)) { throw new Exception(tl("nickNameBlacklist", nick)); @@ -86,8 +85,8 @@ public class Commandnick extends EssentialsLoopCommand { return newNick; } - private boolean isNickBanned(String newNick) { - for (Predicate predicate : ess.getSettings().getNickBlacklist()) { + private boolean isNickBanned(final String newNick) { + for (final Predicate predicate : ess.getSettings().getNickBlacklist()) { if (predicate.test(newNick)) { return true; } @@ -99,7 +98,7 @@ public class Commandnick extends EssentialsLoopCommand { return ess.getSettings().ignoreColorsInMaxLength() ? ChatColor.stripColor(nick).length() : nick.length(); } - private boolean nickInUse(final User target, String nick) { + private boolean nickInUse(final User target, final String nick) { final String lowerNick = FormatUtil.stripFormat(nick.toLowerCase(Locale.ENGLISH)); for (final Player onlinePlayer : ess.getOnlinePlayers()) { if (target.getBase().getName().equals(onlinePlayer.getName())) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandnuke.java b/Essentials/src/com/earth2me/essentials/commands/Commandnuke.java index 547205c87..94a0dae1d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandnuke.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandnuke.java @@ -14,7 +14,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandnuke extends EssentialsCommand { public Commandnuke() { super("nuke"); @@ -22,7 +21,7 @@ public class Commandnuke extends EssentialsCommand { @Override protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws NoSuchFieldException, NotEnoughArgumentsException { - Collection targets; + final Collection targets; if (args.length > 0) { targets = new ArrayList<>(); for (int i = 0; i < args.length; ++i) { @@ -32,7 +31,7 @@ public class Commandnuke extends EssentialsCommand { targets = ess.getOnlinePlayers(); } ess.getTNTListener().enable(); - for (Player player : targets) { + for (final Player player : targets) { if (player == null) { continue; } @@ -48,7 +47,7 @@ public class Commandnuke extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { return getPlayers(server, sender); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandpay.java b/Essentials/src/com/earth2me/essentials/commands/Commandpay.java index c96b8a77f..da60f1756 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandpay.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandpay.java @@ -17,7 +17,6 @@ import java.util.concurrent.atomic.AtomicBoolean; import static com.earth2me.essentials.I18n.tl; - public class Commandpay extends EssentialsLoopCommand { public Commandpay() { super("pay"); @@ -28,12 +27,12 @@ public class Commandpay extends EssentialsLoopCommand { if (args.length < 2) { throw new NotEnoughArgumentsException(); } - + if (args[1].contains("-")) { throw new Exception(tl("payMustBePositive")); } - String stringAmount = args[1].replaceAll("[^0-9\\.]", ""); + final String stringAmount = args[1].replaceAll("[^0-9\\.]", ""); if (stringAmount.length() < 1) { throw new NotEnoughArgumentsException(); @@ -64,18 +63,18 @@ public class Commandpay extends EssentialsLoopCommand { user.payUser(player, amount, UserBalanceUpdateEvent.Cause.COMMAND_PAY); user.getConfirmingPayments().remove(player); Trade.log("Command", "Pay", "Player", user.getName(), new Trade(amount, ess), player.getName(), new Trade(amount, ess), user.getLocation(), ess); - } catch (MaxMoneyException ex) { + } catch (final MaxMoneyException ex) { user.sendMessage(tl("maxMoney")); try { user.setMoney(user.getMoney().add(amount)); - } catch (MaxMoneyException ignored) { + } catch (final MaxMoneyException ignored) { } - } catch (Exception e) { + } catch (final Exception e) { user.sendMessage(e.getMessage()); } }); if (informToConfirm.get()) { - String cmd = "/" + commandLabel + " " + StringUtil.joinList(" ", args); + final String cmd = "/" + commandLabel + " " + StringUtil.joinList(" ", args); user.sendMessage(tl("confirmPayment", NumberUtil.displayCurrency(amount, ess), cmd)); } } @@ -86,7 +85,7 @@ public class Commandpay extends EssentialsLoopCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { return getPlayers(server, sender); } else if (args.length == 2) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandpayconfirmtoggle.java b/Essentials/src/com/earth2me/essentials/commands/Commandpayconfirmtoggle.java index 39940e7c6..f34ebe04a 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandpayconfirmtoggle.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandpayconfirmtoggle.java @@ -12,7 +12,7 @@ public class Commandpayconfirmtoggle extends EssentialsCommand { } @Override - public void run(Server server, User user, String commandLabel, String[] args) throws Exception { + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { boolean confirmingPay = !user.isPromptingPayConfirm(); if (commandLabel.contains("payconfirmon")) { confirmingPay = true; diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandpaytoggle.java b/Essentials/src/com/earth2me/essentials/commands/Commandpaytoggle.java index 241b07934..81f98e4b5 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandpaytoggle.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandpaytoggle.java @@ -13,12 +13,12 @@ public class Commandpaytoggle extends EssentialsToggleCommand { } @Override - protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception { + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { toggleOtherPlayers(server, sender, args); } @Override - public void run(Server server, User user, String commandLabel, String[] args) throws Exception { + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { if (commandLabel.contains("payon")) { togglePlayer(user.getSource(), user, true); } else if (commandLabel.contains("payoff")) { @@ -29,7 +29,7 @@ public class Commandpaytoggle extends EssentialsToggleCommand { } @Override - void togglePlayer(CommandSource sender, User user, Boolean enabled) { + void togglePlayer(final CommandSource sender, final User user, Boolean enabled) { if (enabled == null) { enabled = !user.isAcceptingPay(); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandpotion.java b/Essentials/src/com/earth2me/essentials/commands/Commandpotion.java index 3c97f3303..5bf258cb1 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandpotion.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandpotion.java @@ -13,11 +13,15 @@ import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; -import java.util.*; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; import static com.earth2me.essentials.I18n.tl; - public class Commandpotion extends EssentialsCommand { public Commandpotion() { super("potion"); @@ -28,15 +32,15 @@ public class Commandpotion extends EssentialsCommand { final ItemStack stack = user.getItemInHand(); if (args.length == 0) { final Set potionslist = new TreeSet<>(); - for (Map.Entry entry : Potions.entrySet()) { + for (final Map.Entry entry : Potions.entrySet()) { final String potionName = entry.getValue().getName().toLowerCase(Locale.ENGLISH); - if (potionslist.contains(potionName) || (user.isAuthorized("essentials.potion." + potionName))) { + if (potionslist.contains(potionName) || user.isAuthorized("essentials.potion." + potionName)) { potionslist.add(entry.getKey()); } } throw new NotEnoughArgumentsException(tl("potions", StringUtil.joinList(potionslist.toArray()))); } - + boolean holdingPotion = stack.getType() == Material.POTION; if (!holdingPotion && ReflUtil.getNmsVersionObject().isHigherThanOrEqualTo(ReflUtil.V1_9_R1)) { holdingPotion = stack.getType() == Material.SPLASH_POTION || stack.getType() == Material.LINGERING_POTION; @@ -47,14 +51,14 @@ public class Commandpotion extends EssentialsCommand { pmeta.clearCustomEffects(); stack.setItemMeta(pmeta); } else if (args[0].equalsIgnoreCase("apply") && user.isAuthorized("essentials.potion.apply")) { - for (PotionEffect effect : pmeta.getCustomEffects()) { + for (final PotionEffect effect : pmeta.getCustomEffects()) { effect.apply(user.getBase()); } } else if (args.length < 3) { throw new NotEnoughArgumentsException(); } else { final MetaItemStack mStack = new MetaItemStack(stack); - for (String arg : args) { + for (final String arg : args) { mStack.addPotionMeta(user.getSource(), true, arg, ess); } if (mStack.completePotion()) { @@ -71,15 +75,15 @@ public class Commandpotion extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { // Note: this enforces an order of effect power duration splash, which the actual command doesn't have. But that's fine. if (args.length == 1) { - List options = Lists.newArrayList(); + final List options = Lists.newArrayList(); options.add("clear"); if (user.isAuthorized("essentials.potion.apply")) { options.add("apply"); } - for (Map.Entry entry : Potions.entrySet()) { + for (final Map.Entry entry : Potions.entrySet()) { final String potionName = entry.getValue().getName().toLowerCase(Locale.ENGLISH); if (user.isAuthorized("essentials.potion." + potionName)) { options.add("effect:" + entry.getKey()); @@ -89,8 +93,8 @@ public class Commandpotion extends EssentialsCommand { } else if (args.length == 2 && args[0].startsWith("effect:")) { return Lists.newArrayList("power:1", "power:2", "power:3", "power:4", "amplifier:0", "amplifier:1", "amplifier:2", "amplifier:3"); } else if (args.length == 3 && args[0].startsWith("effect:")) { - List options = Lists.newArrayList(); - for (String duration : COMMON_DURATIONS) { + final List options = Lists.newArrayList(); + for (final String duration : COMMON_DURATIONS) { options.add("duration:" + duration); } return options; diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandpowertool.java b/Essentials/src/com/earth2me/essentials/commands/Commandpowertool.java index 4977aa506..88b7a0c4f 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandpowertool.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandpowertool.java @@ -15,7 +15,6 @@ import java.util.Locale; import static com.earth2me.essentials.I18n.tl; - public class Commandpowertool extends EssentialsCommand { public Commandpowertool() { super("powertool"); @@ -105,23 +104,24 @@ public class Commandpowertool extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { - List options = Lists.newArrayList("d:", "c:", "l:"); + final List options = Lists.newArrayList("d:", "c:", "l:"); if (user.isAuthorized("essentials.powertool.append")) { - for (String command : getCommands(server)) { + for (final String command : getCommands(server)) { options.add("a:" + command); } } try { final ItemStack itemStack = user.getBase().getItemInHand(); - List powertools = user.getPowertool(itemStack); - for (String tool : powertools) { + final List powertools = user.getPowertool(itemStack); + for (final String tool : powertools) { options.add("r:" + tool); } - } catch (Exception ignored) {} + } catch (final Exception ignored) { + } return options; } else if (args[0].startsWith("a:")) { return tabCompleteCommand(user.getSource(), server, args[0].substring(2), args, 1); @@ -131,26 +131,27 @@ public class Commandpowertool extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { return getPlayers(server, sender); } else if (args.length == 2) { return getItems(); } else if (args.length == 3) { - List options = Lists.newArrayList("d:", "c:", "l:"); + final List options = Lists.newArrayList("d:", "c:", "l:"); - for (String command : getCommands(server)) { + for (final String command : getCommands(server)) { options.add("a:" + command); } try { final User user = getPlayer(server, args, 0, true, true); final ItemStack itemStack = ess.getItemDb().get(args[1]); - List powertools = user.getPowertool(itemStack); - for (String tool : powertools) { + final List powertools = user.getPowertool(itemStack); + for (final String tool : powertools) { options.add("r:" + tool); } - } catch (Exception ignored) {} + } catch (final Exception ignored) { + } return options; } else if (args[2].startsWith("a:")) { return tabCompleteCommand(sender, server, args[2].substring(2), args, 3); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandpowertooltoggle.java b/Essentials/src/com/earth2me/essentials/commands/Commandpowertooltoggle.java index fadf3fa47..b594063d1 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandpowertooltoggle.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandpowertooltoggle.java @@ -5,7 +5,6 @@ import org.bukkit.Server; import static com.earth2me.essentials.I18n.tl; - public class Commandpowertooltoggle extends EssentialsCommand { public Commandpowertooltoggle() { super("powertooltoggle"); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandptime.java b/Essentials/src/com/earth2me/essentials/commands/Commandptime.java index e53dab557..d2853d5ee 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandptime.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandptime.java @@ -8,11 +8,13 @@ import com.google.common.collect.Lists; import org.bukkit.Server; import org.bukkit.World; -import java.util.*; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.StringJoiner; import static com.earth2me.essentials.I18n.tl; - public class Commandptime extends EssentialsLoopCommand { private static final List getAliases = Arrays.asList("get", "list", "show", "display"); @@ -43,7 +45,7 @@ public class Commandptime extends EssentialsLoopCommand { if (ess.getOnlinePlayers().size() > 1) { sender.sendMessage(tl("pTimePlayers")); } - for (User player : ess.getOnlineUsers()) { + for (final User player : ess.getOnlineUsers()) { getUserTime(sender, player); } } @@ -54,7 +56,7 @@ public class Commandptime extends EssentialsLoopCommand { } String time = args[0]; - boolean fixed = time.startsWith("@"); + final boolean fixed = time.startsWith("@"); if (fixed) { time = time.substring(1); } @@ -65,12 +67,12 @@ public class Commandptime extends EssentialsLoopCommand { } else { try { ticks = DescParseTickFormat.parse(time); - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { throw new NotEnoughArgumentsException(e); } } - StringJoiner joiner = new StringJoiner(","); + final StringJoiner joiner = new StringJoiner(","); loopOnlinePlayersConsumer(server, sender, false, true, args.length > 1 ? args[1] : sender.getSelfSelector(), player -> { setUserTime(player, ticks, !fixed); joiner.add(player.getName()); @@ -81,11 +83,11 @@ public class Commandptime extends EssentialsLoopCommand { return; } - String formattedTime = DescParseTickFormat.format(ticks); + final String formattedTime = DescParseTickFormat.format(ticks); sender.sendMessage(fixed ? tl("pTimeSetFixed", formattedTime, joiner.toString()) : tl("pTimeSet", formattedTime, joiner.toString())); } - public void getUserTime(final CommandSource sender, IUser user) { + public void getUserTime(final CommandSource sender, final IUser user) { if (user == null) { return; } @@ -95,11 +97,11 @@ public class Commandptime extends EssentialsLoopCommand { return; } - String time = DescParseTickFormat.format(user.getBase().getPlayerTime()); + final String time = DescParseTickFormat.format(user.getBase().getPlayerTime()); sender.sendMessage(user.getBase().isPlayerTimeRelative() ? tl("pTimeCurrent", user.getName(), time) : tl("pTimeCurrentFixed", user.getName(), time)); } - private void setUserTime(final User user, final Long ticks, Boolean relative) { + private void setUserTime(final User user, final Long ticks, final Boolean relative) { if (ticks == null) { user.getBase().resetPlayerTime(); } else { @@ -115,7 +117,7 @@ public class Commandptime extends EssentialsLoopCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { final User user = ess.getUser(sender.getPlayer()); if (args.length == 1) { @@ -128,6 +130,6 @@ public class Commandptime extends EssentialsLoopCommand { } @Override - protected void updatePlayer(Server server, CommandSource sender, User user, String[] args) { + protected void updatePlayer(final Server server, final CommandSource sender, final User user, final String[] args) { } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandpweather.java b/Essentials/src/com/earth2me/essentials/commands/Commandpweather.java index bcaca5f34..64c973d7e 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandpweather.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandpweather.java @@ -7,7 +7,13 @@ import com.google.common.collect.Lists; import org.bukkit.Server; import org.bukkit.WeatherType; -import java.util.*; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.StringJoiner; import static com.earth2me.essentials.I18n.tl; @@ -49,7 +55,7 @@ public class Commandpweather extends EssentialsLoopCommand { if (ess.getOnlinePlayers().size() > 1) { sender.sendMessage(tl("pWeatherPlayers")); } - for (User player : ess.getOnlineUsers()) { + for (final User player : ess.getOnlineUsers()) { getUserWeather(sender, player); } } @@ -59,12 +65,12 @@ public class Commandpweather extends EssentialsLoopCommand { return; } - String weather = args[0].toLowerCase(); + final String weather = args[0].toLowerCase(); if (!weatherAliases.containsKey(weather) && !weather.equalsIgnoreCase("reset")) { throw new NotEnoughArgumentsException(tl("pWeatherInvalidAlias")); } - StringJoiner joiner = new StringJoiner(","); + final StringJoiner joiner = new StringJoiner(","); loopOnlinePlayersConsumer(server, sender, false, true, args.length > 1 ? args[1] : sender.getSelfSelector(), player -> { setUserWeather(player, weather); joiner.add(player.getName()); @@ -78,7 +84,7 @@ public class Commandpweather extends EssentialsLoopCommand { sender.sendMessage(tl("pWeatherSet", weather, joiner.toString())); } - private void getUserWeather(CommandSource sender, IUser user) { + private void getUserWeather(final CommandSource sender, final IUser user) { if (user == null) { return; } @@ -90,7 +96,7 @@ public class Commandpweather extends EssentialsLoopCommand { sender.sendMessage(tl("pWeatherCurrent", user.getName(), user.getBase().getPlayerWeather().toString().toLowerCase(Locale.ENGLISH))); } - private void setUserWeather(User user, String weatherType) { + private void setUserWeather(final User user, final String weatherType) { if (weatherType.equalsIgnoreCase("reset")) { user.getBase().resetPlayerWeather(); return; @@ -99,7 +105,7 @@ public class Commandpweather extends EssentialsLoopCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { return Lists.newArrayList("get", "reset", "storm", "sun"); } else if (args.length == 2 && (getAliases.contains(args[0]) || user == null || user.isAuthorized("essentials.pweather.others"))) { @@ -110,6 +116,6 @@ public class Commandpweather extends EssentialsLoopCommand { } @Override - protected void updatePlayer(Server server, CommandSource sender, User user, String[] args) { + protected void updatePlayer(final Server server, final CommandSource sender, final User user, final String[] args) { } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandr.java b/Essentials/src/com/earth2me/essentials/commands/Commandr.java index fe4b46e7c..4003c6d2e 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandr.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandr.java @@ -10,7 +10,6 @@ import org.bukkit.Server; import static com.earth2me.essentials.I18n.tl; - public class Commandr extends EssentialsCommand { public Commandr() { super("r"); @@ -23,11 +22,11 @@ public class Commandr extends EssentialsCommand { } String message = getFinalArg(args, 0); - IMessageRecipient messageSender; + final IMessageRecipient messageSender; if (sender.isPlayer()) { - User user = ess.getUser(sender.getPlayer()); + final User user = ess.getUser(sender.getPlayer()); if (user.isMuted()) { - String dateDiff = user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : null; + final String dateDiff = user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : null; if (dateDiff == null) { throw new Exception(user.hasMuteReason() ? tl("voiceSilencedReason", user.getMuteReason()) : tl("voiceSilenced")); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java b/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java index 85fa06c4c..ed53615b0 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java @@ -9,7 +9,6 @@ import java.util.Locale; import static com.earth2me.essentials.I18n.tl; - public class Commandrealname extends EssentialsCommand { public Commandrealname() { super("realname"); @@ -23,9 +22,9 @@ public class Commandrealname extends EssentialsCommand { final String lookup = args[0].toLowerCase(Locale.ENGLISH); - boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); + final boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); boolean foundUser = false; - for (User u : ess.getOnlineUsers()) { + for (final User u : ess.getOnlineUsers()) { if (skipHidden && u.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(u.getBase())) { continue; } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandrecipe.java b/Essentials/src/com/earth2me/essentials/commands/Commandrecipe.java index 0d592040f..e57edf3ea 100755 --- a/Essentials/src/com/earth2me/essentials/commands/Commandrecipe.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandrecipe.java @@ -7,10 +7,15 @@ import com.earth2me.essentials.utils.NumberUtil; import com.earth2me.essentials.utils.VersionUtil; import org.bukkit.Material; import org.bukkit.Server; -import org.bukkit.inventory.*; +import org.bukkit.inventory.FurnaceRecipe; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.ShapedRecipe; +import org.bukkit.inventory.ShapelessRecipe; -import java.util.HashMap; import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; @@ -33,7 +38,7 @@ public class Commandrecipe extends EssentialsCommand { if (VersionUtil.getServerBukkitVersion().isHigherThanOrEqualTo(VersionUtil.v1_12_0_R01)) { try { Class.forName("com.destroystokyo.paper.event.player.PlayerRecipeBookClickEvent"); - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { sender.sendMessage(tl("unsupportedFeature")); return; } @@ -72,7 +77,7 @@ public class Commandrecipe extends EssentialsCommand { shapedRecipe(sender, (ShapedRecipe) selectedRecipe, sender.isPlayer()); } else if (selectedRecipe instanceof ShapelessRecipe) { if (recipesOfType.size() == 1 && (itemType.getType() == FIREWORK_ROCKET)) { - ShapelessRecipe shapelessRecipe = new ShapelessRecipe(itemType); + final ShapelessRecipe shapelessRecipe = new ShapelessRecipe(itemType); shapelessRecipe.addIngredient(GUNPOWDER); shapelessRecipe.addIngredient(Material.PAPER); shapelessRecipe.addIngredient(FIREWORK_STAR); @@ -116,8 +121,8 @@ public class Commandrecipe extends EssentialsCommand { } else { final HashMap colorMap = new HashMap<>(); int i = 1; - for (Character c : "abcdefghi".toCharArray()) { - ItemStack item = recipeMap.get(c); + for (final Character c : "abcdefghi".toCharArray()) { + final ItemStack item = recipeMap.get(c); if (!colorMap.containsKey(item == null ? null : item.getType())) { colorMap.put(item == null ? null : item.getType(), String.valueOf(i++)); } @@ -125,7 +130,7 @@ public class Commandrecipe extends EssentialsCommand { final Material[][] materials = new Material[3][3]; for (int j = 0; j < recipe.getShape().length; j++) { for (int k = 0; k < recipe.getShape()[j].length(); k++) { - ItemStack item = recipe.getIngredientMap().get(recipe.getShape()[j].toCharArray()[k]); + final ItemStack item = recipe.getIngredientMap().get(recipe.getShape()[j].toCharArray()[k]); materials[j][k] = item == null ? null : item.getType(); } } @@ -133,8 +138,8 @@ public class Commandrecipe extends EssentialsCommand { sender.sendMessage(tl("recipeGrid", colorMap.get(materials[1][0]), colorMap.get(materials[1][1]), colorMap.get(materials[1][2]))); sender.sendMessage(tl("recipeGrid", colorMap.get(materials[2][0]), colorMap.get(materials[2][1]), colorMap.get(materials[2][2]))); - StringBuilder s = new StringBuilder(); - for (Material items : colorMap.keySet().toArray(new Material[0])) { + final StringBuilder s = new StringBuilder(); + for (final Material items : colorMap.keySet().toArray(new Material[0])) { s.append(tl("recipeGridItem", colorMap.get(items), getMaterialName(items))); } sender.sendMessage(tl("recipeWhere", s.toString())); @@ -156,7 +161,7 @@ public class Commandrecipe extends EssentialsCommand { } } else { - StringBuilder s = new StringBuilder(); + final StringBuilder s = new StringBuilder(); for (int i = 0; i < ingredients.size(); i++) { s.append(getMaterialName(ingredients.get(i))); if (i != ingredients.size() - 1) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandremove.java b/Essentials/src/com/earth2me/essentials/commands/Commandremove.java index 72bafe236..878497416 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandremove.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandremove.java @@ -1,15 +1,35 @@ package com.earth2me.essentials.commands; -import com.google.common.collect.Lists; - import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.Mob; import com.earth2me.essentials.User; +import com.google.common.collect.Lists; import org.bukkit.Chunk; import org.bukkit.OfflinePlayer; import org.bukkit.Server; import org.bukkit.World; -import org.bukkit.entity.*; +import org.bukkit.entity.Ambient; +import org.bukkit.entity.Animals; +import org.bukkit.entity.Boat; +import org.bukkit.entity.ComplexLivingEntity; +import org.bukkit.entity.EnderCrystal; +import org.bukkit.entity.Entity; +import org.bukkit.entity.ExperienceOrb; +import org.bukkit.entity.Flying; +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.Monster; +import org.bukkit.entity.NPC; +import org.bukkit.entity.Painting; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.entity.Slime; +import org.bukkit.entity.Snowman; +import org.bukkit.entity.Tameable; +import org.bukkit.entity.WaterMob; import java.util.ArrayList; import java.util.Collections; @@ -35,7 +55,7 @@ public class Commandremove extends EssentialsCommand { if (args.length >= 2) { try { radius = Integer.parseInt(args[1]); - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { world = ess.getWorld(args[1]); } } @@ -53,13 +73,13 @@ public class Commandremove extends EssentialsCommand { if (args.length < 2) { throw new NotEnoughArgumentsException(); } - World world = ess.getWorld(args[1]); + final World world = ess.getWorld(args[1]); parseCommand(server, sender, args, world, 0); } - private void parseCommand(Server server, CommandSource sender, String[] args, World world, int radius) throws Exception { - List types = new ArrayList<>(); - List customTypes = new ArrayList<>(); + private void parseCommand(final Server server, final CommandSource sender, final String[] args, final World world, final int radius) throws Exception { + final List types = new ArrayList<>(); + final List customTypes = new ArrayList<>(); if (world == null) { throw new Exception(tl("invalidWorld")); @@ -68,14 +88,14 @@ public class Commandremove extends EssentialsCommand { if (args[0].contentEquals("*") || args[0].contentEquals("all")) { types.add(0, "ALL"); } else { - for (String entityType : args[0].split(",")) { + for (final String entityType : args[0].split(",")) { ToRemove toRemove; try { toRemove = ToRemove.valueOf(entityType.toUpperCase(Locale.ENGLISH)); - } catch (Exception e) { + } catch (final Exception e) { try { toRemove = ToRemove.valueOf(entityType.concat("S").toUpperCase(Locale.ENGLISH)); - } catch (Exception ee) { + } catch (final Exception ee) { toRemove = ToRemove.CUSTOM; customTypes.add(entityType); } @@ -86,23 +106,23 @@ public class Commandremove extends EssentialsCommand { removeHandler(sender, types, customTypes, world, radius); } - private void removeHandler(CommandSource sender, List types, List customTypes, World world, int radius) { + private void removeHandler(final CommandSource sender, final List types, final List customTypes, final World world, int radius) { int removed = 0; if (radius > 0) { radius *= radius; } - ArrayList removeTypes = new ArrayList<>(); - ArrayList customRemoveTypes = new ArrayList<>(); + final ArrayList removeTypes = new ArrayList<>(); + final ArrayList customRemoveTypes = new ArrayList<>(); - for (String s : types) { + for (final String s : types) { removeTypes.add(ToRemove.valueOf(s)); } boolean warnUser = false; - for (String s : customTypes) { - Mob mobType = Mob.fromName(s); + for (final String s : customTypes) { + final Mob mobType = Mob.fromName(s); if (mobType == null) { warnUser = true; } else { @@ -114,8 +134,8 @@ public class Commandremove extends EssentialsCommand { sender.sendMessage(tl("invalidMob")); } - for (Chunk chunk : world.getLoadedChunks()) { - for (Entity e : chunk.getEntities()) { + for (final Chunk chunk : world.getLoadedChunks()) { + for (final Entity e : chunk.getEntities()) { if (radius > 0) { if (sender.getPlayer().getLocation().distanceSquared(e.getLocation()) > radius) { continue; @@ -125,7 +145,7 @@ public class Commandremove extends EssentialsCommand { continue; } - for (ToRemove toRemove : removeTypes) { + for (final ToRemove toRemove : removeTypes) { // We should skip any animals tamed by players unless we are specifially targetting them. if (e instanceof Tameable && ((Tameable) e).isTamed() && (((Tameable) e).getOwner() instanceof Player || ((Tameable) e).getOwner() instanceof OfflinePlayer) && !removeTypes.contains(ToRemove.TAMED)) { @@ -230,7 +250,7 @@ public class Commandremove extends EssentialsCommand { removed++; break; case CUSTOM: - for (Mob type : customRemoveTypes) { + for (final Mob type : customRemoveTypes) { if (e.getType() == type.getType()) { e.remove(); removed++; @@ -245,16 +265,16 @@ public class Commandremove extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { - List options = Lists.newArrayList(); - for (ToRemove toRemove : ToRemove.values()) { + final List options = Lists.newArrayList(); + for (final ToRemove toRemove : ToRemove.values()) { options.add(toRemove.name().toLowerCase(Locale.ENGLISH)); } return options; } else if (args.length == 2) { - List worlds = Lists.newArrayList(); - for (World world : server.getWorlds()) { + final List worlds = Lists.newArrayList(); + for (final World world : server.getWorlds()) { worlds.add(world.getName()); } return worlds; @@ -284,4 +304,4 @@ public class Commandremove extends EssentialsCommand { TAMED, NAMED } -} \ No newline at end of file +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandrepair.java b/Essentials/src/com/earth2me/essentials/commands/Commandrepair.java index b72f3a057..252a23036 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandrepair.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandrepair.java @@ -18,7 +18,6 @@ import java.util.Locale; import static com.earth2me.essentials.I18n.tl; - public class Commandrepair extends EssentialsCommand { public Commandrepair() { super("repair"); @@ -38,7 +37,7 @@ public class Commandrepair extends EssentialsCommand { } } - public void repairHand(User user) throws Exception { + public void repairHand(final User user) throws Exception { final ItemStack item = user.getItemInHand(); if (item == null || item.getType().isBlock() || item.getDurability() == 0) { throw new Exception(tl("repairInvalidType")); @@ -60,7 +59,7 @@ public class Commandrepair extends EssentialsCommand { user.sendMessage(tl("repair", itemName.replace('_', ' '))); } - public void repairAll(User user) throws Exception { + public void repairAll(final User user) throws Exception { final List repaired = new ArrayList<>(); repairItems(user.getBase().getInventory().getContents(), user, repaired); @@ -90,7 +89,7 @@ public class Commandrepair extends EssentialsCommand { } private void repairItems(final ItemStack[] items, final IUser user, final List repaired) throws Exception { - for (ItemStack item : items) { + for (final ItemStack item : items) { if (item == null || item.getType().isBlock() || item.getDurability() == 0) { continue; } @@ -100,7 +99,7 @@ public class Commandrepair extends EssentialsCommand { try { charge.isAffordableFor(user); - } catch (ChargeException ex) { + } catch (final ChargeException ex) { user.sendMessage(ex.getMessage()); continue; } @@ -110,12 +109,12 @@ public class Commandrepair extends EssentialsCommand { try { repairItem(item); - } catch (Exception e) { + } catch (final Exception e) { continue; } try { charge.charge(user); - } catch (ChargeException ex) { + } catch (final ChargeException ex) { user.sendMessage(ex.getMessage()); } repaired.add(itemName.replace('_', ' ')); @@ -133,9 +132,9 @@ public class Commandrepair extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { - List options = Lists.newArrayList("hand"); + final List options = Lists.newArrayList("hand"); if (user.isAuthorized("essentials.repair.all")) { options.add("all"); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandrest.java b/Essentials/src/com/earth2me/essentials/commands/Commandrest.java index 0de6ee797..451371972 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandrest.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandrest.java @@ -45,7 +45,7 @@ public class Commandrest extends EssentialsLoopCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1 && sender.isAuthorized("essentials.rest.others", ess)) { return getPlayers(server, sender); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandrtoggle.java b/Essentials/src/com/earth2me/essentials/commands/Commandrtoggle.java index f3a52a10b..2b7886abc 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandrtoggle.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandrtoggle.java @@ -12,17 +12,17 @@ public class Commandrtoggle extends EssentialsToggleCommand { } @Override - public void run(Server server, User user, String commandLabel, String[] args) throws Exception { + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { handleToggleWithArgs(server, user, args); } @Override - public void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception { + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { toggleOtherPlayers(server, sender, args); } @Override - void togglePlayer(CommandSource sender, User user, Boolean enabled) { + void togglePlayer(final CommandSource sender, final User user, Boolean enabled) { if (enabled == null) { enabled = !user.isLastMessageReplyRecipient(); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandrules.java b/Essentials/src/com/earth2me/essentials/commands/Commandrules.java index 353bedb40..e5338ccac 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandrules.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandrules.java @@ -6,7 +6,6 @@ import com.earth2me.essentials.textreader.TextInput; import com.earth2me.essentials.textreader.TextPager; import org.bukkit.Server; - public class Commandrules extends EssentialsCommand { public Commandrules() { super("rules"); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandseen.java b/Essentials/src/com/earth2me/essentials/commands/Commandseen.java index cded5b473..9580b8883 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandseen.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandseen.java @@ -13,14 +13,13 @@ import org.bukkit.Location; import org.bukkit.Server; import java.util.ArrayList; +import java.util.Collections; import java.util.Date; import java.util.List; import java.util.UUID; -import java.util.Collections; import static com.earth2me.essentials.I18n.tl; - public class Commandseen extends EssentialsCommand { public Commandseen() { super("seen"); @@ -28,18 +27,18 @@ public class Commandseen extends EssentialsCommand { @Override protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { - boolean showBan = sender.isAuthorized("essentials.seen.banreason", ess); - boolean showIp = sender.isAuthorized("essentials.seen.ip", ess); - boolean showLocation = sender.isAuthorized("essentials.seen.location", ess); + final boolean showBan = sender.isAuthorized("essentials.seen.banreason", ess); + final boolean showIp = sender.isAuthorized("essentials.seen.ip", ess); + final boolean showLocation = sender.isAuthorized("essentials.seen.location", ess); if (args.length < 1) { throw new NotEnoughArgumentsException(); } User player; // Check by uuid, if it fails check by name. try { - UUID uuid = UUID.fromString(args[0]); + final UUID uuid = UUID.fromString(args[0]); player = ess.getUser(uuid); - } catch (IllegalArgumentException ignored) { // Thrown if invalid UUID from string, check by name. + } catch (final IllegalArgumentException ignored) { // Thrown if invalid UUID from string, check by name. player = ess.getOfflineUser(args[0]); } @@ -57,23 +56,23 @@ public class Commandseen extends EssentialsCommand { ess.getScheduler().runTaskAsynchronously(ess, new Runnable() { @Override public void run() { - User userFromBukkit = ess.getUserMap().getUserFromBukkit(args[0]); + final User userFromBukkit = ess.getUserMap().getUserFromBukkit(args[0]); try { if (userFromBukkit != null) { showUserSeen(userFromBukkit); } else { try { showUserSeen(getPlayer(server, sender, args, 0)); - } catch (PlayerNotFoundException e) { + } catch (final PlayerNotFoundException e) { throw new Exception(tl("playerNeverOnServer", args[0])); } } - } catch (Exception e) { + } catch (final Exception e) { ess.showError(sender, e, commandLabel); } } - private void showUserSeen(User user) throws Exception { + private void showUserSeen(final User user) throws Exception { showSeenMessage(sender, user, showBan, showIp, showLocation); } }); @@ -82,7 +81,7 @@ public class Commandseen extends EssentialsCommand { } } - private void showSeenMessage(CommandSource sender, User player, boolean showBan, boolean showIp, boolean showLocation) { + private void showSeenMessage(final CommandSource sender, final User player, final boolean showBan, final boolean showIp, final boolean showLocation) { if (player.getBase().isOnline() && canInteractWith(sender, player)) { seenOnline(sender, player, showIp); } else { @@ -99,7 +98,7 @@ public class Commandseen extends EssentialsCommand { ess.getLogger().info("UUID: " + user.getBase().getUniqueId().toString()); } - List history = ess.getUserMap().getUserHistory(user.getBase().getUniqueId()); + final List history = ess.getUserMap().getUserHistory(user.getBase().getUniqueId()); if (history != null && history.size() > 1) { sender.sendMessage(tl("seenAccounts", StringUtil.joinListSkip(", ", user.getName(), history))); } @@ -108,18 +107,18 @@ public class Commandseen extends EssentialsCommand { sender.sendMessage(tl("whoisAFK", tl("true"))); } if (user.isJailed()) { - sender.sendMessage(tl("whoisJail", (user.getJailTimeout() > 0 ? DateUtil.formatDateDiff(user.getJailTimeout()) : tl("true")))); + sender.sendMessage(tl("whoisJail", user.getJailTimeout() > 0 ? DateUtil.formatDateDiff(user.getJailTimeout()) : tl("true"))); } if (user.isMuted()) { - long muteTimeout = user.getMuteTimeout(); + final long muteTimeout = user.getMuteTimeout(); if (!user.hasMuteReason()) { - sender.sendMessage(tl("whoisMuted", (muteTimeout > 0 ? DateUtil.formatDateDiff(muteTimeout) : tl("true")))); + sender.sendMessage(tl("whoisMuted", muteTimeout > 0 ? DateUtil.formatDateDiff(muteTimeout) : tl("true"))); } else { - sender.sendMessage(tl("whoisMutedReason", (muteTimeout > 0 ? DateUtil.formatDateDiff(muteTimeout) : tl("true")), user.getMuteReason())); + sender.sendMessage(tl("whoisMutedReason", muteTimeout > 0 ? DateUtil.formatDateDiff(muteTimeout) : tl("true"), user.getMuteReason())); } } final String location = user.getGeoLocation(); - if (location != null && (!(sender.isPlayer()) || ess.getUser(sender.getPlayer()).isAuthorized("essentials.geoip.show"))) { + if (location != null && (!sender.isPlayer() || ess.getUser(sender.getPlayer()).isAuthorized("essentials.geoip.show"))) { sender.sendMessage(tl("whoisGeoLocation", location)); } if (showIp) { @@ -127,7 +126,7 @@ public class Commandseen extends EssentialsCommand { } } - private void seenOffline(final CommandSource sender, User user, final boolean showBan, final boolean showIp, final boolean showLocation) { + private void seenOffline(final CommandSource sender, final User user, final boolean showBan, final boolean showIp, final boolean showLocation) { user.setDisplayNick(); if (user.getLastLogout() > 0) { sender.sendMessage(tl("seenOffline", user.getName(), DateUtil.formatDateDiff(user.getLastLogout()))); @@ -139,7 +138,7 @@ public class Commandseen extends EssentialsCommand { ess.getLogger().info("UUID: " + user.getBase().getUniqueId().toString()); } - List history = ess.getUserMap().getUserHistory(user.getBase().getUniqueId()); + final List history = ess.getUserMap().getUserHistory(user.getBase().getUniqueId()); if (history != null && history.size() > 1) { sender.sendMessage(tl("seenAccounts", StringUtil.joinListSkip(", ", user.getName(), history))); } @@ -149,7 +148,7 @@ public class Commandseen extends EssentialsCommand { final String reason = showBan ? banEntry.getReason() : tl("true"); sender.sendMessage(tl("whoisBanned", reason)); if (banEntry.getExpiration() != null) { - Date expiry = banEntry.getExpiration(); + final Date expiry = banEntry.getExpiration(); String expireString = tl("now"); if (expiry.after(new Date())) { expireString = DateUtil.formatDateDiff(expiry.getTime()); @@ -159,16 +158,16 @@ public class Commandseen extends EssentialsCommand { } if (user.isMuted()) { - long muteTimeout = user.getMuteTimeout(); + final long muteTimeout = user.getMuteTimeout(); if (!user.hasMuteReason()) { - sender.sendMessage(tl("whoisMuted", (muteTimeout > 0 ? DateUtil.formatDateDiff(muteTimeout) : tl("true")))); + sender.sendMessage(tl("whoisMuted", muteTimeout > 0 ? DateUtil.formatDateDiff(muteTimeout) : tl("true"))); } else { - sender.sendMessage(tl("whoisMutedReason", (muteTimeout > 0 ? DateUtil.formatDateDiff(muteTimeout) : tl("true")), user.getMuteReason())); + sender.sendMessage(tl("whoisMutedReason", muteTimeout > 0 ? DateUtil.formatDateDiff(muteTimeout) : tl("true"), user.getMuteReason())); } } final String location = user.getGeoLocation(); - if (location != null && (!(sender.isPlayer()) || ess.getUser(sender.getPlayer()).isAuthorized("essentials.geoip.show"))) { + if (location != null && (!sender.isPlayer() || ess.getUser(sender.getPlayer()).isAuthorized("essentials.geoip.show"))) { sender.sendMessage(tl("whoisGeoLocation", location)); } if (showIp) { @@ -220,7 +219,7 @@ public class Commandseen extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { return getPlayers(server, sender); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsell.java b/Essentials/src/com/earth2me/essentials/commands/Commandsell.java index 0032c003f..6e36d3068 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsell.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsell.java @@ -18,7 +18,6 @@ import java.util.logging.Level; import static com.earth2me.essentials.I18n.tl; - public class Commandsell extends EssentialsCommand { public Commandsell() { super("sell"); @@ -37,12 +36,12 @@ public class Commandsell extends EssentialsCommand { throw new Exception(tl("sellBulkPermission")); } - List is = ess.getItemDb().getMatching(user, args); + final List is = ess.getItemDb().getMatching(user, args); int count = 0; - boolean isBulk = is.size() > 1; + final boolean isBulk = is.size() > 1; - List notSold = new ArrayList<>(); + final List notSold = new ArrayList<>(); for (ItemStack stack : is) { if (!ess.getSettings().isAllowSellNamedItems()) { if (stack.getItemMeta() != null && stack.getItemMeta().hasDisplayName()) { @@ -58,21 +57,21 @@ public class Commandsell extends EssentialsCommand { totalWorth = totalWorth.add(sellItem(user, stack, args, isBulk)); stack = stack.clone(); count++; - for (ItemStack zeroStack : is) { + for (final ItemStack zeroStack : is) { if (zeroStack.isSimilar(stack)) { zeroStack.setAmount(0); } } } - } catch (Exception e) { + } catch (final Exception e) { if (!isBulk) { throw e; } } } if (!notSold.isEmpty()) { - List names = new ArrayList<>(); - for (ItemStack stack : notSold) { + final List names = new ArrayList<>(); + for (final ItemStack stack : notSold) { if (stack.getItemMeta() != null) { //This was already validated but IDE still freaks out names.add(stack.getItemMeta().getDisplayName()); } @@ -80,7 +79,7 @@ public class Commandsell extends EssentialsCommand { ess.showError(user.getSource(), new Exception(tl("cannotSellTheseNamedItems", String.join(ChatColor.RESET + ", ", names))), commandLabel); } if (count != 1) { - String totalWorthStr = NumberUtil.displayCurrency(totalWorth, ess); + final String totalWorthStr = NumberUtil.displayCurrency(totalWorth, ess); if (args[0].equalsIgnoreCase("blocks")) { user.sendMessage(tl("totalWorthBlocks", totalWorthStr, totalWorthStr)); } else { @@ -89,9 +88,9 @@ public class Commandsell extends EssentialsCommand { } } - private BigDecimal sellItem(User user, ItemStack is, String[] args, boolean isBulkSell) throws Exception { - int amount = ess.getWorth().getAmount(ess, user, is, args, isBulkSell); - BigDecimal worth = ess.getWorth().getPrice(ess, is); + private BigDecimal sellItem(final User user, final ItemStack is, final String[] args, final boolean isBulkSell) throws Exception { + final int amount = ess.getWorth().getAmount(ess, user, is, args, isBulkSell); + final BigDecimal worth = ess.getWorth().getPrice(ess, is); if (worth == null) { throw new Exception(tl("itemCannotBeSold")); @@ -104,7 +103,7 @@ public class Commandsell extends EssentialsCommand { return BigDecimal.ZERO; } - BigDecimal result = worth.multiply(BigDecimal.valueOf(amount)); + final BigDecimal result = worth.multiply(BigDecimal.valueOf(amount)); //TODO: Prices for Enchantments final ItemStack ris = is.clone(); @@ -123,7 +122,7 @@ public class Commandsell extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { return getMatchingItems(args[0]); } else if (args.length == 2) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsethome.java b/Essentials/src/com/earth2me/essentials/commands/Commandsethome.java index 85a7b6f3c..1a9b0f377 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsethome.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsethome.java @@ -14,7 +14,6 @@ import java.util.concurrent.TimeUnit; import static com.earth2me.essentials.I18n.tl; - public class Commandsethome extends EssentialsCommand { public Commandsethome() { super("sethome"); @@ -69,9 +68,9 @@ public class Commandsethome extends EssentialsCommand { } - private boolean checkHomeLimit(final User user, final User usersHome, String name) throws Exception { + private boolean checkHomeLimit(final User user, final User usersHome, final String name) throws Exception { if (!user.isAuthorized("essentials.sethome.multiple.unlimited")) { - int limit = ess.getSettings().getHomeLimit(user); + final int limit = ess.getSettings().getHomeLimit(user); if (usersHome.getHomes().size() == limit && usersHome.getHomes().contains(name)) { return false; } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java b/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java index c6e101a69..38a3ddd61 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java @@ -6,7 +6,6 @@ import org.bukkit.Server; import static com.earth2me.essentials.I18n.tl; - public class Commandsetjail extends EssentialsCommand { public Commandsetjail() { super("setjail"); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsettpr.java b/Essentials/src/com/earth2me/essentials/commands/Commandsettpr.java index 6baaa8ff5..ad65ce016 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsettpr.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsettpr.java @@ -10,15 +10,14 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandsettpr extends EssentialsCommand { public Commandsettpr() { super("settpr"); } @Override - protected void run(Server server, User user, String commandLabel, String[] args) throws Exception { - RandomTeleport randomTeleport = ess.getRandomTeleport(); + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + final RandomTeleport randomTeleport = ess.getRandomTeleport(); randomTeleport.getCachedLocations().clear(); if (args.length == 0 || "center".equalsIgnoreCase(args[0])) { randomTeleport.setCenter(user.getLocation()); @@ -34,7 +33,7 @@ public class Commandsettpr extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { return Arrays.asList("center", "minrange", "maxrange"); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java b/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java index 7ca797492..298205b9d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java @@ -10,7 +10,6 @@ import org.bukkit.Server; import static com.earth2me.essentials.I18n.tl; - public class Commandsetwarp extends EssentialsCommand { public Commandsetwarp() { super("setwarp"); @@ -31,7 +30,7 @@ public class Commandsetwarp extends EssentialsCommand { try { warpLoc = warps.getWarp(args[0]); - } catch (WarpNotFoundException | InvalidWorldException ignored) { + } catch (final WarpNotFoundException | InvalidWorldException ignored) { } if (warpLoc == null || user.isAuthorized("essentials.warp.overwrite." + StringUtil.safeString(args[0]))) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsetworth.java b/Essentials/src/com/earth2me/essentials/commands/Commandsetworth.java index ff0f0343f..19b4fd10e 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsetworth.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsetworth.java @@ -8,7 +8,6 @@ import org.bukkit.inventory.ItemStack; import static com.earth2me.essentials.I18n.tl; - public class Commandsetworth extends EssentialsCommand { public Commandsetworth() { super("setworth"); @@ -20,8 +19,8 @@ public class Commandsetworth extends EssentialsCommand { throw new NotEnoughArgumentsException(); } - ItemStack stack; - String price; + final ItemStack stack; + final String price; if (args.length == 1) { stack = user.getBase().getInventory().getItemInHand(); price = args[0]; diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandshowkit.java b/Essentials/src/com/earth2me/essentials/commands/Commandshowkit.java index 2ba92626b..142b2ec90 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandshowkit.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandshowkit.java @@ -24,7 +24,7 @@ public class Commandshowkit extends EssentialsCommand { for (final String kitName : args[0].toLowerCase(Locale.ENGLISH).split(",")) { user.sendMessage(tl("kitContains", kitName)); - for (String s : new Kit(kitName, ess).getItems()) { + for (final String s : new Kit(kitName, ess).getItems()) { user.sendMessage(tl("kitItem", s)); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandskull.java b/Essentials/src/com/earth2me/essentials/commands/Commandskull.java index 6a310d015..07b9aac8c 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandskull.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandskull.java @@ -28,7 +28,7 @@ public class Commandskull extends EssentialsCommand { @Override protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { - String owner; + final String owner; if (args.length > 0 && user.isAuthorized("essentials.skull.others")) { if (!NAME_PATTERN.matcher(args[0]).matches()) { throw new IllegalArgumentException(tl("alphaNames")); @@ -39,7 +39,7 @@ public class Commandskull extends EssentialsCommand { } ItemStack itemSkull = user.getItemInHand(); - SkullMeta metaSkull; + final SkullMeta metaSkull; boolean spawn = false; if (itemSkull != null && MaterialUtil.isPlayerHead(itemSkull.getType(), itemSkull.getDurability())) { @@ -59,7 +59,7 @@ public class Commandskull extends EssentialsCommand { editSkull(user, itemSkull, metaSkull, owner, spawn); } - private void editSkull(User user, ItemStack stack, SkullMeta skullMeta, String owner, boolean spawn) { + private void editSkull(final User user, final ItemStack stack, final SkullMeta skullMeta, final String owner, final boolean spawn) { new BukkitRunnable() { @Override public void run() { @@ -83,7 +83,7 @@ public class Commandskull extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { if (user.isAuthorized("essentials.skull.others")) { return getPlayers(server, user); @@ -95,4 +95,4 @@ public class Commandskull extends EssentialsCommand { } } -} \ No newline at end of file +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsocialspy.java b/Essentials/src/com/earth2me/essentials/commands/Commandsocialspy.java index d33f3045b..1b4ad84a4 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsocialspy.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsocialspy.java @@ -6,7 +6,6 @@ import org.bukkit.Server; import static com.earth2me.essentials.I18n.tl; - public class Commandsocialspy extends EssentialsToggleCommand { public Commandsocialspy() { super("socialspy", "essentials.socialspy.others"); @@ -23,7 +22,7 @@ public class Commandsocialspy extends EssentialsToggleCommand { } @Override - protected void togglePlayer(CommandSource sender, User user, Boolean enabled) { + protected void togglePlayer(final CommandSource sender, final User user, Boolean enabled) { if (enabled == null) { enabled = !user.isSocialSpyEnabled(); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java b/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java index f47a9b622..b5c26e989 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java @@ -17,7 +17,6 @@ import java.util.Locale; import static com.earth2me.essentials.I18n.tl; - public class Commandspawner extends EssentialsCommand { private static final Material MOB_SPAWNER = EnumUtil.getMaterial("SPAWNER", "MOB_SPAWNER"); @@ -38,10 +37,10 @@ public class Commandspawner extends EssentialsCommand { throw new Exception(tl("mobSpawnTarget")); } - String name = args[0]; + final String name = args[0]; int delay = 0; - Mob mob = Mob.fromName(name); + final Mob mob = Mob.fromName(name); if (mob == null) { throw new Exception(tl("invalidMob")); } @@ -59,10 +58,10 @@ public class Commandspawner extends EssentialsCommand { final Trade charge = new Trade("spawner-" + mob.name.toLowerCase(Locale.ENGLISH), ess); charge.isAffordableFor(user); try { - CreatureSpawner spawner = (CreatureSpawner) target.getBlock().getState(); + final CreatureSpawner spawner = (CreatureSpawner) target.getBlock().getState(); spawner.setSpawnedType(mob.getType()); if (delay > 0) { - SpawnerBlockProvider spawnerBlockProvider = ess.getSpawnerBlockProvider(); + final SpawnerBlockProvider spawnerBlockProvider = ess.getSpawnerBlockProvider(); spawnerBlockProvider.setMinSpawnDelay(spawner, 1); spawnerBlockProvider.setMaxSpawnDelay(spawner, Integer.MAX_VALUE); spawnerBlockProvider.setMinSpawnDelay(spawner, delay); @@ -70,7 +69,7 @@ public class Commandspawner extends EssentialsCommand { } spawner.setDelay(delay); spawner.update(); - } catch (Throwable ex) { + } catch (final Throwable ex) { throw new Exception(tl("mobSpawnError"), ex); } charge.charge(user); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java b/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java index 84df7e147..7ba695978 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java @@ -13,7 +13,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandspawnmob extends EssentialsCommand { public Commandspawnmob() { super("spawnmob"); @@ -25,8 +24,8 @@ public class Commandspawnmob extends EssentialsCommand { throw new NotEnoughArgumentsException(tl("mobsAvailable", StringUtil.joinList(Mob.getMobList()))); } - List mobParts = SpawnMob.mobParts(args[0]); - List mobData = SpawnMob.mobData(args[0]); + final List mobParts = SpawnMob.mobParts(args[0]); + final List mobData = SpawnMob.mobData(args[0]); int mobCount = 1; if (args.length >= 2) { @@ -51,14 +50,14 @@ public class Commandspawnmob extends EssentialsCommand { throw new NotEnoughArgumentsException(tl("mobsAvailable", StringUtil.joinList(Mob.getMobList()))); } - List mobParts = SpawnMob.mobParts(args[0]); - List mobData = SpawnMob.mobData(args[0]); + final List mobParts = SpawnMob.mobParts(args[0]); + final List mobData = SpawnMob.mobData(args[0]); SpawnMob.spawnmob(ess, server, sender, getPlayer(ess.getServer(), args, 2, true, false), mobParts, mobData, Integer.parseInt(args[1])); } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { return Lists.newArrayList(Mob.getMobList()); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandspeed.java b/Essentials/src/com/earth2me/essentials/commands/Commandspeed.java index 6ebd03a52..c47b73bc7 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandspeed.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandspeed.java @@ -12,7 +12,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandspeed extends EssentialsCommand { private static final List types = Arrays.asList("walk", "fly", "1", "1.5", "1.75", "2"); private static final List speeds = Arrays.asList("1", "1.5", "1.75", "2"); @@ -35,9 +34,9 @@ public class Commandspeed extends EssentialsCommand { throw new NotEnoughArgumentsException(); } - boolean isFly; - float speed; - boolean isBypass = user.isAuthorized("essentials.speed.bypass"); + final boolean isFly; + final float speed; + final boolean isBypass = user.isAuthorized("essentials.speed.bypass"); if (args.length == 1) { isFly = flyPermCheck(user, user.getBase().isFlying()); speed = getMoveSpeed(args[0]); @@ -63,10 +62,10 @@ public class Commandspeed extends EssentialsCommand { } private void speedOtherPlayers(final Server server, final CommandSource sender, final boolean isFly, final boolean isBypass, final float speed, final String name) throws PlayerNotFoundException { - boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); + final boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); boolean foundUser = false; final List matchedPlayers = server.matchPlayer(name); - for (Player matchPlayer : matchedPlayers) { + for (final Player matchPlayer : matchedPlayers) { final User player = ess.getUser(matchPlayer); if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer)) { continue; @@ -85,16 +84,16 @@ public class Commandspeed extends EssentialsCommand { } } - private Boolean flyPermCheck(User user, boolean input) { - boolean canFly = user.isAuthorized("essentials.speed.fly"); - boolean canWalk = user.isAuthorized("essentials.speed.walk"); + private Boolean flyPermCheck(final User user, final boolean input) { + final boolean canFly = user.isAuthorized("essentials.speed.fly"); + final boolean canWalk = user.isAuthorized("essentials.speed.walk"); if (input && canFly || !input && canWalk || !canFly && !canWalk) { return input; } else return !canWalk; } private boolean isFlyMode(final String modeString) throws NotEnoughArgumentsException { - boolean isFlyMode; + final boolean isFlyMode; if (modeString.contains("fly") || modeString.equalsIgnoreCase("f")) { isFlyMode = true; } else if (modeString.contains("walk") || modeString.contains("run") || modeString.equalsIgnoreCase("w") || modeString.equalsIgnoreCase("r")) { @@ -114,7 +113,7 @@ public class Commandspeed extends EssentialsCommand { } else if (userSpeed < 0.0001f) { userSpeed = 0.0001f; } - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { throw new NotEnoughArgumentsException(); } return userSpeed; @@ -130,13 +129,13 @@ public class Commandspeed extends EssentialsCommand { if (userSpeed < 1f) { return defaultSpeed * userSpeed; } else { - float ratio = ((userSpeed - 1) / 9) * (maxSpeed - defaultSpeed); + final float ratio = ((userSpeed - 1) / 9) * (maxSpeed - defaultSpeed); return ratio + defaultSpeed; } } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { return types; } else if (args.length == 2) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsudo.java b/Essentials/src/com/earth2me/essentials/commands/Commandsudo.java index 1a1710b94..df264f4dd 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsudo.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsudo.java @@ -8,7 +8,6 @@ import java.util.Locale; import static com.earth2me.essentials.I18n.tl; - public class Commandsudo extends EssentialsLoopCommand { public Commandsudo() { super("sudo"); @@ -21,14 +20,14 @@ public class Commandsudo extends EssentialsLoopCommand { } final String command = getFinalArg(args, 1); - boolean multiple = !sender.isPlayer() || ess.getUser(sender.getPlayer()).isAuthorized("essentials.sudo.multiple"); + final boolean multiple = !sender.isPlayer() || ess.getUser(sender.getPlayer()).isAuthorized("essentials.sudo.multiple"); sender.sendMessage(tl("sudoRun", args[0], command, "")); - loopOnlinePlayers(server, sender, false, multiple, args[0], new String[]{command}); + loopOnlinePlayers(server, sender, false, multiple, args[0], new String[] {command}); } @Override - protected void updatePlayer(final Server server, final CommandSource sender, final User user, String[] args) { + protected void updatePlayer(final Server server, final CommandSource sender, final User user, final String[] args) { if (user.getName().equals(sender.getSender().getName())) { return; // Silently don't do anything. } @@ -50,11 +49,12 @@ public class Commandsudo extends EssentialsLoopCommand { public void run() { try { user.getBase().chat("/" + command); - } catch (Exception e) { + } catch (final Exception e) { sender.sendMessage(tl("errorCallingCommand", command)); } } } + ess.scheduleSyncDelayedTask(new SudoCommandTask()); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java b/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java index 41d613b87..2e0a1e8ba 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java @@ -9,7 +9,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandsuicide extends EssentialsCommand { public Commandsuicide() { super("suicide"); @@ -17,7 +16,7 @@ public class Commandsuicide extends EssentialsCommand { @Override public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { - EntityDamageEvent ede = new EntityDamageEvent(user.getBase(), EntityDamageEvent.DamageCause.SUICIDE, Float.MAX_VALUE); + final EntityDamageEvent ede = new EntityDamageEvent(user.getBase(), EntityDamageEvent.DamageCause.SUICIDE, Float.MAX_VALUE); server.getPluginManager().callEvent(ede); ede.getEntity().setLastDamageCause(ede); user.getBase().setHealth(0); @@ -27,7 +26,7 @@ public class Commandsuicide extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { return Collections.emptyList(); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java b/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java index c00b213d2..96fd4a4ce 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java @@ -14,7 +14,6 @@ import java.util.logging.Level; import static com.earth2me.essentials.I18n.tl; - public class Commandtempban extends EssentialsCommand { public Commandtempban() { super("tempban"); @@ -38,7 +37,7 @@ public class Commandtempban extends EssentialsCommand { String banReason = DateUtil.removeTimePattern(time); final long maxBanLength = ess.getSettings().getMaxTempban() * 1000; - if (maxBanLength > 0 && ((banTimestamp - GregorianCalendar.getInstance().getTimeInMillis()) > maxBanLength) && sender.isPlayer() && !(ess.getUser(sender.getPlayer()).isAuthorized("essentials.tempban.unlimited"))) { + if (maxBanLength > 0 && ((banTimestamp - GregorianCalendar.getInstance().getTimeInMillis()) > maxBanLength) && sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.tempban.unlimited")) { sender.sendMessage(tl("oversizedTempban")); return; } @@ -59,7 +58,7 @@ public class Commandtempban extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { return getPlayers(server, sender); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtempbanip.java b/Essentials/src/com/earth2me/essentials/commands/Commandtempbanip.java index 2e1702257..d246bf679 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtempbanip.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtempbanip.java @@ -34,9 +34,9 @@ public class Commandtempbanip extends EssentialsCommand { ipAddress = args[0]; } else { try { - User player = getPlayer(server, args, 0, true, true); + final User player = getPlayer(server, args, 0, true, true); ipAddress = player.getLastLoginAddress(); - } catch (PlayerNotFoundException ex) { + } catch (final PlayerNotFoundException ex) { ipAddress = args[0]; } } @@ -50,7 +50,7 @@ public class Commandtempbanip extends EssentialsCommand { String banReason = DateUtil.removeTimePattern(time); final long maxBanLength = ess.getSettings().getMaxTempban() * 1000; - if (maxBanLength > 0 && ((banTimestamp - GregorianCalendar.getInstance().getTimeInMillis()) > maxBanLength) && sender.isPlayer() && !(ess.getUser(sender.getPlayer()).isAuthorized("essentials.tempban.unlimited"))) { + if (maxBanLength > 0 && ((banTimestamp - GregorianCalendar.getInstance().getTimeInMillis()) > maxBanLength) && sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.tempban.unlimited")) { sender.sendMessage(tl("oversizedTempban")); return; } @@ -61,20 +61,20 @@ public class Commandtempbanip extends EssentialsCommand { ess.getServer().getBanList(BanList.Type.IP).addBan(ipAddress, banReason, new Date(banTimestamp), senderName); - String banDisplay = tl("banFormat", banReason, senderName); - for (Player player : ess.getServer().getOnlinePlayers()) { + final String banDisplay = tl("banFormat", banReason, senderName); + for (final Player player : ess.getServer().getOnlinePlayers()) { if (player.getAddress().getAddress().getHostAddress().equalsIgnoreCase(ipAddress)) { player.kickPlayer(banDisplay); } } - String message = tl("playerTempBanIpAddress", senderName, ipAddress, DateUtil.formatDateDiff(banTimestamp), banReason); + final String message = tl("playerTempBanIpAddress", senderName, ipAddress, DateUtil.formatDateDiff(banTimestamp), banReason); server.getLogger().log(Level.INFO, message); ess.broadcastMessage("essentials.banip.notify", message); } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { // TODO: Also list IP addresses? return getPlayers(server, sender); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandthunder.java b/Essentials/src/com/earth2me/essentials/commands/Commandthunder.java index 2265b5969..48758b435 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandthunder.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandthunder.java @@ -10,7 +10,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandthunder extends EssentialsCommand { public Commandthunder() { super("thunder"); @@ -32,11 +31,11 @@ public class Commandthunder extends EssentialsCommand { world.setThundering(setThunder); world.setThunderDuration(Integer.parseInt(args[1]) * 20); - user.sendMessage(tl("thunderDuration", (setThunder ? tl("enabled") : tl("disabled")), Integer.parseInt(args[1]))); + user.sendMessage(tl("thunderDuration", setThunder ? tl("enabled") : tl("disabled"), Integer.parseInt(args[1]))); } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { return Lists.newArrayList("true", "false"); } else if (args.length == 2) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtime.java b/Essentials/src/com/earth2me/essentials/commands/Commandtime.java index 1151abee0..99a6d7e62 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtime.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtime.java @@ -20,21 +20,19 @@ import java.util.TreeSet; import static com.earth2me.essentials.I18n.tl; - public class Commandtime extends EssentialsCommand { private final List subCommands = Arrays.asList("add", "set"); private final List timeNames = Arrays.asList("sunrise", "day", "morning", "noon", "afternoon", "sunset", "night", "midnight"); private final List timeNumbers = Arrays.asList("1000", "2000", "3000", "4000", "5000"); - public Commandtime() { super("time"); } @Override public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { - long timeTick; - Set worlds; + final long timeTick; + final Set worlds; boolean add = false; if (args.length == 0) { worlds = getWorlds(server, sender, null); @@ -48,7 +46,7 @@ public class Commandtime extends EssentialsCommand { worlds = getWorlds(server, sender, null); try { timeTick = DescParseTickFormat.parse(NumberUtil.isInt(args[0]) ? (args[0] + "t") : args[0]); - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { throw new NotEnoughArgumentsException(e); } } else { @@ -57,14 +55,14 @@ public class Commandtime extends EssentialsCommand { add = args[0].equalsIgnoreCase("add"); timeTick = DescParseTickFormat.parse(NumberUtil.isInt(args[1]) ? (args[1] + "t") : args[1]); worlds = getWorlds(server, sender, args.length > 2 ? args[2] : null); - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { throw new NotEnoughArgumentsException(e); } } else { try { timeTick = DescParseTickFormat.parse(NumberUtil.isInt(args[0]) ? (args[0] + "t") : args[0]); worlds = getWorlds(server, sender, args[1]); - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { throw new NotEnoughArgumentsException(e); } } @@ -75,7 +73,7 @@ public class Commandtime extends EssentialsCommand { throw new Exception(tl("timeSetPermission")); } - for (World world : worlds) { + for (final World world : worlds) { if (!canUpdateWorld(sender, world)) { //We can ensure that this is User as the console has all permissions (for essentials commands). throw new Exception(tl("timeSetWorldPermission", sender.getUser(ess).getBase().getWorld().getName())); @@ -83,7 +81,7 @@ public class Commandtime extends EssentialsCommand { } final StringJoiner joiner = new StringJoiner(","); - for (World world : worlds) { + for (final World world : worlds) { long time = world.getTime(); if (!add) { time -= time % 24000; @@ -102,7 +100,7 @@ public class Commandtime extends EssentialsCommand { return; } - for (World world : worlds) { + for (final World world : worlds) { sender.sendMessage(tl("timeWorldCurrent", world.getName(), DescParseTickFormat.format(world.getTime()))); } } @@ -134,22 +132,22 @@ public class Commandtime extends EssentialsCommand { } return worlds; } - - private boolean canUpdateAll(CommandSource sender) { + + private boolean canUpdateAll(final CommandSource sender) { return !ess.getSettings().isWorldTimePermissions() // First check if per world permissions are enabled, if not, return true. || sender.isAuthorized("essentials.time.world.all", ess); } - private boolean canUpdateWorld(CommandSource sender, World world) { + private boolean canUpdateWorld(final CommandSource sender, final World world) { return canUpdateAll(sender) || sender.isAuthorized("essentials.time.world." + normalizeWorldName(world), ess); } - private String normalizeWorldName(World world) { + private String normalizeWorldName(final World world) { return world.getName().toLowerCase().replaceAll("\\s+", "_"); } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { if (sender.isAuthorized("essentials.time.set", ess)) { return subCommands; @@ -165,8 +163,8 @@ public class Commandtime extends EssentialsCommand { return Collections.emptyList(); } } else if (args.length == 3 && (args[0].equalsIgnoreCase("set") || args[0].equalsIgnoreCase("add"))) { - List worlds = Lists.newArrayList(); - for (World world : server.getWorlds()) { + final List worlds = Lists.newArrayList(); + for (final World world : server.getWorlds()) { if (sender.isAuthorized("essentials.time.world." + normalizeWorldName(world), ess)) { worlds.add(world.getName()); } @@ -181,7 +179,6 @@ public class Commandtime extends EssentialsCommand { } } - class WorldNameComparator implements Comparator { @Override public int compare(final World a, final World b) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java b/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java index a2481b59c..576963259 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java @@ -14,7 +14,6 @@ import java.util.concurrent.CompletableFuture; import static com.earth2me.essentials.I18n.tl; - public class Commandtogglejail extends EssentialsCommand { public Commandtogglejail() { super("togglejail"); @@ -52,7 +51,7 @@ public class Commandtogglejail extends EssentialsCommand { } final long timeDiff = preTimeDiff; - CompletableFuture future = getNewExceptionFuture(sender, commandLabel); + final CompletableFuture future = getNewExceptionFuture(sender, commandLabel); future.thenAccept(success -> { if (success) { player.setJailed(true); @@ -62,7 +61,7 @@ public class Commandtogglejail extends EssentialsCommand { if (args.length > 2) { player.setJailTimeout(timeDiff); } - sender.sendMessage((timeDiff > 0 ? tl("playerJailedFor", player.getName(), DateUtil.formatDateDiff(timeDiff)) : tl("playerJailed", player.getName()))); + sender.sendMessage(timeDiff > 0 ? tl("playerJailedFor", player.getName(), DateUtil.formatDateDiff(timeDiff)) : tl("playerJailed", player.getName())); } }); if (player.getBase().isOnline()) { @@ -102,7 +101,7 @@ public class Commandtogglejail extends EssentialsCommand { player.sendMessage(tl("jailReleasedPlayerNotify")); player.setJail(null); if (player.getBase().isOnline() && ess.getSettings().isTeleportBackWhenFreedFromJail()) { - CompletableFuture future = getNewExceptionFuture(sender, commandLabel); + final CompletableFuture future = getNewExceptionFuture(sender, commandLabel); player.getAsyncTeleport().back(future); future.thenAccept(success -> { if (success) { @@ -128,7 +127,7 @@ public class Commandtogglejail extends EssentialsCommand { } else if (args.length == 2) { try { return new ArrayList<>(ess.getJails().getList()); - } catch (Exception e) { + } catch (final Exception e) { return Collections.emptyList(); } } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtop.java b/Essentials/src/com/earth2me/essentials/commands/Commandtop.java index 47a17e029..18b621170 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtop.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtop.java @@ -11,7 +11,6 @@ import java.util.concurrent.CompletableFuture; import static com.earth2me.essentials.I18n.tl; - public class Commandtop extends EssentialsCommand { public Commandtop() { super("top"); @@ -24,11 +23,11 @@ public class Commandtop extends EssentialsCommand { final float pitch = user.getLocation().getPitch(); final float yaw = user.getLocation().getYaw(); final Location loc = LocationUtil.getSafeDestination(new Location(user.getWorld(), topX, user.getWorld().getMaxHeight(), topZ, yaw, pitch)); - CompletableFuture future = new CompletableFuture<>(); + final CompletableFuture future = new CompletableFuture<>(); future.thenAccept(success -> { - if (success) { - user.sendMessage(tl("teleportTop", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); - } + if (success) { + user.sendMessage(tl("teleportTop", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); + } }); user.getAsyncTeleport().teleport(loc, new Trade(this.getName(), ess), TeleportCause.COMMAND, getNewExceptionFuture(user.getSource(), commandLabel)); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtp.java b/Essentials/src/com/earth2me/essentials/commands/Commandtp.java index 9e6c7307b..bddc68d91 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtp.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtp.java @@ -14,7 +14,6 @@ import java.util.concurrent.CompletableFuture; import static com.earth2me.essentials.I18n.tl; - public class Commandtp extends EssentialsCommand { public Commandtp() { super("tp"); @@ -22,7 +21,7 @@ public class Commandtp extends EssentialsCommand { @Override public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { - CompletableFuture future = getNewExceptionFuture(user.getSource(), commandLabel); + final CompletableFuture future = getNewExceptionFuture(user.getSource(), commandLabel); switch (args.length) { case 0: throw new NotEnoughArgumentsException(); @@ -131,7 +130,7 @@ public class Commandtp extends EssentialsCommand { } final Location loc = new Location(target.getWorld(), x, y, z, target.getLocation().getYaw(), target.getLocation().getPitch()); sender.sendMessage(tl("teleporting", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); - CompletableFuture future = getNewExceptionFuture(sender, commandLabel); + final CompletableFuture future = getNewExceptionFuture(sender, commandLabel); target.getAsyncTeleport().now(loc, false, TeleportCause.COMMAND, future); future.thenAccept(success -> { if (success) { @@ -144,7 +143,7 @@ public class Commandtp extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { // Don't handle coords if (args.length == 1 || (args.length == 2 && user.isAuthorized("essentials.tp.others"))) { return getPlayers(server, user); @@ -154,7 +153,7 @@ public class Commandtp extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { // Don't handle coords if (args.length == 1 || args.length == 2) { return getPlayers(server, sender); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java index 7cfb84633..6233349e6 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java @@ -13,19 +13,18 @@ import java.util.concurrent.CompletableFuture; import static com.earth2me.essentials.I18n.tl; - public class Commandtpa extends EssentialsCommand { public Commandtpa() { super("tpa"); } @Override - public void run(Server server, User user, String commandLabel, String[] args) throws Exception { + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } - User player = getPlayer(server, user, args, 0); + final User player = getPlayer(server, user, args, 0); if (user.getName().equalsIgnoreCase(player.getName())) { throw new NotEnoughArgumentsException(); } @@ -45,9 +44,9 @@ public class Commandtpa extends EssentialsCommand { } if (player.isAutoTeleportEnabled() && !player.isIgnoredPlayer(user)) { final Trade charge = new Trade(this.getName(), ess); - AsyncTeleport teleport = (AsyncTeleport) user.getAsyncTeleport(); + final AsyncTeleport teleport = user.getAsyncTeleport(); teleport.setTpType(AsyncTeleport.TeleportType.TPA); - CompletableFuture future = getNewExceptionFuture(user.getSource(), commandLabel); + final CompletableFuture future = getNewExceptionFuture(user.getSource(), commandLabel); teleport.teleport(player.getBase(), charge, PlayerTeleportEvent.TeleportCause.COMMAND, future); future.thenAccept(success -> { if (success) { @@ -59,7 +58,7 @@ public class Commandtpa extends EssentialsCommand { } if (!player.isIgnoredPlayer(user)) { - TPARequestEvent tpaEvent = new TPARequestEvent(user.getSource(), player, false); + final TPARequestEvent tpaEvent = new TPARequestEvent(user.getSource(), player, false); ess.getServer().getPluginManager().callEvent(tpaEvent); if (tpaEvent.isCancelled()) { throw new Exception(tl("teleportRequestCancelled", player.getDisplayName())); @@ -79,7 +78,7 @@ public class Commandtpa extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { return getPlayers(server, user); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpaall.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpaall.java index 2d076007c..ca3b72896 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpaall.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpaall.java @@ -10,7 +10,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandtpaall extends EssentialsCommand { public Commandtpaall() { super("tpaall"); @@ -32,7 +31,7 @@ public class Commandtpaall extends EssentialsCommand { private void teleportAAllPlayers(final Server server, final CommandSource sender, final User target) { sender.sendMessage(tl("teleportAAll")); - for (User player : ess.getOnlineUsers()) { + for (final User player : ess.getOnlineUsers()) { if (target == player) { continue; } @@ -43,7 +42,7 @@ public class Commandtpaall extends EssentialsCommand { continue; } try { - TPARequestEvent tpaEvent = new TPARequestEvent(sender, player, true); + final TPARequestEvent tpaEvent = new TPARequestEvent(sender, player, true); ess.getServer().getPluginManager().callEvent(tpaEvent); if (tpaEvent.isCancelled()) { sender.sendMessage(tl("teleportRequestCancelled", player.getDisplayName())); @@ -55,14 +54,14 @@ public class Commandtpaall extends EssentialsCommand { if (ess.getSettings().getTpaAcceptCancellation() != 0) { player.sendMessage(tl("teleportRequestTimeoutInfo", ess.getSettings().getTpaAcceptCancellation())); } - } catch (Exception ex) { + } catch (final Exception ex) { ess.showError(sender, ex, getName()); } } } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { return getPlayers(server, sender); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpacancel.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpacancel.java index acb5ba8bb..2531b2799 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpacancel.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpacancel.java @@ -6,7 +6,6 @@ import org.bukkit.Server; import static com.earth2me.essentials.I18n.tl; - public class Commandtpacancel extends EssentialsCommand { public Commandtpacancel() { @@ -15,14 +14,15 @@ public class Commandtpacancel extends EssentialsCommand { /** * Cancel {@link User}'s tp request if its {@code requester} is equal to the given {@code requester}. - * @param ess ess instance - * @param user user holding tp request + * + * @param ess ess instance + * @param user user holding tp request * @param requester tp requester * @return whether tp was cancelled */ - public static boolean cancelTeleportRequest(IEssentials ess, User user, User requester) throws Exception { + public static boolean cancelTeleportRequest(final IEssentials ess, final User user, final User requester) throws Exception { if (user.getTeleportRequest() != null) { - User userRequester = ess.getUser(user.getTeleportRequest()); + final User userRequester = ess.getUser(user.getTeleportRequest()); if (requester.equals(userRequester)) { user.requestTeleport(null, false); return true; @@ -35,7 +35,7 @@ public class Commandtpacancel extends EssentialsCommand { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { if (args.length == 0) { int cancellations = 0; - for (User onlineUser : ess.getOnlineUsers()) { + for (final User onlineUser : ess.getOnlineUsers()) { if (onlineUser == user) continue; if (cancelTeleportRequest(ess, onlineUser, user)) { cancellations++; @@ -47,7 +47,7 @@ public class Commandtpacancel extends EssentialsCommand { throw new Exception(tl("noPendingRequest")); } } else { - User targetPlayer = getPlayer(server, user, args, 0); + final User targetPlayer = getPlayer(server, user, args, 0); if (cancelTeleportRequest(ess, targetPlayer, user)) { user.sendMessage(tl("teleportRequestSpecificCancelled", targetPlayer.getName())); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java index d2bff8b00..77c5ecfc5 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java @@ -11,7 +11,6 @@ import java.util.concurrent.CompletableFuture; import static com.earth2me.essentials.I18n.tl; - public class Commandtpaccept extends EssentialsCommand { public Commandtpaccept() { super("tpaccept"); @@ -22,7 +21,7 @@ public class Commandtpaccept extends EssentialsCommand { final User requester; try { requester = ess.getUser(user.getTeleportRequest()); - } catch (Exception ex) { + } catch (final Exception ex) { throw new Exception(tl("noPendingRequest")); } @@ -51,14 +50,14 @@ public class Commandtpaccept extends EssentialsCommand { user.sendMessage(tl("requestAccepted")); requester.sendMessage(tl("requestAcceptedFrom", user.getDisplayName())); - CompletableFuture future = getNewExceptionFuture(requester.getSource(), commandLabel); + final CompletableFuture future = getNewExceptionFuture(requester.getSource(), commandLabel); future.exceptionally(e -> { user.sendMessage(tl("pendingTeleportCancelled")); return false; }); if (user.isTpRequestHere()) { final Location loc = user.getTpRequestLocation(); - AsyncTeleport teleport = (AsyncTeleport) requester.getAsyncTeleport(); + final AsyncTeleport teleport = requester.getAsyncTeleport(); teleport.setTpType(AsyncTeleport.TeleportType.TPA); future.thenAccept(success -> { if (success) { @@ -67,7 +66,7 @@ public class Commandtpaccept extends EssentialsCommand { }); teleport.teleportPlayer(user, user.getTpRequestLocation(), charge, TeleportCause.COMMAND, future); } else { - AsyncTeleport teleport = (AsyncTeleport) requester.getAsyncTeleport(); + final AsyncTeleport teleport = requester.getAsyncTeleport(); teleport.setTpType(AsyncTeleport.TeleportType.TPA); teleport.teleport(user.getBase(), charge, TeleportCause.COMMAND, future); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java index 904c67469..5a1a3e474 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java @@ -9,7 +9,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandtpahere extends EssentialsCommand { public Commandtpahere() { super("tpahere"); @@ -40,7 +39,7 @@ public class Commandtpahere extends EssentialsCommand { throw new Exception(tl("requestSentAlready", player.getDisplayName())); } if (!player.isIgnoredPlayer(user)) { - TPARequestEvent tpaEvent = new TPARequestEvent(user.getSource(), player, true); + final TPARequestEvent tpaEvent = new TPARequestEvent(user.getSource(), player, true); ess.getServer().getPluginManager().callEvent(tpaEvent); if (tpaEvent.isCancelled()) { throw new Exception(tl("teleportRequestCancelled", player.getDisplayName())); @@ -58,7 +57,7 @@ public class Commandtpahere extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { return getPlayers(server, user); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpall.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpall.java index ae33ebabe..fde60ac0b 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpall.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpall.java @@ -11,7 +11,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandtpall extends EssentialsCommand { public Commandtpall() { super("tpall"); @@ -31,10 +30,10 @@ public class Commandtpall extends EssentialsCommand { teleportAllPlayers(server, sender, target, commandLabel); } - private void teleportAllPlayers(Server server, CommandSource sender, User target, String label) { + private void teleportAllPlayers(final Server server, final CommandSource sender, final User target, final String label) { sender.sendMessage(tl("teleportAll")); final Location loc = target.getLocation(); - for (User player : ess.getOnlineUsers()) { + for (final User player : ess.getOnlineUsers()) { if (target == player) { continue; } @@ -46,7 +45,7 @@ public class Commandtpall extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { return getPlayers(server, sender); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpauto.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpauto.java index e2bc526ac..2ac525955 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpauto.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpauto.java @@ -6,7 +6,6 @@ import org.bukkit.Server; import static com.earth2me.essentials.I18n.tl; - public class Commandtpauto extends EssentialsToggleCommand { public Commandtpauto() { super("tpauto", "essentials.tpauto.others"); @@ -23,7 +22,7 @@ public class Commandtpauto extends EssentialsToggleCommand { } @Override - void togglePlayer(CommandSource sender, User user, Boolean enabled) { + void togglePlayer(final CommandSource sender, final User user, Boolean enabled) { if (enabled == null) { enabled = !user.isAutoTeleportEnabled(); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpdeny.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpdeny.java index 352f6621c..d9c23a791 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpdeny.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpdeny.java @@ -5,7 +5,6 @@ import org.bukkit.Server; import static com.earth2me.essentials.I18n.tl; - public class Commandtpdeny extends EssentialsCommand { public Commandtpdeny() { super("tpdeny"); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtphere.java b/Essentials/src/com/earth2me/essentials/commands/Commandtphere.java index f07b1259e..ff2e43015 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtphere.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtphere.java @@ -10,7 +10,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandtphere extends EssentialsCommand { public Commandtphere() { super("tphere"); @@ -30,7 +29,7 @@ public class Commandtphere extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { return getPlayers(server, user); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java index e2f234662..2b32391d7 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java @@ -10,7 +10,6 @@ import java.util.concurrent.CompletableFuture; import static com.earth2me.essentials.I18n.tl; - public class Commandtpo extends EssentialsCommand { public Commandtpo() { super("tpo"); @@ -41,7 +40,7 @@ public class Commandtpo extends EssentialsCommand { throw new Exception(tl("noPerm", "essentials.worlds." + toPlayer.getWorld().getName())); } - CompletableFuture future = getNewExceptionFuture(user.getSource(), commandLabel); + final CompletableFuture future = getNewExceptionFuture(user.getSource(), commandLabel); target.getAsyncTeleport().now(toPlayer.getBase(), false, TeleportCause.COMMAND, future); future.thenAccept(success -> { if (success) { @@ -53,7 +52,7 @@ public class Commandtpo extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { // Don't handle coords if (args.length == 1 || (args.length == 2 && user.isAuthorized("essentials.tp.others"))) { return getPlayers(server, user); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpoffline.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpoffline.java index 46ea3b493..6700ca223 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpoffline.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpoffline.java @@ -15,20 +15,18 @@ public class Commandtpoffline extends EssentialsCommand { @Override public void run(final Server server, final User user, final String label, final String[] args) throws Exception { - switch (args.length) { - case 0: - throw new NotEnoughArgumentsException(); + if (args.length == 0) { + throw new NotEnoughArgumentsException(); + } else { + final User target = getPlayer(server, args, 0, true, true); + final Location logout = target.getLogoutLocation(); - default: - final User target = getPlayer(server, args, 0, true, true); - final Location logout = target.getLogoutLocation(); + if (user.getWorld() != logout.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + logout.getWorld().getName())) { + throw new Exception(tl("noPerm", "essentials.worlds." + logout.getWorld().getName())); + } - if (user.getWorld() != logout.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + logout.getWorld().getName())) { - throw new Exception(tl("noPerm", "essentials.worlds." + logout.getWorld().getName())); - } - - user.sendMessage(tl("teleporting", logout.getWorld().getName(), logout.getBlockX(), logout.getBlockY(), logout.getBlockZ())); - user.getAsyncTeleport().now(logout, false, PlayerTeleportEvent.TeleportCause.COMMAND, getNewExceptionFuture(user.getSource(), label)); + user.sendMessage(tl("teleporting", logout.getWorld().getName(), logout.getBlockX(), logout.getBlockY(), logout.getBlockZ())); + user.getAsyncTeleport().now(logout, false, PlayerTeleportEvent.TeleportCause.COMMAND, getNewExceptionFuture(user.getSource(), label)); } } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java index 03ec4b8c6..07739e893 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java @@ -9,7 +9,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandtpohere extends EssentialsCommand { public Commandtpohere() { super("tpohere"); @@ -32,7 +31,7 @@ public class Commandtpohere extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { return getPlayers(server, user); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java b/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java index 9d04aa773..428dd20b5 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java @@ -15,7 +15,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandtppos extends EssentialsCommand { public Commandtppos() { super("tppos"); @@ -32,7 +31,7 @@ public class Commandtppos extends EssentialsCommand { final double z = args[2].startsWith("~") ? user.getLocation().getZ() + (args[2].length() > 1 ? Integer.parseInt(args[2].substring(1)) : 0) : Integer.parseInt(args[2]); final Location loc = new Location(user.getWorld(), x, y, z, user.getLocation().getYaw(), user.getLocation().getPitch()); if (args.length == 4) { - World w = ess.getWorld(args[3]); + final World w = ess.getWorld(args[3]); if (user.getWorld() != w && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + w.getName())) { throw new Exception(tl("noPerm", "essentials.worlds." + w.getName())); } @@ -43,7 +42,7 @@ public class Commandtppos extends EssentialsCommand { loc.setPitch(FloatUtil.parseFloat(args[4])); } if (args.length > 5) { - World w = ess.getWorld(args[5]); + final World w = ess.getWorld(args[5]); if (user.getWorld() != w && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + w.getName())) { throw new Exception(tl("noPerm", "essentials.worlds." + w.getName())); } @@ -66,7 +65,7 @@ public class Commandtppos extends EssentialsCommand { throw new NotEnoughArgumentsException(); } - User user = getPlayer(server, args, 0, true, false); + final User user = getPlayer(server, args, 0, true, false); final double x = args[1].startsWith("~") ? user.getLocation().getX() + (args[1].length() > 1 ? Integer.parseInt(args[1].substring(1)) : 0) : Integer.parseInt(args[1]); final double y = args[2].startsWith("~") ? user.getLocation().getY() + (args[2].length() > 1 ? Integer.parseInt(args[2].substring(1)) : 0) : Integer.parseInt(args[2]); final double z = args[3].startsWith("~") ? user.getLocation().getZ() + (args[3].length() > 1 ? Integer.parseInt(args[3].substring(1)) : 0) : Integer.parseInt(args[3]); @@ -90,14 +89,14 @@ public class Commandtppos extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1 || args.length == 2 || args.length == 3) { return Lists.newArrayList("~0"); } else if (args.length == 4 || args.length == 5) { return Lists.newArrayList("0"); } else if (args.length == 6) { - List worlds = Lists.newArrayList(); - for (World world : server.getWorlds()) { + final List worlds = Lists.newArrayList(); + for (final World world : server.getWorlds()) { worlds.add(world.getName()); } return worlds; @@ -107,7 +106,7 @@ public class Commandtppos extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { return getPlayers(server, sender); } else if (args.length == 2 || args.length == 3 || args.length == 4) { @@ -115,8 +114,8 @@ public class Commandtppos extends EssentialsCommand { } else if (args.length == 5 || args.length == 6) { return Lists.newArrayList("0"); } else if (args.length == 7) { - List worlds = Lists.newArrayList(); - for (World world : server.getWorlds()) { + final List worlds = Lists.newArrayList(); + for (final World world : server.getWorlds()) { worlds.add(world.getName()); } return worlds; @@ -124,4 +123,4 @@ public class Commandtppos extends EssentialsCommand { return Collections.emptyList(); } } -} \ No newline at end of file +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpr.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpr.java index cc2c4f809..d4679db50 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpr.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpr.java @@ -13,7 +13,6 @@ import java.util.concurrent.CompletableFuture; import static com.earth2me.essentials.I18n.tl; - public class Commandtpr extends EssentialsCommand { public Commandtpr() { @@ -21,17 +20,17 @@ public class Commandtpr extends EssentialsCommand { } @Override - protected void run(Server server, User user, String commandLabel, String[] args) throws Exception { + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { final Trade charge = new Trade(this.getName(), ess); charge.isAffordableFor(user); - RandomTeleport randomTeleport = ess.getRandomTeleport(); - UserRandomTeleportEvent event = new UserRandomTeleportEvent(user, randomTeleport.getCenter(), randomTeleport.getMinRange(), randomTeleport.getMaxRange()); + final RandomTeleport randomTeleport = ess.getRandomTeleport(); + final UserRandomTeleportEvent event = new UserRandomTeleportEvent(user, randomTeleport.getCenter(), randomTeleport.getMinRange(), randomTeleport.getMaxRange()); server.getPluginManager().callEvent(event); if (event.isCancelled()) { return; } randomTeleport.getRandomLocation(event.getCenter(), event.getMinRange(), event.getMaxRange()).thenAccept(location -> { - CompletableFuture future = getNewExceptionFuture(user.getSource(), commandLabel); + final CompletableFuture future = getNewExceptionFuture(user.getSource(), commandLabel); user.getAsyncTeleport().teleport(location, charge, PlayerTeleportEvent.TeleportCause.COMMAND, future); future.thenAccept(success -> { if (success) { @@ -43,7 +42,7 @@ public class Commandtpr extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { return Collections.emptyList(); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtptoggle.java b/Essentials/src/com/earth2me/essentials/commands/Commandtptoggle.java index 122e37218..15304eef4 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtptoggle.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtptoggle.java @@ -6,7 +6,6 @@ import org.bukkit.Server; import static com.earth2me.essentials.I18n.tl; - public class Commandtptoggle extends EssentialsToggleCommand { public Commandtptoggle() { super("tptoggle", "essentials.tptoggle.others"); @@ -23,7 +22,7 @@ public class Commandtptoggle extends EssentialsToggleCommand { } @Override - void togglePlayer(CommandSource sender, User user, Boolean enabled) { + void togglePlayer(final CommandSource sender, final User user, Boolean enabled) { if (enabled == null) { enabled = !user.isTeleportEnabled(); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtree.java b/Essentials/src/com/earth2me/essentials/commands/Commandtree.java index fad9eb726..b65ec19a9 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtree.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtree.java @@ -24,7 +24,7 @@ public class Commandtree extends EssentialsCommand { if (args.length < 1) { throw new NotEnoughArgumentsException(); } else { - for (TreeType type : TreeType.values()) { + for (final TreeType type : TreeType.values()) { if (type.name().replace("_", "").equalsIgnoreCase(args[0])) { tree = type; break; @@ -55,10 +55,10 @@ public class Commandtree extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { - List options = Lists.newArrayList(); - for (TreeType type : TreeType.values()) { + final List options = Lists.newArrayList(); + for (final TreeType type : TreeType.values()) { options.add(type.name().toLowerCase(Locale.ENGLISH).replace("_", "")); } return options; diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandunban.java b/Essentials/src/com/earth2me/essentials/commands/Commandunban.java index 65d4bac64..9d9e63e0a 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandunban.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandunban.java @@ -11,7 +11,6 @@ import java.util.logging.Level; import static com.earth2me.essentials.I18n.tl; - public class Commandunban extends EssentialsCommand { public Commandunban() { super("unban"); @@ -28,7 +27,7 @@ public class Commandunban extends EssentialsCommand { final User user = getPlayer(server, args, 0, true, true); name = user.getName(); ess.getServer().getBanList(BanList.Type.NAME).pardon(name); - } catch (PlayerNotFoundException e) { + } catch (final PlayerNotFoundException e) { final OfflinePlayer player = server.getOfflinePlayer(args[0]); name = player.getName(); if (!player.isBanned()) { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java b/Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java index bae6b4bd8..28ea8bbfd 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java @@ -11,7 +11,6 @@ import java.util.logging.Level; import static com.earth2me.essentials.I18n.tl; - public class Commandunbanip extends EssentialsCommand { public Commandunbanip() { super("unbanip"); @@ -28,9 +27,9 @@ public class Commandunbanip extends EssentialsCommand { ipAddress = args[0]; } else { try { - User player = getPlayer(server, args, 0, true, true); + final User player = getPlayer(server, args, 0, true, true); ipAddress = player.getLastLoginAddress(); - } catch (PlayerNotFoundException ex) { + } catch (final PlayerNotFoundException ex) { ipAddress = args[0]; } } @@ -39,7 +38,6 @@ public class Commandunbanip extends EssentialsCommand { throw new PlayerNotFoundException(); } - ess.getServer().getBanList(BanList.Type.IP).pardon(ipAddress); final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME; server.getLogger().log(Level.INFO, tl("playerUnbanIpAddress", senderName, ipAddress)); diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandunlimited.java b/Essentials/src/com/earth2me/essentials/commands/Commandunlimited.java index 68f9f641a..a15b1efd9 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandunlimited.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandunlimited.java @@ -12,7 +12,6 @@ import java.util.StringJoiner; import static com.earth2me.essentials.I18n.tl; - public class Commandunlimited extends EssentialsCommand { public Commandunlimited() { super("unlimited"); @@ -32,7 +31,7 @@ public class Commandunlimited extends EssentialsCommand { if (args[0].equalsIgnoreCase("list")) { user.sendMessage(getList(target)); } else if (args[0].equalsIgnoreCase("clear")) { - for (Material m : new HashSet<>(target.getUnlimited())) { + for (final Material m : new HashSet<>(target.getUnlimited())) { toggleUnlimited(user, target, m.toString()); } } else { @@ -47,8 +46,8 @@ public class Commandunlimited extends EssentialsCommand { if (items.isEmpty()) { output.append(tl("none")); } - StringJoiner joiner = new StringJoiner(","); - for (Material material : items) { + final StringJoiner joiner = new StringJoiner(","); + for (final Material material : items) { joiner.add(material.toString().toLowerCase(Locale.ENGLISH).replace("_", "")); } output.append(joiner.toString()); @@ -61,7 +60,7 @@ public class Commandunlimited extends EssentialsCommand { stack.setAmount(Math.min(stack.getType().getMaxStackSize(), 2)); final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); - if (ess.getSettings().permissionBasedItemSpawn() && (!user.isAuthorized("essentials.unlimited.item-all") && !user.isAuthorized("essentials.unlimited.item-" + itemname) && !((stack.getType() == Material.WATER_BUCKET || stack.getType() == Material.LAVA_BUCKET) && user.isAuthorized("essentials.unlimited.item-bucket")))) { + if (ess.getSettings().permissionBasedItemSpawn() && !user.isAuthorized("essentials.unlimited.item-all") && !user.isAuthorized("essentials.unlimited.item-" + itemname) && !((stack.getType() == Material.WATER_BUCKET || stack.getType() == Material.LAVA_BUCKET) && user.isAuthorized("essentials.unlimited.item-bucket"))) { throw new Exception(tl("unlimitedItemPermission", itemname)); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandvanish.java b/Essentials/src/com/earth2me/essentials/commands/Commandvanish.java index 06dc510b1..c8ce0f704 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandvanish.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandvanish.java @@ -7,7 +7,6 @@ import org.bukkit.Server; import static com.earth2me.essentials.I18n.tl; - public class Commandvanish extends EssentialsToggleCommand { public Commandvanish() { super("vanish", "essentials.vanish.others"); @@ -24,12 +23,12 @@ public class Commandvanish extends EssentialsToggleCommand { } @Override - void togglePlayer(CommandSource sender, User user, Boolean enabled) { + void togglePlayer(final CommandSource sender, final User user, Boolean enabled) { if (enabled == null) { enabled = !user.isVanished(); } - - VanishStatusChangeEvent vanishEvent = new VanishStatusChangeEvent(sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null, user, enabled); + + final VanishStatusChangeEvent vanishEvent = new VanishStatusChangeEvent(sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null, user, enabled); ess.getServer().getPluginManager().callEvent(vanishEvent); if (vanishEvent.isCancelled()) { return; diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java b/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java index d97a5eaf2..b1b1ec307 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java @@ -19,7 +19,6 @@ import java.util.stream.Collectors; import static com.earth2me.essentials.I18n.tl; - public class Commandwarp extends EssentialsCommand { private static final int WARPS_PER_PAGE = 20; @@ -55,7 +54,7 @@ public class Commandwarp extends EssentialsCommand { warpList(sender, args, null); throw new NoChargeException(); } - User otherUser = getPlayer(server, args, 1, true, false); + final User otherUser = getPlayer(server, args, 1, true, false); otherUser.getAsyncTeleport().warp(otherUser, args[0], null, TeleportCause.COMMAND, getNewExceptionFuture(sender, commandLabel)); throw new NoChargeException(); } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandweather.java b/Essentials/src/com/earth2me/essentials/commands/Commandweather.java index 9c6a9ff63..1dc9b4198 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandweather.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandweather.java @@ -11,7 +11,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandweather extends EssentialsCommand { public Commandweather() { super("weather"); @@ -67,7 +66,7 @@ public class Commandweather extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { return Lists.newArrayList("storm", "sun"); } else if (args.length == 2) { @@ -78,10 +77,10 @@ public class Commandweather extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { - List worlds = Lists.newArrayList(); - for (World world : server.getWorlds()) { + final List worlds = Lists.newArrayList(); + for (final World world : server.getWorlds()) { worlds.add(world.getName()); } return worlds; diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java b/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java index e40d5a685..613ea61b9 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java @@ -9,13 +9,12 @@ import com.earth2me.essentials.utils.NumberUtil; import org.bukkit.Server; import org.bukkit.Statistic; -import java.util.Locale; import java.util.Collections; import java.util.List; +import java.util.Locale; import static com.earth2me.essentials.I18n.tl; - public class Commandwhois extends EssentialsCommand { // For some reason, in 1.13 PLAY_ONE_MINUTE = ticks played = what used to be PLAY_ONE_TICK // https://hub.spigotmc.org/stash/projects/SPIGOT/repos/bukkit/commits/b848d8ce633871b52115247b089029749c02f579 @@ -31,7 +30,7 @@ public class Commandwhois extends EssentialsCommand { throw new NotEnoughArgumentsException(); } - User user = getPlayer(server, sender, args, 0); + final User user = getPlayer(server, sender, args, 0); sender.sendMessage(tl("whoisTop", user.getName())); user.setDisplayNick(); @@ -41,7 +40,7 @@ public class Commandwhois extends EssentialsCommand { sender.sendMessage(tl("whoisHunger", user.getBase().getFoodLevel(), user.getBase().getSaturation())); sender.sendMessage(tl("whoisExp", SetExpFix.getTotalExperience(user.getBase()), user.getBase().getLevel())); sender.sendMessage(tl("whoisLocation", user.getLocation().getWorld().getName(), user.getLocation().getBlockX(), user.getLocation().getBlockY(), user.getLocation().getBlockZ())); - long playtimeMs = System.currentTimeMillis() - (user.getBase().getStatistic(PLAY_ONE_TICK) * 50); + final long playtimeMs = System.currentTimeMillis() - (user.getBase().getStatistic(PLAY_ONE_TICK) * 50); sender.sendMessage(tl("whoisPlaytime", DateUtil.formatDateDiff(playtimeMs))); if (!ess.getSettings().isEcoDisabled()) { sender.sendMessage(tl("whoisMoney", NumberUtil.displayCurrency(user.getMoney(), ess))); @@ -54,8 +53,8 @@ public class Commandwhois extends EssentialsCommand { sender.sendMessage(tl("whoisGeoLocation", location)); } sender.sendMessage(tl("whoisGamemode", tl(user.getBase().getGameMode().toString().toLowerCase(Locale.ENGLISH)))); - sender.sendMessage(tl("whoisGod", (user.isGodModeEnabled() ? tl("true") : tl("false")))); - sender.sendMessage(tl("whoisOp", (user.getBase().isOp() ? tl("true") : tl("false")))); + sender.sendMessage(tl("whoisGod", user.isGodModeEnabled() ? tl("true") : tl("false"))); + sender.sendMessage(tl("whoisOp", user.getBase().isOp() ? tl("true") : tl("false"))); sender.sendMessage(tl("whoisFly", user.getBase().getAllowFlight() ? tl("true") : tl("false"), user.getBase().isFlying() ? tl("flying") : tl("notFlying"))); sender.sendMessage(tl("whoisSpeed", user.getBase().isFlying() ? user.getBase().getFlySpeed() : user.getBase().getWalkSpeed())); if (user.isAfk()) { @@ -63,19 +62,19 @@ public class Commandwhois extends EssentialsCommand { } else { sender.sendMessage(tl("whoisAFK", tl("false"))); } - sender.sendMessage(tl("whoisJail", (user.isJailed() ? user.getJailTimeout() > 0 ? DateUtil.formatDateDiff(user.getJailTimeout()) : tl("true") : tl("false")))); + sender.sendMessage(tl("whoisJail", user.isJailed() ? user.getJailTimeout() > 0 ? DateUtil.formatDateDiff(user.getJailTimeout()) : tl("true") : tl("false"))); - long muteTimeout = user.getMuteTimeout(); + final long muteTimeout = user.getMuteTimeout(); if (!user.hasMuteReason()) { - sender.sendMessage(tl("whoisMuted", (user.isMuted() ? (muteTimeout > 0 ? DateUtil.formatDateDiff(muteTimeout) : tl("true")) : tl("false")))); + sender.sendMessage(tl("whoisMuted", user.isMuted() ? muteTimeout > 0 ? DateUtil.formatDateDiff(muteTimeout) : tl("true") : tl("false"))); } else { - sender.sendMessage(tl("whoisMutedReason", (user.isMuted() ? (muteTimeout > 0 ? DateUtil.formatDateDiff(muteTimeout) : tl("true")) : tl("false")), + sender.sendMessage(tl("whoisMutedReason", user.isMuted() ? muteTimeout > 0 ? DateUtil.formatDateDiff(muteTimeout) : tl("true") : tl("false"), user.getMuteReason())); } } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { return getPlayers(server, sender); } else { diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandworkbench.java b/Essentials/src/com/earth2me/essentials/commands/Commandworkbench.java index 51bd177ce..e64f6e31f 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandworkbench.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandworkbench.java @@ -3,7 +3,6 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.User; import org.bukkit.Server; - public class Commandworkbench extends EssentialsCommand { public Commandworkbench() { super("workbench"); @@ -13,4 +12,4 @@ public class Commandworkbench extends EssentialsCommand { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { user.getBase().openWorkbench(null, true); } -} \ No newline at end of file +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandworld.java b/Essentials/src/com/earth2me/essentials/commands/Commandworld.java index 96f185008..c183e993d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandworld.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandworld.java @@ -13,7 +13,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandworld extends EssentialsCommand { public Commandworld() { super("world"); @@ -21,14 +20,14 @@ public class Commandworld extends EssentialsCommand { @Override protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { - World world; + final World world; if (args.length < 1) { World nether = null; final List worlds = server.getWorlds(); - for (World world2 : worlds) { + for (final World world2 : worlds) { if (world2.getEnvironment() == World.Environment.NETHER) { nether = world2; break; @@ -52,7 +51,7 @@ public class Commandworld extends EssentialsCommand { throw new Exception(tl("noPerm", "essentials.worlds." + world.getName())); } - double factor; + final double factor; if (user.getWorld().getEnvironment() == World.Environment.NETHER && world.getEnvironment() == World.Environment.NORMAL) { factor = 8.0; } else if (user.getWorld().getEnvironment() == World.Environment.NORMAL && world.getEnvironment() == World.Environment.NETHER) { @@ -72,10 +71,10 @@ public class Commandworld extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { - List worlds = Lists.newArrayList(); - for (World world : server.getWorlds()) { + final List worlds = Lists.newArrayList(); + for (final World world : server.getWorlds()) { if (ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + world.getName())) { continue; } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandworth.java b/Essentials/src/com/earth2me/essentials/commands/Commandworth.java index 913a82f40..4df511d90 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandworth.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandworth.java @@ -14,7 +14,6 @@ import java.util.Locale; import static com.earth2me.essentials.I18n.tl; - public class Commandworth extends EssentialsCommand { public Commandworth() { super("worth"); @@ -22,9 +21,9 @@ public class Commandworth extends EssentialsCommand { @Override public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { - List is = ess.getItemDb().getMatching(user, args); + final List is = ess.getItemDb().getMatching(user, args); int count = 0; - boolean isBulk = is.size() > 1; + final boolean isBulk = is.size() > 1; BigDecimal totalWorth = BigDecimal.ZERO; for (ItemStack stack : is) { try { @@ -32,21 +31,21 @@ public class Commandworth extends EssentialsCommand { totalWorth = totalWorth.add(itemWorth(user.getSource(), user, stack, args)); stack = stack.clone(); count++; - for (ItemStack zeroStack : is) { + for (final ItemStack zeroStack : is) { if (zeroStack.isSimilar(stack)) { zeroStack.setAmount(0); } } } - } catch (Exception e) { + } catch (final Exception e) { if (!isBulk) { throw e; } } } if (count > 1) { - String totalWorthStr = NumberUtil.displayCurrency(totalWorth, ess); + final String totalWorthStr = NumberUtil.displayCurrency(totalWorth, ess); if (args.length > 0 && args[0].equalsIgnoreCase("blocks")) { user.sendMessage(tl("totalSellableBlocks", totalWorthStr, totalWorthStr)); return; @@ -63,13 +62,13 @@ public class Commandworth extends EssentialsCommand { itemWorth(sender, null, ess.getItemDb().get(args[0]), args); } - private BigDecimal itemWorth(CommandSource sender, User user, ItemStack is, String[] args) throws Exception { + private BigDecimal itemWorth(final CommandSource sender, final User user, final ItemStack is, final String[] args) throws Exception { int amount = 1; if (user == null) { if (args.length > 1) { try { amount = Integer.parseInt(args[1].replaceAll("[^0-9]", "")); - } catch (NumberFormatException ex) { + } catch (final NumberFormatException ex) { throw new NotEnoughArgumentsException(ex); } @@ -78,7 +77,7 @@ public class Commandworth extends EssentialsCommand { amount = ess.getWorth().getAmount(ess, user, is, args, true); } - BigDecimal worth = ess.getWorth().getPrice(ess, is); + final BigDecimal worth = ess.getWorth().getPrice(ess, is); if (worth == null) { throw new Exception(tl("itemCannotBeSold")); } @@ -87,13 +86,13 @@ public class Commandworth extends EssentialsCommand { amount = 0; } - BigDecimal result = worth.multiply(BigDecimal.valueOf(amount)); + final BigDecimal result = worth.multiply(BigDecimal.valueOf(amount)); sender.sendMessage(is.getDurability() != 0 ? tl("worthMeta", is.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), is.getDurability(), NumberUtil.displayCurrency(result, ess), amount, NumberUtil.displayCurrency(worth, ess)) : tl("worth", is.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), NumberUtil.displayCurrency(result, ess), amount, NumberUtil.displayCurrency(worth, ess))); return result; } @Override - protected List getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { if (args.length == 1) { return getMatchingItems(args[0]); } else if (args.length == 2) { @@ -104,7 +103,7 @@ public class Commandworth extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { return getItems(); } else if (args.length == 2) { diff --git a/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java b/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java index c2c950f96..57fdf632c 100644 --- a/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java +++ b/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java @@ -29,17 +29,47 @@ import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; - public abstract class EssentialsCommand implements IEssentialsCommand { + protected static final Logger logger = Logger.getLogger("Essentials"); + /** + * Common time durations (in seconds), for use in tab completion. + */ + protected static final List COMMON_DURATIONS = ImmutableList.of("1", "60", "600", "3600", "86400"); + /** + * Common date diffs, for use in tab completion + */ + protected static final List COMMON_DATE_DIFFS = ImmutableList.of("1m", "15m", "1h", "3h", "12h", "1d", "1w", "1mo", "1y"); private final transient String name; protected transient IEssentials ess; protected transient IEssentialsModule module; - protected static final Logger logger = Logger.getLogger("Essentials"); protected EssentialsCommand(final String name) { this.name = name; } + public static String getFinalArg(final String[] args, final int start) { + final StringBuilder bldr = new StringBuilder(); + for (int i = start; i < args.length; i++) { + if (i != start) { + bldr.append(" "); + } + bldr.append(args[i]); + } + return bldr.toString(); + } + + private static boolean canInteractWith(final User interactor, final User interactee) { + if (interactor == null) { + return !interactee.isHidden(); + } + + if (interactor.equals(interactee)) { + return true; + } + + return interactor.getBase().canSee(interactee.getBase()); + } + @Override public void setEssentials(final IEssentials ess) { this.ess = ess; @@ -58,7 +88,7 @@ public abstract class EssentialsCommand implements IEssentialsCommand { // Get online players - only show vanished if source has permission protected User getPlayer(final Server server, final CommandSource sender, final String[] args, final int pos) throws PlayerNotFoundException, NotEnoughArgumentsException { if (sender.isPlayer()) { - User user = ess.getUser(sender.getPlayer()); + final User user = ess.getUser(sender.getPlayer()); return getPlayer(server, user, args, pos); } return getPlayer(server, args, pos, true, false); @@ -67,7 +97,7 @@ public abstract class EssentialsCommand implements IEssentialsCommand { // Get online players - only show vanished if source has permission protected User getPlayer(final Server server, final CommandSource sender, final String searchTerm) throws PlayerNotFoundException, NotEnoughArgumentsException { if (sender.isPlayer()) { - User user = ess.getUser(sender.getPlayer()); + final User user = ess.getUser(sender.getPlayer()); return getPlayer(server, user, searchTerm, user.canInteractVanished(), false); } return getPlayer(server, searchTerm, true, false); @@ -79,11 +109,11 @@ public abstract class EssentialsCommand implements IEssentialsCommand { } // Get online or offline players, this method allows for raw access - protected User getPlayer(final Server server, final String[] args, final int pos, boolean getHidden, final boolean getOffline) throws PlayerNotFoundException, NotEnoughArgumentsException { + protected User getPlayer(final Server server, final String[] args, final int pos, final boolean getHidden, final boolean getOffline) throws PlayerNotFoundException, NotEnoughArgumentsException { return getPlayer(server, null, args, pos, getHidden, getOffline); } - User getPlayer(final Server server, final User sourceUser, final String[] args, final int pos, boolean getHidden, final boolean getOffline) throws PlayerNotFoundException, NotEnoughArgumentsException { + User getPlayer(final Server server, final User sourceUser, final String[] args, final int pos, final boolean getHidden, final boolean getOffline) throws PlayerNotFoundException, NotEnoughArgumentsException { if (args.length <= pos) { throw new NotEnoughArgumentsException(); } @@ -94,17 +124,17 @@ public abstract class EssentialsCommand implements IEssentialsCommand { } // Get online or offline players, this method allows for raw access - protected User getPlayer(final Server server, final String searchTerm, boolean getHidden, final boolean getOffline) throws PlayerNotFoundException { + protected User getPlayer(final Server server, final String searchTerm, final boolean getHidden, final boolean getOffline) throws PlayerNotFoundException { return getPlayer(server, null, searchTerm, getHidden, getOffline); } - private User getPlayer(final Server server, final User sourceUser, final String searchTerm, boolean getHidden, final boolean getOffline) throws PlayerNotFoundException { + private User getPlayer(final Server server, final User sourceUser, final String searchTerm, final boolean getHidden, final boolean getOffline) throws PlayerNotFoundException { final User user; Player exPlayer; try { exPlayer = server.getPlayer(UUID.fromString(searchTerm)); - } catch (IllegalArgumentException ex) { + } catch (final IllegalArgumentException ex) { if (getOffline) { exPlayer = server.getPlayerExact(searchTerm); } else { @@ -136,7 +166,7 @@ public abstract class EssentialsCommand implements IEssentialsCommand { if (matches.isEmpty()) { final String matchText = searchTerm.toLowerCase(Locale.ENGLISH); - for (User userMatch : ess.getOnlineUsers()) { + for (final User userMatch : ess.getOnlineUsers()) { if (getHidden || canInteractWith(sourceUser, userMatch)) { final String displayName = FormatUtil.stripFormat(userMatch.getDisplayName()).toLowerCase(Locale.ENGLISH); if (displayName.contains(matchText)) { @@ -145,7 +175,7 @@ public abstract class EssentialsCommand implements IEssentialsCommand { } } } else { - for (Player player : matches) { + for (final Player player : matches) { final User userMatch = ess.getUser(player); if (userMatch.getDisplayName().startsWith(searchTerm) && (getHidden || canInteractWith(sourceUser, userMatch))) { return userMatch; @@ -186,7 +216,7 @@ public abstract class EssentialsCommand implements IEssentialsCommand { // Shouldn't happen, but bail out early if it does so that args[0] can always be used return Collections.emptyList(); } - List options = getTabCompleteOptions(server, user, commandLabel, args); + final List options = getTabCompleteOptions(server, user, commandLabel, args); if (options == null) { return null; } @@ -204,7 +234,7 @@ public abstract class EssentialsCommand implements IEssentialsCommand { // Shouldn't happen, but bail out early if it does so that args[0] can always be used return Collections.emptyList(); } - List options = getTabCompleteOptions(server, sender, commandLabel, args); + final List options = getTabCompleteOptions(server, sender, commandLabel, args); if (options == null) { return null; } @@ -217,18 +247,7 @@ public abstract class EssentialsCommand implements IEssentialsCommand { return getPlayers(server, sender); } - public static String getFinalArg(final String[] args, final int start) { - final StringBuilder bldr = new StringBuilder(); - for (int i = start; i < args.length; i++) { - if (i != start) { - bldr.append(" "); - } - bldr.append(args[i]); - } - return bldr.toString(); - } - - boolean canInteractWith(CommandSource interactor, User interactee) { + boolean canInteractWith(final CommandSource interactor, final User interactee) { if (interactor == null) { return !interactee.isHidden(); } @@ -240,25 +259,13 @@ public abstract class EssentialsCommand implements IEssentialsCommand { return true; // console } - private static boolean canInteractWith(User interactor, User interactee) { - if (interactor == null) { - return !interactee.isHidden(); - } - - if (interactor.equals(interactee)) { - return true; - } - - return interactor.getBase().canSee(interactee.getBase()); - } - /** * Gets a list of all player names that can be seen with by the given CommandSource, * for tab completion. */ protected List getPlayers(final Server server, final CommandSource interactor) { - List players = Lists.newArrayList(); - for (User user : ess.getOnlineUsers()) { + final List players = Lists.newArrayList(); + for (final User user : ess.getOnlineUsers()) { if (canInteractWith(interactor, user)) { players.add(user.getName()); } @@ -271,8 +278,8 @@ public abstract class EssentialsCommand implements IEssentialsCommand { * for tab completion. */ protected List getPlayers(final Server server, final User interactor) { - List players = Lists.newArrayList(); - for (User user : ess.getOnlineUsers()) { + final List players = Lists.newArrayList(); + for (final User user : ess.getOnlineUsers()) { if (canInteractWith(interactor, user)) { players.add(user.getName()); } @@ -291,8 +298,8 @@ public abstract class EssentialsCommand implements IEssentialsCommand { /** * Gets a list of tab-completable items usable for "getMatching". */ - protected List getMatchingItems(String arg) { - List items = Lists.newArrayList("hand", "inventory", "blocks"); + protected List getMatchingItems(final String arg) { + final List items = Lists.newArrayList("hand", "inventory", "blocks"); if (!arg.isEmpty()) { // Emphasize the other items if they haven't entered anything yet. items.addAll(getItems()); @@ -302,12 +309,12 @@ public abstract class EssentialsCommand implements IEssentialsCommand { /** * Lists all commands. - * + *

* TODO: Use the real commandmap to do this automatically. */ - protected final List getCommands(Server server) { - List commands = Lists.newArrayList(); - for (Plugin p : server.getPluginManager().getPlugins()) { + protected final List getCommands(final Server server) { + final List commands = Lists.newArrayList(); + for (final Plugin p : server.getPluginManager().getPlugins()) { final PluginDescriptionFile desc = p.getDescription(); final Map> cmds = desc.getCommands(); if (cmds != null) { @@ -320,19 +327,19 @@ public abstract class EssentialsCommand implements IEssentialsCommand { /** * Attempts to tab-complete a command or its arguments. */ - protected final List tabCompleteCommand(CommandSource sender, Server server, String label, String[] args, int index) { + protected final List tabCompleteCommand(final CommandSource sender, final Server server, final String label, final String[] args, final int index) { // TODO: Pass this to the real commandmap - Command command = server.getPluginCommand(label); + final Command command = server.getPluginCommand(label); if (command == null) { return Collections.emptyList(); } - int numArgs = args.length - index - 1; + final int numArgs = args.length - index - 1; ess.getLogger().info(numArgs + " " + index + " " + Arrays.toString(args)); String[] effectiveArgs = new String[numArgs]; System.arraycopy(args, index, effectiveArgs, 0, numArgs); if (effectiveArgs.length == 0) { - effectiveArgs = new String[] { "" }; + effectiveArgs = new String[] {""}; } ess.getLogger().info(command + " -- " + Arrays.toString(effectiveArgs)); @@ -340,7 +347,7 @@ public abstract class EssentialsCommand implements IEssentialsCommand { } @Override - public void showError(CommandSender sender, Throwable throwable, String commandLabel) { + public void showError(final CommandSender sender, final Throwable throwable, final String commandLabel) { sender.sendMessage(tl("errorWithMessage", throwable.getMessage())); if (ess.getSettings().isDebug()) { logger.log(Level.INFO, tl("errorCallingCommand", commandLabel), throwable); @@ -348,21 +355,12 @@ public abstract class EssentialsCommand implements IEssentialsCommand { } } - public CompletableFuture getNewExceptionFuture(CommandSource sender, String commandLabel) { - CompletableFuture future = new CompletableFuture<>(); + public CompletableFuture getNewExceptionFuture(final CommandSource sender, final String commandLabel) { + final CompletableFuture future = new CompletableFuture<>(); future.exceptionally(e -> { showError(sender.getSender(), e, commandLabel); return false; }); return future; } - - /** - * Common time durations (in seconds), for use in tab completion. - */ - protected static final List COMMON_DURATIONS = ImmutableList.of("1", "60", "600", "3600", "86400"); - /** - * Common date diffs, for use in tab completion - */ - protected static final List COMMON_DATE_DIFFS = ImmutableList.of("1m", "15m", "1h", "3h", "12h", "1d", "1w", "1mo", "1y"); } diff --git a/Essentials/src/com/earth2me/essentials/commands/EssentialsLoopCommand.java b/Essentials/src/com/earth2me/essentials/commands/EssentialsLoopCommand.java index 42d45b324..29934d7e8 100644 --- a/Essentials/src/com/earth2me/essentials/commands/EssentialsLoopCommand.java +++ b/Essentials/src/com/earth2me/essentials/commands/EssentialsLoopCommand.java @@ -13,17 +13,16 @@ import java.util.List; import java.util.Locale; import java.util.UUID; - public abstract class EssentialsLoopCommand extends EssentialsCommand { - public EssentialsLoopCommand(String command) { + public EssentialsLoopCommand(final String command) { super(command); } - protected void loopOfflinePlayers(final Server server, final CommandSource sender, final boolean multipleStringMatches, boolean matchWildcards, final String searchTerm, final String[] commandArgs) throws PlayerNotFoundException, NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException { + protected void loopOfflinePlayers(final Server server, final CommandSource sender, final boolean multipleStringMatches, final boolean matchWildcards, final String searchTerm, final String[] commandArgs) throws PlayerNotFoundException, NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException { loopOfflinePlayersConsumer(server, sender, multipleStringMatches, matchWildcards, searchTerm, user -> updatePlayer(server, sender, user, commandArgs)); } - protected void loopOfflinePlayersConsumer(final Server server, final CommandSource sender, final boolean multipleStringMatches, boolean matchWildcards, final String searchTerm, UserConsumer userConsumer) throws PlayerNotFoundException, NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException { + protected void loopOfflinePlayersConsumer(final Server server, final CommandSource sender, final boolean multipleStringMatches, final boolean matchWildcards, final String searchTerm, final UserConsumer userConsumer) throws PlayerNotFoundException, NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException { if (searchTerm.isEmpty()) { throw new PlayerNotFoundException(); } @@ -33,13 +32,13 @@ public abstract class EssentialsLoopCommand extends EssentialsCommand { final User matchedUser = ess.getUser(uuid); userConsumer.accept(matchedUser); } else if (matchWildcards && searchTerm.contentEquals("**")) { - for (UUID sUser : ess.getUserMap().getAllUniqueUsers()) { + for (final UUID sUser : ess.getUserMap().getAllUniqueUsers()) { final User matchedUser = ess.getUser(sUser); userConsumer.accept(matchedUser); } } else if (matchWildcards && searchTerm.contentEquals("*")) { - boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); - for (User onlineUser : ess.getOnlineUsers()) { + final boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); + for (final User onlineUser : ess.getOnlineUsers()) { if (skipHidden && onlineUser.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(onlineUser.getBase())) { continue; } @@ -54,7 +53,7 @@ public abstract class EssentialsLoopCommand extends EssentialsCommand { final User matchedUser = getPlayer(server, searchTerm, true, true); userConsumer.accept(matchedUser); } - for (Player matchPlayer : matchedPlayers) { + for (final Player matchPlayer : matchedPlayers) { final User matchedUser = ess.getUser(matchPlayer); userConsumer.accept(matchedUser); } @@ -64,19 +63,19 @@ public abstract class EssentialsLoopCommand extends EssentialsCommand { } } - protected void loopOnlinePlayers(final Server server, final CommandSource sender, final boolean multipleStringMatches, boolean matchWildcards, final String searchTerm, final String[] commandArgs) throws PlayerNotFoundException, NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException { + protected void loopOnlinePlayers(final Server server, final CommandSource sender, final boolean multipleStringMatches, final boolean matchWildcards, final String searchTerm, final String[] commandArgs) throws PlayerNotFoundException, NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException { loopOnlinePlayersConsumer(server, sender, multipleStringMatches, matchWildcards, searchTerm, user -> updatePlayer(server, sender, user, commandArgs)); } - protected void loopOnlinePlayersConsumer(final Server server, final CommandSource sender, final boolean multipleStringMatches, boolean matchWildcards, final String searchTerm, UserConsumer userConsumer) throws PlayerNotFoundException, NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException { + protected void loopOnlinePlayersConsumer(final Server server, final CommandSource sender, final boolean multipleStringMatches, final boolean matchWildcards, final String searchTerm, final UserConsumer userConsumer) throws PlayerNotFoundException, NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException { if (searchTerm.isEmpty()) { throw new PlayerNotFoundException(); } - boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); + final boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); if (matchWildcards && (searchTerm.contentEquals("**") || searchTerm.contentEquals("*"))) { - for (User onlineUser : ess.getOnlineUsers()) { + for (final User onlineUser : ess.getOnlineUsers()) { if (skipHidden && onlineUser.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(onlineUser.getBase())) { continue; } @@ -91,7 +90,7 @@ public abstract class EssentialsLoopCommand extends EssentialsCommand { if (matchedPlayers.isEmpty()) { final String matchText = searchTerm.toLowerCase(Locale.ENGLISH); - for (User player : ess.getOnlineUsers()) { + for (final User player : ess.getOnlineUsers()) { if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(player.getBase())) { continue; } @@ -102,7 +101,7 @@ public abstract class EssentialsLoopCommand extends EssentialsCommand { } } } else { - for (Player matchPlayer : matchedPlayers) { + for (final Player matchPlayer : matchedPlayers) { final User player = ess.getUser(matchPlayer); if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer)) { continue; @@ -124,7 +123,7 @@ public abstract class EssentialsLoopCommand extends EssentialsCommand { @Override protected List getPlayers(final Server server, final CommandSource interactor) { - List players = super.getPlayers(server, interactor); + final List players = super.getPlayers(server, interactor); players.add("**"); players.add("*"); return players; @@ -132,7 +131,7 @@ public abstract class EssentialsLoopCommand extends EssentialsCommand { @Override protected List getPlayers(final Server server, final User interactor) { - List players = super.getPlayers(server, interactor); + final List players = super.getPlayers(server, interactor); players.add("**"); players.add("*"); return players; diff --git a/Essentials/src/com/earth2me/essentials/commands/EssentialsToggleCommand.java b/Essentials/src/com/earth2me/essentials/commands/EssentialsToggleCommand.java index 22c02a041..6197bad81 100644 --- a/Essentials/src/com/earth2me/essentials/commands/EssentialsToggleCommand.java +++ b/Essentials/src/com/earth2me/essentials/commands/EssentialsToggleCommand.java @@ -9,18 +9,17 @@ import org.bukkit.entity.Player; import java.util.Collections; import java.util.List; - public abstract class EssentialsToggleCommand extends EssentialsCommand { - String othersPermission; + final String othersPermission; - public EssentialsToggleCommand(String command, String othersPermission) { + public EssentialsToggleCommand(final String command, final String othersPermission) { super(command); this.othersPermission = othersPermission; } - protected void handleToggleWithArgs(Server server, User user, String[] args) throws Exception { + protected void handleToggleWithArgs(final Server server, final User user, final String[] args) throws Exception { if (args.length == 1) { - Boolean toggle = matchToggleArgument(args[0]); + final Boolean toggle = matchToggleArgument(args[0]); if (toggle == null && user.isAuthorized(othersPermission)) { toggleOtherPlayers(server, user.getSource(), args); } else { @@ -47,22 +46,18 @@ public abstract class EssentialsToggleCommand extends EssentialsCommand { throw new PlayerNotFoundException(); } - boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); + final boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); boolean foundUser = false; final List matchedPlayers = server.matchPlayer(args[0]); - for (Player matchPlayer : matchedPlayers) { + for (final Player matchPlayer : matchedPlayers) { final User player = ess.getUser(matchPlayer); if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer)) { continue; } foundUser = true; if (args.length > 1) { - Boolean toggle = matchToggleArgument(args[1]); - if (toggle) { - togglePlayer(sender, player, true); - } else { - togglePlayer(sender, player, false); - } + final Boolean toggle = matchToggleArgument(args[1]); + togglePlayer(sender, player, toggle); } else { togglePlayer(sender, player, null); } diff --git a/Essentials/src/com/earth2me/essentials/commands/IEssentialsCommand.java b/Essentials/src/com/earth2me/essentials/commands/IEssentialsCommand.java index 86e08877a..2027dd3c3 100644 --- a/Essentials/src/com/earth2me/essentials/commands/IEssentialsCommand.java +++ b/Essentials/src/com/earth2me/essentials/commands/IEssentialsCommand.java @@ -10,7 +10,6 @@ import org.bukkit.command.CommandSender; import java.util.List; - public interface IEssentialsCommand { String getName(); diff --git a/Essentials/src/com/earth2me/essentials/commands/NoChargeException.java b/Essentials/src/com/earth2me/essentials/commands/NoChargeException.java index c29f520bf..1a325b758 100644 --- a/Essentials/src/com/earth2me/essentials/commands/NoChargeException.java +++ b/Essentials/src/com/earth2me/essentials/commands/NoChargeException.java @@ -1,6 +1,5 @@ package com.earth2me.essentials.commands; - public class NoChargeException extends Exception { public NoChargeException() { super("Will charge later"); diff --git a/Essentials/src/com/earth2me/essentials/commands/NotEnoughArgumentsException.java b/Essentials/src/com/earth2me/essentials/commands/NotEnoughArgumentsException.java index 1978833e1..75ca75105 100644 --- a/Essentials/src/com/earth2me/essentials/commands/NotEnoughArgumentsException.java +++ b/Essentials/src/com/earth2me/essentials/commands/NotEnoughArgumentsException.java @@ -1,6 +1,5 @@ package com.earth2me.essentials.commands; - public class NotEnoughArgumentsException extends Exception { public NotEnoughArgumentsException() { super(""); diff --git a/Essentials/src/com/earth2me/essentials/commands/PlayerExemptException.java b/Essentials/src/com/earth2me/essentials/commands/PlayerExemptException.java index e95a4247c..813c89b55 100644 --- a/Essentials/src/com/earth2me/essentials/commands/PlayerExemptException.java +++ b/Essentials/src/com/earth2me/essentials/commands/PlayerExemptException.java @@ -1,7 +1,7 @@ package com.earth2me.essentials.commands; public class PlayerExemptException extends NoSuchFieldException { - public PlayerExemptException(String message) { + public PlayerExemptException(final String message) { super(message); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/QuietAbortException.java b/Essentials/src/com/earth2me/essentials/commands/QuietAbortException.java index 397610c43..23741e9f8 100644 --- a/Essentials/src/com/earth2me/essentials/commands/QuietAbortException.java +++ b/Essentials/src/com/earth2me/essentials/commands/QuietAbortException.java @@ -1,12 +1,11 @@ package com.earth2me.essentials.commands; - public class QuietAbortException extends Exception { public QuietAbortException() { super(); } - public QuietAbortException(String message) { + public QuietAbortException(final String message) { super(message); } } diff --git a/Essentials/src/com/earth2me/essentials/commands/WarpNotFoundException.java b/Essentials/src/com/earth2me/essentials/commands/WarpNotFoundException.java index c6e4cdbf6..e72dc4124 100644 --- a/Essentials/src/com/earth2me/essentials/commands/WarpNotFoundException.java +++ b/Essentials/src/com/earth2me/essentials/commands/WarpNotFoundException.java @@ -7,7 +7,7 @@ public class WarpNotFoundException extends Exception { super(tl("warpNotExist")); } - public WarpNotFoundException(String message) { + public WarpNotFoundException(final String message) { super(message); } } diff --git a/Essentials/src/com/earth2me/essentials/craftbukkit/BanLookup.java b/Essentials/src/com/earth2me/essentials/craftbukkit/BanLookup.java index b20cded7d..65cc2a401 100644 --- a/Essentials/src/com/earth2me/essentials/craftbukkit/BanLookup.java +++ b/Essentials/src/com/earth2me/essentials/craftbukkit/BanLookup.java @@ -7,19 +7,22 @@ import org.bukkit.BanList; import java.util.Set; +public final class BanLookup { -public class BanLookup { - public static Boolean isBanned(IEssentials ess, User user) { + private BanLookup() { + } + + public static Boolean isBanned(final IEssentials ess, final User user) { return isBanned(ess, user.getName()); } - public static Boolean isBanned(IEssentials ess, String name) { + public static Boolean isBanned(final IEssentials ess, final String name) { return getBanEntry(ess, name) != null; } - public static BanEntry getBanEntry(IEssentials ess, String name) { - Set benteries = ess.getServer().getBanList(BanList.Type.NAME).getBanEntries(); - for (BanEntry banEnt : benteries) { + public static BanEntry getBanEntry(final IEssentials ess, final String name) { + final Set benteries = ess.getServer().getBanList(BanList.Type.NAME).getBanEntries(); + for (final BanEntry banEnt : benteries) { if (banEnt.getTarget().equals(name)) { return banEnt; } diff --git a/Essentials/src/com/earth2me/essentials/craftbukkit/FakeWorld.java b/Essentials/src/com/earth2me/essentials/craftbukkit/FakeWorld.java index fec2763d1..70eaac12f 100644 --- a/Essentials/src/com/earth2me/essentials/craftbukkit/FakeWorld.java +++ b/Essentials/src/com/earth2me/essentials/craftbukkit/FakeWorld.java @@ -50,53 +50,52 @@ import java.util.Set; import java.util.UUID; import java.util.function.Predicate; - public class FakeWorld implements World { private final String name; private final Environment env; - public FakeWorld(String string, Environment environment) { + public FakeWorld(final String string, final Environment environment) { this.name = string; this.env = environment; } @Override - public Block getBlockAt(int i, int i1, int i2) { + public Block getBlockAt(final int i, final int i1, final int i2) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Block getBlockAt(Location lctn) { + public Block getBlockAt(final Location lctn) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public int getHighestBlockYAt(int i, int i1) { + public int getHighestBlockYAt(final int i, final int i1) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public int getHighestBlockYAt(Location lctn) { + public int getHighestBlockYAt(final Location lctn) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Chunk getChunkAt(int i, int i1) { + public Chunk getChunkAt(final int i, final int i1) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Chunk getChunkAt(Location lctn) { + public Chunk getChunkAt(final Location lctn) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Chunk getChunkAt(Block block) { + public Chunk getChunkAt(final Block block) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean isChunkLoaded(Chunk chunk) { + public boolean isChunkLoaded(final Chunk chunk) { throw new UnsupportedOperationException("Not supported yet."); } @@ -106,72 +105,72 @@ public class FakeWorld implements World { } @Override - public void loadChunk(Chunk chunk) { + public void loadChunk(final Chunk chunk) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean isChunkLoaded(int i, int i1) { + public boolean isChunkLoaded(final int i, final int i1) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean isChunkGenerated(int x, int z) { + public boolean isChunkGenerated(final int x, final int z) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void loadChunk(int i, int i1) { + public void loadChunk(final int i, final int i1) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean loadChunk(int i, int i1, boolean bln) { + public boolean loadChunk(final int i, final int i1, final boolean bln) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean unloadChunk(int i, int i1) { + public boolean unloadChunk(final int i, final int i1) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean unloadChunk(int i, int i1, boolean bln) { + public boolean unloadChunk(final int i, final int i1, final boolean bln) { throw new UnsupportedOperationException("Not supported yet."); } //@Override - public boolean unloadChunk(int i, int i1, boolean bln, boolean bln1) { + public boolean unloadChunk(final int i, final int i1, final boolean bln, final boolean bln1) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean unloadChunkRequest(int i, int i1) { + public boolean unloadChunkRequest(final int i, final int i1) { throw new UnsupportedOperationException("Not supported yet."); } //@Override - public boolean unloadChunkRequest(int i, int i1, boolean bln) { + public boolean unloadChunkRequest(final int i, final int i1, final boolean bln) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean regenerateChunk(int i, int i1) { + public boolean regenerateChunk(final int i, final int i1) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean refreshChunk(int i, int i1) { + public boolean refreshChunk(final int i, final int i1) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean isChunkForceLoaded(int i, int i1) { + public boolean isChunkForceLoaded(final int i, final int i1) { return false; } @Override - public void setChunkForceLoaded(int i, int i1, boolean b) { + public void setChunkForceLoaded(final int i, final int i1, final boolean b) { } @@ -181,22 +180,22 @@ public class FakeWorld implements World { } @Override - public boolean addPluginChunkTicket(int i, int i1, Plugin plugin) { + public boolean addPluginChunkTicket(final int i, final int i1, final Plugin plugin) { return false; } @Override - public boolean removePluginChunkTicket(int i, int i1, Plugin plugin) { + public boolean removePluginChunkTicket(final int i, final int i1, final Plugin plugin) { return false; } @Override - public void removePluginChunkTickets(Plugin plugin) { + public void removePluginChunkTickets(final Plugin plugin) { } @Override - public Collection getPluginChunkTickets(int i, int i1) { + public Collection getPluginChunkTickets(final int i, final int i1) { return null; } @@ -205,44 +204,43 @@ public class FakeWorld implements World { return null; } - @Override - public Item dropItem(Location lctn, ItemStack is) { + public Item dropItem(final Location lctn, final ItemStack is) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Item dropItemNaturally(Location lctn, ItemStack is) { + public Item dropItemNaturally(final Location lctn, final ItemStack is) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Arrow spawnArrow(Location lctn, Vector vector, float f, float f1) { + public Arrow spawnArrow(final Location lctn, final Vector vector, final float f, final float f1) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public T spawnArrow(Location location, Vector vector, float v, float v1, Class aClass) { + public T spawnArrow(final Location location, final Vector vector, final float v, final float v1, final Class aClass) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean generateTree(Location lctn, TreeType tt) { + public boolean generateTree(final Location lctn, final TreeType tt) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean generateTree(Location loc, TreeType type, BlockChangeDelegate delegate) { + public boolean generateTree(final Location loc, final TreeType type, final BlockChangeDelegate delegate) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public LightningStrike strikeLightning(Location lctn) { + public LightningStrike strikeLightning(final Location lctn) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public LightningStrike strikeLightningEffect(Location lctn) { + public LightningStrike strikeLightningEffect(final Location lctn) { throw new UnsupportedOperationException("Not supported yet."); } @@ -272,17 +270,17 @@ public class FakeWorld implements World { } @Override - public boolean setSpawnLocation(Location location) { + public boolean setSpawnLocation(final Location location) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean setSpawnLocation(int i, int i1, int i2, float v) { + public boolean setSpawnLocation(final int i, final int i1, final int i2, final float v) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean setSpawnLocation(int i, int i1, int i2) { + public boolean setSpawnLocation(final int i, final int i1, final int i2) { throw new UnsupportedOperationException("Not supported yet."); } @@ -292,7 +290,7 @@ public class FakeWorld implements World { } @Override - public void setTime(long l) { + public void setTime(final long l) { throw new UnsupportedOperationException("Not supported yet."); } @@ -302,7 +300,7 @@ public class FakeWorld implements World { } @Override - public void setFullTime(long l) { + public void setFullTime(final long l) { throw new UnsupportedOperationException("Not supported yet."); } @@ -312,7 +310,7 @@ public class FakeWorld implements World { } @Override - public void setStorm(boolean bln) { + public void setStorm(final boolean bln) { throw new UnsupportedOperationException("Not supported yet."); } @@ -322,7 +320,7 @@ public class FakeWorld implements World { } @Override - public void setWeatherDuration(int i) { + public void setWeatherDuration(final int i) { throw new UnsupportedOperationException("Not supported yet."); } @@ -332,7 +330,7 @@ public class FakeWorld implements World { } @Override - public void setThundering(boolean bln) { + public void setThundering(final boolean bln) { throw new UnsupportedOperationException("Not supported yet."); } @@ -342,7 +340,7 @@ public class FakeWorld implements World { } @Override - public void setThunderDuration(int i) { + public void setThunderDuration(final int i) { throw new UnsupportedOperationException("Not supported yet."); } @@ -362,7 +360,7 @@ public class FakeWorld implements World { } @Override - public void setPVP(boolean bln) { + public void setPVP(final boolean bln) { throw new UnsupportedOperationException("Not supported yet."); } @@ -372,12 +370,12 @@ public class FakeWorld implements World { } @Override - public boolean createExplosion(double d, double d1, double d2, float f) { + public boolean createExplosion(final double d, final double d1, final double d2, final float f) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean createExplosion(Location lctn, float f) { + public boolean createExplosion(final Location lctn, final float f) { throw new UnsupportedOperationException("Not supported yet."); } @@ -392,62 +390,62 @@ public class FakeWorld implements World { } @Override - public void playEffect(Location lctn, Effect effect, int i) { + public void playEffect(final Location lctn, final Effect effect, final int i) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void playEffect(Location lctn, Effect effect, int i, int i1) { + public void playEffect(final Location lctn, final Effect effect, final int i, final int i1) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean createExplosion(double d, double d1, double d2, float f, boolean bln) { + public boolean createExplosion(final double d, final double d1, final double d2, final float f, final boolean bln) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean createExplosion(Location lctn, float f, boolean bln) { + public boolean createExplosion(final Location lctn, final float f, final boolean bln) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean createExplosion(Location location, float v, boolean b, boolean b1) { + public boolean createExplosion(final Location location, final float v, final boolean b, final boolean b1) { return false; } @Override - public boolean createExplosion(Location location, float v, boolean b, boolean b1, Entity entity) { + public boolean createExplosion(final Location location, final float v, final boolean b, final boolean b1, final Entity entity) { return false; } @Override - public T spawn(Location lctn, Class type) throws IllegalArgumentException { + public T spawn(final Location lctn, final Class type) throws IllegalArgumentException { throw new UnsupportedOperationException("Not supported yet."); } @Override - public T spawn(Location location, Class aClass, org.bukkit.util.Consumer consumer) throws IllegalArgumentException { + public T spawn(final Location location, final Class aClass, final org.bukkit.util.Consumer consumer) throws IllegalArgumentException { throw new UnsupportedOperationException("Not supported yet."); } @Override - public FallingBlock spawnFallingBlock(Location location, MaterialData materialData) throws IllegalArgumentException { + public FallingBlock spawnFallingBlock(final Location location, final MaterialData materialData) throws IllegalArgumentException { throw new UnsupportedOperationException("Not supported yet."); } @Override - public FallingBlock spawnFallingBlock(Location location, BlockData blockData) throws IllegalArgumentException { + public FallingBlock spawnFallingBlock(final Location location, final BlockData blockData) throws IllegalArgumentException { throw new UnsupportedOperationException("Not supported yet."); } @Override - public ChunkSnapshot getEmptyChunkSnapshot(int i, int i1, boolean bln, boolean bln1) { + public ChunkSnapshot getEmptyChunkSnapshot(final int i, final int i1, final boolean bln, final boolean bln1) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void setSpawnFlags(boolean bln, boolean bln1) { + public void setSpawnFlags(final boolean bln, final boolean bln1) { throw new UnsupportedOperationException("Not supported yet."); } @@ -467,67 +465,67 @@ public class FakeWorld implements World { } @Override - public Block getHighestBlockAt(int i, int i1) { + public Block getHighestBlockAt(final int i, final int i1) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Block getHighestBlockAt(Location lctn) { + public Block getHighestBlockAt(final Location lctn) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public int getHighestBlockYAt(int i, int i1, HeightMap heightMap) { + public int getHighestBlockYAt(final int i, final int i1, final HeightMap heightMap) { return 0; } @Override - public int getHighestBlockYAt(Location location, HeightMap heightMap) { + public int getHighestBlockYAt(final Location location, final HeightMap heightMap) { return 0; } @Override - public Block getHighestBlockAt(int i, int i1, HeightMap heightMap) { + public Block getHighestBlockAt(final int i, final int i1, final HeightMap heightMap) { return null; } @Override - public Block getHighestBlockAt(Location location, HeightMap heightMap) { + public Block getHighestBlockAt(final Location location, final HeightMap heightMap) { return null; } @Override - public Biome getBiome(int i, int i1) { + public Biome getBiome(final int i, final int i1) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Biome getBiome(int i, int i1, int i2) { + public Biome getBiome(final int i, final int i1, final int i2) { return null; } @Override - public double getTemperature(int i, int i1) { + public double getTemperature(final int i, final int i1) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public double getTemperature(int i, int i1, int i2) { + public double getTemperature(final int i, final int i1, final int i2) { return 0; } @Override - public double getHumidity(int i, int i1) { + public double getHumidity(final int i, final int i1) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public double getHumidity(int i, int i1, int i2) { + public double getHumidity(final int i, final int i1, final int i2) { return 0; } @Override - public boolean unloadChunk(Chunk chunk) { + public boolean unloadChunk(final Chunk chunk) { throw new UnsupportedOperationException("Not supported yet."); } @@ -542,7 +540,7 @@ public class FakeWorld implements World { } @Override - public void setKeepSpawnInMemory(boolean bln) { + public void setKeepSpawnInMemory(final boolean bln) { throw new UnsupportedOperationException("Not supported yet."); } @@ -552,7 +550,7 @@ public class FakeWorld implements World { } @Override - public void setAutoSave(boolean bln) { + public void setAutoSave(final boolean bln) { throw new UnsupportedOperationException("Not supported yet."); } @@ -562,7 +560,7 @@ public class FakeWorld implements World { } @Override - public void setDifficulty(Difficulty difficulty) { + public void setDifficulty(final Difficulty difficulty) { throw new UnsupportedOperationException("Not supported yet."); } @@ -577,7 +575,7 @@ public class FakeWorld implements World { } @Override - public Collection getEntitiesByClass(Class... types) { + public Collection getEntitiesByClass(final Class... types) { throw new UnsupportedOperationException("Not supported yet."); } @@ -587,7 +585,7 @@ public class FakeWorld implements World { } @Override - public void sendPluginMessage(Plugin plugin, String string, byte[] bytes) { + public void sendPluginMessage(final Plugin plugin, final String string, final byte[] bytes) { throw new UnsupportedOperationException("Not supported yet."); } @@ -607,7 +605,7 @@ public class FakeWorld implements World { } @Override - public void setHardcore(boolean b) { + public void setHardcore(final boolean b) { } @@ -617,7 +615,7 @@ public class FakeWorld implements World { } @Override - public void setTicksPerAnimalSpawns(int i) { + public void setTicksPerAnimalSpawns(final int i) { throw new UnsupportedOperationException("Not supported yet."); } @@ -627,7 +625,7 @@ public class FakeWorld implements World { } @Override - public void setTicksPerMonsterSpawns(int i) { + public void setTicksPerMonsterSpawns(final int i) { throw new UnsupportedOperationException("Not supported yet."); } @@ -637,7 +635,7 @@ public class FakeWorld implements World { } @Override - public void setTicksPerWaterSpawns(int i) { + public void setTicksPerWaterSpawns(final int i) { } @@ -647,7 +645,7 @@ public class FakeWorld implements World { } @Override - public void setTicksPerWaterAmbientSpawns(int i) { + public void setTicksPerWaterAmbientSpawns(final int i) { } @@ -657,57 +655,57 @@ public class FakeWorld implements World { } @Override - public void setTicksPerAmbientSpawns(int i) { + public void setTicksPerAmbientSpawns(final int i) { } @Override - public Collection getEntitiesByClass(Class type) { + public Collection getEntitiesByClass(final Class type) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Collection getEntitiesByClasses(Class... types) { + public Collection getEntitiesByClasses(final Class... types) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void playEffect(Location lctn, Effect effect, T t) { + public void playEffect(final Location lctn, final Effect effect, final T t) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void playEffect(Location lctn, Effect effect, T t, int i) { + public void playEffect(final Location lctn, final Effect effect, final T t, final int i) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void setMetadata(String string, MetadataValue mv) { + public void setMetadata(final String string, final MetadataValue mv) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public List getMetadata(String string) { + public List getMetadata(final String string) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean hasMetadata(String string) { + public boolean hasMetadata(final String string) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void removeMetadata(String string, Plugin plugin) { + public void removeMetadata(final String string, final Plugin plugin) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void setBiome(int arg0, int arg1, Biome arg2) { + public void setBiome(final int arg0, final int arg1, final Biome arg2) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void setBiome(int i, int i1, int i2, Biome biome) { + public void setBiome(final int i, final int i1, final int i2, final Biome biome) { } @@ -717,7 +715,7 @@ public class FakeWorld implements World { } @Override - public void setMonsterSpawnLimit(int arg0) { + public void setMonsterSpawnLimit(final int arg0) { throw new UnsupportedOperationException("Not supported yet."); } @@ -727,7 +725,7 @@ public class FakeWorld implements World { } @Override - public void setAnimalSpawnLimit(int arg0) { + public void setAnimalSpawnLimit(final int arg0) { throw new UnsupportedOperationException("Not supported yet."); } @@ -737,7 +735,7 @@ public class FakeWorld implements World { } @Override - public void setWaterAnimalSpawnLimit(int arg0) { + public void setWaterAnimalSpawnLimit(final int arg0) { throw new UnsupportedOperationException("Not supported yet."); } @@ -747,42 +745,42 @@ public class FakeWorld implements World { } @Override - public void setWaterAmbientSpawnLimit(int i) { + public void setWaterAmbientSpawnLimit(final int i) { } @Override - public Entity spawnEntity(Location lctn, EntityType et) { + public Entity spawnEntity(final Location lctn, final EntityType et) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean isChunkInUse(int x, int z) { + public boolean isChunkInUse(final int x, final int z) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public FallingBlock spawnFallingBlock(Location location, Material material, byte data) throws IllegalArgumentException { + public FallingBlock spawnFallingBlock(final Location location, final Material material, final byte data) throws IllegalArgumentException { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void playSound(Location arg0, Sound arg1, float arg2, float arg3) { + public void playSound(final Location arg0, final Sound arg1, final float arg2, final float arg3) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void playSound(Location location, String s, float v, float v1) { + public void playSound(final Location location, final String s, final float v, final float v1) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void playSound(Location location, Sound sound, SoundCategory soundCategory, float v, float v1) { + public void playSound(final Location location, final Sound sound, final SoundCategory soundCategory, final float v, final float v1) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void playSound(Location location, String s, SoundCategory soundCategory, float v, float v1) { + public void playSound(final Location location, final String s, final SoundCategory soundCategory, final float v, final float v1) { throw new UnsupportedOperationException("Not supported yet."); } @@ -792,7 +790,7 @@ public class FakeWorld implements World { } @Override - public void setAmbientSpawnLimit(int i) { + public void setAmbientSpawnLimit(final int i) { throw new UnsupportedOperationException("Not supported yet."); } @@ -802,27 +800,27 @@ public class FakeWorld implements World { } @Override - public String getGameRuleValue(String string) { + public String getGameRuleValue(final String string) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean setGameRuleValue(String string, String string1) { + public boolean setGameRuleValue(final String string, final String string1) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean isGameRule(String string) { + public boolean isGameRule(final String string) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean createExplosion(double d, double d1, double d2, float f, boolean bln, boolean bln1) { + public boolean createExplosion(final double d, final double d1, final double d2, final float f, final boolean bln, final boolean bln1) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean createExplosion(double v, double v1, double v2, float v3, boolean b, boolean b1, Entity entity) { + public boolean createExplosion(final double v, final double v1, final double v2, final float v3, final boolean b, final boolean b1, final Entity entity) { return false; } @@ -832,77 +830,77 @@ public class FakeWorld implements World { } @Override - public void spawnParticle(Particle particle, Location location, int i) { + public void spawnParticle(final Particle particle, final Location location, final int i) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void spawnParticle(Particle particle, double v, double v1, double v2, int i) { + public void spawnParticle(final Particle particle, final double v, final double v1, final double v2, final int i) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void spawnParticle(Particle particle, Location location, int i, T t) { + public void spawnParticle(final Particle particle, final Location location, final int i, final T t) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void spawnParticle(Particle particle, double v, double v1, double v2, int i, T t) { + public void spawnParticle(final Particle particle, final double v, final double v1, final double v2, final int i, final T t) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void spawnParticle(Particle particle, Location location, int i, double v, double v1, double v2) { + public void spawnParticle(final Particle particle, final Location location, final int i, final double v, final double v1, final double v2) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void spawnParticle(Particle particle, double v, double v1, double v2, int i, double v3, double v4, double v5) { + public void spawnParticle(final Particle particle, final double v, final double v1, final double v2, final int i, final double v3, final double v4, final double v5) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void spawnParticle(Particle particle, Location location, int i, double v, double v1, double v2, T t) { + public void spawnParticle(final Particle particle, final Location location, final int i, final double v, final double v1, final double v2, final T t) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void spawnParticle(Particle particle, double v, double v1, double v2, int i, double v3, double v4, double v5, T t) { + public void spawnParticle(final Particle particle, final double v, final double v1, final double v2, final int i, final double v3, final double v4, final double v5, final T t) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void spawnParticle(Particle particle, Location location, int i, double v, double v1, double v2, double v3) { + public void spawnParticle(final Particle particle, final Location location, final int i, final double v, final double v1, final double v2, final double v3) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void spawnParticle(Particle particle, double v, double v1, double v2, int i, double v3, double v4, double v5, double v6) { + public void spawnParticle(final Particle particle, final double v, final double v1, final double v2, final int i, final double v3, final double v4, final double v5, final double v6) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void spawnParticle(Particle particle, Location location, int i, double v, double v1, double v2, double v3, T t) { + public void spawnParticle(final Particle particle, final Location location, final int i, final double v, final double v1, final double v2, final double v3, final T t) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void spawnParticle(Particle particle, double v, double v1, double v2, int i, double v3, double v4, double v5, double v6, T t) { + public void spawnParticle(final Particle particle, final double v, final double v1, final double v2, final int i, final double v3, final double v4, final double v5, final double v6, final T t) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void spawnParticle(Particle particle, Location location, int i, double v, double v1, double v2, double v3, T t, boolean b) { + public void spawnParticle(final Particle particle, final Location location, final int i, final double v, final double v1, final double v2, final double v3, final T t, final boolean b) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void spawnParticle(Particle particle, double v, double v1, double v2, int i, double v3, double v4, double v5, double v6, T t, boolean b) { + public void spawnParticle(final Particle particle, final double v, final double v1, final double v2, final int i, final double v3, final double v4, final double v5, final double v6, final T t, final boolean b) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Location locateNearestStructure(Location origin, StructureType structureType, int radius, boolean findUnexplored) { + public Location locateNearestStructure(final Location origin, final StructureType structureType, final int radius, final boolean findUnexplored) { throw new UnsupportedOperationException("Not supported yet."); } @@ -917,7 +915,7 @@ public class FakeWorld implements World { } @Override - public Raid locateNearestRaid(Location location, int i) { + public Raid locateNearestRaid(final Location location, final int i) { return null; } @@ -932,77 +930,77 @@ public class FakeWorld implements World { } @Override - public List getNearbyEntities(Location loc, double x, double y, double z) { + public List getNearbyEntities(final Location loc, final double x, final double y, final double z) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Collection getNearbyEntities(Location location, double v, double v1, double v2, Predicate predicate) { + public Collection getNearbyEntities(final Location location, final double v, final double v1, final double v2, final Predicate predicate) { return null; } @Override - public Collection getNearbyEntities(BoundingBox boundingBox) { + public Collection getNearbyEntities(final BoundingBox boundingBox) { return null; } @Override - public Collection getNearbyEntities(BoundingBox boundingBox, Predicate predicate) { + public Collection getNearbyEntities(final BoundingBox boundingBox, final Predicate predicate) { return null; } @Override - public RayTraceResult rayTraceEntities(Location location, Vector vector, double v) { + public RayTraceResult rayTraceEntities(final Location location, final Vector vector, final double v) { return null; } @Override - public RayTraceResult rayTraceEntities(Location location, Vector vector, double v, double v1) { + public RayTraceResult rayTraceEntities(final Location location, final Vector vector, final double v, final double v1) { return null; } @Override - public RayTraceResult rayTraceEntities(Location location, Vector vector, double v, Predicate predicate) { + public RayTraceResult rayTraceEntities(final Location location, final Vector vector, final double v, final Predicate predicate) { return null; } @Override - public RayTraceResult rayTraceEntities(Location location, Vector vector, double v, double v1, Predicate predicate) { + public RayTraceResult rayTraceEntities(final Location location, final Vector vector, final double v, final double v1, final Predicate predicate) { return null; } @Override - public RayTraceResult rayTraceBlocks(Location location, Vector vector, double v) { + public RayTraceResult rayTraceBlocks(final Location location, final Vector vector, final double v) { return null; } @Override - public RayTraceResult rayTraceBlocks(Location location, Vector vector, double v, FluidCollisionMode fluidCollisionMode) { + public RayTraceResult rayTraceBlocks(final Location location, final Vector vector, final double v, final FluidCollisionMode fluidCollisionMode) { return null; } @Override - public RayTraceResult rayTraceBlocks(Location location, Vector vector, double v, FluidCollisionMode fluidCollisionMode, boolean b) { + public RayTraceResult rayTraceBlocks(final Location location, final Vector vector, final double v, final FluidCollisionMode fluidCollisionMode, final boolean b) { return null; } @Override - public RayTraceResult rayTrace(Location location, Vector vector, double v, FluidCollisionMode fluidCollisionMode, boolean b, double v1, Predicate predicate) { + public RayTraceResult rayTrace(final Location location, final Vector vector, final double v, final FluidCollisionMode fluidCollisionMode, final boolean b, final double v1, final Predicate predicate) { return null; } @Override - public T getGameRuleDefault(GameRule arg0) { + public T getGameRuleDefault(final GameRule arg0) { throw new UnsupportedOperationException("Not supported yet."); - } + } - @Override - public T getGameRuleValue(GameRule arg0) { + @Override + public T getGameRuleValue(final GameRule arg0) { throw new UnsupportedOperationException("Not supported yet."); - } + } - @Override - public boolean setGameRule(GameRule arg0, T arg1) { + @Override + public boolean setGameRule(final GameRule arg0, final T arg1) { throw new UnsupportedOperationException("Not supported yet."); - } + } } diff --git a/Essentials/src/com/earth2me/essentials/craftbukkit/InventoryWorkaround.java b/Essentials/src/com/earth2me/essentials/craftbukkit/InventoryWorkaround.java index 146c8e102..177520879 100644 --- a/Essentials/src/com/earth2me/essentials/craftbukkit/InventoryWorkaround.java +++ b/Essentials/src/com/earth2me/essentials/craftbukkit/InventoryWorkaround.java @@ -17,6 +17,14 @@ import java.util.Map; */ public final class InventoryWorkaround { + /* + Spigot 1.9, for whatever reason, decided to merge the armor and main player inventories without providing a way + to access the main inventory. There's lots of ugly code in here to work around that. + */ + private static final int USABLE_PLAYER_INV_SIZE = 36; + // Hot-ish code so cache + private static Boolean hasMainHandSupport = null; + private InventoryWorkaround() { } @@ -34,18 +42,12 @@ public final class InventoryWorkaround { return -1; } - /* - Spigot 1.9, for whatever reason, decided to merge the armor and main player inventories without providing a way - to access the main inventory. There's lots of ugly code in here to work around that. - */ - private static final int USABLE_PLAYER_INV_SIZE = 36; - - private static boolean isCombinedInventory(Inventory inventory) { + private static boolean isCombinedInventory(final Inventory inventory) { return inventory instanceof PlayerInventory && inventory.getContents().length > USABLE_PLAYER_INV_SIZE; } // Clears inventory without clearing armor - public static void clearInventoryNoArmor(PlayerInventory inventory) { + public static void clearInventoryNoArmor(final PlayerInventory inventory) { if (isCombinedInventory(inventory)) { for (int i = 0; i < USABLE_PLAYER_INV_SIZE; i++) { inventory.setItem(i, null); @@ -55,8 +57,8 @@ public final class InventoryWorkaround { } } - private static Inventory makeTruncatedPlayerInventory(PlayerInventory playerInventory) { - Inventory fakeInventory = Bukkit.getServer().createInventory(null, USABLE_PLAYER_INV_SIZE); + private static Inventory makeTruncatedPlayerInventory(final PlayerInventory playerInventory) { + final Inventory fakeInventory = Bukkit.getServer().createInventory(null, USABLE_PLAYER_INV_SIZE); fakeInventory.setContents(Arrays.copyOf(playerInventory.getContents(), fakeInventory.getSize())); return fakeInventory; } @@ -64,7 +66,7 @@ public final class InventoryWorkaround { // Returns what it couldn't store // This will will abort if it couldn't store all items public static Map addAllItems(final Inventory inventory, final ItemStack... items) { - ItemStack[] contents = inventory.getContents(); + final ItemStack[] contents = inventory.getContents(); final Inventory fakeInventory; if (isCombinedInventory(inventory)) { @@ -73,16 +75,16 @@ public final class InventoryWorkaround { fakeInventory = Bukkit.getServer().createInventory(null, inventory.getType()); fakeInventory.setContents(contents); } - Map overflow = addItems(fakeInventory, items); + final Map overflow = addItems(fakeInventory, items); if (overflow.isEmpty()) { addItems(inventory, items); return null; } return addItems(fakeInventory, items); } - + public static Map addAllOversizedItems(final Inventory inventory, final int oversizedStacks, final ItemStack... items) { - ItemStack[] contents = inventory.getContents(); + final ItemStack[] contents = inventory.getContents(); final Inventory fakeInventory; if (isCombinedInventory(inventory)) { @@ -91,7 +93,7 @@ public final class InventoryWorkaround { fakeInventory = Bukkit.getServer().createInventory(null, inventory.getType()); fakeInventory.setContents(contents); } - Map overflow = addOversizedItems(fakeInventory, oversizedStacks, items); + final Map overflow = addOversizedItems(fakeInventory, oversizedStacks, items); if (overflow.isEmpty()) { addOversizedItems(inventory, oversizedStacks, items); return null; @@ -99,7 +101,6 @@ public final class InventoryWorkaround { return overflow; } - // Returns what it couldn't store public static Map addItems(final Inventory inventory, final ItemStack... items) { return addOversizedItems(inventory, 0, items); @@ -109,8 +110,8 @@ public final class InventoryWorkaround { // Set oversizedStack to below normal stack size to disable oversized stacks public static Map addOversizedItems(final Inventory inventory, final int oversizedStacks, final ItemStack... items) { if (isCombinedInventory(inventory)) { - Inventory fakeInventory = makeTruncatedPlayerInventory((PlayerInventory) inventory); - Map overflow = addOversizedItems(fakeInventory, oversizedStacks, items); + final Inventory fakeInventory = makeTruncatedPlayerInventory((PlayerInventory) inventory); + final Map overflow = addOversizedItems(fakeInventory, oversizedStacks, items); for (int i = 0; i < fakeInventory.getContents().length; i++) { inventory.setItem(i, fakeInventory.getContents()[i]); } @@ -119,15 +120,15 @@ public final class InventoryWorkaround { final Map leftover = new HashMap<>(); - /* + /* * TODO: some optimization - Create a 'firstPartial' with a 'fromIndex' - Record the lastPartial per Material - - * Cache firstEmpty result - */ + * Cache firstEmpty result + */ // combine items final ItemStack[] combined = new ItemStack[items.length]; - for (ItemStack item : items) { + for (final ItemStack item : items) { if (item == null || item.getAmount() < 1) { continue; } @@ -143,7 +144,6 @@ public final class InventoryWorkaround { } } - for (int i = 0; i < combined.length; i++) { final ItemStack item = combined[i]; if (item == null || item.getType() == Material.AIR) { @@ -199,16 +199,13 @@ public final class InventoryWorkaround { return leftover; } - // Hot-ish code so cache - private static Boolean hasMainHandSupport = null; - @SuppressWarnings("deprecation") - public static void setItemInMainHand(Player p, ItemStack item) { + public static void setItemInMainHand(final Player p, final ItemStack item) { if (hasMainHandSupport == null) { try { p.getInventory().setItemInMainHand(item); hasMainHandSupport = true; - } catch (Throwable e) { + } catch (final Throwable e) { p.setItemInHand(item); hasMainHandSupport = false; } @@ -222,12 +219,12 @@ public final class InventoryWorkaround { } @SuppressWarnings("deprecation") - public static void setItemInMainHand(EntityEquipment invent, ItemStack item) { + public static void setItemInMainHand(final EntityEquipment invent, final ItemStack item) { if (hasMainHandSupport == null) { try { invent.setItemInMainHand(item); hasMainHandSupport = true; - } catch (Throwable e) { + } catch (final Throwable e) { invent.setItemInHand(item); hasMainHandSupport = false; } @@ -241,12 +238,12 @@ public final class InventoryWorkaround { } @SuppressWarnings("deprecation") - public static void setItemInMainHandDropChance(EntityEquipment invent, float chance) { + public static void setItemInMainHandDropChance(final EntityEquipment invent, final float chance) { if (hasMainHandSupport == null) { try { invent.setItemInMainHandDropChance(chance); hasMainHandSupport = true; - } catch (Throwable e) { + } catch (final Throwable e) { invent.setItemInHandDropChance(chance); hasMainHandSupport = false; } @@ -259,13 +256,13 @@ public final class InventoryWorkaround { } } - public static void setItemInOffHand(Player p, ItemStack item) { + public static void setItemInOffHand(final Player p, final ItemStack item) { // This assumes that all builds that support a main hand also support an off hand. if (hasMainHandSupport == null || hasMainHandSupport) { try { p.getInventory().setItemInOffHand(item); hasMainHandSupport = true; - } catch (Throwable e) { + } catch (final Throwable e) { hasMainHandSupport = false; } } diff --git a/Essentials/src/com/earth2me/essentials/craftbukkit/SetExpFix.java b/Essentials/src/com/earth2me/essentials/craftbukkit/SetExpFix.java index 650e2c64d..cd8fc4c86 100644 --- a/Essentials/src/com/earth2me/essentials/craftbukkit/SetExpFix.java +++ b/Essentials/src/com/earth2me/essentials/craftbukkit/SetExpFix.java @@ -2,8 +2,11 @@ package com.earth2me.essentials.craftbukkit; import org.bukkit.entity.Player; +public final class SetExpFix { + + private SetExpFix() { + } -public class SetExpFix { //This method is used to update both the recorded total experience and displayed total experience. //We reset both types to prevent issues. public static void setTotalExperience(final Player player, final int exp) { @@ -79,8 +82,8 @@ public class SetExpFix { } public static int getExpUntilNextLevel(final Player player) { - int exp = Math.round(getExpAtLevel(player) * player.getExp()); - int nextLevel = player.getLevel(); + final int exp = Math.round(getExpAtLevel(player) * player.getExp()); + final int nextLevel = player.getLevel(); return getExpAtLevel(nextLevel) - exp; } -} \ No newline at end of file +} diff --git a/Essentials/src/com/earth2me/essentials/items/AbstractItemDb.java b/Essentials/src/com/earth2me/essentials/items/AbstractItemDb.java index 40a07bef7..e20034a0c 100644 --- a/Essentials/src/com/earth2me/essentials/items/AbstractItemDb.java +++ b/Essentials/src/com/earth2me/essentials/items/AbstractItemDb.java @@ -14,12 +14,24 @@ import org.bukkit.block.Banner; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.*; +import org.bukkit.inventory.meta.BannerMeta; +import org.bukkit.inventory.meta.BlockStateMeta; +import org.bukkit.inventory.meta.BookMeta; +import org.bukkit.inventory.meta.EnchantmentStorageMeta; +import org.bukkit.inventory.meta.FireworkMeta; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.LeatherArmorMeta; +import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.plugin.Plugin; import org.bukkit.potion.Potion; import org.bukkit.potion.PotionEffect; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.function.Function; import static com.earth2me.essentials.I18n.tl; @@ -27,17 +39,16 @@ import static com.earth2me.essentials.I18n.tl; public abstract class AbstractItemDb implements IConf, net.ess3.api.IItemDb { protected final IEssentials ess; + private final Map resolverMap = new HashMap<>(); protected boolean ready = false; - private final Map resolverMap = new HashMap<>(); - - AbstractItemDb(IEssentials ess) { + AbstractItemDb(final IEssentials ess) { this.ess = ess; } @Override - public void registerResolver(Plugin plugin, String name, ItemResolver resolver) throws Exception { - PluginKey key = PluginKey.fromKey(plugin, name); + public void registerResolver(final Plugin plugin, final String name, final ItemResolver resolver) throws Exception { + final PluginKey key = PluginKey.fromKey(plugin, name); if (resolverMap.containsKey(key)) { throw new Exception("Tried to add a duplicate resolver with name " + key.toString()); } @@ -46,8 +57,8 @@ public abstract class AbstractItemDb implements IConf, net.ess3.api.IItemDb { } @Override - public void unregisterResolver(Plugin plugin, String name) throws Exception { - PluginKey key = PluginKey.fromKey(plugin, name); + public void unregisterResolver(final Plugin plugin, final String name) throws Exception { + final PluginKey key = PluginKey.fromKey(plugin, name); if (!resolverMap.containsKey(key)) { throw new Exception("Tried to remove nonexistent resolver with name " + key.toString()); } @@ -56,7 +67,7 @@ public abstract class AbstractItemDb implements IConf, net.ess3.api.IItemDb { } @Override - public boolean isResolverPresent(Plugin plugin, String name) { + public boolean isResolverPresent(final Plugin plugin, final String name) { return resolverMap.containsKey(PluginKey.fromKey(plugin, name)); } @@ -66,9 +77,9 @@ public abstract class AbstractItemDb implements IConf, net.ess3.api.IItemDb { } @Override - public Map getResolvers(Plugin plugin) { - Map matchingResolvers = new HashMap<>(); - for (PluginKey key : resolverMap.keySet()) { + public Map getResolvers(final Plugin plugin) { + final Map matchingResolvers = new HashMap<>(); + for (final PluginKey key : resolverMap.keySet()) { if (key.getPlugin().equals(plugin)) { matchingResolvers.put(key, resolverMap.get(key)); } @@ -78,23 +89,23 @@ public abstract class AbstractItemDb implements IConf, net.ess3.api.IItemDb { } @Override - public ItemResolver getResolver(Plugin plugin, String name) { + public ItemResolver getResolver(final Plugin plugin, final String name) { return resolverMap.get(PluginKey.fromKey(plugin, name)); } @Override - public ItemStack get(String id) throws Exception { + public ItemStack get(final String id) throws Exception { return get(id, true); } - ItemStack tryResolverDeserialize(String id) { - for (PluginKey key : resolverMap.keySet()) { + ItemStack tryResolverDeserialize(final String id) { + for (final PluginKey key : resolverMap.keySet()) { if (ess.getSettings().isDebug()) { ess.getLogger().info(String.format("Trying to deserialize item '%s' with resolver '%s'...", id, key)); } - Function resolver = resolverMap.get(key); - ItemStack stack = resolver.apply(id); + final Function resolver = resolverMap.get(key); + final ItemStack stack = resolver.apply(id); if (stack != null) { return stack; @@ -104,14 +115,14 @@ public abstract class AbstractItemDb implements IConf, net.ess3.api.IItemDb { return null; } - String tryResolverSerialize(ItemStack stack) { - for (PluginKey key : resolverMap.keySet()) { + String tryResolverSerialize(final ItemStack stack) { + for (final PluginKey key : resolverMap.keySet()) { if (ess.getSettings().isDebug()) { ess.getLogger().info(String.format("Trying to serialize '%s' with resolver '%s'...", stack.toString(), key)); } - ItemResolver resolver = resolverMap.get(key); - String serialized = resolver.serialize(stack); + final ItemResolver resolver = resolverMap.get(key); + final String serialized = resolver.serialize(stack); if (serialized != null) { return serialized; @@ -122,9 +133,9 @@ public abstract class AbstractItemDb implements IConf, net.ess3.api.IItemDb { } Collection getResolverNames() { - List result = new ArrayList<>(); - for (ItemResolver resolver : resolverMap.values()) { - Collection resolverNames = resolver.getNames(); + final List result = new ArrayList<>(); + for (final ItemResolver resolver : resolverMap.values()) { + final Collection resolverNames = resolver.getNames(); if (resolverNames != null) { result.addAll(resolverNames); } @@ -133,22 +144,22 @@ public abstract class AbstractItemDb implements IConf, net.ess3.api.IItemDb { } @Override - public List getMatching(User user, String[] args) throws Exception { - List is = new ArrayList<>(); + public List getMatching(final User user, final String[] args) throws Exception { + final List is = new ArrayList<>(); if (args.length < 1) { is.add(user.getItemInHand().clone()); } else if (args[0].equalsIgnoreCase("hand")) { is.add(user.getItemInHand().clone()); } else if (args[0].equalsIgnoreCase("inventory") || args[0].equalsIgnoreCase("invent") || args[0].equalsIgnoreCase("all")) { - for (ItemStack stack : user.getBase().getInventory().getContents()) { + for (final ItemStack stack : user.getBase().getInventory().getContents()) { if (stack == null || stack.getType() == Material.AIR) { continue; } is.add(stack.clone()); } } else if (args[0].equalsIgnoreCase("blocks")) { - for (ItemStack stack : user.getBase().getInventory().getContents()) { + for (final ItemStack stack : user.getBase().getInventory().getContents()) { if (stack == null || stack.getType() == Material.AIR) { continue; } @@ -166,14 +177,14 @@ public abstract class AbstractItemDb implements IConf, net.ess3.api.IItemDb { } @Override - public String serialize(ItemStack is) { + public String serialize(final ItemStack is) { return serialize(is, true); } @Override - public String serialize(ItemStack is, boolean useResolvers) { + public String serialize(final ItemStack is, final boolean useResolvers) { if (useResolvers) { - String serialized = tryResolverSerialize(is); + final String serialized = tryResolverSerialize(is); if (serialized != null) { return serialized; } @@ -183,13 +194,13 @@ public abstract class AbstractItemDb implements IConf, net.ess3.api.IItemDb { if (VersionUtil.getServerBukkitVersion().isLowerThanOrEqualTo(VersionUtil.v1_12_2_R01) && is.getData().getData() != 0) { mat = mat + ":" + is.getData().getData(); } - int quantity = is.getAmount(); - StringBuilder sb = new StringBuilder(); // Add space AFTER you add something. We can trim at end. + final int quantity = is.getAmount(); + final StringBuilder sb = new StringBuilder(); // Add space AFTER you add something. We can trim at end. sb.append(mat).append(" ").append(quantity).append(" "); // ItemMeta applies to anything. if (is.hasItemMeta()) { - ItemMeta meta = is.getItemMeta(); + final ItemMeta meta = is.getItemMeta(); if (meta.hasDisplayName()) { sb.append("name:").append(meta.getDisplayName().replaceAll(" ", "_")).append(" "); } @@ -197,7 +208,7 @@ public abstract class AbstractItemDb implements IConf, net.ess3.api.IItemDb { if (meta.hasLore()) { sb.append("lore:"); boolean first = true; - for (String s : meta.getLore()) { + for (final String s : meta.getLore()) { // Add | before the line if it's not the first one. Easy but weird way // to do this since we need each line separated by | if (!first) { @@ -210,16 +221,16 @@ public abstract class AbstractItemDb implements IConf, net.ess3.api.IItemDb { } if (meta.hasEnchants()) { - for (Enchantment e : meta.getEnchants().keySet()) { + for (final Enchantment e : meta.getEnchants().keySet()) { sb.append(e.getName().toLowerCase()).append(":").append(meta.getEnchantLevel(e)).append(" "); } } - Set flags = meta.getItemFlags(); + final Set flags = meta.getItemFlags(); if (flags != null && !flags.isEmpty()) { sb.append("itemflags:"); boolean first = true; - for (ItemFlag flag : flags) { + for (final ItemFlag flag : flags) { if (!first) { sb.append(","); } @@ -235,7 +246,7 @@ public abstract class AbstractItemDb implements IConf, net.ess3.api.IItemDb { case WRITTEN_BOOK: // Everything from http://wiki.ess3.net/wiki/Item_Meta#Books in that order. // Interesting as I didn't see a way to do pages or chapters. - BookMeta bookMeta = (BookMeta) is.getItemMeta(); + final BookMeta bookMeta = (BookMeta) is.getItemMeta(); if (bookMeta.hasTitle()) { sb.append("title:").append(bookMeta.getTitle()).append(" "); } @@ -245,8 +256,8 @@ public abstract class AbstractItemDb implements IConf, net.ess3.api.IItemDb { // Only other thing it could have is lore but that's done up there ^^^ break; case ENCHANTED_BOOK: - EnchantmentStorageMeta enchantmentStorageMeta = (EnchantmentStorageMeta) is.getItemMeta(); - for (Enchantment e : enchantmentStorageMeta.getStoredEnchants().keySet()) { + final EnchantmentStorageMeta enchantmentStorageMeta = (EnchantmentStorageMeta) is.getItemMeta(); + for (final Enchantment e : enchantmentStorageMeta.getStoredEnchants().keySet()) { sb.append(e.getName().toLowerCase()).append(":").append(enchantmentStorageMeta.getStoredEnchantLevel(e)).append(" "); } break; @@ -254,13 +265,13 @@ public abstract class AbstractItemDb implements IConf, net.ess3.api.IItemDb { if (MaterialUtil.isFirework(material)) { // Everything from http://wiki.ess3.net/wiki/Item_Meta#Fireworks in that order. - FireworkMeta fireworkMeta = (FireworkMeta) is.getItemMeta(); + final FireworkMeta fireworkMeta = (FireworkMeta) is.getItemMeta(); if (fireworkMeta.hasEffects()) { - for (FireworkEffect effect : fireworkMeta.getEffects()) { + for (final FireworkEffect effect : fireworkMeta.getEffects()) { if (effect.getColors() != null && !effect.getColors().isEmpty()) { sb.append("color:"); boolean first = true; - for (Color c : effect.getColors()) { + for (final Color c : effect.getColors()) { if (!first) { sb.append(","); // same thing as above. } @@ -274,7 +285,7 @@ public abstract class AbstractItemDb implements IConf, net.ess3.api.IItemDb { if (effect.getFadeColors() != null && !effect.getFadeColors().isEmpty()) { sb.append("fade:"); boolean first = true; - for (Color c : effect.getFadeColors()) { + for (final Color c : effect.getFadeColors()) { if (!first) { sb.append(","); // same thing as above. } @@ -287,55 +298,55 @@ public abstract class AbstractItemDb implements IConf, net.ess3.api.IItemDb { sb.append("power:").append(fireworkMeta.getPower()).append(" "); } } else if (MaterialUtil.isPotion(material)) { - Potion potion = Potion.fromItemStack(is); - for (PotionEffect e : potion.getEffects()) { + final Potion potion = Potion.fromItemStack(is); + for (final PotionEffect e : potion.getEffects()) { // long but needs to be effect:speed power:2 duration:120 in that order. sb.append("splash:").append(potion.isSplash()).append(" ").append("effect:").append(e.getType().getName().toLowerCase()).append(" ").append("power:").append(e.getAmplifier()).append(" ").append("duration:").append(e.getDuration() / 20).append(" "); } } else if (MaterialUtil.isPlayerHead(material, is.getData().getData())) { // item stack with meta - SkullMeta skullMeta = (SkullMeta) is.getItemMeta(); + final SkullMeta skullMeta = (SkullMeta) is.getItemMeta(); if (skullMeta != null && skullMeta.hasOwner()) { sb.append("player:").append(skullMeta.getOwner()).append(" "); } } else if (MaterialUtil.isBanner(material)) { if (material.toString().contains("SHIELD")) { // Hacky fix for accessing Shield meta - https://github.com/drtshock/Essentials/pull/745#issuecomment-234843795 - BlockStateMeta shieldMeta = (BlockStateMeta) is.getItemMeta(); - Banner shieldBannerMeta = (Banner) shieldMeta.getBlockState(); - DyeColor baseDyeColor = shieldBannerMeta.getBaseColor(); + final BlockStateMeta shieldMeta = (BlockStateMeta) is.getItemMeta(); + final Banner shieldBannerMeta = (Banner) shieldMeta.getBlockState(); + final DyeColor baseDyeColor = shieldBannerMeta.getBaseColor(); if (baseDyeColor != null) { - int basecolor = baseDyeColor.getColor().asRGB(); + final int basecolor = baseDyeColor.getColor().asRGB(); sb.append("basecolor:").append(basecolor).append(" "); } - for (org.bukkit.block.banner.Pattern p : shieldBannerMeta.getPatterns()) { - String type = p.getPattern().getIdentifier(); - int color = p.getColor().getColor().asRGB(); + for (final org.bukkit.block.banner.Pattern p : shieldBannerMeta.getPatterns()) { + final String type = p.getPattern().getIdentifier(); + final int color = p.getColor().getColor().asRGB(); sb.append(type).append(",").append(color).append(" "); } } else { - BannerMeta bannerMeta = (BannerMeta) is.getItemMeta(); + final BannerMeta bannerMeta = (BannerMeta) is.getItemMeta(); if (bannerMeta != null) { DyeColor baseDyeColor = bannerMeta.getBaseColor(); if (baseDyeColor == null) { baseDyeColor = MaterialUtil.getColorOf(material); } if (baseDyeColor != null) { - int basecolor = baseDyeColor - .getColor() - .asRGB(); + final int basecolor = baseDyeColor + .getColor() + .asRGB(); sb.append("basecolor:").append(basecolor).append(" "); } - for (org.bukkit.block.banner.Pattern p : bannerMeta.getPatterns()) { - String type = p.getPattern().getIdentifier(); - int color = p.getColor().getColor().asRGB(); + for (final org.bukkit.block.banner.Pattern p : bannerMeta.getPatterns()) { + final String type = p.getPattern().getIdentifier(); + final int color = p.getColor().getColor().asRGB(); sb.append(type).append(",").append(color).append(" "); } } } } else if (MaterialUtil.isLeatherArmor(material)) { - LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) is.getItemMeta(); - int rgb = leatherArmorMeta.getColor().asRGB(); + final LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) is.getItemMeta(); + final int rgb = leatherArmorMeta.getColor().asRGB(); sb.append("color:").append(rgb).append(" "); } diff --git a/Essentials/src/com/earth2me/essentials/items/CustomItemResolver.java b/Essentials/src/com/earth2me/essentials/items/CustomItemResolver.java index 53e673792..b0c043b0a 100644 --- a/Essentials/src/com/earth2me/essentials/items/CustomItemResolver.java +++ b/Essentials/src/com/earth2me/essentials/items/CustomItemResolver.java @@ -3,30 +3,32 @@ package com.earth2me.essentials.items; import com.earth2me.essentials.Essentials; import com.earth2me.essentials.EssentialsConf; import com.earth2me.essentials.IConf; -import java.io.File; -import java.util.Collection; -import java.util.HashMap; import net.ess3.api.IItemDb; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.inventory.ItemStack; +import java.io.File; +import java.util.Collection; +import java.util.HashMap; + public class CustomItemResolver implements IItemDb.ItemResolver, IConf { private final EssentialsConf config; private final Essentials ess; private final HashMap map = new HashMap<>(); - public CustomItemResolver(Essentials ess) { + public CustomItemResolver(final Essentials ess) { config = new EssentialsConf(new File(ess.getDataFolder(), "custom_items.yml")); this.ess = ess; config.setTemplateName("/custom_items.yml"); } @Override - public ItemStack apply(String item) { + public ItemStack apply(final String item) { if (map.containsKey(item)) { try { return ess.getItemDb().get(map.get(item)); - } catch (Exception ignored) {} + } catch (final Exception ignored) { + } } return null; @@ -42,15 +44,15 @@ public class CustomItemResolver implements IItemDb.ItemResolver, IConf { map.clear(); config.load(); - ConfigurationSection section = config.getConfigurationSection("aliases"); + final ConfigurationSection section = config.getConfigurationSection("aliases"); if (section == null || section.getKeys(false).isEmpty()) { ess.getLogger().warning("No aliases found in custom_items.yml."); return; } - for (String alias : section.getKeys(false)) { + for (final String alias : section.getKeys(false)) { if (!section.isString(alias)) continue; - String target = section.getString(alias); + final String target = section.getString(alias); if (target != null && !section.contains(target) && existsInItemDb(target)) { map.put(alias, target); @@ -58,7 +60,7 @@ public class CustomItemResolver implements IItemDb.ItemResolver, IConf { } } - public void setAlias(String alias, String target) { + public void setAlias(final String alias, final String target) { if (map.containsKey(alias) && map.get(alias).equalsIgnoreCase(target)) { return; } @@ -67,7 +69,7 @@ public class CustomItemResolver implements IItemDb.ItemResolver, IConf { save(); } - public void removeAlias(String alias) { + public void removeAlias(final String alias) { if (map.remove(alias) != null) { save(); } @@ -78,11 +80,11 @@ public class CustomItemResolver implements IItemDb.ItemResolver, IConf { config.save(); } - private boolean existsInItemDb(String item) { + private boolean existsInItemDb(final String item) { try { ess.getItemDb().get(item); return true; - } catch (Exception e) { + } catch (final Exception e) { return false; } } diff --git a/Essentials/src/com/earth2me/essentials/items/FlatItemDb.java b/Essentials/src/com/earth2me/essentials/items/FlatItemDb.java index e33c476c9..64fa358cd 100644 --- a/Essentials/src/com/earth2me/essentials/items/FlatItemDb.java +++ b/Essentials/src/com/earth2me/essentials/items/FlatItemDb.java @@ -16,13 +16,18 @@ import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionData; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.logging.Logger; import java.util.stream.Collectors; import static com.earth2me.essentials.I18n.tl; - public class FlatItemDb extends AbstractItemDb { protected static final Logger LOGGER = Logger.getLogger("Essentials"); private static final Gson gson = new Gson(); @@ -55,7 +60,7 @@ public class FlatItemDb extends AbstractItemDb { private void rebuild() { this.reset(); - String json = file.getLines().stream() + final String json = file.getLines().stream() .filter(line -> !line.startsWith("#")) .collect(Collectors.joining()); @@ -71,24 +76,25 @@ public class FlatItemDb extends AbstractItemDb { allAliases.clear(); } - private void loadJSON(String source) { - JsonObject map = (new JsonParser()).parse(source).getAsJsonObject(); + private void loadJSON(final String source) { + final JsonObject map = new JsonParser().parse(source).getAsJsonObject(); - for (Map.Entry entry : map.entrySet()) { - String key = entry.getKey(); - JsonElement element = entry.getValue(); + for (final Map.Entry entry : map.entrySet()) { + final String key = entry.getKey(); + final JsonElement element = entry.getValue(); boolean valid = false; if (element.isJsonObject()) { - ItemData data = gson.fromJson(element, ItemData.class); + final ItemData data = gson.fromJson(element, ItemData.class); items.put(key, data); valid = true; } else { try { - String target = element.getAsString(); + final String target = element.getAsString(); itemAliases.put(key, target); valid = true; - } catch (Exception ignored) {} + } catch (final Exception ignored) { + } } if (valid) { @@ -100,9 +106,9 @@ public class FlatItemDb extends AbstractItemDb { } @Override - public ItemStack get(String id, boolean useResolvers) throws Exception { + public ItemStack get(String id, final boolean useResolvers) throws Exception { if (useResolvers) { - ItemStack resolved = tryResolverDeserialize(id); + final ItemStack resolved = tryResolverDeserialize(id); if (resolved != null) { return resolved; } @@ -111,31 +117,31 @@ public class FlatItemDb extends AbstractItemDb { id = id.toLowerCase(); final String[] split = id.split(":"); - ItemData data = getByName(split[0]); + final ItemData data = getByName(split[0]); if (data == null) { throw new Exception(tl("unknownItemName", id)); } - Material material = data.getMaterial(); + final Material material = data.getMaterial(); if (!material.isItem()) throw new Exception(tl("unableToSpawnItem", id)); - ItemStack stack = new ItemStack(material); + final ItemStack stack = new ItemStack(material); stack.setAmount(material.getMaxStackSize()); - PotionData potionData = data.getPotionData(); - ItemMeta meta = stack.getItemMeta(); + final PotionData potionData = data.getPotionData(); + final ItemMeta meta = stack.getItemMeta(); if (potionData != null && meta instanceof PotionMeta) { - PotionMeta potionMeta = (PotionMeta) meta; + final PotionMeta potionMeta = (PotionMeta) meta; potionMeta.setBasePotionData(potionData); } // For some reason, Damageable doesn't extend ItemMeta but CB implements them in the same // class. As to why, your guess is as good as mine. if (split.length > 1 && meta instanceof Damageable) { - Damageable damageMeta = (Damageable) meta; + final Damageable damageMeta = (Damageable) meta; damageMeta.setDamage(Integer.parseInt(split[1])); } @@ -143,7 +149,7 @@ public class FlatItemDb extends AbstractItemDb { // The spawner provider will update the meta again, so we need to call it after // setItemMeta to prevent a race condition - EntityType entity = data.getEntity(); + final EntityType entity = data.getEntity(); if (entity != null && material.toString().contains("SPAWNER")) { ess.getSpawnerItemProvider().setEntityType(stack, entity); } @@ -163,12 +169,12 @@ public class FlatItemDb extends AbstractItemDb { } @Override - public List nameList(ItemStack item) { - List names = new ArrayList<>(); - String primaryName = name(item); + public List nameList(final ItemStack item) { + final List names = new ArrayList<>(); + final String primaryName = name(item); names.add(primaryName); - for (Map.Entry entry : itemAliases.entrySet()) { + for (final Map.Entry entry : itemAliases.entrySet()) { if (entry.getValue().equalsIgnoreCase(primaryName)) { names.add(entry.getKey()); } @@ -178,10 +184,10 @@ public class FlatItemDb extends AbstractItemDb { } @Override - public String name(ItemStack item) { - ItemData data = lookup(item); + public String name(final ItemStack item) { + final ItemData data = lookup(item); - for (Map.Entry entry : items.entrySet()) { + for (final Map.Entry entry : items.entrySet()) { if (entry.getValue().equals(data)) { return entry.getKey(); } @@ -192,18 +198,18 @@ public class FlatItemDb extends AbstractItemDb { @Override @Deprecated - public int getLegacyId(Material material) { + public int getLegacyId(final Material material) { throw new UnsupportedOperationException("Legacy IDs aren't supported on this version."); } - private ItemData lookup(ItemStack item) { - Material type = item.getType(); + private ItemData lookup(final ItemStack item) { + final Material type = item.getType(); if (MaterialUtil.isPotion(type) && item.getItemMeta() instanceof PotionMeta) { - PotionData potion = ((PotionMeta) item.getItemMeta()).getBasePotionData(); + final PotionData potion = ((PotionMeta) item.getItemMeta()).getBasePotionData(); return new ItemData(type, potion); } else if (type.toString().contains("SPAWNER")) { - EntityType entity = ess.getSpawnerItemProvider().getEntityType(item); + final EntityType entity = ess.getSpawnerItemProvider().getEntityType(item); return new ItemData(type, entity); } else { return new ItemData(type); @@ -212,7 +218,7 @@ public class FlatItemDb extends AbstractItemDb { @Override public Collection listNames() { - Set names = new HashSet<>(allAliases); + final Set names = new HashSet<>(allAliases); names.addAll(getResolverNames()); return names; } @@ -223,16 +229,16 @@ public class FlatItemDb extends AbstractItemDb { private PotionData potionData = null; private EntityType entity = null; - ItemData(Material material) { + ItemData(final Material material) { this.material = material; } - ItemData(Material material, PotionData potionData) { + ItemData(final Material material, final PotionData potionData) { this.material = material; this.potionData = potionData; } - ItemData(Material material, EntityType entity) { + ItemData(final Material material, final EntityType entity) { this.material = material; this.entity = entity; } @@ -243,14 +249,14 @@ public class FlatItemDb extends AbstractItemDb { } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { if (o == null) { return false; } if (!(o instanceof ItemData)) { return false; } - ItemData that = (ItemData) o; + final ItemData that = (ItemData) o; return this.getMaterial() == that.getMaterial() && potionDataEquals(that) && entityEquals(that); } @@ -271,7 +277,7 @@ public class FlatItemDb extends AbstractItemDb { return this.entity; } - private boolean potionDataEquals(ItemData o) { + private boolean potionDataEquals(final ItemData o) { if (this.potionData == null && o.getPotionData() == null) { return true; } else if (this.potionData != null && o.getPotionData() != null) { @@ -281,7 +287,7 @@ public class FlatItemDb extends AbstractItemDb { } } - private boolean entityEquals(ItemData o) { + private boolean entityEquals(final ItemData o) { if (this.entity == null && o.getEntity() == null) { // neither have an entity return true; } else if (this.entity != null && o.getEntity() != null) { // both have an entity; check if it's the same one diff --git a/Essentials/src/com/earth2me/essentials/items/LegacyItemDb.java b/Essentials/src/com/earth2me/essentials/items/LegacyItemDb.java index a7d3457f3..f9bd11677 100644 --- a/Essentials/src/com/earth2me/essentials/items/LegacyItemDb.java +++ b/Essentials/src/com/earth2me/essentials/items/LegacyItemDb.java @@ -10,14 +10,19 @@ import org.bukkit.Material; import org.bukkit.entity.EntityType; import org.bukkit.inventory.ItemStack; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.earth2me.essentials.I18n.tl; - public class LegacyItemDb extends AbstractItemDb { protected static final Logger LOGGER = Logger.getLogger("Essentials"); private final transient Map items = new HashMap<>(); @@ -49,7 +54,7 @@ public class LegacyItemDb extends AbstractItemDb { names.clear(); primaryName.clear(); - for (String line : lines) { + for (final String line : lines) { if (line.length() > 0 && line.charAt(0) == '#') { continue; } @@ -60,7 +65,7 @@ public class LegacyItemDb extends AbstractItemDb { String nbt = null; int col = 0; - Matcher matcher = csvSplitPattern.matcher(line); + final Matcher matcher = csvSplitPattern.matcher(line); while (matcher.find()) { String match = matcher.group(1); if (StringUtils.stripToNull(match) == null) { @@ -96,12 +101,12 @@ public class LegacyItemDb extends AbstractItemDb { nbtData.put(itemName, nbt); } - ItemData itemData = new ItemData(numeric, data); + final ItemData itemData = new ItemData(numeric, data); if (names.containsKey(itemData)) { - List nameList = names.get(itemData); + final List nameList = names.get(itemData); nameList.add(itemName); } else { - List nameList = new ArrayList<>(); + final List nameList = new ArrayList<>(); nameList.add(itemName); names.put(itemData, nameList); primaryName.put(itemData, itemName); @@ -110,7 +115,7 @@ public class LegacyItemDb extends AbstractItemDb { legacyIds.put(numeric, itemData); } - for (List nameList : names.values()) { + for (final List nameList : names.values()) { nameList.sort(LengthCompare.INSTANCE); } @@ -122,7 +127,7 @@ public class LegacyItemDb extends AbstractItemDb { @Override public ItemStack get(final String id, final boolean useResolvers) throws Exception { if (useResolvers) { - ItemStack resolved = tryResolverDeserialize(id); + final ItemStack resolved = tryResolverDeserialize(id); if (resolved != null) { return resolved; } @@ -131,7 +136,7 @@ public class LegacyItemDb extends AbstractItemDb { int itemid = 0; String itemname; short metaData = 0; - Matcher parts = splitPattern.matcher(id); + final Matcher parts = splitPattern.matcher(id); if (parts.matches()) { itemname = parts.group(2); metaData = Short.parseShort(parts.group(3)); @@ -157,7 +162,7 @@ public class LegacyItemDb extends AbstractItemDb { } if (itemid < 1) { - Material matFromName = EnumUtil.getMaterial(itemname.toUpperCase()); + final Material matFromName = EnumUtil.getMaterial(itemname.toUpperCase()); if (matFromName != null) { itemid = matFromName.getId(); } @@ -167,12 +172,12 @@ public class LegacyItemDb extends AbstractItemDb { throw new Exception(tl("unknownItemName", itemname)); } - ItemData data = legacyIds.get(itemid); + final ItemData data = legacyIds.get(itemid); if (data == null) { throw new Exception(tl("unknownItemId", itemid)); } - Material mat = getFromLegacy(itemid, (byte) metaData); + final Material mat = getFromLegacy(itemid, (byte) metaData); ItemStack retval = new ItemStack(mat); if (nbtData.containsKey(itemname)) { String nbt = nbtData.get(itemname); @@ -181,24 +186,24 @@ public class LegacyItemDb extends AbstractItemDb { } retval = ess.getServer().getUnsafe().modifyItemStack(retval, nbt); } - Material MOB_SPAWNER = EnumUtil.getMaterial("SPAWNER", "MOB_SPAWNER"); + final Material MOB_SPAWNER = EnumUtil.getMaterial("SPAWNER", "MOB_SPAWNER"); if (mat == MOB_SPAWNER) { if (metaData == 0) metaData = EntityType.PIG.getTypeId(); try { retval = ess.getSpawnerItemProvider().setEntityType(retval, EntityType.fromId(metaData)); - } catch (IllegalArgumentException e) { + } catch (final IllegalArgumentException e) { throw new Exception("Can't spawn entity ID " + metaData + " from mob spawners."); } } else if (mat.name().contains("MONSTER_EGG")) { - EntityType type; + final EntityType type; try { type = EntityType.fromId(metaData); - } catch (IllegalArgumentException e) { + } catch (final IllegalArgumentException e) { throw new Exception("Can't spawn entity ID " + metaData + " from spawn eggs."); } retval = ess.getSpawnEggProvider().createEggItem(type); } else if (mat.name().endsWith("POTION") - && ReflUtil.getNmsVersionObject().isLowerThan(ReflUtil.V1_11_R1)) { // Only apply this to pre-1.11 as items.csv might only work in 1.11 + && ReflUtil.getNmsVersionObject().isLowerThan(ReflUtil.V1_11_R1)) { // Only apply this to pre-1.11 as items.csv might only work in 1.11 retval = ess.getPotionMetaProvider().createPotionItem(mat, metaData); } else { retval.setDurability(metaData); @@ -208,7 +213,7 @@ public class LegacyItemDb extends AbstractItemDb { } @Override - public List nameList(ItemStack item) { + public List nameList(final ItemStack item) { ItemData itemData = new ItemData(item.getType().getId(), item.getDurability()); List nameList = names.get(itemData); if (nameList == null) { @@ -223,7 +228,7 @@ public class LegacyItemDb extends AbstractItemDb { } @Override - public String name(ItemStack item) { + public String name(final ItemStack item) { ItemData itemData = new ItemData(item.getType().getId(), item.getDurability()); String name = primaryName.get(itemData); if (name == null) { @@ -234,9 +239,9 @@ public class LegacyItemDb extends AbstractItemDb { } @Override - public int getLegacyId(Material material) throws Exception { - for(Map.Entry entry : items.entrySet()) { - if(material.name().toLowerCase(Locale.ENGLISH).equalsIgnoreCase(entry.getKey())) { + public int getLegacyId(final Material material) throws Exception { + for (final Map.Entry entry : items.entrySet()) { + if (material.name().toLowerCase(Locale.ENGLISH).equalsIgnoreCase(entry.getKey())) { return entry.getValue(); } } @@ -246,7 +251,7 @@ public class LegacyItemDb extends AbstractItemDb { @Override public Collection listNames() { - Collection values = new ArrayList<>(primaryName.values()); + final Collection values = new ArrayList<>(primaryName.values()); values.addAll(getResolverNames()); return values; } @@ -274,29 +279,28 @@ public class LegacyItemDb extends AbstractItemDb { } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { if (o == null) { return false; } if (!(o instanceof ItemData)) { return false; } - ItemData pairo = (ItemData) o; + final ItemData pairo = (ItemData) o; return this.itemNo == pairo.getItemNo() && this.itemData == pairo.getItemData(); } } - static class LengthCompare implements java.util.Comparator { private static final LengthCompare INSTANCE = new LengthCompare(); - public LengthCompare() { + LengthCompare() { super(); } @Override - public int compare(String s1, String s2) { + public int compare(final String s1, final String s2) { return s1.length() - s2.length(); } } diff --git a/Essentials/src/com/earth2me/essentials/messaging/IMessageRecipient.java b/Essentials/src/com/earth2me/essentials/messaging/IMessageRecipient.java index dc3385cd7..284c656b7 100644 --- a/Essentials/src/com/earth2me/essentials/messaging/IMessageRecipient.java +++ b/Essentials/src/com/earth2me/essentials/messaging/IMessageRecipient.java @@ -19,8 +19,7 @@ public interface IMessageRecipient { * String)} implementation by the {@code sender}. * * @param recipient recipient to receive the {@code message} - * @param message message to send - * + * @param message message to send * @return the response of the message */ MessageResponse sendMessage(IMessageRecipient recipient, String message); @@ -30,12 +29,11 @@ public interface IMessageRecipient { *
* The {@link MessageResponse} that is returned is used to determine what exactly should happen in the {@link #sendMessage(IMessageRecipient, * String)} implementation by the {@code sender}. - *

+ *

* This method should only be called by {@link #sendMessage(IMessageRecipient, String)}. * - * @param sender sender of the {@code message} + * @param sender sender of the {@code message} * @param message message being received - * * @return the response of the message */ MessageResponse onReceiveMessage(IMessageRecipient sender, String message); @@ -44,7 +42,6 @@ public interface IMessageRecipient { * Returns the name of this recipient. This name is typically used internally to identify this recipient. * * @return name of this recipient - * * @see #getDisplayName() */ String getName(); @@ -82,17 +79,29 @@ public interface IMessageRecipient { * {@link IMessageRecipient#onReceiveMessage(IMessageRecipient, String)}. */ enum MessageResponse { - /** States that the message was received and assumed readable by the receiver. */ + /** + * States that the message was received and assumed readable by the receiver. + */ SUCCESS, - /** States that the message was received, but the receiver was away, assuming the message was not read. */ + /** + * States that the message was received, but the receiver was away, assuming the message was not read. + */ SUCCESS_BUT_AFK, - /** States that the message was NOT received as a result of the receiver ignoring all messages. */ + /** + * States that the message was NOT received as a result of the receiver ignoring all messages. + */ MESSAGES_IGNORED, - /** States that the message was NOT received as a result of the sender being ignored by the recipient. */ + /** + * States that the message was NOT received as a result of the sender being ignored by the recipient. + */ SENDER_IGNORED, - /** States that the message was NOT received as a result of the recipient being unreachable. */ + /** + * States that the message was NOT received as a result of the recipient being unreachable. + */ UNREACHABLE, - /** States that the message was NOT received as a result of the message pre-send event being cancelled. */ + /** + * States that the message was NOT received as a result of the message pre-send event being cancelled. + */ EVENT_CANCELLED; /** diff --git a/Essentials/src/com/earth2me/essentials/messaging/SimpleMessageRecipient.java b/Essentials/src/com/earth2me/essentials/messaging/SimpleMessageRecipient.java index fa2180ea6..680572b11 100644 --- a/Essentials/src/com/earth2me/essentials/messaging/SimpleMessageRecipient.java +++ b/Essentials/src/com/earth2me/essentials/messaging/SimpleMessageRecipient.java @@ -26,7 +26,7 @@ import static com.earth2me.essentials.I18n.tl; *

  • {@link IMessageRecipient#getDisplayName()}
  • *
  • {@link IMessageRecipient#isReachable()}
  • * - * + *

    * The reply-recipient is wrapped in a {@link WeakReference}. */ public class SimpleMessageRecipient implements IMessageRecipient { @@ -37,20 +37,20 @@ public class SimpleMessageRecipient implements IMessageRecipient { private long lastMessageMs; private WeakReference replyRecipient; - protected static User getUser(IMessageRecipient recipient) { + public SimpleMessageRecipient(final IEssentials ess, final IMessageRecipient parent) { + this.ess = ess; + this.parent = parent; + } + + protected static User getUser(final IMessageRecipient recipient) { if (recipient instanceof SimpleMessageRecipient) { return ((SimpleMessageRecipient) recipient).parent instanceof User ? (User) ((SimpleMessageRecipient) recipient).parent : null; } return recipient instanceof User ? (User) recipient : null; } - public SimpleMessageRecipient(IEssentials ess, IMessageRecipient parent) { - this.ess = ess; - this.parent = parent; - } - @Override - public void sendMessage(String message) { + public void sendMessage(final String message) { this.parent.sendMessage(message); } @@ -59,11 +59,13 @@ public class SimpleMessageRecipient implements IMessageRecipient { return this.parent.getName(); } - @Override public String getDisplayName() { + @Override + public String getDisplayName() { return this.parent.getDisplayName(); } - @Override public MessageResponse sendMessage(IMessageRecipient recipient, String message) { + @Override + public MessageResponse sendMessage(final IMessageRecipient recipient, String message) { final PrivateMessagePreSendEvent preSendEvent = new PrivateMessagePreSendEvent(parent, recipient, message); ess.getServer().getPluginManager().callEvent(preSendEvent); if (preSendEvent.isCancelled()) { @@ -71,7 +73,7 @@ public class SimpleMessageRecipient implements IMessageRecipient { } message = preSendEvent.getMessage(); - MessageResponse messageResponse = recipient.onReceiveMessage(this.parent, message); + final MessageResponse messageResponse = recipient.onReceiveMessage(this.parent, message); switch (messageResponse) { case UNREACHABLE: sendMessage(tl("recentlyForeverAlone", recipient.getDisplayName())); @@ -89,17 +91,18 @@ public class SimpleMessageRecipient implements IMessageRecipient { } else { sendMessage(tl("userAFK", recipient.getDisplayName())); } + // fall through default: sendMessage(tl("msgFormat", tl("meSender"), recipient.getDisplayName(), message)); // Better Social Spy - User senderUser = getUser(this); - User recipientUser = getUser(recipient); + final User senderUser = getUser(this); + final User recipientUser = getUser(recipient); if (senderUser != null // not null if player. // Dont spy on chats involving socialspy exempt players && !senderUser.isAuthorized("essentials.chat.spy.exempt") - && (recipientUser != null && !recipientUser.isAuthorized("essentials.chat.spy.exempt"))) { - for (User onlineUser : ess.getOnlineUsers()) { + && recipientUser != null && !recipientUser.isAuthorized("essentials.chat.spy.exempt")) { + for (final User onlineUser : ess.getOnlineUsers()) { if (onlineUser.isSocialSpyEnabled() // Don't send socialspy messages to message sender/receiver to prevent spam && !onlineUser.equals(senderUser) @@ -112,6 +115,7 @@ public class SimpleMessageRecipient implements IMessageRecipient { } } } + break; } // If the message was a success, set this sender's reply-recipient to the current recipient. if (messageResponse.isSuccess()) { @@ -125,12 +129,12 @@ public class SimpleMessageRecipient implements IMessageRecipient { } @Override - public MessageResponse onReceiveMessage(IMessageRecipient sender, String message) { + public MessageResponse onReceiveMessage(final IMessageRecipient sender, final String message) { if (!isReachable()) { return MessageResponse.UNREACHABLE; } - User user = getUser(this); + final User user = getUser(this); boolean afk = false; boolean isLastMessageReplyRecipient = ess.getSettings().isLastMessageReplyRecipient(); if (user != null) { @@ -150,7 +154,7 @@ public class SimpleMessageRecipient implements IMessageRecipient { if (isLastMessageReplyRecipient) { // If this recipient doesn't have a reply recipient, initiate by setting the first // message sender to this recipient's replyRecipient. - long timeout = ess.getSettings().getLastMessageReplyRecipientTimeout() * 1000; + final long timeout = ess.getSettings().getLastMessageReplyRecipientTimeout() * 1000; if (getReplyRecipient() == null || !getReplyRecipient().isReachable() || System.currentTimeMillis() - this.lastMessageMs > timeout) { setReplyRecipient(sender); @@ -162,13 +166,14 @@ public class SimpleMessageRecipient implements IMessageRecipient { return afk ? MessageResponse.SUCCESS_BUT_AFK : MessageResponse.SUCCESS; } - @Override public boolean isReachable() { + @Override + public boolean isReachable() { return this.parent.isReachable(); } /** * {@inheritDoc} - *

    + *

    * This {@link com.earth2me.essentials.messaging.SimpleMessageRecipient} implementation stores the a weak reference to the recipient. */ @Override @@ -178,7 +183,7 @@ public class SimpleMessageRecipient implements IMessageRecipient { /** * {@inheritDoc} - *

    + *

    * This {@link com.earth2me.essentials.messaging.SimpleMessageRecipient} implementation stores the a weak reference to the recipient. */ @Override diff --git a/Essentials/src/com/earth2me/essentials/metrics/Metrics.java b/Essentials/src/com/earth2me/essentials/metrics/Metrics.java index 2ac50984b..24eb88713 100644 --- a/Essentials/src/com/earth2me/essentials/metrics/Metrics.java +++ b/Essentials/src/com/earth2me/essentials/metrics/Metrics.java @@ -12,12 +12,23 @@ import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.ServicePriority; import javax.net.ssl.HttpsURLConnection; -import java.io.*; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.nio.charset.StandardCharsets; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Timer; +import java.util.TimerTask; +import java.util.UUID; import java.util.concurrent.Callable; import java.util.logging.Level; import java.util.zip.GZIPOutputStream; @@ -30,13 +41,26 @@ import java.util.zip.GZIPOutputStream; @SuppressWarnings({"WeakerAccess", "unused"}) public class Metrics { + // The version of this bStats class + public static final int B_STATS_VERSION = 1; + // The url to which the data is sent + private static final String URL = "https://bStats.org/submitData/bukkit"; + // Should failed requests be logged? + private static boolean logFailedRequests; + // Should the sent data be logged? + private static boolean logSentData; + // Should the response text be logged? + private static boolean logResponseStatusText; + // The uuid of the server + private static String serverUUID; + static { // You can use the property to disable the check in your test environment if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D final String defaultPackage = new String( - new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'}); - final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); + new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'}); + final String examplePackage = new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); // We want to make sure nobody just copy & pastes the example and use the wrong package names if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) { throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); @@ -44,27 +68,8 @@ public class Metrics { } } - // The version of this bStats class - public static final int B_STATS_VERSION = 1; - - // The url to which the data is sent - private static final String URL = "https://bStats.org/submitData/bukkit"; - // Is bStats enabled on this server? - private boolean enabled; - - // Should failed requests be logged? - private static boolean logFailedRequests; - - // Should the sent data be logged? - private static boolean logSentData; - - // Should the response text be logged? - private static boolean logResponseStatusText; - - // The uuid of the server - private static String serverUUID; - + private final boolean enabled; // The plugin private final Plugin plugin; @@ -77,11 +82,11 @@ public class Metrics { /** * Class constructor. * - * @param plugin The plugin which stats should be submitted. + * @param plugin The plugin which stats should be submitted. * @param pluginId The id of the plugin. * It can be found at What is my plugin id? */ - public Metrics(Plugin plugin, int pluginId) { + public Metrics(final Plugin plugin, final int pluginId) { if (plugin == null) { throw new IllegalArgumentException("Plugin cannot be null!"); } @@ -89,9 +94,9 @@ public class Metrics { this.pluginId = pluginId; // Get the config file - File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); - File configFile = new File(bStatsFolder, "config.yml"); - YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + final File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + final File configFile = new File(bStatsFolder, "config.yml"); + final YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); // Check if the config file exists if (!config.isSet("serverUuid")) { @@ -109,14 +114,15 @@ public class Metrics { // Inform the server owners about bStats config.options().header( - "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + - "To honor their work, you should not disable it.\n" + - "This has nearly no effect on the server performance!\n" + - "Check out https://bStats.org/ to learn more :)" + "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + + "To honor their work, you should not disable it.\n" + + "This has nearly no effect on the server performance!\n" + + "Check out https://bStats.org/ to learn more :)" ).copyDefaults(true); try { config.save(configFile); - } catch (IOException ignored) { } + } catch (final IOException ignored) { + } } // Load the data @@ -129,12 +135,13 @@ public class Metrics { if (enabled) { boolean found = false; // Search for all other bStats Metrics classes to see if we are the first one - for (Class service : Bukkit.getServicesManager().getKnownServices()) { + for (final Class service : Bukkit.getServicesManager().getKnownServices()) { try { service.getField("B_STATS_VERSION"); // Our identifier :) found = true; // We aren't the first break; - } catch (NoSuchFieldException ignored) { } + } catch (final NoSuchFieldException ignored) { + } } // Register our service Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); @@ -145,6 +152,74 @@ public class Metrics { } } + /** + * Sends the data to the bStats server. + * + * @param plugin Any plugin. It's just used to get a logger instance. + * @param data The data to send. + * @throws Exception If the request failed. + */ + private static void sendData(final Plugin plugin, final JsonObject data) throws Exception { + if (data == null) { + throw new IllegalArgumentException("Data cannot be null!"); + } + if (Bukkit.isPrimaryThread()) { + throw new IllegalAccessException("This method must not be called from the main thread!"); + } + if (logSentData) { + plugin.getLogger().info("Sending data to bStats: " + data); + } + final HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); + + // Compress the data to save bandwidth + final byte[] compressedData = compress(data.toString()); + + // Add headers + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format + connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); + + // Send data + connection.setDoOutput(true); + try (final DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { + outputStream.write(compressedData); + } + + final StringBuilder builder = new StringBuilder(); + try (final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + } + + if (logResponseStatusText) { + plugin.getLogger().info("Sent data to bStats and received response: " + builder); + } + } + + /** + * Gzips the given String. + * + * @param str The string to gzip. + * @return The gzipped String. + * @throws IOException If the compression failed. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (final GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + } + return outputStream.toByteArray(); + } + /** * Checks if bStats is enabled. * @@ -159,7 +234,7 @@ public class Metrics { * * @param chart The chart to add. */ - public void addCustomChart(CustomChart chart) { + public void addCustomChart(final CustomChart chart) { if (chart == null) { throw new IllegalArgumentException("Chart cannot be null!"); } @@ -195,18 +270,18 @@ public class Metrics { * @return The plugin specific data. */ public JsonObject getPluginData() { - JsonObject data = new JsonObject(); + final JsonObject data = new JsonObject(); - String pluginName = plugin.getDescription().getName().replace("Essentials", "EssentialsX"); - String pluginVersion = plugin.getDescription().getVersion(); + final String pluginName = plugin.getDescription().getName().replace("Essentials", "EssentialsX"); + final String pluginVersion = plugin.getDescription().getVersion(); data.addProperty("pluginName", pluginName); // Append the name of the plugin data.addProperty("id", pluginId); // Append the id of the plugin data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin - JsonArray customCharts = new JsonArray(); - for (CustomChart customChart : charts) { + final JsonArray customCharts = new JsonArray(); + for (final CustomChart customChart : charts) { // Add the data of the custom charts - JsonObject chart = customChart.getRequestJsonObject(); + final JsonObject chart = customChart.getRequestJsonObject(); if (chart == null) { // If the chart is null, we skip it continue; } @@ -228,25 +303,25 @@ public class Metrics { try { // Around MC 1.8 the return type was changed to a collection from an array, // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; - Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); + final Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) - ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() - : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; - } catch (Exception e) { + ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() + : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; + } catch (final Exception e) { playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed } - int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; - String bukkitVersion = Bukkit.getVersion(); - String bukkitName = Bukkit.getName(); + final int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; + final String bukkitVersion = Bukkit.getVersion(); + final String bukkitName = Bukkit.getName(); // OS/Java specific data - String javaVersion = System.getProperty("java.version"); - String osName = System.getProperty("os.name"); - String osArch = System.getProperty("os.arch"); - String osVersion = System.getProperty("os.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); + final String javaVersion = System.getProperty("java.version"); + final String osName = System.getProperty("os.name"); + final String osArch = System.getProperty("os.arch"); + final String osVersion = System.getProperty("os.version"); + final int coreCount = Runtime.getRuntime().availableProcessors(); - JsonObject data = new JsonObject(); + final JsonObject data = new JsonObject(); data.addProperty("serverUUID", serverUUID); @@ -270,37 +345,39 @@ public class Metrics { private void submitData() { final JsonObject data = getServerData(); - JsonArray pluginData = new JsonArray(); + final JsonArray pluginData = new JsonArray(); // Search for all other bStats Metrics classes to get their plugin data - for (Class service : Bukkit.getServicesManager().getKnownServices()) { + for (final Class service : Bukkit.getServicesManager().getKnownServices()) { try { service.getField("B_STATS_VERSION"); // Our identifier :) - for (RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { + for (final RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { try { - Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider()); + final Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider()); if (plugin instanceof JsonObject) { pluginData.add((JsonObject) plugin); } else { // old bstats version compatibility try { - Class jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject"); + final Class jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject"); if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) { - Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString"); + final Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString"); jsonStringGetter.setAccessible(true); - String jsonString = (String) jsonStringGetter.invoke(plugin); - JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject(); + final String jsonString = (String) jsonStringGetter.invoke(plugin); + final JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject(); pluginData.add(object); } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // minecraft version 1.14+ if (logFailedRequests) { this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e); } } } - } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } + } catch (final NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { + } } - } catch (NoSuchFieldException ignored) { } + } catch (final NoSuchFieldException ignored) { + } } data.add("plugins", pluginData); @@ -310,7 +387,7 @@ public class Metrics { try { // Send the data sendData(plugin, data); - } catch (Exception e) { + } catch (final Exception e) { // Something went wrong! :( if (logFailedRequests) { plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); @@ -319,74 +396,6 @@ public class Metrics { }).start(); } - /** - * Sends the data to the bStats server. - * - * @param plugin Any plugin. It's just used to get a logger instance. - * @param data The data to send. - * @throws Exception If the request failed. - */ - private static void sendData(Plugin plugin, JsonObject data) throws Exception { - if (data == null) { - throw new IllegalArgumentException("Data cannot be null!"); - } - if (Bukkit.isPrimaryThread()) { - throw new IllegalAccessException("This method must not be called from the main thread!"); - } - if (logSentData) { - plugin.getLogger().info("Sending data to bStats: " + data); - } - HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); - - // Compress the data to save bandwidth - byte[] compressedData = compress(data.toString()); - - // Add headers - connection.setRequestMethod("POST"); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request - connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); - connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format - connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); - - // Send data - connection.setDoOutput(true); - try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { - outputStream.write(compressedData); - } - - StringBuilder builder = new StringBuilder(); - try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { - String line; - while ((line = bufferedReader.readLine()) != null) { - builder.append(line); - } - } - - if (logResponseStatusText) { - plugin.getLogger().info("Sent data to bStats and received response: " + builder); - } - } - - /** - * Gzips the given String. - * - * @param str The string to gzip. - * @return The gzipped String. - * @throws IOException If the compression failed. - */ - private static byte[] compress(final String str) throws IOException { - if (str == null) { - return null; - } - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { - gzip.write(str.getBytes(StandardCharsets.UTF_8)); - } - return outputStream.toByteArray(); - } - /** * Represents a custom chart. */ @@ -400,7 +409,7 @@ public class Metrics { * * @param chartId The id of the chart. */ - CustomChart(String chartId) { + CustomChart(final String chartId) { if (chartId == null || chartId.isEmpty()) { throw new IllegalArgumentException("ChartId cannot be null or empty!"); } @@ -408,16 +417,16 @@ public class Metrics { } private JsonObject getRequestJsonObject() { - JsonObject chart = new JsonObject(); + final JsonObject chart = new JsonObject(); chart.addProperty("chartId", chartId); try { - JsonObject data = getChartData(); + final JsonObject data = getChartData(); if (data == null) { // If the data is null we don't send the chart. return null; } chart.add("data", data); - } catch (Throwable t) { + } catch (final Throwable t) { if (logFailedRequests) { Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); } @@ -440,18 +449,18 @@ public class Metrics { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ - public SimplePie(String chartId, Callable callable) { + public SimplePie(final String chartId, final Callable callable) { super(chartId); this.callable = callable; } @Override protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - String value = callable.call(); + final JsonObject data = new JsonObject(); + final String value = callable.call(); if (value == null || value.isEmpty()) { // Null = skip the chart return null; @@ -471,25 +480,25 @@ public class Metrics { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ - public AdvancedPie(String chartId, Callable> callable) { + public AdvancedPie(final String chartId, final Callable> callable) { super(chartId); this.callable = callable; } @Override protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); + final JsonObject data = new JsonObject(); + final JsonObject values = new JsonObject(); + final Map map = callable.call(); if (map == null || map.isEmpty()) { // Null = skip the chart return null; } boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { + for (final Map.Entry entry : map.entrySet()) { if (entry.getValue() == 0) { continue; // Skip this invalid } @@ -515,28 +524,28 @@ public class Metrics { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ - public DrilldownPie(String chartId, Callable>> callable) { + public DrilldownPie(final String chartId, final Callable>> callable) { super(chartId); this.callable = callable; } @Override public JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map> map = callable.call(); + final JsonObject data = new JsonObject(); + final JsonObject values = new JsonObject(); + final Map> map = callable.call(); if (map == null || map.isEmpty()) { // Null = skip the chart return null; } boolean reallyAllSkipped = true; - for (Map.Entry> entryValues : map.entrySet()) { - JsonObject value = new JsonObject(); + for (final Map.Entry> entryValues : map.entrySet()) { + final JsonObject value = new JsonObject(); boolean allSkipped = true; - for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { + for (final Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { value.addProperty(valueEntry.getKey(), valueEntry.getValue()); allSkipped = false; } @@ -564,18 +573,18 @@ public class Metrics { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ - public SingleLineChart(String chartId, Callable callable) { + public SingleLineChart(final String chartId, final Callable callable) { super(chartId); this.callable = callable; } @Override protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - int value = callable.call(); + final JsonObject data = new JsonObject(); + final int value = callable.call(); if (value == 0) { // Null = skip the chart return null; @@ -596,25 +605,25 @@ public class Metrics { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ - public MultiLineChart(String chartId, Callable> callable) { + public MultiLineChart(final String chartId, final Callable> callable) { super(chartId); this.callable = callable; } @Override protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); + final JsonObject data = new JsonObject(); + final JsonObject values = new JsonObject(); + final Map map = callable.call(); if (map == null || map.isEmpty()) { // Null = skip the chart return null; } boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { + for (final Map.Entry entry : map.entrySet()) { if (entry.getValue() == 0) { continue; // Skip this invalid } @@ -641,25 +650,25 @@ public class Metrics { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ - public SimpleBarChart(String chartId, Callable> callable) { + public SimpleBarChart(final String chartId, final Callable> callable) { super(chartId); this.callable = callable; } @Override protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); + final JsonObject data = new JsonObject(); + final JsonObject values = new JsonObject(); + final Map map = callable.call(); if (map == null || map.isEmpty()) { // Null = skip the chart return null; } - for (Map.Entry entry : map.entrySet()) { - JsonArray categoryValues = new JsonArray(); + for (final Map.Entry entry : map.entrySet()) { + final JsonArray categoryValues = new JsonArray(); categoryValues.add(new JsonPrimitive(entry.getValue())); values.add(entry.getKey(), categoryValues); } @@ -679,31 +688,31 @@ public class Metrics { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ - public AdvancedBarChart(String chartId, Callable> callable) { + public AdvancedBarChart(final String chartId, final Callable> callable) { super(chartId); this.callable = callable; } @Override protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); + final JsonObject data = new JsonObject(); + final JsonObject values = new JsonObject(); + final Map map = callable.call(); if (map == null || map.isEmpty()) { // Null = skip the chart return null; } boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { + for (final Map.Entry entry : map.entrySet()) { if (entry.getValue().length == 0) { continue; // Skip this invalid } allSkipped = false; - JsonArray categoryValues = new JsonArray(); - for (int categoryValue : entry.getValue()) { + final JsonArray categoryValues = new JsonArray(); + for (final int categoryValue : entry.getValue()) { categoryValues.add(new JsonPrimitive(categoryValue)); } values.add(entry.getKey(), categoryValues); @@ -717,4 +726,4 @@ public class Metrics { } } -} \ No newline at end of file +} diff --git a/Essentials/src/com/earth2me/essentials/metrics/MetricsWrapper.java b/Essentials/src/com/earth2me/essentials/metrics/MetricsWrapper.java index 1510df891..2d601527c 100644 --- a/Essentials/src/com/earth2me/essentials/metrics/MetricsWrapper.java +++ b/Essentials/src/com/earth2me/essentials/metrics/MetricsWrapper.java @@ -14,15 +14,14 @@ import java.util.Map; public class MetricsWrapper { + private static final List KNOWN_FORCED_METRICS = ImmutableList.of("ChatControl"); + private static boolean hasWarned = false; private final Essentials ess; private final Metrics metrics; private final Map commands = new HashMap<>(); private final Plugin plugin; - private static boolean hasWarned = false; - private static final List KNOWN_FORCED_METRICS = ImmutableList.of("ChatControl"); - - public MetricsWrapper(Plugin plugin, int pluginId, boolean includeCommands) { + public MetricsWrapper(final Plugin plugin, final int pluginId, final boolean includeCommands) { this.plugin = plugin; this.ess = (Essentials) Bukkit.getPluginManager().getPlugin("Essentials"); this.metrics = new Metrics(plugin, pluginId); @@ -43,19 +42,19 @@ public class MetricsWrapper { if (includeCommands) addCommandsChart(); } - public void markCommand(String command, boolean state) { + public void markCommand(final String command, final boolean state) { commands.put(command, state); } - public void addCustomChart(Metrics.CustomChart chart) { + public void addCustomChart(final Metrics.CustomChart chart) { metrics.addCustomChart(chart); } private void addPermsChart() { metrics.addCustomChart(new Metrics.DrilldownPie("permsPlugin", () -> { - Map> result = new HashMap<>(); - String handler = ess.getPermissionsHandler().getName(); - Map backend = new HashMap<>(); + final Map> result = new HashMap<>(); + final String handler = ess.getPermissionsHandler().getName(); + final Map backend = new HashMap<>(); backend.put(ess.getPermissionsHandler().getBackendName(), 1); result.put(handler, backend); return result; @@ -64,8 +63,8 @@ public class MetricsWrapper { private void addEconomyChart() { metrics.addCustomChart(new Metrics.DrilldownPie("econPlugin", () -> { - Map> result = new HashMap<>(); - Map backend = new HashMap<>(); + final Map> result = new HashMap<>(); + final Map backend = new HashMap<>(); if (Methods.hasMethod()) { backend.put(Methods.getMethod().getBackend(), 1); result.put(Methods.getMethod().getName(), backend); @@ -79,24 +78,24 @@ public class MetricsWrapper { private void addVersionHistoryChart() { metrics.addCustomChart(new Metrics.MultiLineChart("versionHistory", () -> { - HashMap result = new HashMap<>(); + final HashMap result = new HashMap<>(); result.put(plugin.getDescription().getVersion(), 1); return result; })); } private void addCommandsChart() { - for (String command : plugin.getDescription().getCommands().keySet()) { + for (final String command : plugin.getDescription().getCommands().keySet()) { markCommand(command, false); } metrics.addCustomChart(new Metrics.AdvancedBarChart("commands", () -> { - Map result = new HashMap<>(); - for (Map.Entry entry : commands.entrySet()) { + final Map result = new HashMap<>(); + for (final Map.Entry entry : commands.entrySet()) { if (entry.getValue()) { - result.put(entry.getKey(), new int[]{1, 0}); + result.put(entry.getKey(), new int[] {1, 0}); } else { - result.put(entry.getKey(), new int[]{0, 1}); + result.put(entry.getKey(), new int[] {0, 1}); } } return result; @@ -108,52 +107,55 @@ public class MetricsWrapper { hasWarned = true; Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> { - for (Class service : Bukkit.getServicesManager().getKnownServices()) { + for (final Class service : Bukkit.getServicesManager().getKnownServices()) { try { service.getField("B_STATS_VERSION"); // Identifies bStats classes - JavaPlugin owningPlugin = getProvidingPlugin(service); + final JavaPlugin owningPlugin = getProvidingPlugin(service); if (owningPlugin != null && KNOWN_FORCED_METRICS.contains(owningPlugin.getName())) { warnForcedMetrics(service); } else { try { service.getDeclaredField("pluginId"); // Only present in recent bStats classes, which should also have the enabled field unless modified - } catch (NoSuchFieldException e) { + } catch (final NoSuchFieldException e) { // Old bStats class found so "enabled" field detection is unreliable. break; } try { service.getDeclaredField("enabled"); // In modified forced metrics classes, this will fail - } catch (NoSuchFieldException e) { + } catch (final NoSuchFieldException e) { warnForcedMetrics(service); } } - } catch (NoSuchFieldException ignored) {} + } catch (final NoSuchFieldException ignored) { + } } }); } - private void warnForcedMetrics(Class service) { - Plugin servicePlugin = JavaPlugin.getProvidingPlugin(service); + private void warnForcedMetrics(final Class service) { + final Plugin servicePlugin = JavaPlugin.getProvidingPlugin(service); plugin.getLogger().severe("WARNING: Potential forced metrics collection by plugin '" + servicePlugin.getName() + "' v" + servicePlugin.getDescription().getVersion()); plugin.getLogger().severe("Your server is running a plugin that may not respect bStats' opt-out settings."); plugin.getLogger().severe("This may cause data to be uploaded to bStats.org for plugins that use bStats, even if you've opted out in the bStats config."); plugin.getLogger().severe("Please report this to bStats and to the authors of '" + servicePlugin.getName() + "'. (Offending class: " + service.getName() + ")"); } - private JavaPlugin getProvidingPlugin(Class clazz) { + private JavaPlugin getProvidingPlugin(final Class clazz) { try { return JavaPlugin.getProvidingPlugin(clazz); - } catch (Exception ignored) {} + } catch (final Exception ignored) { + } - ClassLoader parent = clazz.getClassLoader().getParent(); + final ClassLoader parent = clazz.getClassLoader().getParent(); if (parent.getClass().getName().equals("org.bukkit.plugin.java.PluginClassLoader")) { try { - Field pluginField = parent.getClass().getDeclaredField("plugin"); + final Field pluginField = parent.getClass().getDeclaredField("plugin"); pluginField.setAccessible(true); return (JavaPlugin) pluginField.get(parent); - } catch (Exception ignored) {} + } catch (final Exception ignored) { + } } return null; diff --git a/Essentials/src/com/earth2me/essentials/perm/IPermissionsHandler.java b/Essentials/src/com/earth2me/essentials/perm/IPermissionsHandler.java index 166645117..1e8b38a4f 100644 --- a/Essentials/src/com/earth2me/essentials/perm/IPermissionsHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/IPermissionsHandler.java @@ -6,7 +6,6 @@ import java.util.List; import java.util.function.Function; import java.util.function.Supplier; - public interface IPermissionsHandler { String getGroup(Player base); diff --git a/Essentials/src/com/earth2me/essentials/perm/PermissionsHandler.java b/Essentials/src/com/earth2me/essentials/perm/PermissionsHandler.java index a3c7174a9..9ca7e8754 100644 --- a/Essentials/src/com/earth2me/essentials/perm/PermissionsHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/PermissionsHandler.java @@ -1,7 +1,12 @@ package com.earth2me.essentials.perm; import com.earth2me.essentials.Essentials; -import com.earth2me.essentials.perm.impl.*; +import com.earth2me.essentials.perm.impl.AbstractVaultHandler; +import com.earth2me.essentials.perm.impl.ConfigPermissionsHandler; +import com.earth2me.essentials.perm.impl.GenericVaultHandler; +import com.earth2me.essentials.perm.impl.LuckPermsHandler; +import com.earth2me.essentials.perm.impl.ModernVaultHandler; +import com.earth2me.essentials.perm.impl.SuperpermsHandler; import com.google.common.collect.ImmutableSet; import org.bukkit.entity.Player; @@ -14,9 +19,9 @@ import java.util.function.Supplier; import java.util.logging.Level; public class PermissionsHandler implements IPermissionsHandler { - private transient IPermissionsHandler handler = null; private final transient String defaultGroup = "default"; private final transient Essentials ess; + private transient IPermissionsHandler handler = null; private transient boolean useSuperperms; private Class lastHandler = null; @@ -94,7 +99,7 @@ public class PermissionsHandler implements IPermissionsHandler { } @Override - public void registerContext(String context, Function> calculator, Supplier> suggestions) { + public void registerContext(final String context, final Function> calculator, final Supplier> suggestions) { handler.registerContext(context, calculator, suggestions); } @@ -115,15 +120,15 @@ public class PermissionsHandler implements IPermissionsHandler { public void checkPermissions() { // load and assign a handler - List> providerClazz = Arrays.asList( - LuckPermsHandler.class, - ModernVaultHandler.class, - GenericVaultHandler.class, - SuperpermsHandler.class + final List> providerClazz = Arrays.asList( + LuckPermsHandler.class, + ModernVaultHandler.class, + GenericVaultHandler.class, + SuperpermsHandler.class ); - for (Class providerClass : providerClazz) { + for (final Class providerClass : providerClazz) { try { - IPermissionsHandler provider = providerClass.newInstance(); + final IPermissionsHandler provider = providerClass.newInstance(); if (provider.tryProvider()) { if (provider.getClass().isInstance(this.handler)) { return; @@ -135,7 +140,7 @@ public class PermissionsHandler implements IPermissionsHandler { initContexts(); break; } - } catch (Throwable ignored) { + } catch (final Throwable ignored) { } } if (handler == null) { @@ -147,7 +152,7 @@ public class PermissionsHandler implements IPermissionsHandler { } // don't spam logs - Class handlerClass = handler.getClass(); + final Class handlerClass = handler.getClass(); if (lastHandler != null && lastHandler == handlerClass) { return; } @@ -161,9 +166,9 @@ public class PermissionsHandler implements IPermissionsHandler { } else if (handler.getClass() == SuperpermsHandler.class) { if (handler.tryProvider()) { ess.getLogger().warning("Detected supported permissions plugin " + - ((SuperpermsHandler) handler).getEnabledPermsPlugin() + " without Vault installed."); + ((SuperpermsHandler) handler).getEnabledPermsPlugin() + " without Vault installed."); ess.getLogger().warning("Features such as chat prefixes/suffixes and group-related functionality will not " + - "work until you install Vault."); + "work until you install Vault."); } ess.getLogger().info("Using superperms-based permissions."); } else if (handler.getClass() == ConfigPermissionsHandler.class) { @@ -180,7 +185,7 @@ public class PermissionsHandler implements IPermissionsHandler { return handler.getClass().getSimpleName().replace("Provider", ""); } - private void checkPermLag(long start, String summary) { + private void checkPermLag(final long start, final String summary) { final long elapsed = System.nanoTime() - start; if (elapsed > ess.getSettings().getPermissionsLagWarning()) { ess.getLogger().log(Level.WARNING, String.format("Permissions lag notice with (%s). Response took %fms. Summary: %s", getName(), elapsed / 1000000.0, summary)); @@ -195,7 +200,7 @@ public class PermissionsHandler implements IPermissionsHandler { registerContext("essentials:jail", player -> Optional.ofNullable(ess.getUser(player).getJail()).map(Arrays::asList).orElse(Collections.emptyList()), () -> { try { return ess.getJails().getList(); - } catch (Exception e) { + } catch (final Exception e) { return Collections.emptyList(); } }); diff --git a/Essentials/src/com/earth2me/essentials/perm/impl/AbstractVaultHandler.java b/Essentials/src/com/earth2me/essentials/perm/impl/AbstractVaultHandler.java index 3fae03184..9f2777f7d 100644 --- a/Essentials/src/com/earth2me/essentials/perm/impl/AbstractVaultHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/impl/AbstractVaultHandler.java @@ -18,12 +18,12 @@ public abstract class AbstractVaultHandler extends SuperpermsHandler { try { Class.forName("net.milkbowl.vault.permission.Permission"); Class.forName("net.milkbowl.vault.chat.Chat"); - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { return false; } - RegisteredServiceProvider permsProvider = Bukkit.getServer().getServicesManager().getRegistration(Permission.class); - RegisteredServiceProvider chatProvider = Bukkit.getServer().getServicesManager().getRegistration(Chat.class); + final RegisteredServiceProvider permsProvider = Bukkit.getServer().getServicesManager().getRegistration(Permission.class); + final RegisteredServiceProvider chatProvider = Bukkit.getServer().getServicesManager().getRegistration(Chat.class); if (permsProvider == null || chatProvider == null) return false; perms = permsProvider.getProvider(); @@ -48,12 +48,12 @@ public abstract class AbstractVaultHandler extends SuperpermsHandler { @Override public String getPrefix(final Player base) { - String playerPrefix = chat.getPlayerPrefix(base); + final String playerPrefix = chat.getPlayerPrefix(base); if (playerPrefix != null) { return playerPrefix; } - String playerGroup = perms.getPrimaryGroup(base); + final String playerGroup = perms.getPrimaryGroup(base); if (playerGroup != null) { return chat.getGroupPrefix(base.getWorld().getName(), playerGroup); } @@ -63,12 +63,12 @@ public abstract class AbstractVaultHandler extends SuperpermsHandler { @Override public String getSuffix(final Player base) { - String playerSuffix = chat.getPlayerSuffix(base); + final String playerSuffix = chat.getPlayerSuffix(base); if (playerSuffix != null) { return playerSuffix; } - String playerGroup = perms.getPrimaryGroup(base); + final String playerGroup = perms.getPrimaryGroup(base); if (playerGroup != null) { return chat.getGroupSuffix(base.getWorld().getName(), playerGroup); } @@ -78,8 +78,8 @@ public abstract class AbstractVaultHandler extends SuperpermsHandler { @Override public String getBackendName() { - String reportedPlugin = perms.getName(); - String classPlugin = JavaPlugin.getProvidingPlugin(perms.getClass()).getName(); + final String reportedPlugin = perms.getName(); + final String classPlugin = JavaPlugin.getProvidingPlugin(perms.getClass()).getName(); if (reportedPlugin.equals(classPlugin)) { return reportedPlugin; @@ -91,7 +91,7 @@ public abstract class AbstractVaultHandler extends SuperpermsHandler { if (Bukkit.getPluginManager().getPlugin("Vault") == null) return false; try { return setupProviders(); - } catch (Throwable t) { + } catch (final Throwable t) { return false; } } diff --git a/Essentials/src/com/earth2me/essentials/perm/impl/ConfigPermissionsHandler.java b/Essentials/src/com/earth2me/essentials/perm/impl/ConfigPermissionsHandler.java index 951f4e369..1086818f4 100644 --- a/Essentials/src/com/earth2me/essentials/perm/impl/ConfigPermissionsHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/impl/ConfigPermissionsHandler.java @@ -4,7 +4,6 @@ import net.ess3.api.IEssentials; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; - public class ConfigPermissionsHandler extends SuperpermsHandler { private final transient IEssentials ess; diff --git a/Essentials/src/com/earth2me/essentials/perm/impl/LuckPermsHandler.java b/Essentials/src/com/earth2me/essentials/perm/impl/LuckPermsHandler.java index 98dbe6fbd..44a51493d 100644 --- a/Essentials/src/com/earth2me/essentials/perm/impl/LuckPermsHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/impl/LuckPermsHandler.java @@ -19,16 +19,16 @@ public class LuckPermsHandler extends ModernVaultHandler { private Set> contextCalculators; @Override - public void registerContext(String context, Function> calculator, Supplier> suggestions) { - ContextCalculator contextCalculator = new ContextCalculator() { + public void registerContext(final String context, final Function> calculator, final Supplier> suggestions) { + final ContextCalculator contextCalculator = new ContextCalculator() { @Override - public void calculate(Player target, ContextConsumer consumer) { + public void calculate(final Player target, final ContextConsumer consumer) { calculator.apply(target).forEach(value -> consumer.accept(context, value)); } @Override public ContextSet estimatePotentialContexts() { - ImmutableContextSet.Builder builder = ImmutableContextSet.builder(); + final ImmutableContextSet.Builder builder = ImmutableContextSet.builder(); suggestions.get().forEach(value -> builder.add(context, value)); return builder.build(); } @@ -45,7 +45,7 @@ public class LuckPermsHandler extends ModernVaultHandler { @Override public boolean tryProvider() { - RegisteredServiceProvider provider = Bukkit.getServicesManager().getRegistration(LuckPerms.class); + final RegisteredServiceProvider provider = Bukkit.getServicesManager().getRegistration(LuckPerms.class); if (provider != null) { luckPerms = provider.getProvider(); contextCalculators = new HashSet<>(); diff --git a/Essentials/src/com/earth2me/essentials/perm/impl/ModernVaultHandler.java b/Essentials/src/com/earth2me/essentials/perm/impl/ModernVaultHandler.java index be99aaf68..adddc6f48 100644 --- a/Essentials/src/com/earth2me/essentials/perm/impl/ModernVaultHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/impl/ModernVaultHandler.java @@ -1,9 +1,10 @@ package com.earth2me.essentials.perm.impl; +import org.bukkit.entity.Player; + import java.util.Arrays; import java.util.List; import java.util.Objects; -import org.bukkit.entity.Player; public class ModernVaultHandler extends AbstractVaultHandler { private final List supportedPlugins = Arrays.asList("PermissionsEx", "LuckPerms"); diff --git a/Essentials/src/com/earth2me/essentials/perm/impl/SuperpermsHandler.java b/Essentials/src/com/earth2me/essentials/perm/impl/SuperpermsHandler.java index e0cee3081..1fe1da6f3 100644 --- a/Essentials/src/com/earth2me/essentials/perm/impl/SuperpermsHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/impl/SuperpermsHandler.java @@ -5,14 +5,12 @@ import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.permissions.Permission; import org.bukkit.plugin.Plugin; -import org.bukkit.scheduler.BukkitRunnable; import java.util.Arrays; import java.util.List; import java.util.function.Function; import java.util.function.Supplier; - public class SuperpermsHandler implements IPermissionsHandler { protected boolean emulateWildcards() { return true; @@ -114,7 +112,7 @@ public class SuperpermsHandler implements IPermissionsHandler { } @Override - public void registerContext(String context, Function> calculator, Supplier> suggestions) { + public void registerContext(final String context, final Function> calculator, final Supplier> suggestions) { } @Override @@ -133,10 +131,10 @@ public class SuperpermsHandler implements IPermissionsHandler { public String getEnabledPermsPlugin() { String enabledPermsPlugin = null; - List specialCasePlugins = Arrays.asList("PermissionsEx", "GroupManager", - "SimplyPerms", "Privileges", "bPermissions", "zPermissions", "PermissionsBukkit", - "DroxPerms", "xPerms", "LuckPerms"); - for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { + final List specialCasePlugins = Arrays.asList("PermissionsEx", "GroupManager", + "SimplyPerms", "Privileges", "bPermissions", "zPermissions", "PermissionsBukkit", + "DroxPerms", "xPerms", "LuckPerms"); + for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { if (specialCasePlugins.contains(plugin.getName())) { enabledPermsPlugin = plugin.getName(); break; diff --git a/Essentials/src/com/earth2me/essentials/register/payment/Method.java b/Essentials/src/com/earth2me/essentials/register/payment/Method.java index daa90c109..16106c72d 100644 --- a/Essentials/src/com/earth2me/essentials/register/payment/Method.java +++ b/Essentials/src/com/earth2me/essentials/register/payment/Method.java @@ -2,7 +2,6 @@ package com.earth2me.essentials.register.payment; import org.bukkit.plugin.Plugin; - /** * Interface to be implemented by a payment method. * Copyright (C) 2011 @@ -20,12 +19,18 @@ public interface Method { * iConomy plugin = ((iConomy)method.getPlugin()); * * @return Object - * * @see #getName() * @see #getVersion() */ Plugin getPlugin(); + /** + * Set Plugin data. + * + * @param plugin Plugin + */ + void setPlugin(Plugin plugin); + /** * Returns the actual name of this method. * @@ -65,7 +70,6 @@ public interface Method { * Formats amounts into this payment methods style of currency display. * * @param amount Double - * * @return String - Formatted Currency Display. */ String format(double amount); @@ -81,9 +85,7 @@ public interface Method { * Determines the existence of a bank via name. * * @param bank Bank name - * * @return boolean - * * @see #hasBanks */ boolean hasBank(String bank); @@ -92,7 +94,6 @@ public interface Method { * Determines the existence of an account via name. * * @param name Account name - * * @return boolean */ boolean hasAccount(String name); @@ -102,7 +103,6 @@ public interface Method { * * @param bank Bank name * @param name Account name - * * @return boolean */ boolean hasBankAccount(String bank, String name); @@ -111,7 +111,6 @@ public interface Method { * Forces an account creation * * @param name Account name - * * @return boolean */ boolean createAccount(String name); @@ -121,7 +120,6 @@ public interface Method { * * @param name Account name * @param balance Initial account balance - * * @return boolean */ boolean createAccount(String name, Double balance); @@ -130,7 +128,6 @@ public interface Method { * Returns a MethodAccount class for an account name. * * @param name Account name - * * @return MethodAccount or Null */ MethodAccount getAccount(String name); @@ -140,7 +137,6 @@ public interface Method { * * @param bank Bank name * @param name Account name - * * @return MethodBankAccount or Null */ MethodBankAccount getBankAccount(String bank, String name); @@ -149,19 +145,10 @@ public interface Method { * Checks to verify the compatibility between this Method and a plugin. Internal usage only, for the most part. * * @param plugin Plugin - * * @return boolean */ boolean isCompatible(Plugin plugin); - /** - * Set Plugin data. - * - * @param plugin Plugin - */ - void setPlugin(Plugin plugin); - - /** * Contains Calculator and Balance functions for Accounts. */ @@ -192,7 +179,6 @@ public interface Method { String toString(); } - /** * Contains Calculator and Balance functions for Bank Accounts. */ diff --git a/Essentials/src/com/earth2me/essentials/register/payment/Methods.java b/Essentials/src/com/earth2me/essentials/register/payment/Methods.java index 458501ef1..4b39b843b 100644 --- a/Essentials/src/com/earth2me/essentials/register/payment/Methods.java +++ b/Essentials/src/com/earth2me/essentials/register/payment/Methods.java @@ -6,7 +6,6 @@ import org.bukkit.plugin.PluginManager; import java.util.HashSet; import java.util.Set; - /** * The Methods initializes Methods that utilize the Method interface based on a "first come, first served" * basis. @@ -25,33 +24,27 @@ import java.util.Set; * @author Nijikokun (@nijikokun) @copyright: Copyright (C) 2011 @license: AOL license * */ -public class Methods { +public final class Methods { + private static final Set Methods = new HashSet<>(); + private static final Set Dependencies = new HashSet<>(); + private static final Set Attachables = new HashSet<>(); private static String version = null; private static boolean self = false; private static Method Method = null; private static String preferred = ""; - private static final Set Methods = new HashSet<>(); - private static final Set Dependencies = new HashSet<>(); - private static final Set Attachables = new HashSet<>(); - static { - _init(); + private Methods() { } /** * Implement all methods along with their respective name & class. */ - private static void _init() { - addMethod("Vault", new com.earth2me.essentials.register.payment.methods.VaultEco()); - } + public static void init() { + if (!Methods.isEmpty()) { + throw new IllegalStateException("Methods already initialised!"); + } - /** - * Used by the plugin to setup version - * - * @param v version - */ - public static void setVersion(String v) { - version = v; + addMethod("Vault", new com.earth2me.essentials.register.payment.methods.VaultEco()); } /** @@ -74,11 +67,19 @@ public class Methods { return version; } + /** + * Used by the plugin to setup version + * + * @param v version + */ + public static void setVersion(final String v) { + version = v; + } + /** * Returns an array of payment method names that have been loaded through the _init method. * * @return Set - Array of payment methods that are loaded. - * * @see #setMethod(PluginManager) */ public static Set getDependencies() { @@ -90,11 +91,10 @@ public class Methods { * payments and other various economic activity. * * @param plugin Plugin data from bukkit, Internal Class file. - * * @return Method or Null */ - public static Method createMethod(Plugin plugin) { - for (Method method : Methods) { + public static Method createMethod(final Plugin plugin) { + for (final Method method : Methods) { if (method.isCompatible(plugin)) { method.setPlugin(plugin); return method; @@ -104,7 +104,7 @@ public class Methods { return null; } - private static void addMethod(String name, Method method) { + private static void addMethod(final String name, final Method method) { Dependencies.add(name); Methods.add(method); } @@ -113,22 +113,20 @@ public class Methods { * Verifies if Register has set a payment method for usage yet. * * @return boolean - * * @see #setMethod(PluginManager) * @see #checkDisabled(Plugin) */ public static boolean hasMethod() { - return (Method != null); + return Method != null; } /** * Checks Plugin Class against a multitude of checks to verify it's usability as a payment method. * * @param manager the plugin manager for the server - * * @return boolean True on success, False on failure. */ - public static boolean setMethod(PluginManager manager) { + public static boolean setMethod(final PluginManager manager) { if (hasMethod()) { return true; } @@ -142,7 +140,7 @@ public class Methods { boolean match = false; Plugin plugin; - for (String name : getDependencies()) { + for (final String name : getDependencies()) { if (hasMethod()) { break; } @@ -152,7 +150,7 @@ public class Methods { continue; } - Method current = createMethod(plugin); + final Method current = createMethod(plugin); if (current == null) { continue; } @@ -169,7 +167,7 @@ public class Methods { if (hasMethod()) { match = true; } else { - for (Method attached : Attachables) { + for (final Method attached : Attachables) { if (attached == null) { continue; } @@ -205,7 +203,7 @@ public class Methods { * * @return boolean */ - public static boolean setPreferred(String check) { + public static boolean setPreferred(final String check) { if (getDependencies().contains(check)) { preferred = check; return true; @@ -228,10 +226,9 @@ public class Methods { * Register. * * @param method Plugin data from bukkit, Internal Class file. - * * @return boolean */ - public static boolean checkDisabled(Plugin method) { + public static boolean checkDisabled(final Plugin method) { if (!hasMethod()) { return true; } @@ -240,6 +237,6 @@ public class Methods { Method = null; } - return (Method == null); + return Method == null; } } diff --git a/Essentials/src/com/earth2me/essentials/register/payment/methods/VaultEco.java b/Essentials/src/com/earth2me/essentials/register/payment/methods/VaultEco.java index 20c5dc1a2..a28145e04 100644 --- a/Essentials/src/com/earth2me/essentials/register/payment/methods/VaultEco.java +++ b/Essentials/src/com/earth2me/essentials/register/payment/methods/VaultEco.java @@ -5,7 +5,6 @@ import net.milkbowl.vault.economy.Economy; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.RegisteredServiceProvider; - public class VaultEco implements Method { private Plugin vault; private Economy economy; @@ -16,7 +15,16 @@ public class VaultEco implements Method { } @Override - public boolean createAccount(String name, Double amount) { + public void setPlugin(final Plugin plugin) { + this.vault = plugin; + final RegisteredServiceProvider economyProvider = this.vault.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); + if (economyProvider != null) { + this.economy = economyProvider.getProvider(); + } + } + + @Override + public boolean createAccount(final String name, final Double amount) { if (hasAccount(name)) { return false; } @@ -50,7 +58,7 @@ public class VaultEco implements Method { } @Override - public String format(double amount) { + public String format(final double amount) { return this.economy.format(amount); } @@ -60,26 +68,26 @@ public class VaultEco implements Method { } @Override - public boolean hasBank(String bank) { + public boolean hasBank(final String bank) { return this.economy.getBanks().contains(bank); } @Override - public boolean hasAccount(String name) { + public boolean hasAccount(final String name) { return this.economy.hasAccount(name); } @Override - public boolean hasBankAccount(String bank, String name) { + public boolean hasBankAccount(final String bank, final String name) { return this.economy.isBankOwner(bank, name).transactionSuccess() || this.economy.isBankMember(bank, name).transactionSuccess(); } @Override - public boolean createAccount(String name) { + public boolean createAccount(final String name) { return this.economy.createBank(name, "").transactionSuccess(); } - public boolean createAccount(String name, double balance) { + public boolean createAccount(final String name, final double balance) { if (!this.economy.createBank(name, "").transactionSuccess()) { return false; } @@ -87,7 +95,7 @@ public class VaultEco implements Method { } @Override - public MethodAccount getAccount(String name) { + public MethodAccount getAccount(final String name) { if (!hasAccount(name)) { return null; } @@ -96,7 +104,7 @@ public class VaultEco implements Method { } @Override - public MethodBankAccount getBankAccount(String bank, String name) { + public MethodBankAccount getBankAccount(final String bank, final String name) { if (!hasBankAccount(bank, name)) { return null; } @@ -105,30 +113,20 @@ public class VaultEco implements Method { } @Override - public boolean isCompatible(Plugin plugin) { + public boolean isCompatible(final Plugin plugin) { try { - RegisteredServiceProvider ecoPlugin = plugin.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); + final RegisteredServiceProvider ecoPlugin = plugin.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); return plugin.getName().equals("Vault") && ecoPlugin != null && !ecoPlugin.getProvider().getName().equals("Essentials Economy"); - } catch (LinkageError | Exception e) { + } catch (final LinkageError | Exception e) { return false; } } - @Override - public void setPlugin(Plugin plugin) { - this.vault = plugin; - RegisteredServiceProvider economyProvider = this.vault.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); - if (economyProvider != null) { - this.economy = economyProvider.getProvider(); - } - } - - public static class VaultAccount implements MethodAccount { private final String name; private final Economy economy; - VaultAccount(String name, Economy economy) { + VaultAccount(final String name, final Economy economy) { this.name = name; this.economy = economy; } @@ -139,7 +137,7 @@ public class VaultEco implements Method { } @Override - public boolean set(double amount) { + public boolean set(final double amount) { if (!this.economy.withdrawPlayer(this.name, this.balance()).transactionSuccess()) { return false; } @@ -150,45 +148,45 @@ public class VaultEco implements Method { } @Override - public boolean add(double amount) { + public boolean add(final double amount) { return this.economy.depositPlayer(this.name, amount).transactionSuccess(); } @Override - public boolean subtract(double amount) { + public boolean subtract(final double amount) { return this.economy.withdrawPlayer(this.name, amount).transactionSuccess(); } @Override - public boolean multiply(double amount) { - double balance = this.balance(); + public boolean multiply(final double amount) { + final double balance = this.balance(); return this.set(balance * amount); } @Override - public boolean divide(double amount) { - double balance = this.balance(); + public boolean divide(final double amount) { + final double balance = this.balance(); return this.set(balance / amount); } @Override - public boolean hasEnough(double amount) { - return (this.balance() >= amount); + public boolean hasEnough(final double amount) { + return this.balance() >= amount; } @Override - public boolean hasOver(double amount) { - return (this.balance() > amount); + public boolean hasOver(final double amount) { + return this.balance() > amount; } @Override - public boolean hasUnder(double amount) { - return (this.balance() < amount); + public boolean hasUnder(final double amount) { + return this.balance() < amount; } @Override public boolean isNegative() { - return (this.balance() < 0); + return this.balance() < 0; } @Override @@ -197,12 +195,11 @@ public class VaultEco implements Method { } } - public static class VaultBankAccount implements MethodBankAccount { private final String bank; private final Economy economy; - public VaultBankAccount(String bank, Economy economy) { + public VaultBankAccount(final String bank, final Economy economy) { this.bank = bank; this.economy = economy; } @@ -223,7 +220,7 @@ public class VaultEco implements Method { } @Override - public boolean set(double amount) { + public boolean set(final double amount) { if (!this.economy.bankWithdraw(this.bank, this.balance()).transactionSuccess()) { return false; } @@ -234,45 +231,45 @@ public class VaultEco implements Method { } @Override - public boolean add(double amount) { + public boolean add(final double amount) { return this.economy.bankDeposit(this.bank, amount).transactionSuccess(); } @Override - public boolean subtract(double amount) { + public boolean subtract(final double amount) { return this.economy.bankWithdraw(this.bank, amount).transactionSuccess(); } @Override - public boolean multiply(double amount) { - double balance = this.balance(); + public boolean multiply(final double amount) { + final double balance = this.balance(); return this.set(balance * amount); } @Override - public boolean divide(double amount) { - double balance = this.balance(); + public boolean divide(final double amount) { + final double balance = this.balance(); return this.set(balance / amount); } @Override - public boolean hasEnough(double amount) { - return (this.balance() >= amount); + public boolean hasEnough(final double amount) { + return this.balance() >= amount; } @Override - public boolean hasOver(double amount) { - return (this.balance() > amount); + public boolean hasOver(final double amount) { + return this.balance() > amount; } @Override - public boolean hasUnder(double amount) { - return (this.balance() < amount); + public boolean hasUnder(final double amount) { + return this.balance() < amount; } @Override public boolean isNegative() { - return (this.balance() < 0); + return this.balance() < 0; } @Override @@ -280,4 +277,4 @@ public class VaultEco implements Method { return this.set(0.0); } } -} \ No newline at end of file +} diff --git a/Essentials/src/com/earth2me/essentials/settings/Jails.java b/Essentials/src/com/earth2me/essentials/settings/Jails.java index 91b08ea9c..1c867cfa8 100644 --- a/Essentials/src/com/earth2me/essentials/settings/Jails.java +++ b/Essentials/src/com/earth2me/essentials/settings/Jails.java @@ -8,7 +8,6 @@ import java.util.HashMap; import java.util.Map; import java.util.Objects; - public class Jails implements StorageObject { @MapValueType(Location.class) private Map jails = new HashMap<>(); @@ -17,19 +16,19 @@ public class Jails implements StorageObject { return jails; } - public void setJails(Map jails) { + public void setJails(final Map jails) { this.jails = jails; } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } - Jails jails1 = (Jails) o; + final Jails jails1 = (Jails) o; return Objects.equals(jails, jails1.jails); } diff --git a/Essentials/src/com/earth2me/essentials/settings/Spawns.java b/Essentials/src/com/earth2me/essentials/settings/Spawns.java index 5df62e8cf..5f0c3b5e0 100644 --- a/Essentials/src/com/earth2me/essentials/settings/Spawns.java +++ b/Essentials/src/com/earth2me/essentials/settings/Spawns.java @@ -16,19 +16,19 @@ public class Spawns implements StorageObject { return spawns; } - public void setSpawns(Map spawns) { + public void setSpawns(final Map spawns) { this.spawns = spawns; } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } - Spawns spawns1 = (Spawns) o; + final Spawns spawns1 = (Spawns) o; return Objects.equals(spawns, spawns1.spawns); } diff --git a/Essentials/src/com/earth2me/essentials/signs/EssentialsSign.java b/Essentials/src/com/earth2me/essentials/signs/EssentialsSign.java index 1d045b8bb..a86c7cc39 100644 --- a/Essentials/src/com/earth2me/essentials/signs/EssentialsSign.java +++ b/Essentials/src/com/earth2me/essentials/signs/EssentialsSign.java @@ -1,6 +1,10 @@ package com.earth2me.essentials.signs; -import com.earth2me.essentials.*; +import com.earth2me.essentials.ChargeException; +import com.earth2me.essentials.CommandSource; +import com.earth2me.essentials.MetaItemStack; +import com.earth2me.essentials.Trade; +import com.earth2me.essentials.User; import com.earth2me.essentials.utils.MaterialUtil; import com.earth2me.essentials.utils.NumberUtil; import net.ess3.api.IEssentials; @@ -25,16 +29,68 @@ import java.util.Set; import static com.earth2me.essentials.I18n.tl; - public class EssentialsSign { - private static final Set EMPTY_SET = new HashSet<>(); protected static final BigDecimal MINTRANSACTION = new BigDecimal("0.01"); + private static final Set EMPTY_SET = new HashSet<>(); protected transient final String signName; public EssentialsSign(final String signName) { this.signName = signName; } + protected static boolean checkIfBlockBreaksSigns(final Block block) { + final Block sign = block.getRelative(BlockFace.UP); + if (MaterialUtil.isSignPost(sign.getType()) && isValidSign(new BlockSign(sign))) { + return true; + } + final BlockFace[] directions = new BlockFace[] {BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST}; + for (final BlockFace blockFace : directions) { + final Block signBlock = block.getRelative(blockFace); + if (MaterialUtil.isWallSign(signBlock.getType())) { + try { + if (getWallSignFacing(signBlock) == blockFace && isValidSign(new BlockSign(signBlock))) { + return true; + } + } catch (final NullPointerException ex) { + // Sometimes signs enter a state of being semi broken, having no text or state data, usually while burning. + } + } + } + return false; + } + + /** + * @deprecated, use {@link #isValidSign(IEssentials, ISign)} if possible + */ + @Deprecated + public static boolean isValidSign(final ISign sign) { + return sign.getLine(0).matches("§1\\[.*\\]"); + } + + public static boolean isValidSign(final IEssentials ess, final ISign sign) { + if (!sign.getLine(0).matches("§1\\[.*\\]")) + return false; + + // Validate that the sign is actually an essentials sign + final String signName = ChatColor.stripColor(sign.getLine(0)).replaceAll("[^a-zA-Z]", ""); + for (final EssentialsSign essSign : ess.getSettings().enabledSigns()) { + if (essSign.getName().equalsIgnoreCase(signName)) + return true; + } + + return false; + } + + private static BlockFace getWallSignFacing(final Block block) { + try { + final WallSign signData = (WallSign) block.getState().getBlockData(); + return signData.getFacing(); + } catch (final NoClassDefFoundError | NoSuchMethodError e) { + final org.bukkit.material.Sign signMat = (org.bukkit.material.Sign) block.getState().getData(); + return signMat.getFacing(); + } + } + protected final boolean onSignCreate(final SignChangeEvent event, final IEssentials ess) { final ISign sign = new EventSign(event); final User user = ess.getUser(event.getPlayer()); @@ -60,15 +116,15 @@ public class EssentialsSign { sign.setLine(0, getSuccessName(ess)); } return ret; - } catch (ChargeException | SignException ex) { + } catch (final ChargeException | SignException ex) { showError(ess, user.getSource(), ex, signName); } // Return true, so the player sees the wrong sign. return true; } - public String getSuccessName(IEssentials ess) { - String successName = getSuccessName(); + public String getSuccessName(final IEssentials ess) { + final String successName = getSuccessName(); if (successName == null) { ess.getLogger().severe("signFormatSuccess message must use the {0} argument."); } @@ -115,7 +171,7 @@ public class EssentialsSign { } return onSignInteract(sign, user, getUsername(user), ess); - } catch (Exception ex) { + } catch (final Exception ex) { showError(ess, user.getSource(), ex, signName); return false; } @@ -136,7 +192,7 @@ public class EssentialsSign { } return onSignBreak(sign, user, getUsername(user), ess); - } catch (SignException ex) { + } catch (final SignException ex) { showError(ess, user.getSource(), ex, signName); return false; } @@ -155,30 +211,30 @@ public class EssentialsSign { } protected final boolean onBlockPlace(final Block block, final Player player, final IEssentials ess) { - User user = ess.getUser(player); + final User user = ess.getUser(player); try { return onBlockPlace(block, user, getUsername(user), ess); - } catch (ChargeException | SignException ex) { + } catch (final ChargeException | SignException ex) { showError(ess, user.getSource(), ex, signName); } return false; } protected final boolean onBlockInteract(final Block block, final Player player, final IEssentials ess) { - User user = ess.getUser(player); + final User user = ess.getUser(player); try { return onBlockInteract(block, user, getUsername(user), ess); - } catch (ChargeException | SignException ex) { + } catch (final ChargeException | SignException ex) { showError(ess, user.getSource(), ex, signName); } return false; } protected final boolean onBlockBreak(final Block block, final Player player, final IEssentials ess) throws MaxMoneyException { - User user = ess.getUser(player); + final User user = ess.getUser(player); try { return onBlockBreak(block, user, getUsername(user), ess); - } catch (SignException ex) { + } catch (final SignException ex) { showError(ess, user.getSource(), ex, signName); } return false; @@ -204,47 +260,6 @@ public class EssentialsSign { return true; } - protected static boolean checkIfBlockBreaksSigns(final Block block) { - final Block sign = block.getRelative(BlockFace.UP); - if (MaterialUtil.isSignPost(sign.getType()) && isValidSign(new BlockSign(sign))) { - return true; - } - final BlockFace[] directions = new BlockFace[]{BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST}; - for (BlockFace blockFace : directions) { - final Block signBlock = block.getRelative(blockFace); - if (MaterialUtil.isWallSign(signBlock.getType())) { - try { - if (getWallSignFacing(signBlock) == blockFace && isValidSign(new BlockSign(signBlock))) { - return true; - } - } catch (NullPointerException ex) { - // Sometimes signs enter a state of being semi broken, having no text or state data, usually while burning. - } - } - } - return false; - } - - /** @deprecated, use {@link #isValidSign(IEssentials, ISign)} if possible */ - @Deprecated - public static boolean isValidSign(final ISign sign) { - return sign.getLine(0).matches("§1\\[.*\\]"); - } - - public static boolean isValidSign(final IEssentials ess, final ISign sign) { - if (!sign.getLine(0).matches("§1\\[.*\\]")) - return false; - - // Validate that the sign is actually an essentials sign - String signName = ChatColor.stripColor(sign.getLine(0)).replaceAll("[^a-zA-Z]", ""); - for (EssentialsSign essSign : ess.getSettings().enabledSigns()) { - if (essSign.getName().equalsIgnoreCase(signName)) - return true; - } - - return false; - } - protected boolean onBlockPlace(final Block block, final User player, final String username, final IEssentials ess) throws SignException, ChargeException { return true; } @@ -284,7 +299,7 @@ public class EssentialsSign { protected final void validateTrade(final ISign sign, final int amountIndex, final int itemIndex, final User player, final IEssentials ess) throws SignException { final String itemType = getSignText(sign, itemIndex); if (itemType.equalsIgnoreCase("exp") || itemType.equalsIgnoreCase("xp")) { - int amount = getIntegerPositive(getSignText(sign, amountIndex)); + final int amount = getIntegerPositive(getSignText(sign, amountIndex)); sign.setLine(amountIndex, Integer.toString(amount)); sign.setLine(itemIndex, "exp"); return; @@ -334,7 +349,7 @@ public class EssentialsSign { protected final int getInteger(final String line) throws SignException { try { return Integer.parseInt(line); - } catch (NumberFormatException ex) { + } catch (final NumberFormatException ex) { throw new SignException("Invalid sign", ex); } } @@ -355,7 +370,7 @@ public class EssentialsSign { final ItemStack item = ess.getItemDb().get(itemName); item.setAmount(quantity); return item; - } catch (Exception ex) { + } catch (final Exception ex) { throw new SignException(ex.getMessage(), ex); } } @@ -364,12 +379,12 @@ public class EssentialsSign { ItemStack stack = item; try { if (!meta.isEmpty()) { - MetaItemStack metaStack = new MetaItemStack(stack); + final MetaItemStack metaStack = new MetaItemStack(stack); final boolean allowUnsafe = ess.getSettings().allowUnsafeEnchantments(); metaStack.addStringMeta(null, allowUnsafe, meta, ess); stack = metaStack.getItemStack(); } - } catch (Exception ex) { + } catch (final Exception ex) { throw new SignException(ex.getMessage(), ex); } return stack; @@ -391,7 +406,7 @@ public class EssentialsSign { protected final BigDecimal getBigDecimal(final String line) throws SignException { try { return new BigDecimal(line); - } catch (ArithmeticException | NumberFormatException ex) { + } catch (final ArithmeticException | NumberFormatException ex) { throw new SignException(ex.getMessage(), ex); } } @@ -440,16 +455,15 @@ public class EssentialsSign { ess.showError(sender, exception, "\\ sign: " + signName); } - private static BlockFace getWallSignFacing(Block block) { - try { - final WallSign signData = (WallSign) block.getState().getBlockData(); - return signData.getFacing(); - } catch (NoClassDefFoundError | NoSuchMethodError e) { - final org.bukkit.material.Sign signMat = (org.bukkit.material.Sign) block.getState().getData(); - return signMat.getFacing(); - } - } + public interface ISign { + String getLine(final int index); + void setLine(final int index, final String text); + + Block getBlock(); + + void updateSign(); + } static class EventSign implements ISign { private final transient SignChangeEvent event; @@ -464,8 +478,8 @@ public class EssentialsSign { @Override public final String getLine(final int index) { - StringBuilder builder = new StringBuilder(); - for (char c : event.getLine(index).toCharArray()) { + final StringBuilder builder = new StringBuilder(); + for (final char c : event.getLine(index).toCharArray()) { if (c < 0xF700 || c > 0xF747) { builder.append(c); } @@ -492,7 +506,6 @@ public class EssentialsSign { } } - static class BlockSign implements ISign { private final transient Sign sign; private final transient Block block; @@ -504,8 +517,8 @@ public class EssentialsSign { @Override public final String getLine(final int index) { - StringBuilder builder = new StringBuilder(); - for (char c : sign.getLine(index).toCharArray()) { + final StringBuilder builder = new StringBuilder(); + for (final char c : sign.getLine(index).toCharArray()) { if (c < 0xF700 || c > 0xF747) { builder.append(c); } @@ -529,15 +542,4 @@ public class EssentialsSign { sign.update(); } } - - - public interface ISign { - String getLine(final int index); - - void setLine(final int index, final String text); - - Block getBlock(); - - void updateSign(); - } } diff --git a/Essentials/src/com/earth2me/essentials/signs/SignBalance.java b/Essentials/src/com/earth2me/essentials/signs/SignBalance.java index 6b9201499..b1fabbb89 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignBalance.java +++ b/Essentials/src/com/earth2me/essentials/signs/SignBalance.java @@ -6,7 +6,6 @@ import net.ess3.api.IEssentials; import static com.earth2me.essentials.I18n.tl; - public class SignBalance extends EssentialsSign { public SignBalance() { super("Balance"); diff --git a/Essentials/src/com/earth2me/essentials/signs/SignBlockListener.java b/Essentials/src/com/earth2me/essentials/signs/SignBlockListener.java index 2ce30d323..eba8079a7 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignBlockListener.java +++ b/Essentials/src/com/earth2me/essentials/signs/SignBlockListener.java @@ -14,17 +14,22 @@ 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.BlockBurnEvent; +import org.bukkit.event.block.BlockIgniteEvent; +import org.bukkit.event.block.BlockPistonExtendEvent; +import org.bukkit.event.block.BlockPistonRetractEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.block.SignChangeEvent; import java.util.logging.Level; import java.util.logging.Logger; - public class SignBlockListener implements Listener { private static final Logger LOGGER = Logger.getLogger("Essentials"); private final transient IEssentials ess; - public SignBlockListener(IEssentials ess) { + public SignBlockListener(final IEssentials ess) { this.ess = ess; } @@ -38,7 +43,7 @@ public class SignBlockListener implements Listener { if (protectSignsAndBlocks(event.getBlock(), event.getPlayer())) { event.setCancelled(true); } - } catch (MaxMoneyException ex) { + } catch (final MaxMoneyException ex) { event.setCancelled(true); } } @@ -56,14 +61,14 @@ public class SignBlockListener implements Listener { if (MaterialUtil.isSign(mat)) { final Sign csign = (Sign) block.getState(); - for (EssentialsSign sign : ess.getSettings().enabledSigns()) { + for (final EssentialsSign sign : ess.getSettings().enabledSigns()) { if (csign.getLine(0).equalsIgnoreCase(sign.getSuccessName(ess)) && !sign.onSignBreak(block, player, ess)) { return true; } } } - for (EssentialsSign sign : ess.getSettings().enabledSigns()) { + for (final EssentialsSign sign : ess.getSettings().enabledSigns()) { if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType()) && !sign.onBlockBreak(block, player, ess)) { LOGGER.log(Level.INFO, "A block was protected by a sign."); return true; @@ -78,7 +83,7 @@ public class SignBlockListener implements Listener { event.getHandlers().unregister(this); return; } - User user = ess.getUser(event.getPlayer()); + final User user = ess.getUser(event.getPlayer()); for (int i = 0; i < 4; i++) { event.setLine(i, FormatUtil.formatString(user, "essentials.signs", event.getLine(i))); @@ -89,18 +94,18 @@ public class SignBlockListener implements Listener { return; } //We loop through all sign types here to prevent clashes with preexisting signs later - for (Signs signs : Signs.values()) { + for (final Signs signs : Signs.values()) { final EssentialsSign sign = signs.getSign(); // If the top sign line contains any of the success name (excluding colors), just remove all colours from the first line. // This is to ensure we are only modifying possible Essentials Sign and not just removing colors from the first line of all signs. // Top line and sign#getSuccessName() are both lowercased since contains is case-sensitive. - String successName = sign.getSuccessName(ess); + final String successName = sign.getSuccessName(ess); if (successName == null) { event.getPlayer().sendMessage(I18n.tl("errorWithMessage", "Please report this error to a staff member.")); return; } - String lSuccessName = ChatColor.stripColor(successName.toLowerCase()); + final String lSuccessName = ChatColor.stripColor(successName.toLowerCase()); if (lColorlessTopLine.contains(lSuccessName)) { // If this sign is not enabled and it has been requested to not protect it's name (when disabled), then do not protect the name. @@ -121,7 +126,7 @@ public class SignBlockListener implements Listener { return; } - for (EssentialsSign sign : ess.getSettings().enabledSigns()) { + for (final EssentialsSign sign : ess.getSettings().enabledSigns()) { if (event.getLine(0).equalsIgnoreCase(sign.getSuccessName(ess))) { event.setCancelled(true); return; @@ -149,7 +154,7 @@ public class SignBlockListener implements Listener { if (MaterialUtil.isSign(block.getType())) { return; } - for (EssentialsSign sign : ess.getSettings().enabledSigns()) { + for (final EssentialsSign sign : ess.getSettings().enabledSigns()) { if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType()) && !sign.onBlockPlace(block, event.getPlayer(), ess)) { event.setCancelled(true); return; @@ -169,7 +174,7 @@ public class SignBlockListener implements Listener { event.setCancelled(true); return; } - for (EssentialsSign sign : ess.getSettings().enabledSigns()) { + for (final EssentialsSign sign : ess.getSettings().enabledSigns()) { if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType()) && !sign.onBlockBurn(block, ess)) { event.setCancelled(true); return; @@ -189,7 +194,7 @@ public class SignBlockListener implements Listener { event.setCancelled(true); return; } - for (EssentialsSign sign : ess.getSettings().enabledSigns()) { + for (final EssentialsSign sign : ess.getSettings().enabledSigns()) { if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType()) && !sign.onBlockIgnite(block, ess)) { event.setCancelled(true); return; @@ -204,12 +209,12 @@ public class SignBlockListener implements Listener { return; } - for (Block block : event.getBlocks()) { + for (final Block block : event.getBlocks()) { if ((MaterialUtil.isSign(block.getType()) && EssentialsSign.isValidSign(ess, new EssentialsSign.BlockSign(block))) || EssentialsSign.checkIfBlockBreaksSigns(block)) { event.setCancelled(true); return; } - for (EssentialsSign sign : ess.getSettings().enabledSigns()) { + for (final EssentialsSign sign : ess.getSettings().enabledSigns()) { if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType()) && !sign.onBlockPush(block, ess)) { event.setCancelled(true); return; @@ -227,14 +232,14 @@ public class SignBlockListener implements Listener { if (event.isSticky()) { final Block pistonBaseBlock = event.getBlock(); - final Block[] affectedBlocks = new Block[]{pistonBaseBlock, pistonBaseBlock.getRelative(event.getDirection()), event.getRetractLocation().getBlock()}; + final Block[] affectedBlocks = new Block[] {pistonBaseBlock, pistonBaseBlock.getRelative(event.getDirection()), event.getRetractLocation().getBlock()}; - for (Block block : affectedBlocks) { + for (final Block block : affectedBlocks) { if ((MaterialUtil.isSign(block.getType()) && EssentialsSign.isValidSign(ess, new EssentialsSign.BlockSign(block))) || EssentialsSign.checkIfBlockBreaksSigns(block)) { event.setCancelled(true); return; } - for (EssentialsSign sign : ess.getSettings().enabledSigns()) { + for (final EssentialsSign sign : ess.getSettings().enabledSigns()) { if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType()) && !sign.onBlockPush(block, ess)) { event.setCancelled(true); return; diff --git a/Essentials/src/com/earth2me/essentials/signs/SignBuy.java b/Essentials/src/com/earth2me/essentials/signs/SignBuy.java index a97eb10c0..e347fb092 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignBuy.java +++ b/Essentials/src/com/earth2me/essentials/signs/SignBuy.java @@ -9,7 +9,6 @@ import org.bukkit.inventory.ItemStack; import java.math.BigDecimal; - public class SignBuy extends EssentialsSign { public SignBuy() { super("Buy"); @@ -29,15 +28,15 @@ public class SignBuy extends EssentialsSign { // Check if the player is trying to buy in bulk. if (ess.getSettings().isAllowBulkBuySell() && player.getBase().isSneaking()) { - ItemStack heldItem = player.getItemInHand(); + final ItemStack heldItem = player.getItemInHand(); if (items.getItemStack().isSimilar(heldItem)) { - int initialItemAmount = items.getItemStack().getAmount(); - int newItemAmount = heldItem.getAmount(); - ItemStack item = items.getItemStack(); + final int initialItemAmount = items.getItemStack().getAmount(); + final int newItemAmount = heldItem.getAmount(); + final ItemStack item = items.getItemStack(); item.setAmount(newItemAmount); items = new Trade(item, ess); - BigDecimal chargeAmount = charge.getMoney(); + final BigDecimal chargeAmount = charge.getMoney(); //noinspection BigDecimalMethodWithoutRoundingCalled BigDecimal pricePerSingleItem = chargeAmount.divide(new BigDecimal(initialItemAmount)); pricePerSingleItem = pricePerSingleItem.multiply(new BigDecimal(newItemAmount)); diff --git a/Essentials/src/com/earth2me/essentials/signs/SignDisposal.java b/Essentials/src/com/earth2me/essentials/signs/SignDisposal.java index c86d0ecbd..a189e1522 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignDisposal.java +++ b/Essentials/src/com/earth2me/essentials/signs/SignDisposal.java @@ -6,14 +6,13 @@ import net.ess3.api.IEssentials; import static com.earth2me.essentials.I18n.tl; - public class SignDisposal extends EssentialsSign { public SignDisposal() { super("Disposal"); } @Override - protected boolean onSignCreate(ISign sign, User player, String username, IEssentials ess) throws SignException, ChargeException { + protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException { if (!player.isAuthorized("essentials.signs.disposal.name")) { sign.setLine(1, ""); sign.setLine(2, ""); diff --git a/Essentials/src/com/earth2me/essentials/signs/SignEnchant.java b/Essentials/src/com/earth2me/essentials/signs/SignEnchant.java index 73907b172..9ac87aca5 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignEnchant.java +++ b/Essentials/src/com/earth2me/essentials/signs/SignEnchant.java @@ -12,7 +12,6 @@ import java.util.Locale; import static com.earth2me.essentials.I18n.tl; - public class SignEnchant extends EssentialsSign { public SignEnchant() { super("Enchant"); @@ -23,7 +22,7 @@ public class SignEnchant extends EssentialsSign { final ItemStack stack; try { stack = sign.getLine(1).equals("*") || sign.getLine(1).equalsIgnoreCase("any") ? null : getItemStack(sign.getLine(1), 1, ess); - } catch (SignException e) { + } catch (final SignException e) { sign.setLine(1, "§c"); throw e; } @@ -37,7 +36,7 @@ public class SignEnchant extends EssentialsSign { if (enchantLevel.length > 1) { try { level = Integer.parseInt(enchantLevel[1]); - } catch (NumberFormatException ex) { + } catch (final NumberFormatException ex) { sign.setLine(2, "§c"); throw new SignException(ex.getMessage(), ex); } @@ -55,7 +54,7 @@ public class SignEnchant extends EssentialsSign { stack.addEnchantment(enchantment, level); } } - } catch (Throwable ex) { + } catch (final Throwable ex) { throw new SignException(ex.getMessage(), ex); } getTrade(sign, 3, ess); @@ -63,7 +62,7 @@ public class SignEnchant extends EssentialsSign { } @Override - protected boolean onSignInteract(ISign sign, User player, String username, IEssentials ess) throws SignException, ChargeException { + protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException { final ItemStack search = sign.getLine(1).equals("*") || sign.getLine(1).equalsIgnoreCase("any") ? null : getItemStack(sign.getLine(1), 1, ess); final Trade charge = getTrade(sign, 3, ess); charge.isAffordableFor(player); @@ -76,7 +75,7 @@ public class SignEnchant extends EssentialsSign { if (enchantLevel.length > 1) { try { level = Integer.parseInt(enchantLevel[1]); - } catch (NumberFormatException ex) { + } catch (final NumberFormatException ex) { throw new SignException(ex.getMessage(), ex); } } @@ -99,7 +98,7 @@ public class SignEnchant extends EssentialsSign { playerHand.addEnchantment(enchantment, level); } } - } catch (Exception ex) { + } catch (final Exception ex) { throw new SignException(ex.getMessage(), ex); } diff --git a/Essentials/src/com/earth2me/essentials/signs/SignEntityListener.java b/Essentials/src/com/earth2me/essentials/signs/SignEntityListener.java index 8a7507caf..c940dc59f 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignEntityListener.java +++ b/Essentials/src/com/earth2me/essentials/signs/SignEntityListener.java @@ -9,7 +9,6 @@ import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityExplodeEvent; - public class SignEntityListener implements Listener { private final transient IEssentials ess; @@ -25,12 +24,12 @@ public class SignEntityListener implements Listener { return; } - for (Block block : event.blockList()) { + for (final Block block : event.blockList()) { if ((MaterialUtil.isSign(block.getType()) && EssentialsSign.isValidSign(ess, new EssentialsSign.BlockSign(block))) || EssentialsSign.checkIfBlockBreaksSigns(block)) { event.setCancelled(true); return; } - for (EssentialsSign sign : ess.getSettings().enabledSigns()) { + for (final EssentialsSign sign : ess.getSettings().enabledSigns()) { if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType())) { event.setCancelled(!sign.onBlockExplode(block, ess)); return; @@ -51,7 +50,7 @@ public class SignEntityListener implements Listener { event.setCancelled(true); return; } - for (EssentialsSign sign : ess.getSettings().enabledSigns()) { + for (final EssentialsSign sign : ess.getSettings().enabledSigns()) { if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType()) && !sign.onBlockBreak(block, ess)) { event.setCancelled(true); return; diff --git a/Essentials/src/com/earth2me/essentials/signs/SignException.java b/Essentials/src/com/earth2me/essentials/signs/SignException.java index 2a00f8270..bad354534 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignException.java +++ b/Essentials/src/com/earth2me/essentials/signs/SignException.java @@ -1,6 +1,5 @@ package com.earth2me.essentials.signs; - public class SignException extends Exception { public SignException(final String message) { super(message); diff --git a/Essentials/src/com/earth2me/essentials/signs/SignFree.java b/Essentials/src/com/earth2me/essentials/signs/SignFree.java index 617d29e01..70d31625b 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignFree.java +++ b/Essentials/src/com/earth2me/essentials/signs/SignFree.java @@ -10,7 +10,6 @@ import org.bukkit.inventory.meta.ItemMeta; import static com.earth2me.essentials.I18n.tl; - public class SignFree extends EssentialsSign { public SignFree() { super("Free"); @@ -22,7 +21,7 @@ public class SignFree extends EssentialsSign { ItemStack item = getItemStack(sign.getLine(1), 1, ess); item = getItemMeta(item, sign.getLine(2), ess); item = getItemMeta(item, sign.getLine(3), ess); - } catch (SignException ex) { + } catch (final SignException ex) { sign.setLine(1, "§c"); throw new SignException(ex.getMessage(), ex); } @@ -41,11 +40,11 @@ public class SignFree extends EssentialsSign { item.setAmount(item.getType().getMaxStackSize()); - ItemMeta meta = item.getItemMeta(); + final ItemMeta meta = item.getItemMeta(); final String displayName = meta.hasDisplayName() ? meta.getDisplayName() : item.getType().toString(); - Inventory invent = ess.getServer().createInventory(player.getBase(), 36, displayName); + final Inventory invent = ess.getServer().createInventory(player.getBase(), 36, displayName); for (int i = 0; i < 36; i++) { invent.addItem(item); } diff --git a/Essentials/src/com/earth2me/essentials/signs/SignGameMode.java b/Essentials/src/com/earth2me/essentials/signs/SignGameMode.java index 820ecd84c..703fd6258 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignGameMode.java +++ b/Essentials/src/com/earth2me/essentials/signs/SignGameMode.java @@ -11,7 +11,6 @@ import java.util.Locale; import static com.earth2me.essentials.I18n.tl; - public class SignGameMode extends EssentialsSign { public SignGameMode() { super("GameMode"); @@ -47,7 +46,7 @@ public class SignGameMode extends EssentialsSign { return true; } - private void performSetMode(String mode, Player player) throws SignException { + private void performSetMode(final String mode, final Player player) throws SignException { if (mode.contains("survi") || mode.equalsIgnoreCase("0")) { player.setGameMode(GameMode.SURVIVAL); } else if (mode.contains("creat") || mode.equalsIgnoreCase("1")) { diff --git a/Essentials/src/com/earth2me/essentials/signs/SignHeal.java b/Essentials/src/com/earth2me/essentials/signs/SignHeal.java index a299e2214..23c38708c 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignHeal.java +++ b/Essentials/src/com/earth2me/essentials/signs/SignHeal.java @@ -7,7 +7,6 @@ import net.ess3.api.IEssentials; import static com.earth2me.essentials.I18n.tl; - public class SignHeal extends EssentialsSign { public SignHeal() { super("Heal"); diff --git a/Essentials/src/com/earth2me/essentials/signs/SignInfo.java b/Essentials/src/com/earth2me/essentials/signs/SignInfo.java index c5df803bd..82e144385 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignInfo.java +++ b/Essentials/src/com/earth2me/essentials/signs/SignInfo.java @@ -11,7 +11,6 @@ import net.ess3.api.IEssentials; import java.io.IOException; - public class SignInfo extends EssentialsSign { public SignInfo() { super("Info"); @@ -28,8 +27,8 @@ public class SignInfo extends EssentialsSign { final Trade charge = getTrade(sign, 3, ess); charge.isAffordableFor(player); - String chapter = sign.getLine(1); - String page = sign.getLine(2); + final String chapter = sign.getLine(1); + final String page = sign.getLine(2); final IText input; try { @@ -39,7 +38,7 @@ public class SignInfo extends EssentialsSign { final TextPager pager = new TextPager(output); pager.showPage(chapter, page, null, player.getSource()); - } catch (IOException ex) { + } catch (final IOException ex) { throw new SignException(ex.getMessage(), ex); } diff --git a/Essentials/src/com/earth2me/essentials/signs/SignKit.java b/Essentials/src/com/earth2me/essentials/signs/SignKit.java index a9e569283..b122a8713 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignKit.java +++ b/Essentials/src/com/earth2me/essentials/signs/SignKit.java @@ -11,7 +11,6 @@ import java.util.Locale; import static com.earth2me.essentials.I18n.tl; - public class SignKit extends EssentialsSign { public SignKit() { super("Kit"); @@ -29,7 +28,7 @@ public class SignKit extends EssentialsSign { } else { try { ess.getKits().getKit(kitName); - } catch (Exception ex) { + } catch (final Exception ex) { throw new SignException(ex.getMessage(), ex); } final String group = sign.getLine(2); @@ -44,7 +43,7 @@ public class SignKit extends EssentialsSign { protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException { final String kitName = sign.getLine(1).toLowerCase(Locale.ENGLISH).trim(); final String group = sign.getLine(2).trim(); - if ((!group.isEmpty() && ("§2Everyone".equals(group) || player.inGroup(group))) || (group.isEmpty() && (player.isAuthorized("essentials.kits." + kitName)))) { + if ((!group.isEmpty() && ("§2Everyone".equals(group) || player.inGroup(group))) || (group.isEmpty() && player.isAuthorized("essentials.kits." + kitName))) { final Trade charge = getTrade(sign, 3, ess); charge.isAffordableFor(player); try { @@ -55,9 +54,9 @@ public class SignKit extends EssentialsSign { charge.charge(player); Trade.log("Sign", "Kit", "Interact", username, null, username, charge, sign.getBlock().getLocation(), ess); - } catch (NoChargeException ex) { + } catch (final NoChargeException ex) { return false; - } catch (Exception ex) { + } catch (final Exception ex) { throw new SignException(ex.getMessage(), ex); } return true; diff --git a/Essentials/src/com/earth2me/essentials/signs/SignMail.java b/Essentials/src/com/earth2me/essentials/signs/SignMail.java index a20572a04..fe0a34560 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignMail.java +++ b/Essentials/src/com/earth2me/essentials/signs/SignMail.java @@ -7,7 +7,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class SignMail extends EssentialsSign { public SignMail() { super("Mail"); @@ -20,7 +19,7 @@ public class SignMail extends EssentialsSign { player.sendMessage(tl("noNewMail")); return false; } - for (String s : mail) { + for (final String s : mail) { player.sendMessage(s); } player.sendMessage(tl("markMailAsRead")); diff --git a/Essentials/src/com/earth2me/essentials/signs/SignPlayerListener.java b/Essentials/src/com/earth2me/essentials/signs/SignPlayerListener.java index 67de6f507..05dafd0c7 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignPlayerListener.java +++ b/Essentials/src/com/earth2me/essentials/signs/SignPlayerListener.java @@ -11,10 +11,8 @@ import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; -import java.util.Set; import java.util.logging.Level; - public class SignPlayerListener implements Listener { private final transient IEssentials ess; @@ -40,7 +38,7 @@ public class SignPlayerListener implements Listener { Block targetBlock = null; try { targetBlock = event.getPlayer().getTargetBlock(null, 5); - } catch (IllegalStateException ex) { + } catch (final IllegalStateException ex) { if (ess.getSettings().isDebug()) { ess.getLogger().log(Level.WARNING, ex.getMessage(), ex); } @@ -56,7 +54,7 @@ public class SignPlayerListener implements Listener { final Material mat = block.getType(); if (MaterialUtil.isSign(mat)) { final String csign = ((Sign) block.getState()).getLine(0); - for (EssentialsSign sign : ess.getSettings().enabledSigns()) { + for (final EssentialsSign sign : ess.getSettings().enabledSigns()) { if (csign.equalsIgnoreCase(sign.getSuccessName(ess))) { sign.onSignInteract(block, event.getPlayer(), ess); event.setCancelled(true); @@ -64,7 +62,7 @@ public class SignPlayerListener implements Listener { } } } else { - for (EssentialsSign sign : ess.getSettings().enabledSigns()) { + for (final EssentialsSign sign : ess.getSettings().enabledSigns()) { if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType()) && !sign.onBlockInteract(block, event.getPlayer(), ess)) { event.setCancelled(true); return; diff --git a/Essentials/src/com/earth2me/essentials/signs/SignProtection.java b/Essentials/src/com/earth2me/essentials/signs/SignProtection.java index ae8cc8d97..cbb69dda8 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignProtection.java +++ b/Essentials/src/com/earth2me/essentials/signs/SignProtection.java @@ -16,11 +16,13 @@ import org.bukkit.block.BlockFace; import org.bukkit.block.Sign; import org.bukkit.inventory.ItemStack; -import java.util.*; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Set; import static com.earth2me.essentials.I18n.tl; - @Deprecated // This sign will be removed soon public class SignProtection extends EssentialsSign { private final transient Set protectedBlocks = EnumUtil.getAllMatching(Material.class, @@ -55,8 +57,8 @@ public class SignProtection extends EssentialsSign { public boolean hasAdjacentBlock(final Block block, final Block... ignoredBlocks) { final Block[] faces = getAdjacentBlocks(block); - for (Block b : faces) { - for (Block ignoredBlock : ignoredBlocks) { + for (final Block b : faces) { + for (final Block ignoredBlock : ignoredBlocks) { if (b.getLocation().equals(ignoredBlock.getLocation())) { //TODO: What? } @@ -70,7 +72,7 @@ public class SignProtection extends EssentialsSign { private void checkIfSignsAreBroken(final Block block, final User player, final String username, final IEssentials ess) throws MaxMoneyException { final Map signs = getConnectedSigns(block, player, username, false); - for (Map.Entry entry : signs.entrySet()) { + for (final Map.Entry entry : signs.entrySet()) { if (entry.getValue() != SignProtectionState.NOSIGN) { final Block sign = entry.getKey().getBlock(); if (!hasAdjacentBlock(sign, block)) { @@ -82,7 +84,7 @@ public class SignProtection extends EssentialsSign { } } - private Map getConnectedSigns(final Block block, final User user, final String username, boolean secure) { + private Map getConnectedSigns(final Block block, final User user, final String username, final boolean secure) { final Map signs = new HashMap<>(); getConnectedSigns(block, signs, user, username, secure ? 4 : 2); return signs; @@ -90,7 +92,7 @@ public class SignProtection extends EssentialsSign { private void getConnectedSigns(final Block block, final Map signs, final User user, final String username, final int depth) { final Block[] faces = getAdjacentBlocks(block); - for (Block b : faces) { + for (final Block b : faces) { final Location loc = b.getLocation(); if (signs.containsKey(loc)) { continue; @@ -136,13 +138,13 @@ public class SignProtection extends EssentialsSign { } private Block[] getAdjacentBlocks(final Block block) { - return new Block[]{block.getRelative(BlockFace.NORTH), block.getRelative(BlockFace.SOUTH), block.getRelative(BlockFace.EAST), block.getRelative(BlockFace.WEST), block.getRelative(BlockFace.DOWN), block.getRelative(BlockFace.UP)}; + return new Block[] {block.getRelative(BlockFace.NORTH), block.getRelative(BlockFace.SOUTH), block.getRelative(BlockFace.EAST), block.getRelative(BlockFace.WEST), block.getRelative(BlockFace.DOWN), block.getRelative(BlockFace.UP)}; } - public SignProtectionState isBlockProtected(final Block block, final User user, final String username, boolean secure) { + public SignProtectionState isBlockProtected(final Block block, final User user, final String username, final boolean secure) { final Map signs = getConnectedSigns(block, user, username, secure); SignProtectionState retstate = SignProtectionState.NOSIGN; - for (SignProtectionState state : signs.values()) { + for (final SignProtectionState state : signs.values()) { if (state == SignProtectionState.ALLOWED) { retstate = state; } else if (state == SignProtectionState.NOT_ALLOWED && retstate != SignProtectionState.ALLOWED) { @@ -150,7 +152,7 @@ public class SignProtection extends EssentialsSign { } } if (!secure || retstate == SignProtectionState.NOSIGN) { - for (SignProtectionState state : signs.values()) { + for (final SignProtectionState state : signs.values()) { if (state == SignProtectionState.OWNER) { return state; } @@ -161,7 +163,7 @@ public class SignProtection extends EssentialsSign { public boolean isBlockProtected(final Block block) { final Block[] faces = getAdjacentBlocks(block); - for (Block b : faces) { + for (final Block b : faces) { if (MaterialUtil.isSign(b.getType())) { final Sign sign = (Sign) b.getState(); if (sign.getLine(0).equalsIgnoreCase("§1[Protection]")) { @@ -171,7 +173,7 @@ public class SignProtection extends EssentialsSign { if (protectedBlocks.contains(b.getType())) { final Block[] faceChest = getAdjacentBlocks(b); - for (Block a : faceChest) { + for (final Block a : faceChest) { if (MaterialUtil.isSign(a.getType())) { final Sign sign = (Sign) a.getState(); if (sign.getLine(0).equalsIgnoreCase("§1[Protection]")) { @@ -196,7 +198,7 @@ public class SignProtection extends EssentialsSign { @Override protected boolean onBlockPlace(final Block block, final User player, final String username, final IEssentials ess) throws SignException { - for (Block adjBlock : getAdjacentBlocks(block)) { + for (final Block adjBlock : getAdjacentBlocks(block)) { final SignProtectionState state = isBlockProtected(adjBlock, player, username, true); if ((state == SignProtectionState.ALLOWED || state == SignProtectionState.NOT_ALLOWED) && !player.isAuthorized("essentials.signs.protection.override")) { @@ -220,7 +222,6 @@ public class SignProtection extends EssentialsSign { return true; } - player.sendMessage(tl("noAccessPermission", block.getType().toString().toLowerCase(Locale.ENGLISH))); return false; } @@ -239,7 +240,6 @@ public class SignProtection extends EssentialsSign { return true; } - player.sendMessage(tl("noDestroyPermission", block.getType().toString().toLowerCase(Locale.ENGLISH))); return false; } diff --git a/Essentials/src/com/earth2me/essentials/signs/SignRepair.java b/Essentials/src/com/earth2me/essentials/signs/SignRepair.java index 3b028db27..f4c81071c 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignRepair.java +++ b/Essentials/src/com/earth2me/essentials/signs/SignRepair.java @@ -9,7 +9,6 @@ import net.ess3.api.IEssentials; import static com.earth2me.essentials.I18n.tl; - public class SignRepair extends EssentialsSign { public SignRepair() { super("Repair"); @@ -33,7 +32,7 @@ public class SignRepair extends EssentialsSign { final Trade charge = getTrade(sign, 2, ess); charge.isAffordableFor(player); - Commandrepair command = new Commandrepair(); + final Commandrepair command = new Commandrepair(); command.setEssentials(ess); try { @@ -45,7 +44,7 @@ public class SignRepair extends EssentialsSign { throw new NotEnoughArgumentsException(); } - } catch (Exception ex) { + } catch (final Exception ex) { throw new SignException(ex.getMessage(), ex); } diff --git a/Essentials/src/com/earth2me/essentials/signs/SignSell.java b/Essentials/src/com/earth2me/essentials/signs/SignSell.java index 33b850a5e..fa2941823 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignSell.java +++ b/Essentials/src/com/earth2me/essentials/signs/SignSell.java @@ -10,7 +10,6 @@ import org.bukkit.inventory.ItemStack; import java.math.BigDecimal; - public class SignSell extends EssentialsSign { public SignSell() { super("Sell"); @@ -30,15 +29,15 @@ public class SignSell extends EssentialsSign { // Check if the player is trying to sell in bulk. if (ess.getSettings().isAllowBulkBuySell() && player.getBase().isSneaking()) { - ItemStack heldItem = player.getItemInHand(); + final ItemStack heldItem = player.getItemInHand(); if (charge.getItemStack().isSimilar(heldItem)) { - int initialItemAmount = charge.getItemStack().getAmount(); - int newItemAmount = heldItem.getAmount(); - ItemStack item = charge.getItemStack(); + final int initialItemAmount = charge.getItemStack().getAmount(); + final int newItemAmount = heldItem.getAmount(); + final ItemStack item = charge.getItemStack(); item.setAmount(newItemAmount); charge = new Trade(item, ess); - BigDecimal chargeAmount = money.getMoney(); + final BigDecimal chargeAmount = money.getMoney(); //noinspection BigDecimalMethodWithoutRoundingCalled BigDecimal pricePerSingleItem = chargeAmount.divide(new BigDecimal(initialItemAmount)); pricePerSingleItem = pricePerSingleItem.multiply(new BigDecimal(newItemAmount)); diff --git a/Essentials/src/com/earth2me/essentials/signs/SignSpawnmob.java b/Essentials/src/com/earth2me/essentials/signs/SignSpawnmob.java index 5a7f81643..dc8978940 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignSpawnmob.java +++ b/Essentials/src/com/earth2me/essentials/signs/SignSpawnmob.java @@ -8,29 +8,28 @@ import net.ess3.api.IEssentials; import java.util.List; - public class SignSpawnmob extends EssentialsSign { public SignSpawnmob() { super("Spawnmob"); } @Override - protected boolean onSignCreate(ISign sign, User player, String username, IEssentials ess) throws SignException, ChargeException { + protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException { validateInteger(sign, 1); validateTrade(sign, 3, ess); return true; } @Override - protected boolean onSignInteract(ISign sign, User player, String username, IEssentials ess) throws SignException, ChargeException { + protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException { final Trade charge = getTrade(sign, 3, ess); charge.isAffordableFor(player); try { - List mobParts = SpawnMob.mobParts(sign.getLine(2)); - List mobData = SpawnMob.mobData(sign.getLine(2)); + final List mobParts = SpawnMob.mobParts(sign.getLine(2)); + final List mobData = SpawnMob.mobData(sign.getLine(2)); SpawnMob.spawnmob(ess, ess.getServer(), player.getSource(), player, mobParts, mobData, Integer.parseInt(sign.getLine(1))); - } catch (Exception ex) { + } catch (final Exception ex) { throw new SignException(ex.getMessage(), ex); } diff --git a/Essentials/src/com/earth2me/essentials/signs/SignTime.java b/Essentials/src/com/earth2me/essentials/signs/SignTime.java index 9cdcb9d3c..76de1e188 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignTime.java +++ b/Essentials/src/com/earth2me/essentials/signs/SignTime.java @@ -7,7 +7,6 @@ import net.ess3.api.IEssentials; import static com.earth2me.essentials.I18n.tl; - public class SignTime extends EssentialsSign { public SignTime() { super("Time"); diff --git a/Essentials/src/com/earth2me/essentials/signs/SignTrade.java b/Essentials/src/com/earth2me/essentials/signs/SignTrade.java index f206faace..bbeb54a50 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignTrade.java +++ b/Essentials/src/com/earth2me/essentials/signs/SignTrade.java @@ -42,12 +42,12 @@ public class SignTrade extends EssentialsSign { protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException, MaxMoneyException { if (sign.getLine(3).substring(2).equalsIgnoreCase(username)) { final Trade store = rechargeSign(sign, ess, player); - Trade stored; + final Trade stored; try { stored = getTrade(sign, 1, AmountType.TOTAL, true, true, ess); subtractAmount(sign, 1, stored, ess); - Map withdraw = stored.pay(player, OverflowType.RETURN); + final Map withdraw = stored.pay(player, OverflowType.RETURN); if (withdraw == null) { Trade.log("Sign", "Trade", "Withdraw", username, store, username, null, sign.getBlock().getLocation(), ess); @@ -55,7 +55,7 @@ public class SignTrade extends EssentialsSign { setAmount(sign, 1, BigDecimal.valueOf(withdraw.get(0).getAmount()), ess); Trade.log("Sign", "Trade", "Withdraw", username, stored, username, new Trade(withdraw.get(0), ess), sign.getBlock().getLocation(), ess); } - } catch (SignException e) { + } catch (final SignException e) { if (store == null) { throw new SignException(tl("tradeSignEmptyOwner"), e); } @@ -100,7 +100,7 @@ public class SignTrade extends EssentialsSign { protected boolean onSignBreak(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, MaxMoneyException { final String signOwner = sign.getLine(3); - final boolean isOwner = (signOwner.length() > 3 && signOwner.substring(2).equalsIgnoreCase(username)); + final boolean isOwner = signOwner.length() > 3 && signOwner.substring(2).equalsIgnoreCase(username); final boolean canBreak = isOwner || player.isAuthorized("essentials.signs.trade.override"); final boolean canCollect = isOwner || player.isAuthorized("essentials.signs.trade.override.collect"); @@ -129,7 +129,7 @@ public class SignTrade extends EssentialsSign { Trade.log("Sign", "Trade", "Withdraw", signOwner, stored2, username, withdraw2 == null ? null : new Trade(withdraw2.get(0), ess), sign.getBlock().getLocation(), ess); sign.updateSign(); - } catch (SignException e) { + } catch (final SignException e) { if (player.isAuthorized("essentials.signs.trade.override")) { return true; } @@ -181,7 +181,7 @@ public class SignTrade extends EssentialsSign { if (!(split[1].equalsIgnoreCase("exp") || split[1].equalsIgnoreCase("xp")) && getItemStack(split[1], amount, ess).getType() == Material.AIR) { throw new SignException(tl("moreThanZero")); } - String newline = amount + " " + split[1] + ":0"; + final String newline = amount + " " + split[1] + ":0"; if ((newline + amount).length() > 15) { throw new SignException("Line can be too long!"); } @@ -223,7 +223,7 @@ public class SignTrade extends EssentialsSign { if (money != null && amount != null) { return new Trade(amountType == AmountType.COST ? money : amount, ess); } - } catch (SignException e) { + } catch (final SignException e) { throw new SignException(tl("tradeSignEmpty"), e); } } @@ -238,7 +238,7 @@ public class SignTrade extends EssentialsSign { if (notEmpty && (amount < 1 || stackamount < 1)) { throw new SignException(tl("tradeSignEmpty")); } - return new Trade((amountType == AmountType.COST ? stackamount : amount), ess); + return new Trade(amountType == AmountType.COST ? stackamount : amount, ess); } else { final int stackamount = getIntegerPositive(split[0]); final ItemStack item = getItemStack(split[1], stackamount, allowId, ess); @@ -332,7 +332,7 @@ public class SignTrade extends EssentialsSign { if (split.length == 3) { if (split[1].equalsIgnoreCase("exp") || split[1].equalsIgnoreCase("xp")) { final int stackamount = getIntegerPositive(split[0]); - final String newline = stackamount + " " + split[1] + ":" + (value.intValueExact()); + final String newline = stackamount + " " + split[1] + ":" + value.intValueExact(); if (newline.length() > 15) { throw new SignException("This sign is full: Line too long!"); } @@ -341,7 +341,7 @@ public class SignTrade extends EssentialsSign { } else { final int stackamount = getIntegerPositive(split[0]); getItemStack(split[1], stackamount, ess); - final String newline = stackamount + " " + split[1] + ":" + (value.intValueExact()); + final String newline = stackamount + " " + split[1] + ":" + value.intValueExact(); if (newline.length() > 15) { throw new SignException("This sign is full: Line too long!"); } @@ -352,7 +352,6 @@ public class SignTrade extends EssentialsSign { throw new SignException(tl("invalidSignLine", index + 1)); } - public enum AmountType { TOTAL, ROUNDED, diff --git a/Essentials/src/com/earth2me/essentials/signs/SignWarp.java b/Essentials/src/com/earth2me/essentials/signs/SignWarp.java index add12a47c..121fd19c0 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignWarp.java +++ b/Essentials/src/com/earth2me/essentials/signs/SignWarp.java @@ -10,7 +10,6 @@ import java.util.concurrent.CompletableFuture; import static com.earth2me.essentials.I18n.tl; - public class SignWarp extends EssentialsSign { public SignWarp() { super("Warp"); @@ -27,7 +26,7 @@ public class SignWarp extends EssentialsSign { } else { try { ess.getWarps().getWarp(warpName); - } catch (Exception ex) { + } catch (final Exception ex) { throw new SignException(ex.getMessage(), ex); } final String group = sign.getLine(2); @@ -54,7 +53,7 @@ public class SignWarp extends EssentialsSign { } final Trade charge = getTrade(sign, 3, ess); - CompletableFuture future = new CompletableFuture<>(); + final CompletableFuture future = new CompletableFuture<>(); player.getAsyncTeleport().warp(player, warpName, charge, TeleportCause.PLUGIN, future); future.thenAccept(success -> { if (success) { diff --git a/Essentials/src/com/earth2me/essentials/signs/SignWeather.java b/Essentials/src/com/earth2me/essentials/signs/SignWeather.java index 534d14832..4fc2a758e 100644 --- a/Essentials/src/com/earth2me/essentials/signs/SignWeather.java +++ b/Essentials/src/com/earth2me/essentials/signs/SignWeather.java @@ -7,7 +7,6 @@ import net.ess3.api.IEssentials; import static com.earth2me.essentials.I18n.tl; - public class SignWeather extends EssentialsSign { public SignWeather() { super("Weather"); diff --git a/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileReader.java b/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileReader.java index f7dd7a09e..1903a20f6 100644 --- a/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileReader.java +++ b/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileReader.java @@ -9,11 +9,10 @@ import java.io.FileReader; import java.io.IOException; import java.util.logging.Level; - public abstract class AbstractDelayedYamlFileReader implements Runnable { + protected final transient IEssentials plugin; private final transient File file; private final transient Class clazz; - protected final transient IEssentials plugin; public AbstractDelayedYamlFileReader(final IEssentials ess, final File file, final Class clazz) { this.file = file; @@ -35,17 +34,17 @@ public abstract class AbstractDelayedYamlFileReader imp } finally { try { reader.close(); - } catch (IOException ex) { + } catch (final IOException ex) { Bukkit.getLogger().log(Level.SEVERE, "File can't be closed: " + file.toString(), ex); } } - } catch (FileNotFoundException ex) { + } catch (final FileNotFoundException ex) { onException(); if (plugin.getSettings() == null || plugin.getSettings().isDebug()) { Bukkit.getLogger().log(Level.INFO, "File not found: " + file.toString()); } - } catch (ObjectLoadException ex) { + } catch (final ObjectLoadException ex) { onException(); Bukkit.getLogger().log(Level.SEVERE, "File broken: " + file.toString(), ex.getCause()); } diff --git a/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileWriter.java b/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileWriter.java index 26cbb3e59..0b75a53dd 100644 --- a/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileWriter.java +++ b/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileWriter.java @@ -8,11 +8,10 @@ import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.logging.Level; - public abstract class AbstractDelayedYamlFileWriter implements Runnable { private final transient File file; - public AbstractDelayedYamlFileWriter(IEssentials ess, File file) { + public AbstractDelayedYamlFileWriter(final IEssentials ess, final File file) { this.file = file; ess.runTaskAsynchronously(this); } @@ -30,7 +29,7 @@ public abstract class AbstractDelayedYamlFileWriter implements Runnable { } pw = new PrintWriter(file); new YamlStorageWriter(pw).save(object); - } catch (FileNotFoundException ex) { + } catch (final FileNotFoundException ex) { Bukkit.getLogger().log(Level.SEVERE, file.toString(), ex); } finally { onFinish(); diff --git a/Essentials/src/com/earth2me/essentials/storage/AsyncStorageObjectHolder.java b/Essentials/src/com/earth2me/essentials/storage/AsyncStorageObjectHolder.java index c57bbed1b..6788bd4af 100644 --- a/Essentials/src/com/earth2me/essentials/storage/AsyncStorageObjectHolder.java +++ b/Essentials/src/com/earth2me/essentials/storage/AsyncStorageObjectHolder.java @@ -9,19 +9,18 @@ import java.io.File; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Level; - public abstract class AsyncStorageObjectHolder implements IConf, IStorageObjectHolder, IReload { - private transient T data; + protected final transient IEssentials ess; private final transient ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); private final transient Class clazz; - protected final transient IEssentials ess; + private transient T data; public AsyncStorageObjectHolder(final IEssentials ess, final Class clazz) { this.ess = ess; this.clazz = clazz; try { this.data = clazz.newInstance(); - } catch (IllegalAccessException | InstantiationException ex) { + } catch (final IllegalAccessException | InstantiationException ex) { Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); } } @@ -77,7 +76,6 @@ public abstract class AsyncStorageObjectHolder implemen public abstract File getStorageFile(); - private class StorageObjectDataWriter extends AbstractDelayedYamlFileWriter { StorageObjectDataWriter() { super(ess, getStorageFile()); @@ -96,7 +94,6 @@ public abstract class AsyncStorageObjectHolder implemen } } - private class StorageObjectDataReader extends AbstractDelayedYamlFileReader { StorageObjectDataReader() { super(ess, getStorageFile(), clazz); @@ -121,7 +118,7 @@ public abstract class AsyncStorageObjectHolder implemen if (data == null) { try { data = clazz.newInstance(); - } catch (IllegalAccessException | InstantiationException ex) { + } catch (final IllegalAccessException | InstantiationException ex) { Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); } } diff --git a/Essentials/src/com/earth2me/essentials/storage/BukkitConstructor.java b/Essentials/src/com/earth2me/essentials/storage/BukkitConstructor.java index f6cc42db8..d4aa1d3b4 100644 --- a/Essentials/src/com/earth2me/essentials/storage/BukkitConstructor.java +++ b/Essentials/src/com/earth2me/essentials/storage/BukkitConstructor.java @@ -13,43 +13,45 @@ import org.bukkit.plugin.Plugin; import org.yaml.snakeyaml.constructor.BaseConstructor; import org.yaml.snakeyaml.constructor.CustomClassLoaderConstructor; import org.yaml.snakeyaml.introspector.PropertyUtils; -import org.yaml.snakeyaml.nodes.*; +import org.yaml.snakeyaml.nodes.MappingNode; +import org.yaml.snakeyaml.nodes.Node; +import org.yaml.snakeyaml.nodes.NodeId; +import org.yaml.snakeyaml.nodes.NodeTuple; +import org.yaml.snakeyaml.nodes.ScalarNode; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; - public class BukkitConstructor extends CustomClassLoaderConstructor { + private Method constructScalarMethod = null; + public BukkitConstructor(final Class clazz, final Plugin plugin) { super(clazz, plugin.getClass().getClassLoader()); yamlClassConstructors.put(NodeId.scalar, new ConstructBukkitScalar()); yamlClassConstructors.put(NodeId.mapping, new ConstructBukkitMapping()); - PropertyUtils propertyUtils = getPropertyUtils(); + final PropertyUtils propertyUtils = getPropertyUtils(); propertyUtils.setSkipMissingProperties(true); setPropertyUtils(propertyUtils); } - private Method constructScalarMethod = null; - - protected String constructScalarRefl(ScalarNode scalarNode) { + protected String constructScalarRefl(final ScalarNode scalarNode) { try { if (constructScalarMethod == null) { constructScalarMethod = BaseConstructor.class.getDeclaredMethod("constructScalar", ScalarNode.class); } return (String) constructScalarMethod.invoke(this, scalarNode); - } catch (NoSuchMethodException - | SecurityException - | IllegalAccessException - | IllegalArgumentException - | InvocationTargetException e) { + } catch (final NoSuchMethodException + | SecurityException + | IllegalAccessException + | IllegalArgumentException + | InvocationTargetException e) { e.printStackTrace(); } return null; } - private class ConstructBukkitScalar extends ConstructScalar { @Override @@ -69,7 +71,7 @@ public class BukkitConstructor extends CustomClassLoaderConstructor { return null; } - Material mat = Material.matchMaterial(split[0]); + final Material mat = Material.matchMaterial(split[0]); if (mat == null) { return null; @@ -94,7 +96,7 @@ public class BukkitConstructor extends CustomClassLoaderConstructor { return null; } - Material mat = Material.matchMaterial(split2[0]); + final Material mat = Material.matchMaterial(split2[0]); if (mat == null) { return null; @@ -114,7 +116,7 @@ public class BukkitConstructor extends CustomClassLoaderConstructor { if (split3.length < 1) { continue; } - Enchantment enchantment = Enchantments.getByName(split3[0]); + final Enchantment enchantment = Enchantments.getByName(split3[0]); if (enchantment == null) { continue; } @@ -142,7 +144,7 @@ public class BukkitConstructor extends CustomClassLoaderConstructor { if (split.length == 0) { return null; } - Enchantment enchant = Enchantments.getByName(split[0]); + final Enchantment enchant = Enchantments.getByName(split[0]); if (enchant == null) { return null; } @@ -163,7 +165,7 @@ public class BukkitConstructor extends CustomClassLoaderConstructor { } private class ConstructBukkitMapping extends ConstructMapping { - + @Override public Object construct(final Node node) { if (node.getType().equals(Location.class)) { @@ -175,7 +177,7 @@ public class BukkitConstructor extends CustomClassLoaderConstructor { if (mnode.getValue().size() < 4) { return null; } - for (NodeTuple nodeTuple : mnode.getValue()) { + for (final NodeTuple nodeTuple : mnode.getValue()) { final String key = constructScalarRefl((ScalarNode) nodeTuple.getKeyNode()); final ScalarNode snode = (ScalarNode) nodeTuple.getValueNode(); if (key.equalsIgnoreCase("world")) { diff --git a/Essentials/src/com/earth2me/essentials/storage/Comment.java b/Essentials/src/com/earth2me/essentials/storage/Comment.java index 848c02ee8..0a4514a67 100644 --- a/Essentials/src/com/earth2me/essentials/storage/Comment.java +++ b/Essentials/src/com/earth2me/essentials/storage/Comment.java @@ -1,8 +1,14 @@ package com.earth2me.essentials.storage; -import java.lang.annotation.*; +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; - -@Target(ElementType.FIELD) @Documented @Retention(RetentionPolicy.RUNTIME) public @interface Comment { +@Target(ElementType.FIELD) +@Documented +@Retention(RetentionPolicy.RUNTIME) +public @interface Comment { String[] value() default ""; -} \ No newline at end of file +} diff --git a/Essentials/src/com/earth2me/essentials/storage/EnchantmentLevel.java b/Essentials/src/com/earth2me/essentials/storage/EnchantmentLevel.java index 8e4e79086..b9290a761 100644 --- a/Essentials/src/com/earth2me/essentials/storage/EnchantmentLevel.java +++ b/Essentials/src/com/earth2me/essentials/storage/EnchantmentLevel.java @@ -4,7 +4,6 @@ import org.bukkit.enchantments.Enchantment; import java.util.Map.Entry; - public class EnchantmentLevel implements Entry { private Enchantment enchantment; private int level; @@ -42,7 +41,7 @@ public class EnchantmentLevel implements Entry { @Override public Integer setValue(final Integer v) { - int t = level; + final int t = level; level = v; return t; } diff --git a/Essentials/src/com/earth2me/essentials/storage/IStorageObjectHolder.java b/Essentials/src/com/earth2me/essentials/storage/IStorageObjectHolder.java index 586b3ecd2..b7ef42d7e 100644 --- a/Essentials/src/com/earth2me/essentials/storage/IStorageObjectHolder.java +++ b/Essentials/src/com/earth2me/essentials/storage/IStorageObjectHolder.java @@ -1,6 +1,5 @@ package com.earth2me.essentials.storage; - public interface IStorageObjectHolder { T getData(); diff --git a/Essentials/src/com/earth2me/essentials/storage/IStorageReader.java b/Essentials/src/com/earth2me/essentials/storage/IStorageReader.java index 03103ae5d..b21d9aa31 100644 --- a/Essentials/src/com/earth2me/essentials/storage/IStorageReader.java +++ b/Essentials/src/com/earth2me/essentials/storage/IStorageReader.java @@ -1,6 +1,5 @@ package com.earth2me.essentials.storage; - public interface IStorageReader { T load(final Class clazz) throws ObjectLoadException; } diff --git a/Essentials/src/com/earth2me/essentials/storage/IStorageWriter.java b/Essentials/src/com/earth2me/essentials/storage/IStorageWriter.java index f6a03bdde..698ee9ec1 100644 --- a/Essentials/src/com/earth2me/essentials/storage/IStorageWriter.java +++ b/Essentials/src/com/earth2me/essentials/storage/IStorageWriter.java @@ -1,6 +1,5 @@ package com.earth2me.essentials.storage; - public interface IStorageWriter { void save(final StorageObject object); } diff --git a/Essentials/src/com/earth2me/essentials/storage/ListType.java b/Essentials/src/com/earth2me/essentials/storage/ListType.java index acedaec2e..d58af7930 100644 --- a/Essentials/src/com/earth2me/essentials/storage/ListType.java +++ b/Essentials/src/com/earth2me/essentials/storage/ListType.java @@ -5,7 +5,8 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - -@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface ListType { +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +public @interface ListType { Class value() default String.class; } diff --git a/Essentials/src/com/earth2me/essentials/storage/MapKeyType.java b/Essentials/src/com/earth2me/essentials/storage/MapKeyType.java index 37b6e12ca..2a2374d55 100644 --- a/Essentials/src/com/earth2me/essentials/storage/MapKeyType.java +++ b/Essentials/src/com/earth2me/essentials/storage/MapKeyType.java @@ -5,7 +5,8 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - -@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface MapKeyType { +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +public @interface MapKeyType { Class value() default String.class; -} \ No newline at end of file +} diff --git a/Essentials/src/com/earth2me/essentials/storage/MapValueType.java b/Essentials/src/com/earth2me/essentials/storage/MapValueType.java index 69ec9e366..ef6d72e7b 100644 --- a/Essentials/src/com/earth2me/essentials/storage/MapValueType.java +++ b/Essentials/src/com/earth2me/essentials/storage/MapValueType.java @@ -5,7 +5,8 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - -@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface MapValueType { +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +public @interface MapValueType { Class value() default String.class; -} \ No newline at end of file +} diff --git a/Essentials/src/com/earth2me/essentials/storage/ObjectLoadException.java b/Essentials/src/com/earth2me/essentials/storage/ObjectLoadException.java index b14a1c6b5..97a1de67d 100644 --- a/Essentials/src/com/earth2me/essentials/storage/ObjectLoadException.java +++ b/Essentials/src/com/earth2me/essentials/storage/ObjectLoadException.java @@ -1,8 +1,7 @@ package com.earth2me.essentials.storage; - public class ObjectLoadException extends Exception { - public ObjectLoadException(Throwable thrwbl) { + public ObjectLoadException(final Throwable thrwbl) { super(thrwbl); } } diff --git a/Essentials/src/com/earth2me/essentials/storage/StorageObject.java b/Essentials/src/com/earth2me/essentials/storage/StorageObject.java index d980c337b..7e01ce463 100644 --- a/Essentials/src/com/earth2me/essentials/storage/StorageObject.java +++ b/Essentials/src/com/earth2me/essentials/storage/StorageObject.java @@ -1,5 +1,4 @@ package com.earth2me.essentials.storage; - public interface StorageObject { } diff --git a/Essentials/src/com/earth2me/essentials/storage/YamlStorageReader.java b/Essentials/src/com/earth2me/essentials/storage/YamlStorageReader.java index 24a881c0f..f3038fb6a 100644 --- a/Essentials/src/com/earth2me/essentials/storage/YamlStorageReader.java +++ b/Essentials/src/com/earth2me/essentials/storage/YamlStorageReader.java @@ -7,10 +7,13 @@ import org.yaml.snakeyaml.constructor.Constructor; import java.io.Reader; import java.lang.reflect.Field; -import java.util.*; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; import java.util.concurrent.locks.ReentrantLock; - public class YamlStorageReader implements IStorageReader { private transient static final Map PREPARED_YAMLS = Collections.synchronizedMap(new HashMap<>()); private transient static final Map LOCKS = new HashMap<>(); @@ -43,7 +46,7 @@ public class YamlStorageReader implements IStorageReader { object = clazz.newInstance(); } return object; - } catch (IllegalAccessException | InstantiationException ex) { + } catch (final IllegalAccessException | InstantiationException ex) { throw new ObjectLoadException(ex); } finally { lock.unlock(); @@ -61,7 +64,7 @@ public class YamlStorageReader implements IStorageReader { private void prepareConstructor(final Constructor constructor, final Set classes, final Class clazz) { classes.add(clazz); final TypeDescription description = new TypeDescription(clazz); - for (Field field : clazz.getDeclaredFields()) { + for (final Field field : clazz.getDeclaredFields()) { prepareList(field, description, classes, constructor); prepareMap(field, description, classes, constructor); if (StorageObject.class.isAssignableFrom(field.getType()) && !classes.contains(field.getType())) { diff --git a/Essentials/src/com/earth2me/essentials/storage/YamlStorageWriter.java b/Essentials/src/com/earth2me/essentials/storage/YamlStorageWriter.java index e897cb261..c6a8a3532 100644 --- a/Essentials/src/com/earth2me/essentials/storage/YamlStorageWriter.java +++ b/Essentials/src/com/earth2me/essentials/storage/YamlStorageWriter.java @@ -19,7 +19,6 @@ import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; - public class YamlStorageWriter implements IStorageWriter { private transient static final Pattern NON_WORD_PATTERN = Pattern.compile("\\W"); private transient static final Yaml YAML = new Yaml(); @@ -33,13 +32,13 @@ public class YamlStorageWriter implements IStorageWriter { public void save(final StorageObject object) { try { writeToFile(object, 0, object.getClass()); - } catch (IllegalArgumentException | IllegalAccessException ex) { + } catch (final IllegalArgumentException | IllegalAccessException ex) { Logger.getLogger(YamlStorageWriter.class.getName()).log(Level.SEVERE, null, ex); } } private void writeToFile(final Object object, final int depth, final Class clazz) throws IllegalAccessException { - for (Field field : clazz.getDeclaredFields()) { + for (final Field field : clazz.getDeclaredFields()) { final int modifier = field.getModifiers(); if (Modifier.isPrivate(modifier) && !Modifier.isTransient(modifier) && !Modifier.isStatic(modifier)) { field.setAccessible(true); @@ -89,7 +88,7 @@ public class YamlStorageWriter implements IStorageWriter { final boolean commentPresent = field.isAnnotationPresent(Comment.class); if (commentPresent) { final Comment comments = field.getAnnotation(Comment.class); - for (String comment : comments.value()) { + for (final String comment : comments.value()) { final String trimmed = comment.trim(); if (trimmed.isEmpty()) { continue; @@ -108,7 +107,7 @@ public class YamlStorageWriter implements IStorageWriter { if (data.isEmpty()) { writer.println(); } - for (Object entry : data) { + for (final Object entry : data) { if (entry != null) { writeIndention(depth); writer.print("- "); @@ -130,7 +129,7 @@ public class YamlStorageWriter implements IStorageWriter { if (data.isEmpty()) { writer.println(); } - for (Entry entry : data.entrySet()) { + for (final Entry entry : data.entrySet()) { final Object value = entry.getValue(); if (value != null) { writeIndention(depth); @@ -181,7 +180,7 @@ public class YamlStorageWriter implements IStorageWriter { private void writeKey(final Object data) { if (data instanceof String || data instanceof Boolean || data instanceof Number) { - String output = data.toString(); + final String output = data.toString(); if (NON_WORD_PATTERN.matcher(output).find()) { writer.print('"'); writer.print(output.replace("\"", "\\\"")); @@ -218,13 +217,13 @@ public class YamlStorageWriter implements IStorageWriter { writeMaterialData(itemStack.getData()); writer.print(' '); writer.print(itemStack.getAmount()); - for (Entry entry : itemStack.getEnchantments().entrySet()) { + for (final Entry entry : itemStack.getEnchantments().entrySet()) { writer.print(' '); writeEnchantmentLevel(entry); } } - private void writeEnchantmentLevel(Object data) { + private void writeEnchantmentLevel(final Object data) { final Entry enchLevel = (Entry) data; writer.print(enchLevel.getKey().getName().toLowerCase(Locale.ENGLISH)); writer.print(':'); diff --git a/Essentials/src/com/earth2me/essentials/textreader/BookInput.java b/Essentials/src/com/earth2me/essentials/textreader/BookInput.java index 5350fd7a5..1826f77f4 100644 --- a/Essentials/src/com/earth2me/essentials/textreader/BookInput.java +++ b/Essentials/src/com/earth2me/essentials/textreader/BookInput.java @@ -2,11 +2,24 @@ package com.earth2me.essentials.textreader; import net.ess3.api.IEssentials; -import java.io.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.Reader; import java.lang.ref.SoftReference; import java.nio.charset.StandardCharsets; -import java.util.*; - +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; public class BookInput implements IText { private final static HashMap> cache = new HashMap<>(); @@ -23,7 +36,7 @@ public class BookInput implements IText { } if (!file.exists()) { if (createFile) { - try (InputStream input = ess.getResource(filename + ".txt"); OutputStream output = new FileOutputStream(file)) { + try (final InputStream input = ess.getResource(filename + ".txt"); final OutputStream output = new FileOutputStream(file)) { final byte[] buffer = new byte[1024]; int length = input.read(buffer); while (length > 0) { @@ -42,10 +55,10 @@ public class BookInput implements IText { throw new FileNotFoundException("Could not create " + filename + ".txt"); } else { lastChange = file.lastModified(); - boolean readFromfile; + final boolean readFromfile; synchronized (cache) { final SoftReference inputRef = cache.get(file.getName()); - BookInput input; + final BookInput input; if (inputRef == null || (input = inputRef.get()) == null || input.lastChange < lastChange) { lines = new ArrayList<>(); chapters = new ArrayList<>(); diff --git a/Essentials/src/com/earth2me/essentials/textreader/BookPager.java b/Essentials/src/com/earth2me/essentials/textreader/BookPager.java index 4f19cd1a2..e000419a6 100644 --- a/Essentials/src/com/earth2me/essentials/textreader/BookPager.java +++ b/Essentials/src/com/earth2me/essentials/textreader/BookPager.java @@ -7,21 +7,20 @@ import java.util.Map; import static com.earth2me.essentials.I18n.tl; - public class BookPager { - private final transient IText text; final double pageMax = 254; final double charMax = 18.5; final int lineMax = 12; + private final transient IText text; public BookPager(final IText text) { this.text = text; } public List getPages(final String pageStr) throws Exception { - List lines = text.getLines(); - List pageLines = new ArrayList<>(); - Map bookmarks = text.getBookmarks(); + final List lines = text.getLines(); + final List pageLines = new ArrayList<>(); + final Map bookmarks = text.getBookmarks(); //This checks to see if we have the chapter in the index if (!bookmarks.containsKey(pageStr.toLowerCase(Locale.ENGLISH))) { @@ -38,11 +37,11 @@ public class BookPager { } } - List pages = new ArrayList<>(); + final List pages = new ArrayList<>(); double pageLength = 0; for (int lineNo = chapterstart; lineNo < chapterend; lineNo += 1) { - String pageLine = lines.get(lineNo); + final String pageLine = lines.get(lineNo); String tempLine; final int lineLength = pageLine.length(); @@ -53,7 +52,7 @@ public class BookPager { boolean forcePageEnd = false; while (pointer < lineLength) { - char letter = pageLine.charAt(pointer); + final char letter = pageLine.charAt(pointer); if (pageLine.charAt(start) == ' ') { start++; @@ -94,7 +93,7 @@ public class BookPager { pageLength++; if (letter == '\u00a7' && pointer + 1 < lineLength) { - char nextLetter = pageLine.charAt(pointer + 1); + final char nextLetter = pageLine.charAt(pointer + 1); if (nextLetter == 'l' || nextLetter == 'L') { weight = 1.25; } else { @@ -102,15 +101,15 @@ public class BookPager { } pointer++; } else if (letter == 'i' || letter == '.' || letter == ',' || letter == '!' || letter == ':' || letter == ';' || letter == '|') { - length += (0.34 * weight); + length += 0.34 * weight; } else if (letter == 'l' || letter == '\'' || letter == '`') { - length += (0.53 * weight); + length += 0.53 * weight; } else if (letter == ' ' || letter == 't' || letter == 'I' || letter == '[' || letter == ']') { - length += (0.69 * weight); + length += 0.69 * weight; } else if (letter == 'f' || letter == 'k' || letter == '"' || letter == '*' || letter == '(' || letter == ')' || letter == '{' || letter == '}' || letter == '<' || letter == '>') { - length += (0.85 * weight); + length += 0.85 * weight; } else if (letter == '@' || letter == '~') { - length += (1.2 * weight); + length += 1.2 * weight; } else { length += weight; } @@ -130,10 +129,10 @@ public class BookPager { return pages; } - boolean buildPage(List pages, List lines, boolean override) { + boolean buildPage(final List pages, final List lines, final boolean override) { if (override || lines.size() > lineMax) { - StringBuilder newPage = new StringBuilder(); - for (String aline : lines) { + final StringBuilder newPage = new StringBuilder(); + for (final String aline : lines) { newPage.append(aline).append("\n"); } pages.add(newPage.toString()); diff --git a/Essentials/src/com/earth2me/essentials/textreader/HelpInput.java b/Essentials/src/com/earth2me/essentials/textreader/HelpInput.java index c8a6ce085..859a5f30a 100644 --- a/Essentials/src/com/earth2me/essentials/textreader/HelpInput.java +++ b/Essentials/src/com/earth2me/essentials/textreader/HelpInput.java @@ -6,13 +6,16 @@ import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import java.io.IOException; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; - public class HelpInput implements IText { private static final String DESCRIPTION = "description"; private static final String PERMISSION = "permission"; @@ -31,7 +34,7 @@ public class HelpInput implements IText { lines.add(tl("helpMatching", match)); } - for (Plugin p : ess.getServer().getPluginManager().getPlugins()) { + for (final Plugin p : ess.getServer().getPluginManager().getPlugins()) { try { final List pluginLines = new ArrayList<>(); final PluginDescriptionFile desc = p.getDescription(); @@ -45,9 +48,9 @@ public class HelpInput implements IText { } final boolean isOnWhitelist = user.isAuthorized("essentials.help." + pluginNameLow); - for (Map.Entry> k : cmds.entrySet()) { + for (final Map.Entry> k : cmds.entrySet()) { try { - if (!match.equalsIgnoreCase("") && (!pluginNameLow.contains(match)) && (!k.getKey().toLowerCase(Locale.ENGLISH).contains(match)) && (!(k.getValue().get(DESCRIPTION) instanceof String && ((String) k.getValue().get(DESCRIPTION)).toLowerCase(Locale.ENGLISH).contains(match)))) { + if (!match.equalsIgnoreCase("") && !pluginNameLow.contains(match) && !k.getKey().toLowerCase(Locale.ENGLISH).contains(match) && !(k.getValue().get(DESCRIPTION) instanceof String && ((String) k.getValue().get(DESCRIPTION)).toLowerCase(Locale.ENGLISH).contains(match))) { continue; } @@ -69,7 +72,7 @@ public class HelpInput implements IText { pluginLines.add(tl("helpLine", k.getKey(), value.get(DESCRIPTION))); } else if (permissions instanceof List && !((List) permissions).isEmpty()) { boolean enabled = false; - for (Object o : (List) permissions) { + for (final Object o : (List) permissions) { if (o instanceof String && user.isAuthorized(o.toString())) { enabled = true; break; @@ -89,7 +92,7 @@ public class HelpInput implements IText { } } } - } catch (NullPointerException ignored) { + } catch (final NullPointerException ignored) { } } if (!pluginLines.isEmpty()) { @@ -101,8 +104,8 @@ public class HelpInput implements IText { lines.add(tl("helpPlugin", pluginName, pluginNameLow)); } } - } catch (NullPointerException ignored) { - } catch (Exception ex) { + } catch (final NullPointerException ignored) { + } catch (final Exception ex) { if (!reported) { logger.log(Level.WARNING, tl("commandHelpFailedForPlugin", pluginNameLow), ex); } diff --git a/Essentials/src/com/earth2me/essentials/textreader/IText.java b/Essentials/src/com/earth2me/essentials/textreader/IText.java index cc47a2499..16cb7d3b6 100644 --- a/Essentials/src/com/earth2me/essentials/textreader/IText.java +++ b/Essentials/src/com/earth2me/essentials/textreader/IText.java @@ -3,7 +3,6 @@ package com.earth2me.essentials.textreader; import java.util.List; import java.util.Map; - public interface IText { // Contains the raw text lines List getLines(); diff --git a/Essentials/src/com/earth2me/essentials/textreader/KeywordReplacer.java b/Essentials/src/com/earth2me/essentials/textreader/KeywordReplacer.java index ee7c640fa..af2824c5a 100644 --- a/Essentials/src/com/earth2me/essentials/textreader/KeywordReplacer.java +++ b/Essentials/src/com/earth2me/essentials/textreader/KeywordReplacer.java @@ -16,13 +16,71 @@ import org.bukkit.plugin.Plugin; import java.lang.management.ManagementFactory; import java.text.DateFormat; import java.text.NumberFormat; -import java.util.*; +import java.util.ArrayList; +import java.util.Date; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; import java.util.logging.Level; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.earth2me.essentials.I18n.tl; +//When adding a keyword here, you also need to add the implementation above +enum KeywordType { + PLAYER(KeywordCachable.CACHEABLE), + DISPLAYNAME(KeywordCachable.CACHEABLE), + USERNAME(KeywordCachable.NOTCACHEABLE), + BALANCE(KeywordCachable.CACHEABLE), + MAILS(KeywordCachable.CACHEABLE), + WORLD(KeywordCachable.CACHEABLE), + WORLDNAME(KeywordCachable.CACHEABLE), + ONLINE(KeywordCachable.CACHEABLE), + UNIQUE(KeywordCachable.CACHEABLE), + WORLDS(KeywordCachable.CACHEABLE), + PLAYERLIST(KeywordCachable.SUBVALUE, true), + TIME(KeywordCachable.CACHEABLE), + DATE(KeywordCachable.CACHEABLE), + WORLDTIME12(KeywordCachable.CACHEABLE), + WORLDTIME24(KeywordCachable.CACHEABLE), + WORLDDATE(KeywordCachable.CACHEABLE), + COORDS(KeywordCachable.CACHEABLE), + TPS(KeywordCachable.CACHEABLE), + UPTIME(KeywordCachable.CACHEABLE), + IP(KeywordCachable.CACHEABLE, true), + ADDRESS(KeywordCachable.CACHEABLE, true), + PLUGINS(KeywordCachable.CACHEABLE, true), + VERSION(KeywordCachable.CACHEABLE, true); + private final KeywordCachable type; + private final boolean isPrivate; + + KeywordType(final KeywordCachable type) { + this.type = type; + this.isPrivate = false; + } + + KeywordType(final KeywordCachable type, final boolean isPrivate) { + this.type = type; + this.isPrivate = isPrivate; + } + + public KeywordCachable getType() { + return type; + } + + public boolean isPrivate() { + return isPrivate; + } +} + +enum KeywordCachable { + CACHEABLE, // This keyword can be cached as a string + SUBVALUE, // This keyword can be cached as a map + NOTCACHEABLE // This keyword should never be cached +} public class KeywordReplacer implements IText { private static final Pattern KEYWORD = Pattern.compile("\\{([^\\{\\}]+)\\}"); @@ -31,7 +89,6 @@ public class KeywordReplacer implements IText { private final transient List replaced; private final transient IEssentials ess; private final transient boolean includePrivate; - private transient ExecuteTimer execTimer; private final transient boolean replaceSpacesWithUnderscores; private final EnumMap keywordCache = new EnumMap<>(KeywordType.class); @@ -54,7 +111,7 @@ public class KeywordReplacer implements IText { } public KeywordReplacer(final IText input, final CommandSource sender, final IEssentials ess, final boolean showPrivate, - boolean replaceSpacesWithUnderscores) { + final boolean replaceSpacesWithUnderscores) { this.input = input; this.replaced = new ArrayList<>(this.input.getLines().size()); this.ess = ess; @@ -64,7 +121,7 @@ public class KeywordReplacer implements IText { } private void replaceKeywords(final CommandSource sender) { - execTimer = new ExecuteTimer(); + final ExecuteTimer execTimer = new ExecuteTimer(); execTimer.start(); User user = null; if (sender.isPlayer()) { @@ -96,7 +153,7 @@ public class KeywordReplacer implements IText { final String keyword = matchTokens[0]; try { String replacer = null; - KeywordType validKeyword = KeywordType.valueOf(keyword); + final KeywordType validKeyword = KeywordType.valueOf(keyword); if (validKeyword.getType().equals(KeywordCachable.CACHEABLE) && keywordCache.containsKey(validKeyword)) { replacer = keywordCache.get(validKeyword).toString(); } else if (validKeyword.getType().equals(KeywordCachable.SUBVALUE)) { @@ -106,7 +163,7 @@ public class KeywordReplacer implements IText { } if (keywordCache.containsKey(validKeyword)) { - Map values = (Map) keywordCache.get(validKeyword); + final Map values = (Map) keywordCache.get(validKeyword); if (values.containsKey(subKeyword)) { replacer = values.get(subKeyword); } @@ -150,7 +207,7 @@ public class KeywordReplacer implements IText { break; case ONLINE: int playerHidden = 0; - for (User u : ess.getOnlineUsers()) { + for (final User u : ess.getOnlineUsers()) { if (u.isHidden()) { playerHidden++; } @@ -162,7 +219,7 @@ public class KeywordReplacer implements IText { break; case WORLDS: final StringBuilder worldsBuilder = new StringBuilder(); - for (World w : ess.getServer().getWorlds()) { + for (final World w : ess.getServer().getWorlds()) { if (worldsBuilder.length() > 0) { worldsBuilder.append(", "); } @@ -185,7 +242,7 @@ public class KeywordReplacer implements IText { //First lets build the per group playerlist final Map> playerList = PlayerList.getPlayerLists(ess, user, showHidden); outputList = new HashMap<>(); - for (String groupName : playerList.keySet()) { + for (final String groupName : playerList.keySet()) { final List groupUsers = playerList.get(groupName); if (groupUsers != null && !groupUsers.isEmpty()) { outputList.put(groupName, PlayerList.listUsers(ess, groupUsers, " ")); @@ -194,7 +251,7 @@ public class KeywordReplacer implements IText { //Now lets build the all user playerlist final StringBuilder playerlistBuilder = new StringBuilder(); - for (Player p : ess.getOnlinePlayers()) { + for (final Player p : ess.getOnlinePlayers()) { if (ess.getUser(p).isHidden()) { continue; } @@ -263,7 +320,7 @@ public class KeywordReplacer implements IText { break; case PLUGINS: final StringBuilder pluginlistBuilder = new StringBuilder(); - for (Plugin p : ess.getServer().getPluginManager().getPlugins()) { + for (final Plugin p : ess.getServer().getPluginManager().getPlugins()) { if (pluginlistBuilder.length() > 0) { pluginlistBuilder.append(", "); } @@ -290,7 +347,7 @@ public class KeywordReplacer implements IText { } line = line.replace(fullMatch, replacer); - } catch (IllegalArgumentException ignored) { + } catch (final IllegalArgumentException ignored) { } return line; @@ -311,57 +368,3 @@ public class KeywordReplacer implements IText { return input.getBookmarks(); } } - -//When adding a keyword here, you also need to add the implementation above -enum KeywordType { - PLAYER(KeywordCachable.CACHEABLE), - DISPLAYNAME(KeywordCachable.CACHEABLE), - USERNAME(KeywordCachable.NOTCACHEABLE), - BALANCE(KeywordCachable.CACHEABLE), - MAILS(KeywordCachable.CACHEABLE), - WORLD(KeywordCachable.CACHEABLE), - WORLDNAME(KeywordCachable.CACHEABLE), - ONLINE(KeywordCachable.CACHEABLE), - UNIQUE(KeywordCachable.CACHEABLE), - WORLDS(KeywordCachable.CACHEABLE), - PLAYERLIST(KeywordCachable.SUBVALUE, true), - TIME(KeywordCachable.CACHEABLE), - DATE(KeywordCachable.CACHEABLE), - WORLDTIME12(KeywordCachable.CACHEABLE), - WORLDTIME24(KeywordCachable.CACHEABLE), - WORLDDATE(KeywordCachable.CACHEABLE), - COORDS(KeywordCachable.CACHEABLE), - TPS(KeywordCachable.CACHEABLE), - UPTIME(KeywordCachable.CACHEABLE), - IP(KeywordCachable.CACHEABLE, true), - ADDRESS(KeywordCachable.CACHEABLE, true), - PLUGINS(KeywordCachable.CACHEABLE, true), - VERSION(KeywordCachable.CACHEABLE, true); - private final KeywordCachable type; - private final boolean isPrivate; - - KeywordType(KeywordCachable type) { - this.type = type; - this.isPrivate = false; - } - - KeywordType(KeywordCachable type, boolean isPrivate) { - this.type = type; - this.isPrivate = isPrivate; - } - - public KeywordCachable getType() { - return type; - } - - public boolean isPrivate() { - return isPrivate; - } -} - - -enum KeywordCachable { - CACHEABLE, // This keyword can be cached as a string - SUBVALUE, // This keyword can be cached as a map - NOTCACHEABLE // This keyword should never be cached -} diff --git a/Essentials/src/com/earth2me/essentials/textreader/SimpleTextInput.java b/Essentials/src/com/earth2me/essentials/textreader/SimpleTextInput.java index 1e183169a..1627fcbcc 100644 --- a/Essentials/src/com/earth2me/essentials/textreader/SimpleTextInput.java +++ b/Essentials/src/com/earth2me/essentials/textreader/SimpleTextInput.java @@ -1,7 +1,10 @@ package com.earth2me.essentials.textreader; -import java.util.*; - +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; public class SimpleTextInput implements IText { private final transient List lines = new ArrayList<>(); diff --git a/Essentials/src/com/earth2me/essentials/textreader/SimpleTextPager.java b/Essentials/src/com/earth2me/essentials/textreader/SimpleTextPager.java index b7349439f..cb2820c7d 100644 --- a/Essentials/src/com/earth2me/essentials/textreader/SimpleTextPager.java +++ b/Essentials/src/com/earth2me/essentials/textreader/SimpleTextPager.java @@ -12,7 +12,7 @@ public class SimpleTextPager { } public void showPage(final CommandSource sender) { - for (String line : text.getLines()) { + for (final String line : text.getLines()) { sender.sendMessage(line); } } @@ -21,7 +21,7 @@ public class SimpleTextPager { return text.getLines(); } - public String getLine(int line) { + public String getLine(final int line) { if (text.getLines().size() < line) { return null; } diff --git a/Essentials/src/com/earth2me/essentials/textreader/TextInput.java b/Essentials/src/com/earth2me/essentials/textreader/TextInput.java index f804e00c6..967140f22 100644 --- a/Essentials/src/com/earth2me/essentials/textreader/TextInput.java +++ b/Essentials/src/com/earth2me/essentials/textreader/TextInput.java @@ -6,11 +6,24 @@ import com.earth2me.essentials.utils.FormatUtil; import com.earth2me.essentials.utils.StringUtil; import net.ess3.api.IEssentials; -import java.io.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.Reader; import java.lang.ref.SoftReference; import java.nio.charset.StandardCharsets; -import java.util.*; - +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; public class TextInput implements IText { private static final HashMap> cache = new HashMap<>(); @@ -34,10 +47,10 @@ public class TextInput implements IText { } if (file.exists()) { lastChange = file.lastModified(); - boolean readFromfile; + final boolean readFromfile; synchronized (cache) { final SoftReference inputRef = cache.get(file.getName()); - TextInput input; + final TextInput input; if (inputRef == null || (input = inputRef.get()) == null || input.lastChange < lastChange) { lines = new ArrayList<>(); chapters = new ArrayList<>(); @@ -62,9 +75,9 @@ public class TextInput implements IText { break; } if (line.length() > 1 && line.charAt(0) == '#') { - String[] titles = line.substring(1).trim().replace(" ", "_").split(","); + final String[] titles = line.substring(1).trim().replace(" ", "_").split(","); chapters.add(FormatUtil.replaceFormat(titles[0])); - for (String title : titles) { + for (final String title : titles) { bookmarks.put(FormatUtil.stripEssentialsFormat(title.toLowerCase(Locale.ENGLISH)), lineNumber); } } @@ -82,7 +95,7 @@ public class TextInput implements IText { chapters = Collections.emptyList(); bookmarks = Collections.emptyMap(); if (createFile) { - try (InputStream input = ess.getResource(filename + ".txt"); OutputStream output = new FileOutputStream(file)) { + try (final InputStream input = ess.getResource(filename + ".txt"); final OutputStream output = new FileOutputStream(file)) { final byte[] buffer = new byte[1024]; int length = input.read(buffer); while (length > 0) { diff --git a/Essentials/src/com/earth2me/essentials/textreader/TextPager.java b/Essentials/src/com/earth2me/essentials/textreader/TextPager.java index 901c937f2..8f988091d 100644 --- a/Essentials/src/com/earth2me/essentials/textreader/TextPager.java +++ b/Essentials/src/com/earth2me/essentials/textreader/TextPager.java @@ -9,7 +9,6 @@ import java.util.Map; import static com.earth2me.essentials.I18n.tl; - public class TextPager { private final transient IText text; private final transient boolean onePage; @@ -24,9 +23,9 @@ public class TextPager { } public void showPage(final String pageStr, final String chapterPageStr, final String commandName, final CommandSource sender) { - List lines = text.getLines(); - List chapters = text.getChapters(); - Map bookmarks = text.getBookmarks(); + final List lines = text.getLines(); + final List chapters = text.getChapters(); + final Map bookmarks = text.getBookmarks(); //This code deals with the initial chapter. We use this to display the initial output or contents. //We also use this code to display some extra information if we don't intend to use chapters @@ -40,7 +39,7 @@ public class TextPager { sender.sendMessage(tl("infoChapter")); final StringBuilder sb = new StringBuilder(); boolean first = true; - for (String string : chapters) { + for (final String string : chapters) { if (!first) { sb.append(", "); } @@ -54,30 +53,30 @@ public class TextPager { if (pageStr != null) { try { page = Integer.parseInt(pageStr); - } catch (NumberFormatException ignored) { + } catch (final NumberFormatException ignored) { } if (page < 1) { page = 1; } } - int start = onePage ? 0 : (page - 1) * 9; + final int start = onePage ? 0 : (page - 1) * 9; int end; for (end = 0; end < lines.size(); end++) { - String line = lines.get(end); + final String line = lines.get(end); if (line.startsWith("#")) { break; } } - int pages = end / 9 + (end % 9 > 0 ? 1 : 0); + final int pages = end / 9 + (end % 9 > 0 ? 1 : 0); if (page > pages) { sender.sendMessage(tl("infoUnknownChapter")); return; } if (!onePage && commandName != null) { - StringBuilder content = new StringBuilder(); + final StringBuilder content = new StringBuilder(); final String[] title = commandName.split(" ", 2); if (title.length > 1) { content.append(I18n.capitalCase(title[0])).append(": "); @@ -102,7 +101,7 @@ public class TextPager { if (chapterPageStr != null) { try { chapterpage = Integer.parseInt(chapterPageStr) - 1; - } catch (NumberFormatException ignored) { + } catch (final NumberFormatException ignored) { } if (chapterpage < 0) { chapterpage = 0; @@ -130,7 +129,7 @@ public class TextPager { final int page = chapterpage + 1; final int pages = (chapterend - chapterstart) / 9 + ((chapterend - chapterstart) % 9 > 0 ? 1 : 0); if (!onePage && commandName != null) { - StringBuilder content = new StringBuilder(); + final StringBuilder content = new StringBuilder(); content.append(I18n.capitalCase(commandName)).append(": "); content.append(pageStr); sender.sendMessage(tl("infoChapterPages", content, page, pages)); diff --git a/Essentials/src/com/earth2me/essentials/utils/DateUtil.java b/Essentials/src/com/earth2me/essentials/utils/DateUtil.java index 3a5d65505..becdf0178 100644 --- a/Essentials/src/com/earth2me/essentials/utils/DateUtil.java +++ b/Essentials/src/com/earth2me/essentials/utils/DateUtil.java @@ -7,17 +7,19 @@ import java.util.regex.Pattern; import static com.earth2me.essentials.I18n.tl; - -public class DateUtil { +public final class DateUtil { private static final Pattern timePattern = Pattern.compile("(?:([0-9]+)\\s*y[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*mo[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*w[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*d[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*h[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*m[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*(?:s[a-z]*)?)?", Pattern.CASE_INSENSITIVE); private static final int maxYears = 100000; - public static String removeTimePattern(String input) { + private DateUtil() { + } + + public static String removeTimePattern(final String input) { return timePattern.matcher(input).replaceFirst("").trim(); } - public static long parseDateDiff(String time, boolean future) throws Exception { - Matcher m = timePattern.matcher(time); + public static long parseDateDiff(final String time, final boolean future) throws Exception { + final Matcher m = timePattern.matcher(time); int years = 0; int months = 0; int weeks = 0; @@ -64,7 +66,7 @@ public class DateUtil { if (!found) { throw new Exception(tl("illegalDate")); } - Calendar c = new GregorianCalendar(); + final Calendar c = new GregorianCalendar(); if (years > 0) { if (years > maxYears) { years = maxYears; @@ -89,7 +91,7 @@ public class DateUtil { if (seconds > 0) { c.add(Calendar.SECOND, seconds * (future ? 1 : -1)); } - Calendar max = new GregorianCalendar(); + final Calendar max = new GregorianCalendar(); max.add(Calendar.YEAR, 10); if (c.after(max)) { return max.getTimeInMillis(); @@ -97,14 +99,14 @@ public class DateUtil { return c.getTimeInMillis(); } - static int dateDiff(int type, Calendar fromDate, Calendar toDate, boolean future) { - int year = Calendar.YEAR; + static int dateDiff(final int type, final Calendar fromDate, final Calendar toDate, final boolean future) { + final int year = Calendar.YEAR; - int fromYear = fromDate.get(year); - int toYear = toDate.get(year); + final int fromYear = fromDate.get(year); + final int toYear = toDate.get(year); if (Math.abs(fromYear - toYear) > maxYears) { toDate.set(year, fromYear + - (future ? maxYears : -maxYears)); + (future ? maxYears : -maxYears)); } int diff = 0; @@ -119,14 +121,14 @@ public class DateUtil { return diff; } - public static String formatDateDiff(long date) { - Calendar c = new GregorianCalendar(); + public static String formatDateDiff(final long date) { + final Calendar c = new GregorianCalendar(); c.setTimeInMillis(date); - Calendar now = new GregorianCalendar(); + final Calendar now = new GregorianCalendar(); return DateUtil.formatDateDiff(now, c); } - public static String formatDateDiff(Calendar fromDate, Calendar toDate) { + public static String formatDateDiff(final Calendar fromDate, final Calendar toDate) { boolean future = false; if (toDate.equals(fromDate)) { return tl("now"); @@ -136,15 +138,15 @@ public class DateUtil { } // Temporary 50ms time buffer added to avoid display truncation due to code execution delays toDate.add(Calendar.MILLISECOND, future ? 50 : -50); - StringBuilder sb = new StringBuilder(); - int[] types = new int[]{Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND}; - String[] names = new String[]{tl("year"), tl("years"), tl("month"), tl("months"), tl("day"), tl("days"), tl("hour"), tl("hours"), tl("minute"), tl("minutes"), tl("second"), tl("seconds")}; + final StringBuilder sb = new StringBuilder(); + final int[] types = new int[] {Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND}; + final String[] names = new String[] {tl("year"), tl("years"), tl("month"), tl("months"), tl("day"), tl("days"), tl("hour"), tl("hours"), tl("minute"), tl("minutes"), tl("second"), tl("seconds")}; int accuracy = 0; for (int i = 0; i < types.length; i++) { if (accuracy > 2) { break; } - int diff = dateDiff(types[i], fromDate, toDate, future); + final int diff = dateDiff(types[i], fromDate, toDate, future); if (diff > 0) { accuracy++; sb.append(" ").append(diff).append(" ").append(names[i * 2 + (diff > 1 ? 1 : 0)]); diff --git a/Essentials/src/com/earth2me/essentials/utils/DescParseTickFormat.java b/Essentials/src/com/earth2me/essentials/utils/DescParseTickFormat.java index 4dbce7504..f978fa05c 100644 --- a/Essentials/src/com/earth2me/essentials/utils/DescParseTickFormat.java +++ b/Essentials/src/com/earth2me/essentials/utils/DescParseTickFormat.java @@ -1,11 +1,17 @@ package com.earth2me.essentials.utils; import java.text.SimpleDateFormat; -import java.util.*; +import java.util.Calendar; +import java.util.Date; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TimeZone; import static com.earth2me.essentials.I18n.tl; - /** * This utility class is used for converting between the ingame time in ticks to ingame time as a friendly string. Note * that the time is INGAME. @@ -60,6 +66,9 @@ public final class DescParseTickFormat { resetAliases.add("default"); } + private DescParseTickFormat() { + } + // ============================================ public static long parse(String desc) throws NumberFormatException { // Only look at alphanumeric and lowercase and : for 24:00 @@ -68,25 +77,25 @@ public final class DescParseTickFormat { // Detect ticks format try { return parseTicks(desc); - } catch (NumberFormatException ignored) { + } catch (final NumberFormatException ignored) { } // Detect 24-hour format try { return parse24(desc); - } catch (NumberFormatException ignored) { + } catch (final NumberFormatException ignored) { } // Detect 12-hour format try { return parse12(desc); - } catch (NumberFormatException ignored) { + } catch (final NumberFormatException ignored) { } // Detect aliases try { return parseAlias(desc); - } catch (NumberFormatException ignored) { + } catch (final NumberFormatException ignored) { } // Well we failed to understand... @@ -129,7 +138,7 @@ public final class DescParseTickFormat { int minutes = 0; desc = desc.toLowerCase(Locale.ENGLISH); - String parsetime = desc.replaceAll("[^0-9]", ""); + final String parsetime = desc.replaceAll("[^0-9]", ""); if (parsetime.length() > 4) { throw new NumberFormatException(); @@ -162,7 +171,7 @@ public final class DescParseTickFormat { public static long hoursMinutesToTicks(final int hours, final int minutes) { long ret = ticksAtMidnight; - ret += (hours) * ticksPerHour; + ret += hours * ticksPerHour; ret += (minutes / 60.0) * ticksPerHour; @@ -242,7 +251,4 @@ public final class DescParseTickFormat { return cal.getTime(); } - - private DescParseTickFormat() { - } } diff --git a/Essentials/src/com/earth2me/essentials/utils/EnumUtil.java b/Essentials/src/com/earth2me/essentials/utils/EnumUtil.java index fd5d86fa1..69f45bdb3 100644 --- a/Essentials/src/com/earth2me/essentials/utils/EnumUtil.java +++ b/Essentials/src/com/earth2me/essentials/utils/EnumUtil.java @@ -8,27 +8,30 @@ import java.lang.reflect.Field; import java.util.HashSet; import java.util.Set; -public class EnumUtil { +public final class EnumUtil { + private EnumUtil() { + } /** * Returns the field matching the first provided enum name that exists within the given * enum class. If no field is found, this method returns null. * * @param enumClass The class to search through - * @param names The names of the fields to search for - * @param The enum to search through + * @param names The names of the fields to search for + * @param The enum to search through * @return The first matching enum field */ - public static T valueOf(Class enumClass, String... names) { - for (String name : names) { + public static T valueOf(final Class enumClass, final String... names) { + for (final String name : names) { try { - Field enumField = enumClass.getDeclaredField(name); + final Field enumField = enumClass.getDeclaredField(name); if (enumField.isEnumConstant()) { return (T) enumField.get(null); } - } catch (NoSuchFieldException | IllegalAccessException ignored) {} + } catch (final NoSuchFieldException | IllegalAccessException ignored) { + } } return null; @@ -39,21 +42,22 @@ public class EnumUtil { * names. * * @param enumClass The class to search through - * @param names The names of the fields to search for - * @param The enum to search through + * @param names The names of the fields to search for + * @param The enum to search through * @return All matching enum fields */ - public static Set getAllMatching(Class enumClass, String... names) { - Set set = new HashSet<>(); + public static Set getAllMatching(final Class enumClass, final String... names) { + final Set set = new HashSet<>(); - for (String name : names) { + for (final String name : names) { try { - Field enumField = enumClass.getDeclaredField(name); + final Field enumField = enumClass.getDeclaredField(name); if (enumField.isEnumConstant()) { set.add((T) enumField.get(null)); } - } catch (NoSuchFieldException | IllegalAccessException ignored) {} + } catch (final NoSuchFieldException | IllegalAccessException ignored) { + } } return set; @@ -65,7 +69,7 @@ public class EnumUtil { * @param names The names of the fields to search for * @return The first matching Material */ - public static Material getMaterial(String... names) { + public static Material getMaterial(final String... names) { return valueOf(Material.class, names); } @@ -75,11 +79,11 @@ public class EnumUtil { * @param names The names of the fields to search for * @return The first matching Statistic */ - public static Statistic getStatistic(String... names) { + public static Statistic getStatistic(final String... names) { return valueOf(Statistic.class, names); } - public static EntityType getEntityType(String... names) { + public static EntityType getEntityType(final String... names) { return valueOf(EntityType.class, names); } } diff --git a/Essentials/src/com/earth2me/essentials/utils/FloatUtil.java b/Essentials/src/com/earth2me/essentials/utils/FloatUtil.java index 188645def..d69429e71 100644 --- a/Essentials/src/com/earth2me/essentials/utils/FloatUtil.java +++ b/Essentials/src/com/earth2me/essentials/utils/FloatUtil.java @@ -3,12 +3,12 @@ package com.earth2me.essentials.utils; /** * parseFloat and parseDouble proxies that are protected against non-finite values. */ -public class FloatUtil { +public final class FloatUtil { private FloatUtil() { } - public static float parseFloat(String s) throws NumberFormatException { - float f = Float.parseFloat(s); + public static float parseFloat(final String s) throws NumberFormatException { + final float f = Float.parseFloat(s); if (Float.isNaN(f)) { throw new NumberFormatException("NaN is not valid"); } @@ -18,8 +18,8 @@ public class FloatUtil { return f; } - public static double parseDouble(String s) throws NumberFormatException { - double d = Double.parseDouble(s); + public static double parseDouble(final String s) throws NumberFormatException { + final double d = Double.parseDouble(s); if (Double.isNaN(d)) { throw new NumberFormatException("NaN is not valid"); } @@ -28,4 +28,4 @@ public class FloatUtil { } return d; } -} \ No newline at end of file +} diff --git a/Essentials/src/com/earth2me/essentials/utils/FormatUtil.java b/Essentials/src/com/earth2me/essentials/utils/FormatUtil.java index 38dd0be87..afcdb2620 100644 --- a/Essentials/src/com/earth2me/essentials/utils/FormatUtil.java +++ b/Essentials/src/com/earth2me/essentials/utils/FormatUtil.java @@ -10,24 +10,24 @@ import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; - -public class FormatUtil { +public final class FormatUtil { + public static final Pattern IPPATTERN = Pattern.compile("^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); private static final Set COLORS = EnumSet.of(ChatColor.BLACK, ChatColor.DARK_BLUE, ChatColor.DARK_GREEN, ChatColor.DARK_AQUA, ChatColor.DARK_RED, ChatColor.DARK_PURPLE, ChatColor.GOLD, ChatColor.GRAY, ChatColor.DARK_GRAY, ChatColor.BLUE, ChatColor.GREEN, ChatColor.AQUA, ChatColor.RED, ChatColor.LIGHT_PURPLE, ChatColor.YELLOW, ChatColor.WHITE); private static final Set FORMATS = EnumSet.of(ChatColor.BOLD, ChatColor.STRIKETHROUGH, ChatColor.UNDERLINE, ChatColor.ITALIC, ChatColor.RESET); private static final Set MAGIC = EnumSet.of(ChatColor.MAGIC); - //Vanilla patterns used to strip existing formats private static final Pattern STRIP_ALL_PATTERN = Pattern.compile("\u00a7+([0-9a-fk-orA-FK-OR])"); //Pattern used to strip md_5 legacy hex hack private static final Pattern STRIP_RGB_PATTERN = Pattern.compile("\u00a7x((?:\u00a7[0-9a-fA-F]){6})"); //Essentials '&' convention colour codes private static final Pattern REPLACE_ALL_PATTERN = Pattern.compile("(&)?&([0-9a-fk-orA-FK-OR])"); - private static final Pattern REPLACE_ALL_RGB_PATTERN = Pattern.compile("(&)?&#([0-9a-fA-F]{6})"); //Used to prepare xmpp output private static final Pattern LOGCOLOR_PATTERN = Pattern.compile("\\x1B\\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]"); private static final Pattern URL_PATTERN = Pattern.compile("((?:(?:https?)://)?[\\w-_\\.]{2,})\\.([a-zA-Z]{2,3}(?:/\\S+)?)"); - public static final Pattern IPPATTERN = Pattern.compile("^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); + + private FormatUtil() { + } //This method is used to simply strip the native minecraft colour codes public static String stripFormat(final String input) { @@ -65,14 +65,15 @@ public class FormatUtil { return replaceColor(input, EnumSet.allOf(ChatColor.class), true); } - static String replaceColor(final String input, final Set supported, boolean rgb) { - StringBuffer legacyBuilder = new StringBuffer(); - Matcher legacyMatcher = REPLACE_ALL_PATTERN.matcher(input); - legacyLoop: while (legacyMatcher.find()) { - boolean isEscaped = (legacyMatcher.group(1) != null); + static String replaceColor(final String input, final Set supported, final boolean rgb) { + final StringBuffer legacyBuilder = new StringBuffer(); + final Matcher legacyMatcher = REPLACE_ALL_PATTERN.matcher(input); + legacyLoop: + while (legacyMatcher.find()) { + final boolean isEscaped = legacyMatcher.group(1) != null; if (!isEscaped) { - char code = legacyMatcher.group(2).toLowerCase(Locale.ROOT).charAt(0); - for (ChatColor color : supported) { + final char code = legacyMatcher.group(2).toLowerCase(Locale.ROOT).charAt(0); + for (final ChatColor color : supported) { if (color.getChar() == code) { legacyMatcher.appendReplacement(legacyBuilder, "\u00a7$2"); continue legacyLoop; @@ -85,16 +86,16 @@ public class FormatUtil { legacyMatcher.appendTail(legacyBuilder); if (rgb) { - StringBuffer rgbBuilder = new StringBuffer(); - Matcher rgbMatcher = REPLACE_ALL_RGB_PATTERN.matcher(legacyBuilder.toString()); + final StringBuffer rgbBuilder = new StringBuffer(); + final Matcher rgbMatcher = REPLACE_ALL_RGB_PATTERN.matcher(legacyBuilder.toString()); while (rgbMatcher.find()) { - boolean isEscaped = (rgbMatcher.group(1) != null); + final boolean isEscaped = rgbMatcher.group(1) != null; if (!isEscaped) { try { - String hexCode = rgbMatcher.group(2); + final String hexCode = rgbMatcher.group(2); rgbMatcher.appendReplacement(rgbBuilder, parseHexColor(hexCode)); continue; - } catch (NumberFormatException ignored) { + } catch (final NumberFormatException ignored) { } } rgbMatcher.appendReplacement(rgbBuilder, "&#$2"); @@ -120,20 +121,21 @@ public class FormatUtil { throw new NumberFormatException("Invalid hex length"); } Color.decode("#" + hexColor); - StringBuilder assembledColorCode = new StringBuilder(); + final StringBuilder assembledColorCode = new StringBuilder(); assembledColorCode.append("\u00a7x"); - for (char curChar : hexColor.toCharArray()) { + for (final char curChar : hexColor.toCharArray()) { assembledColorCode.append("\u00a7").append(curChar); } return assembledColorCode.toString(); } static String stripColor(final String input, final Set strip) { - StringBuffer builder = new StringBuffer(); - Matcher matcher = STRIP_ALL_PATTERN.matcher(input); - searchLoop: while (matcher.find()) { - char code = matcher.group(1).toLowerCase(Locale.ROOT).charAt(0); - for (ChatColor color : strip) { + final StringBuffer builder = new StringBuffer(); + final Matcher matcher = STRIP_ALL_PATTERN.matcher(input); + searchLoop: + while (matcher.find()) { + final char code = matcher.group(1).toLowerCase(Locale.ROOT).charAt(0); + for (final ChatColor color : strip) { if (color.getChar() == code) { matcher.appendReplacement(builder, ""); continue searchLoop; @@ -150,14 +152,14 @@ public class FormatUtil { if (message == null) { return null; } - EnumSet supported = getSupported(user, permBase); + final EnumSet supported = getSupported(user, permBase); // RGB Codes - StringBuffer rgbBuilder = new StringBuffer(); - Matcher rgbMatcher = STRIP_RGB_PATTERN.matcher(message); - boolean rgb = user.isAuthorized(permBase + ".rgb"); + final StringBuffer rgbBuilder = new StringBuffer(); + final Matcher rgbMatcher = STRIP_RGB_PATTERN.matcher(message); + final boolean rgb = user.isAuthorized(permBase + ".rgb"); while (rgbMatcher.find()) { - String code = rgbMatcher.group(1).replace("\u00a7", ""); + final String code = rgbMatcher.group(1).replace("\u00a7", ""); if (rgb) { rgbMatcher.appendReplacement(rgbBuilder, "&#" + code); continue; @@ -168,11 +170,12 @@ public class FormatUtil { message = rgbBuilder.toString(); // arreter de parler // Legacy Colors - StringBuffer builder = new StringBuffer(); - Matcher matcher = STRIP_ALL_PATTERN.matcher(message); - searchLoop: while (matcher.find()) { - char code = matcher.group(1).toLowerCase(Locale.ROOT).charAt(0); - for (ChatColor color : supported) { + final StringBuffer builder = new StringBuffer(); + final Matcher matcher = STRIP_ALL_PATTERN.matcher(message); + searchLoop: + while (matcher.find()) { + final char code = matcher.group(1).toLowerCase(Locale.ROOT).charAt(0); + for (final ChatColor color : supported) { if (color.getChar() == code) { matcher.appendReplacement(builder, "&" + code); continue searchLoop; @@ -189,10 +192,10 @@ public class FormatUtil { if (message == null) { return null; } - EnumSet supported = getSupported(user, permBase); - EnumSet strip = EnumSet.complementOf(supported); + final EnumSet supported = getSupported(user, permBase); + final EnumSet strip = EnumSet.complementOf(supported); - boolean rgb = user.isAuthorized(permBase + ".rgb"); + final boolean rgb = user.isAuthorized(permBase + ".rgb"); if (!supported.isEmpty() || rgb) { message = replaceColor(message, supported, rgb); } @@ -202,8 +205,8 @@ public class FormatUtil { return message; } - private static EnumSet getSupported(IUser user, String permBase) { - EnumSet supported = EnumSet.noneOf(ChatColor.class); + private static EnumSet getSupported(final IUser user, final String permBase) { + final EnumSet supported = EnumSet.noneOf(ChatColor.class); if (user.isAuthorized(permBase + ".color")) { supported.addAll(COLORS); } @@ -213,7 +216,7 @@ public class FormatUtil { if (user.isAuthorized(permBase + ".magic")) { supported.addAll(MAGIC); } - for (ChatColor chatColor : ChatColor.values()) { + for (final ChatColor chatColor : ChatColor.values()) { String colorName = chatColor.name(); if (chatColor == ChatColor.MAGIC) { // Bukkit's name doesn't match with vanilla's @@ -246,7 +249,7 @@ public class FormatUtil { } public static String lastCode(final String input) { - int pos = input.lastIndexOf('\u00a7'); + final int pos = input.lastIndexOf('\u00a7'); if (pos == -1 || (pos + 1) == input.length()) { return ""; } @@ -264,7 +267,7 @@ public class FormatUtil { return text; } - public static boolean validIP(String ipAddress) { + public static boolean validIP(final String ipAddress) { return IPPATTERN.matcher(ipAddress).matches(); } } diff --git a/Essentials/src/com/earth2me/essentials/utils/LocationUtil.java b/Essentials/src/com/earth2me/essentials/utils/LocationUtil.java index df04d8b3c..1d0111006 100644 --- a/Essentials/src/com/earth2me/essentials/utils/LocationUtil.java +++ b/Essentials/src/com/earth2me/essentials/utils/LocationUtil.java @@ -10,30 +10,33 @@ import org.bukkit.block.Block; import org.bukkit.entity.LivingEntity; import org.bukkit.inventory.ItemStack; -import java.util.*; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Set; import static com.earth2me.essentials.I18n.tl; - -public class LocationUtil { +public final class LocationUtil { + public static final int RADIUS = 3; + public static final Vector3D[] VOLUME; // Water types used for TRANSPARENT_MATERIALS and is-water-safe config option private static final Set WATER_TYPES = EnumUtil.getAllMatching(Material.class, - "FLOWING_WATER", "WATER"); - + "FLOWING_WATER", "WATER"); // Types checked by isBlockDamaging private static final Set DAMAGING_TYPES = EnumUtil.getAllMatching(Material.class, - "CACTUS", "CAMPFIRE", "FIRE", "MAGMA_BLOCK", "SOUL_CAMPFIRE", "SOUL_FIRE", "SWEET_BERRY_BUSH", "WITHER_ROSE"); + "CACTUS", "CAMPFIRE", "FIRE", "MAGMA_BLOCK", "SOUL_CAMPFIRE", "SOUL_FIRE", "SWEET_BERRY_BUSH", "WITHER_ROSE"); private static final Set LAVA_TYPES = EnumUtil.getAllMatching(Material.class, - "FLOWING_LAVA", "LAVA", "STATIONARY_LAVA"); + "FLOWING_LAVA", "LAVA", "STATIONARY_LAVA"); private static final Material PORTAL = EnumUtil.getMaterial("NETHER_PORTAL", "PORTAL"); - // The player can stand inside these materials private static final Set HOLLOW_MATERIALS = new HashSet<>(); private static final Set TRANSPARENT_MATERIALS = new HashSet<>(); static { // Materials from Material.isTransparent() - for (Material mat : Material.values()) { + for (final Material mat : Material.values()) { if (mat.isTransparent()) { HOLLOW_MATERIALS.add(mat); } @@ -43,36 +46,8 @@ public class LocationUtil { TRANSPARENT_MATERIALS.addAll(WATER_TYPES); } - public static void setIsWaterSafe(boolean isWaterSafe) { - if (isWaterSafe) { - HOLLOW_MATERIALS.addAll(WATER_TYPES); - } else { - HOLLOW_MATERIALS.removeAll(WATER_TYPES); - } - } - - public static final int RADIUS = 3; - public static final Vector3D[] VOLUME; - - public static ItemStack convertBlockToItem(final Block block) { - return new ItemStack(block.getType(), 1); - } - - - public static class Vector3D { - public int x; - public int y; - public int z; - - Vector3D(int x, int y, int z) { - this.x = x; - this.y = y; - this.z = z; - } - } - static { - List pos = new ArrayList<>(); + final List pos = new ArrayList<>(); for (int x = -RADIUS; x <= RADIUS; x++) { for (int y = -RADIUS; y <= RADIUS; y++) { for (int z = -RADIUS; z <= RADIUS; z++) { @@ -80,15 +55,31 @@ public class LocationUtil { } } } - pos.sort(Comparator.comparingInt(a -> (a.x * a.x + a.y * a.y + a.z * a.z))); + pos.sort(Comparator.comparingInt(a -> a.x * a.x + a.y * a.y + a.z * a.z)); VOLUME = pos.toArray(new Vector3D[0]); } + private LocationUtil() { + } + + public static void setIsWaterSafe(final boolean isWaterSafe) { + if (isWaterSafe) { + HOLLOW_MATERIALS.addAll(WATER_TYPES); + } else { + HOLLOW_MATERIALS.removeAll(WATER_TYPES); + } + } + + public static ItemStack convertBlockToItem(final Block block) { + return new ItemStack(block.getType(), 1); + } + public static Location getTarget(final LivingEntity entity) throws Exception { Block block = null; try { block = entity.getTargetBlock(TRANSPARENT_MATERIALS, 300); - } catch (NoSuchMethodError ignored) {} // failing now :( + } catch (final NoSuchMethodError ignored) { + } // failing now :( if (block == null) { throw new Exception("Not targeting a block"); } @@ -168,9 +159,9 @@ public class LocationUtil { // Not needed if using getSafeDestination(loc) public static Location getRoundedDestination(final Location loc) { final World world = loc.getWorld(); - int x = loc.getBlockX(); - int y = (int) Math.round(loc.getY()); - int z = loc.getBlockZ(); + final int x = loc.getBlockX(); + final int y = (int) Math.round(loc.getY()); + final int z = loc.getBlockZ(); return new Location(world, x + 0.5, y, z + 0.5, loc.getYaw(), loc.getPitch()); } @@ -256,7 +247,7 @@ public class LocationUtil { return new Location(world, x + 0.5, y, z + 0.5, loc.getYaw(), loc.getPitch()); } - public static boolean shouldFly(Location loc) { + public static boolean shouldFly(final Location loc) { final World world = loc.getWorld(); final int x = loc.getBlockX(); int y = (int) Math.round(loc.getY()); @@ -272,4 +263,16 @@ public class LocationUtil { return y < 0; } + + public static class Vector3D { + public final int x; + public final int y; + public final int z; + + Vector3D(final int x, final int y, final int z) { + this.x = x; + this.y = y; + this.z = z; + } + } } diff --git a/Essentials/src/com/earth2me/essentials/utils/MaterialUtil.java b/Essentials/src/com/earth2me/essentials/utils/MaterialUtil.java index 8cdc5d667..79fbc4f55 100644 --- a/Essentials/src/com/earth2me/essentials/utils/MaterialUtil.java +++ b/Essentials/src/com/earth2me/essentials/utils/MaterialUtil.java @@ -10,9 +10,9 @@ import java.lang.reflect.Method; import java.util.EnumSet; import java.util.Set; -public class MaterialUtil { - +public final class MaterialUtil { + public static final Material SPAWNER = EnumUtil.getMaterial("MOB_SPAWNER", "SPAWNER"); private static final Set BEDS; private static final Set BANNERS; private static final Set FIREWORKS; @@ -25,8 +25,6 @@ public class MaterialUtil { private static final Set SIGN_POSTS; private static final Set WALL_SIGNS; - public static final Material SPAWNER = EnumUtil.getMaterial("MOB_SPAWNER", "SPAWNER"); - static { BEDS = EnumUtil.getAllMatching(Material.class, "BED", "BED_BLOCK", "WHITE_BED", "ORANGE_BED", @@ -36,7 +34,7 @@ public class MaterialUtil { BANNERS = EnumUtil.getAllMatching(Material.class, "BANNER", "WHITE_BANNER", "ORANGE_BANNER", "MAGENTA_BANNER", "LIGHT_BLUE_BANNER", "YELLOW_BANNER", "LIME_BANNER", - "PINK_BANNER","GRAY_BANNER","LIGHT_GRAY_BANNER", "CYAN_BANNER", "PURPLE_BANNER", + "PINK_BANNER", "GRAY_BANNER", "LIGHT_GRAY_BANNER", "CYAN_BANNER", "PURPLE_BANNER", "BLUE_BANNER", "BROWN_BANNER", "GREEN_BANNER", "RED_BANNER", "BLACK_BANNER", "SHIELD"); FIREWORKS = EnumUtil.getAllMatching(Material.class, "FIREWORK", "FIREWORK_ROCKET", @@ -45,7 +43,7 @@ public class MaterialUtil { LEATHER_ARMOR = EnumUtil.getAllMatching(Material.class, "LEATHER_HELMET", "LEATHER_CHESTPLATE", "LEATHER_LEGGINGS", "LEATHER_BOOTS"); - LEGACY_SKULLS = EnumUtil.getAllMatching(Material.class,"SKULL", "SKULL_ITEM"); + LEGACY_SKULLS = EnumUtil.getAllMatching(Material.class, "SKULL", "SKULL_ITEM"); MOB_HEADS = EnumUtil.getAllMatching(Material.class, "SKELETON_SKULL", "SKELETON_WALL_SKULL", "WITHER_SKELETON_SKULL", "WITHER_SKELETON_WALL_SKULL", @@ -70,23 +68,26 @@ public class MaterialUtil { "CRIMSON_WALL_SIGN", "WARPED_WALL_SIGN"); } - public static boolean isBed(Material material) { + private MaterialUtil() { + } + + public static boolean isBed(final Material material) { return BEDS.contains(material); } - public static boolean isBanner(Material material) { + public static boolean isBanner(final Material material) { return BANNERS.contains(material); } - public static boolean isFirework(Material material) { + public static boolean isFirework(final Material material) { return FIREWORKS.contains(material); } - public static boolean isLeatherArmor(Material material) { + public static boolean isLeatherArmor(final Material material) { return LEATHER_ARMOR.contains(material); } - public static boolean isMobHead(Material material, int durability) { + public static boolean isMobHead(final Material material, final int durability) { if (MOB_HEADS.contains(material)) { return true; } @@ -94,7 +95,7 @@ public class MaterialUtil { return LEGACY_SKULLS.contains(material) && (durability != 3); } - public static boolean isPlayerHead(Material material, int durability) { + public static boolean isPlayerHead(final Material material, final int durability) { if (PLAYER_HEADS.contains(material)) { return true; } @@ -102,47 +103,49 @@ public class MaterialUtil { return LEGACY_SKULLS.contains(material) && durability == 3; } - public static boolean isPotion(Material material) { + public static boolean isPotion(final Material material) { return POTIONS.contains(material); } - public static boolean isSignPost(Material material) { + public static boolean isSignPost(final Material material) { return SIGN_POSTS.contains(material); } - public static boolean isWallSign(Material material) { + public static boolean isWallSign(final Material material) { return WALL_SIGNS.contains(material); } - public static boolean isSign(Material material) { + public static boolean isSign(final Material material) { return isSignPost(material) || isWallSign(material); } - public static boolean isSkull(Material material) { + public static boolean isSkull(final Material material) { return isPlayerHead(material, -1) || isMobHead(material, -1); } - public static Material convertFromLegacy(int id, byte damage) { - for (Material material : EnumSet.allOf(Material.class)) { + public static Material convertFromLegacy(final int id, final byte damage) { + for (final Material material : EnumSet.allOf(Material.class)) { if (material.getId() == id) { try { return Bukkit.getUnsafe().fromLegacy(new MaterialData(material, damage)); - } catch (NoSuchMethodError error) { + } catch (final NoSuchMethodError error) { break; } } } try { - Method getMaterialFromId = Material.class.getDeclaredMethod("getMaterial", int.class); + //noinspection JavaReflectionMemberAccess + final Method getMaterialFromId = Material.class.getDeclaredMethod("getMaterial", int.class); return (Material) getMaterialFromId.invoke(null, id); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {} + } catch (final NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { + } return null; } - public static DyeColor getColorOf(Material material) { - for (DyeColor color : DyeColor.values()) { + public static DyeColor getColorOf(final Material material) { + for (final DyeColor color : DyeColor.values()) { if (material.toString().contains(color.name())) { return color; } diff --git a/Essentials/src/com/earth2me/essentials/utils/NumberUtil.java b/Essentials/src/com/earth2me/essentials/utils/NumberUtil.java index 3bbed3bb8..acfd29efc 100644 --- a/Essentials/src/com/earth2me/essentials/utils/NumberUtil.java +++ b/Essentials/src/com/earth2me/essentials/utils/NumberUtil.java @@ -11,11 +11,11 @@ import java.util.Locale; import static com.earth2me.essentials.I18n.tl; -public class NumberUtil { +public final class NumberUtil { private static final DecimalFormat twoDPlaces = new DecimalFormat("#,###.##"); private static final DecimalFormat currencyFormat = new DecimalFormat("#0.00", DecimalFormatSymbols.getInstance(Locale.US)); - + // This field is likely to be modified in com.earth2me.essentials.Settings when loading currency format. // This ensures that we can supply a constant formatting. private static NumberFormat PRETTY_FORMAT = NumberFormat.getInstance(Locale.US); @@ -30,8 +30,11 @@ public class NumberUtil { PRETTY_FORMAT.setMaximumFractionDigits(2); } + private NumberUtil() { + } + // this method should only be called by Essentials - public static void internalSetPrettyFormat(NumberFormat prettyFormat) { + public static void internalSetPrettyFormat(final NumberFormat prettyFormat) { PRETTY_FORMAT = prettyFormat; } @@ -54,7 +57,7 @@ public class NumberUtil { return str; } - public static String formatAsPrettyCurrency(BigDecimal value) { + public static String formatAsPrettyCurrency(final BigDecimal value) { String str = PRETTY_FORMAT.format(value); if (str.endsWith(".00")) { str = str.substring(0, str.length() - 3); @@ -89,8 +92,8 @@ public class NumberUtil { } public static String sanitizeCurrencyString(final String input, final IEssentials ess) { - String symbol = ess.getSettings().getCurrencySymbol(); - boolean suffix = ess.getSettings().isCurrencySymbolSuffixed(); + final String symbol = ess.getSettings().getCurrencySymbol(); + final boolean suffix = ess.getSettings().isCurrencySymbolSuffixed(); if (input.contains(symbol)) { return suffix ? input.substring(0, input.indexOf(symbol)) : input.substring(symbol.length()); } @@ -100,7 +103,7 @@ public class NumberUtil { public static boolean isInt(final String sInt) { try { Integer.parseInt(sInt); - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { return false; } return true; diff --git a/Essentials/src/com/earth2me/essentials/utils/StringUtil.java b/Essentials/src/com/earth2me/essentials/utils/StringUtil.java index 9db7cf055..e4d03bfb1 100644 --- a/Essentials/src/com/earth2me/essentials/utils/StringUtil.java +++ b/Essentials/src/com/earth2me/essentials/utils/StringUtil.java @@ -5,12 +5,14 @@ import java.util.Locale; import java.util.UUID; import java.util.regex.Pattern; - -public class StringUtil { +public final class StringUtil { private static final Pattern INVALIDFILECHARS = Pattern.compile("[^a-z0-9-]"); private static final Pattern STRICTINVALIDCHARS = Pattern.compile("[^a-z0-9]"); private static final Pattern INVALIDCHARS = Pattern.compile("[^\t\n\r\u0020-\u007E\u0085\u00A0-\uD7FF\uE000-\uFFFC]"); + private StringUtil() { + } + //Used to clean file names before saving to disk public static String sanitizeFileName(final String name) { return INVALIDFILECHARS.matcher(name.toLowerCase(Locale.ENGLISH)).replaceAll("_"); @@ -26,13 +28,13 @@ public class StringUtil { return INVALIDCHARS.matcher(string).replaceAll(""); } - public static String joinList(Object... list) { + public static String joinList(final Object... list) { return joinList(", ", list); } - public static String joinList(String seperator, Object... list) { - StringBuilder buf = new StringBuilder(); - for (Object each : list) { + public static String joinList(final String seperator, final Object... list) { + final StringBuilder buf = new StringBuilder(); + for (final Object each : list) { if (buf.length() > 0) { buf.append(seperator); } @@ -42,7 +44,7 @@ public class StringUtil { } else { try { buf.append(each.toString()); - } catch (Exception e) { + } catch (final Exception e) { buf.append(each.toString()); } } @@ -50,9 +52,9 @@ public class StringUtil { return buf.toString(); } - public static String joinListSkip(String seperator, String skip, Object... list) { - StringBuilder buf = new StringBuilder(); - for (Object each : list) { + public static String joinListSkip(final String seperator, final String skip, final Object... list) { + final StringBuilder buf = new StringBuilder(); + for (final Object each : list) { if (each.toString().equalsIgnoreCase(skip)) { continue; } @@ -66,7 +68,7 @@ public class StringUtil { } else { try { buf.append(each.toString()); - } catch (Exception e) { + } catch (final Exception e) { buf.append(each.toString()); } } @@ -74,14 +76,12 @@ public class StringUtil { return buf.toString(); } - public static UUID toUUID(String input) { + public static UUID toUUID(final String input) { try { return UUID.fromString(input); - } catch (IllegalArgumentException ignored) {} + } catch (final IllegalArgumentException ignored) { + } return null; } - - private StringUtil() { - } } diff --git a/Essentials/src/com/earth2me/essentials/utils/VersionUtil.java b/Essentials/src/com/earth2me/essentials/utils/VersionUtil.java index 6bf09440d..5bb44d4d3 100644 --- a/Essentials/src/com/earth2me/essentials/utils/VersionUtil.java +++ b/Essentials/src/com/earth2me/essentials/utils/VersionUtil.java @@ -9,8 +9,9 @@ import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; -public class VersionUtil { +public final class VersionUtil { + public static final BukkitVersion v1_14_R01 = BukkitVersion.fromString("1.14-R0.1-SNAPSHOT"); public static final BukkitVersion v1_8_8_R01 = BukkitVersion.fromString("1.8.8-R0.1-SNAPSHOT"); public static final BukkitVersion v1_9_R01 = BukkitVersion.fromString("1.9-R0.1-SNAPSHOT"); public static final BukkitVersion v1_9_4_R01 = BukkitVersion.fromString("1.9.4-R0.1-SNAPSHOT"); @@ -22,7 +23,6 @@ public class VersionUtil { public static final BukkitVersion v1_12_2_R01 = BukkitVersion.fromString("1.12.2-R0.1-SNAPSHOT"); public static final BukkitVersion v1_13_0_R01 = BukkitVersion.fromString("1.13.0-R0.1-SNAPSHOT"); public static final BukkitVersion v1_13_2_R01 = BukkitVersion.fromString("1.13.2-R0.1-SNAPSHOT"); - public static final BukkitVersion v1_14_R01 = BukkitVersion.fromString("1.14-R0.1-SNAPSHOT"); public static final BukkitVersion v1_14_4_R01 = BukkitVersion.fromString("1.14.4-R0.1-SNAPSHOT"); public static final BukkitVersion v1_15_R01 = BukkitVersion.fromString("1.15-R0.1-SNAPSHOT"); public static final BukkitVersion v1_15_2_R01 = BukkitVersion.fromString("1.15.2-R0.1-SNAPSHOT"); @@ -34,6 +34,9 @@ public class VersionUtil { private static BukkitVersion serverVersion = null; + private VersionUtil() { + } + public static BukkitVersion getServerBukkitVersion() { if (serverVersion == null) { serverVersion = BukkitVersion.fromString(Bukkit.getServer().getBukkitVersion()); @@ -45,7 +48,7 @@ public class VersionUtil { return supportedVersions.contains(getServerBukkitVersion()); } - public static class BukkitVersion implements Comparable { + public static final class BukkitVersion implements Comparable { private static final Pattern VERSION_PATTERN = Pattern.compile("^(\\d+)\\.(\\d+)\\.?([0-9]*)?(?:-pre(\\d))?(?:-?R?([\\d.]+))?(?:-SNAPSHOT)?"); private final int major; @@ -54,7 +57,15 @@ public class VersionUtil { private final int patch; private final double revision; - public static BukkitVersion fromString(String string) { + private BukkitVersion(final int major, final int minor, final int patch, final double revision, final int prerelease) { + this.major = major; + this.minor = minor; + this.patch = patch; + this.revision = revision; + this.prerelease = prerelease; + } + + public static BukkitVersion fromString(final String string) { Preconditions.checkNotNull(string, "string cannot be null."); Matcher matcher = VERSION_PATTERN.matcher(string); if (!matcher.matches()) { @@ -68,7 +79,7 @@ public class VersionUtil { return from(matcher.group(1), matcher.group(2), matcher.group(3), matcher.groupCount() < 5 ? "" : matcher.group(5), matcher.group(4)); } - private static BukkitVersion from(String major, String minor, String patch, String revision, String prerelease) { + private static BukkitVersion from(final String major, final String minor, String patch, String revision, String prerelease) { if (patch == null || patch.isEmpty()) patch = "0"; if (revision == null || revision.isEmpty()) revision = "0"; if (prerelease == null || prerelease.isEmpty()) prerelease = "-1"; @@ -79,27 +90,19 @@ public class VersionUtil { Integer.parseInt(prerelease)); } - private BukkitVersion(int major, int minor, int patch, double revision, int prerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.revision = revision; - this.prerelease = prerelease; - } - - public boolean isHigherThan(BukkitVersion o) { + public boolean isHigherThan(final BukkitVersion o) { return compareTo(o) > 0; } - public boolean isHigherThanOrEqualTo(BukkitVersion o) { + public boolean isHigherThanOrEqualTo(final BukkitVersion o) { return compareTo(o) >= 0; } - public boolean isLowerThan(BukkitVersion o) { + public boolean isLowerThan(final BukkitVersion o) { return compareTo(o) < 0; } - public boolean isLowerThanOrEqualTo(BukkitVersion o) { + public boolean isLowerThanOrEqualTo(final BukkitVersion o) { return compareTo(o) <= 0; } @@ -124,14 +127,14 @@ public class VersionUtil { } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } - BukkitVersion that = (BukkitVersion) o; + final BukkitVersion that = (BukkitVersion) o; return major == that.major && minor == that.minor && patch == that.patch && @@ -146,7 +149,7 @@ public class VersionUtil { @Override public String toString() { - StringBuilder sb = new StringBuilder(major + "." + minor); + final StringBuilder sb = new StringBuilder(major + "." + minor); if (patch != 0) { sb.append(".").append(patch); } @@ -157,7 +160,7 @@ public class VersionUtil { } @Override - public int compareTo(BukkitVersion o) { + public int compareTo(final BukkitVersion o) { if (major < o.major) { return -1; } else if (major > o.major) { diff --git a/Essentials/src/net/ess3/api/Economy.java b/Essentials/src/net/ess3/api/Economy.java index f12572e10..c18a3c360 100644 --- a/Essentials/src/net/ess3/api/Economy.java +++ b/Essentials/src/net/ess3/api/Economy.java @@ -1,6 +1,5 @@ package net.ess3.api; - public class Economy extends com.earth2me.essentials.api.Economy { } diff --git a/Essentials/src/net/ess3/api/II18n.java b/Essentials/src/net/ess3/api/II18n.java index 655746acf..423b884fc 100644 --- a/Essentials/src/net/ess3/api/II18n.java +++ b/Essentials/src/net/ess3/api/II18n.java @@ -1,6 +1,5 @@ package net.ess3.api; - public interface II18n extends com.earth2me.essentials.api.II18n { } diff --git a/Essentials/src/net/ess3/api/IItemDb.java b/Essentials/src/net/ess3/api/IItemDb.java index 23efa958d..da4f6e1bc 100644 --- a/Essentials/src/net/ess3/api/IItemDb.java +++ b/Essentials/src/net/ess3/api/IItemDb.java @@ -1,6 +1,5 @@ package net.ess3.api; - import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; @@ -13,8 +12,8 @@ public interface IItemDb extends com.earth2me.essentials.api.IItemDb { /** * Add an item resolver that is called before looking up the item in the item database. * - * @param plugin The owning plugin - * @param name The name of the resolver + * @param plugin The owning plugin + * @param name The name of the resolver * @param resolver The resolver accepting a String and returning an ItemStack, or null if * none was found * @throws Exception If a resolver with a conflicting name is found @@ -25,7 +24,7 @@ public interface IItemDb extends com.earth2me.essentials.api.IItemDb { * Remove an item resolver from the given plugin with the given name. * * @param plugin The owning plugin - * @param name The name of the resolver + * @param name The name of the resolver * @throws Exception If no matching resolver was found */ void unregisterResolver(Plugin plugin, String name) throws Exception; @@ -34,7 +33,7 @@ public interface IItemDb extends com.earth2me.essentials.api.IItemDb { * Check whether a resolver with a given name from a given plugin has been registered. * * @param plugin The owning plugin - * @param name The name of the resolver + * @param name The name of the resolver * @return Whether the resolver could be found */ boolean isResolverPresent(Plugin plugin, String name); @@ -58,7 +57,7 @@ public interface IItemDb extends com.earth2me.essentials.api.IItemDb { * Get the resolver function with the given name from the given plugin. * * @param plugin The owning plugin - * @param name The name of the resolver + * @param name The name of the resolver * @return The resolver function, or null if not found */ ItemResolver getResolver(Plugin plugin, String name); @@ -66,7 +65,7 @@ public interface IItemDb extends com.earth2me.essentials.api.IItemDb { /** * Create a stack from the given name with the maximum stack size for that material. * - * @param name Item name to look up in the database + * @param name Item name to look up in the database * @param useResolvers Whether to call other plugins' resolver functions before looking the * item up in the database * @return The requested item stack with the maximum stack size @@ -118,7 +117,7 @@ public interface IItemDb extends com.earth2me.essentials.api.IItemDb { * @param stack The stack to serialize * @return The name of the item if a suitable name was found, else null */ - default String serialize(ItemStack stack) { + default String serialize(final ItemStack stack) { return null; } } diff --git a/Essentials/src/net/ess3/api/IJails.java b/Essentials/src/net/ess3/api/IJails.java index e6447ee89..18c7342d9 100644 --- a/Essentials/src/net/ess3/api/IJails.java +++ b/Essentials/src/net/ess3/api/IJails.java @@ -1,6 +1,5 @@ package net.ess3.api; - public interface IJails extends com.earth2me.essentials.api.IJails { } diff --git a/Essentials/src/net/ess3/api/IReload.java b/Essentials/src/net/ess3/api/IReload.java index 859528037..1d6ae518e 100644 --- a/Essentials/src/net/ess3/api/IReload.java +++ b/Essentials/src/net/ess3/api/IReload.java @@ -1,6 +1,5 @@ package net.ess3.api; - public interface IReload extends com.earth2me.essentials.api.IReload { } diff --git a/Essentials/src/net/ess3/api/ISettings.java b/Essentials/src/net/ess3/api/ISettings.java index 2a34978bd..d1a9b9743 100644 --- a/Essentials/src/net/ess3/api/ISettings.java +++ b/Essentials/src/net/ess3/api/ISettings.java @@ -1,5 +1,4 @@ package net.ess3.api; - public interface ISettings extends com.earth2me.essentials.ISettings { } diff --git a/Essentials/src/net/ess3/api/ITeleport.java b/Essentials/src/net/ess3/api/ITeleport.java index c09852170..3ab92c09d 100644 --- a/Essentials/src/net/ess3/api/ITeleport.java +++ b/Essentials/src/net/ess3/api/ITeleport.java @@ -1,6 +1,5 @@ package net.ess3.api; - /** * @deprecated This API is not asynchronous. Use {@link com.earth2me.essentials.api.IAsyncTeleport IAsyncTeleport} */ diff --git a/Essentials/src/net/ess3/api/IUser.java b/Essentials/src/net/ess3/api/IUser.java index aae8900a7..1816a2ef3 100644 --- a/Essentials/src/net/ess3/api/IUser.java +++ b/Essentials/src/net/ess3/api/IUser.java @@ -1,6 +1,5 @@ package net.ess3.api; - public interface IUser extends com.earth2me.essentials.IUser { } diff --git a/Essentials/src/net/ess3/api/IWarps.java b/Essentials/src/net/ess3/api/IWarps.java index 4a9b979e7..f3a5d8656 100644 --- a/Essentials/src/net/ess3/api/IWarps.java +++ b/Essentials/src/net/ess3/api/IWarps.java @@ -1,6 +1,5 @@ package net.ess3.api; - public interface IWarps extends com.earth2me.essentials.api.IWarps { } diff --git a/Essentials/src/net/ess3/api/InvalidNameException.java b/Essentials/src/net/ess3/api/InvalidNameException.java index 8c78dcca9..0b108b7ae 100644 --- a/Essentials/src/net/ess3/api/InvalidNameException.java +++ b/Essentials/src/net/ess3/api/InvalidNameException.java @@ -1,6 +1,5 @@ package net.ess3.api; - public class InvalidNameException extends Exception { /** * NOTE: This is not implemented yet, just here for future 3.x api support Allow serialization of the @@ -8,7 +7,7 @@ public class InvalidNameException extends Exception { */ private static final long serialVersionUID = 1485321420293663139L; - public InvalidNameException(Throwable thrwbl) { + public InvalidNameException(final Throwable thrwbl) { super(thrwbl); } } diff --git a/Essentials/src/net/ess3/api/InvalidWorldException.java b/Essentials/src/net/ess3/api/InvalidWorldException.java index f43b6e7c1..c641184c8 100644 --- a/Essentials/src/net/ess3/api/InvalidWorldException.java +++ b/Essentials/src/net/ess3/api/InvalidWorldException.java @@ -2,7 +2,6 @@ package net.ess3.api; import static com.earth2me.essentials.I18n.tl; - public class InvalidWorldException extends Exception { private final String world; diff --git a/Essentials/src/net/ess3/api/MaxMoneyException.java b/Essentials/src/net/ess3/api/MaxMoneyException.java index 3e934cedb..b7679c270 100644 --- a/Essentials/src/net/ess3/api/MaxMoneyException.java +++ b/Essentials/src/net/ess3/api/MaxMoneyException.java @@ -2,7 +2,6 @@ package net.ess3.api; import static com.earth2me.essentials.I18n.tl; - public class MaxMoneyException extends Exception { public MaxMoneyException() { super(tl("maxMoney")); diff --git a/Essentials/src/net/ess3/api/NoLoanPermittedException.java b/Essentials/src/net/ess3/api/NoLoanPermittedException.java index 088265cf6..fa058e258 100644 --- a/Essentials/src/net/ess3/api/NoLoanPermittedException.java +++ b/Essentials/src/net/ess3/api/NoLoanPermittedException.java @@ -2,7 +2,6 @@ package net.ess3.api; import static com.earth2me.essentials.I18n.tl; - public class NoLoanPermittedException extends Exception { public NoLoanPermittedException() { super(tl("negativeBalanceError")); diff --git a/Essentials/src/net/ess3/api/PluginKey.java b/Essentials/src/net/ess3/api/PluginKey.java index 353485a2a..90ee02490 100644 --- a/Essentials/src/net/ess3/api/PluginKey.java +++ b/Essentials/src/net/ess3/api/PluginKey.java @@ -9,11 +9,19 @@ public final class PluginKey { private final Plugin plugin; private final String key; - private PluginKey(Plugin plugin, String key) { + private PluginKey(final Plugin plugin, final String key) { this.plugin = plugin; this.key = key; } + public static PluginKey random(final Plugin plugin) { + return new PluginKey(plugin, UUID.randomUUID().toString()); + } + + public static PluginKey fromKey(final Plugin plugin, final String key) { + return new PluginKey(plugin, key); + } + public Plugin getPlugin() { return plugin; } @@ -33,19 +41,11 @@ public final class PluginKey { } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { if (!(o instanceof PluginKey || o.getClass().getName().equals("org.bukkit.NamespacedKey"))) { return false; } return this == o || this.toString().equals(o.toString()); } - public static PluginKey random(Plugin plugin) { - return new PluginKey(plugin, UUID.randomUUID().toString()); - } - - public static PluginKey fromKey(Plugin plugin, String key) { - return new PluginKey(plugin, key); - } - } diff --git a/Essentials/src/net/ess3/api/UserDoesNotExistException.java b/Essentials/src/net/ess3/api/UserDoesNotExistException.java index 2c3f0daa9..7b5f109fe 100644 --- a/Essentials/src/net/ess3/api/UserDoesNotExistException.java +++ b/Essentials/src/net/ess3/api/UserDoesNotExistException.java @@ -2,9 +2,8 @@ package net.ess3.api; import static com.earth2me.essentials.I18n.tl; - public class UserDoesNotExistException extends Exception { - public UserDoesNotExistException(String name) { + public UserDoesNotExistException(final String name) { super(tl("userDoesNotExist", name)); } } diff --git a/Essentials/src/net/ess3/api/events/AfkStatusChangeEvent.java b/Essentials/src/net/ess3/api/events/AfkStatusChangeEvent.java index c5f4b9db5..5e51fa696 100644 --- a/Essentials/src/net/ess3/api/events/AfkStatusChangeEvent.java +++ b/Essentials/src/net/ess3/api/events/AfkStatusChangeEvent.java @@ -2,16 +2,15 @@ package net.ess3.api.events; import net.ess3.api.IUser; - public class AfkStatusChangeEvent extends StatusChangeEvent { - private Cause cause; + private final Cause cause; @Deprecated - public AfkStatusChangeEvent(IUser affected, boolean value) { + public AfkStatusChangeEvent(final IUser affected, final boolean value) { this(affected, value, Cause.UNKNOWN); } - public AfkStatusChangeEvent(IUser affected, boolean value, Cause cause) { + public AfkStatusChangeEvent(final IUser affected, final boolean value, final Cause cause) { super(affected, affected, value); this.cause = cause; } diff --git a/Essentials/src/net/ess3/api/events/FlyStatusChangeEvent.java b/Essentials/src/net/ess3/api/events/FlyStatusChangeEvent.java index ece3c19b3..566481b9f 100644 --- a/Essentials/src/net/ess3/api/events/FlyStatusChangeEvent.java +++ b/Essentials/src/net/ess3/api/events/FlyStatusChangeEvent.java @@ -3,7 +3,7 @@ package net.ess3.api.events; import net.ess3.api.IUser; public class FlyStatusChangeEvent extends StatusChangeEvent { - public FlyStatusChangeEvent(IUser affected, IUser controller, boolean value) { + public FlyStatusChangeEvent(final IUser affected, final IUser controller, final boolean value) { super(affected, controller, value); } } diff --git a/Essentials/src/net/ess3/api/events/GodStatusChangeEvent.java b/Essentials/src/net/ess3/api/events/GodStatusChangeEvent.java index 61b87133a..50b3fe501 100644 --- a/Essentials/src/net/ess3/api/events/GodStatusChangeEvent.java +++ b/Essentials/src/net/ess3/api/events/GodStatusChangeEvent.java @@ -2,15 +2,14 @@ package net.ess3.api.events; import net.ess3.api.IUser; - /** * Fired when a user's god status is toggled. - * + *

    * Note that in older versions (original Essentials and early EssentialsX), the #getAffected * and #getController methods are inverted. */ public class GodStatusChangeEvent extends StatusChangeEvent { - public GodStatusChangeEvent(IUser affected, IUser controller, boolean value) { + public GodStatusChangeEvent(final IUser affected, final IUser controller, final boolean value) { super(affected, controller, value); } } diff --git a/Essentials/src/net/ess3/api/events/IgnoreStatusChangeEvent.java b/Essentials/src/net/ess3/api/events/IgnoreStatusChangeEvent.java index b5af0da2e..435dc57c8 100644 --- a/Essentials/src/net/ess3/api/events/IgnoreStatusChangeEvent.java +++ b/Essentials/src/net/ess3/api/events/IgnoreStatusChangeEvent.java @@ -6,7 +6,7 @@ import net.ess3.api.IUser; * This event is currently unused, and is retained for ABI compatibility and potential future implementation. */ public class IgnoreStatusChangeEvent extends StatusChangeEvent { - public IgnoreStatusChangeEvent(IUser affected, IUser controller, boolean value) { + public IgnoreStatusChangeEvent(final IUser affected, final IUser controller, final boolean value) { super(affected, controller, value); } } diff --git a/Essentials/src/net/ess3/api/events/JailStatusChangeEvent.java b/Essentials/src/net/ess3/api/events/JailStatusChangeEvent.java index 03eda5932..fface4b72 100644 --- a/Essentials/src/net/ess3/api/events/JailStatusChangeEvent.java +++ b/Essentials/src/net/ess3/api/events/JailStatusChangeEvent.java @@ -2,9 +2,8 @@ package net.ess3.api.events; import net.ess3.api.IUser; - public class JailStatusChangeEvent extends StatusChangeEvent { - public JailStatusChangeEvent(IUser affected, IUser controller, boolean value) { + public JailStatusChangeEvent(final IUser affected, final IUser controller, final boolean value) { super(affected, controller, value); } -} \ No newline at end of file +} diff --git a/Essentials/src/net/ess3/api/events/KitClaimEvent.java b/Essentials/src/net/ess3/api/events/KitClaimEvent.java index 35ba3a7c8..5d36d4eb0 100644 --- a/Essentials/src/net/ess3/api/events/KitClaimEvent.java +++ b/Essentials/src/net/ess3/api/events/KitClaimEvent.java @@ -1,14 +1,12 @@ package net.ess3.api.events; +import com.earth2me.essentials.Kit; +import net.ess3.api.IUser; import org.bukkit.Bukkit; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; -import com.earth2me.essentials.Kit; - -import net.ess3.api.IUser; - /** * Called when the player is given a kit */ @@ -16,16 +14,20 @@ public class KitClaimEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); - private Kit kit; - private IUser user; + private final Kit kit; + private final IUser user; private boolean cancelled; - public KitClaimEvent(IUser user, Kit kit) { + public KitClaimEvent(final IUser user, final Kit kit) { super(!Bukkit.getServer().isPrimaryThread()); this.user = user; this.kit = kit; } + public static HandlerList getHandlerList() { + return handlers; + } + public IUser getUser() { return user; } @@ -40,7 +42,7 @@ public class KitClaimEvent extends Event implements Cancellable { } @Override - public void setCancelled(boolean cancel) { + public void setCancelled(final boolean cancel) { cancelled = cancel; } @@ -48,8 +50,4 @@ public class KitClaimEvent extends Event implements Cancellable { public HandlerList getHandlers() { return handlers; } - - public static HandlerList getHandlerList() { - return handlers; - } } diff --git a/Essentials/src/net/ess3/api/events/LocalChatSpyEvent.java b/Essentials/src/net/ess3/api/events/LocalChatSpyEvent.java index ab3cf431a..3a1409f40 100644 --- a/Essentials/src/net/ess3/api/events/LocalChatSpyEvent.java +++ b/Essentials/src/net/ess3/api/events/LocalChatSpyEvent.java @@ -10,14 +10,13 @@ import java.util.Set; import static com.earth2me.essentials.I18n.tl; - public class LocalChatSpyEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); + private final Player player; + private final Set recipients; private boolean cancelled = false; private String message; private String format; - private Player player; - private final Set recipients; public LocalChatSpyEvent(final boolean async, final Player who, final String format, final String message, final Set players) { super(async); @@ -27,6 +26,10 @@ public class LocalChatSpyEvent extends Event implements Cancellable { player = who; } + public static HandlerList getHandlerList() { + return handlers; + } + /** * Gets the message that the player is attempting to send. This message will be used with {@link #getFormat()}. * @@ -41,7 +44,7 @@ public class LocalChatSpyEvent extends Event implements Cancellable { * * @param message New message that the player will send */ - public void setMessage(String message) { + public void setMessage(final String message) { this.message = message; } @@ -60,7 +63,6 @@ public class LocalChatSpyEvent extends Event implements Cancellable { * parameter is the {@link Player#getDisplayName()} and the second parameter is {@link #getMessage()} * * @param format {@link String#format(String, Object...)} compatible format string - * * @throws IllegalFormatException if the underlying API throws the exception * @throws NullPointerException if format is null * @see String#format(String, Object...) @@ -69,7 +71,7 @@ public class LocalChatSpyEvent extends Event implements Cancellable { // Oh for a better way to do this! try { String.format(format, player, message); - } catch (RuntimeException ex) { + } catch (final RuntimeException ex) { ex.fillInStackTrace(); throw ex; } @@ -101,7 +103,7 @@ public class LocalChatSpyEvent extends Event implements Cancellable { } @Override - public void setCancelled(boolean cancel) { + public void setCancelled(final boolean cancel) { this.cancelled = cancel; } @@ -109,8 +111,4 @@ public class LocalChatSpyEvent extends Event implements Cancellable { public HandlerList getHandlers() { return handlers; } - - public static HandlerList getHandlerList() { - return handlers; - } } diff --git a/Essentials/src/net/ess3/api/events/MuteStatusChangeEvent.java b/Essentials/src/net/ess3/api/events/MuteStatusChangeEvent.java index 25738c4da..db2987811 100644 --- a/Essentials/src/net/ess3/api/events/MuteStatusChangeEvent.java +++ b/Essentials/src/net/ess3/api/events/MuteStatusChangeEvent.java @@ -4,15 +4,14 @@ import net.ess3.api.IUser; import java.util.Optional; - public class MuteStatusChangeEvent extends StatusChangeEvent { - private Long timestamp; - private String reason; + private final Long timestamp; + private final String reason; - public MuteStatusChangeEvent(IUser affected, IUser controller, boolean value, Long timestamp, String reason) { + public MuteStatusChangeEvent(final IUser affected, final IUser controller, final boolean value, final Long timestamp, final String reason) { super(affected, controller, value); this.timestamp = timestamp; - this.reason = reason == null ? null : (reason.isEmpty() ? null : reason); + this.reason = reason == null ? null : reason.isEmpty() ? null : reason; } /** diff --git a/Essentials/src/net/ess3/api/events/NickChangeEvent.java b/Essentials/src/net/ess3/api/events/NickChangeEvent.java index 695f74e97..9a1ab9c39 100644 --- a/Essentials/src/net/ess3/api/events/NickChangeEvent.java +++ b/Essentials/src/net/ess3/api/events/NickChangeEvent.java @@ -3,11 +3,10 @@ package net.ess3.api.events; import net.ess3.api.IUser; import org.bukkit.event.Cancellable; - public class NickChangeEvent extends StateChangeEvent implements Cancellable { - private String newValue; + private final String newValue; - public NickChangeEvent(IUser affected, IUser controller, String value) { + public NickChangeEvent(final IUser affected, final IUser controller, final String value) { super(affected, controller); this.newValue = value; } diff --git a/Essentials/src/net/ess3/api/events/PrivateMessagePreSendEvent.java b/Essentials/src/net/ess3/api/events/PrivateMessagePreSendEvent.java index 3dac80e91..1f9d06775 100644 --- a/Essentials/src/net/ess3/api/events/PrivateMessagePreSendEvent.java +++ b/Essentials/src/net/ess3/api/events/PrivateMessagePreSendEvent.java @@ -11,18 +11,21 @@ import org.bukkit.event.HandlerList; public class PrivateMessagePreSendEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); + private final IMessageRecipient sender; + private final IMessageRecipient recipient; private boolean cancelled; - - private IMessageRecipient sender; - private IMessageRecipient recipient; private String message; - public PrivateMessagePreSendEvent(IMessageRecipient sender, IMessageRecipient recipient, String message) { + public PrivateMessagePreSendEvent(final IMessageRecipient sender, final IMessageRecipient recipient, final String message) { this.sender = sender; this.recipient = recipient; this.message = message; } + public static HandlerList getHandlerList() { + return handlers; + } + public IMessageRecipient getSender() { return sender; } @@ -35,7 +38,7 @@ public class PrivateMessagePreSendEvent extends Event implements Cancellable { return message; } - public void setMessage(String message) { + public void setMessage(final String message) { this.message = message; } @@ -45,7 +48,7 @@ public class PrivateMessagePreSendEvent extends Event implements Cancellable { } @Override - public void setCancelled(boolean b) { + public void setCancelled(final boolean b) { this.cancelled = b; } @@ -53,8 +56,4 @@ public class PrivateMessagePreSendEvent extends Event implements Cancellable { public HandlerList getHandlers() { return handlers; } - - public static HandlerList getHandlerList() { - return handlers; - } } diff --git a/Essentials/src/net/ess3/api/events/PrivateMessageSentEvent.java b/Essentials/src/net/ess3/api/events/PrivateMessageSentEvent.java index ae480b2a9..c537a1fa7 100644 --- a/Essentials/src/net/ess3/api/events/PrivateMessageSentEvent.java +++ b/Essentials/src/net/ess3/api/events/PrivateMessageSentEvent.java @@ -6,7 +6,7 @@ import org.bukkit.event.HandlerList; /** * Called after a private message has been sent to its recipient. - * + *

    * The related private message may not have been successfully received by the recipient, * check the MessageResponse with getResponse() to determine the outcome of the delivery attempt. */ @@ -14,18 +14,22 @@ public class PrivateMessageSentEvent extends Event { private static final HandlerList handlers = new HandlerList(); - private IMessageRecipient sender; - private IMessageRecipient recipient; - private String message; - private IMessageRecipient.MessageResponse response; + private final IMessageRecipient sender; + private final IMessageRecipient recipient; + private final String message; + private final IMessageRecipient.MessageResponse response; - public PrivateMessageSentEvent(IMessageRecipient sender, IMessageRecipient recipient, String message, IMessageRecipient.MessageResponse response) { + public PrivateMessageSentEvent(final IMessageRecipient sender, final IMessageRecipient recipient, final String message, final IMessageRecipient.MessageResponse response) { this.sender = sender; this.recipient = recipient; this.message = message; this.response = response; } + public static HandlerList getHandlerList() { + return handlers; + } + public IMessageRecipient getSender() { return sender; } @@ -46,8 +50,4 @@ public class PrivateMessageSentEvent extends Event { public HandlerList getHandlers() { return handlers; } - - public static HandlerList getHandlerList() { - return handlers; - } } diff --git a/Essentials/src/net/ess3/api/events/SignBreakEvent.java b/Essentials/src/net/ess3/api/events/SignBreakEvent.java index a367621e7..cdb617ebd 100644 --- a/Essentials/src/net/ess3/api/events/SignBreakEvent.java +++ b/Essentials/src/net/ess3/api/events/SignBreakEvent.java @@ -3,9 +3,8 @@ package net.ess3.api.events; import com.earth2me.essentials.signs.EssentialsSign; import net.ess3.api.IUser; - public class SignBreakEvent extends SignEvent { - public SignBreakEvent(EssentialsSign.ISign sign, EssentialsSign essSign, IUser user) { + public SignBreakEvent(final EssentialsSign.ISign sign, final EssentialsSign essSign, final IUser user) { super(sign, essSign, user); } } diff --git a/Essentials/src/net/ess3/api/events/SignCreateEvent.java b/Essentials/src/net/ess3/api/events/SignCreateEvent.java index d295d11f2..08950e061 100644 --- a/Essentials/src/net/ess3/api/events/SignCreateEvent.java +++ b/Essentials/src/net/ess3/api/events/SignCreateEvent.java @@ -3,9 +3,8 @@ package net.ess3.api.events; import com.earth2me.essentials.signs.EssentialsSign; import net.ess3.api.IUser; - public class SignCreateEvent extends SignEvent { - public SignCreateEvent(EssentialsSign.ISign sign, EssentialsSign essSign, IUser user) { + public SignCreateEvent(final EssentialsSign.ISign sign, final EssentialsSign essSign, final IUser user) { super(sign, essSign, user); } } diff --git a/Essentials/src/net/ess3/api/events/SignEvent.java b/Essentials/src/net/ess3/api/events/SignEvent.java index 25687111f..f0ed49566 100644 --- a/Essentials/src/net/ess3/api/events/SignEvent.java +++ b/Essentials/src/net/ess3/api/events/SignEvent.java @@ -8,16 +8,15 @@ import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; - /** * This handles common boilerplate for other SignEvent */ public class SignEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); + final ISign sign; + final EssentialsSign essSign; + final IUser user; private boolean cancelled = false; - ISign sign; - EssentialsSign essSign; - IUser user; public SignEvent(final ISign sign, final EssentialsSign essSign, final IUser user) { super(!Bukkit.getServer().isPrimaryThread()); @@ -26,6 +25,10 @@ public class SignEvent extends Event implements Cancellable { this.user = user; } + public static HandlerList getHandlerList() { + return handlers; + } + public ISign getSign() { return sign; } @@ -43,17 +46,13 @@ public class SignEvent extends Event implements Cancellable { return handlers; } - public static HandlerList getHandlerList() { - return handlers; - } - @Override public boolean isCancelled() { return cancelled; } @Override - public void setCancelled(boolean cancelled) { + public void setCancelled(final boolean cancelled) { this.cancelled = cancelled; } } diff --git a/Essentials/src/net/ess3/api/events/SignInteractEvent.java b/Essentials/src/net/ess3/api/events/SignInteractEvent.java index 6855984b8..da8055d7f 100644 --- a/Essentials/src/net/ess3/api/events/SignInteractEvent.java +++ b/Essentials/src/net/ess3/api/events/SignInteractEvent.java @@ -3,9 +3,8 @@ package net.ess3.api.events; import com.earth2me.essentials.signs.EssentialsSign; import net.ess3.api.IUser; - public class SignInteractEvent extends SignEvent { - public SignInteractEvent(EssentialsSign.ISign sign, EssentialsSign essSign, IUser user) { + public SignInteractEvent(final EssentialsSign.ISign sign, final EssentialsSign essSign, final IUser user) { super(sign, essSign, user); } } diff --git a/Essentials/src/net/ess3/api/events/StateChangeEvent.java b/Essentials/src/net/ess3/api/events/StateChangeEvent.java index bec9ca3ee..1c240797c 100644 --- a/Essentials/src/net/ess3/api/events/StateChangeEvent.java +++ b/Essentials/src/net/ess3/api/events/StateChangeEvent.java @@ -5,29 +5,32 @@ import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; - /** * This handles common boilerplate for events for changes in state. * For boolean state, events should extend StatusChangeEvent instead. */ public abstract class StateChangeEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); + final IUser affected; + final IUser controller; private boolean cancelled = false; - IUser affected; - IUser controller; - public StateChangeEvent(IUser affected, IUser controller) { + public StateChangeEvent(final IUser affected, final IUser controller) { super(); this.affected = affected; this.controller = controller; } - public StateChangeEvent(boolean isAsync, IUser affected, IUser controller) { + public StateChangeEvent(final boolean isAsync, final IUser affected, final IUser controller) { super(isAsync); this.affected = affected; this.controller = controller; } + public static HandlerList getHandlerList() { + return handlers; + } + /** * Get the user who is affected by the state change. * @@ -51,17 +54,13 @@ public abstract class StateChangeEvent extends Event implements Cancellable { return handlers; } - public static HandlerList getHandlerList() { - return handlers; - } - @Override public boolean isCancelled() { return cancelled; } @Override - public void setCancelled(boolean cancelled) { + public void setCancelled(final boolean cancelled) { this.cancelled = cancelled; } } diff --git a/Essentials/src/net/ess3/api/events/StatusChangeEvent.java b/Essentials/src/net/ess3/api/events/StatusChangeEvent.java index 1ac8a243c..dcbf260e9 100644 --- a/Essentials/src/net/ess3/api/events/StatusChangeEvent.java +++ b/Essentials/src/net/ess3/api/events/StatusChangeEvent.java @@ -4,18 +4,17 @@ import net.ess3.api.IUser; import org.bukkit.Bukkit; import org.bukkit.event.Cancellable; - /** * This handles common boilerplate for events for changes in state that are boolean (true/false). */ public abstract class StatusChangeEvent extends StateChangeEvent implements Cancellable { - private boolean newValue; + private final boolean newValue; - public StatusChangeEvent(IUser affected, IUser controller, boolean value) { + public StatusChangeEvent(final IUser affected, final IUser controller, final boolean value) { this(!Bukkit.getServer().isPrimaryThread(), affected, controller, value); } - public StatusChangeEvent(boolean isAsync, IUser affected, IUser controller, boolean value) { + public StatusChangeEvent(final boolean isAsync, final IUser affected, final IUser controller, final boolean value) { super(isAsync, affected, controller); this.newValue = value; } diff --git a/Essentials/src/net/ess3/api/events/TPARequestEvent.java b/Essentials/src/net/ess3/api/events/TPARequestEvent.java index d0f165a0c..5720e3814 100644 --- a/Essentials/src/net/ess3/api/events/TPARequestEvent.java +++ b/Essentials/src/net/ess3/api/events/TPARequestEvent.java @@ -6,20 +6,24 @@ import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; - public class TPARequestEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); - private CommandSource requester; - private IUser target; - private boolean cancelled = false, requestToTPAHere = false; + private final CommandSource requester; + private final IUser target; + private boolean cancelled = false; + private boolean requestToTPAHere; - public TPARequestEvent(CommandSource requester, IUser target, boolean tpaHere) { + public TPARequestEvent(final CommandSource requester, final IUser target, final boolean tpaHere) { super(); this.requester = requester; this.target = target; this.requestToTPAHere = tpaHere; } + public static HandlerList getHandlerList() { + return handlers; + } + public CommandSource getRequester() { return requester; } @@ -38,7 +42,7 @@ public class TPARequestEvent extends Event implements Cancellable { } @Override - public void setCancelled(boolean cancelled) { + public void setCancelled(final boolean cancelled) { this.cancelled = cancelled; } @@ -46,8 +50,4 @@ public class TPARequestEvent extends Event implements Cancellable { public HandlerList getHandlers() { return handlers; } - - public static HandlerList getHandlerList() { - return handlers; - } -} \ No newline at end of file +} diff --git a/Essentials/src/net/ess3/api/events/UserBalanceUpdateEvent.java b/Essentials/src/net/ess3/api/events/UserBalanceUpdateEvent.java index 5cae42012..d0da97a32 100644 --- a/Essentials/src/net/ess3/api/events/UserBalanceUpdateEvent.java +++ b/Essentials/src/net/ess3/api/events/UserBalanceUpdateEvent.java @@ -1,7 +1,6 @@ package net.ess3.api.events; import com.google.common.base.Preconditions; - import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.Event; @@ -9,20 +8,19 @@ import org.bukkit.event.HandlerList; import java.math.BigDecimal; - public class UserBalanceUpdateEvent extends Event { private static final HandlerList handlers = new HandlerList(); private final Player player; private final BigDecimal originalBalance; + private final Cause cause; private BigDecimal balance; - private Cause cause; @Deprecated - public UserBalanceUpdateEvent(Player player, BigDecimal originalBalance, BigDecimal balance) { + public UserBalanceUpdateEvent(final Player player, final BigDecimal originalBalance, final BigDecimal balance) { this(player, originalBalance, balance, Cause.UNKNOWN); } - public UserBalanceUpdateEvent(Player player, BigDecimal originalBalance, BigDecimal balance, Cause cause) { + public UserBalanceUpdateEvent(final Player player, final BigDecimal originalBalance, final BigDecimal balance, final Cause cause) { super(!Bukkit.getServer().isPrimaryThread()); this.player = player; this.originalBalance = originalBalance; @@ -30,12 +28,12 @@ public class UserBalanceUpdateEvent extends Event { this.cause = cause; } - @Override - public HandlerList getHandlers() { + public static HandlerList getHandlerList() { return handlers; } - public static HandlerList getHandlerList() { + @Override + public HandlerList getHandlers() { return handlers; } @@ -46,8 +44,8 @@ public class UserBalanceUpdateEvent extends Event { public BigDecimal getNewBalance() { return balance; } - - public void setNewBalance(BigDecimal newBalance) { + + public void setNewBalance(final BigDecimal newBalance) { Preconditions.checkNotNull(newBalance, "newBalance cannot be null."); this.balance = newBalance; } diff --git a/Essentials/src/net/ess3/api/events/UserRandomTeleportEvent.java b/Essentials/src/net/ess3/api/events/UserRandomTeleportEvent.java index a8727c813..d7dc4403d 100644 --- a/Essentials/src/net/ess3/api/events/UserRandomTeleportEvent.java +++ b/Essentials/src/net/ess3/api/events/UserRandomTeleportEvent.java @@ -13,12 +13,13 @@ import org.bukkit.event.HandlerList; public class UserRandomTeleportEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); - private IUser user; + private final IUser user; private Location center; - private double minRange, maxRange; + private double minRange; + private double maxRange; private boolean cancelled = false; - public UserRandomTeleportEvent(IUser user, Location center, double minRange, double maxRange) { + public UserRandomTeleportEvent(final IUser user, final Location center, final double minRange, final double maxRange) { super(!Bukkit.isPrimaryThread()); this.user = user; this.center = center; @@ -26,6 +27,10 @@ public class UserRandomTeleportEvent extends Event implements Cancellable { this.maxRange = maxRange; } + public static HandlerList getHandlerList() { + return handlers; + } + public IUser getUser() { return user; } @@ -34,7 +39,7 @@ public class UserRandomTeleportEvent extends Event implements Cancellable { return center; } - public void setCenter(Location center) { + public void setCenter(final Location center) { this.center = center; } @@ -42,7 +47,7 @@ public class UserRandomTeleportEvent extends Event implements Cancellable { return minRange; } - public void setMinRange(double minRange) { + public void setMinRange(final double minRange) { this.minRange = minRange; } @@ -50,7 +55,7 @@ public class UserRandomTeleportEvent extends Event implements Cancellable { return maxRange; } - public void setMaxRange(double maxRange) { + public void setMaxRange(final double maxRange) { this.maxRange = maxRange; } @@ -60,7 +65,7 @@ public class UserRandomTeleportEvent extends Event implements Cancellable { } @Override - public void setCancelled(boolean b) { + public void setCancelled(final boolean b) { cancelled = b; } @@ -68,8 +73,4 @@ public class UserRandomTeleportEvent extends Event implements Cancellable { public HandlerList getHandlers() { return handlers; } - - public static HandlerList getHandlerList() { - return handlers; - } } diff --git a/Essentials/src/net/ess3/api/events/UserTeleportHomeEvent.java b/Essentials/src/net/ess3/api/events/UserTeleportHomeEvent.java index ad04da29c..1bbdd32e2 100644 --- a/Essentials/src/net/ess3/api/events/UserTeleportHomeEvent.java +++ b/Essentials/src/net/ess3/api/events/UserTeleportHomeEvent.java @@ -8,7 +8,7 @@ import org.bukkit.event.HandlerList; /** * Called when a user is teleported home via the /home command. - * + *

    * This is called before {@link net.ess3.api.events.teleport.TeleportWarmupEvent TeleportWarmupEvent}. */ public class UserTeleportHomeEvent extends Event implements Cancellable { @@ -20,13 +20,17 @@ public class UserTeleportHomeEvent extends Event implements Cancellable { private final HomeType homeType; private boolean cancelled = false; - public UserTeleportHomeEvent(IUser user, String homeName, Location target, HomeType homeType) { + public UserTeleportHomeEvent(final IUser user, final String homeName, final Location target, final HomeType homeType) { this.user = user; this.homeName = homeName; this.target = target; this.homeType = homeType; } + public static HandlerList getHandlerList() { + return handlers; + } + /** * Returns the user who is being teleported * @@ -38,7 +42,7 @@ public class UserTeleportHomeEvent extends Event implements Cancellable { /** * Returns the name of the home being teleported to. - * + *

    * The behavior of this method varies based on the {@link HomeType} as follows; * {@link HomeType#HOME} - Returns name of home being teleported to. * {@link HomeType#BED} - Returns "bed". @@ -61,7 +65,7 @@ public class UserTeleportHomeEvent extends Event implements Cancellable { /** * Returns the home location type. - * + *

    * {@link HomeType#HOME} - A user-set home location. * {@link HomeType#BED} - A user's bed location. * {@link HomeType#SPAWN} - The user's current world spawn. @@ -78,7 +82,7 @@ public class UserTeleportHomeEvent extends Event implements Cancellable { } @Override - public void setCancelled(boolean cancelled) { + public void setCancelled(final boolean cancelled) { this.cancelled = cancelled; } @@ -87,10 +91,6 @@ public class UserTeleportHomeEvent extends Event implements Cancellable { return handlers; } - public static HandlerList getHandlerList() { - return handlers; - } - public enum HomeType { HOME, BED, diff --git a/Essentials/src/net/ess3/api/events/UserWarpEvent.java b/Essentials/src/net/ess3/api/events/UserWarpEvent.java index de9ff7f2e..d3b01eb22 100644 --- a/Essentials/src/net/ess3/api/events/UserWarpEvent.java +++ b/Essentials/src/net/ess3/api/events/UserWarpEvent.java @@ -3,29 +3,32 @@ package net.ess3.api.events; import com.earth2me.essentials.Trade; import net.ess3.api.IUser; import org.bukkit.Bukkit; -import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; + /** * Called when the player use the command /warp */ public class UserWarpEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); - private IUser user; + private final IUser user; + private final Trade trade; private String warp; - private Trade trade; private boolean cancelled = false; - - public UserWarpEvent(IUser user, String warp, Trade trade) { + public UserWarpEvent(final IUser user, final String warp, final Trade trade) { super(!Bukkit.getServer().isPrimaryThread()); this.user = user; this.warp = warp; this.trade = trade; } + public static HandlerList getHandlerList() { + return handlers; + } + public IUser getUser() { return user; } @@ -34,25 +37,26 @@ public class UserWarpEvent extends Event implements Cancellable { return warp; } + public void setWarp(final String warp) { + this.warp = warp; + } + /** * Getting payment handling information + * * @return The payment handling class */ public Trade getTrade() { return trade; } - public void setWarp(String warp) { - this.warp = warp; - } - @Override public boolean isCancelled() { return cancelled; } @Override - public void setCancelled(boolean b) { + public void setCancelled(final boolean b) { cancelled = b; } @@ -60,8 +64,4 @@ public class UserWarpEvent extends Event implements Cancellable { public HandlerList getHandlers() { return handlers; } - - public static HandlerList getHandlerList() { - return handlers; - } } diff --git a/Essentials/src/net/ess3/api/events/VanishStatusChangeEvent.java b/Essentials/src/net/ess3/api/events/VanishStatusChangeEvent.java index e251c8a96..604e33012 100644 --- a/Essentials/src/net/ess3/api/events/VanishStatusChangeEvent.java +++ b/Essentials/src/net/ess3/api/events/VanishStatusChangeEvent.java @@ -4,12 +4,12 @@ import net.ess3.api.IUser; /** * Fired when a player's vanish status changes due to the /vanish command. - * + *

    * For other cases where the player's vanish status changes, you should listen on PlayerJoinEvent and * check with {@link IUser#isVanished()}. */ public class VanishStatusChangeEvent extends StatusChangeEvent { - public VanishStatusChangeEvent(IUser affected, IUser controller, boolean value) { + public VanishStatusChangeEvent(final IUser affected, final IUser controller, final boolean value) { super(affected, controller, value); } } diff --git a/Essentials/src/net/ess3/api/events/teleport/PreTeleportEvent.java b/Essentials/src/net/ess3/api/events/teleport/PreTeleportEvent.java index 357c20119..327b29932 100644 --- a/Essentials/src/net/ess3/api/events/teleport/PreTeleportEvent.java +++ b/Essentials/src/net/ess3/api/events/teleport/PreTeleportEvent.java @@ -15,7 +15,7 @@ public class PreTeleportEvent extends TeleportEvent { private static final HandlerList handlers = new HandlerList(); - public PreTeleportEvent(IUser teleportee, PlayerTeleportEvent.TeleportCause cause, ITarget target) { + public PreTeleportEvent(final IUser teleportee, final PlayerTeleportEvent.TeleportCause cause, final ITarget target) { super(teleportee, cause, target); } diff --git a/Essentials/src/net/ess3/api/events/teleport/TeleportEvent.java b/Essentials/src/net/ess3/api/events/teleport/TeleportEvent.java index 761a1a6e2..35ddd2339 100644 --- a/Essentials/src/net/ess3/api/events/teleport/TeleportEvent.java +++ b/Essentials/src/net/ess3/api/events/teleport/TeleportEvent.java @@ -15,7 +15,7 @@ public abstract class TeleportEvent extends Event implements Cancellable { private final ITarget target; private boolean cancelled = false; - TeleportEvent(IUser teleporter, IUser teleportee, PlayerTeleportEvent.TeleportCause cause, ITarget target) { + TeleportEvent(final IUser teleporter, final IUser teleportee, final PlayerTeleportEvent.TeleportCause cause, final ITarget target) { super(!Bukkit.isPrimaryThread()); this.teleporter = teleporter; this.teleportee = teleportee; @@ -23,7 +23,7 @@ public abstract class TeleportEvent extends Event implements Cancellable { this.target = target; } - TeleportEvent(IUser teleportee, PlayerTeleportEvent.TeleportCause cause, ITarget target) { + TeleportEvent(final IUser teleportee, final PlayerTeleportEvent.TeleportCause cause, final ITarget target) { this(teleportee, teleportee, cause, target); } @@ -61,7 +61,7 @@ public abstract class TeleportEvent extends Event implements Cancellable { } @Override - public void setCancelled(boolean b) { + public void setCancelled(final boolean b) { cancelled = b; } } diff --git a/Essentials/src/net/ess3/api/events/teleport/TeleportWarmupEvent.java b/Essentials/src/net/ess3/api/events/teleport/TeleportWarmupEvent.java index 92f60992c..9035657c8 100644 --- a/Essentials/src/net/ess3/api/events/teleport/TeleportWarmupEvent.java +++ b/Essentials/src/net/ess3/api/events/teleport/TeleportWarmupEvent.java @@ -17,12 +17,12 @@ public class TeleportWarmupEvent extends TeleportEvent { private double delay; - public TeleportWarmupEvent(IUser teleporter, IUser teleportee, PlayerTeleportEvent.TeleportCause cause, ITarget target, double delay) { + public TeleportWarmupEvent(final IUser teleporter, final IUser teleportee, final PlayerTeleportEvent.TeleportCause cause, final ITarget target, final double delay) { super(teleporter, teleportee, cause, target); this.delay = delay; } - public TeleportWarmupEvent(IUser teleportee, PlayerTeleportEvent.TeleportCause cause, ITarget target, double delay) { + public TeleportWarmupEvent(final IUser teleportee, final PlayerTeleportEvent.TeleportCause cause, final ITarget target, final double delay) { super(teleportee, cause, target); this.delay = delay; } @@ -46,7 +46,7 @@ public class TeleportWarmupEvent extends TeleportEvent { /** * @param delay The warmup delay, in seconds. Set this to 0 to skip the warmup delay. */ - public void setDelay(double delay) { + public void setDelay(final double delay) { this.delay = delay; } } diff --git a/Essentials/test/com/earth2me/essentials/EconomyTest.java b/Essentials/test/com/earth2me/essentials/EconomyTest.java index 82c528e7e..888ca11e5 100644 --- a/Essentials/test/com/earth2me/essentials/EconomyTest.java +++ b/Essentials/test/com/earth2me/essentials/EconomyTest.java @@ -4,7 +4,6 @@ import com.earth2me.essentials.api.NoLoanPermittedException; import com.earth2me.essentials.api.UserDoesNotExistException; import com.earth2me.essentials.commands.IEssentialsCommand; import com.earth2me.essentials.commands.NoChargeException; - import net.ess3.api.Economy; import org.bukkit.World.Environment; import org.bukkit.command.CommandSender; @@ -14,12 +13,11 @@ import org.junit.Test; import java.io.IOException; - public class EconomyTest { - private final transient Essentials ess; private static final String NPCNAME = "npc1"; private static final String PLAYERNAME = "testPlayer1"; private static final String PLAYERNAME2 = "testPlayer2"; + private final transient Essentials ess; private final FakeServer server; public EconomyTest() { @@ -28,9 +26,9 @@ public class EconomyTest { ess = new Essentials(server); try { ess.setupForTesting(server); - } catch (InvalidDescriptionException ex) { + } catch (final InvalidDescriptionException ex) { Assert.fail("InvalidDescriptionException"); - } catch (IOException ex) { + } catch (final IOException ex) { Assert.fail("IOException"); } server.addPlayer(new OfflinePlayer(PLAYERNAME, ess.getServer())); @@ -47,7 +45,7 @@ public class EconomyTest { Assert.assertNotNull("NPC can be accessed", ess.getOfflineUser(NPCNAME)); try { Economy.removeNPC(NPCNAME); - } catch (UserDoesNotExistException ex) { + } catch (final UserDoesNotExistException ex) { Assert.fail(ex.getMessage()); } Assert.assertFalse("NPC can be removed", Economy.playerExists(NPCNAME)); @@ -59,16 +57,16 @@ public class EconomyTest { Economy.resetBalance(PLAYERNAME); Assert.assertEquals("Player has no money", 0.0, Economy.getMoney(PLAYERNAME), 0); Economy.add(PLAYERNAME, 10.0); - Assert.assertEquals("Add money", 10.0, Economy.getMoney(PLAYERNAME),0); + Assert.assertEquals("Add money", 10.0, Economy.getMoney(PLAYERNAME), 0); Economy.subtract(PLAYERNAME, 5.0); - Assert.assertEquals("Subtract money", 5.0, Economy.getMoney(PLAYERNAME),0); + Assert.assertEquals("Subtract money", 5.0, Economy.getMoney(PLAYERNAME), 0); Economy.multiply(PLAYERNAME, 2.0); - Assert.assertEquals("Multiply money", 10.0, Economy.getMoney(PLAYERNAME),0); + Assert.assertEquals("Multiply money", 10.0, Economy.getMoney(PLAYERNAME), 0); Economy.divide(PLAYERNAME, 2.0); - Assert.assertEquals("Divide money", 5.0, Economy.getMoney(PLAYERNAME),0); + Assert.assertEquals("Divide money", 5.0, Economy.getMoney(PLAYERNAME), 0); Economy.setMoney(PLAYERNAME, 10.0); - Assert.assertEquals("Set money", 10.0, Economy.getMoney(PLAYERNAME),0); - } catch (NoLoanPermittedException | UserDoesNotExistException ex) { + Assert.assertEquals("Set money", 10.0, Economy.getMoney(PLAYERNAME), 0); + } catch (final NoLoanPermittedException | UserDoesNotExistException ex) { Assert.fail(ex.getMessage()); } @@ -79,66 +77,68 @@ public class EconomyTest { Assert.assertEquals("Format $10.10", "$10.10", Economy.format(10.1000001)); Assert.assertEquals("Format $10.10", "$10.10", Economy.format(10.1099999)); - //test Exceptions try { Assert.assertTrue("Player exists", Economy.playerExists(PLAYERNAME)); Economy.resetBalance(PLAYERNAME); - Assert.assertEquals("Reset balance", 0.0, Economy.getMoney(PLAYERNAME),0); + Assert.assertEquals("Reset balance", 0.0, Economy.getMoney(PLAYERNAME), 0); Economy.subtract(PLAYERNAME, 5.0); Assert.fail("Did not throw exception"); - } catch (NoLoanPermittedException ignored) { - } catch (UserDoesNotExistException ex) { + } catch (final NoLoanPermittedException ignored) { + } catch (final UserDoesNotExistException ex) { Assert.fail(ex.getMessage()); } try { Economy.resetBalance("UnknownPlayer"); Assert.fail("Did not throw exception"); - } catch (NoLoanPermittedException ex) { + } catch (final NoLoanPermittedException ex) { Assert.fail(ex.getMessage()); - } catch (UserDoesNotExistException ignored) {} + } catch (final UserDoesNotExistException ignored) { + } } - private void runCommand(String command, User user, String args) throws Exception { + private void runCommand(final String command, final User user, final String args) throws Exception { runCommand(command, user, args.split("\\s+")); } - private void runCommand(String command, User user, String[] args) throws Exception { - IEssentialsCommand cmd; + private void runCommand(final String command, final User user, final String[] args) throws Exception { + final IEssentialsCommand cmd; try { cmd = (IEssentialsCommand) Essentials.class.getClassLoader() .loadClass("com.earth2me.essentials.commands.Command" + command).newInstance(); cmd.setEssentials(ess); cmd.run(server, user, command, null, args); - } catch (NoChargeException ignored) {} + } catch (final NoChargeException ignored) { + } } - private void runConsoleCommand(String command, String args) throws Exception { + private void runConsoleCommand(final String command, final String args) throws Exception { runConsoleCommand(command, args.split("\\s+")); } - private void runConsoleCommand(String command, String[] args) throws Exception { - IEssentialsCommand cmd; + private void runConsoleCommand(final String command, final String[] args) throws Exception { + final IEssentialsCommand cmd; - CommandSender sender = server.getConsoleSender(); + final CommandSender sender = server.getConsoleSender(); try { cmd = (IEssentialsCommand) Essentials.class.getClassLoader() .loadClass("com.earth2me.essentials.commands.Command" + command).newInstance(); cmd.setEssentials(ess); cmd.run(server, new CommandSource(sender), command, null, args); - } catch (NoChargeException ignored) {} + } catch (final NoChargeException ignored) { + } } @Test public void testNegativePayCommand() { - User user1 = ess.getUser(PLAYERNAME); + final User user1 = ess.getUser(PLAYERNAME); try { runCommand("pay", user1, PLAYERNAME2 + " -123"); - } catch (Exception e) { + } catch (final Exception e) { Assert.assertEquals(I18n.tl("payMustBePositive"), e.getMessage()); } } diff --git a/Essentials/test/com/earth2me/essentials/FakeServer.java b/Essentials/test/com/earth2me/essentials/FakeServer.java index 34f0b5d03..54772ecca 100644 --- a/Essentials/test/com/earth2me/essentials/FakeServer.java +++ b/Essentials/test/com/earth2me/essentials/FakeServer.java @@ -1,12 +1,29 @@ package com.earth2me.essentials; import com.earth2me.essentials.craftbukkit.FakeWorld; -import org.bukkit.*; +import org.bukkit.BanList; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Keyed; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Server; +import org.bukkit.Statistic; +import org.bukkit.StructureType; +import org.bukkit.Tag; +import org.bukkit.UnsafeValues; import org.bukkit.Warning.WarningState; +import org.bukkit.World; import org.bukkit.World.Environment; +import org.bukkit.WorldCreator; import org.bukkit.advancement.Advancement; import org.bukkit.block.data.BlockData; -import org.bukkit.boss.*; +import org.bukkit.boss.BarColor; +import org.bukkit.boss.BarFlag; +import org.bukkit.boss.BarStyle; +import org.bukkit.boss.BossBar; +import org.bukkit.boss.KeyedBossBar; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.command.PluginCommand; @@ -22,14 +39,25 @@ import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.generator.ChunkGenerator; import org.bukkit.help.HelpMap; -import org.bukkit.inventory.*; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.ItemFactory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.Merchant; +import org.bukkit.inventory.Recipe; import org.bukkit.loot.LootTable; import org.bukkit.map.MapView; import org.bukkit.permissions.Permissible; import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionAttachment; import org.bukkit.permissions.PermissionAttachmentInfo; -import org.bukkit.plugin.*; +import org.bukkit.plugin.EventExecutor; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginLoader; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.RegisteredListener; +import org.bukkit.plugin.ServicesManager; +import org.bukkit.plugin.UnknownDependencyException; import org.bukkit.plugin.messaging.Messenger; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitScheduler; @@ -40,17 +68,22 @@ import org.bukkit.util.CachedServerIcon; import java.awt.image.BufferedImage; import java.io.File; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.function.Consumer; import java.util.logging.Logger; - public class FakeServer implements Server { - private List players = new ArrayList<>(); private final List worlds = new ArrayList<>(); - private PluginManager pluginManager = new FakePluginManager(); + private final PluginManager pluginManager = new FakePluginManager(); + private List players = new ArrayList<>(); FakeServer() { if (Bukkit.getServer() == null) { @@ -73,7 +106,7 @@ public class FakeServer implements Server { return players; } - public void setOnlinePlayers(List players) { + public void setOnlinePlayers(final List players) { this.players = players; } @@ -93,9 +126,9 @@ public class FakeServer implements Server { } @Override - public int broadcastMessage(String string) { + public int broadcastMessage(final String string) { int i = 0; - for (Player player : players) { + for (final Player player : players) { player.sendMessage(string); i++; } @@ -118,8 +151,8 @@ public class FakeServer implements Server { } @Override - public Player getPlayer(String string) { - for (Player player : players) { + public Player getPlayer(final String string) { + for (final Player player : players) { if (player.getName().equalsIgnoreCase(string)) { return player; } @@ -128,9 +161,9 @@ public class FakeServer implements Server { } @Override - public List matchPlayer(String string) { - List matches = new ArrayList<>(); - for (Player player : players) { + public List matchPlayer(final String string) { + final List matches = new ArrayList<>(); + for (final Player player : players) { if (player.getName().substring(0, Math.min(player.getName().length(), string.length())).equalsIgnoreCase(string)) { matches.add(player); } @@ -147,62 +180,62 @@ public class FakeServer implements Server { public BukkitScheduler getScheduler() { return new BukkitScheduler() { @Override - public int scheduleSyncDelayedTask(Plugin plugin, Runnable r, long l) { + public int scheduleSyncDelayedTask(final Plugin plugin, final Runnable r, final long l) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public int scheduleSyncDelayedTask(Plugin plugin, BukkitRunnable bukkitRunnable, long l) { + public int scheduleSyncDelayedTask(final Plugin plugin, final BukkitRunnable bukkitRunnable, final long l) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public int scheduleSyncDelayedTask(Plugin plugin, Runnable r) { + public int scheduleSyncDelayedTask(final Plugin plugin, final Runnable r) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public int scheduleSyncDelayedTask(Plugin plugin, BukkitRunnable bukkitRunnable) { + public int scheduleSyncDelayedTask(final Plugin plugin, final BukkitRunnable bukkitRunnable) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public int scheduleSyncRepeatingTask(Plugin plugin, Runnable r, long l, long l1) { + public int scheduleSyncRepeatingTask(final Plugin plugin, final Runnable r, final long l, final long l1) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public int scheduleSyncRepeatingTask(Plugin plugin, BukkitRunnable bukkitRunnable, long l, long l1) { + public int scheduleSyncRepeatingTask(final Plugin plugin, final BukkitRunnable bukkitRunnable, final long l, final long l1) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public int scheduleAsyncRepeatingTask(Plugin plugin, Runnable r, long l, long l1) { + public int scheduleAsyncRepeatingTask(final Plugin plugin, final Runnable r, final long l, final long l1) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Future callSyncMethod(Plugin plugin, Callable clbl) { + public Future callSyncMethod(final Plugin plugin, final Callable clbl) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void cancelTask(int i) { + public void cancelTask(final int i) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void cancelTasks(Plugin plugin) { + public void cancelTasks(final Plugin plugin) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean isCurrentlyRunning(int i) { + public boolean isCurrentlyRunning(final int i) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean isQueued(int i) { + public boolean isQueued(final int i) { throw new UnsupportedOperationException("Not supported yet."); } @@ -217,104 +250,104 @@ public class FakeServer implements Server { } @Override - public BukkitTask runTask(Plugin plugin, Runnable r) throws IllegalArgumentException { + public BukkitTask runTask(final Plugin plugin, final Runnable r) throws IllegalArgumentException { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void runTask(Plugin plugin, Consumer task) throws IllegalArgumentException { + public void runTask(final Plugin plugin, final Consumer task) throws IllegalArgumentException { throw new UnsupportedOperationException("Not supported yet."); } @Override - public BukkitTask runTask(Plugin plugin, BukkitRunnable bukkitRunnable) throws IllegalArgumentException { + public BukkitTask runTask(final Plugin plugin, final BukkitRunnable bukkitRunnable) throws IllegalArgumentException { return null; } @Override - public BukkitTask runTaskAsynchronously(Plugin plugin, Runnable r) throws IllegalArgumentException { + public BukkitTask runTaskAsynchronously(final Plugin plugin, final Runnable r) throws IllegalArgumentException { r.run(); return null; } @Override - public void runTaskAsynchronously(Plugin plugin, Consumer task) throws IllegalArgumentException { + public void runTaskAsynchronously(final Plugin plugin, final Consumer task) throws IllegalArgumentException { throw new UnsupportedOperationException("Not supported yet."); } @Override - public BukkitTask runTaskAsynchronously(Plugin plugin, BukkitRunnable bukkitRunnable) throws IllegalArgumentException { + public BukkitTask runTaskAsynchronously(final Plugin plugin, final BukkitRunnable bukkitRunnable) throws IllegalArgumentException { return null; } @Override - public BukkitTask runTaskLater(Plugin plugin, Runnable r, long l) throws IllegalArgumentException { + public BukkitTask runTaskLater(final Plugin plugin, final Runnable r, final long l) throws IllegalArgumentException { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void runTaskLater(Plugin plugin, Consumer task, long delay) throws IllegalArgumentException { + public void runTaskLater(final Plugin plugin, final Consumer task, final long delay) throws IllegalArgumentException { throw new UnsupportedOperationException("Not supported yet."); } @Override - public BukkitTask runTaskLater(Plugin plugin, BukkitRunnable bukkitRunnable, long l) throws IllegalArgumentException { + public BukkitTask runTaskLater(final Plugin plugin, final BukkitRunnable bukkitRunnable, final long l) throws IllegalArgumentException { return null; } @Override - public BukkitTask runTaskLaterAsynchronously(Plugin plugin, Runnable r, long l) throws IllegalArgumentException { + public BukkitTask runTaskLaterAsynchronously(final Plugin plugin, final Runnable r, final long l) throws IllegalArgumentException { r.run(); return null; } @Override - public void runTaskLaterAsynchronously(Plugin plugin, Consumer task, long delay) throws IllegalArgumentException { + public void runTaskLaterAsynchronously(final Plugin plugin, final Consumer task, final long delay) throws IllegalArgumentException { throw new UnsupportedOperationException("Not supported yet."); } @Override - public BukkitTask runTaskLaterAsynchronously(Plugin plugin, BukkitRunnable bukkitRunnable, long l) throws IllegalArgumentException { + public BukkitTask runTaskLaterAsynchronously(final Plugin plugin, final BukkitRunnable bukkitRunnable, final long l) throws IllegalArgumentException { return null; } @Override - public BukkitTask runTaskTimer(Plugin plugin, Runnable r, long l, long l1) throws IllegalArgumentException { + public BukkitTask runTaskTimer(final Plugin plugin, final Runnable r, final long l, final long l1) throws IllegalArgumentException { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void runTaskTimer(Plugin plugin, Consumer task, long delay, long period) throws IllegalArgumentException { + public void runTaskTimer(final Plugin plugin, final Consumer task, final long delay, final long period) throws IllegalArgumentException { throw new UnsupportedOperationException("Not supported yet."); } @Override - public BukkitTask runTaskTimer(Plugin plugin, BukkitRunnable bukkitRunnable, long l, long l1) throws IllegalArgumentException { + public BukkitTask runTaskTimer(final Plugin plugin, final BukkitRunnable bukkitRunnable, final long l, final long l1) throws IllegalArgumentException { return null; } @Override - public BukkitTask runTaskTimerAsynchronously(Plugin plugin, Runnable r, long l, long l1) throws IllegalArgumentException { + public BukkitTask runTaskTimerAsynchronously(final Plugin plugin, final Runnable r, final long l, final long l1) throws IllegalArgumentException { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void runTaskTimerAsynchronously(Plugin plugin, Consumer task, long delay, long period) throws IllegalArgumentException { + public void runTaskTimerAsynchronously(final Plugin plugin, final Consumer task, final long delay, final long period) throws IllegalArgumentException { throw new UnsupportedOperationException("Not supported yet."); } @Override - public BukkitTask runTaskTimerAsynchronously(Plugin plugin, BukkitRunnable bukkitRunnable, long l, long l1) throws IllegalArgumentException { + public BukkitTask runTaskTimerAsynchronously(final Plugin plugin, final BukkitRunnable bukkitRunnable, final long l, final long l1) throws IllegalArgumentException { return null; } @Override - public int scheduleAsyncDelayedTask(Plugin plugin, Runnable r, long l) { + public int scheduleAsyncDelayedTask(final Plugin plugin, final Runnable r, final long l) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public int scheduleAsyncDelayedTask(Plugin plugin, Runnable r) { + public int scheduleAsyncDelayedTask(final Plugin plugin, final Runnable r) { throw new UnsupportedOperationException("Not supported yet."); } }; @@ -330,21 +363,21 @@ public class FakeServer implements Server { return worlds; } - public World createWorld(String string, Environment e) { - World w = new FakeWorld(string, e); + public World createWorld(final String string, final Environment e) { + final World w = new FakeWorld(string, e); worlds.add(w); return w; } - public World createWorld(String string, Environment e, long l) { - World w = new FakeWorld(string, e); + public World createWorld(final String string, final Environment e, final long l) { + final World w = new FakeWorld(string, e); worlds.add(w); return w; } @Override - public World getWorld(String string) { - for (World world : worlds) { + public World getWorld(final String string) { + for (final World world : worlds) { if (world.getName().equalsIgnoreCase(string)) { return world; } @@ -362,7 +395,7 @@ public class FakeServer implements Server { } @Override - public PluginCommand getPluginCommand(String string) { + public PluginCommand getPluginCommand(final String string) { throw new UnsupportedOperationException("Not supported yet."); } @@ -371,38 +404,38 @@ public class FakeServer implements Server { } @Override - public boolean dispatchCommand(CommandSender cs, String string) { + public boolean dispatchCommand(final CommandSender cs, final String string) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean addRecipe(Recipe recipe) { + public boolean addRecipe(final Recipe recipe) { throw new UnsupportedOperationException("Not supported yet."); } - void addPlayer(Player base1) { + void addPlayer(final Player base1) { players.add(base1); pluginManager.callEvent(new PlayerJoinEvent(base1, null)); } - OfflinePlayer createPlayer(String name) { - OfflinePlayer player = new OfflinePlayer(name, this); + OfflinePlayer createPlayer(final String name) { + final OfflinePlayer player = new OfflinePlayer(name, this); player.setLocation(new Location(worlds.get(0), 0, 0, 0, 0, 0)); return player; } @Override - public World createWorld(WorldCreator creator) { + public World createWorld(final WorldCreator creator) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean unloadWorld(String string, boolean bln) { + public boolean unloadWorld(final String string, final boolean bln) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean unloadWorld(World world, boolean bln) { + public boolean unloadWorld(final World world, final boolean bln) { throw new UnsupportedOperationException("Not supported yet."); } @@ -417,7 +450,7 @@ public class FakeServer implements Server { } @Override - public void setSpawnRadius(int i) { + public void setSpawnRadius(final int i) { throw new UnsupportedOperationException("Not supported yet."); } @@ -426,16 +459,16 @@ public class FakeServer implements Server { throw new UnsupportedOperationException("Not supported yet."); } - public World getWorld(long l) { + public World getWorld(final long l) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public World getWorld(UUID uuid) { + public World getWorld(final UUID uuid) { throw new UnsupportedOperationException("Not supported yet."); } - public MapView getMap(int id) { + public MapView getMap(final int id) { throw new UnsupportedOperationException("Not supported yet."); } @@ -455,17 +488,17 @@ public class FakeServer implements Server { } @Override - public MapView createMap(World world) { + public MapView createMap(final World world) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public ItemStack createExplorerMap(World world, Location location, StructureType structureType) { + public ItemStack createExplorerMap(final World world, final Location location, final StructureType structureType) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public ItemStack createExplorerMap(World world, Location location, StructureType structureType, int radius, boolean findUnexplored) { + public ItemStack createExplorerMap(final World world, final Location location, final StructureType structureType, final int radius, final boolean findUnexplored) { throw new UnsupportedOperationException("Not supported yet."); } @@ -475,7 +508,7 @@ public class FakeServer implements Server { } @Override - public void setWhitelist(boolean bln) { + public void setWhitelist(final boolean bln) { throw new UnsupportedOperationException("Not supported yet."); } @@ -490,8 +523,8 @@ public class FakeServer implements Server { } @Override - public Player getPlayerExact(String string) { - for (Player player : players) { + public Player getPlayerExact(final String string) { + for (final Player player : players) { if (player.getName().equals(string)) { return player; } @@ -505,7 +538,7 @@ public class FakeServer implements Server { } @Override - public int broadcast(String string, String string1) { + public int broadcast(final String string, final String string1) { throw new UnsupportedOperationException("Not supported yet."); } @@ -537,7 +570,7 @@ public class FakeServer implements Server { } @Override - public void setWhitelisted(boolean bln) { + public void setWhitelisted(final boolean bln) { throw new UnsupportedOperationException("Not supported yet."); } @@ -551,11 +584,6 @@ public class FakeServer implements Server { throw new UnsupportedOperationException("Not supported yet."); } - @Override - public void setOp(boolean bln) { - throw new UnsupportedOperationException("Not supported yet."); - } - @Override public Map serialize() { throw new UnsupportedOperationException("Not supported yet."); @@ -564,6 +592,9 @@ public class FakeServer implements Server { @Override public long getFirstPlayed() { throw new UnsupportedOperationException("Not supported yet."); + } @Override + public void setOp(final boolean bln) { + throw new UnsupportedOperationException("Not supported yet."); } @Override @@ -595,94 +626,97 @@ public class FakeServer implements Server { } @Override - public void incrementStatistic(Statistic statistic) { + public void incrementStatistic(final Statistic statistic) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void decrementStatistic(Statistic statistic) { + public void decrementStatistic(final Statistic statistic) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public int getStatistic(Statistic statistic) { + public int getStatistic(final Statistic statistic) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void incrementStatistic(Statistic statistic, int amount) { + public void incrementStatistic(final Statistic statistic, final int amount) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void decrementStatistic(Statistic statistic, int amount) { + public void decrementStatistic(final Statistic statistic, final int amount) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void setStatistic(Statistic statistic, int newValue) { + public void setStatistic(final Statistic statistic, final int newValue) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void incrementStatistic(Statistic statistic, Material material) { + public void incrementStatistic(final Statistic statistic, final Material material) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void decrementStatistic(Statistic statistic, Material material) { + public void decrementStatistic(final Statistic statistic, final Material material) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public int getStatistic(Statistic statistic, Material material) { + public int getStatistic(final Statistic statistic, final Material material) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void incrementStatistic(Statistic statistic, Material material, int amount) { + public void incrementStatistic(final Statistic statistic, final Material material, final int amount) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void decrementStatistic(Statistic statistic, Material material, int amount) { + public void decrementStatistic(final Statistic statistic, final Material material, final int amount) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void setStatistic(Statistic statistic, Material material, int newValue) { + public void setStatistic(final Statistic statistic, final Material material, final int newValue) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void incrementStatistic(Statistic statistic, EntityType entityType) { + public void incrementStatistic(final Statistic statistic, final EntityType entityType) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void decrementStatistic(Statistic statistic, EntityType entityType) { + public void decrementStatistic(final Statistic statistic, final EntityType entityType) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public int getStatistic(Statistic statistic, EntityType entityType) { + public int getStatistic(final Statistic statistic, final EntityType entityType) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void incrementStatistic(Statistic statistic, EntityType entityType, int amount) { + public void incrementStatistic(final Statistic statistic, final EntityType entityType, final int amount) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void decrementStatistic(Statistic statistic, EntityType entityType, int amount) { + public void decrementStatistic(final Statistic statistic, final EntityType entityType, final int amount) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void setStatistic(Statistic statistic, EntityType entityType, int newValue) { + public void setStatistic(final Statistic statistic, final EntityType entityType, final int newValue) { throw new UnsupportedOperationException("Not supported yet."); } + + + }; } @@ -692,12 +726,12 @@ public class FakeServer implements Server { } @Override - public void banIP(String string) { + public void banIP(final String string) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void unbanIP(String string) { + public void unbanIP(final String string) { throw new UnsupportedOperationException("Not supported yet."); } @@ -712,7 +746,7 @@ public class FakeServer implements Server { } @Override - public void setDefaultGameMode(GameMode gamemode) { + public void setDefaultGameMode(final GameMode gamemode) { throw new UnsupportedOperationException("Not supported yet."); } @@ -720,13 +754,13 @@ public class FakeServer implements Server { public ConsoleCommandSender getConsoleSender() { return new ConsoleCommandSender() { @Override - public void sendMessage(String message) { + public void sendMessage(final String message) { System.out.println("Console message: " + message); } @Override - public void sendMessage(String[] messages) { - for (String message : messages) { + public void sendMessage(final String[] messages) { + for (final String message : messages) { System.out.println("Console message: " + message); } } @@ -747,47 +781,47 @@ public class FakeServer implements Server { } @Override - public boolean isPermissionSet(String name) { + public boolean isPermissionSet(final String name) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean isPermissionSet(Permission perm) { + public boolean isPermissionSet(final Permission perm) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean hasPermission(String name) { + public boolean hasPermission(final String name) { return true; } @Override - public boolean hasPermission(Permission perm) { + public boolean hasPermission(final Permission perm) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) { + public PermissionAttachment addAttachment(final Plugin plugin, final String name, final boolean value) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public PermissionAttachment addAttachment(Plugin plugin) { + public PermissionAttachment addAttachment(final Plugin plugin) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) { + public PermissionAttachment addAttachment(final Plugin plugin, final String name, final boolean value, final int ticks) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public PermissionAttachment addAttachment(Plugin plugin, int ticks) { + public PermissionAttachment addAttachment(final Plugin plugin, final int ticks) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void removeAttachment(PermissionAttachment attachment) { + public void removeAttachment(final PermissionAttachment attachment) { throw new UnsupportedOperationException("Not supported yet."); } @@ -806,40 +840,41 @@ public class FakeServer implements Server { return true; } - @Override - public void setOp(boolean value) { - throw new UnsupportedOperationException("Not supported yet."); - } - @Override public boolean isConversing() { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void acceptConversationInput(String input) { + public void acceptConversationInput(final String input) { + throw new UnsupportedOperationException("Not supported yet."); + } @Override + public void setOp(final boolean value) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean beginConversation(Conversation conversation) { + public boolean beginConversation(final Conversation conversation) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void abandonConversation(Conversation conversation) { + public void abandonConversation(final Conversation conversation) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void abandonConversation(Conversation conversation, ConversationAbandonedEvent details) { + public void abandonConversation(final Conversation conversation, final ConversationAbandonedEvent details) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void sendRawMessage(String message) { + public void sendRawMessage(final String message) { throw new UnsupportedOperationException("Not supported yet."); } + + + }; } @@ -874,7 +909,7 @@ public class FakeServer implements Server { } @Override - public void sendPluginMessage(Plugin plugin, String string, byte[] bytes) { + public void sendPluginMessage(final Plugin plugin, final String string, final byte[] bytes) { throw new UnsupportedOperationException("Not supported yet."); } @@ -909,12 +944,12 @@ public class FakeServer implements Server { } @Override - public List getRecipesFor(ItemStack is) { + public List getRecipesFor(final ItemStack is) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Recipe getRecipe(NamespacedKey namespacedKey) { + public Recipe getRecipe(final NamespacedKey namespacedKey) { throw new UnsupportedOperationException("Not supported yet."); } @@ -934,7 +969,7 @@ public class FakeServer implements Server { } @Override - public boolean removeRecipe(NamespacedKey key) { + public boolean removeRecipe(final NamespacedKey key) { throw new UnsupportedOperationException("Not supported yet."); } @@ -944,22 +979,22 @@ public class FakeServer implements Server { } @Override - public Inventory createInventory(InventoryHolder ih, InventoryType it) { + public Inventory createInventory(final InventoryHolder ih, final InventoryType it) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Inventory createInventory(InventoryHolder ih, int i) { + public Inventory createInventory(final InventoryHolder ih, final int i) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Inventory createInventory(InventoryHolder ih, int i, String string) { + public Inventory createInventory(final InventoryHolder ih, final int i, final String string) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Merchant createMerchant(String s) { + public Merchant createMerchant(final String s) { throw new UnsupportedOperationException("Not supported yet."); } @@ -1039,17 +1074,12 @@ public class FakeServer implements Server { } @Override - public CachedServerIcon loadServerIcon(File file) { + public CachedServerIcon loadServerIcon(final File file) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public CachedServerIcon loadServerIcon(BufferedImage bufferedImage) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setIdleTimeout(int i) { + public CachedServerIcon loadServerIcon(final BufferedImage bufferedImage) { throw new UnsupportedOperationException("Not supported yet."); } @@ -1059,17 +1089,22 @@ public class FakeServer implements Server { } @Override - public ChunkGenerator.ChunkData createChunkData(World world) { + public void setIdleTimeout(final int i) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public BossBar createBossBar(String s, BarColor barColor, BarStyle barStyle, BarFlag... barFlags) { + public ChunkGenerator.ChunkData createChunkData(final World world) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public KeyedBossBar createBossBar(NamespacedKey key, String title, BarColor color, BarStyle style, BarFlag... flags) { + public BossBar createBossBar(final String s, final BarColor barColor, final BarStyle barStyle, final BarFlag... barFlags) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public KeyedBossBar createBossBar(final NamespacedKey key, final String title, final BarColor color, final BarStyle style, final BarFlag... flags) { throw new UnsupportedOperationException("Not supported yet."); } @@ -1079,12 +1114,12 @@ public class FakeServer implements Server { } @Override - public KeyedBossBar getBossBar(NamespacedKey key) { + public KeyedBossBar getBossBar(final NamespacedKey key) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean removeBossBar(NamespacedKey key) { + public boolean removeBossBar(final NamespacedKey key) { throw new UnsupportedOperationException("Not supported yet."); } @@ -1100,13 +1135,13 @@ public class FakeServer implements Server { } @Override - public BanList getBanList(BanList.Type arg0) { + public BanList getBanList(final BanList.Type arg0) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Player getPlayer(UUID arg0) { - for (Player player : players) { + public Player getPlayer(final UUID arg0) { + for (final Player player : players) { if (player.getUniqueId().equals(arg0)) { return player; } @@ -1115,7 +1150,7 @@ public class FakeServer implements Server { } @Override - public org.bukkit.OfflinePlayer getOfflinePlayer(UUID arg0) { + public org.bukkit.OfflinePlayer getOfflinePlayer(final UUID arg0) { if (arg0.toString().equalsIgnoreCase("3c9ebe1a-9098-43fd-bc0c-a369b76817ba")) { return createOPlayer("testPlayer1"); } @@ -1126,7 +1161,7 @@ public class FakeServer implements Server { } @Override - public Inventory createInventory(InventoryHolder arg0, InventoryType arg1, String arg2) { + public Inventory createInventory(final InventoryHolder arg0, final InventoryType arg1, final String arg2) { throw new UnsupportedOperationException("Not supported yet."); } @@ -1136,12 +1171,12 @@ public class FakeServer implements Server { } @Override - public Entity getEntity(UUID uuid) { + public Entity getEntity(final UUID uuid) { return getPlayer(uuid); } @Override - public Advancement getAdvancement(NamespacedKey key) { + public Advancement getAdvancement(final NamespacedKey key) { throw new UnsupportedOperationException("Not supported yet."); } @@ -1151,44 +1186,54 @@ public class FakeServer implements Server { } @Override - public BlockData createBlockData(Material material) { + public BlockData createBlockData(final Material material) { return null; } @Override - public BlockData createBlockData(Material material, Consumer consumer) { + public BlockData createBlockData(final Material material, final Consumer consumer) { return null; } @Override - public BlockData createBlockData(String data) throws IllegalArgumentException { + public BlockData createBlockData(final String data) throws IllegalArgumentException { return null; } @Override - public BlockData createBlockData(Material material, String data) throws IllegalArgumentException { + public BlockData createBlockData(final Material material, final String data) throws IllegalArgumentException { return null; } @Override - public Tag getTag(String s, NamespacedKey namespacedKey, Class aClass) { + public Tag getTag(final String s, final NamespacedKey namespacedKey, final Class aClass) { throw new UnsupportedOperationException("Not supported yet."); } - public Iterable> getTags(String registry, Class clazz) { + public Iterable> getTags(final String registry, final Class clazz) { throw new UnsupportedOperationException("Not supported yet."); } - class FakePluginManager implements PluginManager { - ArrayList listeners = new ArrayList<>(); + @Override + public LootTable getLootTable(final NamespacedKey arg0) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public List selectEntities(final CommandSender sender, final String selector) throws IllegalArgumentException { + throw new UnsupportedOperationException("Not supported yet."); + } + + static class FakePluginManager implements PluginManager { + final ArrayList listeners = new ArrayList<>(); @Override - public void registerInterface(Class loader) throws IllegalArgumentException { + public void registerInterface(final Class loader) throws IllegalArgumentException { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Plugin getPlugin(String name) { + public Plugin getPlugin(final String name) { throw new UnsupportedOperationException("Not supported yet."); } @@ -1198,22 +1243,22 @@ public class FakeServer implements Server { } @Override - public boolean isPluginEnabled(String name) { + public boolean isPluginEnabled(final String name) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public boolean isPluginEnabled(Plugin plugin) { + public boolean isPluginEnabled(final Plugin plugin) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Plugin loadPlugin(File file) throws UnknownDependencyException { + public Plugin loadPlugin(final File file) throws UnknownDependencyException { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Plugin[] loadPlugins(File directory) { + public Plugin[] loadPlugins(final File directory) { throw new UnsupportedOperationException("Not supported yet."); } @@ -1228,15 +1273,15 @@ public class FakeServer implements Server { } @Override - public void callEvent(Event event) throws IllegalStateException { + public void callEvent(final Event event) throws IllegalStateException { Logger.getLogger("Minecraft").info("Called event " + event.getEventName()); if (event instanceof PlayerJoinEvent) { - for (RegisteredListener listener : listeners) { + for (final RegisteredListener listener : listeners) { if (listener.getListener() instanceof EssentialsPlayerListener) { - PlayerJoinEvent jEvent = (PlayerJoinEvent) event; - EssentialsPlayerListener epl = (EssentialsPlayerListener) listener.getListener(); + final PlayerJoinEvent jEvent = (PlayerJoinEvent) event; + final EssentialsPlayerListener epl = (EssentialsPlayerListener) listener.getListener(); epl.onPlayerJoin(jEvent); - Essentials ess = (Essentials) listener.getPlugin(); + final Essentials ess = (Essentials) listener.getPlugin(); ess.getLogger().info("Sending join event to Essentials"); ess.getUser(jEvent.getPlayer()); } @@ -1245,87 +1290,87 @@ public class FakeServer implements Server { } @Override - public void registerEvents(Listener listener, Plugin plugin) { + public void registerEvents(final Listener listener, final Plugin plugin) { listeners.add(new RegisteredListener(listener, null, null, plugin, false)); } @Override - public void registerEvent(Class event, Listener listener, EventPriority priority, EventExecutor executor, Plugin plugin) { + public void registerEvent(final Class event, final Listener listener, final EventPriority priority, final EventExecutor executor, final Plugin plugin) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void registerEvent(Class event, Listener listener, EventPriority priority, EventExecutor executor, Plugin plugin, boolean ignoreCancelled) { + public void registerEvent(final Class event, final Listener listener, final EventPriority priority, final EventExecutor executor, final Plugin plugin, final boolean ignoreCancelled) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void enablePlugin(Plugin plugin) { + public void enablePlugin(final Plugin plugin) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void disablePlugin(Plugin plugin) { + public void disablePlugin(final Plugin plugin) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Permission getPermission(String name) { + public Permission getPermission(final String name) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void addPermission(Permission perm) { + public void addPermission(final Permission perm) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void removePermission(Permission perm) { + public void removePermission(final Permission perm) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void removePermission(String name) { + public void removePermission(final String name) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Set getDefaultPermissions(boolean op) { + public Set getDefaultPermissions(final boolean op) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void recalculatePermissionDefaults(Permission perm) { + public void recalculatePermissionDefaults(final Permission perm) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void subscribeToPermission(String permission, Permissible permissible) { + public void subscribeToPermission(final String permission, final Permissible permissible) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void unsubscribeFromPermission(String permission, Permissible permissible) { + public void unsubscribeFromPermission(final String permission, final Permissible permissible) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Set getPermissionSubscriptions(String permission) { + public Set getPermissionSubscriptions(final String permission) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void subscribeToDefaultPerms(boolean op, Permissible permissible) { + public void subscribeToDefaultPerms(final boolean op, final Permissible permissible) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void unsubscribeFromDefaultPerms(boolean op, Permissible permissible) { + public void unsubscribeFromDefaultPerms(final boolean op, final Permissible permissible) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public Set getDefaultPermSubscriptions(boolean op) { + public Set getDefaultPermSubscriptions(final boolean op) { throw new UnsupportedOperationException("Not supported yet."); } @@ -1340,14 +1385,4 @@ public class FakeServer implements Server { } } - @Override - public LootTable getLootTable(NamespacedKey arg0) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public List selectEntities(CommandSender sender, String selector) throws IllegalArgumentException { - throw new UnsupportedOperationException("Not supported yet."); - } - } diff --git a/Essentials/test/com/earth2me/essentials/MessagingTest.java b/Essentials/test/com/earth2me/essentials/MessagingTest.java index b90b9ea21..0248b92b0 100644 --- a/Essentials/test/com/earth2me/essentials/MessagingTest.java +++ b/Essentials/test/com/earth2me/essentials/MessagingTest.java @@ -1,12 +1,7 @@ package com.earth2me.essentials; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - import com.earth2me.essentials.commands.IEssentialsCommand; import com.earth2me.essentials.commands.NoChargeException; - import org.bukkit.World.Environment; import org.bukkit.command.CommandSender; import org.bukkit.plugin.InvalidDescriptionException; @@ -14,6 +9,9 @@ import org.junit.Test; import java.io.IOException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; public class MessagingTest { @@ -27,9 +25,9 @@ public class MessagingTest { ess = new Essentials(server); try { ess.setupForTesting(server); - } catch (InvalidDescriptionException ex) { + } catch (final InvalidDescriptionException ex) { fail("InvalidDescriptionException"); - } catch (IOException ex) { + } catch (final IOException ex) { fail("IOException"); } base1 = server.createPlayer("testPlayer1"); @@ -37,43 +35,45 @@ public class MessagingTest { ess.getUser(base1); } - private void runCommand(String command, User user, String args) throws Exception { + private void runCommand(final String command, final User user, final String args) throws Exception { runCommand(command, user, args.split("\\s+")); } - private void runCommand(String command, User user, String[] args) throws Exception { - IEssentialsCommand cmd; + private void runCommand(final String command, final User user, final String[] args) throws Exception { + final IEssentialsCommand cmd; try { cmd = (IEssentialsCommand) Essentials.class.getClassLoader() .loadClass("com.earth2me.essentials.commands.Command" + command).newInstance(); cmd.setEssentials(ess); cmd.run(server, user, command, null, args); - } catch (NoChargeException ignored) {} + } catch (final NoChargeException ignored) { + } } - private void runConsoleCommand(String command, String args) throws Exception { + private void runConsoleCommand(final String command, final String args) throws Exception { runConsoleCommand(command, args.split("\\s+")); } - private void runConsoleCommand(String command, String[] args) throws Exception { - IEssentialsCommand cmd; + private void runConsoleCommand(final String command, final String[] args) throws Exception { + final IEssentialsCommand cmd; - CommandSender sender = server.getConsoleSender(); + final CommandSender sender = server.getConsoleSender(); try { cmd = (IEssentialsCommand) Essentials.class.getClassLoader() .loadClass("com.earth2me.essentials.commands.Command" + command).newInstance(); cmd.setEssentials(ess); cmd.run(server, new CommandSource(sender), command, null, args); - } catch (NoChargeException ignored) {} + } catch (final NoChargeException ignored) { + } } @Test(expected = Exception.class) // I really don't like this, but see note below about console reply public void testNullLastMessageReplyRecipient() throws Exception { - User user1 = ess.getUser(base1); - Console console = Console.getInstance(); + final User user1 = ess.getUser(base1); + final Console console = Console.getInstance(); if (ess.getSettings().isLastMessageReplyRecipient()) { assertNull(console.getReplyRecipient()); // console never messaged or received messages from anyone. @@ -95,8 +95,8 @@ public class MessagingTest { @Test public void testNonNullLastMessageReplyRecipient() throws Exception { - User user1 = ess.getUser(base1); - Console console = Console.getInstance(); + final User user1 = ess.getUser(base1); + final Console console = Console.getInstance(); if (ess.getSettings().isLastMessageReplyRecipient()) { assertNull(console.getReplyRecipient()); // console never messaged or received messages from anyone. diff --git a/Essentials/test/com/earth2me/essentials/StorageTest.java b/Essentials/test/com/earth2me/essentials/StorageTest.java index 3a10abcab..07e609d5c 100644 --- a/Essentials/test/com/earth2me/essentials/StorageTest.java +++ b/Essentials/test/com/earth2me/essentials/StorageTest.java @@ -9,11 +9,10 @@ import org.junit.Test; import java.io.IOException; - public class StorageTest { - private Essentials ess; - private FakeServer server; - private World world; + private final Essentials ess; + private final FakeServer server; + private final World world; public StorageTest() { server = new FakeServer(); @@ -21,21 +20,21 @@ public class StorageTest { ess = new Essentials(server); try { ess.setupForTesting(server); - } catch (InvalidDescriptionException ex) { + } catch (final InvalidDescriptionException ex) { Assert.fail("InvalidDescriptionException"); - } catch (IOException ex) { + } catch (final IOException ex) { Assert.fail("IOException"); } } @Test public void testOldUserdata() { - ExecuteTimer ext = new ExecuteTimer(); + final ExecuteTimer ext = new ExecuteTimer(); ext.start(); - OfflinePlayer base1 = server.createPlayer("testPlayer1"); + final OfflinePlayer base1 = server.createPlayer("testPlayer1"); server.addPlayer(base1); ext.mark("fake user created"); - UserData user = ess.getUser(base1); + final UserData user = ess.getUser(base1); ext.mark("load empty user"); for (int j = 0; j < 1; j++) { user.setHome("home", new Location(world, j, j, j)); diff --git a/Essentials/test/com/earth2me/essentials/ToggleTest.java b/Essentials/test/com/earth2me/essentials/ToggleTest.java index 7250ce566..87d87aa07 100644 --- a/Essentials/test/com/earth2me/essentials/ToggleTest.java +++ b/Essentials/test/com/earth2me/essentials/ToggleTest.java @@ -9,22 +9,21 @@ import org.bukkit.plugin.InvalidDescriptionException; import java.io.IOException; - public class ToggleTest extends TestCase { private final OfflinePlayer base1; private final Essentials ess; private final FakeServer server; - public ToggleTest(String testName) { + public ToggleTest(final String testName) { super(testName); server = new FakeServer(); server.createWorld("testWorld", Environment.NORMAL); ess = new Essentials(server); try { ess.setupForTesting(server); - } catch (InvalidDescriptionException ex) { + } catch (final InvalidDescriptionException ex) { fail("InvalidDescriptionException"); - } catch (IOException ex) { + } catch (final IOException ex) { fail("IOException"); } base1 = server.createPlayer("testPlayer1"); @@ -32,140 +31,142 @@ public class ToggleTest extends TestCase { ess.getUser(base1); } - private void runCommand(String command, User user, String[] args) throws Exception { - IEssentialsCommand cmd; + private void runCommand(final String command, final User user, final String[] args) throws Exception { + final IEssentialsCommand cmd; try { cmd = (IEssentialsCommand) Essentials.class.getClassLoader().loadClass("com.earth2me.essentials.commands.Command" + command).newInstance(); cmd.setEssentials(ess); cmd.run(server, user, command, null, args); - } catch (NoChargeException ignored) {} + } catch (final NoChargeException ignored) { + } } - private void runConsoleCommand(String command, String[] args) throws Exception { - IEssentialsCommand cmd; + private void runConsoleCommand(final String command, final String[] args) throws Exception { + final IEssentialsCommand cmd; - CommandSender sender = server.getConsoleSender(); + final CommandSender sender = server.getConsoleSender(); try { cmd = (IEssentialsCommand) Essentials.class.getClassLoader().loadClass("com.earth2me.essentials.commands.Command" + command).newInstance(); cmd.setEssentials(ess); cmd.run(server, new CommandSource(sender), command, null, args); - } catch (NoChargeException ignored) {} + } catch (final NoChargeException ignored) { + } } public void testFlyToggle() throws Exception { - User user = ess.getUser(base1); + final User user = ess.getUser(base1); assertFalse(user.getBase().getAllowFlight()); - runCommand("fly", user, new String[]{"on"}); + runCommand("fly", user, new String[] {"on"}); assertTrue(user.getBase().getAllowFlight()); - runCommand("fly", user, new String[]{"on"}); + runCommand("fly", user, new String[] {"on"}); assertTrue(user.getBase().getAllowFlight()); - runCommand("fly", user, new String[]{"off"}); + runCommand("fly", user, new String[] {"off"}); assertFalse(user.getBase().getAllowFlight()); - runCommand("fly", user, new String[]{"off"}); + runCommand("fly", user, new String[] {"off"}); assertFalse(user.getBase().getAllowFlight()); - runCommand("fly", user, new String[]{}); + runCommand("fly", user, new String[] {}); assertTrue(user.getBase().getAllowFlight()); - runCommand("fly", user, new String[]{}); + runCommand("fly", user, new String[] {}); assertFalse(user.getBase().getAllowFlight()); } public void testFlyDisOnToggle() throws Exception { - User user = ess.getUser(base1); + final User user = ess.getUser(base1); user.getBase().setAllowFlight(true); user.getBase().setFlying(true); assertTrue(user.getBase().isFlying()); - runCommand("fly", user, new String[]{}); + runCommand("fly", user, new String[] {}); assertFalse(user.getBase().getAllowFlight()); assertFalse(user.getBase().isFlying()); } public void testGodToggle() throws Exception { - User user = ess.getUser(base1); + final User user = ess.getUser(base1); assertFalse(user.isGodModeEnabled()); - runCommand("god", user, new String[]{"on"}); + runCommand("god", user, new String[] {"on"}); assertTrue(user.isGodModeEnabled()); - runCommand("god", user, new String[]{"on"}); + runCommand("god", user, new String[] {"on"}); assertTrue(user.isGodModeEnabled()); - runCommand("god", user, new String[]{"off"}); + runCommand("god", user, new String[] {"off"}); assertFalse(user.isGodModeEnabled()); - runCommand("god", user, new String[]{"off"}); + runCommand("god", user, new String[] {"off"}); assertFalse(user.isGodModeEnabled()); - runCommand("god", user, new String[]{}); + runCommand("god", user, new String[] {}); assertTrue(user.isGodModeEnabled()); - runCommand("god", user, new String[]{}); + runCommand("god", user, new String[] {}); assertFalse(user.isGodModeEnabled()); } public void testConsoleToggle() throws Exception { - User user = ess.getUser(base1); + final User user = ess.getUser(base1); assertFalse(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[]{base1.getName(), "on"}); + runConsoleCommand("fly", new String[] {base1.getName(), "on"}); assertTrue(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[]{base1.getName(), "on"}); + runConsoleCommand("fly", new String[] {base1.getName(), "on"}); assertTrue(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[]{base1.getName(), "off"}); + runConsoleCommand("fly", new String[] {base1.getName(), "off"}); assertFalse(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[]{base1.getName(), "off"}); + runConsoleCommand("fly", new String[] {base1.getName(), "off"}); assertFalse(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[]{base1.getName()}); + runConsoleCommand("fly", new String[] {base1.getName()}); assertTrue(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[]{base1.getName()}); + runConsoleCommand("fly", new String[] {base1.getName()}); assertFalse(user.getBase().getAllowFlight()); } public void testAliasesToggle() throws Exception { - User user = ess.getUser(base1); + final User user = ess.getUser(base1); assertFalse(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[]{base1.getName(), "enable"}); + runConsoleCommand("fly", new String[] {base1.getName(), "enable"}); assertTrue(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[]{base1.getName(), "enable"}); + runConsoleCommand("fly", new String[] {base1.getName(), "enable"}); assertTrue(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[]{base1.getName(), "disable"}); + runConsoleCommand("fly", new String[] {base1.getName(), "disable"}); assertFalse(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[]{base1.getName(), "disable"}); + runConsoleCommand("fly", new String[] {base1.getName(), "disable"}); assertFalse(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[]{base1.getName(), "1"}); + runConsoleCommand("fly", new String[] {base1.getName(), "1"}); assertTrue(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[]{base1.getName(), "1"}); + runConsoleCommand("fly", new String[] {base1.getName(), "1"}); assertTrue(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[]{base1.getName(), "0"}); + runConsoleCommand("fly", new String[] {base1.getName(), "0"}); assertFalse(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[]{base1.getName(), "0"}); + runConsoleCommand("fly", new String[] {base1.getName(), "0"}); assertFalse(user.getBase().getAllowFlight()); } diff --git a/Essentials/test/com/earth2me/essentials/UserTest.java b/Essentials/test/com/earth2me/essentials/UserTest.java index 0099dd4c3..336bcba9f 100644 --- a/Essentials/test/com/earth2me/essentials/UserTest.java +++ b/Essentials/test/com/earth2me/essentials/UserTest.java @@ -9,22 +9,21 @@ import org.bukkit.plugin.InvalidDescriptionException; import java.io.IOException; import java.math.BigDecimal; - public class UserTest extends TestCase { private final OfflinePlayer base1; private final Essentials ess; private final FakeServer server; - public UserTest(String testName) { + public UserTest(final String testName) { super(testName); server = new FakeServer(); server.createWorld("testWorld", Environment.NORMAL); ess = new Essentials(server); try { ess.setupForTesting(server); - } catch (InvalidDescriptionException ex) { + } catch (final InvalidDescriptionException ex) { fail("InvalidDescriptionException"); - } catch (IOException ex) { + } catch (final IOException ex) { fail("IOException"); } base1 = server.createPlayer("testPlayer1"); @@ -32,23 +31,23 @@ public class UserTest extends TestCase { ess.getUser(base1); } - private void should(String what) { + private void should(final String what) { System.out.println(getName() + " should " + what); } public void testUpdate() { - OfflinePlayer base1alt = server.createPlayer(base1.getName()); + final OfflinePlayer base1alt = server.createPlayer(base1.getName()); assertEquals(base1alt, ess.getUser(base1alt).getBase()); } public void testHome() { - User user = ess.getUser(base1); - Location loc = base1.getLocation(); + final User user = ess.getUser(base1); + final Location loc = base1.getLocation(); user.setHome("home", loc); - OfflinePlayer base2 = server.createPlayer(base1.getName()); - User user2 = ess.getUser(base2); + final OfflinePlayer base2 = server.createPlayer(base1.getName()); + final User user2 = ess.getUser(base2); - Location home = user2.getHome(loc); + final Location home = user2.getHome(loc); assertNotNull(home); assertEquals(loc.getWorld().getName(), home.getWorld().getName()); assertEquals(loc.getX(), home.getX()); @@ -60,7 +59,7 @@ public class UserTest extends TestCase { public void testMoney() { should("properly set, take, give, and get money"); - User user = ess.getUser(base1); + final User user = ess.getUser(base1); BigDecimal i = new BigDecimal("100.5"); try { user.setMoney(i); @@ -68,7 +67,7 @@ public class UserTest extends TestCase { i = i.subtract(BigDecimal.valueOf(50)); user.giveMoney(new BigDecimal(25)); i = i.add(BigDecimal.valueOf(25)); - } catch (MaxMoneyException ex) { + } catch (final MaxMoneyException ex) { fail(); } diff --git a/Essentials/test/com/earth2me/essentials/UtilTest.java b/Essentials/test/com/earth2me/essentials/UtilTest.java index 5fc56e2b5..8375a3772 100644 --- a/Essentials/test/com/earth2me/essentials/UtilTest.java +++ b/Essentials/test/com/earth2me/essentials/UtilTest.java @@ -13,26 +13,30 @@ import java.util.GregorianCalendar; import java.util.HashSet; import java.util.Set; - public class UtilTest extends TestCase { public UtilTest() { - FakeServer server = new FakeServer(); + final FakeServer server = new FakeServer(); server.createWorld("testWorld", Environment.NORMAL); - Essentials ess = new Essentials(server); + final Essentials ess = new Essentials(server); try { ess.setupForTesting(server); - } catch (InvalidDescriptionException ex) { + } catch (final InvalidDescriptionException ex) { fail("InvalidDescriptionException"); - } catch (IOException ex) { + } catch (final IOException ex) { fail("IOException"); } } public void testSafeLocation() { - Set testSet = new HashSet<>(); + final Set testSet = new HashSet<>(); int count = 0; - int x, y, z, origX, origY, origZ; + int x; + int y; + int z; + final int origX; + final int origY; + final int origZ; x = y = z = origX = origY = origZ = 0; int i = 0; while (true) { @@ -49,13 +53,13 @@ public class UtilTest extends TestCase { assertTrue(testSet.contains("0:0:0")); assertTrue(testSet.contains("3:3:3")); assertEquals(testSet.size(), count); - int diameter = LocationUtil.RADIUS * 2 + 1; + final int diameter = LocationUtil.RADIUS * 2 + 1; assertEquals(diameter * diameter * diameter, count); } public void testFDDnow() { - Calendar c = new GregorianCalendar(); - String resp = DateUtil.formatDateDiff(c, c); + final Calendar c = new GregorianCalendar(); + final String resp = DateUtil.formatDateDiff(c, c); assertEquals(resp, "now"); } diff --git a/Essentials/test/com/earth2me/essentials/utils/FormatUtilTest.java b/Essentials/test/com/earth2me/essentials/utils/FormatUtilTest.java index 4f6abd31a..8c2c27580 100644 --- a/Essentials/test/com/earth2me/essentials/utils/FormatUtilTest.java +++ b/Essentials/test/com/earth2me/essentials/utils/FormatUtilTest.java @@ -1,10 +1,11 @@ package com.earth2me.essentials.utils; import net.ess3.api.IUser; - import org.junit.Test; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class FormatUtilTest { @@ -105,8 +106,8 @@ public class FormatUtilTest { checkUnformatPerms("§x§b§3§4§2§f§5Th§eis is §aa §dmessag§5e", "&#b342f5Th&eis is a message", "rgb", "yellow"); } - private IUser getMockUser(String... perms) { - IUser user = mock(IUser.class); + private IUser getMockUser(final String... perms) { + final IUser user = mock(IUser.class); for (String perm : perms) { if (perm.startsWith("-")) { // Negated perms @@ -121,11 +122,11 @@ public class FormatUtilTest { return user; } - private void checkFormatPerms(String input, String expectedOutput, String... perms) { + private void checkFormatPerms(final String input, final String expectedOutput, final String... perms) { assertEquals(expectedOutput, FormatUtil.formatString(getMockUser(perms), "essentials.chat", input)); } - private void checkUnformatPerms(String input, String expectedOutput, String... perms) { + private void checkUnformatPerms(final String input, final String expectedOutput, final String... perms) { assertEquals(expectedOutput, FormatUtil.unformatString(getMockUser(perms), "essentials.chat", input)); } } diff --git a/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/AntiBuildConfig.java b/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/AntiBuildConfig.java index 3cdd68855..a03dbdcf5 100644 --- a/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/AntiBuildConfig.java +++ b/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/AntiBuildConfig.java @@ -1,6 +1,5 @@ package com.earth2me.essentials.antibuild; - public enum AntiBuildConfig { disable_build("protect.disable.build", true), disable_use("protect.disable.use", true), diff --git a/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsAntiBuild.java b/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsAntiBuild.java index 465b65a12..6a65eafca 100644 --- a/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsAntiBuild.java +++ b/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsAntiBuild.java @@ -1,6 +1,5 @@ package com.earth2me.essentials.antibuild; -import com.earth2me.essentials.metrics.Metrics; import com.earth2me.essentials.metrics.MetricsWrapper; import org.bukkit.Material; import org.bukkit.plugin.Plugin; @@ -11,13 +10,16 @@ import java.util.EnumMap; import java.util.List; import java.util.Map; - public class EssentialsAntiBuild extends JavaPlugin implements IAntiBuild { private final transient Map settingsBoolean = new EnumMap<>(AntiBuildConfig.class); private final transient Map> settingsList = new EnumMap<>(AntiBuildConfig.class); private transient EssentialsConnect ess = null; private transient MetricsWrapper metrics = null; + static String getNameForType(final Material type) { + return type.toString().toLowerCase().replaceAll("_", " "); + } + @Override public void onEnable() { final PluginManager pm = this.getServer().getPluginManager(); @@ -61,8 +63,4 @@ public class EssentialsAntiBuild extends JavaPlugin implements IAntiBuild { final Boolean bool = settingsBoolean.get(protectConfig); return bool == null ? protectConfig.getDefaultValueBoolean() : bool; } - - static String getNameForType(Material type) { - return type.toString().toLowerCase().replaceAll("_", " "); - } } diff --git a/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsAntiBuildListener.java b/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsAntiBuildListener.java index 3e626013d..5edd6ebc7 100644 --- a/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsAntiBuildListener.java +++ b/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsAntiBuildListener.java @@ -5,16 +5,31 @@ import com.earth2me.essentials.utils.VersionUtil; import net.ess3.api.IEssentials; import org.bukkit.Material; import org.bukkit.block.Block; -import org.bukkit.entity.*; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.EnderCrystal; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.ItemFrame; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; 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.BlockDispenseEvent; +import org.bukkit.event.block.BlockPistonExtendEvent; +import org.bukkit.event.block.BlockPistonRetractEvent; +import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityPickupItemEvent; import org.bukkit.event.hanging.HangingBreakByEntityEvent; import org.bukkit.event.inventory.CraftItemEvent; -import org.bukkit.event.player.*; +import org.bukkit.event.player.PlayerDropItemEvent; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.inventory.ItemStack; import java.util.logging.Level; @@ -22,7 +37,6 @@ import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; - public class EssentialsAntiBuildListener implements Listener { private static final Logger logger = Logger.getLogger("EssentialsAntiBuild"); final private transient IAntiBuild prot; @@ -43,7 +57,7 @@ public class EssentialsAntiBuildListener implements Listener { try { Class.forName("org.bukkit.event.entity.EntityPickupItemEvent"); return true; - } catch (ClassNotFoundException ignored) { + } catch (final ClassNotFoundException ignored) { return false; } } @@ -77,7 +91,6 @@ public class EssentialsAntiBuildListener implements Listener { } } - return user.isAuthorized(blockPerm); } @@ -222,8 +235,8 @@ public class EssentialsAntiBuildListener implements Listener { if (event.getDamager() instanceof Player) { player = (Player) event.getDamager(); - } else if (event.getDamager() instanceof Projectile && ((Projectile)event.getDamager()).getShooter() instanceof Player) { - player = (Player) ((Projectile)event.getDamager()).getShooter(); + } else if (event.getDamager() instanceof Projectile && ((Projectile) event.getDamager()).getShooter() instanceof Player) { + player = (Player) ((Projectile) event.getDamager()).getShooter(); } else { return; } @@ -264,7 +277,7 @@ public class EssentialsAntiBuildListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockPistonExtend(final BlockPistonExtendEvent event) { - for (Block block : event.getBlocks()) { + for (final Block block : event.getBlocks()) { if (prot.checkProtectionItems(AntiBuildConfig.blacklist_piston, block.getType())) { event.setCancelled(true); return; @@ -277,7 +290,7 @@ public class EssentialsAntiBuildListener implements Listener { if (!event.isSticky()) { return; } - for (Block block : event.getBlocks()) { + for (final Block block : event.getBlocks()) { if (prot.checkProtectionItems(AntiBuildConfig.blacklist_piston, block.getType())) { event.setCancelled(true); return; @@ -322,7 +335,7 @@ public class EssentialsAntiBuildListener implements Listener { @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onCraftItemEvent(final CraftItemEvent event) { - HumanEntity entity = event.getWhoClicked(); + final HumanEntity entity = event.getWhoClicked(); if (entity instanceof Player) { final User user = ess.getUser((Player) entity); @@ -366,7 +379,7 @@ public class EssentialsAntiBuildListener implements Listener { private class EntityPickupItemListener implements Listener { @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onPlayerPickupItem(EntityPickupItemEvent event) { + public void onPlayerPickupItem(final EntityPickupItemEvent event) { if (!(event.getEntity() instanceof Player)) return; final User user = ess.getUser((Player) event.getEntity()); @@ -383,7 +396,7 @@ public class EssentialsAntiBuildListener implements Listener { private class PlayerPickupItemListener implements Listener { @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onPlayerPickupItem(PlayerPickupItemEvent event) { + public void onPlayerPickupItem(final PlayerPickupItemEvent event) { final User user = ess.getUser(event.getPlayer()); final ItemStack item = event.getItem().getItemStack(); diff --git a/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsConnect.java b/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsConnect.java index 41de89449..c6fa26c41 100644 --- a/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsConnect.java +++ b/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsConnect.java @@ -12,19 +12,18 @@ import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; - class EssentialsConnect { private static final Logger logger = Logger.getLogger("EssentialsAntiBuild"); private final transient IEssentials ess; private final transient IAntiBuild protect; - EssentialsConnect(Plugin essPlugin, Plugin essProtect) { + EssentialsConnect(final Plugin essPlugin, final Plugin essProtect) { if (!essProtect.getDescription().getVersion().equals(essPlugin.getDescription().getVersion())) { logger.log(Level.WARNING, tl("versionMismatchAll")); } ess = (IEssentials) essPlugin; protect = (IAntiBuild) essProtect; - AntiBuildReloader pr = new AntiBuildReloader(); + final AntiBuildReloader pr = new AntiBuildReloader(); pr.reloadConfig(); ess.addReloadListener(pr); } @@ -37,7 +36,7 @@ class EssentialsConnect { final Location loc = user.getLocation(); final String warnMessage = tl("alertFormat", user.getName(), type, item, loc.getWorld().getName() + "," + loc.getBlockX() + "," + loc.getBlockY() + "," + loc.getBlockZ()); logger.log(Level.WARNING, warnMessage); - for (Player p : ess.getServer().getOnlinePlayers()) { + for (final Player p : ess.getServer().getOnlinePlayers()) { final User alertUser = ess.getUser(p); if (alertUser.isAuthorized("essentials.protect.alerts")) { alertUser.sendMessage(warnMessage); @@ -48,7 +47,7 @@ class EssentialsConnect { private class AntiBuildReloader implements IConf { @Override public void reloadConfig() { - for (AntiBuildConfig protectConfig : AntiBuildConfig.values()) { + for (final AntiBuildConfig protectConfig : AntiBuildConfig.values()) { if (protectConfig.isList()) { protect.getSettingsList().put(protectConfig, ess.getSettings().getProtectList(protectConfig.getConfigName())); } else { diff --git a/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/IAntiBuild.java b/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/IAntiBuild.java index cb19d75de..81aa7d3cb 100644 --- a/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/IAntiBuild.java +++ b/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/IAntiBuild.java @@ -6,7 +6,6 @@ import org.bukkit.plugin.Plugin; import java.util.List; import java.util.Map; - public interface IAntiBuild extends Plugin { boolean checkProtectionItems(final AntiBuildConfig list, final Material mat); diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/ChatStore.java b/EssentialsChat/src/com/earth2me/essentials/chat/ChatStore.java index b1bab89f1..915aebf0e 100644 --- a/EssentialsChat/src/com/earth2me/essentials/chat/ChatStore.java +++ b/EssentialsChat/src/com/earth2me/essentials/chat/ChatStore.java @@ -4,7 +4,6 @@ import com.earth2me.essentials.Trade; import com.earth2me.essentials.User; import net.ess3.api.IEssentials; - class ChatStore { private final User user; private final String type; @@ -37,7 +36,7 @@ class ChatStore { return radius; } - void setRadius(long radius) { + void setRadius(final long radius) { this.radius = radius; } } diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChat.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChat.java index 09201a644..29dc149ce 100644 --- a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChat.java +++ b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChat.java @@ -1,6 +1,5 @@ package com.earth2me.essentials.chat; -import com.earth2me.essentials.metrics.Metrics; import com.earth2me.essentials.metrics.MetricsWrapper; import net.ess3.api.IEssentials; import org.bukkit.event.player.AsyncPlayerChatEvent; @@ -14,7 +13,6 @@ import java.util.logging.Level; import static com.earth2me.essentials.I18n.tl; - public class EssentialsChat extends JavaPlugin { private transient MetricsWrapper metrics = null; diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayer.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayer.java index 27ba87998..2d9fd9f03 100644 --- a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayer.java +++ b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayer.java @@ -11,10 +11,9 @@ import org.bukkit.event.player.AsyncPlayerChatEvent; import java.util.Map; import java.util.logging.Logger; - public abstract class EssentialsChatPlayer implements Listener { static final Logger logger = Logger.getLogger("EssentialsChat"); - transient IEssentials ess; + final transient IEssentials ess; final transient Server server; private final transient Map chatStorage; @@ -65,7 +64,7 @@ public abstract class EssentialsChatPlayer implements Listener { boolean charge(final AsyncPlayerChatEvent event, final ChatStore chatStore) { try { charge(chatStore.getUser(), chatStore.getCharge()); - } catch (ChargeException e) { + } catch (final ChargeException e) { ess.showError(chatStore.getUser().getSource(), e, "\\ chat " + chatStore.getLongType()); event.setCancelled(true); return false; diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerHighest.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerHighest.java index 65845e560..f59436f1d 100644 --- a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerHighest.java +++ b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerHighest.java @@ -8,7 +8,6 @@ import org.bukkit.event.player.AsyncPlayerChatEvent; import java.util.Map; - public class EssentialsChatPlayerListenerHighest extends EssentialsChatPlayer { EssentialsChatPlayerListenerHighest(final Server server, final IEssentials ess, final Map chatStorage) { super(server, ess, chatStorage); diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerLowest.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerLowest.java index 1c62cc751..0b280a723 100644 --- a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerLowest.java +++ b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerLowest.java @@ -14,7 +14,6 @@ import org.bukkit.scoreboard.Team; import java.util.Locale; import java.util.Map; - public class EssentialsChatPlayerListenerLowest extends EssentialsChatPlayer { EssentialsChatPlayerListenerLowest(final Server server, final IEssentials ess, final Map chatStorage) { super(server, ess, chatStorage); @@ -40,18 +39,18 @@ public class EssentialsChatPlayerListenerLowest extends EssentialsChatPlayer { // This listener should apply the general chat formatting only...then return control back the event handler event.setMessage(FormatUtil.formatMessage(user, "essentials.chat", event.getMessage())); - if ((ChatColor.stripColor(event.getMessage())).length() == 0) { + if (ChatColor.stripColor(event.getMessage()).length() == 0) { event.setCancelled(true); return; } - String group = user.getGroup(); - String world = user.getWorld().getName(); + final String group = user.getGroup(); + final String world = user.getWorld().getName(); - Player player = user.getBase(); - String prefix = FormatUtil.replaceFormat(ess.getPermissionsHandler().getPrefix(player)); - String suffix = FormatUtil.replaceFormat(ess.getPermissionsHandler().getSuffix(player)); - Team team = player.getScoreboard().getPlayerTeam(player); + final Player player = user.getBase(); + final String prefix = FormatUtil.replaceFormat(ess.getPermissionsHandler().getPrefix(player)); + final String suffix = FormatUtil.replaceFormat(ess.getPermissionsHandler().getSuffix(player)); + final Team team = player.getScoreboard().getPlayerTeam(player); String format = ess.getSettings().getChatFormat(group); format = format.replace("{0}", group); diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerNormal.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerNormal.java index caa977210..8122ddeaa 100644 --- a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerNormal.java +++ b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerNormal.java @@ -11,12 +11,15 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.AsyncPlayerChatEvent; -import java.util.*; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Locale; +import java.util.Map; +import java.util.Set; import java.util.logging.Level; import static com.earth2me.essentials.I18n.tl; - public class EssentialsChatPlayerListenerNormal extends EssentialsChatPlayer { EssentialsChatPlayerListenerNormal(final Server server, final IEssentials ess, final Map chatStorage) { super(server, ess, chatStorage); @@ -62,12 +65,12 @@ public class EssentialsChatPlayerListenerNormal extends EssentialsChatPlayer { return; } - Set outList = event.getRecipients(); - Set spyList = new HashSet<>(); + final Set outList = event.getRecipients(); + final Set spyList = new HashSet<>(); try { outList.add(event.getPlayer()); - } catch (UnsupportedOperationException ex) { + } catch (final UnsupportedOperationException ex) { if (ess.getSettings().isDebug()) { logger.log(Level.INFO, "Plugin triggered custom chat event, local chat handling aborted.", ex); } @@ -105,11 +108,11 @@ public class EssentialsChatPlayerListenerNormal extends EssentialsChatPlayer { user.sendMessage(tl("localNoOne")); } - LocalChatSpyEvent spyEvent = new LocalChatSpyEvent(event.isAsynchronous(), event.getPlayer(), format, event.getMessage(), spyList); + final LocalChatSpyEvent spyEvent = new LocalChatSpyEvent(event.isAsynchronous(), event.getPlayer(), format, event.getMessage(), spyList); server.getPluginManager().callEvent(spyEvent); if (!spyEvent.isCancelled()) { - for (Player onlinePlayer : spyEvent.getRecipients()) { + for (final Player onlinePlayer : spyEvent.getRecipients()) { onlinePlayer.sendMessage(String.format(spyEvent.getFormat(), user.getDisplayName(), spyEvent.getMessage())); } } diff --git a/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIP.java b/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIP.java index d81349448..8cf58ebb1 100644 --- a/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIP.java +++ b/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIP.java @@ -1,19 +1,17 @@ package com.earth2me.essentials.geoip; -import static com.earth2me.essentials.I18n.tl; - -import com.earth2me.essentials.metrics.Metrics; -import java.util.logging.Level; -import java.util.logging.Logger; - import com.earth2me.essentials.metrics.MetricsWrapper; import net.ess3.api.IEssentials; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; +import java.util.logging.Level; +import java.util.logging.Logger; + +import static com.earth2me.essentials.I18n.tl; public class EssentialsGeoIP extends JavaPlugin { - + private transient MetricsWrapper metrics = null; @Override @@ -33,7 +31,6 @@ public class EssentialsGeoIP extends JavaPlugin { final EssentialsGeoIPPlayerListener playerListener = new EssentialsGeoIPPlayerListener(getDataFolder(), ess); pm.registerEvents(playerListener, this); - getLogger().log(Level.INFO, "This product includes GeoLite2 data created by MaxMind, available from http://www.maxmind.com/."); if (metrics == null) { diff --git a/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIPPlayerListener.java b/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIPPlayerListener.java index b969cbf8b..3b1298a0c 100644 --- a/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIPPlayerListener.java +++ b/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIPPlayerListener.java @@ -3,10 +3,13 @@ package com.earth2me.essentials.geoip; import com.earth2me.essentials.EssentialsConf; import com.earth2me.essentials.IConf; import com.earth2me.essentials.User; +import com.ice.tar.TarEntry; +import com.ice.tar.TarInputStream; import com.maxmind.geoip2.DatabaseReader; +import com.maxmind.geoip2.exception.AddressNotFoundException; +import com.maxmind.geoip2.exception.GeoIp2Exception; import com.maxmind.geoip2.model.CityResponse; import com.maxmind.geoip2.model.CountryResponse; -import com.maxmind.geoip2.exception.*; import net.ess3.api.IEssentials; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -14,28 +17,34 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; -import java.io.*; -import java.net.*; -import java.util.logging.Level; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.MalformedURLException; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.net.URL; +import java.net.URLConnection; +import java.util.Arrays; import java.util.Date; +import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.GZIPInputStream; -import java.util.Arrays; -import com.ice.tar.TarInputStream; -import com.ice.tar.TarEntry; import static com.earth2me.essentials.I18n.tl; - public class EssentialsGeoIPPlayerListener implements Listener, IConf { - private DatabaseReader mmreader = null; // initialize maxmind geoip2 reader private static final Logger logger = Logger.getLogger("EssentialsGeoIP"); - private File databaseFile; - private File dataFolder; + private final File dataFolder; private final EssentialsConf config; private final transient IEssentials ess; + private DatabaseReader mmreader = null; // initialize maxmind geoip2 reader + private File databaseFile; - EssentialsGeoIPPlayerListener(File dataFolder, IEssentials ess) { + EssentialsGeoIPPlayerListener(final File dataFolder, final IEssentials ess) { this.ess = ess; this.dataFolder = dataFolder; this.config = new EssentialsConf(new File(dataFolder, "config.yml")); @@ -48,13 +57,13 @@ public class EssentialsGeoIPPlayerListener implements Listener, IConf { ess.runTaskAsynchronously(() -> delayedJoin(event.getPlayer())); } - private void delayedJoin(Player player) { - User u = ess.getUser(player); + private void delayedJoin(final Player player) { + final User u = ess.getUser(player); if (u.isAuthorized("essentials.geoip.hide") || player.getAddress() == null) { return; } - InetAddress address = player.getAddress().getAddress(); - StringBuilder sb = new StringBuilder(); + final InetAddress address = player.getAddress().getAddress(); + final StringBuilder sb = new StringBuilder(); if (mmreader == null) { logger.log(Level.WARNING, tl("geoIpErrorOnJoin", u.getName())); @@ -63,13 +72,13 @@ public class EssentialsGeoIPPlayerListener implements Listener, IConf { try { if (config.getBoolean("database.show-cities", false)) { - CityResponse response = mmreader.city(address); + final CityResponse response = mmreader.city(address); if (response == null) { return; } - String city; - String region; - String country; + final String city; + final String region; + final String country; city = response.getCity().getName(); region = response.getMostSpecificSubdivision().getName(); country = response.getCountry().getName(); @@ -81,14 +90,14 @@ public class EssentialsGeoIPPlayerListener implements Listener, IConf { } sb.append(country); } else { - CountryResponse response = mmreader.country(address); + final CountryResponse response = mmreader.country(address); sb.append(response.getCountry().getName()); } - } catch (AddressNotFoundException ex) { + } catch (final AddressNotFoundException ex) { if (checkIfLocal(address)) { - for (Player online : player.getServer().getOnlinePlayers()) { - User user = ess.getUser(online); + for (final Player online : player.getServer().getOnlinePlayers()) { + final User user = ess.getUser(online); if (user.isAuthorized("essentials.geoip.show")) { user.sendMessage(tl("geoipCantFind", u.getDisplayName())); } @@ -98,7 +107,7 @@ public class EssentialsGeoIPPlayerListener implements Listener, IConf { // GeoIP2 API forced this when address not found in their DB. jar will not complied without this. // TODO: Maybe, we can set a new custom msg about addr-not-found in messages.properties. logger.log(Level.INFO, tl("cantReadGeoIpDB") + " " + ex.getLocalizedMessage()); - } catch (IOException | GeoIp2Exception ex) { + } catch (final IOException | GeoIp2Exception ex) { // GeoIP2 API forced this when address not found in their DB. jar will not complied without this. logger.log(Level.SEVERE, tl("cantReadGeoIpDB") + " " + ex.getLocalizedMessage()); } @@ -106,8 +115,8 @@ public class EssentialsGeoIPPlayerListener implements Listener, IConf { u.setGeoLocation(sb.toString()); } if (config.getBoolean("show-on-login", true) && !u.isHidden()) { - for (Player onlinePlayer : player.getServer().getOnlinePlayers()) { - User user = ess.getUser(onlinePlayer); + for (final Player onlinePlayer : player.getServer().getOnlinePlayers()) { + final User user = ess.getUser(onlinePlayer); if (user.isAuthorized("essentials.geoip.show")) { user.sendMessage(tl("geoipJoinFormat", u.getDisplayName(), sb.toString())); } @@ -129,8 +138,8 @@ public class EssentialsGeoIPPlayerListener implements Listener, IConf { config.set("enable-locale", true); config.save(); // delete old GeoIP.dat fiiles - File oldDatFile = new File(dataFolder, "GeoIP.dat"); - File oldDatFileCity = new File(dataFolder, "GeoIP-City.dat"); + final File oldDatFile = new File(dataFolder, "GeoIP.dat"); + final File oldDatFileCity = new File(dataFolder, "GeoIP-City.dat"); oldDatFile.delete(); oldDatFileCity.delete(); } @@ -149,8 +158,8 @@ public class EssentialsGeoIPPlayerListener implements Listener, IConf { } } else if (config.getBoolean("database.update.enable", true)) { // try to update expired mmdb files - long diff = new Date().getTime() - databaseFile.lastModified(); - if (diff/24/3600/1000>config.getLong("database.update.by-every-x-days", 30)) { + final long diff = new Date().getTime() - databaseFile.lastModified(); + if (diff / 24 / 3600 / 1000 > config.getLong("database.update.by-every-x-days", 30)) { downloadDatabase(); } } @@ -163,11 +172,11 @@ public class EssentialsGeoIPPlayerListener implements Listener, IConf { if ("zh".equalsIgnoreCase(locale)) { locale = "zh-CN"; } - mmreader = new DatabaseReader.Builder(databaseFile).locales(Arrays.asList(locale,"en")).build(); + mmreader = new DatabaseReader.Builder(databaseFile).locales(Arrays.asList(locale, "en")).build(); } else { mmreader = new DatabaseReader.Builder(databaseFile).build(); } - } catch (IOException ex) { + } catch (final IOException ex) { logger.log(Level.SEVERE, tl("cantReadGeoIpDB"), ex); } } @@ -184,26 +193,26 @@ public class EssentialsGeoIPPlayerListener implements Listener, IConf { logger.log(Level.SEVERE, tl("geoIpUrlEmpty")); return; } - String licenseKey = config.getString("database.license-key", ""); + final String licenseKey = config.getString("database.license-key", ""); if (licenseKey == null || licenseKey.isEmpty()) { logger.log(Level.SEVERE, tl("geoIpLicenseMissing")); return; } url = url.replace("{LICENSEKEY}", licenseKey); logger.log(Level.INFO, tl("downloadingGeoIp")); - URL downloadUrl = new URL(url); - URLConnection conn = downloadUrl.openConnection(); + final URL downloadUrl = new URL(url); + final URLConnection conn = downloadUrl.openConnection(); conn.setConnectTimeout(10000); conn.connect(); InputStream input = conn.getInputStream(); - OutputStream output = new FileOutputStream(databaseFile); - byte[] buffer = new byte[2048]; + final OutputStream output = new FileOutputStream(databaseFile); + final byte[] buffer = new byte[2048]; if (url.contains("gz")) { input = new GZIPInputStream(input); if (url.contains("tar.gz")) { // The new GeoIP2 uses tar.gz to pack the db file along with some other txt. So it makes things a bit complicated here. String filename; - TarInputStream tarInputStream = new TarInputStream(input); + final TarInputStream tarInputStream = new TarInputStream(input); TarEntry entry; while ((entry = tarInputStream.getNextEntry()) != null) { if (!entry.isDirectory()) { @@ -223,14 +232,14 @@ public class EssentialsGeoIPPlayerListener implements Listener, IConf { } output.close(); input.close(); - } catch (MalformedURLException ex) { + } catch (final MalformedURLException ex) { logger.log(Level.SEVERE, tl("geoIpUrlInvalid"), ex); - } catch (IOException ex) { + } catch (final IOException ex) { logger.log(Level.SEVERE, tl("connectionFailed"), ex); } } - private boolean checkIfLocal(InetAddress address) { + private boolean checkIfLocal(final InetAddress address) { if (address.isAnyLocalAddress() || address.isLoopbackAddress()) { return true; } @@ -238,8 +247,8 @@ public class EssentialsGeoIPPlayerListener implements Listener, IConf { // Double checks if address is defined on any interface try { return NetworkInterface.getByInetAddress(address) != null; - } catch (SocketException e) { + } catch (final SocketException e) { return false; } } -} \ No newline at end of file +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EmergencyListener.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EmergencyListener.java index bfd1886c2..2eaeee46c 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EmergencyListener.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EmergencyListener.java @@ -12,9 +12,8 @@ import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.server.PluginEnableEvent; - public class EmergencyListener implements Listener { - private EssentialsProtect plugin; + private final EssentialsProtect plugin; EmergencyListener(final EssentialsProtect essProtPlugin) { plugin = essProtPlugin; diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsConnect.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsConnect.java index d24221ced..41a97a9df 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsConnect.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsConnect.java @@ -9,19 +9,18 @@ import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; - class EssentialsConnect { private static final Logger logger = Logger.getLogger("EssentialsProtect"); private final IEssentials ess; private final IProtect protect; - EssentialsConnect(Plugin essPlugin, Plugin essProtect) { + EssentialsConnect(final Plugin essPlugin, final Plugin essProtect) { if (!essProtect.getDescription().getVersion().equals(essPlugin.getDescription().getVersion())) { logger.log(Level.WARNING, tl("versionMismatchAll")); } ess = (IEssentials) essPlugin; protect = (IProtect) essProtect; - ProtectReloader pr = new ProtectReloader(); + final ProtectReloader pr = new ProtectReloader(); pr.reloadConfig(); ess.addReloadListener(pr); } @@ -33,7 +32,7 @@ class EssentialsConnect { private class ProtectReloader implements IConf { @Override public void reloadConfig() { - for (ProtectConfig protectConfig : ProtectConfig.values()) { + for (final ProtectConfig protectConfig : ProtectConfig.values()) { if (protectConfig.isList()) { protect.getSettingsList().put(protectConfig, ess.getSettings().getProtectList(protectConfig.getConfigName())); } else if (protectConfig.isString()) { @@ -44,4 +43,4 @@ class EssentialsConnect { } } } -} \ No newline at end of file +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtect.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtect.java index 921a83ab6..a57ba56e6 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtect.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtect.java @@ -14,16 +14,14 @@ import java.util.List; import java.util.Map; import java.util.logging.Level; - public class EssentialsProtect extends JavaPlugin implements IProtect { private final Map settingsBoolean = new EnumMap<>(ProtectConfig.class); private final Map settingsString = new EnumMap<>(ProtectConfig.class); private final Map> settingsList = new EnumMap<>(ProtectConfig.class); + private final EmergencyListener emListener = new EmergencyListener(this); private EssentialsConnect ess = null; private transient MetricsWrapper metrics = null; - private final EmergencyListener emListener = new EmergencyListener(this); - @Override public void onEnable() { final PluginManager pm = this.getServer().getPluginManager(); @@ -71,7 +69,7 @@ public class EssentialsProtect extends JavaPlugin implements IProtect { private void enableEmergencyMode(final PluginManager pm) { pm.registerEvents(emListener, this); - for (Player player : getServer().getOnlinePlayers()) { + for (final Player player : getServer().getOnlinePlayers()) { player.sendMessage("Essentials Protect is in emergency mode. Check your log for errors."); } getLogger().log(Level.SEVERE, "Essentials not installed or failed to load. Essentials Protect is in emergency mode now."); @@ -87,7 +85,7 @@ public class EssentialsProtect extends JavaPlugin implements IProtect { HandlerList.unregisterAll(emListener); - for (Player player : getServer().getOnlinePlayers()) { + for (final Player player : getServer().getOnlinePlayers()) { player.sendMessage("Essentials Protect is no longer in emergency mode."); } getLogger().log(Level.SEVERE, "Essentials was loaded late! Essentials Protect is no longer in emergency mode."); diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java index 4a0f30ef4..96514f576 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java @@ -1,13 +1,16 @@ package com.earth2me.essentials.protect; import com.earth2me.essentials.utils.EnumUtil; - import com.earth2me.essentials.utils.MaterialUtil; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; -import org.bukkit.entity.*; +import org.bukkit.entity.Creeper; +import org.bukkit.entity.Fireball; +import org.bukkit.entity.Item; +import org.bukkit.entity.TNTPrimed; +import org.bukkit.entity.WitherSkull; import org.bukkit.entity.minecart.ExplosiveMinecart; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -23,7 +26,6 @@ import org.bukkit.event.world.PortalCreateEvent; import java.util.Set; - public class EssentialsProtectBlockListener implements Listener { private static final Set WATER_TYPES = EnumUtil.getAllMatching(Material.class, "WATER", "STATIONARY_WATER"); @@ -36,7 +38,7 @@ public class EssentialsProtectBlockListener implements Listener { } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockIgnite(BlockIgniteEvent event) { + public void onBlockIgnite(final BlockIgniteEvent event) { if (event.getBlock().getType() == Material.OBSIDIAN || event.getBlock().getRelative(BlockFace.DOWN).getType() == Material.OBSIDIAN) { event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_portal_creation)); return; @@ -67,7 +69,7 @@ public class EssentialsProtectBlockListener implements Listener { } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { + public void onEntityDamageByEntity(final EntityDamageByEntityEvent event) { if (event.getEntity() instanceof Item) { if (event.getCause() == EntityDamageEvent.DamageCause.FIRE || event.getCause() == EntityDamageEvent.DamageCause.FIRE_TICK || event.getCause() == EntityDamageEvent.DamageCause.LAVA) { event.setCancelled(prot.getSettingBool(ProtectConfig.disable_lava_item_dmg)); @@ -124,7 +126,7 @@ public class EssentialsProtectBlockListener implements Listener { } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPortalLight(PortalCreateEvent event) { + public void onPortalLight(final PortalCreateEvent event) { if (event.getReason() == PortalCreateEvent.CreateReason.FIRE) { event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_portal_creation)); } @@ -135,11 +137,11 @@ public class EssentialsProtectBlockListener implements Listener { if (!event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { return; } - Block block = event.getClickedBlock(); + final Block block = event.getClickedBlock(); if (block == null) { return; } - World.Environment environment = block.getWorld().getEnvironment(); + final World.Environment environment = block.getWorld().getEnvironment(); if (MaterialUtil.isBed(block.getType()) && !environment.equals(World.Environment.NORMAL)) { event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_bed_explosion)); } diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener_1_16_R1.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener_1_16_R1.java index ed899031b..d358f0d06 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener_1_16_R1.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener_1_16_R1.java @@ -23,13 +23,13 @@ public class EssentialsProtectBlockListener_1_16_R1 implements Listener { if (!event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { return; } - Block block = event.getClickedBlock(); + final Block block = event.getClickedBlock(); if (block == null) { return; } - World.Environment environment = block.getWorld().getEnvironment(); + final World.Environment environment = block.getWorld().getEnvironment(); if (block.getType() == Material.RESPAWN_ANCHOR && !environment.equals(World.Environment.NETHER)) { - RespawnAnchor respawnAnchor = (RespawnAnchor) block.getBlockData(); + final RespawnAnchor respawnAnchor = (RespawnAnchor) block.getBlockData(); if (respawnAnchor.getCharges() == respawnAnchor.getMaximumCharges()) { event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_respawn_anchor_explosion)); } diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener.java index acd1c3164..f0dd06091 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener.java @@ -35,7 +35,6 @@ import org.bukkit.event.hanging.HangingBreakEvent; import java.util.Locale; - public class EssentialsProtectEntityListener implements Listener { private final IProtect prot; private final IEssentials ess; @@ -152,7 +151,7 @@ public class EssentialsProtectEntityListener implements Listener { } private boolean shouldBeDamaged(final User user, final String type) { - return (user.isAuthorized("essentials.protect.damage.".concat(type)) && !user.isAuthorized("essentials.protect.damage.disable")); + return user.isAuthorized("essentials.protect.damage.".concat(type)) && !user.isAuthorized("essentials.protect.damage.disable"); } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @@ -160,7 +159,7 @@ public class EssentialsProtectEntityListener implements Listener { if (event.getEntity() == null) { return; } - Entity entity = event.getEntity(); + final Entity entity = event.getEntity(); final int maxHeight = ess.getSettings().getProtectCreeperMaxHeight(); if (entity instanceof EnderDragon && prot.getSettingBool(ProtectConfig.prevent_enderdragon_blockdmg)) { @@ -222,14 +221,14 @@ public class EssentialsProtectEntityListener implements Listener { } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onExplosionPrime(ExplosionPrimeEvent event) { + public void onExplosionPrime(final ExplosionPrimeEvent event) { if ((event.getEntity() instanceof Fireball || event.getEntity() instanceof SmallFireball) && prot.getSettingBool(ProtectConfig.prevent_fireball_fire)) { event.setFire(false); } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onEntityChangeBlock(EntityChangeBlockEvent event) { + public void onEntityChangeBlock(final EntityChangeBlockEvent event) { if (event.getEntityType() == EntityType.ENDERMAN && prot.getSettingBool(ProtectConfig.prevent_enderman_pickup)) { event.setCancelled(true); return; @@ -244,14 +243,14 @@ public class EssentialsProtectEntityListener implements Listener { } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onDoorBreak(EntityBreakDoorEvent event) { + public void onDoorBreak(final EntityBreakDoorEvent event) { if (event.getEntityType() == EntityType.ZOMBIE && prot.getSettingBool(ProtectConfig.prevent_zombie_door_break)) { event.setCancelled(true); } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPaintingBreak(HangingBreakByEntityEvent event) { + public void onPaintingBreak(final HangingBreakByEntityEvent event) { if ((event.getCause() == HangingBreakEvent.RemoveCause.ENTITY) && ((event.getRemover() instanceof Creeper) && prot.getSettingBool(ProtectConfig.prevent_creeper_explosion) || (((event.getRemover() instanceof Fireball) || (event.getRemover() instanceof SmallFireball)) && prot.getSettingBool(ProtectConfig.prevent_fireball_explosion)) || ((event.getRemover() instanceof TNTPrimed) && prot.getSettingBool(ProtectConfig.prevent_tnt_explosion)) || ((event.getRemover() instanceof WitherSkull) && prot.getSettingBool(ProtectConfig.prevent_witherskull_explosion)))) { event.setCancelled(true); } diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener_1_13_2_R1.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener_1_13_2_R1.java index 8fa9ab960..0e9da4634 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener_1_13_2_R1.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener_1_13_2_R1.java @@ -1,6 +1,5 @@ package com.earth2me.essentials.protect; -import net.ess3.api.IEssentials; import org.bukkit.entity.Creeper; import org.bukkit.entity.Entity; import org.bukkit.entity.MushroomCow; @@ -13,11 +12,9 @@ import org.bukkit.event.entity.EntityTransformEvent; public class EssentialsProtectEntityListener_1_13_2_R1 implements Listener { private final IProtect prot; - private final IEssentials ess; EssentialsProtectEntityListener_1_13_2_R1(final IProtect prot) { this.prot = prot; - this.ess = prot.getEssentialsConnect().getEssentials(); } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener_1_14_R1.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener_1_14_R1.java index f23063ddd..e5a25da13 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener_1_14_R1.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener_1_14_R1.java @@ -1,6 +1,5 @@ package com.earth2me.essentials.protect; -import net.ess3.api.IEssentials; import org.bukkit.entity.EntityType; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -9,15 +8,13 @@ import org.bukkit.event.entity.EntityChangeBlockEvent; public class EssentialsProtectEntityListener_1_14_R1 implements Listener { private final IProtect prot; - private final IEssentials ess; EssentialsProtectEntityListener_1_14_R1(final IProtect prot) { this.prot = prot; - this.ess = prot.getEssentialsConnect().getEssentials(); } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onEntityChangeBlock(EntityChangeBlockEvent event) { + public void onEntityChangeBlock(final EntityChangeBlockEvent event) { if (event.getEntityType() == EntityType.RAVAGER && prot.getSettingBool(ProtectConfig.prevent_ravager_thief)) { event.setCancelled(true); } diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectWeatherListener.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectWeatherListener.java index ba11ac3b2..fbb1aaa6a 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectWeatherListener.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectWeatherListener.java @@ -7,7 +7,6 @@ import org.bukkit.event.weather.LightningStrikeEvent; import org.bukkit.event.weather.ThunderChangeEvent; import org.bukkit.event.weather.WeatherChangeEvent; - public class EssentialsProtectWeatherListener implements Listener { private final IProtect prot; diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/IProtect.java b/EssentialsProtect/src/com/earth2me/essentials/protect/IProtect.java index 7d12107ad..af85b9cfe 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/IProtect.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/IProtect.java @@ -6,7 +6,6 @@ import org.bukkit.plugin.Plugin; import java.util.List; import java.util.Map; - public interface IProtect extends Plugin { boolean getSettingBool(final ProtectConfig protectConfig); diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/ProtectConfig.java b/EssentialsProtect/src/com/earth2me/essentials/protect/ProtectConfig.java index bab0e37e6..4e6485ae9 100644 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/ProtectConfig.java +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/ProtectConfig.java @@ -1,6 +1,5 @@ package com.earth2me.essentials.protect; - public enum ProtectConfig { disable_contactdmg("protect.disable.contactdmg", false), disable_lavadmg("protect.disable.lavadmg", false), diff --git a/EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandsetspawn.java b/EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandsetspawn.java index 18d15a001..2965dac3f 100644 --- a/EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandsetspawn.java +++ b/EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandsetspawn.java @@ -10,7 +10,6 @@ import java.util.List; import static com.earth2me.essentials.I18n.tl; - public class Commandsetspawn extends EssentialsCommand { public Commandsetspawn() { super("setspawn"); @@ -24,7 +23,7 @@ public class Commandsetspawn extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { return Collections.emptyList(); } } diff --git a/EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandspawn.java b/EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandspawn.java index fed5111d5..0bae8dc64 100644 --- a/EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandspawn.java +++ b/EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandspawn.java @@ -17,7 +17,6 @@ import java.util.concurrent.CompletableFuture; import static com.earth2me.essentials.I18n.tl; - public class Commandspawn extends EssentialsCommand { public Commandspawn() { super("spawn"); @@ -29,7 +28,7 @@ public class Commandspawn extends EssentialsCommand { charge.isAffordableFor(user); if (args.length > 0 && user.isAuthorized("essentials.spawn.others")) { final User otherUser = getPlayer(server, user, args, 0); - CompletableFuture future = new CompletableFuture<>(); + final CompletableFuture future = new CompletableFuture<>(); future.thenAccept(success -> { if (success) { if (!otherUser.equals(user)) { @@ -41,7 +40,7 @@ public class Commandspawn extends EssentialsCommand { } else { respawn(user.getSource(), user, user, charge, commandLabel, new CompletableFuture<>()); } - + throw new NoChargeException(); } @@ -51,7 +50,7 @@ public class Commandspawn extends EssentialsCommand { throw new NotEnoughArgumentsException(); } final User user = getPlayer(server, args, 0, true, false); - CompletableFuture future = new CompletableFuture<>(); + final CompletableFuture future = new CompletableFuture<>(); respawn(sender, null, user, null, commandLabel, future); future.thenAccept(success -> { if (success) { @@ -61,14 +60,14 @@ public class Commandspawn extends EssentialsCommand { } @Override - protected List getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { + protected List getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1 && sender.isAuthorized("essentials.spawn.others", ess)) { return getPlayers(server, sender); } return Collections.emptyList(); } - private void respawn(final CommandSource sender, final User teleportOwner, final User teleportee, final Trade charge, String commandLabel, CompletableFuture future) throws Exception { + private void respawn(final CommandSource sender, final User teleportOwner, final User teleportee, final Trade charge, final String commandLabel, final CompletableFuture future) throws Exception { final Location spawn = ((SpawnStorage) this.module).getSpawn(teleportee.getGroup()); sender.sendMessage(tl("teleporting", spawn.getWorld().getName(), spawn.getBlockX(), spawn.getBlockY(), spawn.getBlockZ())); future.exceptionally(e -> { diff --git a/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawn.java b/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawn.java index bacb0ce65..a23a28b1b 100644 --- a/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawn.java +++ b/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawn.java @@ -15,7 +15,6 @@ import java.util.logging.Level; import static com.earth2me.essentials.I18n.tl; - public class EssentialsSpawn extends JavaPlugin implements IEssentialsSpawn { private transient IEssentials ess; private transient SpawnStorage spawns; @@ -38,16 +37,16 @@ public class EssentialsSpawn extends JavaPlugin implements IEssentialsSpawn { final EssentialsSpawnPlayerListener playerListener = new EssentialsSpawnPlayerListener(ess, spawns); - EventPriority respawnPriority = ess.getSettings().getRespawnPriority(); + final EventPriority respawnPriority = ess.getSettings().getRespawnPriority(); if (respawnPriority != null) { pluginManager.registerEvent(PlayerRespawnEvent.class, playerListener, respawnPriority, (ll, event) -> - ((EssentialsSpawnPlayerListener) ll).onPlayerRespawn((PlayerRespawnEvent) event), this); + ((EssentialsSpawnPlayerListener) ll).onPlayerRespawn((PlayerRespawnEvent) event), this); } - EventPriority joinPriority = ess.getSettings().getSpawnJoinPriority(); + final EventPriority joinPriority = ess.getSettings().getSpawnJoinPriority(); if (joinPriority != null) { pluginManager.registerEvent(PlayerJoinEvent.class, playerListener, joinPriority, (ll, event) -> - ((EssentialsSpawnPlayerListener) ll).onPlayerJoin((PlayerJoinEvent) event), this); + ((EssentialsSpawnPlayerListener) ll).onPlayerJoin((PlayerJoinEvent) event), this); } if (metrics == null) { @@ -66,7 +65,7 @@ public class EssentialsSpawn extends JavaPlugin implements IEssentialsSpawn { } @Override - public void setSpawn(Location loc, String group) { + public void setSpawn(final Location loc, final String group) { if (group == null) { throw new IllegalArgumentException("Null group"); } @@ -74,7 +73,7 @@ public class EssentialsSpawn extends JavaPlugin implements IEssentialsSpawn { } @Override - public Location getSpawn(String group) { + public Location getSpawn(final String group) { if (group == null) { throw new IllegalArgumentException("Null group"); } diff --git a/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawnPlayerListener.java b/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawnPlayerListener.java index 45f41f802..3d289127b 100644 --- a/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawnPlayerListener.java +++ b/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawnPlayerListener.java @@ -24,7 +24,6 @@ import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; - class EssentialsSpawnPlayerListener implements Listener { private static final Logger logger = Logger.getLogger("EssentialsSpawn"); private final transient IEssentials ess; @@ -48,7 +47,7 @@ class EssentialsSpawnPlayerListener implements Listener { } if (ess.getSettings().getRespawnAtHome()) { - Location home; + final Location home; final Location bed = user.getBase().getBedSpawnLocation(); // cannot nuke this sync load due to the event being sync so it would hand either way. if (bed != null) { home = bed; @@ -73,16 +72,16 @@ class EssentialsSpawnPlayerListener implements Listener { private void delayedJoin(final Player player) { if (player.hasPlayedBefore()) { logger.log(Level.FINE, "Old player join"); - List spawnOnJoinGroups = ess.getSettings().getSpawnOnJoinGroups(); + final List spawnOnJoinGroups = ess.getSettings().getSpawnOnJoinGroups(); if (!spawnOnJoinGroups.isEmpty()) { final User user = ess.getUser(player); - + if (ess.getSettings().isUserInSpawnOnJoinGroup(user) && !user.isAuthorized("essentials.spawn-on-join.exempt")) { ess.scheduleSyncDelayedTask(() -> { - Location spawn = spawns.getSpawn(user.getGroup()); + final Location spawn = spawns.getSpawn(user.getGroup()); try { PaperLib.teleportAsync(user.getBase(), spawn, TeleportCause.PLUGIN); - } catch (Exception e) { + } catch (final Exception e) { ess.showError(user.getSource(), e, "spawn-on-join"); } }); @@ -108,7 +107,7 @@ class EssentialsSpawnPlayerListener implements Listener { final IText output = new KeywordReplacer(ess.getSettings().getAnnounceNewPlayerFormat(), user.getSource(), ess); final SimpleTextPager pager = new SimpleTextPager(output); - for (String line : pager.getLines()) { + for (final String line : pager.getLines()) { ess.broadcastMessage(user, line); } } @@ -118,7 +117,7 @@ class EssentialsSpawnPlayerListener implements Listener { try { final Kit kit = new Kit(kitName.toLowerCase(Locale.ENGLISH), ess); kit.expandItems(user); - } catch (Exception ex) { + } catch (final Exception ex) { logger.log(Level.WARNING, ex.getMessage()); } } @@ -127,7 +126,6 @@ class EssentialsSpawnPlayerListener implements Listener { }, 2L); } - private class NewPlayerTeleport implements Runnable { private final transient User user; @@ -143,7 +141,7 @@ class EssentialsSpawnPlayerListener implements Listener { final Location spawn = spawns.getSpawn(ess.getSettings().getNewbieSpawn()); if (spawn != null) { - CompletableFuture future = new CompletableFuture<>(); + final CompletableFuture future = new CompletableFuture<>(); future.exceptionally(e -> { logger.log(Level.WARNING, tl("teleportNewPlayerError"), e); return false; diff --git a/EssentialsSpawn/src/com/earth2me/essentials/spawn/IEssentialsSpawn.java b/EssentialsSpawn/src/com/earth2me/essentials/spawn/IEssentialsSpawn.java index f71d48937..91d0175fe 100644 --- a/EssentialsSpawn/src/com/earth2me/essentials/spawn/IEssentialsSpawn.java +++ b/EssentialsSpawn/src/com/earth2me/essentials/spawn/IEssentialsSpawn.java @@ -3,7 +3,6 @@ package com.earth2me.essentials.spawn; import org.bukkit.Location; import org.bukkit.plugin.Plugin; - public interface IEssentialsSpawn extends Plugin { /** @@ -11,7 +10,6 @@ public interface IEssentialsSpawn extends Plugin { * * @param loc The location to set the spawn to * @param group The group to set the spawn of, or 'default' for the default spawn - * * @throws IllegalArgumentException If group is null */ void setSpawn(Location loc, String group); @@ -20,9 +18,7 @@ public interface IEssentialsSpawn extends Plugin { * Gets the spawn location for a given group. * * @param group The group to get the spawn of, or 'default' for the default spawn - * * @return The spawn location set for the given group - * * @throws IllegalArgumentException If group is null */ Location getSpawn(String group); diff --git a/EssentialsSpawn/src/com/earth2me/essentials/spawn/SpawnStorage.java b/EssentialsSpawn/src/com/earth2me/essentials/spawn/SpawnStorage.java index 2c7f666b9..adab926ae 100644 --- a/EssentialsSpawn/src/com/earth2me/essentials/spawn/SpawnStorage.java +++ b/EssentialsSpawn/src/com/earth2me/essentials/spawn/SpawnStorage.java @@ -12,7 +12,6 @@ import java.util.HashMap; import java.util.Locale; import java.util.Map; - public class SpawnStorage extends AsyncStorageObjectHolder implements IEssentialsModule { SpawnStorage(final IEssentials ess) { super(ess, Spawns.class); @@ -25,10 +24,12 @@ public class SpawnStorage extends AsyncStorageObjectHolder implements IE } @Override - public void finishRead() { } + public void finishRead() { + } @Override - public void finishWrite() { } + public void finishWrite() { + } void setSpawn(final Location loc, final String group) { acquireWriteLock(); @@ -67,7 +68,7 @@ public class SpawnStorage extends AsyncStorageObjectHolder implements IE } private Location getWorldSpawn() { - for (World world : ess.getServer().getWorlds()) { + for (final World world : ess.getServer().getWorlds()) { if (world.getEnvironment() != World.Environment.NORMAL) { continue; } diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandsetxmpp.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandsetxmpp.java index 435e2544d..3c29d90b7 100644 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandsetxmpp.java +++ b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandsetxmpp.java @@ -5,7 +5,6 @@ import com.earth2me.essentials.commands.EssentialsCommand; import com.earth2me.essentials.commands.NotEnoughArgumentsException; import org.bukkit.Server; - public class Commandsetxmpp extends EssentialsCommand { public Commandsetxmpp() { super("setxmpp"); @@ -13,7 +12,7 @@ public class Commandsetxmpp extends EssentialsCommand { @Override protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws NotEnoughArgumentsException { - if (args.length == 0 ) { + if (args.length == 0) { throw new NotEnoughArgumentsException(); } diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmpp.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmpp.java index a3f318f04..47fc9cdaa 100644 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmpp.java +++ b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmpp.java @@ -7,7 +7,6 @@ import com.earth2me.essentials.commands.NotEnoughArgumentsException; import org.bukkit.ChatColor; import org.bukkit.Server; - public class Commandxmpp extends EssentialsCommand { public Commandxmpp() { super("xmpp"); diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmppspy.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmppspy.java index 1d05f11c4..ef586c4b1 100644 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmppspy.java +++ b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmppspy.java @@ -10,7 +10,6 @@ import com.earth2me.essentials.commands.PlayerNotFoundException; import net.ess3.api.MaxMoneyException; import org.bukkit.Server; - public class Commandxmppspy extends EssentialsLoopCommand { public Commandxmppspy() { super("xmppspy"); @@ -26,11 +25,11 @@ public class Commandxmppspy extends EssentialsLoopCommand { } @Override - protected void updatePlayer(Server server, CommandSource sender, User user, String[] args) { + protected void updatePlayer(final Server server, final CommandSource sender, final User user, final String[] args) { try { sender.sendMessage("XMPP Spy " + (EssentialsXMPP.getInstance().toggleSpy(user.getBase()) ? "enabled" : "disabled") + " for " + user.getDisplayName()); - } catch (Exception ex) { + } catch (final Exception ex) { sender.sendMessage("Error: " + ex.getMessage()); } } -} \ No newline at end of file +} diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPP.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPP.java index cb2bbbbc7..86fd10fc1 100644 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPP.java +++ b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPP.java @@ -16,7 +16,6 @@ import java.util.logging.Level; import static com.earth2me.essentials.I18n.tl; - public class EssentialsXMPP extends JavaPlugin implements IEssentialsXMPP { private static EssentialsXMPP instance = null; private transient UserManager users; @@ -28,6 +27,10 @@ public class EssentialsXMPP extends JavaPlugin implements IEssentialsXMPP { return instance; } + static void updatePresence() { + instance.xmpp.updatePresence(); + } + @Override public void onEnable() { instance = this; @@ -84,7 +87,7 @@ public class EssentialsXMPP extends JavaPlugin implements IEssentialsXMPP { @Override public IUser getUserByAddress(final String address) { - String username = instance.users.getUserByAddress(address); + final String username = instance.users.getUserByAddress(address); return username == null ? null : ess.getUser(username); } @@ -111,10 +114,6 @@ public class EssentialsXMPP extends JavaPlugin implements IEssentialsXMPP { return instance.xmpp.sendMessage(address, message); } - static void updatePresence() { - instance.xmpp.updatePresence(); - } - @Override public List getSpyUsers() { return instance.users.getSpyUsers(); @@ -124,12 +123,13 @@ public class EssentialsXMPP extends JavaPlugin implements IEssentialsXMPP { public void broadcastMessage(final IUser sender, final String message, final String xmppAddress) { ess.broadcastMessage(sender, message); try { - for (String address : getSpyUsers()) { + for (final String address : getSpyUsers()) { if (!address.equalsIgnoreCase(xmppAddress)) { sendMessage(address, message); } } - } catch (Exception ignored) {} + } catch (final Exception ignored) { + } } @Override diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPPPlayerListener.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPPPlayerListener.java index e832ed4fa..7bb591463 100644 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPPPlayerListener.java +++ b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPPPlayerListener.java @@ -12,7 +12,6 @@ import org.bukkit.event.player.PlayerQuitEvent; import java.util.List; - class EssentialsXMPPPlayerListener implements Listener { private final transient IEssentials ess; @@ -42,18 +41,18 @@ class EssentialsXMPPPlayerListener implements Listener { Bukkit.getScheduler().scheduleSyncDelayedTask(ess, EssentialsXMPP::updatePresence); - sendMessageToSpyUsers("Player " + user.getDisplayName() + " left the game"); } private void sendMessageToSpyUsers(final String message) { try { - List users = EssentialsXMPP.getInstance().getSpyUsers(); + final List users = EssentialsXMPP.getInstance().getSpyUsers(); synchronized (users) { for (final String address : users) { Bukkit.getScheduler().scheduleSyncDelayedTask(ess, () -> EssentialsXMPP.getInstance().sendMessage(address, message)); } } - } catch (Exception ignored) {} + } catch (final Exception ignored) { + } } } diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/IEssentialsXMPP.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/IEssentialsXMPP.java index 567bb7720..69bcca3fa 100644 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/IEssentialsXMPP.java +++ b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/IEssentialsXMPP.java @@ -7,7 +7,6 @@ import org.bukkit.plugin.Plugin; import java.util.List; - public interface IEssentialsXMPP extends Plugin { String getAddress(final Player user); diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/UserManager.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/UserManager.java index 736e7b507..64d5541db 100644 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/UserManager.java +++ b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/UserManager.java @@ -4,14 +4,19 @@ import com.earth2me.essentials.EssentialsConf; import com.earth2me.essentials.IConf; import java.io.File; -import java.util.*; - +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; public class UserManager implements IConf { - private final transient EssentialsConf users; - private final transient List spyusers = Collections.synchronizedList(new ArrayList<>()); private static final String ADDRESS = "address"; private static final String SPY = "spy"; + private final transient EssentialsConf users; + private final transient List spyusers = Collections.synchronizedList(new ArrayList<>()); UserManager(final File folder) { users = new EssentialsConf(new File(folder, "users.yml")); @@ -32,7 +37,7 @@ public class UserManager implements IConf { final String getUserByAddress(final String search) { final Set usernames = users.getKeys(false); - for (String username : usernames) { + for (final String username : usernames) { final String address = users.getString(username + "." + ADDRESS, null); if (search.equalsIgnoreCase(address)) { return username; @@ -63,7 +68,7 @@ public class UserManager implements IConf { users.load(); spyusers.clear(); final Set keys = users.getKeys(false); - for (String key : keys) { + for (final String key : keys) { if (isSpy(key)) { final String address = getAddress(key); if (address != null) { diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/XMPPManager.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/XMPPManager.java index dc7768b89..4b6f70c56 100644 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/XMPPManager.java +++ b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/XMPPManager.java @@ -6,28 +6,43 @@ import com.earth2me.essentials.IConf; import com.earth2me.essentials.utils.FormatUtil; import net.ess3.api.IUser; import org.bukkit.entity.Player; -import org.jivesoftware.smack.*; +import org.jivesoftware.smack.Chat; +import org.jivesoftware.smack.ChatManager; +import org.jivesoftware.smack.ChatManagerListener; +import org.jivesoftware.smack.ConnectionConfiguration; +import org.jivesoftware.smack.MessageListener; import org.jivesoftware.smack.Roster.SubscriptionMode; +import org.jivesoftware.smack.XMPPConnection; +import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.util.StringUtils; import java.io.File; -import java.util.*; -import java.util.logging.*; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.logging.Logger; +import java.util.logging.SimpleFormatter; import static com.earth2me.essentials.I18n.tl; - public class XMPPManager extends Handler implements MessageListener, ChatManagerListener, IConf { private static final Logger logger = Logger.getLogger("EssentialsXMPP"); private static final SimpleFormatter formatter = new SimpleFormatter(); private final transient EssentialsConf config; - private transient XMPPConnection connection; - private transient ChatManager chatManager; private final transient Map chats = Collections.synchronizedMap(new HashMap<>()); private final transient Set logrecords = Collections.synchronizedSet(new HashSet<>()); private final transient IEssentialsXMPP parent; + private transient XMPPConnection connection; + private transient ChatManager chatManager; private transient List logUsers; private transient Level logLevel; private transient boolean ignoreLagMessages = true; @@ -58,7 +73,7 @@ public class XMPPManager extends Handler implements MessageListener, ChatManager chat.sendMessage(FormatUtil.stripFormat(message)); return true; } - } catch (XMPPException ex) { + } catch (final XMPPException ex) { disableChat(address); } } @@ -81,6 +96,7 @@ public class XMPPManager extends Handler implements MessageListener, ChatManager default: final IUser sender = parent.getUserByAddress(StringUtils.parseBareAddress(chat.getParticipant())); parent.broadcastMessage(sender, "=" + sender.getBase().getDisplayName() + ": " + message, StringUtils.parseBareAddress(chat.getParticipant())); + break; } } } @@ -96,7 +112,7 @@ public class XMPPManager extends Handler implements MessageListener, ChatManager final String xmppuser = config.getString("xmpp.user"); final String password = config.getString("xmpp.password"); final ConnectionConfiguration connConf = new ConnectionConfiguration(server, port, serviceName); - String stringBuilder = "Connecting to xmpp server " + server + ":" + port + " as user " + xmppuser + "."; + final String stringBuilder = "Connecting to xmpp server " + server + ":" + port + " as user " + xmppuser + "."; logger.log(Level.INFO, stringBuilder); connConf.setSASLAuthenticationEnabled(config.getBoolean("xmpp.sasl-enabled", false)); connConf.setSendPresence(true); @@ -113,7 +129,7 @@ public class XMPPManager extends Handler implements MessageListener, ChatManager chatManager = connection.getChatManager(); chatManager.addChatListener(this); return true; - } catch (XMPPException ex) { + } catch (final XMPPException ex) { logger.log(Level.WARNING, "Failed to connect to server: " + server, ex); return false; } @@ -186,7 +202,7 @@ public class XMPPManager extends Handler implements MessageListener, ChatManager final String level = config.getString("log-level", "info"); try { logLevel = Level.parse(level.toUpperCase(Locale.ENGLISH)); - } catch (IllegalArgumentException e) { + } catch (final IllegalArgumentException e) { logLevel = Level.INFO; } ignoreLagMessages = config.getBoolean("ignore-lag-messages", true); @@ -204,7 +220,7 @@ public class XMPPManager extends Handler implements MessageListener, ChatManager logrecords.add(logRecord); } } - } catch (Exception ignored) { + } catch (final Exception ignored) { // Ignore all exceptions // Otherwise we create a loop. } @@ -232,10 +248,10 @@ public class XMPPManager extends Handler implements MessageListener, ChatManager } } if (!copy.isEmpty()) { - for (String user : logUsers) { + for (final String user : logUsers) { try { XMPPManager.this.startChat(user); - for (LogRecord logRecord : copy) { + for (final LogRecord logRecord : copy) { final String message = formatter.format(logRecord); if (!XMPPManager.this.sendMessage(user, FormatUtil.stripLogColorFormat(message))) { failedUsers.add(user); @@ -243,7 +259,7 @@ public class XMPPManager extends Handler implements MessageListener, ChatManager } } - } catch (XMPPException ex) { + } catch (final XMPPException ex) { failedUsers.add(user); logger.removeHandler(XMPPManager.this); logger.log(Level.SEVERE, "Failed to deliver log message! Disabling logging to XMPP.", ex); @@ -258,7 +274,7 @@ public class XMPPManager extends Handler implements MessageListener, ChatManager } try { Thread.sleep(2000); - } catch (InterruptedException ex) { + } catch (final InterruptedException ex) { threadrunning = false; } } @@ -290,12 +306,12 @@ public class XMPPManager extends Handler implements MessageListener, ChatManager if (matches.isEmpty()) { try { chat.sendMessage("User " + parts[0] + " not found"); - } catch (XMPPException ex) { + } catch (final XMPPException ex) { logger.log(Level.WARNING, "Failed to send xmpp message.", ex); } } else { final String from = "[" + parent.getUserByAddress(StringUtils.parseBareAddress(chat.getParticipant())) + ">"; - for (Player p : matches) { + for (final Player p : matches) { p.sendMessage(from + p.getDisplayName() + "] " + message); } } @@ -306,7 +322,7 @@ public class XMPPManager extends Handler implements MessageListener, ChatManager if (config.getStringList("op-users").contains(StringUtils.parseBareAddress(chat.getParticipant()))) { try { parent.getServer().dispatchCommand(Console.getInstance().getCommandSender(), message.substring(1)); - } catch (Exception ex) { + } catch (final Exception ex) { logger.log(Level.SEVERE, ex.getMessage(), ex); } } diff --git a/providers/1_8Provider/src/com/earth2me/essentials/OfflinePlayer.java b/providers/1_8Provider/src/com/earth2me/essentials/OfflinePlayer.java index 0abba4f7f..ab840a662 100644 --- a/providers/1_8Provider/src/com/earth2me/essentials/OfflinePlayer.java +++ b/providers/1_8Provider/src/com/earth2me/essentials/OfflinePlayer.java @@ -65,9 +65,9 @@ import java.util.UUID; public class OfflinePlayer implements Player { private final transient Server server; + private final transient org.bukkit.OfflinePlayer base; private transient Location location = new Location(null, 0, 0, 0, 0, 0); private transient World world; - private final transient org.bukkit.OfflinePlayer base; private boolean allowFlight = false; private boolean isFlying = false; private String name; @@ -96,11 +96,7 @@ public class OfflinePlayer implements Player { } @Override - public void setDisplayName(String string) { - } - - @Override - public void setCompassTarget(Location lctn) { + public void setDisplayName(final String string) { } @Override @@ -109,7 +105,7 @@ public class OfflinePlayer implements Player { } @Override - public void kickPlayer(String string) { + public void kickPlayer(final String string) { } @Override @@ -123,7 +119,7 @@ public class OfflinePlayer implements Player { } @Override - public void setItemInHand(ItemStack is) { + public void setItemInHand(final ItemStack is) { } @Override @@ -132,7 +128,7 @@ public class OfflinePlayer implements Player { } @Override - public void setHealth(double d) { + public void setHealth(final double d) { } @Override @@ -155,22 +151,22 @@ public class OfflinePlayer implements Player { return location; } + public void setLocation(final Location loc) { + location = loc; + world = loc.getWorld(); + } + @Override public World getWorld() { return world; } - public void setLocation(Location loc) { - location = loc; - world = loc.getWorld(); - } - - public void teleportTo(Location lctn) { + public void teleportTo(final Location lctn) { location = lctn; world = location.getWorld(); } - public void teleportTo(Entity entity) { + public void teleportTo(final Entity entity) { teleportTo(entity.getLocation()); } @@ -184,7 +180,7 @@ public class OfflinePlayer implements Player { } @Override - public boolean performCommand(String string) { + public boolean performCommand(final String string) { return false; } @@ -194,7 +190,7 @@ public class OfflinePlayer implements Player { } @Override - public void setRemainingAir(int i) { + public void setRemainingAir(final int i) { } @Override @@ -203,7 +199,7 @@ public class OfflinePlayer implements Player { } @Override - public void setMaximumAir(int i) { + public void setMaximumAir(final int i) { } @Override @@ -212,7 +208,7 @@ public class OfflinePlayer implements Player { } @Override - public void setSneaking(boolean bln) { + public void setSneaking(final boolean bln) { } @Override @@ -220,22 +216,22 @@ public class OfflinePlayer implements Player { } @Override - public void awardAchievement(Achievement achievement) { + public void awardAchievement(final Achievement achievement) { } @Override - public void removeAchievement(Achievement achievement) { + public void removeAchievement(final Achievement achievement) { } @Override - public boolean hasAchievement(Achievement achievement) { + public boolean hasAchievement(final Achievement achievement) { return false; } @Override - public void chat(String string) { + public void chat(final String string) { } @Override @@ -244,22 +240,22 @@ public class OfflinePlayer implements Player { } @Override - public double getEyeHeight(boolean bln) { + public double getEyeHeight(final boolean bln) { return 0D; } @Override - public List getLineOfSight(Set mat, int i) { + public List getLineOfSight(final Set mat, final int i) { return Collections.emptyList(); } @Override - public Block getTargetBlock(Set mat, int i) { + public Block getTargetBlock(final Set mat, final int i) { return null; } @Override - public List getLastTwoTargetBlocks(Set mat, int i) { + public List getLastTwoTargetBlocks(final Set mat, final int i) { return Collections.emptyList(); } @@ -269,12 +265,12 @@ public class OfflinePlayer implements Player { } @Override - public int getMaxFireTicks() { - return 0; + public void setFireTicks(final int i) { } @Override - public void setFireTicks(int i) { + public int getMaxFireTicks() { + return 0; } @Override @@ -290,11 +286,7 @@ public class OfflinePlayer implements Player { return getVelocity(); } - public void setMomentum(Vector vector) { - } - - @Override - public void setVelocity(Vector vector) { + public void setMomentum(final Vector vector) { } @Override @@ -302,6 +294,10 @@ public class OfflinePlayer implements Player { return new Vector(0, 0, 0); } + @Override + public void setVelocity(final Vector vector) { + } + @Override public double getHeight() { return 0; @@ -313,11 +309,11 @@ public class OfflinePlayer implements Player { } @Override - public void damage(double d) { + public void damage(final double d) { } @Override - public void damage(double d, Entity entity) { + public void damage(final double d, final Entity entity) { } @Override @@ -326,7 +322,7 @@ public class OfflinePlayer implements Player { } @Override - public void sendRawMessage(String string) { + public void sendRawMessage(final String string) { } @Override @@ -334,13 +330,17 @@ public class OfflinePlayer implements Player { return null; } + @Override + public void setCompassTarget(final Location lctn) { + } + @Override public int getMaximumNoDamageTicks() { return 0; } @Override - public void setMaximumNoDamageTicks(int i) { + public void setMaximumNoDamageTicks(final int i) { } @Override @@ -349,7 +349,7 @@ public class OfflinePlayer implements Player { } @Override - public void setLastDamage(double d) { + public void setLastDamage(final double d) { } @Override @@ -358,16 +358,16 @@ public class OfflinePlayer implements Player { } @Override - public void setNoDamageTicks(int i) { + public void setNoDamageTicks(final int i) { } @Override - public boolean teleport(Location lctn) { + public boolean teleport(final Location lctn) { return false; } @Override - public boolean teleport(Entity entity) { + public boolean teleport(final Entity entity) { return false; } @@ -377,7 +377,7 @@ public class OfflinePlayer implements Player { } @Override - public boolean setPassenger(Entity entity) { + public boolean setPassenger(final Entity entity) { return false; } @@ -387,12 +387,12 @@ public class OfflinePlayer implements Player { } @Override - public boolean addPassenger(Entity passenger) { + public boolean addPassenger(final Entity passenger) { return false; } @Override - public boolean removePassenger(Entity passenger) { + public boolean removePassenger(final Entity passenger) { return false; } @@ -425,7 +425,7 @@ public class OfflinePlayer implements Player { } @Override - public List getNearbyEntities(double d, double d1, double d2) { + public List getNearbyEntities(final double d, final double d1, final double d2) { return Collections.emptyList(); } @@ -440,11 +440,7 @@ public class OfflinePlayer implements Player { } @Override - public void setFallDistance(float f) { - } - - @Override - public void setSleepingIgnored(boolean bln) { + public void setFallDistance(final float f) { } @Override @@ -453,90 +449,90 @@ public class OfflinePlayer implements Player { } @Override - public void incrementStatistic(Statistic ststc) { + public void setSleepingIgnored(final boolean bln) { } @Override - public void decrementStatistic(Statistic statistic) throws IllegalArgumentException { + public void incrementStatistic(final Statistic ststc) { } @Override - public void incrementStatistic(Statistic ststc, int i) { + public void decrementStatistic(final Statistic statistic) throws IllegalArgumentException { } @Override - public void decrementStatistic(Statistic statistic, int i) throws IllegalArgumentException { + public void incrementStatistic(final Statistic ststc, final int i) { } @Override - public void setStatistic(Statistic statistic, int i) throws IllegalArgumentException { + public void decrementStatistic(final Statistic statistic, final int i) throws IllegalArgumentException { } @Override - public int getStatistic(Statistic statistic) throws IllegalArgumentException { + public void setStatistic(final Statistic statistic, final int i) throws IllegalArgumentException { + } + + @Override + public int getStatistic(final Statistic statistic) throws IllegalArgumentException { return 0; } @Override - public void incrementStatistic(Statistic ststc, Material mtrl) { + public void incrementStatistic(final Statistic ststc, final Material mtrl) { } @Override - public void decrementStatistic(Statistic statistic, Material material) throws IllegalArgumentException { + public void decrementStatistic(final Statistic statistic, final Material material) throws IllegalArgumentException { } @Override - public int getStatistic(Statistic statistic, Material material) throws IllegalArgumentException { + public int getStatistic(final Statistic statistic, final Material material) throws IllegalArgumentException { return 0; } @Override - public void incrementStatistic(Statistic ststc, Material mtrl, int i) { + public void incrementStatistic(final Statistic ststc, final Material mtrl, final int i) { } @Override - public void decrementStatistic(Statistic statistic, Material material, int i) throws IllegalArgumentException { + public void decrementStatistic(final Statistic statistic, final Material material, final int i) throws IllegalArgumentException { } @Override - public void setStatistic(Statistic statistic, Material material, int i) throws IllegalArgumentException { + public void setStatistic(final Statistic statistic, final Material material, final int i) throws IllegalArgumentException { } @Override - public void incrementStatistic(Statistic statistic, EntityType entityType) throws IllegalArgumentException { + public void incrementStatistic(final Statistic statistic, final EntityType entityType) throws IllegalArgumentException { } @Override - public void decrementStatistic(Statistic statistic, EntityType entityType) throws IllegalArgumentException { + public void decrementStatistic(final Statistic statistic, final EntityType entityType) throws IllegalArgumentException { } @Override - public int getStatistic(Statistic statistic, EntityType entityType) throws IllegalArgumentException { + public int getStatistic(final Statistic statistic, final EntityType entityType) throws IllegalArgumentException { return 0; } @Override - public void incrementStatistic(Statistic statistic, EntityType entityType, int i) throws IllegalArgumentException { + public void incrementStatistic(final Statistic statistic, final EntityType entityType, final int i) throws IllegalArgumentException { } @Override - public void decrementStatistic(Statistic statistic, EntityType entityType, int i) { + public void decrementStatistic(final Statistic statistic, final EntityType entityType, final int i) { } @Override - public void setStatistic(Statistic statistic, EntityType entityType, int i) { + public void setStatistic(final Statistic statistic, final EntityType entityType, final int i) { } @Override - public void playNote(Location lctn, byte b, byte b1) { + public void playNote(final Location lctn, final byte b, final byte b1) { } @Override - public void sendBlockChange(Location lctn, Material mtrl, byte b) { - } - - @Override - public void setLastDamageCause(EntityDamageEvent ede) { + public void sendBlockChange(final Location lctn, final Material mtrl, final byte b) { } @Override @@ -545,25 +541,29 @@ public class OfflinePlayer implements Player { } @Override - public void playEffect(Location lctn, Effect effect, int i) { + public void setLastDamageCause(final EntityDamageEvent ede) { } @Override - public boolean sendChunkChange(Location lctn, int i, int i1, int i2, byte[] bytes) { + public void playEffect(final Location lctn, final Effect effect, final int i) { + } + + @Override + public boolean sendChunkChange(final Location lctn, final int i, final int i1, final int i2, final byte[] bytes) { return true; } @Override - public void sendBlockChange(Location location, int i, byte b) { + public void sendBlockChange(final Location location, final int i, final byte b) { } @Override - public void playNote(Location lctn, Instrument i, Note note) { + public void playNote(final Location lctn, final Instrument i, final Note note) { } @Override - public void setPlayerTime(long l, boolean bln) { + public void setPlayerTime(final long l, final boolean bln) { } @Override @@ -586,47 +586,47 @@ public class OfflinePlayer implements Player { } @Override - public boolean isPermissionSet(String string) { + public boolean isPermissionSet(final String string) { return false; } @Override - public boolean isPermissionSet(Permission prmsn) { + public boolean isPermissionSet(final Permission prmsn) { return false; } @Override - public boolean hasPermission(String string) { + public boolean hasPermission(final String string) { return false; } @Override - public boolean hasPermission(Permission prmsn) { + public boolean hasPermission(final Permission prmsn) { return false; } @Override - public PermissionAttachment addAttachment(Plugin plugin, String string, boolean bln) { + public PermissionAttachment addAttachment(final Plugin plugin, final String string, final boolean bln) { return null; } @Override - public PermissionAttachment addAttachment(Plugin plugin) { + public PermissionAttachment addAttachment(final Plugin plugin) { return null; } @Override - public PermissionAttachment addAttachment(Plugin plugin, String string, boolean bln, int i) { + public PermissionAttachment addAttachment(final Plugin plugin, final String string, final boolean bln, final int i) { return null; } @Override - public PermissionAttachment addAttachment(Plugin plugin, int i) { + public PermissionAttachment addAttachment(final Plugin plugin, final int i) { return null; } @Override - public void removeAttachment(PermissionAttachment pa) { + public void removeAttachment(final PermissionAttachment pa) { } @Override @@ -639,7 +639,7 @@ public class OfflinePlayer implements Player { } @Override - public void sendMap(MapView mv) { + public void sendMap(final MapView mv) { } @Override @@ -648,7 +648,7 @@ public class OfflinePlayer implements Player { } @Override - public void setGameMode(GameMode gm) { + public void setGameMode(final GameMode gm) { } @Override @@ -657,7 +657,7 @@ public class OfflinePlayer implements Player { } @Override - public void setLevel(int i) { + public void setLevel(final int i) { } @Override @@ -666,7 +666,7 @@ public class OfflinePlayer implements Player { } @Override - public void setTotalExperience(int i) { + public void setTotalExperience(final int i) { } @Override @@ -675,7 +675,7 @@ public class OfflinePlayer implements Player { } @Override - public void setExhaustion(float f) { + public void setExhaustion(final float f) { } @Override @@ -684,7 +684,7 @@ public class OfflinePlayer implements Player { } @Override - public void setSaturation(float f) { + public void setSaturation(final float f) { } @Override @@ -693,7 +693,7 @@ public class OfflinePlayer implements Player { } @Override - public void setFoodLevel(int i) { + public void setFoodLevel(final int i) { } @Override @@ -702,11 +702,7 @@ public class OfflinePlayer implements Player { } @Override - public void setSprinting(boolean bln) { - } - - @Override - public void setPlayerListName(String name) { + public void setSprinting(final boolean bln) { } @Override @@ -714,13 +710,17 @@ public class OfflinePlayer implements Player { return name; } + @Override + public void setPlayerListName(final String name) { + } + @Override public int getTicksLived() { return 0; } @Override - public void setTicksLived(int i) { + public void setTicksLived(final int i) { } @Override @@ -729,7 +729,11 @@ public class OfflinePlayer implements Player { } @Override - public void giveExp(int i) { + public void setMaxHealth(final double i) { + } + + @Override + public void giveExp(final int i) { } @Override @@ -738,16 +742,16 @@ public class OfflinePlayer implements Player { } @Override - public void setExp(float f) { + public void setExp(final float f) { } @Override - public boolean teleport(Location lctn, TeleportCause tc) { + public boolean teleport(final Location lctn, final TeleportCause tc) { return false; } @Override - public boolean teleport(Entity entity, TeleportCause tc) { + public boolean teleport(final Entity entity, final TeleportCause tc) { return false; } @@ -756,15 +760,8 @@ public class OfflinePlayer implements Player { return null; } - void setName(final String name) { - this.name = base.getName(); - if (this.name == null) { - this.name = name; - } - } - @Override - public void sendPluginMessage(Plugin plugin, String string, byte[] bytes) { + public void sendPluginMessage(final Plugin plugin, final String string, final byte[] bytes) { } @Override @@ -772,78 +769,74 @@ public class OfflinePlayer implements Player { return Collections.emptySet(); } - @Override - public void setAllowFlight(boolean bln) { - allowFlight = bln; - } - @Override public boolean getAllowFlight() { return allowFlight; } @Override - public void setBedSpawnLocation(Location lctn) { + public void setAllowFlight(final boolean bln) { + allowFlight = bln; } @Override - public void setBedSpawnLocation(Location lctn, boolean force) { + public void setBedSpawnLocation(final Location lctn, final boolean force) { } @Override - public void playEffect(EntityEffect ee) { + public void playEffect(final EntityEffect ee) { } @Override - public void hidePlayer(Player player) { + public void hidePlayer(final Player player) { } @Override - public void hidePlayer(Plugin plugin, Player player) { + public void hidePlayer(final Plugin plugin, final Player player) { } @Override - public void showPlayer(Player player) { + public void showPlayer(final Player player) { } @Override - public void showPlayer(Plugin plugin, Player player) { + public void showPlayer(final Plugin plugin, final Player player) { } @Override - public boolean canSee(Player player) { + public boolean canSee(final Player player) { return false; } @Override - public boolean addPotionEffect(PotionEffect pe) { + public boolean addPotionEffect(final PotionEffect pe) { return false; } @Override - public boolean addPotionEffect(PotionEffect pe, boolean bln) { + public boolean addPotionEffect(final PotionEffect pe, final boolean bln) { return false; } @Override - public boolean addPotionEffects(Collection clctn) { + public boolean addPotionEffects(final Collection clctn) { return false; } @Override - public boolean hasPotionEffect(PotionEffectType pet) { + public boolean hasPotionEffect(final PotionEffectType pet) { return false; } @Override - public PotionEffect getPotionEffect(PotionEffectType type) { + public PotionEffect getPotionEffect(final PotionEffectType type) { return null; } @Override - public void removePotionEffect(PotionEffectType pet) { + public void removePotionEffect(final PotionEffectType pet) { } @Override @@ -852,7 +845,7 @@ public class OfflinePlayer implements Player { } @Override - public T launchProjectile(Class arg0) { + public T launchProjectile(final Class arg0) { return null; } @@ -862,11 +855,11 @@ public class OfflinePlayer implements Player { } @Override - public void playEffect(Location lctn, Effect effect, T t) { + public void playEffect(final Location lctn, final Effect effect, final T t) { } @Override - public boolean setWindowProperty(Property prprt, int i) { + public boolean setWindowProperty(final Property prprt, final int i) { return false; } @@ -876,31 +869,31 @@ public class OfflinePlayer implements Player { } @Override - public InventoryView openInventory(Inventory invntr) { + public InventoryView openInventory(final Inventory invntr) { return null; } @Override - public InventoryView openWorkbench(Location lctn, boolean bln) { + public InventoryView openWorkbench(final Location lctn, final boolean bln) { return null; } @Override - public InventoryView openEnchanting(Location lctn, boolean bln) { + public InventoryView openEnchanting(final Location lctn, final boolean bln) { return null; } @Override - public void openInventory(InventoryView iv) { + public void openInventory(final InventoryView iv) { } @Override - public InventoryView openMerchant(Villager trader, boolean force) { + public InventoryView openMerchant(final Villager trader, final boolean force) { return null; } @Override - public InventoryView openMerchant(Merchant merchant, boolean force) { + public InventoryView openMerchant(final Merchant merchant, final boolean force) { return null; } @@ -914,40 +907,40 @@ public class OfflinePlayer implements Player { } @Override - public void setItemOnCursor(ItemStack is) { + public void setItemOnCursor(final ItemStack is) { } @Override - public boolean hasCooldown(Material material) { + public boolean hasCooldown(final Material material) { return false; } @Override - public int getCooldown(Material material) { + public int getCooldown(final Material material) { return 0; } @Override - public void setCooldown(Material material, int ticks) { + public void setCooldown(final Material material, final int ticks) { } @Override - public void setMetadata(String string, MetadataValue mv) { + public void setMetadata(final String string, final MetadataValue mv) { } @Override - public List getMetadata(String string) { + public List getMetadata(final String string) { return Collections.emptyList(); } @Override - public boolean hasMetadata(String string) { + public boolean hasMetadata(final String string) { return false; } @Override - public void removeMetadata(String string, Plugin plugin) { + public void removeMetadata(final String string, final Plugin plugin) { } @Override @@ -956,20 +949,20 @@ public class OfflinePlayer implements Player { } @Override - public void acceptConversationInput(String string) { + public void acceptConversationInput(final String string) { } @Override - public boolean beginConversation(Conversation c) { + public boolean beginConversation(final Conversation c) { return false; } @Override - public void abandonConversation(Conversation c) { + public void abandonConversation(final Conversation c) { } @Override - public void sendMessage(String[] strings) { + public void sendMessage(final String[] strings) { } @Override @@ -983,7 +976,7 @@ public class OfflinePlayer implements Player { } @Override - public void abandonConversation(Conversation arg0, ConversationAbandonedEvent arg1) { + public void abandonConversation(final Conversation arg0, final ConversationAbandonedEvent arg1) { } @Override @@ -992,7 +985,7 @@ public class OfflinePlayer implements Player { } @Override - public void setFlying(boolean arg0) { + public void setFlying(final boolean arg0) { isFlying = arg0; } @@ -1007,7 +1000,7 @@ public class OfflinePlayer implements Player { } @Override - public void setShoulderEntityLeft(Entity entity) { + public void setShoulderEntityLeft(final Entity entity) { } @@ -1017,12 +1010,12 @@ public class OfflinePlayer implements Player { } @Override - public void setShoulderEntityRight(Entity entity) { + public void setShoulderEntityRight(final Entity entity) { } @Override - public boolean hasLineOfSight(Entity entity) { + public boolean hasLineOfSight(final Entity entity) { return false; } @@ -1031,24 +1024,24 @@ public class OfflinePlayer implements Player { return false; } - @Override - public void setFlySpeed(float value) throws IllegalArgumentException { - } - - @Override - public void setWalkSpeed(float value) throws IllegalArgumentException { - } - @Override public float getFlySpeed() { return 0.1f; } + @Override + public void setFlySpeed(final float value) throws IllegalArgumentException { + } + @Override public float getWalkSpeed() { return 0.2f; } + @Override + public void setWalkSpeed(final float value) throws IllegalArgumentException { + } + @Override public Inventory getEnderChest() { return null; @@ -1060,11 +1053,11 @@ public class OfflinePlayer implements Player { } @Override - public void playSound(Location arg0, Sound arg1, float arg2, float arg3) { + public void playSound(final Location arg0, final Sound arg1, final float arg2, final float arg3) { } @Override - public void giveExpLevels(int i) { + public void giveExpLevels(final int i) { } @Override @@ -1073,7 +1066,7 @@ public class OfflinePlayer implements Player { } @Override - public void setRemoveWhenFarAway(boolean bln) { + public void setRemoveWhenFarAway(final boolean bln) { } @Override @@ -1081,52 +1074,44 @@ public class OfflinePlayer implements Player { return null; } - @Override - public void setCanPickupItems(boolean bln) { - } - @Override public boolean getCanPickupItems() { return false; } @Override - public Location getLocation(Location lctn) { + public void setCanPickupItems(final boolean bln) { + } + + @Override + public Location getLocation(final Location lctn) { return lctn; } @Override - public void setTexturePack(String string) { + public void setTexturePack(final String string) { } @Override - public void setResourcePack(String s) { + public void setResourcePack(final String s) { } @Override - public void setResourcePack(String url, byte[] hash) { + public void setResourcePack(final String url, final byte[] hash) { } - @Override - public void setMaxHealth(double i) { - } - @Override public void resetMaxHealth() { } - @Override - public void setCustomName(String string) { - } - @Override public String getCustomName() { return null; } @Override - public void setCustomNameVisible(boolean bln) { + public void setCustomName(final String string) { } @Override @@ -1135,8 +1120,7 @@ public class OfflinePlayer implements Player { } @Override - public void setGlowing(boolean flag) { - + public void setCustomNameVisible(final boolean bln) { } @Override @@ -1145,7 +1129,7 @@ public class OfflinePlayer implements Player { } @Override - public void setInvulnerable(boolean flag) { + public void setGlowing(final boolean flag) { } @@ -1154,13 +1138,18 @@ public class OfflinePlayer implements Player { return false; } + @Override + public void setInvulnerable(final boolean flag) { + + } + @Override public boolean isSilent() { return false; } @Override - public void setSilent(boolean flag) { + public void setSilent(final boolean flag) { } @@ -1170,7 +1159,7 @@ public class OfflinePlayer implements Player { } @Override - public void setGravity(boolean gravity) { + public void setGravity(final boolean gravity) { } @@ -1180,7 +1169,7 @@ public class OfflinePlayer implements Player { } @Override - public void setPortalCooldown(int cooldown) { + public void setPortalCooldown(final int cooldown) { } @@ -1190,12 +1179,12 @@ public class OfflinePlayer implements Player { } @Override - public boolean addScoreboardTag(String tag) { + public boolean addScoreboardTag(final String tag) { return false; } @Override - public boolean removeScoreboardTag(String tag) { + public boolean removeScoreboardTag(final String tag) { return false; } @@ -1205,12 +1194,12 @@ public class OfflinePlayer implements Player { } @Override - public void setPlayerWeather(WeatherType arg0) { + public WeatherType getPlayerWeather() { + return null; // per player weather, null means default anyways } @Override - public WeatherType getPlayerWeather() { - return null; // per player weather, null means default anyways + public void setPlayerWeather(final WeatherType arg0) { } @Override @@ -1228,40 +1217,40 @@ public class OfflinePlayer implements Player { } @Override - public void setScoreboard(Scoreboard scrbrd) throws IllegalArgumentException, IllegalStateException { + public void setScoreboard(final Scoreboard scrbrd) throws IllegalArgumentException, IllegalStateException { } @Override - public void playSound(Location arg0, String arg1, float arg2, float arg3) { + public void playSound(final Location arg0, final String arg1, final float arg2, final float arg3) { } @Override - public void playSound(Location location, Sound sound, SoundCategory category, float volume, float pitch) { + public void playSound(final Location location, final Sound sound, final SoundCategory category, final float volume, final float pitch) { } @Override - public void playSound(Location location, String sound, SoundCategory category, float volume, float pitch) { + public void playSound(final Location location, final String sound, final SoundCategory category, final float volume, final float pitch) { } @Override - public void stopSound(Sound sound) { + public void stopSound(final Sound sound) { } @Override - public void stopSound(String sound) { + public void stopSound(final String sound) { } @Override - public void stopSound(Sound sound, SoundCategory category) { + public void stopSound(final Sound sound, final SoundCategory category) { } @Override - public void stopSound(String sound, SoundCategory category) { + public void stopSound(final String sound, final SoundCategory category) { } @@ -1271,12 +1260,7 @@ public class OfflinePlayer implements Player { } @Override - public void setHealthScaled(boolean arg0) { - } - - @Override - public void setHealthScale(double arg0) throws IllegalArgumentException { - + public void setHealthScaled(final boolean arg0) { } @Override @@ -1285,7 +1269,8 @@ public class OfflinePlayer implements Player { } @Override - public void setSpectatorTarget(Entity entity) { + public void setHealthScale(final double arg0) throws IllegalArgumentException { + } @Override @@ -1299,7 +1284,7 @@ public class OfflinePlayer implements Player { } @Override - public boolean setLeashHolder(Entity arg0) { + public boolean setLeashHolder(final Entity arg0) { return false; } @@ -1309,12 +1294,12 @@ public class OfflinePlayer implements Player { } @Override - public void setGliding(boolean gliding) { + public void setGliding(final boolean gliding) { } @Override - public void setAI(boolean ai) { + public void setAI(final boolean ai) { } @@ -1323,23 +1308,23 @@ public class OfflinePlayer implements Player { return false; } - @Override - public void setCollidable(boolean collidable) { - - } - @Override public boolean isCollidable() { return false; } @Override - public T launchProjectile(Class type, Vector vector) { + public void setCollidable(final boolean collidable) { + + } + + @Override + public T launchProjectile(final Class type, final Vector vector) { return null; } @Override - public void sendSignChange(Location arg0, String[] arg1) throws IllegalArgumentException { + public void sendSignChange(final Location arg0, final String[] arg1) throws IllegalArgumentException { } @Override @@ -1347,11 +1332,22 @@ public class OfflinePlayer implements Player { return null; } + @Override + public void setBedSpawnLocation(final Location lctn) { + } + @Override public String getName() { return name; } + void setName(final String name) { + this.name = base.getName(); + if (this.name == null) { + this.name = name; + } + } + @Override public UUID getUniqueId() { return base.getUniqueId(); @@ -1363,7 +1359,7 @@ public class OfflinePlayer implements Player { } @Override - public void setOp(boolean value) { + public void setOp(final boolean value) { base.setOp(value); } @@ -1382,7 +1378,7 @@ public class OfflinePlayer implements Player { // Removed in 1.12, retain for backwards compatibility. @Deprecated - public void setBanned(boolean banned) { + public void setBanned(final boolean banned) { if (ReflUtil.getNmsVersionObject().isHigherThanOrEqualTo(ReflUtil.V1_12_R1)) { throw new UnsupportedOperationException("Cannot call setBanned on MC 1.12 and higher."); } @@ -1394,9 +1390,9 @@ public class OfflinePlayer implements Player { } } try { - Method method = base.getClass().getDeclaredMethod("setBanned", boolean.class); + final Method method = base.getClass().getDeclaredMethod("setBanned", boolean.class); method.invoke(base, banned); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + } catch (final NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { // This will never happen in a normal CraftBukkit pre-1.12 instance e.printStackTrace(); } @@ -1408,7 +1404,7 @@ public class OfflinePlayer implements Player { } @Override - public void setWhitelisted(boolean value) { + public void setWhitelisted(final boolean value) { base.setWhitelisted(value); } @@ -1442,72 +1438,76 @@ public class OfflinePlayer implements Player { return null; } + @Override + public void setSpectatorTarget(final Entity entity) { + } + @Override public void resetTitle() { } @Override - public void spawnParticle(Particle particle, Location location, int count) { + public void spawnParticle(final Particle particle, final Location location, final int count) { } @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count) { + public void spawnParticle(final Particle particle, final double x, final double y, final double z, final int count) { } @Override - public void spawnParticle(Particle particle, Location location, int count, T data) { + public void spawnParticle(final Particle particle, final Location location, final int count, final T data) { } @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, T data) { + public void spawnParticle(final Particle particle, final double x, final double y, final double z, final int count, final T data) { } @Override - public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ) { + public void spawnParticle(final Particle particle, final Location location, final int count, final double offsetX, final double offsetY, final double offsetZ) { } @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ) { + public void spawnParticle(final Particle particle, final double x, final double y, final double z, final int count, final double offsetX, final double offsetY, final double offsetZ) { } @Override - public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, T data) { + public void spawnParticle(final Particle particle, final Location location, final int count, final double offsetX, final double offsetY, final double offsetZ, final T data) { } @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, T data) { + public void spawnParticle(final Particle particle, final double x, final double y, final double z, final int count, final double offsetX, final double offsetY, final double offsetZ, final T data) { } @Override - public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra) { + public void spawnParticle(final Particle particle, final Location location, final int count, final double offsetX, final double offsetY, final double offsetZ, final double extra) { } @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra) { + public void spawnParticle(final Particle particle, final double x, final double y, final double z, final int count, final double offsetX, final double offsetY, final double offsetZ, final double extra) { } @Override - public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, T data) { + public void spawnParticle(final Particle particle, final Location location, final int count, final double offsetX, final double offsetY, final double offsetZ, final double extra, final T data) { } @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, T data) { + public void spawnParticle(final Particle particle, final double x, final double y, final double z, final int count, final double offsetX, final double offsetY, final double offsetZ, final double extra, final T data) { } @Override - public AdvancementProgress getAdvancementProgress(Advancement advancement) { + public AdvancementProgress getAdvancementProgress(final Advancement advancement) { return null; } @@ -1517,17 +1517,17 @@ public class OfflinePlayer implements Player { } @Override - public void sendTitle(String title, String subtitle) { + public void sendTitle(final String title, final String subtitle) { } @Override - public void sendTitle(String title, String subtitle, int fadeIn, int stay, int fadeOut) { + public void sendTitle(final String title, final String subtitle, final int fadeIn, final int stay, final int fadeOut) { } @Override - public AttributeInstance getAttribute(Attribute attribute) { + public AttributeInstance getAttribute(final Attribute attribute) { return null; } } diff --git a/providers/BaseProviders/src/net/ess3/provider/ProviderListener.java b/providers/BaseProviders/src/net/ess3/provider/ProviderListener.java index 0750e87b7..c6bf353c2 100644 --- a/providers/BaseProviders/src/net/ess3/provider/ProviderListener.java +++ b/providers/BaseProviders/src/net/ess3/provider/ProviderListener.java @@ -6,9 +6,9 @@ import org.bukkit.event.Listener; import java.util.function.Consumer; public abstract class ProviderListener implements Provider, Listener { - protected Consumer function; + protected final Consumer function; - public ProviderListener(Consumer function) { + public ProviderListener(final Consumer function) { this.function = function; } } diff --git a/providers/BaseProviders/src/net/ess3/provider/SpawnerItemProvider.java b/providers/BaseProviders/src/net/ess3/provider/SpawnerItemProvider.java index d377ee8bd..512ba8b92 100644 --- a/providers/BaseProviders/src/net/ess3/provider/SpawnerItemProvider.java +++ b/providers/BaseProviders/src/net/ess3/provider/SpawnerItemProvider.java @@ -10,27 +10,27 @@ import java.util.stream.Collectors; import java.util.stream.Stream; public interface SpawnerItemProvider extends Provider { + Map entityToDisplayName = Stream.of("CAVE_SPIDER:Cave Spider", "PIG_ZOMBIE:Zombie Pigman", + "ZOMBIFIED_PIGLIN:Zombie Piglin", "MAGMA_CUBE:Magma Cube", "ENDER_DRAGON:Ender Dragon", + "MUSHROOM_COW:Mooshroom", "SNOWMAN:Snow Golem", "OCELOT:Ocelot", "IRON_GOLEM:Iron Golem", "WITHER:Wither", + "HORSE:Horse") + .filter(s -> { + try { + EntityType.valueOf(s); + return true; + } catch (IllegalArgumentException e) { + return false; + } + }) + .collect(Collectors.toMap(s -> EntityType.valueOf(s.split(":")[0]), s -> s.split(":")[1])); + ItemStack setEntityType(ItemStack is, EntityType type) throws IllegalArgumentException; EntityType getEntityType(ItemStack is) throws IllegalArgumentException; - Map entityToDisplayName = Stream.of("CAVE_SPIDER:Cave Spider", "PIG_ZOMBIE:Zombie Pigman", - "ZOMBIFIED_PIGLIN:Zombie Piglin", "MAGMA_CUBE:Magma Cube", "ENDER_DRAGON:Ender Dragon", - "MUSHROOM_COW:Mooshroom", "SNOWMAN:Snow Golem", "OCELOT:Ocelot", "IRON_GOLEM:Iron Golem", "WITHER:Wither", - "HORSE:Horse") - .filter(s -> { - try { - EntityType.valueOf(s); - return true; - } catch (IllegalArgumentException e) { - return false; - } - }) - .collect(Collectors.toMap(s -> EntityType.valueOf(s.split(":")[0]), s -> s.split(":")[1])); - - default ItemStack setDisplayName(ItemStack is, EntityType type) { - ItemMeta meta = is.getItemMeta(); - String displayName; + default ItemStack setDisplayName(final ItemStack is, final EntityType type) { + final ItemMeta meta = is.getItemMeta(); + final String displayName; if (entityToDisplayName.containsKey(type)) { displayName = entityToDisplayName.get(type); } else { diff --git a/providers/BaseProviders/src/net/ess3/provider/providers/BasePotionDataProvider.java b/providers/BaseProviders/src/net/ess3/provider/providers/BasePotionDataProvider.java index 210a6be65..74b4592a5 100644 --- a/providers/BaseProviders/src/net/ess3/provider/providers/BasePotionDataProvider.java +++ b/providers/BaseProviders/src/net/ess3/provider/providers/BasePotionDataProvider.java @@ -12,36 +12,40 @@ import java.util.Map; public class BasePotionDataProvider implements PotionMetaProvider { private static final Map damageValueToType = ImmutableMap.builder() - .put(1, PotionType.REGEN) - .put(2, PotionType.SPEED) - .put(3, PotionType.FIRE_RESISTANCE) - .put(4, PotionType.POISON) - .put(5, PotionType.INSTANT_HEAL) - .put(6, PotionType.NIGHT_VISION) - // Skip 7 - .put(8, PotionType.WEAKNESS) - .put(9, PotionType.STRENGTH) - .put(10, PotionType.SLOWNESS) - .put(11, PotionType.JUMP) - .put(12, PotionType.INSTANT_DAMAGE) - .put(13, PotionType.WATER_BREATHING) - .put(14, PotionType.INVISIBILITY) - .build(); + .put(1, PotionType.REGEN) + .put(2, PotionType.SPEED) + .put(3, PotionType.FIRE_RESISTANCE) + .put(4, PotionType.POISON) + .put(5, PotionType.INSTANT_HEAL) + .put(6, PotionType.NIGHT_VISION) + // Skip 7 + .put(8, PotionType.WEAKNESS) + .put(9, PotionType.STRENGTH) + .put(10, PotionType.SLOWNESS) + .put(11, PotionType.JUMP) + .put(12, PotionType.INSTANT_DAMAGE) + .put(13, PotionType.WATER_BREATHING) + .put(14, PotionType.INVISIBILITY) + .build(); + + private static int getBit(final int n, final int k) { + return (n >> k) & 1; + } @Override - public ItemStack createPotionItem(Material initial, int effectId) { + public ItemStack createPotionItem(final Material initial, final int effectId) { ItemStack potion = new ItemStack(initial, 1); if (effectId == 0) { return potion; } - int damageValue = getBit(effectId, 0) + - 2 * getBit(effectId, 1) + - 4 * getBit(effectId, 2) + - 8 * getBit(effectId, 3); + final int damageValue = getBit(effectId, 0) + + 2 * getBit(effectId, 1) + + 4 * getBit(effectId, 2) + + 8 * getBit(effectId, 3); - PotionType type = damageValueToType.get(damageValue); + final PotionType type = damageValueToType.get(damageValue); if (type == null) { throw new IllegalArgumentException("Unable to process potion effect ID " + effectId + " with damage value " + damageValue); } @@ -51,19 +55,15 @@ public class BasePotionDataProvider implements PotionMetaProvider { potion = new ItemStack(Material.SPLASH_POTION, 1); } - PotionMeta meta = (PotionMeta) potion.getItemMeta(); + final PotionMeta meta = (PotionMeta) potion.getItemMeta(); //getBit(s) are extended and upgraded respectfully - PotionData data = new PotionData(type, getBit(effectId, 6) == 1, getBit(effectId, 5) == 1); + final PotionData data = new PotionData(type, getBit(effectId, 6) == 1, getBit(effectId, 5) == 1); meta.setBasePotionData(data); // this method is exclusive to recent 1.9+ potion.setItemMeta(meta); return potion; } - private static int getBit(int n, int k) { - return (n >> k) & 1; - } - @Override public String getDescription() { return "1.9+ Potion Meta Provider"; diff --git a/providers/BaseProviders/src/net/ess3/provider/providers/BlockMetaSpawnerItemProvider.java b/providers/BaseProviders/src/net/ess3/provider/providers/BlockMetaSpawnerItemProvider.java index cc67da3b2..790231060 100644 --- a/providers/BaseProviders/src/net/ess3/provider/providers/BlockMetaSpawnerItemProvider.java +++ b/providers/BaseProviders/src/net/ess3/provider/providers/BlockMetaSpawnerItemProvider.java @@ -9,9 +9,9 @@ import org.bukkit.inventory.meta.BlockStateMeta; public class BlockMetaSpawnerItemProvider implements SpawnerItemProvider { @Override - public ItemStack setEntityType(ItemStack is, EntityType type) throws IllegalArgumentException { - BlockStateMeta bsm = (BlockStateMeta) is.getItemMeta(); - BlockState bs = bsm.getBlockState(); + public ItemStack setEntityType(final ItemStack is, final EntityType type) throws IllegalArgumentException { + final BlockStateMeta bsm = (BlockStateMeta) is.getItemMeta(); + final BlockState bs = bsm.getBlockState(); ((CreatureSpawner) bs).setSpawnedType(type); bsm.setBlockState(bs); is.setItemMeta(bsm); @@ -19,9 +19,9 @@ public class BlockMetaSpawnerItemProvider implements SpawnerItemProvider { } @Override - public EntityType getEntityType(ItemStack is) throws IllegalArgumentException { - BlockStateMeta bsm = (BlockStateMeta) is.getItemMeta(); - CreatureSpawner bs = (CreatureSpawner) bsm.getBlockState(); + public EntityType getEntityType(final ItemStack is) throws IllegalArgumentException { + final BlockStateMeta bsm = (BlockStateMeta) is.getItemMeta(); + final CreatureSpawner bs = (CreatureSpawner) bsm.getBlockState(); return bs.getSpawnedType(); } diff --git a/providers/BaseProviders/src/net/ess3/provider/providers/BukkitSpawnerBlockProvider.java b/providers/BaseProviders/src/net/ess3/provider/providers/BukkitSpawnerBlockProvider.java index eac24e970..fd6e8c30e 100644 --- a/providers/BaseProviders/src/net/ess3/provider/providers/BukkitSpawnerBlockProvider.java +++ b/providers/BaseProviders/src/net/ess3/provider/providers/BukkitSpawnerBlockProvider.java @@ -5,12 +5,12 @@ import org.bukkit.block.CreatureSpawner; public class BukkitSpawnerBlockProvider implements SpawnerBlockProvider { @Override - public void setMaxSpawnDelay(CreatureSpawner spawner, int delay) { + public void setMaxSpawnDelay(final CreatureSpawner spawner, final int delay) { spawner.setMaxSpawnDelay(delay); } @Override - public void setMinSpawnDelay(CreatureSpawner spawner, int delay) { + public void setMinSpawnDelay(final CreatureSpawner spawner, final int delay) { spawner.setMinSpawnDelay(delay); } diff --git a/providers/BaseProviders/src/net/ess3/provider/providers/FlatSpawnEggProvider.java b/providers/BaseProviders/src/net/ess3/provider/providers/FlatSpawnEggProvider.java index e90bc20be..794a47707 100644 --- a/providers/BaseProviders/src/net/ess3/provider/providers/FlatSpawnEggProvider.java +++ b/providers/BaseProviders/src/net/ess3/provider/providers/FlatSpawnEggProvider.java @@ -7,14 +7,14 @@ import org.bukkit.inventory.ItemStack; public class FlatSpawnEggProvider implements SpawnEggProvider { @Override - public ItemStack createEggItem(EntityType type) throws IllegalArgumentException { - Material material = Material.valueOf(type.name() + "_SPAWN_EGG"); + public ItemStack createEggItem(final EntityType type) throws IllegalArgumentException { + final Material material = Material.valueOf(type.name() + "_SPAWN_EGG"); return new ItemStack(material); } @Override - public EntityType getSpawnedType(ItemStack eggItem) throws IllegalArgumentException { - String materialName = eggItem.getType().name(); + public EntityType getSpawnedType(final ItemStack eggItem) throws IllegalArgumentException { + final String materialName = eggItem.getType().name(); if (materialName.contains("_SPAWN_EGG")) { return EntityType.valueOf(materialName.replace("_SPAWN_EGG", "")); } diff --git a/providers/BaseProviders/src/net/ess3/provider/providers/LegacyPotionMetaProvider.java b/providers/BaseProviders/src/net/ess3/provider/providers/LegacyPotionMetaProvider.java index 6391ee585..2ab157895 100644 --- a/providers/BaseProviders/src/net/ess3/provider/providers/LegacyPotionMetaProvider.java +++ b/providers/BaseProviders/src/net/ess3/provider/providers/LegacyPotionMetaProvider.java @@ -7,8 +7,8 @@ import org.bukkit.inventory.ItemStack; @SuppressWarnings("deprecation") public class LegacyPotionMetaProvider implements PotionMetaProvider { @Override - public ItemStack createPotionItem(Material initial, int effectId) { - ItemStack potion = new ItemStack(initial, 1); + public ItemStack createPotionItem(final Material initial, final int effectId) { + final ItemStack potion = new ItemStack(initial, 1); potion.setDurability((short) effectId); return potion; } diff --git a/providers/BaseProviders/src/net/ess3/provider/providers/LegacySpawnEggProvider.java b/providers/BaseProviders/src/net/ess3/provider/providers/LegacySpawnEggProvider.java index 8fb3c751c..c16bee48f 100644 --- a/providers/BaseProviders/src/net/ess3/provider/providers/LegacySpawnEggProvider.java +++ b/providers/BaseProviders/src/net/ess3/provider/providers/LegacySpawnEggProvider.java @@ -9,13 +9,13 @@ import org.bukkit.material.SpawnEgg; @SuppressWarnings("deprecation") public class LegacySpawnEggProvider implements SpawnEggProvider { @Override - public ItemStack createEggItem(EntityType type) throws IllegalArgumentException { + public ItemStack createEggItem(final EntityType type) throws IllegalArgumentException { return new SpawnEgg(type).toItemStack(); } @Override - public EntityType getSpawnedType(ItemStack eggItem) throws IllegalArgumentException { - MaterialData data = eggItem.getData(); + public EntityType getSpawnedType(final ItemStack eggItem) throws IllegalArgumentException { + final MaterialData data = eggItem.getData(); if (data instanceof SpawnEgg) { return ((SpawnEgg) data).getSpawnedType(); } diff --git a/providers/NMSReflectionProvider/src/net/ess3/nms/refl/ReflUtil.java b/providers/NMSReflectionProvider/src/net/ess3/nms/refl/ReflUtil.java index a14602e8a..30aa79e1b 100644 --- a/providers/NMSReflectionProvider/src/net/ess3/nms/refl/ReflUtil.java +++ b/providers/NMSReflectionProvider/src/net/ess3/nms/refl/ReflUtil.java @@ -15,18 +15,27 @@ import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; -public class ReflUtil { +public final class ReflUtil { + public static final NMSVersion V1_12_R1 = NMSVersion.fromString("v1_12_R1"); public static final NMSVersion V1_8_R1 = NMSVersion.fromString("v1_8_R1"); public static final NMSVersion V1_9_R1 = NMSVersion.fromString("v1_9_R1"); public static final NMSVersion V1_11_R1 = NMSVersion.fromString("v1_11_R1"); - public static final NMSVersion V1_12_R1 = NMSVersion.fromString("v1_12_R1"); + private static final Map> classCache = new HashMap<>(); + private static final Table, String, Method> methodCache = HashBasedTable.create(); + private static final Table, MethodParams, Method> methodParamCache = HashBasedTable.create(); + private static final Table, String, Field> fieldCache = HashBasedTable.create(); + private static final Map, Constructor> constructorCache = new HashMap<>(); + private static final Table, ConstructorParams, Constructor> constructorParamCache = HashBasedTable.create(); private static NMSVersion nmsVersionObject; private static String nmsVersion; + private ReflUtil() { + } + public static String getNMSVersion() { if (nmsVersion == null) { - String name = Bukkit.getServer().getClass().getName(); - String[] parts = name.split("\\."); + final String name = Bukkit.getServer().getClass().getName(); + final String[] parts = name.split("\\."); nmsVersion = parts[3]; } return nmsVersion; @@ -39,107 +48,95 @@ public class ReflUtil { return nmsVersionObject; } - public static Class getNMSClass(String className) { + public static Class getNMSClass(final String className) { return getClassCached("net.minecraft.server." + getNMSVersion() + "." + className); } - public static Class getOBCClass(String className) { + public static Class getOBCClass(final String className) { return getClassCached("org.bukkit.craftbukkit." + getNMSVersion() + "." + className); } - private static final Map> classCache = new HashMap<>(); - - public static Class getClassCached(String className) { + public static Class getClassCached(final String className) { if (classCache.containsKey(className)) { return classCache.get(className); } try { - Class classForName = Class.forName(className); + final Class classForName = Class.forName(className); classCache.put(className, classForName); return classForName; - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { return null; } } - private static final Table, String, Method> methodCache = HashBasedTable.create(); - - public static Method getMethodCached(Class clazz, String methodName) { + public static Method getMethodCached(final Class clazz, final String methodName) { if (methodCache.contains(clazz, methodName)) { return methodCache.get(clazz, methodName); } try { - Method method = clazz.getDeclaredMethod(methodName); + final Method method = clazz.getDeclaredMethod(methodName); method.setAccessible(true); methodCache.put(clazz, methodName, method); return method; - } catch (NoSuchMethodException e) { + } catch (final NoSuchMethodException e) { return null; } } - private static final Table, MethodParams, Method> methodParamCache = HashBasedTable.create(); - - public static Method getMethodCached(Class clazz, String methodName, Class... params) { - MethodParams methodParams = new MethodParams(methodName, params); + public static Method getMethodCached(final Class clazz, final String methodName, final Class... params) { + final MethodParams methodParams = new MethodParams(methodName, params); if (methodParamCache.contains(clazz, methodParams)) { return methodParamCache.get(clazz, methodParams); } try { - Method method = clazz.getDeclaredMethod(methodName, params); + final Method method = clazz.getDeclaredMethod(methodName, params); method.setAccessible(true); methodParamCache.put(clazz, methodParams, method); return method; - } catch (NoSuchMethodException e) { + } catch (final NoSuchMethodException e) { return null; } } - private static final Table, String, Field> fieldCache = HashBasedTable.create(); - - public static Field getFieldCached(Class clazz, String fieldName) { + public static Field getFieldCached(final Class clazz, final String fieldName) { if (fieldCache.contains(clazz, fieldName)) { return fieldCache.get(clazz, fieldName); } try { - Field field = clazz.getDeclaredField(fieldName); + final Field field = clazz.getDeclaredField(fieldName); field.setAccessible(true); fieldCache.put(clazz, fieldName, field); return field; - } catch (NoSuchFieldException e) { + } catch (final NoSuchFieldException e) { return null; } } - private static final Map, Constructor> constructorCache = new HashMap<>(); - - public static Constructor getConstructorCached(Class clazz) { + public static Constructor getConstructorCached(final Class clazz) { if (constructorCache.containsKey(clazz)) { return constructorCache.get(clazz); } try { - Constructor constructor = clazz.getDeclaredConstructor(); + final Constructor constructor = clazz.getDeclaredConstructor(); constructor.setAccessible(true); constructorCache.put(clazz, constructor); return constructor; - } catch (NoSuchMethodException e) { + } catch (final NoSuchMethodException e) { return null; } } - private static final Table, ConstructorParams, Constructor> constructorParamCache = HashBasedTable.create(); - - public static Constructor getConstructorCached(Class clazz, Class... params) { - ConstructorParams constructorParams = new ConstructorParams(params); + public static Constructor getConstructorCached(final Class clazz, final Class... params) { + final ConstructorParams constructorParams = new ConstructorParams(params); if (constructorParamCache.contains(clazz, constructorParams)) { return constructorParamCache.get(clazz, constructorParams); } try { - Constructor constructor = clazz.getDeclaredConstructor(params); + final Constructor constructor = clazz.getDeclaredConstructor(params); constructor.setAccessible(true); constructorParamCache.put(clazz, constructorParams, constructor); return constructor; - } catch (NoSuchMethodException e) { + } catch (final NoSuchMethodException e) { return null; } } @@ -197,16 +194,16 @@ public class ReflUtil { private static class ConstructorParams { private final Class[] params; - ConstructorParams(Class[] params) { + ConstructorParams(final Class[] params) { this.params = params; } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; - ConstructorParams that = (ConstructorParams) o; + final ConstructorParams that = (ConstructorParams) o; return Arrays.deepEquals(params, that.params); } @@ -222,13 +219,19 @@ public class ReflUtil { * * @author SupaHam (https://github.com/SupaHam) */ - public static class NMSVersion implements Comparable { + public static final class NMSVersion implements Comparable { private static final Pattern VERSION_PATTERN = Pattern.compile("^v(\\d+)_(\\d+)_R(\\d+)"); private final int major; private final int minor; private final int release; - public static NMSVersion fromString(String string) { + private NMSVersion(final int major, final int minor, final int release) { + this.major = major; + this.minor = minor; + this.release = release; + } + + public static NMSVersion fromString(final String string) { Preconditions.checkNotNull(string, "string cannot be null."); Matcher matcher = VERSION_PATTERN.matcher(string); if (!matcher.matches()) { @@ -241,25 +244,19 @@ public class ReflUtil { return new NMSVersion(Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)), Integer.parseInt(matcher.group(3))); } - private NMSVersion(int major, int minor, int release) { - this.major = major; - this.minor = minor; - this.release = release; - } - - public boolean isHigherThan(NMSVersion o) { + public boolean isHigherThan(final NMSVersion o) { return compareTo(o) > 0; } - public boolean isHigherThanOrEqualTo(NMSVersion o) { + public boolean isHigherThanOrEqualTo(final NMSVersion o) { return compareTo(o) >= 0; } - public boolean isLowerThan(NMSVersion o) { + public boolean isLowerThan(final NMSVersion o) { return compareTo(o) < 0; } - public boolean isLowerThanOrEqualTo(NMSVersion o) { + public boolean isLowerThanOrEqualTo(final NMSVersion o) { return compareTo(o) <= 0; } @@ -276,17 +273,17 @@ public class ReflUtil { } @Override - public boolean equals(Object o) { + public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } - NMSVersion that = (NMSVersion) o; + final NMSVersion that = (NMSVersion) o; return major == that.major && - minor == that.minor && - release == that.release; + minor == that.minor && + release == that.release; } @Override @@ -300,7 +297,7 @@ public class ReflUtil { } @Override - public int compareTo(NMSVersion o) { + public int compareTo(final NMSVersion o) { if (major < o.major) { return -1; } else if (major > o.major) { diff --git a/providers/NMSReflectionProvider/src/net/ess3/nms/refl/SpawnEggRefl.java b/providers/NMSReflectionProvider/src/net/ess3/nms/refl/SpawnEggRefl.java index 267a86cf1..4c1c7e59e 100644 --- a/providers/NMSReflectionProvider/src/net/ess3/nms/refl/SpawnEggRefl.java +++ b/providers/NMSReflectionProvider/src/net/ess3/nms/refl/SpawnEggRefl.java @@ -33,10 +33,49 @@ import java.lang.reflect.Method; public class SpawnEggRefl { private EntityType type; - public SpawnEggRefl(EntityType type) { + public SpawnEggRefl(final EntityType type) { this.type = type; } + /** + * Converts from an item stack to a spawn egg + * + * @param item - ItemStack, quantity is disregarded + * @return SpawnEgg + */ + public static SpawnEggRefl fromItemStack(final ItemStack item) throws Exception { + if (item == null) + throw new IllegalArgumentException("Item cannot be null"); + if (item.getType() != Material.MONSTER_EGG) + throw new IllegalArgumentException("Item is not a monster egg"); + + final Class NMSItemStackClass = ReflUtil.getNMSClass("ItemStack"); + final Class craftItemStackClass = ReflUtil.getOBCClass("inventory.CraftItemStack"); + final Method asNMSCopyMethod = ReflUtil.getMethodCached(craftItemStackClass, "asNMSCopy", ItemStack.class); + + final Object stack = asNMSCopyMethod.invoke(null, item); + final Object tagCompound = ReflUtil.getMethodCached(NMSItemStackClass, "getTag").invoke(stack); + if (tagCompound != null) { + final Method tagGetCompound = ReflUtil.getMethodCached(tagCompound.getClass(), "getCompound", String.class); + final Object entityTag = tagGetCompound.invoke(tagCompound, "EntityTag"); + + final Method tagGetString = ReflUtil.getMethodCached(entityTag.getClass(), "getString", String.class); + String idString = (String) tagGetString.invoke(entityTag, "id"); + if (ReflUtil.getNmsVersionObject().isHigherThanOrEqualTo(ReflUtil.V1_11_R1)) { + idString = idString.split("minecraft:")[1]; + } + //noinspection deprecation + final EntityType type = EntityType.fromName(idString); + if (type != null) { + return new SpawnEggRefl(type); + } else { + throw new IllegalArgumentException("Unable to parse type from item"); + } + } else { + throw new IllegalArgumentException("Item is lacking tag compound"); + } + } + /** * Get the type of entity this egg will spawn. * @@ -51,7 +90,7 @@ public class SpawnEggRefl { * * @param type The entity type. */ - public void setSpawnedType(EntityType type) { + public void setSpawnedType(final EntityType type) { if (type.isAlive()) { this.type = type; } @@ -78,23 +117,23 @@ public class SpawnEggRefl { * @return ItemStack of spawn eggs */ @SuppressWarnings("deprecation") - public ItemStack toItemStack(int amount) throws Exception { - ItemStack item = new ItemStack(Material.MONSTER_EGG, amount); + public ItemStack toItemStack(final int amount) throws Exception { + final ItemStack item = new ItemStack(Material.MONSTER_EGG, amount); - Class craftItemStackClass = ReflUtil.getOBCClass("inventory.CraftItemStack"); - Method asNMSCopyMethod = ReflUtil.getMethodCached(craftItemStackClass, "asNMSCopy", ItemStack.class); + final Class craftItemStackClass = ReflUtil.getOBCClass("inventory.CraftItemStack"); + final Method asNMSCopyMethod = ReflUtil.getMethodCached(craftItemStackClass, "asNMSCopy", ItemStack.class); - Class NMSItemStackClass = ReflUtil.getNMSClass("ItemStack"); - Object stack = asNMSCopyMethod.invoke(null, item); + final Class NMSItemStackClass = ReflUtil.getNMSClass("ItemStack"); + final Object stack = asNMSCopyMethod.invoke(null, item); Object tagCompound = ReflUtil.getMethodCached(NMSItemStackClass, "getTag").invoke(stack); - Class NBTTagCompoundClass = ReflUtil.getNMSClass("NBTTagCompound"); - Constructor NBTTagCompoundConstructor = ReflUtil.getConstructorCached(NBTTagCompoundClass); + final Class NBTTagCompoundClass = ReflUtil.getNMSClass("NBTTagCompound"); + final Constructor NBTTagCompoundConstructor = ReflUtil.getConstructorCached(NBTTagCompoundClass); if (tagCompound == null) { tagCompound = NBTTagCompoundConstructor.newInstance(); } - Object id = NBTTagCompoundConstructor.newInstance(); - Method tagSetString = ReflUtil.getMethodCached(NBTTagCompoundClass, "setString", String.class, String.class); + final Object id = NBTTagCompoundConstructor.newInstance(); + final Method tagSetString = ReflUtil.getMethodCached(NBTTagCompoundClass, "setString", String.class, String.class); String idString = type.getName(); if (ReflUtil.getNmsVersionObject().isHigherThanOrEqualTo(ReflUtil.V1_11_R1)) { @@ -103,52 +142,13 @@ public class SpawnEggRefl { } tagSetString.invoke(id, "id", idString); - Method tagSetTag = ReflUtil.getMethodCached(NBTTagCompoundClass, "set", String.class, NBTTagCompoundClass.getSuperclass()); + final Method tagSetTag = ReflUtil.getMethodCached(NBTTagCompoundClass, "set", String.class, NBTTagCompoundClass.getSuperclass()); tagSetTag.invoke(tagCompound, "EntityTag", id); - Method stackSetTag = ReflUtil.getMethodCached(NMSItemStackClass, "setTag", NBTTagCompoundClass); + final Method stackSetTag = ReflUtil.getMethodCached(NMSItemStackClass, "setTag", NBTTagCompoundClass); stackSetTag.invoke(stack, tagCompound); - Method asBukkitCopyMethod = ReflUtil.getMethodCached(craftItemStackClass, "asBukkitCopy", NMSItemStackClass); + final Method asBukkitCopyMethod = ReflUtil.getMethodCached(craftItemStackClass, "asBukkitCopy", NMSItemStackClass); return (ItemStack) asBukkitCopyMethod.invoke(null, stack); } - - /** - * Converts from an item stack to a spawn egg - * - * @param item - ItemStack, quantity is disregarded - * @return SpawnEgg - */ - public static SpawnEggRefl fromItemStack(ItemStack item) throws Exception { - if (item == null) - throw new IllegalArgumentException("Item cannot be null"); - if (item.getType() != Material.MONSTER_EGG) - throw new IllegalArgumentException("Item is not a monster egg"); - - Class NMSItemStackClass = ReflUtil.getNMSClass("ItemStack"); - Class craftItemStackClass = ReflUtil.getOBCClass("inventory.CraftItemStack"); - Method asNMSCopyMethod = ReflUtil.getMethodCached(craftItemStackClass, "asNMSCopy", ItemStack.class); - - Object stack = asNMSCopyMethod.invoke(null, item); - Object tagCompound = ReflUtil.getMethodCached(NMSItemStackClass, "getTag").invoke(stack); - if (tagCompound != null) { - Method tagGetCompound = ReflUtil.getMethodCached(tagCompound.getClass(), "getCompound", String.class); - Object entityTag = tagGetCompound.invoke(tagCompound, "EntityTag"); - - Method tagGetString = ReflUtil.getMethodCached(entityTag.getClass(), "getString", String.class); - String idString = (String) tagGetString.invoke(entityTag, "id"); - if (ReflUtil.getNmsVersionObject().isHigherThanOrEqualTo(ReflUtil.V1_11_R1)) { - idString = idString.split("minecraft:")[1]; - } - @SuppressWarnings("deprecation") - EntityType type = EntityType.fromName(idString); - if (type != null) { - return new SpawnEggRefl(type); - } else { - throw new IllegalArgumentException("Unable to parse type from item"); - } - } else { - throw new IllegalArgumentException("Item is lacking tag compound"); - } - } } diff --git a/providers/NMSReflectionProvider/src/net/ess3/nms/refl/providers/ReflServerStateProvider.java b/providers/NMSReflectionProvider/src/net/ess3/nms/refl/providers/ReflServerStateProvider.java index c4b49e730..f19145b60 100644 --- a/providers/NMSReflectionProvider/src/net/ess3/nms/refl/providers/ReflServerStateProvider.java +++ b/providers/NMSReflectionProvider/src/net/ess3/nms/refl/providers/ReflServerStateProvider.java @@ -12,14 +12,14 @@ public class ReflServerStateProvider implements ServerStateProvider { private final Object nmsServer; private final MethodHandle nmsIsRunning; - public ReflServerStateProvider(Logger logger) { + public ReflServerStateProvider(final Logger logger) { Object serverObject = null; MethodHandle isRunning = null; - Class nmsClass = ReflUtil.getNMSClass("MinecraftServer"); + final Class nmsClass = ReflUtil.getNMSClass("MinecraftServer"); try { serverObject = nmsClass.getMethod("getServer").invoke(null); isRunning = MethodHandles.lookup().findVirtual(nmsClass, "isRunning", MethodType.methodType(boolean.class)); - } catch (Exception e) { + } catch (final Exception e) { e.printStackTrace(); } nmsServer = serverObject; @@ -31,7 +31,7 @@ public class ReflServerStateProvider implements ServerStateProvider { if (nmsServer != null && nmsIsRunning != null) { try { return !(boolean) nmsIsRunning.invoke(nmsServer); - } catch (Throwable throwable) { + } catch (final Throwable throwable) { throwable.printStackTrace(); } } diff --git a/providers/NMSReflectionProvider/src/net/ess3/nms/refl/providers/ReflSpawnEggProvider.java b/providers/NMSReflectionProvider/src/net/ess3/nms/refl/providers/ReflSpawnEggProvider.java index 284f40c85..34b68f870 100644 --- a/providers/NMSReflectionProvider/src/net/ess3/nms/refl/providers/ReflSpawnEggProvider.java +++ b/providers/NMSReflectionProvider/src/net/ess3/nms/refl/providers/ReflSpawnEggProvider.java @@ -8,19 +8,19 @@ import org.bukkit.inventory.ItemStack; public class ReflSpawnEggProvider implements SpawnEggProvider { @Override - public ItemStack createEggItem(EntityType type) throws IllegalArgumentException { + public ItemStack createEggItem(final EntityType type) throws IllegalArgumentException { try { return new SpawnEggRefl(type).toItemStack(); - } catch (Exception e) { + } catch (final Exception e) { throw new IllegalArgumentException(e.getMessage(), e.getCause()); } } @Override - public EntityType getSpawnedType(ItemStack eggItem) throws IllegalArgumentException { + public EntityType getSpawnedType(final ItemStack eggItem) throws IllegalArgumentException { try { return SpawnEggRefl.fromItemStack(eggItem).getSpawnedType(); - } catch (Exception e) { + } catch (final Exception e) { throw new IllegalArgumentException(e.getMessage(), e.getCause()); } } diff --git a/providers/NMSReflectionProvider/src/net/ess3/nms/refl/providers/ReflSpawnerBlockProvider.java b/providers/NMSReflectionProvider/src/net/ess3/nms/refl/providers/ReflSpawnerBlockProvider.java index 554cc9908..96266474c 100644 --- a/providers/NMSReflectionProvider/src/net/ess3/nms/refl/providers/ReflSpawnerBlockProvider.java +++ b/providers/NMSReflectionProvider/src/net/ess3/nms/refl/providers/ReflSpawnerBlockProvider.java @@ -10,25 +10,25 @@ import java.lang.reflect.Method; public class ReflSpawnerBlockProvider implements SpawnerBlockProvider { @Override - public void setMaxSpawnDelay(CreatureSpawner spawner, int delay) { - Class mobSpawnerAbstract = ReflUtil.getNMSClass("MobSpawnerAbstract"); - Field maxSpawnDelay = ReflUtil.getFieldCached(mobSpawnerAbstract, "maxSpawnDelay"); + public void setMaxSpawnDelay(final CreatureSpawner spawner, final int delay) { + final Class mobSpawnerAbstract = ReflUtil.getNMSClass("MobSpawnerAbstract"); + final Field maxSpawnDelay = ReflUtil.getFieldCached(mobSpawnerAbstract, "maxSpawnDelay"); if (maxSpawnDelay != null) { try { maxSpawnDelay.setInt(getNMSSpawner(spawner), delay); - } catch (IllegalAccessException ignored) { + } catch (final IllegalAccessException ignored) { } } } @Override - public void setMinSpawnDelay(CreatureSpawner spawner, int delay) { - Class mobSpawnerAbstract = ReflUtil.getNMSClass("MobSpawnerAbstract"); - Field minSpawnDelay = ReflUtil.getFieldCached(mobSpawnerAbstract, "minSpawnDelay"); + public void setMinSpawnDelay(final CreatureSpawner spawner, final int delay) { + final Class mobSpawnerAbstract = ReflUtil.getNMSClass("MobSpawnerAbstract"); + final Field minSpawnDelay = ReflUtil.getFieldCached(mobSpawnerAbstract, "minSpawnDelay"); if (minSpawnDelay != null) { try { minSpawnDelay.setInt(getNMSSpawner(spawner), delay); - } catch (IllegalAccessException ignored) { + } catch (final IllegalAccessException ignored) { } } } @@ -38,17 +38,17 @@ public class ReflSpawnerBlockProvider implements SpawnerBlockProvider { return "Reflection based provider"; } - private Object getNMSSpawner(CreatureSpawner spawner) { + private Object getNMSSpawner(final CreatureSpawner spawner) { try { - Class craftWorld = ReflUtil.getOBCClass("CraftWorld"); - Class tileEntityMobSpawner = ReflUtil.getNMSClass("TileEntityMobSpawner"); - Method getSpawner = ReflUtil.getMethodCached(tileEntityMobSpawner, "getSpawner"); - Method getTileEntityAt = ReflUtil.getMethodCached(craftWorld, "getTileEntityAt", int.class, int.class, int.class); + final Class craftWorld = ReflUtil.getOBCClass("CraftWorld"); + final Class tileEntityMobSpawner = ReflUtil.getNMSClass("TileEntityMobSpawner"); + final Method getSpawner = ReflUtil.getMethodCached(tileEntityMobSpawner, "getSpawner"); + final Method getTileEntityAt = ReflUtil.getMethodCached(craftWorld, "getTileEntityAt", int.class, int.class, int.class); if (getSpawner != null && getTileEntityAt != null) { - Object craftTileEntity = getTileEntityAt.invoke(spawner.getWorld(), spawner.getX(), spawner.getY(), spawner.getZ()); + final Object craftTileEntity = getTileEntityAt.invoke(spawner.getWorld(), spawner.getX(), spawner.getY(), spawner.getZ()); return getSpawner.invoke(craftTileEntity); } - } catch (IllegalAccessException | InvocationTargetException ignored) { + } catch (final IllegalAccessException | InvocationTargetException ignored) { } return null; } diff --git a/providers/PaperProvider/src/net/ess3/provider/providers/PaperRecipeBookListener.java b/providers/PaperProvider/src/net/ess3/provider/providers/PaperRecipeBookListener.java index 217b3eca2..2db752d51 100644 --- a/providers/PaperProvider/src/net/ess3/provider/providers/PaperRecipeBookListener.java +++ b/providers/PaperProvider/src/net/ess3/provider/providers/PaperRecipeBookListener.java @@ -8,12 +8,12 @@ import org.bukkit.event.EventHandler; import java.util.function.Consumer; public class PaperRecipeBookListener extends ProviderListener { - public PaperRecipeBookListener(Consumer function) { + public PaperRecipeBookListener(final Consumer function) { super(function); } @EventHandler - public void onPlayerRecipeBookClick(PlayerRecipeBookClickEvent event) { + public void onPlayerRecipeBookClick(final PlayerRecipeBookClickEvent event) { function.accept(event); }