From 9d41899b970c01e4b482ddb5d06f2b6f9d11a656 Mon Sep 17 00:00:00 2001 From: ementalo Date: Mon, 16 Jul 2012 15:01:00 +0100 Subject: Package Renames --- .../src/com/earth2me/essentials/Console.java | 33 - .../src/com/earth2me/essentials/Essentials.java | 378 ------------ .../com/earth2me/essentials/EssentialsTimer.java | 83 --- Essentials/src/com/earth2me/essentials/I18n.java | 177 ------ Essentials/src/com/earth2me/essentials/ItemDb.java | 151 ----- Essentials/src/com/earth2me/essentials/Jails.java | 301 --------- Essentials/src/com/earth2me/essentials/Kits.java | 90 --- .../src/com/earth2me/essentials/Teleport.java | 301 --------- Essentials/src/com/earth2me/essentials/Warps.java | 149 ----- .../earth2me/essentials/api/ChargeException.java | 15 - .../src/com/earth2me/essentials/api/IBackup.java | 7 - .../earth2me/essentials/api/ICommandHandler.java | 20 - .../com/earth2me/essentials/api/IComponent.java | 13 - .../src/com/earth2me/essentials/api/IEconomy.java | 21 - .../com/earth2me/essentials/api/IEssentials.java | 65 -- .../earth2me/essentials/api/IEssentialsModule.java | 6 - .../src/com/earth2me/essentials/api/II18n.java | 9 - .../src/com/earth2me/essentials/api/IItemDb.java | 13 - .../src/com/earth2me/essentials/api/IJails.java | 18 - .../src/com/earth2me/essentials/api/IKits.java | 18 - .../com/earth2me/essentials/api/IPermission.java | 16 - .../src/com/earth2me/essentials/api/IRanks.java | 25 - .../src/com/earth2me/essentials/api/IReload.java | 7 - .../src/com/earth2me/essentials/api/IReplyTo.java | 11 - .../src/com/earth2me/essentials/api/ISettings.java | 14 - .../src/com/earth2me/essentials/api/ITeleport.java | 28 - .../src/com/earth2me/essentials/api/IUser.java | 110 ---- .../src/com/earth2me/essentials/api/IUserMap.java | 29 - .../src/com/earth2me/essentials/api/IWarp.java | 9 - .../src/com/earth2me/essentials/api/IWarps.java | 21 - .../src/com/earth2me/essentials/api/IWorth.java | 12 - .../essentials/api/InvalidNameException.java | 10 - .../essentials/api/NoLoanPermittedException.java | 12 - .../essentials/api/UserDoesNotExistException.java | 12 - .../essentials/api/server/CommandSender.java | 13 - .../essentials/api/server/Enchantment.java | 7 - .../earth2me/essentials/api/server/IInventory.java | 19 - .../earth2me/essentials/api/server/IPlugin.java | 32 - .../earth2me/essentials/api/server/IServer.java | 28 - .../earth2me/essentials/api/server/ItemStack.java | 47 -- .../earth2me/essentials/api/server/Location.java | 52 -- .../earth2me/essentials/api/server/Material.java | 37 -- .../earth2me/essentials/api/server/Permission.java | 27 - .../com/earth2me/essentials/api/server/Player.java | 61 -- .../com/earth2me/essentials/api/server/World.java | 26 - .../src/com/earth2me/essentials/backup/Backup.java | 150 ----- .../essentials/bukkit/BukkitCommandSender.java | 40 -- .../essentials/bukkit/BukkitItemStack.java | 62 -- .../earth2me/essentials/bukkit/BukkitLocation.java | 63 -- .../earth2me/essentials/bukkit/BukkitMaterial.java | 62 -- .../essentials/bukkit/BukkitPermission.java | 82 --- .../earth2me/essentials/bukkit/BukkitPlayer.java | 202 ------- .../earth2me/essentials/bukkit/BukkitWorld.java | 45 -- .../earth2me/essentials/bukkit/Enchantments.java | 88 --- .../essentials/bukkit/EssentialsPlugin.java | 95 --- .../com/earth2me/essentials/bukkit/Inventory.java | 48 -- .../src/com/earth2me/essentials/bukkit/Mob.java | 120 ---- .../src/com/earth2me/essentials/bukkit/Plugin.java | 87 --- .../src/com/earth2me/essentials/bukkit/Server.java | 126 ---- .../earth2me/essentials/bukkit/VersionCheck.java | 46 -- .../earth2me/essentials/commands/Commandafk.java | 55 -- .../essentials/commands/Commandantioch.java | 23 - .../earth2me/essentials/commands/Commandback.java | 19 - .../essentials/commands/Commandbackup.java | 18 - .../essentials/commands/Commandbalance.java | 32 - .../essentials/commands/Commandbalancetop.java | 180 ------ .../earth2me/essentials/commands/Commandban.java | 68 --- .../earth2me/essentials/commands/Commandbanip.java | 40 -- .../essentials/commands/Commandbigtree.java | 41 -- .../earth2me/essentials/commands/Commandbreak.java | 41 -- .../essentials/commands/Commandbroadcast.java | 20 - .../earth2me/essentials/commands/Commandburn.java | 24 - .../essentials/commands/Commandclearinventory.java | 93 --- .../essentials/commands/Commandcompass.java | 52 -- .../essentials/commands/Commanddelhome.java | 60 -- .../essentials/commands/Commanddeljail.java | 20 - .../essentials/commands/Commanddelwarp.java | 20 - .../earth2me/essentials/commands/Commanddepth.java | 26 - .../earth2me/essentials/commands/Commandeco.java | 121 ---- .../essentials/commands/Commandenchant.java | 94 --- .../essentials/commands/Commandessentials.java | 172 ------ .../earth2me/essentials/commands/Commandext.java | 43 -- .../earth2me/essentials/commands/Commandfeed.java | 46 -- .../essentials/commands/Commandfireball.java | 23 - .../essentials/commands/Commandgamemode.java | 53 -- .../earth2me/essentials/commands/Commandgc.java | 27 - .../essentials/commands/Commandgetpos.java | 51 -- .../earth2me/essentials/commands/Commandgive.java | 76 --- .../earth2me/essentials/commands/Commandgod.java | 50 -- .../earth2me/essentials/commands/Commandheal.java | 64 -- .../earth2me/essentials/commands/Commandhelp.java | 51 -- .../essentials/commands/Commandhelpop.java | 34 -- .../earth2me/essentials/commands/Commandhome.java | 91 --- .../essentials/commands/Commandignore.java | 42 -- .../earth2me/essentials/commands/Commandinfo.java | 21 - .../essentials/commands/Commandinvsee.java | 52 -- .../earth2me/essentials/commands/Commanditem.java | 66 -- .../essentials/commands/Commanditemdb.java | 32 - .../earth2me/essentials/commands/Commandjails.java | 15 - .../earth2me/essentials/commands/Commandjump.java | 36 -- .../earth2me/essentials/commands/Commandkick.java | 40 -- .../essentials/commands/Commandkickall.java | 25 - .../earth2me/essentials/commands/Commandkill.java | 34 -- .../essentials/commands/Commandkillall.java | 145 ----- .../earth2me/essentials/commands/Commandkit.java | 62 -- .../essentials/commands/Commandkittycannon.java | 38 -- .../essentials/commands/Commandlightning.java | 73 --- .../earth2me/essentials/commands/Commandlist.java | 166 ----- .../earth2me/essentials/commands/Commandmail.java | 164 ----- .../earth2me/essentials/commands/Commandme.java | 36 -- .../earth2me/essentials/commands/Commandmore.java | 57 -- .../earth2me/essentials/commands/Commandmotd.java | 21 - .../earth2me/essentials/commands/Commandmsg.java | 99 --- .../earth2me/essentials/commands/Commandmute.java | 52 -- .../earth2me/essentials/commands/Commandnear.java | 112 ---- .../earth2me/essentials/commands/Commandnick.java | 128 ---- .../earth2me/essentials/commands/Commandnuke.java | 55 -- .../earth2me/essentials/commands/Commandpay.java | 44 -- .../earth2me/essentials/commands/Commandping.java | 22 - .../essentials/commands/Commandpowertool.java | 112 ---- .../commands/Commandpowertooltoggle.java | 23 - .../earth2me/essentials/commands/Commandptime.java | 229 ------- .../com/earth2me/essentials/commands/Commandr.java | 86 --- .../essentials/commands/Commandrealname.java | 44 -- .../essentials/commands/Commandremove.java | 156 ----- .../essentials/commands/Commandrepair.java | 137 ----- .../earth2me/essentials/commands/Commandrules.java | 21 - .../earth2me/essentials/commands/Commandseen.java | 55 -- .../earth2me/essentials/commands/Commandsell.java | 152 ----- .../essentials/commands/Commandsethome.java | 93 --- .../essentials/commands/Commandsetjail.java | 20 - .../essentials/commands/Commandsetspawn.java | 17 - .../essentials/commands/Commandsetwarp.java | 47 -- .../essentials/commands/Commandsetworth.java | 50 -- .../essentials/commands/Commandsocialspy.java | 14 - .../earth2me/essentials/commands/Commandspawn.java | 56 -- .../essentials/commands/Commandspawner.java | 58 -- .../essentials/commands/Commandspawnmob.java | 281 --------- .../earth2me/essentials/commands/Commandsudo.java | 42 -- .../essentials/commands/Commandsuicide.java | 19 - .../essentials/commands/Commandtempban.java | 63 -- .../essentials/commands/Commandthunder.java | 35 -- .../earth2me/essentials/commands/Commandtime.java | 150 ----- .../essentials/commands/Commandtogglejail.java | 107 ---- .../earth2me/essentials/commands/Commandtop.java | 21 - .../earth2me/essentials/commands/Commandtp.java | 66 -- .../earth2me/essentials/commands/Commandtpa.java | 47 -- .../essentials/commands/Commandtpaall.java | 74 --- .../essentials/commands/Commandtpaccept.java | 76 --- .../essentials/commands/Commandtpahere.java | 46 -- .../earth2me/essentials/commands/Commandtpall.java | 50 -- .../essentials/commands/Commandtpdeny.java | 22 - .../essentials/commands/Commandtphere.java | 27 - .../earth2me/essentials/commands/Commandtpo.java | 38 -- .../essentials/commands/Commandtpohere.java | 39 -- .../earth2me/essentials/commands/Commandtppos.java | 38 -- .../essentials/commands/Commandtptoggle.java | 16 - .../earth2me/essentials/commands/Commandtree.java | 57 -- .../earth2me/essentials/commands/Commandunban.java | 34 -- .../essentials/commands/Commandunbanip.java | 32 - .../essentials/commands/Commandunlimited.java | 112 ---- .../earth2me/essentials/commands/Commandwarp.java | 124 ---- .../essentials/commands/Commandweather.java | 72 --- .../earth2me/essentials/commands/Commandwhois.java | 85 --- .../earth2me/essentials/commands/Commandworld.java | 81 --- .../earth2me/essentials/commands/Commandworth.java | 103 ---- .../essentials/commands/EssentialsCommand.java | 130 ---- .../commands/EssentialsCommandHandler.java | 317 ---------- .../essentials/commands/IEssentialsCommand.java | 22 - .../essentials/commands/NoChargeException.java | 10 - .../commands/NotEnoughArgumentsException.java | 20 - .../essentials/commands/WarpNotFoundException.java | 17 - .../essentials/craftbukkit/FakeExplosion.java | 51 -- .../essentials/craftbukkit/FakeInventory.java | 225 ------- .../craftbukkit/InventoryWorkaround.java | 322 ---------- .../earth2me/essentials/craftbukkit/SetExpFix.java | 58 -- .../com/earth2me/essentials/economy/Economy.java | 207 ------- .../src/com/earth2me/essentials/economy/Money.java | 17 - .../earth2me/essentials/economy/MoneyHolder.java | 22 - .../src/com/earth2me/essentials/economy/Trade.java | 333 ---------- .../src/com/earth2me/essentials/economy/Worth.java | 33 - .../earth2me/essentials/economy/WorthHolder.java | 86 --- .../essentials/economy/register/Method.java | 210 ------- .../essentials/economy/register/Methods.java | 296 --------- .../essentials/economy/register/methods/BOSE6.java | 329 ---------- .../essentials/economy/register/methods/BOSE7.java | 318 ---------- .../essentials/economy/register/methods/MCUR.java | 191 ------ .../economy/register/methods/VaultEco.java | 337 ----------- .../essentials/economy/register/methods/iCo4.java | 251 -------- .../essentials/economy/register/methods/iCo5.java | 371 ------------ .../essentials/economy/register/methods/iCo6.java | 237 -------- .../listener/EssentialsBlockListener.java | 50 -- .../listener/EssentialsEntityListener.java | 138 ----- .../listener/EssentialsPlayerListener.java | 438 -------------- .../listener/EssentialsPluginListener.java | 110 ---- .../essentials/listener/TntExplodeListener.java | 59 -- .../permissions/AbstractSuperpermsPermission.java | 41 -- .../essentials/permissions/BasePermission.java | 16 - .../essentials/permissions/EnchantPermissions.java | 23 - .../essentials/permissions/GivePermissions.java | 31 - .../essentials/permissions/GroupsPermissions.java | 23 - .../essentials/permissions/HelpPermissions.java | 23 - .../essentials/permissions/ItemPermissions.java | 33 - .../essentials/permissions/KitPermissions.java | 31 - .../permissions/NoCommandCostPermissions.java | 23 - .../essentials/permissions/Permissions.java | 123 ---- .../essentials/permissions/SpawnerPermissions.java | 23 - .../permissions/SpawnmobPermissions.java | 21 - .../permissions/UnlimitedItemPermissions.java | 23 - .../essentials/permissions/WarpPermissions.java | 31 - .../essentials/permissions/WorldPermissions.java | 22 - .../com/earth2me/essentials/ranks/GMGroups.java | 143 ----- .../com/earth2me/essentials/ranks/RankOptions.java | 27 - .../src/com/earth2me/essentials/ranks/Ranks.java | 28 - .../earth2me/essentials/ranks/RanksStorage.java | 195 ------ .../com/earth2me/essentials/ranks/VaultGroups.java | 115 ---- .../com/earth2me/essentials/settings/Backup.java | 17 - .../src/com/earth2me/essentials/settings/Chat.java | 33 - .../com/earth2me/essentials/settings/Commands.java | 74 --- .../com/earth2me/essentials/settings/Economy.java | 67 -- .../com/earth2me/essentials/settings/General.java | 54 -- .../com/earth2me/essentials/settings/Jails.java | 18 - .../src/com/earth2me/essentials/settings/Kit.java | 19 - .../src/com/earth2me/essentials/settings/Kits.java | 28 - .../com/earth2me/essentials/settings/Settings.java | 72 --- .../essentials/settings/SettingsHolder.java | 64 -- .../com/earth2me/essentials/settings/Spawns.java | 40 -- .../earth2me/essentials/settings/SpawnsHolder.java | 307 ---------- .../src/com/earth2me/essentials/settings/Warp.java | 14 - .../earth2me/essentials/settings/WarpHolder.java | 35 -- .../earth2me/essentials/settings/WorldOptions.java | 14 - .../com/earth2me/essentials/settings/Worlds.java | 12 - .../earth2me/essentials/settings/commands/Afk.java | 38 -- .../essentials/settings/commands/Back.java | 19 - .../earth2me/essentials/settings/commands/God.java | 15 - .../essentials/settings/commands/Help.java | 23 - .../essentials/settings/commands/Home.java | 26 - .../essentials/settings/commands/Lightning.java | 15 - .../essentials/settings/commands/List.java | 16 - .../essentials/settings/commands/Spawnmob.java | 15 - .../earth2me/essentials/settings/commands/Tpa.java | 21 - .../essentials/settings/geoip/Database.java | 16 - .../earth2me/essentials/settings/geoip/GeoIP.java | 15 - .../essentials/settings/protect/Prevent.java | 45 -- .../essentials/settings/protect/Protect.java | 45 -- .../essentials/settings/protect/SignsAndRails.java | 26 - .../storage/AbstractDelayedYamlFileReader.java | 95 --- .../storage/AbstractDelayedYamlFileWriter.java | 77 --- .../storage/AsyncStorageObjectHolder.java | 186 ------ .../essentials/storage/BukkitConstructor.java | 439 -------------- .../com/earth2me/essentials/storage/Comment.java | 12 - .../essentials/storage/EnchantmentLevel.java | 80 --- .../essentials/storage/IStorageObjectHolder.java | 17 - .../essentials/storage/IStorageObjectMap.java | 22 - .../essentials/storage/IStorageReader.java | 7 - .../essentials/storage/IStorageWriter.java | 7 - .../com/earth2me/essentials/storage/ListType.java | 14 - .../earth2me/essentials/storage/ManagedFile.java | 228 ------- .../earth2me/essentials/storage/MapKeyType.java | 14 - .../earth2me/essentials/storage/MapValueType.java | 14 - .../essentials/storage/ObjectLoadException.java | 10 - .../earth2me/essentials/storage/StorageObject.java | 6 - .../essentials/storage/StorageObjectMap.java | 137 ----- .../essentials/storage/StoredLocation.java | 115 ---- .../essentials/storage/YamlStorageReader.java | 120 ---- .../essentials/storage/YamlStorageWriter.java | 348 ----------- .../src/com/earth2me/essentials/user/Ban.java | 14 - .../essentials/user/CooldownException.java | 12 - .../earth2me/essentials/user/IOfflinePlayer.java | 18 - .../com/earth2me/essentials/user/IOfflineUser.java | 9 - .../com/earth2me/essentials/user/Inventory.java | 58 -- .../essentials/user/TooManyMatchesException.java | 5 - .../src/com/earth2me/essentials/user/User.java | 673 --------------------- .../src/com/earth2me/essentials/user/UserBase.java | 368 ----------- .../src/com/earth2me/essentials/user/UserData.java | 106 ---- .../src/com/earth2me/essentials/user/UserMap.java | 255 -------- .../com/earth2me/essentials/utils/DateUtil.java | 186 ------ .../essentials/utils/DescParseTickFormat.java | 295 --------- .../earth2me/essentials/utils/ExecuteTimer.java | 89 --- .../earth2me/essentials/utils/LocationUtil.java | 142 ----- .../src/com/earth2me/essentials/utils/Util.java | 358 ----------- .../utils/gnu/inet/encoding/Punycode.java | 321 ---------- .../utils/gnu/inet/encoding/PunycodeException.java | 45 -- .../utils/textreader/ArrayListInput.java | 31 - .../essentials/utils/textreader/HelpInput.java | 152 ----- .../essentials/utils/textreader/IText.java | 14 - .../utils/textreader/KeywordReplacer.java | 156 ----- .../utils/textreader/SimpleTextInput.java | 35 -- .../utils/textreader/SimpleTextPager.java | 31 - .../essentials/utils/textreader/TextInput.java | 146 ----- .../essentials/utils/textreader/TextPager.java | 183 ------ Essentials/src/net/ess3/Console.java | 33 + Essentials/src/net/ess3/Essentials.java | 377 ++++++++++++ Essentials/src/net/ess3/EssentialsTimer.java | 80 +++ Essentials/src/net/ess3/I18n.java | 177 ++++++ Essentials/src/net/ess3/ItemDb.java | 151 +++++ Essentials/src/net/ess3/Jails.java | 301 +++++++++ Essentials/src/net/ess3/Kits.java | 90 +++ Essentials/src/net/ess3/Teleport.java | 301 +++++++++ Essentials/src/net/ess3/Warps.java | 148 +++++ Essentials/src/net/ess3/api/ChargeException.java | 15 + Essentials/src/net/ess3/api/Economy.java | 231 +++++++ Essentials/src/net/ess3/api/IBackup.java | 7 + Essentials/src/net/ess3/api/ICommandHandler.java | 20 + Essentials/src/net/ess3/api/IComponent.java | 13 + Essentials/src/net/ess3/api/IEconomy.java | 21 + Essentials/src/net/ess3/api/IEssentials.java | 64 ++ Essentials/src/net/ess3/api/IEssentialsModule.java | 6 + Essentials/src/net/ess3/api/II18n.java | 9 + Essentials/src/net/ess3/api/IItemDb.java | 13 + Essentials/src/net/ess3/api/IJails.java | 18 + Essentials/src/net/ess3/api/IKits.java | 18 + Essentials/src/net/ess3/api/IPermission.java | 16 + Essentials/src/net/ess3/api/IRanks.java | 25 + Essentials/src/net/ess3/api/IReload.java | 7 + Essentials/src/net/ess3/api/IReplyTo.java | 11 + Essentials/src/net/ess3/api/ISettings.java | 14 + Essentials/src/net/ess3/api/ITeleport.java | 28 + Essentials/src/net/ess3/api/IUser.java | 110 ++++ Essentials/src/net/ess3/api/IUserMap.java | 28 + Essentials/src/net/ess3/api/IWarp.java | 9 + Essentials/src/net/ess3/api/IWarps.java | 21 + Essentials/src/net/ess3/api/IWorth.java | 12 + .../src/net/ess3/api/InvalidNameException.java | 10 + .../src/net/ess3/api/NoLoanPermittedException.java | 12 + .../net/ess3/api/UserDoesNotExistException.java | 12 + .../src/net/ess3/api/server/CommandSender.java | 13 + .../src/net/ess3/api/server/Enchantment.java | 7 + Essentials/src/net/ess3/api/server/IInventory.java | 19 + Essentials/src/net/ess3/api/server/IPlugin.java | 32 + Essentials/src/net/ess3/api/server/IServer.java | 28 + Essentials/src/net/ess3/api/server/ItemStack.java | 47 ++ Essentials/src/net/ess3/api/server/Location.java | 52 ++ Essentials/src/net/ess3/api/server/Material.java | 37 ++ Essentials/src/net/ess3/api/server/Permission.java | 27 + Essentials/src/net/ess3/api/server/Player.java | 61 ++ Essentials/src/net/ess3/api/server/World.java | 26 + Essentials/src/net/ess3/backup/Backup.java | 150 +++++ .../src/net/ess3/bukkit/BukkitCommandSender.java | 40 ++ .../src/net/ess3/bukkit/BukkitItemStack.java | 62 ++ Essentials/src/net/ess3/bukkit/BukkitLocation.java | 63 ++ Essentials/src/net/ess3/bukkit/BukkitMaterial.java | 62 ++ .../src/net/ess3/bukkit/BukkitPermission.java | 82 +++ Essentials/src/net/ess3/bukkit/BukkitPlayer.java | 202 +++++++ Essentials/src/net/ess3/bukkit/BukkitWorld.java | 45 ++ Essentials/src/net/ess3/bukkit/Enchantments.java | 88 +++ .../src/net/ess3/bukkit/EssentialsPlugin.java | 95 +++ Essentials/src/net/ess3/bukkit/Inventory.java | 48 ++ Essentials/src/net/ess3/bukkit/Mob.java | 120 ++++ Essentials/src/net/ess3/bukkit/Plugin.java | 87 +++ Essentials/src/net/ess3/bukkit/Server.java | 126 ++++ Essentials/src/net/ess3/bukkit/VersionCheck.java | 46 ++ Essentials/src/net/ess3/commands/Commandafk.java | 55 ++ .../src/net/ess3/commands/Commandantioch.java | 23 + Essentials/src/net/ess3/commands/Commandback.java | 19 + .../src/net/ess3/commands/Commandbackup.java | 16 + .../src/net/ess3/commands/Commandbalance.java | 30 + .../src/net/ess3/commands/Commandbalancetop.java | 178 ++++++ Essentials/src/net/ess3/commands/Commandban.java | 64 ++ Essentials/src/net/ess3/commands/Commandbanip.java | 38 ++ .../src/net/ess3/commands/Commandbigtree.java | 41 ++ Essentials/src/net/ess3/commands/Commandbreak.java | 41 ++ .../src/net/ess3/commands/Commandbroadcast.java | 18 + Essentials/src/net/ess3/commands/Commandburn.java | 24 + .../net/ess3/commands/Commandclearinventory.java | 93 +++ .../src/net/ess3/commands/Commandcompass.java | 52 ++ .../src/net/ess3/commands/Commanddelhome.java | 58 ++ .../src/net/ess3/commands/Commanddeljail.java | 18 + .../src/net/ess3/commands/Commanddelwarp.java | 18 + Essentials/src/net/ess3/commands/Commanddepth.java | 26 + Essentials/src/net/ess3/commands/Commandeco.java | 118 ++++ .../src/net/ess3/commands/Commandenchant.java | 94 +++ .../src/net/ess3/commands/Commandessentials.java | 170 ++++++ Essentials/src/net/ess3/commands/Commandext.java | 43 ++ Essentials/src/net/ess3/commands/Commandfeed.java | 46 ++ .../src/net/ess3/commands/Commandfireball.java | 23 + .../src/net/ess3/commands/Commandgamemode.java | 51 ++ Essentials/src/net/ess3/commands/Commandgc.java | 23 + .../src/net/ess3/commands/Commandgetpos.java | 49 ++ Essentials/src/net/ess3/commands/Commandgive.java | 75 +++ Essentials/src/net/ess3/commands/Commandgod.java | 48 ++ Essentials/src/net/ess3/commands/Commandheal.java | 64 ++ Essentials/src/net/ess3/commands/Commandhelp.java | 49 ++ .../src/net/ess3/commands/Commandhelpop.java | 32 + Essentials/src/net/ess3/commands/Commandhome.java | 91 +++ .../src/net/ess3/commands/Commandignore.java | 42 ++ Essentials/src/net/ess3/commands/Commandinfo.java | 19 + .../src/net/ess3/commands/Commandinvsee.java | 52 ++ Essentials/src/net/ess3/commands/Commanditem.java | 66 ++ .../src/net/ess3/commands/Commanditemdb.java | 30 + Essentials/src/net/ess3/commands/Commandjails.java | 13 + Essentials/src/net/ess3/commands/Commandjump.java | 36 ++ Essentials/src/net/ess3/commands/Commandkick.java | 38 ++ .../src/net/ess3/commands/Commandkickall.java | 25 + Essentials/src/net/ess3/commands/Commandkill.java | 33 + .../src/net/ess3/commands/Commandkillall.java | 144 +++++ Essentials/src/net/ess3/commands/Commandkit.java | 62 ++ .../src/net/ess3/commands/Commandkittycannon.java | 38 ++ .../src/net/ess3/commands/Commandlightning.java | 71 +++ Essentials/src/net/ess3/commands/Commandlist.java | 162 +++++ Essentials/src/net/ess3/commands/Commandmail.java | 164 +++++ Essentials/src/net/ess3/commands/Commandme.java | 36 ++ Essentials/src/net/ess3/commands/Commandmore.java | 55 ++ Essentials/src/net/ess3/commands/Commandmotd.java | 19 + Essentials/src/net/ess3/commands/Commandmsg.java | 98 +++ Essentials/src/net/ess3/commands/Commandmute.java | 50 ++ Essentials/src/net/ess3/commands/Commandnear.java | 110 ++++ Essentials/src/net/ess3/commands/Commandnick.java | 126 ++++ Essentials/src/net/ess3/commands/Commandnuke.java | 54 ++ Essentials/src/net/ess3/commands/Commandpay.java | 44 ++ Essentials/src/net/ess3/commands/Commandping.java | 22 + .../src/net/ess3/commands/Commandpowertool.java | 112 ++++ .../net/ess3/commands/Commandpowertooltoggle.java | 23 + Essentials/src/net/ess3/commands/Commandptime.java | 227 +++++++ Essentials/src/net/ess3/commands/Commandr.java | 84 +++ .../src/net/ess3/commands/Commandrealname.java | 43 ++ .../src/net/ess3/commands/Commandremove.java | 155 +++++ .../src/net/ess3/commands/Commandrepair.java | 137 +++++ Essentials/src/net/ess3/commands/Commandrules.java | 19 + Essentials/src/net/ess3/commands/Commandseen.java | 53 ++ Essentials/src/net/ess3/commands/Commandsell.java | 152 +++++ .../src/net/ess3/commands/Commandsethome.java | 93 +++ .../src/net/ess3/commands/Commandsetjail.java | 20 + .../src/net/ess3/commands/Commandsetspawn.java | 17 + .../src/net/ess3/commands/Commandsetwarp.java | 47 ++ .../src/net/ess3/commands/Commandsetworth.java | 48 ++ .../src/net/ess3/commands/Commandsocialspy.java | 14 + Essentials/src/net/ess3/commands/Commandspawn.java | 54 ++ .../src/net/ess3/commands/Commandspawner.java | 58 ++ .../src/net/ess3/commands/Commandspawnmob.java | 281 +++++++++ Essentials/src/net/ess3/commands/Commandsudo.java | 42 ++ .../src/net/ess3/commands/Commandsuicide.java | 18 + .../src/net/ess3/commands/Commandtempban.java | 60 ++ .../src/net/ess3/commands/Commandthunder.java | 35 ++ Essentials/src/net/ess3/commands/Commandtime.java | 148 +++++ .../src/net/ess3/commands/Commandtogglejail.java | 104 ++++ Essentials/src/net/ess3/commands/Commandtop.java | 21 + Essentials/src/net/ess3/commands/Commandtp.java | 64 ++ Essentials/src/net/ess3/commands/Commandtpa.java | 47 ++ .../src/net/ess3/commands/Commandtpaall.java | 72 +++ .../src/net/ess3/commands/Commandtpaccept.java | 75 +++ .../src/net/ess3/commands/Commandtpahere.java | 46 ++ Essentials/src/net/ess3/commands/Commandtpall.java | 48 ++ .../src/net/ess3/commands/Commandtpdeny.java | 22 + .../src/net/ess3/commands/Commandtphere.java | 27 + Essentials/src/net/ess3/commands/Commandtpo.java | 38 ++ .../src/net/ess3/commands/Commandtpohere.java | 39 ++ Essentials/src/net/ess3/commands/Commandtppos.java | 38 ++ .../src/net/ess3/commands/Commandtptoggle.java | 16 + Essentials/src/net/ess3/commands/Commandtree.java | 57 ++ Essentials/src/net/ess3/commands/Commandunban.java | 32 + .../src/net/ess3/commands/Commandunbanip.java | 30 + .../src/net/ess3/commands/Commandunlimited.java | 111 ++++ Essentials/src/net/ess3/commands/Commandwarp.java | 123 ++++ .../src/net/ess3/commands/Commandweather.java | 72 +++ Essentials/src/net/ess3/commands/Commandwhois.java | 85 +++ Essentials/src/net/ess3/commands/Commandworld.java | 81 +++ Essentials/src/net/ess3/commands/Commandworth.java | 101 ++++ .../src/net/ess3/commands/EssentialsCommand.java | 130 ++++ .../ess3/commands/EssentialsCommandHandler.java | 312 ++++++++++ .../src/net/ess3/commands/IEssentialsCommand.java | 22 + .../src/net/ess3/commands/NoChargeException.java | 10 + .../ess3/commands/NotEnoughArgumentsException.java | 20 + .../net/ess3/commands/WarpNotFoundException.java | 17 + .../src/net/ess3/craftbukkit/FakeExplosion.java | 51 ++ .../src/net/ess3/craftbukkit/FakeInventory.java | 225 +++++++ .../net/ess3/craftbukkit/InventoryWorkaround.java | 322 ++++++++++ Essentials/src/net/ess3/craftbukkit/SetExpFix.java | 56 ++ Essentials/src/net/ess3/economy/Economy.java | 207 +++++++ Essentials/src/net/ess3/economy/Money.java | 17 + Essentials/src/net/ess3/economy/MoneyHolder.java | 22 + Essentials/src/net/ess3/economy/Trade.java | 333 ++++++++++ Essentials/src/net/ess3/economy/Worth.java | 33 + Essentials/src/net/ess3/economy/WorthHolder.java | 86 +++ .../src/net/ess3/economy/register/Method.java | 210 +++++++ .../src/net/ess3/economy/register/Methods.java | 296 +++++++++ .../net/ess3/economy/register/methods/BOSE6.java | 329 ++++++++++ .../net/ess3/economy/register/methods/BOSE7.java | 318 ++++++++++ .../net/ess3/economy/register/methods/MCUR.java | 191 ++++++ .../ess3/economy/register/methods/VaultEco.java | 337 +++++++++++ .../net/ess3/economy/register/methods/iCo4.java | 251 ++++++++ .../net/ess3/economy/register/methods/iCo5.java | 371 ++++++++++++ .../net/ess3/economy/register/methods/iCo6.java | 237 ++++++++ .../net/ess3/listener/EssentialsBlockListener.java | 50 ++ .../ess3/listener/EssentialsEntityListener.java | 138 +++++ .../ess3/listener/EssentialsPlayerListener.java | 438 ++++++++++++++ .../ess3/listener/EssentialsPluginListener.java | 110 ++++ .../src/net/ess3/listener/TntExplodeListener.java | 59 ++ .../permissions/AbstractSuperpermsPermission.java | 40 ++ .../src/net/ess3/permissions/BasePermission.java | 16 + .../net/ess3/permissions/EnchantPermissions.java | 23 + .../src/net/ess3/permissions/GivePermissions.java | 31 + .../net/ess3/permissions/GroupsPermissions.java | 23 + .../src/net/ess3/permissions/HelpPermissions.java | 23 + .../src/net/ess3/permissions/ItemPermissions.java | 33 + .../src/net/ess3/permissions/KitPermissions.java | 31 + .../ess3/permissions/NoCommandCostPermissions.java | 23 + .../src/net/ess3/permissions/Permissions.java | 122 ++++ .../net/ess3/permissions/SpawnerPermissions.java | 23 + .../net/ess3/permissions/SpawnmobPermissions.java | 21 + .../ess3/permissions/UnlimitedItemPermissions.java | 23 + .../src/net/ess3/permissions/WarpPermissions.java | 31 + .../src/net/ess3/permissions/WorldPermissions.java | 22 + Essentials/src/net/ess3/ranks/GMGroups.java | 143 +++++ Essentials/src/net/ess3/ranks/RankOptions.java | 27 + Essentials/src/net/ess3/ranks/Ranks.java | 28 + Essentials/src/net/ess3/ranks/RanksStorage.java | 195 ++++++ Essentials/src/net/ess3/ranks/VaultGroups.java | 114 ++++ Essentials/src/net/ess3/settings/Backup.java | 17 + Essentials/src/net/ess3/settings/Chat.java | 33 + Essentials/src/net/ess3/settings/Commands.java | 74 +++ Essentials/src/net/ess3/settings/Economy.java | 67 ++ Essentials/src/net/ess3/settings/General.java | 54 ++ Essentials/src/net/ess3/settings/Jails.java | 18 + Essentials/src/net/ess3/settings/Kit.java | 19 + Essentials/src/net/ess3/settings/Kits.java | 28 + Essentials/src/net/ess3/settings/Settings.java | 72 +++ .../src/net/ess3/settings/SettingsHolder.java | 64 ++ Essentials/src/net/ess3/settings/Spawns.java | 40 ++ Essentials/src/net/ess3/settings/SpawnsHolder.java | 307 ++++++++++ Essentials/src/net/ess3/settings/Warp.java | 14 + Essentials/src/net/ess3/settings/WarpHolder.java | 35 ++ Essentials/src/net/ess3/settings/WorldOptions.java | 14 + Essentials/src/net/ess3/settings/Worlds.java | 12 + Essentials/src/net/ess3/settings/commands/Afk.java | 38 ++ .../src/net/ess3/settings/commands/Back.java | 19 + Essentials/src/net/ess3/settings/commands/God.java | 15 + .../src/net/ess3/settings/commands/Help.java | 23 + .../src/net/ess3/settings/commands/Home.java | 26 + .../src/net/ess3/settings/commands/Lightning.java | 15 + .../src/net/ess3/settings/commands/List.java | 16 + .../src/net/ess3/settings/commands/Spawnmob.java | 15 + Essentials/src/net/ess3/settings/commands/Tpa.java | 21 + .../src/net/ess3/settings/geoip/Database.java | 16 + Essentials/src/net/ess3/settings/geoip/GeoIP.java | 15 + .../src/net/ess3/settings/protect/Prevent.java | 45 ++ .../src/net/ess3/settings/protect/Protect.java | 45 ++ .../net/ess3/settings/protect/SignsAndRails.java | 26 + .../storage/AbstractDelayedYamlFileReader.java | 93 +++ .../storage/AbstractDelayedYamlFileWriter.java | 75 +++ .../net/ess3/storage/AsyncStorageObjectHolder.java | 186 ++++++ .../src/net/ess3/storage/BukkitConstructor.java | 439 ++++++++++++++ Essentials/src/net/ess3/storage/Comment.java | 12 + .../src/net/ess3/storage/EnchantmentLevel.java | 80 +++ .../src/net/ess3/storage/IStorageObjectHolder.java | 17 + .../src/net/ess3/storage/IStorageObjectMap.java | 22 + .../src/net/ess3/storage/IStorageReader.java | 7 + .../src/net/ess3/storage/IStorageWriter.java | 7 + Essentials/src/net/ess3/storage/ListType.java | 14 + Essentials/src/net/ess3/storage/ManagedFile.java | 228 +++++++ Essentials/src/net/ess3/storage/MapKeyType.java | 14 + Essentials/src/net/ess3/storage/MapValueType.java | 14 + .../src/net/ess3/storage/ObjectLoadException.java | 10 + Essentials/src/net/ess3/storage/StorageObject.java | 6 + .../src/net/ess3/storage/StorageObjectMap.java | 137 +++++ .../src/net/ess3/storage/StoredLocation.java | 115 ++++ .../src/net/ess3/storage/YamlStorageReader.java | 120 ++++ .../src/net/ess3/storage/YamlStorageWriter.java | 348 +++++++++++ Essentials/src/net/ess3/user/Ban.java | 14 + .../src/net/ess3/user/CooldownException.java | 12 + Essentials/src/net/ess3/user/IOfflinePlayer.java | 17 + Essentials/src/net/ess3/user/IOfflineUser.java | 9 + Essentials/src/net/ess3/user/Inventory.java | 58 ++ .../src/net/ess3/user/TooManyMatchesException.java | 5 + Essentials/src/net/ess3/user/User.java | 673 +++++++++++++++++++++ Essentials/src/net/ess3/user/UserBase.java | 368 +++++++++++ Essentials/src/net/ess3/user/UserData.java | 106 ++++ Essentials/src/net/ess3/user/UserMap.java | 254 ++++++++ Essentials/src/net/ess3/utils/DateUtil.java | 186 ++++++ .../src/net/ess3/utils/DescParseTickFormat.java | 295 +++++++++ Essentials/src/net/ess3/utils/ExecuteTimer.java | 89 +++ Essentials/src/net/ess3/utils/LocationUtil.java | 142 +++++ Essentials/src/net/ess3/utils/Util.java | 353 +++++++++++ .../net/ess3/utils/gnu/inet/encoding/Punycode.java | 321 ++++++++++ .../utils/gnu/inet/encoding/PunycodeException.java | 45 ++ .../net/ess3/utils/textreader/ArrayListInput.java | 31 + .../src/net/ess3/utils/textreader/HelpInput.java | 152 +++++ .../src/net/ess3/utils/textreader/IText.java | 14 + .../net/ess3/utils/textreader/KeywordReplacer.java | 156 +++++ .../net/ess3/utils/textreader/SimpleTextInput.java | 35 ++ .../net/ess3/utils/textreader/SimpleTextPager.java | 31 + .../src/net/ess3/utils/textreader/TextInput.java | 146 +++++ .../src/net/ess3/utils/textreader/TextPager.java | 182 ++++++ .../src/com/earth2me/essentials/api/Economy.java | 231 ------- 584 files changed, 23790 insertions(+), 23925 deletions(-) delete mode 100644 Essentials/src/com/earth2me/essentials/Console.java delete mode 100644 Essentials/src/com/earth2me/essentials/Essentials.java delete mode 100644 Essentials/src/com/earth2me/essentials/EssentialsTimer.java delete mode 100644 Essentials/src/com/earth2me/essentials/I18n.java delete mode 100644 Essentials/src/com/earth2me/essentials/ItemDb.java delete mode 100644 Essentials/src/com/earth2me/essentials/Jails.java delete mode 100644 Essentials/src/com/earth2me/essentials/Kits.java delete mode 100644 Essentials/src/com/earth2me/essentials/Teleport.java delete mode 100644 Essentials/src/com/earth2me/essentials/Warps.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/ChargeException.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/IBackup.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/ICommandHandler.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/IComponent.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/IEconomy.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/IEssentials.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/IEssentialsModule.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/II18n.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/IItemDb.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/IJails.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/IKits.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/IPermission.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/IRanks.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/IReload.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/IReplyTo.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/ISettings.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/ITeleport.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/IUser.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/IUserMap.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/IWarp.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/IWarps.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/IWorth.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/InvalidNameException.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/NoLoanPermittedException.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/UserDoesNotExistException.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/server/CommandSender.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/server/Enchantment.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/server/IInventory.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/server/IPlugin.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/server/IServer.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/server/ItemStack.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/server/Location.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/server/Material.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/server/Permission.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/server/Player.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/server/World.java delete mode 100644 Essentials/src/com/earth2me/essentials/backup/Backup.java delete mode 100644 Essentials/src/com/earth2me/essentials/bukkit/BukkitCommandSender.java delete mode 100644 Essentials/src/com/earth2me/essentials/bukkit/BukkitItemStack.java delete mode 100644 Essentials/src/com/earth2me/essentials/bukkit/BukkitLocation.java delete mode 100644 Essentials/src/com/earth2me/essentials/bukkit/BukkitMaterial.java delete mode 100644 Essentials/src/com/earth2me/essentials/bukkit/BukkitPermission.java delete mode 100644 Essentials/src/com/earth2me/essentials/bukkit/BukkitPlayer.java delete mode 100644 Essentials/src/com/earth2me/essentials/bukkit/BukkitWorld.java delete mode 100644 Essentials/src/com/earth2me/essentials/bukkit/Enchantments.java delete mode 100644 Essentials/src/com/earth2me/essentials/bukkit/EssentialsPlugin.java delete mode 100644 Essentials/src/com/earth2me/essentials/bukkit/Inventory.java delete mode 100644 Essentials/src/com/earth2me/essentials/bukkit/Mob.java delete mode 100644 Essentials/src/com/earth2me/essentials/bukkit/Plugin.java delete mode 100644 Essentials/src/com/earth2me/essentials/bukkit/Server.java delete mode 100644 Essentials/src/com/earth2me/essentials/bukkit/VersionCheck.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandafk.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandantioch.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandback.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandbackup.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandbalance.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandbalancetop.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandban.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandbanip.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandbreak.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandbroadcast.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandburn.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandcompass.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commanddelhome.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commanddepth.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandeco.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandenchant.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandessentials.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandext.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandfeed.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandfireball.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandgamemode.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandgc.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandgive.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandgod.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandheal.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandhelp.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandhome.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandignore.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandinfo.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commanditem.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commanditemdb.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandjails.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandjump.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandkick.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandkickall.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandkill.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandkillall.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandkit.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandkittycannon.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandlightning.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandlist.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandmail.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandme.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandmore.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandmotd.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandmsg.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandmute.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandnear.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandnick.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandnuke.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandpay.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandping.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandpowertool.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandpowertooltoggle.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandptime.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandr.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandrealname.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandremove.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandrepair.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandrules.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandseen.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandsell.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandsethome.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandsetspawn.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandsetworth.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandsocialspy.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandspawn.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandspawner.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandsudo.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtempban.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandthunder.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtime.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtop.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtp.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtpa.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtpaall.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtpall.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtpdeny.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtphere.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtpo.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtppos.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtptoggle.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtree.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandunban.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandunlimited.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandwarp.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandweather.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandwhois.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandworld.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandworth.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/EssentialsCommandHandler.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/IEssentialsCommand.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/NoChargeException.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/NotEnoughArgumentsException.java delete mode 100644 Essentials/src/com/earth2me/essentials/commands/WarpNotFoundException.java delete mode 100644 Essentials/src/com/earth2me/essentials/craftbukkit/FakeExplosion.java delete mode 100644 Essentials/src/com/earth2me/essentials/craftbukkit/FakeInventory.java delete mode 100644 Essentials/src/com/earth2me/essentials/craftbukkit/InventoryWorkaround.java delete mode 100644 Essentials/src/com/earth2me/essentials/craftbukkit/SetExpFix.java delete mode 100644 Essentials/src/com/earth2me/essentials/economy/Economy.java delete mode 100644 Essentials/src/com/earth2me/essentials/economy/Money.java delete mode 100644 Essentials/src/com/earth2me/essentials/economy/MoneyHolder.java delete mode 100644 Essentials/src/com/earth2me/essentials/economy/Trade.java delete mode 100644 Essentials/src/com/earth2me/essentials/economy/Worth.java delete mode 100644 Essentials/src/com/earth2me/essentials/economy/WorthHolder.java delete mode 100644 Essentials/src/com/earth2me/essentials/economy/register/Method.java delete mode 100644 Essentials/src/com/earth2me/essentials/economy/register/Methods.java delete mode 100644 Essentials/src/com/earth2me/essentials/economy/register/methods/BOSE6.java delete mode 100644 Essentials/src/com/earth2me/essentials/economy/register/methods/BOSE7.java delete mode 100644 Essentials/src/com/earth2me/essentials/economy/register/methods/MCUR.java delete mode 100644 Essentials/src/com/earth2me/essentials/economy/register/methods/VaultEco.java delete mode 100644 Essentials/src/com/earth2me/essentials/economy/register/methods/iCo4.java delete mode 100644 Essentials/src/com/earth2me/essentials/economy/register/methods/iCo5.java delete mode 100644 Essentials/src/com/earth2me/essentials/economy/register/methods/iCo6.java delete mode 100644 Essentials/src/com/earth2me/essentials/listener/EssentialsBlockListener.java delete mode 100644 Essentials/src/com/earth2me/essentials/listener/EssentialsEntityListener.java delete mode 100644 Essentials/src/com/earth2me/essentials/listener/EssentialsPlayerListener.java delete mode 100644 Essentials/src/com/earth2me/essentials/listener/EssentialsPluginListener.java delete mode 100644 Essentials/src/com/earth2me/essentials/listener/TntExplodeListener.java delete mode 100644 Essentials/src/com/earth2me/essentials/permissions/AbstractSuperpermsPermission.java delete mode 100644 Essentials/src/com/earth2me/essentials/permissions/BasePermission.java delete mode 100644 Essentials/src/com/earth2me/essentials/permissions/EnchantPermissions.java delete mode 100644 Essentials/src/com/earth2me/essentials/permissions/GivePermissions.java delete mode 100644 Essentials/src/com/earth2me/essentials/permissions/GroupsPermissions.java delete mode 100644 Essentials/src/com/earth2me/essentials/permissions/HelpPermissions.java delete mode 100644 Essentials/src/com/earth2me/essentials/permissions/ItemPermissions.java delete mode 100644 Essentials/src/com/earth2me/essentials/permissions/KitPermissions.java delete mode 100644 Essentials/src/com/earth2me/essentials/permissions/NoCommandCostPermissions.java delete mode 100644 Essentials/src/com/earth2me/essentials/permissions/Permissions.java delete mode 100644 Essentials/src/com/earth2me/essentials/permissions/SpawnerPermissions.java delete mode 100644 Essentials/src/com/earth2me/essentials/permissions/SpawnmobPermissions.java delete mode 100644 Essentials/src/com/earth2me/essentials/permissions/UnlimitedItemPermissions.java delete mode 100644 Essentials/src/com/earth2me/essentials/permissions/WarpPermissions.java delete mode 100644 Essentials/src/com/earth2me/essentials/permissions/WorldPermissions.java delete mode 100644 Essentials/src/com/earth2me/essentials/ranks/GMGroups.java delete mode 100644 Essentials/src/com/earth2me/essentials/ranks/RankOptions.java delete mode 100644 Essentials/src/com/earth2me/essentials/ranks/Ranks.java delete mode 100644 Essentials/src/com/earth2me/essentials/ranks/RanksStorage.java delete mode 100644 Essentials/src/com/earth2me/essentials/ranks/VaultGroups.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/Backup.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/Chat.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/Commands.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/Economy.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/General.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/Jails.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/Kit.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/Kits.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/Settings.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/SettingsHolder.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/Spawns.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/SpawnsHolder.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/Warp.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/WarpHolder.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/WorldOptions.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/Worlds.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/commands/Afk.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/commands/Back.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/commands/God.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/commands/Help.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/commands/Home.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/commands/Lightning.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/commands/List.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/commands/Spawnmob.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/commands/Tpa.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/geoip/Database.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/geoip/GeoIP.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/protect/Prevent.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/protect/Protect.java delete mode 100644 Essentials/src/com/earth2me/essentials/settings/protect/SignsAndRails.java delete mode 100644 Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileReader.java delete mode 100644 Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileWriter.java delete mode 100644 Essentials/src/com/earth2me/essentials/storage/AsyncStorageObjectHolder.java delete mode 100644 Essentials/src/com/earth2me/essentials/storage/BukkitConstructor.java delete mode 100644 Essentials/src/com/earth2me/essentials/storage/Comment.java delete mode 100644 Essentials/src/com/earth2me/essentials/storage/EnchantmentLevel.java delete mode 100644 Essentials/src/com/earth2me/essentials/storage/IStorageObjectHolder.java delete mode 100644 Essentials/src/com/earth2me/essentials/storage/IStorageObjectMap.java delete mode 100644 Essentials/src/com/earth2me/essentials/storage/IStorageReader.java delete mode 100644 Essentials/src/com/earth2me/essentials/storage/IStorageWriter.java delete mode 100644 Essentials/src/com/earth2me/essentials/storage/ListType.java delete mode 100644 Essentials/src/com/earth2me/essentials/storage/ManagedFile.java delete mode 100644 Essentials/src/com/earth2me/essentials/storage/MapKeyType.java delete mode 100644 Essentials/src/com/earth2me/essentials/storage/MapValueType.java delete mode 100644 Essentials/src/com/earth2me/essentials/storage/ObjectLoadException.java delete mode 100644 Essentials/src/com/earth2me/essentials/storage/StorageObject.java delete mode 100644 Essentials/src/com/earth2me/essentials/storage/StorageObjectMap.java delete mode 100644 Essentials/src/com/earth2me/essentials/storage/StoredLocation.java delete mode 100644 Essentials/src/com/earth2me/essentials/storage/YamlStorageReader.java delete mode 100644 Essentials/src/com/earth2me/essentials/storage/YamlStorageWriter.java delete mode 100644 Essentials/src/com/earth2me/essentials/user/Ban.java delete mode 100644 Essentials/src/com/earth2me/essentials/user/CooldownException.java delete mode 100644 Essentials/src/com/earth2me/essentials/user/IOfflinePlayer.java delete mode 100644 Essentials/src/com/earth2me/essentials/user/IOfflineUser.java delete mode 100644 Essentials/src/com/earth2me/essentials/user/Inventory.java delete mode 100644 Essentials/src/com/earth2me/essentials/user/TooManyMatchesException.java delete mode 100644 Essentials/src/com/earth2me/essentials/user/User.java delete mode 100644 Essentials/src/com/earth2me/essentials/user/UserBase.java delete mode 100644 Essentials/src/com/earth2me/essentials/user/UserData.java delete mode 100644 Essentials/src/com/earth2me/essentials/user/UserMap.java delete mode 100644 Essentials/src/com/earth2me/essentials/utils/DateUtil.java delete mode 100644 Essentials/src/com/earth2me/essentials/utils/DescParseTickFormat.java delete mode 100644 Essentials/src/com/earth2me/essentials/utils/ExecuteTimer.java delete mode 100644 Essentials/src/com/earth2me/essentials/utils/LocationUtil.java delete mode 100644 Essentials/src/com/earth2me/essentials/utils/Util.java delete mode 100644 Essentials/src/com/earth2me/essentials/utils/gnu/inet/encoding/Punycode.java delete mode 100644 Essentials/src/com/earth2me/essentials/utils/gnu/inet/encoding/PunycodeException.java delete mode 100644 Essentials/src/com/earth2me/essentials/utils/textreader/ArrayListInput.java delete mode 100644 Essentials/src/com/earth2me/essentials/utils/textreader/HelpInput.java delete mode 100644 Essentials/src/com/earth2me/essentials/utils/textreader/IText.java delete mode 100644 Essentials/src/com/earth2me/essentials/utils/textreader/KeywordReplacer.java delete mode 100644 Essentials/src/com/earth2me/essentials/utils/textreader/SimpleTextInput.java delete mode 100644 Essentials/src/com/earth2me/essentials/utils/textreader/SimpleTextPager.java delete mode 100644 Essentials/src/com/earth2me/essentials/utils/textreader/TextInput.java delete mode 100644 Essentials/src/com/earth2me/essentials/utils/textreader/TextPager.java create mode 100644 Essentials/src/net/ess3/Console.java create mode 100644 Essentials/src/net/ess3/Essentials.java create mode 100644 Essentials/src/net/ess3/EssentialsTimer.java create mode 100644 Essentials/src/net/ess3/I18n.java create mode 100644 Essentials/src/net/ess3/ItemDb.java create mode 100644 Essentials/src/net/ess3/Jails.java create mode 100644 Essentials/src/net/ess3/Kits.java create mode 100644 Essentials/src/net/ess3/Teleport.java create mode 100644 Essentials/src/net/ess3/Warps.java create mode 100644 Essentials/src/net/ess3/api/ChargeException.java create mode 100644 Essentials/src/net/ess3/api/Economy.java create mode 100644 Essentials/src/net/ess3/api/IBackup.java create mode 100644 Essentials/src/net/ess3/api/ICommandHandler.java create mode 100644 Essentials/src/net/ess3/api/IComponent.java create mode 100644 Essentials/src/net/ess3/api/IEconomy.java create mode 100644 Essentials/src/net/ess3/api/IEssentials.java create mode 100644 Essentials/src/net/ess3/api/IEssentialsModule.java create mode 100644 Essentials/src/net/ess3/api/II18n.java create mode 100644 Essentials/src/net/ess3/api/IItemDb.java create mode 100644 Essentials/src/net/ess3/api/IJails.java create mode 100644 Essentials/src/net/ess3/api/IKits.java create mode 100644 Essentials/src/net/ess3/api/IPermission.java create mode 100644 Essentials/src/net/ess3/api/IRanks.java create mode 100644 Essentials/src/net/ess3/api/IReload.java create mode 100644 Essentials/src/net/ess3/api/IReplyTo.java create mode 100644 Essentials/src/net/ess3/api/ISettings.java create mode 100644 Essentials/src/net/ess3/api/ITeleport.java create mode 100644 Essentials/src/net/ess3/api/IUser.java create mode 100644 Essentials/src/net/ess3/api/IUserMap.java create mode 100644 Essentials/src/net/ess3/api/IWarp.java create mode 100644 Essentials/src/net/ess3/api/IWarps.java create mode 100644 Essentials/src/net/ess3/api/IWorth.java create mode 100644 Essentials/src/net/ess3/api/InvalidNameException.java create mode 100644 Essentials/src/net/ess3/api/NoLoanPermittedException.java create mode 100644 Essentials/src/net/ess3/api/UserDoesNotExistException.java create mode 100644 Essentials/src/net/ess3/api/server/CommandSender.java create mode 100644 Essentials/src/net/ess3/api/server/Enchantment.java create mode 100644 Essentials/src/net/ess3/api/server/IInventory.java create mode 100644 Essentials/src/net/ess3/api/server/IPlugin.java create mode 100644 Essentials/src/net/ess3/api/server/IServer.java create mode 100644 Essentials/src/net/ess3/api/server/ItemStack.java create mode 100644 Essentials/src/net/ess3/api/server/Location.java create mode 100644 Essentials/src/net/ess3/api/server/Material.java create mode 100644 Essentials/src/net/ess3/api/server/Permission.java create mode 100644 Essentials/src/net/ess3/api/server/Player.java create mode 100644 Essentials/src/net/ess3/api/server/World.java create mode 100644 Essentials/src/net/ess3/backup/Backup.java create mode 100644 Essentials/src/net/ess3/bukkit/BukkitCommandSender.java create mode 100644 Essentials/src/net/ess3/bukkit/BukkitItemStack.java create mode 100644 Essentials/src/net/ess3/bukkit/BukkitLocation.java create mode 100644 Essentials/src/net/ess3/bukkit/BukkitMaterial.java create mode 100644 Essentials/src/net/ess3/bukkit/BukkitPermission.java create mode 100644 Essentials/src/net/ess3/bukkit/BukkitPlayer.java create mode 100644 Essentials/src/net/ess3/bukkit/BukkitWorld.java create mode 100644 Essentials/src/net/ess3/bukkit/Enchantments.java create mode 100644 Essentials/src/net/ess3/bukkit/EssentialsPlugin.java create mode 100644 Essentials/src/net/ess3/bukkit/Inventory.java create mode 100644 Essentials/src/net/ess3/bukkit/Mob.java create mode 100644 Essentials/src/net/ess3/bukkit/Plugin.java create mode 100644 Essentials/src/net/ess3/bukkit/Server.java create mode 100644 Essentials/src/net/ess3/bukkit/VersionCheck.java create mode 100644 Essentials/src/net/ess3/commands/Commandafk.java create mode 100644 Essentials/src/net/ess3/commands/Commandantioch.java create mode 100644 Essentials/src/net/ess3/commands/Commandback.java create mode 100644 Essentials/src/net/ess3/commands/Commandbackup.java create mode 100644 Essentials/src/net/ess3/commands/Commandbalance.java create mode 100644 Essentials/src/net/ess3/commands/Commandbalancetop.java create mode 100644 Essentials/src/net/ess3/commands/Commandban.java create mode 100644 Essentials/src/net/ess3/commands/Commandbanip.java create mode 100644 Essentials/src/net/ess3/commands/Commandbigtree.java create mode 100644 Essentials/src/net/ess3/commands/Commandbreak.java create mode 100644 Essentials/src/net/ess3/commands/Commandbroadcast.java create mode 100644 Essentials/src/net/ess3/commands/Commandburn.java create mode 100644 Essentials/src/net/ess3/commands/Commandclearinventory.java create mode 100644 Essentials/src/net/ess3/commands/Commandcompass.java create mode 100644 Essentials/src/net/ess3/commands/Commanddelhome.java create mode 100644 Essentials/src/net/ess3/commands/Commanddeljail.java create mode 100644 Essentials/src/net/ess3/commands/Commanddelwarp.java create mode 100644 Essentials/src/net/ess3/commands/Commanddepth.java create mode 100644 Essentials/src/net/ess3/commands/Commandeco.java create mode 100644 Essentials/src/net/ess3/commands/Commandenchant.java create mode 100644 Essentials/src/net/ess3/commands/Commandessentials.java create mode 100644 Essentials/src/net/ess3/commands/Commandext.java create mode 100644 Essentials/src/net/ess3/commands/Commandfeed.java create mode 100644 Essentials/src/net/ess3/commands/Commandfireball.java create mode 100644 Essentials/src/net/ess3/commands/Commandgamemode.java create mode 100644 Essentials/src/net/ess3/commands/Commandgc.java create mode 100644 Essentials/src/net/ess3/commands/Commandgetpos.java create mode 100644 Essentials/src/net/ess3/commands/Commandgive.java create mode 100644 Essentials/src/net/ess3/commands/Commandgod.java create mode 100644 Essentials/src/net/ess3/commands/Commandheal.java create mode 100644 Essentials/src/net/ess3/commands/Commandhelp.java create mode 100644 Essentials/src/net/ess3/commands/Commandhelpop.java create mode 100644 Essentials/src/net/ess3/commands/Commandhome.java create mode 100644 Essentials/src/net/ess3/commands/Commandignore.java create mode 100644 Essentials/src/net/ess3/commands/Commandinfo.java create mode 100644 Essentials/src/net/ess3/commands/Commandinvsee.java create mode 100644 Essentials/src/net/ess3/commands/Commanditem.java create mode 100644 Essentials/src/net/ess3/commands/Commanditemdb.java create mode 100644 Essentials/src/net/ess3/commands/Commandjails.java create mode 100644 Essentials/src/net/ess3/commands/Commandjump.java create mode 100644 Essentials/src/net/ess3/commands/Commandkick.java create mode 100644 Essentials/src/net/ess3/commands/Commandkickall.java create mode 100644 Essentials/src/net/ess3/commands/Commandkill.java create mode 100644 Essentials/src/net/ess3/commands/Commandkillall.java create mode 100644 Essentials/src/net/ess3/commands/Commandkit.java create mode 100644 Essentials/src/net/ess3/commands/Commandkittycannon.java create mode 100644 Essentials/src/net/ess3/commands/Commandlightning.java create mode 100644 Essentials/src/net/ess3/commands/Commandlist.java create mode 100644 Essentials/src/net/ess3/commands/Commandmail.java create mode 100644 Essentials/src/net/ess3/commands/Commandme.java create mode 100644 Essentials/src/net/ess3/commands/Commandmore.java create mode 100644 Essentials/src/net/ess3/commands/Commandmotd.java create mode 100644 Essentials/src/net/ess3/commands/Commandmsg.java create mode 100644 Essentials/src/net/ess3/commands/Commandmute.java create mode 100644 Essentials/src/net/ess3/commands/Commandnear.java create mode 100644 Essentials/src/net/ess3/commands/Commandnick.java create mode 100644 Essentials/src/net/ess3/commands/Commandnuke.java create mode 100644 Essentials/src/net/ess3/commands/Commandpay.java create mode 100644 Essentials/src/net/ess3/commands/Commandping.java create mode 100644 Essentials/src/net/ess3/commands/Commandpowertool.java create mode 100644 Essentials/src/net/ess3/commands/Commandpowertooltoggle.java create mode 100644 Essentials/src/net/ess3/commands/Commandptime.java create mode 100644 Essentials/src/net/ess3/commands/Commandr.java create mode 100644 Essentials/src/net/ess3/commands/Commandrealname.java create mode 100644 Essentials/src/net/ess3/commands/Commandremove.java create mode 100644 Essentials/src/net/ess3/commands/Commandrepair.java create mode 100644 Essentials/src/net/ess3/commands/Commandrules.java create mode 100644 Essentials/src/net/ess3/commands/Commandseen.java create mode 100644 Essentials/src/net/ess3/commands/Commandsell.java create mode 100644 Essentials/src/net/ess3/commands/Commandsethome.java create mode 100644 Essentials/src/net/ess3/commands/Commandsetjail.java create mode 100644 Essentials/src/net/ess3/commands/Commandsetspawn.java create mode 100644 Essentials/src/net/ess3/commands/Commandsetwarp.java create mode 100644 Essentials/src/net/ess3/commands/Commandsetworth.java create mode 100644 Essentials/src/net/ess3/commands/Commandsocialspy.java create mode 100644 Essentials/src/net/ess3/commands/Commandspawn.java create mode 100644 Essentials/src/net/ess3/commands/Commandspawner.java create mode 100644 Essentials/src/net/ess3/commands/Commandspawnmob.java create mode 100644 Essentials/src/net/ess3/commands/Commandsudo.java create mode 100644 Essentials/src/net/ess3/commands/Commandsuicide.java create mode 100644 Essentials/src/net/ess3/commands/Commandtempban.java create mode 100644 Essentials/src/net/ess3/commands/Commandthunder.java create mode 100644 Essentials/src/net/ess3/commands/Commandtime.java create mode 100644 Essentials/src/net/ess3/commands/Commandtogglejail.java create mode 100644 Essentials/src/net/ess3/commands/Commandtop.java create mode 100644 Essentials/src/net/ess3/commands/Commandtp.java create mode 100644 Essentials/src/net/ess3/commands/Commandtpa.java create mode 100644 Essentials/src/net/ess3/commands/Commandtpaall.java create mode 100644 Essentials/src/net/ess3/commands/Commandtpaccept.java create mode 100644 Essentials/src/net/ess3/commands/Commandtpahere.java create mode 100644 Essentials/src/net/ess3/commands/Commandtpall.java create mode 100644 Essentials/src/net/ess3/commands/Commandtpdeny.java create mode 100644 Essentials/src/net/ess3/commands/Commandtphere.java create mode 100644 Essentials/src/net/ess3/commands/Commandtpo.java create mode 100644 Essentials/src/net/ess3/commands/Commandtpohere.java create mode 100644 Essentials/src/net/ess3/commands/Commandtppos.java create mode 100644 Essentials/src/net/ess3/commands/Commandtptoggle.java create mode 100644 Essentials/src/net/ess3/commands/Commandtree.java create mode 100644 Essentials/src/net/ess3/commands/Commandunban.java create mode 100644 Essentials/src/net/ess3/commands/Commandunbanip.java create mode 100644 Essentials/src/net/ess3/commands/Commandunlimited.java create mode 100644 Essentials/src/net/ess3/commands/Commandwarp.java create mode 100644 Essentials/src/net/ess3/commands/Commandweather.java create mode 100644 Essentials/src/net/ess3/commands/Commandwhois.java create mode 100644 Essentials/src/net/ess3/commands/Commandworld.java create mode 100644 Essentials/src/net/ess3/commands/Commandworth.java create mode 100644 Essentials/src/net/ess3/commands/EssentialsCommand.java create mode 100644 Essentials/src/net/ess3/commands/EssentialsCommandHandler.java create mode 100644 Essentials/src/net/ess3/commands/IEssentialsCommand.java create mode 100644 Essentials/src/net/ess3/commands/NoChargeException.java create mode 100644 Essentials/src/net/ess3/commands/NotEnoughArgumentsException.java create mode 100644 Essentials/src/net/ess3/commands/WarpNotFoundException.java create mode 100644 Essentials/src/net/ess3/craftbukkit/FakeExplosion.java create mode 100644 Essentials/src/net/ess3/craftbukkit/FakeInventory.java create mode 100644 Essentials/src/net/ess3/craftbukkit/InventoryWorkaround.java create mode 100644 Essentials/src/net/ess3/craftbukkit/SetExpFix.java create mode 100644 Essentials/src/net/ess3/economy/Economy.java create mode 100644 Essentials/src/net/ess3/economy/Money.java create mode 100644 Essentials/src/net/ess3/economy/MoneyHolder.java create mode 100644 Essentials/src/net/ess3/economy/Trade.java create mode 100644 Essentials/src/net/ess3/economy/Worth.java create mode 100644 Essentials/src/net/ess3/economy/WorthHolder.java create mode 100644 Essentials/src/net/ess3/economy/register/Method.java create mode 100644 Essentials/src/net/ess3/economy/register/Methods.java create mode 100644 Essentials/src/net/ess3/economy/register/methods/BOSE6.java create mode 100644 Essentials/src/net/ess3/economy/register/methods/BOSE7.java create mode 100644 Essentials/src/net/ess3/economy/register/methods/MCUR.java create mode 100644 Essentials/src/net/ess3/economy/register/methods/VaultEco.java create mode 100644 Essentials/src/net/ess3/economy/register/methods/iCo4.java create mode 100644 Essentials/src/net/ess3/economy/register/methods/iCo5.java create mode 100644 Essentials/src/net/ess3/economy/register/methods/iCo6.java create mode 100644 Essentials/src/net/ess3/listener/EssentialsBlockListener.java create mode 100644 Essentials/src/net/ess3/listener/EssentialsEntityListener.java create mode 100644 Essentials/src/net/ess3/listener/EssentialsPlayerListener.java create mode 100644 Essentials/src/net/ess3/listener/EssentialsPluginListener.java create mode 100644 Essentials/src/net/ess3/listener/TntExplodeListener.java create mode 100644 Essentials/src/net/ess3/permissions/AbstractSuperpermsPermission.java create mode 100644 Essentials/src/net/ess3/permissions/BasePermission.java create mode 100644 Essentials/src/net/ess3/permissions/EnchantPermissions.java create mode 100644 Essentials/src/net/ess3/permissions/GivePermissions.java create mode 100644 Essentials/src/net/ess3/permissions/GroupsPermissions.java create mode 100644 Essentials/src/net/ess3/permissions/HelpPermissions.java create mode 100644 Essentials/src/net/ess3/permissions/ItemPermissions.java create mode 100644 Essentials/src/net/ess3/permissions/KitPermissions.java create mode 100644 Essentials/src/net/ess3/permissions/NoCommandCostPermissions.java create mode 100644 Essentials/src/net/ess3/permissions/Permissions.java create mode 100644 Essentials/src/net/ess3/permissions/SpawnerPermissions.java create mode 100644 Essentials/src/net/ess3/permissions/SpawnmobPermissions.java create mode 100644 Essentials/src/net/ess3/permissions/UnlimitedItemPermissions.java create mode 100644 Essentials/src/net/ess3/permissions/WarpPermissions.java create mode 100644 Essentials/src/net/ess3/permissions/WorldPermissions.java create mode 100644 Essentials/src/net/ess3/ranks/GMGroups.java create mode 100644 Essentials/src/net/ess3/ranks/RankOptions.java create mode 100644 Essentials/src/net/ess3/ranks/Ranks.java create mode 100644 Essentials/src/net/ess3/ranks/RanksStorage.java create mode 100644 Essentials/src/net/ess3/ranks/VaultGroups.java create mode 100644 Essentials/src/net/ess3/settings/Backup.java create mode 100644 Essentials/src/net/ess3/settings/Chat.java create mode 100644 Essentials/src/net/ess3/settings/Commands.java create mode 100644 Essentials/src/net/ess3/settings/Economy.java create mode 100644 Essentials/src/net/ess3/settings/General.java create mode 100644 Essentials/src/net/ess3/settings/Jails.java create mode 100644 Essentials/src/net/ess3/settings/Kit.java create mode 100644 Essentials/src/net/ess3/settings/Kits.java create mode 100644 Essentials/src/net/ess3/settings/Settings.java create mode 100644 Essentials/src/net/ess3/settings/SettingsHolder.java create mode 100644 Essentials/src/net/ess3/settings/Spawns.java create mode 100644 Essentials/src/net/ess3/settings/SpawnsHolder.java create mode 100644 Essentials/src/net/ess3/settings/Warp.java create mode 100644 Essentials/src/net/ess3/settings/WarpHolder.java create mode 100644 Essentials/src/net/ess3/settings/WorldOptions.java create mode 100644 Essentials/src/net/ess3/settings/Worlds.java create mode 100644 Essentials/src/net/ess3/settings/commands/Afk.java create mode 100644 Essentials/src/net/ess3/settings/commands/Back.java create mode 100644 Essentials/src/net/ess3/settings/commands/God.java create mode 100644 Essentials/src/net/ess3/settings/commands/Help.java create mode 100644 Essentials/src/net/ess3/settings/commands/Home.java create mode 100644 Essentials/src/net/ess3/settings/commands/Lightning.java create mode 100644 Essentials/src/net/ess3/settings/commands/List.java create mode 100644 Essentials/src/net/ess3/settings/commands/Spawnmob.java create mode 100644 Essentials/src/net/ess3/settings/commands/Tpa.java create mode 100644 Essentials/src/net/ess3/settings/geoip/Database.java create mode 100644 Essentials/src/net/ess3/settings/geoip/GeoIP.java create mode 100644 Essentials/src/net/ess3/settings/protect/Prevent.java create mode 100644 Essentials/src/net/ess3/settings/protect/Protect.java create mode 100644 Essentials/src/net/ess3/settings/protect/SignsAndRails.java create mode 100644 Essentials/src/net/ess3/storage/AbstractDelayedYamlFileReader.java create mode 100644 Essentials/src/net/ess3/storage/AbstractDelayedYamlFileWriter.java create mode 100644 Essentials/src/net/ess3/storage/AsyncStorageObjectHolder.java create mode 100644 Essentials/src/net/ess3/storage/BukkitConstructor.java create mode 100644 Essentials/src/net/ess3/storage/Comment.java create mode 100644 Essentials/src/net/ess3/storage/EnchantmentLevel.java create mode 100644 Essentials/src/net/ess3/storage/IStorageObjectHolder.java create mode 100644 Essentials/src/net/ess3/storage/IStorageObjectMap.java create mode 100644 Essentials/src/net/ess3/storage/IStorageReader.java create mode 100644 Essentials/src/net/ess3/storage/IStorageWriter.java create mode 100644 Essentials/src/net/ess3/storage/ListType.java create mode 100644 Essentials/src/net/ess3/storage/ManagedFile.java create mode 100644 Essentials/src/net/ess3/storage/MapKeyType.java create mode 100644 Essentials/src/net/ess3/storage/MapValueType.java create mode 100644 Essentials/src/net/ess3/storage/ObjectLoadException.java create mode 100644 Essentials/src/net/ess3/storage/StorageObject.java create mode 100644 Essentials/src/net/ess3/storage/StorageObjectMap.java create mode 100644 Essentials/src/net/ess3/storage/StoredLocation.java create mode 100644 Essentials/src/net/ess3/storage/YamlStorageReader.java create mode 100644 Essentials/src/net/ess3/storage/YamlStorageWriter.java create mode 100644 Essentials/src/net/ess3/user/Ban.java create mode 100644 Essentials/src/net/ess3/user/CooldownException.java create mode 100644 Essentials/src/net/ess3/user/IOfflinePlayer.java create mode 100644 Essentials/src/net/ess3/user/IOfflineUser.java create mode 100644 Essentials/src/net/ess3/user/Inventory.java create mode 100644 Essentials/src/net/ess3/user/TooManyMatchesException.java create mode 100644 Essentials/src/net/ess3/user/User.java create mode 100644 Essentials/src/net/ess3/user/UserBase.java create mode 100644 Essentials/src/net/ess3/user/UserData.java create mode 100644 Essentials/src/net/ess3/user/UserMap.java create mode 100644 Essentials/src/net/ess3/utils/DateUtil.java create mode 100644 Essentials/src/net/ess3/utils/DescParseTickFormat.java create mode 100644 Essentials/src/net/ess3/utils/ExecuteTimer.java create mode 100644 Essentials/src/net/ess3/utils/LocationUtil.java create mode 100644 Essentials/src/net/ess3/utils/Util.java create mode 100644 Essentials/src/net/ess3/utils/gnu/inet/encoding/Punycode.java create mode 100644 Essentials/src/net/ess3/utils/gnu/inet/encoding/PunycodeException.java create mode 100644 Essentials/src/net/ess3/utils/textreader/ArrayListInput.java create mode 100644 Essentials/src/net/ess3/utils/textreader/HelpInput.java create mode 100644 Essentials/src/net/ess3/utils/textreader/IText.java create mode 100644 Essentials/src/net/ess3/utils/textreader/KeywordReplacer.java create mode 100644 Essentials/src/net/ess3/utils/textreader/SimpleTextInput.java create mode 100644 Essentials/src/net/ess3/utils/textreader/SimpleTextPager.java create mode 100644 Essentials/src/net/ess3/utils/textreader/TextInput.java create mode 100644 Essentials/src/net/ess3/utils/textreader/TextPager.java delete mode 100644 Essentials2Compat/src/com/earth2me/essentials/api/Economy.java diff --git a/Essentials/src/com/earth2me/essentials/Console.java b/Essentials/src/com/earth2me/essentials/Console.java deleted file mode 100644 index 296ff380f..000000000 --- a/Essentials/src/com/earth2me/essentials/Console.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.earth2me.essentials; - -import com.earth2me.essentials.api.IReplyTo; -import com.earth2me.essentials.api.server.CommandSender; - - -public final class Console implements IReplyTo -{ - private static Console instance = new Console(); - private CommandSender replyTo; - public final static String NAME = "Console"; - - private Console() - { - } - - @Override - public void setReplyTo(final CommandSender user) - { - replyTo = user; - } - - @Override - public CommandSender getReplyTo() - { - return replyTo; - } - - public static Console getConsoleReplyTo() - { - return instance; - } -} diff --git a/Essentials/src/com/earth2me/essentials/Essentials.java b/Essentials/src/com/earth2me/essentials/Essentials.java deleted file mode 100644 index ff0086dda..000000000 --- a/Essentials/src/com/earth2me/essentials/Essentials.java +++ /dev/null @@ -1,378 +0,0 @@ -/* - * Essentials - a bukkit plugin - * Copyright (C) 2011 Essentials Team - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.earth2me.essentials; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.*; -import com.earth2me.essentials.api.server.Player; -import com.earth2me.essentials.api.server.IPlugin; -import com.earth2me.essentials.api.server.IServer; -import com.earth2me.essentials.api.server.World; -import com.earth2me.essentials.backup.Backup; -import com.earth2me.essentials.commands.EssentialsCommandHandler; -import com.earth2me.essentials.economy.Economy; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.economy.WorthHolder; -import com.earth2me.essentials.economy.register.Methods; -import com.earth2me.essentials.listener.*; -import com.earth2me.essentials.ranks.RanksStorage; -import com.earth2me.essentials.settings.SettingsHolder; -import com.earth2me.essentials.settings.SpawnsHolder; -import com.earth2me.essentials.user.UserMap; -import com.earth2me.essentials.utils.ExecuteTimer; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import lombok.Getter; -import org.bukkit.Server; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.plugin.InvalidDescriptionException; -import org.yaml.snakeyaml.error.YAMLException; - - -public class Essentials implements IEssentials -{ - private transient ISettings settings; - private final transient TntExplodeListener tntListener = new TntExplodeListener(this); - private transient IJails jails; - private transient IKits kits; - private transient IWarps warps; - private transient IWorth worth; - private transient List reloadList; - private transient IBackup backup; - private transient IItemDb itemDb; - private transient IRanks groups; - private transient SpawnsHolder spawns; - private transient final Methods paymentMethod = new Methods(); - //private transient PermissionsHandler permissionsHandler; - private transient IUserMap userMap; - private transient ExecuteTimer execTimer; - @Getter - private final I18n i18n; - private transient ICommandHandler commandHandler; - private transient Economy economy; - @Getter - private final IServer server; - @Getter - private final Logger logger; - @Getter - private final IPlugin plugin; - public static boolean testing; - - public Essentials(final IServer server, final Logger logger, final IPlugin plugin) - { - this.server = server; - this.logger = logger; - this.plugin = plugin; - this.i18n = new I18n(this); - i18n.onEnable(); - } - - @Override - public ISettings getSettings() - { - return settings; - } - - public void setupForTesting(final Server server) throws IOException, InvalidDescriptionException - { - testing = true; - final File dataFolder = File.createTempFile("essentialstest", ""); - if (!dataFolder.delete()) - { - throw new IOException(); - } - if (!dataFolder.mkdir()) - { - throw new IOException(); - } - - logger.log(Level.INFO, _("usingTempFolderForTesting")); - logger.log(Level.INFO, dataFolder.toString()); - //this.initialize(null, server, new PluginDescriptionFile(new FileReader(new File("src" + File.separator + "plugin.yml"))), dataFolder, null, null); - settings = new SettingsHolder(this); - i18n.updateLocale("en"); - userMap = new UserMap(this); - //permissionsHandler = new PermissionsHandler(this); - economy = new Economy(this); - } - - @Override - public void onEnable() - { - execTimer = new ExecuteTimer(); - execTimer.start(); - - execTimer.mark("I18n1"); - - execTimer.mark("BukkitCheck"); - try - { - //final EssentialsUpgrade upgrade = new EssentialsUpgrade(this); - //upgrade.beforeSettings(); - //execTimer.mark("Upgrade"); - reloadList = new ArrayList(); - settings = new SettingsHolder(this); - reloadList.add(settings); - execTimer.mark("Settings"); - //upgrade.afterSettings(); - //execTimer.mark("Upgrade2"); - i18n.updateLocale(settings.getLocale()); - userMap = new UserMap(this); - reloadList.add(userMap); - execTimer.mark("Init(Usermap)"); - groups = new RanksStorage(this); - reloadList.add((RanksStorage)groups); - warps = new Warps(this); - reloadList.add(warps); - execTimer.mark("Init(Spawn/Warp)"); - worth = new WorthHolder(this); - reloadList.add(worth); - itemDb = new ItemDb(this); - reloadList.add(itemDb); - execTimer.mark("Init(Worth/ItemDB)"); - kits = new Kits(this); - reloadList.add(kits); - commandHandler = new EssentialsCommandHandler(Essentials.class.getClassLoader(), "com.earth2me.essentials.commands.Command", "essentials.", this); - reloadList.add(commandHandler); - economy = new Economy(this); - reloadList.add(economy); - spawns = new SpawnsHolder(this); - reloadList.add(spawns); - onReload(); - } - catch (YAMLException exception) - { - if (pm.getPlugin("EssentialsUpdate") != null) - { - logger.log(Level.SEVERE, _("essentialsHelp2")); - } - else - { - logger.log(Level.SEVERE, _("essentialsHelp1")); - } - logger.log(Level.SEVERE, exception.toString()); - pm.registerEvents(new Listener() - { - @EventHandler(priority = EventPriority.LOW) - public void onPlayerJoin(final PlayerJoinEvent event) - { - event.getPlayer().sendMessage("Essentials failed to load, read the log file."); - } - }, this); - for (Player player : getServer().getOnlinePlayers()) - { - player.sendMessage("Essentials failed to load, read the log file."); - } - this.setEnabled(false); - return; - } - backup = new Backup(this); - //permissionsHandler = new PermissionsHandler(this); - final EssentialsPluginListener serverListener = new EssentialsPluginListener(this); - pm.registerEvents(serverListener, this); - reloadList.add(serverListener); - - final EssentialsPlayerListener playerListener = new EssentialsPlayerListener(this); - pm.registerEvents(playerListener, this); - - final EssentialsBlockListener blockListener = new EssentialsBlockListener(this); - pm.registerEvents(blockListener, this); - - final EssentialsEntityListener entityListener = new EssentialsEntityListener(this); - pm.registerEvents(entityListener, this); - - jails = new Jails(this); - reloadList.add(jails); - - pm.registerEvents(tntListener, this); - - - final EssentialsTimer timer = new EssentialsTimer(this); - getPlugin().scheduleSyncRepeatingTask(timer, 1, 100); - execTimer.mark("RegListeners"); - final String timeroutput = execTimer.end(); - if (getSettings().isDebug()) - { - logger.log(Level.INFO, "Essentials load {0}", timeroutput); - } - } - - @Override - public void onDisable() - { - i18n.onDisable(); - Trade.closeLog(); - } - - @Override - public void onReload() - { - Trade.closeLog(); - - for (IReload iReload : reloadList) - { - iReload.onReload(); - execTimer.mark("Reload(" + iReload.getClass().getSimpleName() + ")"); - } - - i18n.updateLocale(settings.getLocale()); - } - - @Override - public IJails getJails() - { - return jails; - } - - @Override - public IKits getKits() - { - return kits; - } - - @Override - public IWarps getWarps() - { - return warps; - } - - @Override - public IWorth getWorth() - { - return worth; - } - - @Override - public IBackup getBackup() - { - return backup; - } - - @Override - public IUser getUser(final String playerName) - { - return userMap.getUser(playerName); - } - - @Override - public World getWorld(final String name) - { - if (name.matches("[0-9]+")) - { - final int worldId = Integer.parseInt(name); - if (worldId < getServer().getWorlds().size()) - { - return getServer().getWorlds().get(worldId); - } - } - return getServer().getWorld(name); - } - - @Override - public void addReloadListener(final IReload listener) - { - reloadList.add(listener); - } - - @Override - public Methods getPaymentMethod() - { - return paymentMethod; - } - - @Override - public int broadcastMessage(final IUser sender, final String message) - { - if (sender == null) - { - return getServer().broadcastMessage(message); - } - if (sender.isHidden()) - { - return 0; - } - for (Player player : getServer().getOnlinePlayers()) - { - final IUser user = player.getUser(); - if (!user.isIgnoringPlayer(sender.getName())) - { - player.sendMessage(message); - } - } - - return getServer().getOnlinePlayers().size(); - } - - @Override - public TntExplodeListener getTNTListener() - { - return tntListener; - } - - /* - * @Override public PermissionsHandler getPermissionsHandler() { return permissionsHandler; } - */ - @Override - public IItemDb getItemDb() - { - return itemDb; - } - - @Override - public IUserMap getUserMap() - { - return userMap; - } - - @Override - public IRanks getRanks() - { - return groups; - } - - @Override - public ICommandHandler getCommandHandler() - { - return commandHandler; - } - - @Override - public void setRanks(final IRanks groups) - { - this.groups = groups; - } - - @Override - public void removeReloadListener(IReload groups) - { - this.reloadList.remove(groups); - } - - @Override - public IEconomy getEconomy() - { - return economy; - } -} diff --git a/Essentials/src/com/earth2me/essentials/EssentialsTimer.java b/Essentials/src/com/earth2me/essentials/EssentialsTimer.java deleted file mode 100644 index 8bbcb4c66..000000000 --- a/Essentials/src/com/earth2me/essentials/EssentialsTimer.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.earth2me.essentials; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.Player; -import com.earth2me.essentials.permissions.Permissions; -import com.earth2me.essentials.user.UserData.TimestampType; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.logging.Level; -import org.bukkit.entity.Player; - - -public class EssentialsTimer implements Runnable -{ - private final transient IEssentials ess; - private final transient Set onlineUsers = new HashSet(); - - EssentialsTimer(final IEssentials ess) - { - this.ess = ess; - } - - @Override - public void run() - { - final long currentTime = System.currentTimeMillis(); - for (Player player : ess.getServer().getOnlinePlayers()) - { - - try - { - final IUser user = player.getUser(); - onlineUsers.add(user); - user.setLastOnlineActivity(currentTime); - user.checkActivity(); - - boolean mailDisabled = false; - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - try - { - mailDisabled = settings.getData().getCommands().isDisabled("mail"); - } - finally - { - settings.unlock(); - } - // New mail notification - if (user != null && !mailDisabled && Permissions.MAIL.isAuthorized(user) && !user.gotMailInfo()) - { - final List mail = user.getMails(); - if (mail != null && !mail.isEmpty()) - { - user.sendMessage(_("youHaveNewMail", mail.size())); - } - } - } - catch (Exception e) - { - ess.getLogger().log(Level.WARNING, "EssentialsTimer Error:", e); - } - } - - final Iterator iterator = onlineUsers.iterator(); - while (iterator.hasNext()) - { - final IUser user = iterator.next(); - if (user.getLastOnlineActivity() < currentTime && user.getLastOnlineActivity() > user.getTimestamp(TimestampType.LOGOUT)) - { - user.setTimestamp(TimestampType.LOGOUT, user.getLastOnlineActivity()); - iterator.remove(); - continue; - } - user.checkMuteTimeout(currentTime); - user.checkJailTimeout(currentTime); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/I18n.java b/Essentials/src/com/earth2me/essentials/I18n.java deleted file mode 100644 index 6eb164dd4..000000000 --- a/Essentials/src/com/earth2me/essentials/I18n.java +++ /dev/null @@ -1,177 +0,0 @@ -package com.earth2me.essentials; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.II18n; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.text.MessageFormat; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; - - -public class I18n implements 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 final transient Map messageFormatCache = new HashMap(); - private final transient IEssentials ess; - - public I18n(final IEssentials ess) - { - this.ess = ess; - customBundle = ResourceBundle.getBundle(MESSAGES, defaultLocale, new FileResClassLoader(I18n.class.getClassLoader(), ess)); - localeBundle = ResourceBundle.getBundle(MESSAGES, defaultLocale); - defaultBundle = ResourceBundle.getBundle(MESSAGES, Locale.ENGLISH); - } - - public void onEnable() - { - instance = this; - } - - public void onDisable() - { - instance = null; - } - - @Override - public Locale getCurrentLocale() - { - return currentLocale; - } - - public String translate(final String string) - { - try - { - try - { - return customBundle.getString(string); - } - catch (MissingResourceException ex) - { - return localeBundle.getString(string); - } - } - catch (MissingResourceException ex) - { - Logger.getLogger("Minecraft").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 _(final String string, final Object... objects) - { - if (instance == null) { - return ""; - } - if (objects.length == 0) - { - return instance.translate(string); - } - else - { - return instance.format(string, objects); - } - } - - public String format(final String string, final Object... objects) - { - final String format = translate(string); - MessageFormat messageFormat = messageFormatCache.get(format); - if (messageFormat == null) - { - messageFormat = new MessageFormat(format); - messageFormatCache.put(format, messageFormat); - } - return messageFormat.format(objects); - } - - public void updateLocale(final String loc) - { - if (loc == null || loc.isEmpty()) - { - return; - } - final String[] parts = loc.split("[_\\.]"); - if (parts.length == 1) - { - currentLocale = new Locale(parts[0]); - } - if (parts.length == 2) - { - currentLocale = new Locale(parts[0], parts[1]); - } - if (parts.length == 3) - { - currentLocale = new Locale(parts[0], parts[1], parts[2]); - } - Logger.getLogger("Minecraft").log(Level.INFO, String.format("Using locale %s", currentLocale.toString())); - customBundle = ResourceBundle.getBundle(MESSAGES, currentLocale, new FileResClassLoader(I18n.class.getClassLoader(), ess)); - localeBundle = ResourceBundle.getBundle(MESSAGES, currentLocale); - } - - 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); - } - - - private static class FileResClassLoader extends ClassLoader - { - private final transient File dataFolder; - - public FileResClassLoader(final ClassLoader classLoader, final IEssentials ess) - { - super(classLoader); - this.dataFolder = ess.getPlugin().getDataFolder(); - } - - @Override - public URL getResource(final String string) - { - final File file = new File(dataFolder, string); - if (file.exists()) - { - try - { - return file.toURI().toURL(); - } - catch (MalformedURLException ex) - { - } - } - return super.getResource(string); - } - - @Override - public InputStream getResourceAsStream(final String string) - { - final File file = new File(dataFolder, string); - if (file.exists()) - { - try - { - return new FileInputStream(file); - } - catch (FileNotFoundException ex) - { - } - } - return super.getResourceAsStream(string); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/ItemDb.java b/Essentials/src/com/earth2me/essentials/ItemDb.java deleted file mode 100644 index 479119a31..000000000 --- a/Essentials/src/com/earth2me/essentials/ItemDb.java +++ /dev/null @@ -1,151 +0,0 @@ -package com.earth2me.essentials; - -import com.earth2me.essentials.storage.ManagedFile; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IItemDb; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.ItemStack; -import com.earth2me.essentials.api.server.Material; -import com.earth2me.essentials.permissions.Permissions; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.regex.Pattern; -import lombok.Cleanup; - - -public class ItemDb implements IItemDb -{ - private final transient IEssentials ess; - - public ItemDb(final IEssentials ess) - { - this.ess = ess; - file = new ManagedFile("items.csv", ess); - } - private final transient Map items = new HashMap(); - private final transient ManagedFile file; - private static final Pattern SPLIT = Pattern.compile("[^a-zA-Z0-9]"); - - @Override - public void onReload() - { - final List lines = file.getLines(); - - if (lines.isEmpty()) - { - return; - } - - items.clear(); - - for (String line : lines) - { - line = line.trim(); - if (line.length() > 0 && line.charAt(0) == '#') - { - continue; - } - - final String[] parts = SPLIT.split(line); - if (parts.length < 2) - { - continue; - } - - final long numeric = Integer.parseInt(parts[1]); - - final long durability = parts.length > 2 && !(parts[2].length() == 1 && parts[2].charAt(0) == '0') ? Short.parseShort(parts[2]) : 0; - items.put(parts[0].toLowerCase(Locale.ENGLISH), numeric | (durability << 32)); - } - } - - public ItemStack get(final String id, final IUser user) throws Exception - { - final ItemStack stack = get(id.toLowerCase(Locale.ENGLISH)); - - @Cleanup - com.earth2me.essentials.api.ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - - final int defaultStackSize = settings.getData().getGeneral().getDefaultStacksize(); - - if (defaultStackSize > 0) - { - stack.setAmount(defaultStackSize); - } - else - { - final int oversizedStackSize = settings.getData().getGeneral().getOversizedStacksize(); - if (oversizedStackSize > 0 && Permissions.OVERSIZEDSTACKS.isAuthorized(user)) - { - stack.setAmount(oversizedStackSize); - } - } - return stack; - } - - public ItemStack get(final String id, final int quantity) throws Exception - { - final ItemStack retval = get(id.toLowerCase(Locale.ENGLISH)); - retval.setAmount(quantity); - return retval; - } - - public ItemStack get(final String id) throws Exception - { - int itemid = 0; - String itemname = null; - short metaData = 0; - if (id.matches("^\\d+[:+',;.]\\d+$")) - { - itemid = Integer.parseInt(id.split("[:+',;.]")[0]); - metaData = Short.parseShort(id.split("[:+',;.]")[1]); - } - else if (id.matches("^\\d+$")) - { - itemid = Integer.parseInt(id); - } - else if (id.matches("^[^:+',;.]+[:+',;.]\\d+$")) - { - itemname = id.split("[:+',;.]")[0].toLowerCase(Locale.ENGLISH); - metaData = Short.parseShort(id.split("[:+',;.]")[1]); - } - else - { - itemname = id.toLowerCase(Locale.ENGLISH); - } - - if (itemname != null) - { - if (items.containsKey(itemname)) - { - long item = items.get(itemname); - itemid = (int)(item & 0xffffffffL); - if (metaData == 0) - { - metaData = (short)((item >> 32) & 0xffffL); - } - } - else if (Material.get(itemname) != null) - { - itemid = Material.get(itemname).getId(); - metaData = 0; - } - else - { - throw new Exception(_("unknownItemName", id)); - } - } - - final Material mat = Material.get(itemid); - if (mat == null) - { - throw new Exception(_("unknownItemId", itemid)); - } - final ItemStack retval = ItemStack.create(mat, mat.getMaxStackSize(), metaData); - return retval; - } -} diff --git a/Essentials/src/com/earth2me/essentials/Jails.java b/Essentials/src/com/earth2me/essentials/Jails.java deleted file mode 100644 index cc95da8aa..000000000 --- a/Essentials/src/com/earth2me/essentials/Jails.java +++ /dev/null @@ -1,301 +0,0 @@ -package com.earth2me.essentials; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IJails; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.storage.AsyncStorageObjectHolder; -import java.io.File; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; -import lombok.Cleanup; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockDamageEvent; -import org.bukkit.event.block.BlockPlaceEvent; -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; - - -public class Jails extends AsyncStorageObjectHolder implements IJails -{ - private static final transient Logger LOGGER = Bukkit.getLogger(); - - public Jails(final IEssentials ess) - { - super(ess, com.earth2me.essentials.settings.Jails.class); - onReload(); - registerListeners(); - } - - private void registerListeners() - { - final PluginManager pluginManager = ess.getServer().getPluginManager(); - final JailBlockListener blockListener = new JailBlockListener(); - final JailPlayerListener playerListener = new JailPlayerListener(); - pluginManager.registerEvents(blockListener, ess); - pluginManager.registerEvents(playerListener, ess); - } - - @Override - public File getStorageFile() - { - return new File(ess.getPlugin().getDataFolder(), "jail.yml"); - } - - @Override - public Location getJail(final String jailName) throws Exception - { - acquireReadLock(); - try - { - if (getData().getJails() == null || jailName == null - || !getData().getJails().containsKey(jailName.toLowerCase(Locale.ENGLISH))) - { - throw new Exception(_("jailNotExist")); - } - Location loc = getData().getJails().get(jailName.toLowerCase(Locale.ENGLISH)).getStoredLocation(); - if (loc == null || loc.getWorld() == null) - { - throw new Exception(_("jailNotExist")); - } - return loc; - } - finally - { - unlock(); - } - } - - @Override - public Collection getList() throws Exception - { - acquireReadLock(); - try - { - if (getData().getJails() == null) - { - return Collections.emptyList(); - } - return new ArrayList(getData().getJails().keySet()); - } - finally - { - unlock(); - } - } - - @Override - public void removeJail(final String jail) throws Exception - { - acquireWriteLock(); - try - { - if (getData().getJails() == null) - { - return; - } - getData().getJails().remove(jail.toLowerCase(Locale.ENGLISH)); - } - finally - { - unlock(); - } - } - - @Override - public void sendToJail(final IUser user, final String jail) throws Exception - { - acquireReadLock(); - try - { - if (user.isOnline()) - { - Location loc = getJail(jail); - user.getTeleport().now(loc, false, TeleportCause.COMMAND); - } - user.acquireWriteLock(); - try - { - user.getData().setJail(jail); - } - finally - { - unlock(); - } - } - finally - { - unlock(); - } - } - - @Override - public void setJail(final String jailName, final Location loc) throws Exception - { - acquireWriteLock(); - try - { - if (getData().getJails() == null) - { - getData().setJails(new HashMap()); - } - getData().getJails().put(jailName.toLowerCase(Locale.ENGLISH), new com.earth2me.essentials.storage.StoredLocation(loc)); - } - finally - { - unlock(); - } - } - - - private class JailBlockListener implements Listener - { - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onBlockBreak(final BlockBreakEvent event) - { - @Cleanup - final IUser user = ess.getUser(event.getPlayer()); - user.acquireReadLock(); - if (user.getData().isJailed()) - { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onBlockPlace(final BlockPlaceEvent event) - { - @Cleanup - final IUser user = ess.getUser(event.getPlayer()); - user.acquireReadLock(); - if (user.getData().isJailed()) - { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onBlockDamage(final BlockDamageEvent event) - { - @Cleanup - final IUser user = ess.getUser(event.getPlayer()); - user.acquireReadLock(); - if (user.getData().isJailed()) - { - event.setCancelled(true); - } - } - } - - - private class JailPlayerListener implements Listener - { - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onPlayerInteract(final PlayerInteractEvent event) - { - @Cleanup - final IUser user = ess.getUser(event.getPlayer()); - user.acquireReadLock(); - if (user.getData().isJailed()) - { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onPlayerRespawn(final PlayerRespawnEvent event) - { - @Cleanup - final IUser user = ess.getUser(event.getPlayer()); - user.acquireReadLock(); - if (!user.getData().isJailed() || user.getData().getJail() == null || user.getData().getJail().isEmpty()) - { - return; - } - - try - { - event.setRespawnLocation(getJail(user.getData().getJail())); - } - catch (Exception ex) - { - if (ess.getSettings().isDebug()) - { - LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex); - } - else - { - LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())); - } - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerTeleport(final PlayerTeleportEvent event) - { - @Cleanup - final IUser user = ess.getUser(event.getPlayer()); - user.acquireReadLock(); - if (!user.getData().isJailed() || user.getData().getJail() == null || user.getData().getJail().isEmpty()) - { - return; - } - - try - { - event.setTo(getJail(user.getData().getJail())); - } - catch (Exception ex) - { - if (ess.getSettings().isDebug()) - { - LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex); - } - else - { - LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())); - } - } - user.sendMessage(_("jailMessage")); - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onPlayerJoin(final PlayerJoinEvent event) - { - @Cleanup - final IUser user = ess.getUser(event.getPlayer()); - user.acquireReadLock(); - if (!user.getData().isJailed() || user.getData().getJail() == null || user.getData().getJail().isEmpty()) - { - return; - } - - try - { - sendToJail(user, user.getData().getJail()); - } - catch (Exception ex) - { - if (ess.getSettings().isDebug()) - { - LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex); - } - else - { - LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())); - } - } - user.sendMessage(_("jailMessage")); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/Kits.java b/Essentials/src/com/earth2me/essentials/Kits.java deleted file mode 100644 index 2f12188eb..000000000 --- a/Essentials/src/com/earth2me/essentials/Kits.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.earth2me.essentials; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IKits; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.settings.Kit; -import com.earth2me.essentials.storage.AsyncStorageObjectHolder; -import java.io.File; -import java.io.IOException; -import java.util.*; -import org.bukkit.inventory.ItemStack; - - -public class Kits extends AsyncStorageObjectHolder implements IKits -{ - public Kits(final IEssentials ess) - { - super(ess, com.earth2me.essentials.settings.Kits.class); - onReload(); - } - - @Override - public File getStorageFile() throws IOException - { - return new File(ess.getPlugin().getDataFolder(), "kits.yml"); - } - - @Override - public Kit getKit(String kitName) throws Exception - { - acquireReadLock(); - try - { - if (getData().getKits() == null || kitName == null - || !getData().getKits().containsKey(kitName.toLowerCase(Locale.ENGLISH))) - { - throw new Exception(_("kitError2")); - } - final Kit kit = getData().getKits().get(kitName.toLowerCase(Locale.ENGLISH)); - if (kit == null) - { - throw new Exception(_("kitError2")); - } - return kit; - } - finally - { - unlock(); - } - } - - @Override - public void sendKit(IUser user, String kitName) throws Exception - { - final Kit kit = getKit(kitName); - sendKit(user, kit); - } - - @Override - public void sendKit(IUser user, Kit kit) throws Exception - { - final List itemList = kit.getItems(); - user.giveItems(itemList, true); - } - - @Override - public Collection getList() throws Exception - { - acquireReadLock(); - try - { - if (getData().getKits() == null) - { - return Collections.emptyList(); - } - return new ArrayList(getData().getKits().keySet()); - } - finally - { - unlock(); - } - } - - @Override - public boolean isEmpty() - { - return getData().getKits().isEmpty(); - } -} diff --git a/Essentials/src/com/earth2me/essentials/Teleport.java b/Essentials/src/com/earth2me/essentials/Teleport.java deleted file mode 100644 index 4d79183e1..000000000 --- a/Essentials/src/com/earth2me/essentials/Teleport.java +++ /dev/null @@ -1,301 +0,0 @@ -package com.earth2me.essentials; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.ITeleport; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.Player; -import com.earth2me.essentials.api.server.Location; -import com.earth2me.essentials.commands.NotEnoughArgumentsException; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.permissions.Permissions; -import com.earth2me.essentials.user.CooldownException; -import com.earth2me.essentials.user.UserData.TimestampType; -import com.earth2me.essentials.utils.DateUtil; -import com.earth2me.essentials.utils.LocationUtil; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.logging.Logger; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; - - -public class Teleport implements Runnable, ITeleport -{ - private static final double MOVE_CONSTANT = 0.3; - - - private static class Target - { - private final Location location; - private final Player entity; - - public Target(Location location) - { - this.location = location; - this.entity = null; - } - - public Target(Player entity) - { - this.entity = entity; - this.location = null; - } - - public Location getLocation() - { - if (this.entity != null) - { - return this.entity.getLocation(); - } - return location; - } - } - private IUser user; - private int teleTimer = -1; - private long started; // time this task was initiated - private long delay; // how long to delay the teleport - private int 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 - private long initX; - private long initY; - private long initZ; - private Target teleportTarget; - private Trade chargeFor; - private final IEssentials ess; - private static final Logger logger = Logger.getLogger("Minecraft"); - private TeleportCause cause; - - private void initTimer(long delay, Target target, Trade chargeFor, TeleportCause cause) - { - this.started = System.currentTimeMillis(); - this.delay = delay; - this.health = user.getHealth(); - this.initX = Math.round(user.getLocation().getX() * MOVE_CONSTANT); - this.initY = Math.round(user.getLocation().getY() * MOVE_CONSTANT); - this.initZ = Math.round(user.getLocation().getZ() * MOVE_CONSTANT); - this.teleportTarget = target; - this.chargeFor = chargeFor; - this.cause = cause; - } - - @Override - public void run() - { - - if (user == null || !user.isOnline() || user.getLocation() == null) - { - cancel(); - return; - } - if (Math.round(user.getLocation().getX() * MOVE_CONSTANT) != initX - || Math.round(user.getLocation().getY() * MOVE_CONSTANT) != initY - || Math.round(user.getLocation().getZ() * MOVE_CONSTANT) != initZ - || user.getHealth() < health) - { // user moved, cancel teleport - cancel(true); - return; - } - - health = user.getHealth(); // in case user healed, then later gets injured - - long now = System.currentTimeMillis(); - if (now > started + delay) - { - try - { - cooldown(false); - user.sendMessage(_("teleportationCommencing")); - try - { - - now(teleportTarget, cause); - if (chargeFor != null) - { - chargeFor.charge(user); - } - } - catch (Throwable ex) - { - ess.getCommandHandler().showCommandError(user, "teleport", ex); - } - } - catch (Exception ex) - { - user.sendMessage(_("cooldownWithMessage", ex.getMessage())); - } - } - } - - public Teleport(IUser user, IEssentials ess) - { - this.user = user; - this.ess = ess; - } - - public void respawn(final Trade chargeFor, TeleportCause cause) throws Exception - { - final Location bed = user.getBedSpawnLocation(); - final Location respawnLoc = ess.getPlugin().callRespawnEvent(user, bed == null ? user.getWorld().getSpawnLocation() : bed, bed != null); - teleport(new Target(respawnLoc), chargeFor, cause); - } - - public void warp(String warp, Trade chargeFor, TeleportCause cause) throws Exception - { - final Location loc = ess.getWarps().getWarp(warp); - teleport(new Target(loc), chargeFor, cause); - user.sendMessage(_("warpingTo", warp)); - } - - public void cooldown(boolean check) throws Exception - { - try - { - user.checkCooldown(TimestampType.LASTTELEPORT, ess.getRanks().getTeleportCooldown(user), !check, Permissions.TELEPORT_COOLDOWN_BYPASS); - } - catch (CooldownException ex) - { - throw new Exception(_("timeBeforeTeleport", ex.getMessage())); - - } - } - - public void cancel(boolean notifyUser) - { - if (teleTimer == -1) - { - return; - } - try - { - ess.getPlugin().cancelTask(teleTimer); - if (notifyUser) - { - user.sendMessage(_("pendingTeleportCancelled")); - } - } - finally - { - teleTimer = -1; - } - } - - public void cancel() - { - cancel(false); - } - - public void teleport(Location loc, Trade chargeFor) throws Exception - { - teleport(new Target(loc), chargeFor, TeleportCause.PLUGIN); - } - - public void teleport(Location loc, Trade chargeFor, TeleportCause cause) throws Exception - { - teleport(new Target(loc), chargeFor, cause); - } - - public void teleport(Player entity, Trade chargeFor, TeleportCause cause) throws Exception - { - teleport(new Target(entity), chargeFor, cause); - } - - private void teleport(Target target, Trade chargeFor, TeleportCause cause) throws Exception - { - double delay = ess.getRanks().getTeleportDelay(user); - - if (chargeFor != null) - { - chargeFor.isAffordableFor(user); - } - cooldown(true); - if (delay <= 0 || Permissions.TELEPORT_TIMER_BYPASS.isAuthorized(user)) - { - cooldown(false); - now(target, cause); - if (chargeFor != null) - { - chargeFor.charge(user); - } - return; - } - - cancel(); - Calendar c = new GregorianCalendar(); - c.add(Calendar.SECOND, (int)delay); - c.add(Calendar.MILLISECOND, (int)((delay * 1000.0) % 1000.0)); - user.sendMessage(_("dontMoveMessage", DateUtil.formatDateDiff(c.getTimeInMillis()))); - initTimer((long)(delay * 1000.0), target, chargeFor, cause); - - teleTimer = ess.getPlugin().scheduleSyncRepeatingTask(this, 10, 10); - } - - private void now(Target target, TeleportCause cause) throws Exception - { - cancel(); - user.setLastLocation(); - user.getBase().teleport(LocationUtil.getSafeDestination(target.getLocation()), cause); - } - - public void now(Location loc, boolean cooldown, TeleportCause cause) throws Exception - { - if (cooldown) - { - cooldown(false); - } - now(new Target(loc), cause); - } - - public void now(Location loc, Trade chargeFor, TeleportCause cause) throws Exception - { - cooldown(false); - chargeFor.charge(user); - now(new Target(loc), cause); - } - - public void now(Player entity, boolean cooldown, TeleportCause cause) throws Exception - { - if (cooldown) - { - cooldown(false); - } - now(new Target(entity), cause); - } - - public void back(Trade chargeFor) throws Exception - { - user.acquireReadLock(); - try - { - teleport(new Target(user.getData().getLastLocation().getStoredLocation()), chargeFor, TeleportCause.COMMAND); - } - finally - { - user.unlock(); - } - } - - public void back() throws Exception - { - user.acquireReadLock(); - try - { - now(new Target(user.getData().getLastLocation().getStoredLocation()), TeleportCause.COMMAND); - } - finally - { - user.unlock(); - } - } - - public void home(IUser user, String home, Trade chargeFor) throws Exception - { - final Location loc = user.getHome(home); - if (loc == null) - { - throw new NotEnoughArgumentsException(); - } - teleport(new Target(loc), chargeFor, TeleportCause.COMMAND); - } -} diff --git a/Essentials/src/com/earth2me/essentials/Warps.java b/Essentials/src/com/earth2me/essentials/Warps.java deleted file mode 100644 index 017fd2d3e..000000000 --- a/Essentials/src/com/earth2me/essentials/Warps.java +++ /dev/null @@ -1,149 +0,0 @@ -package com.earth2me.essentials; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IWarp; -import com.earth2me.essentials.api.IWarps; -import com.earth2me.essentials.api.InvalidNameException; -import com.earth2me.essentials.api.server.Location; -import com.earth2me.essentials.commands.WarpNotFoundException; -import com.earth2me.essentials.settings.WarpHolder; -import com.earth2me.essentials.storage.StorageObjectMap; -import java.io.File; -import java.util.*; -import java.util.logging.Logger; - - -public class Warps extends StorageObjectMap implements IWarps -{ - public Warps(IEssentials ess) - { - super(ess, "warps"); - } - - @Override - public boolean isEmpty() - { - return getKeySize() == 0; - } - - @Override - public Collection getList() - { - final List names = new ArrayList(); - for (String key : getAllKeys()) - { - IWarp warp = getObject(key); - if (warp == null) - { - continue; - } - warp.acquireReadLock(); - try - { - names.add(warp.getData().getName()); - } - finally - { - warp.unlock(); - } - } - Collections.sort(names, String.CASE_INSENSITIVE_ORDER); - return names; - } - - @Override - public Location getWarp(final String name) throws Exception - { - IWarp warp = getObject(name); - if (warp == null) - { - throw new WarpNotFoundException(_("warpNotExist")); - } - warp.acquireReadLock(); - try - { - return warp.getData().getLocation().getStoredLocation(); - } - finally - { - warp.unlock(); - } - } - - @Override - public void setWarp(final String name, final Location loc) throws Exception - { - setWarp(name, new com.earth2me.essentials.storage.StoredLocation(loc)); - } - - public void setWarp(final String name, final com.earth2me.essentials.storage.StoredLocation loc) throws Exception - { - IWarp warp = getObject(name); - if (warp == null) - { - warp = new WarpHolder(name, ess); - } - warp.acquireWriteLock(); - try - { - warp.getData().setLocation(loc); - } - finally - { - warp.unlock(); - } - } - - @Override - public void removeWarp(final String name) throws Exception - { - removeObject(name); - } - - @Override - public File getWarpFile(String name) throws InvalidNameException - { - return getStorageFile(name); - } - - @Override - public IWarp load(String name) throws Exception - { - final IWarp warp = new WarpHolder(name, ess); - warp.onReload(); - return warp; - } - - - private static class StringIgnoreCase - { - private final String string; - - public StringIgnoreCase(String string) - { - this.string = string; - } - - @Override - public int hashCode() - { - return getString().toLowerCase(Locale.ENGLISH).hashCode(); - } - - @Override - public boolean equals(Object o) - { - if (o instanceof StringIgnoreCase) - { - return getString().equalsIgnoreCase(((StringIgnoreCase)o).getString()); - } - return false; - } - - public String getString() - { - return string; - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/api/ChargeException.java b/Essentials/src/com/earth2me/essentials/api/ChargeException.java deleted file mode 100644 index 5b157ce63..000000000 --- a/Essentials/src/com/earth2me/essentials/api/ChargeException.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.earth2me.essentials.api; - - -public class ChargeException extends Exception -{ - public ChargeException(final String message) - { - super(message); - } - - public ChargeException(final String message, final Throwable throwable) - { - super(message, throwable); - } -} diff --git a/Essentials/src/com/earth2me/essentials/api/IBackup.java b/Essentials/src/com/earth2me/essentials/api/IBackup.java deleted file mode 100644 index 8af074c54..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IBackup.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.earth2me.essentials.api; - - -public interface IBackup extends Runnable -{ - public void startTask(); -} diff --git a/Essentials/src/com/earth2me/essentials/api/ICommandHandler.java b/Essentials/src/com/earth2me/essentials/api/ICommandHandler.java deleted file mode 100644 index b515f9f38..000000000 --- a/Essentials/src/com/earth2me/essentials/api/ICommandHandler.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.earth2me.essentials.api; - -import com.earth2me.essentials.api.server.CommandSender; -import java.util.Map; -import org.bukkit.command.Command; -import org.bukkit.plugin.Plugin; - - -public interface ICommandHandler extends IReload -{ - Map disabledCommands(); - - public void removePlugin(Plugin plugin); - - public void addPlugin(Plugin plugin); - - boolean handleCommand(CommandSender sender, Command command, String commandLabel, String[] args); - - void showCommandError(CommandSender sender, String commandLabel, Throwable exception); -} diff --git a/Essentials/src/com/earth2me/essentials/api/IComponent.java b/Essentials/src/com/earth2me/essentials/api/IComponent.java deleted file mode 100644 index ae3c2a9c2..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IComponent.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.earth2me.essentials.api; - -public interface IComponent extends IReload { - /** - * Enable the component. - */ - void onEnable(); - - /** - * Disable the component. - */ - void onDisable(); -} diff --git a/Essentials/src/com/earth2me/essentials/api/IEconomy.java b/Essentials/src/com/earth2me/essentials/api/IEconomy.java deleted file mode 100644 index 092d86c88..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IEconomy.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.earth2me.essentials.api; - - -public interface IEconomy extends IReload -{ - public double getMoney(String name) throws UserDoesNotExistException; - - public void setMoney(String name, double balance) throws UserDoesNotExistException, NoLoanPermittedException; - - public void resetBalance(String name) throws UserDoesNotExistException, NoLoanPermittedException; - - public String format(double amount); - - public boolean playerExists(String name); - - public boolean isNPC(String name) throws UserDoesNotExistException; - - public boolean createNPC(String name); - - public void removeNPC(String name) throws UserDoesNotExistException; -} diff --git a/Essentials/src/com/earth2me/essentials/api/IEssentials.java b/Essentials/src/com/earth2me/essentials/api/IEssentials.java deleted file mode 100644 index 2a3b21147..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IEssentials.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.earth2me.essentials.api; - -import com.earth2me.essentials.api.server.Player; -import com.earth2me.essentials.api.server.IPlugin; -import com.earth2me.essentials.api.server.IServer; -import com.earth2me.essentials.api.server.World; -import com.earth2me.essentials.economy.register.Methods; -import com.earth2me.essentials.listener.TntExplodeListener; -import java.util.logging.Logger; - - -public interface IEssentials extends IComponent -{ - void addReloadListener(IReload listener); - - IUser getUser(String playerName); - - int broadcastMessage(IUser sender, String message); - - II18n getI18n(); - - ISettings getSettings(); - - IRanks getRanks(); - - IJails getJails(); - - IKits getKits(); - - IWarps getWarps(); - - IWorth getWorth(); - - IItemDb getItemDb(); - - IUserMap getUserMap(); - - IBackup getBackup(); - - ICommandHandler getCommandHandler(); - - World getWorld(String name); - - Methods getPaymentMethod(); - - //int scheduleAsyncDelayedTask(Runnable run); - //int scheduleSyncDelayedTask(Runnable run); - //int scheduleSyncDelayedTask(Runnable run, long delay); - //int scheduleSyncRepeatingTask(Runnable run, long delay, long period); - //IPermissionsHandler getPermissionsHandler(); - //void reload(); - TntExplodeListener getTNTListener(); - - void setRanks(IRanks groups); - - void removeReloadListener(IReload groups); - - IEconomy getEconomy(); - - IServer getServer(); - - Logger getLogger(); - - IPlugin getPlugin(); -} diff --git a/Essentials/src/com/earth2me/essentials/api/IEssentialsModule.java b/Essentials/src/com/earth2me/essentials/api/IEssentialsModule.java deleted file mode 100644 index cc185980a..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IEssentialsModule.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.earth2me.essentials.api; - - -public interface IEssentialsModule -{ -} diff --git a/Essentials/src/com/earth2me/essentials/api/II18n.java b/Essentials/src/com/earth2me/essentials/api/II18n.java deleted file mode 100644 index 567d4e59e..000000000 --- a/Essentials/src/com/earth2me/essentials/api/II18n.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.earth2me.essentials.api; - -import java.util.Locale; - - -public interface II18n -{ - Locale getCurrentLocale(); -} diff --git a/Essentials/src/com/earth2me/essentials/api/IItemDb.java b/Essentials/src/com/earth2me/essentials/api/IItemDb.java deleted file mode 100644 index b792e02d2..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IItemDb.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.earth2me.essentials.api; - -import com.earth2me.essentials.api.server.ItemStack; - - -public interface IItemDb extends IReload -{ - ItemStack get(final String name, final IUser user) throws Exception; - - ItemStack get(final String name, final int quantity) throws Exception; - - ItemStack get(final String name) throws Exception; -} diff --git a/Essentials/src/com/earth2me/essentials/api/IJails.java b/Essentials/src/com/earth2me/essentials/api/IJails.java deleted file mode 100644 index caa1ee0a8..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IJails.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.earth2me.essentials.api; - -import java.util.Collection; -import org.bukkit.Location; - - -public interface IJails extends IReload -{ - Location getJail(String jailName) throws Exception; - - Collection getList() throws Exception; - - void removeJail(String jail) throws Exception; - - void sendToJail(IUser user, String jail) throws Exception; - - void setJail(String jailName, Location loc) throws Exception; -} diff --git a/Essentials/src/com/earth2me/essentials/api/IKits.java b/Essentials/src/com/earth2me/essentials/api/IKits.java deleted file mode 100644 index 85ca4cdea..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IKits.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.earth2me.essentials.api; - -import com.earth2me.essentials.settings.Kit; -import java.util.Collection; - - -public interface IKits extends IReload -{ - Kit getKit(String kit) throws Exception; - - void sendKit(IUser user, String kit) throws Exception; - - void sendKit(IUser user, Kit kit) throws Exception; - - Collection getList() throws Exception; - - boolean isEmpty(); -} diff --git a/Essentials/src/com/earth2me/essentials/api/IPermission.java b/Essentials/src/com/earth2me/essentials/api/IPermission.java deleted file mode 100644 index d20e900fd..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IPermission.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.earth2me.essentials.api; - -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.api.server.Permission; - - -public interface IPermission -{ - String getPermissionName(); - - boolean isAuthorized(CommandSender sender); - - Permission getPermission(); - - Permission.Default getPermissionDefault(); -} diff --git a/Essentials/src/com/earth2me/essentials/api/IRanks.java b/Essentials/src/com/earth2me/essentials/api/IRanks.java deleted file mode 100644 index e29b31302..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IRanks.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.earth2me.essentials.api; - -import java.text.MessageFormat; - - -public interface IRanks -{ - String getMainGroup(IUser player); - - boolean inGroup(IUser player, String groupname); - - double getHealCooldown(IUser player); - - double getTeleportCooldown(IUser player); - - double getTeleportDelay(IUser player); - - String getPrefix(IUser player); - - String getSuffix(IUser player); - - int getHomeLimit(IUser player); - - MessageFormat getChatFormat(IUser player); -} diff --git a/Essentials/src/com/earth2me/essentials/api/IReload.java b/Essentials/src/com/earth2me/essentials/api/IReload.java deleted file mode 100644 index 75403b55c..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IReload.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.earth2me.essentials.api; - - -public interface IReload -{ - void onReload(); -} diff --git a/Essentials/src/com/earth2me/essentials/api/IReplyTo.java b/Essentials/src/com/earth2me/essentials/api/IReplyTo.java deleted file mode 100644 index ec07139cb..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IReplyTo.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.earth2me.essentials.api; - -import com.earth2me.essentials.api.server.CommandSender; - - -public interface IReplyTo -{ - void setReplyTo(CommandSender user); - - CommandSender getReplyTo(); -} diff --git a/Essentials/src/com/earth2me/essentials/api/ISettings.java b/Essentials/src/com/earth2me/essentials/api/ISettings.java deleted file mode 100644 index a445d21b4..000000000 --- a/Essentials/src/com/earth2me/essentials/api/ISettings.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.earth2me.essentials.api; - -import com.earth2me.essentials.settings.Settings; -import com.earth2me.essentials.storage.IStorageObjectHolder; - - -public interface ISettings extends IStorageObjectHolder -{ - public String getLocale(); - - public boolean isDebug(); - - public void setDebug(boolean b); -} diff --git a/Essentials/src/com/earth2me/essentials/api/ITeleport.java b/Essentials/src/com/earth2me/essentials/api/ITeleport.java deleted file mode 100644 index 3a5f25f78..000000000 --- a/Essentials/src/com/earth2me/essentials/api/ITeleport.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.earth2me.essentials.api; - -import com.earth2me.essentials.economy.Trade; -import org.bukkit.Location; -import org.bukkit.entity.Entity; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; - - -public interface ITeleport -{ - void now(Location loc, boolean cooldown, TeleportCause cause) throws Exception; - - void now(Entity entity, boolean cooldown, TeleportCause cause) throws Exception; - - void back(Trade chargeFor) throws Exception; - - void teleport(Location bed, Trade charge, TeleportCause teleportCause) throws Exception; - - void teleport(Entity entity, Trade chargeFor, TeleportCause cause) throws Exception; - - void home(IUser player, String toLowerCase, Trade charge) throws Exception; - - void respawn(Trade charge, TeleportCause teleportCause) throws Exception; - - void back() throws Exception; - - public void warp(String name, Trade charge, TeleportCause teleportCause) throws Exception; -} diff --git a/Essentials/src/com/earth2me/essentials/api/IUser.java b/Essentials/src/com/earth2me/essentials/api/IUser.java deleted file mode 100644 index 928dc41b2..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IUser.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.earth2me.essentials.api; - -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.api.server.Player; -import com.earth2me.essentials.api.server.ItemStack; -import com.earth2me.essentials.api.server.Location; -import com.earth2me.essentials.storage.IStorageObjectHolder; -import com.earth2me.essentials.user.CooldownException; -import com.earth2me.essentials.user.UserData; -import java.util.List; - - -public interface IUser extends Player, IStorageObjectHolder, IReload, IReplyTo, Comparable -{ - Player getBase(); - - double getMoney(); - - void takeMoney(double value); - - void takeMoney(double value, CommandSender initiator); - - void giveMoney(double value); - - void giveMoney(double value, CommandSender initiator); - - void giveItems(ItemStack itemStack, Boolean canSpew) throws ChargeException; - - void giveItems(List itemStacks, Boolean canSpew) throws ChargeException; - - void setMoney(double value); - - void payUser(final IUser reciever, final double value) throws Exception; - - void setLastLocation(); - - Location getHome(String name) throws Exception; - - Location getHome(Location loc); - - boolean isHidden(); - - ITeleport getTeleport(); - - void checkCooldown(UserData.TimestampType cooldownType, double cooldown, boolean set, IPermission bypassPermission) throws CooldownException; - - boolean toggleAfk(); - - void updateActivity(boolean broadcast); - - void updateDisplayName(); - - boolean checkJailTimeout(long currentTime); - - boolean checkMuteTimeout(long currentTime); - - boolean checkBanTimeout(long currentTime); - - long getTimestamp(UserData.TimestampType name); - - void setTimestamp(UserData.TimestampType name, long value); - - void setLastOnlineActivity(long currentTime); - - void checkActivity(); - - long getLastOnlineActivity(); - - boolean isGodModeEnabled(); - - boolean isIgnoringPlayer(String name); - - void setIgnoredPlayer(String name, boolean set); - - Location getAfkPosition(); - - boolean toggleGodModeEnabled(); - - void dispose(); - - void updateCompass(); - - List getHomes(); - - void addMail(String string); - - boolean toggleMuted(); - - boolean toggleSocialSpy(); - - void requestTeleport(IUser user, boolean b); - - boolean isTeleportRequestHere(); - - IUser getTeleportRequester(); - - boolean toggleTeleportEnabled(); - - long getTeleportRequestTime(); - - boolean gotMailInfo(); - - List getMails(); - - public boolean canAfford(double money); - - public void updateMoneyCache(double userMoney); - - public boolean canAfford(double amount, boolean b); -} diff --git a/Essentials/src/com/earth2me/essentials/api/IUserMap.java b/Essentials/src/com/earth2me/essentials/api/IUserMap.java deleted file mode 100644 index bdbf084c7..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IUserMap.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.earth2me.essentials.api; - -import com.earth2me.essentials.api.server.Player; -import com.earth2me.essentials.user.TooManyMatchesException; -import java.io.File; -import java.util.List; -import java.util.Set; - - -public interface IUserMap extends IReload -{ - boolean userExists(final String name); - - IUser getUser(final Player player); - - IUser getUser(final String playerName); - - void removeUser(final String name) throws InvalidNameException; - - Set getAllUniqueUsers(); - - int getUniqueUsers(); - - File getUserFile(final String name) throws InvalidNameException; - - IUser matchUser(final String name, final boolean includeHidden, final boolean onlineOnly) throws TooManyMatchesException; - - Set matchUsers(final String name, final boolean includeHidden, final boolean onlineOnly); -} diff --git a/Essentials/src/com/earth2me/essentials/api/IWarp.java b/Essentials/src/com/earth2me/essentials/api/IWarp.java deleted file mode 100644 index f08e5757d..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IWarp.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.earth2me.essentials.api; - -import com.earth2me.essentials.settings.Warp; -import com.earth2me.essentials.storage.IStorageObjectHolder; - - -public interface IWarp extends IStorageObjectHolder -{ -} diff --git a/Essentials/src/com/earth2me/essentials/api/IWarps.java b/Essentials/src/com/earth2me/essentials/api/IWarps.java deleted file mode 100644 index 3c3c4a2e4..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IWarps.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.earth2me.essentials.api; - -import com.earth2me.essentials.api.server.Location; -import java.io.File; -import java.util.Collection; - - -public interface IWarps extends IReload -{ - Location getWarp(String warp) throws Exception; - - Collection getList(); - - void removeWarp(String name) throws Exception; - - void setWarp(String name, Location loc) throws Exception; - - public boolean isEmpty(); - - public File getWarpFile(String name) throws InvalidNameException; -} diff --git a/Essentials/src/com/earth2me/essentials/api/IWorth.java b/Essentials/src/com/earth2me/essentials/api/IWorth.java deleted file mode 100644 index 6a1ba2e9a..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IWorth.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.earth2me.essentials.api; - -import com.earth2me.essentials.api.server.ItemStack; - - - -public interface IWorth extends IReload -{ - double getPrice(ItemStack itemStack); - - void setPrice(ItemStack itemStack, double price); -} diff --git a/Essentials/src/com/earth2me/essentials/api/InvalidNameException.java b/Essentials/src/com/earth2me/essentials/api/InvalidNameException.java deleted file mode 100644 index 951c66b17..000000000 --- a/Essentials/src/com/earth2me/essentials/api/InvalidNameException.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.earth2me.essentials.api; - - -public class InvalidNameException extends Exception -{ - public InvalidNameException(Throwable thrwbl) - { - super(thrwbl); - } -} diff --git a/Essentials/src/com/earth2me/essentials/api/NoLoanPermittedException.java b/Essentials/src/com/earth2me/essentials/api/NoLoanPermittedException.java deleted file mode 100644 index f21bf98cc..000000000 --- a/Essentials/src/com/earth2me/essentials/api/NoLoanPermittedException.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.earth2me.essentials.api; - -import static com.earth2me.essentials.I18n._; - - -public class NoLoanPermittedException extends Exception -{ - public NoLoanPermittedException() - { - super(_("negativeBalanceError")); - } -} diff --git a/Essentials/src/com/earth2me/essentials/api/UserDoesNotExistException.java b/Essentials/src/com/earth2me/essentials/api/UserDoesNotExistException.java deleted file mode 100644 index 531d9ead6..000000000 --- a/Essentials/src/com/earth2me/essentials/api/UserDoesNotExistException.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.earth2me.essentials.api; - -import static com.earth2me.essentials.I18n._; - - -public class UserDoesNotExistException extends Exception -{ - public UserDoesNotExistException(String name) - { - super(_("userDoesNotExist", name)); - } -} diff --git a/Essentials/src/com/earth2me/essentials/api/server/CommandSender.java b/Essentials/src/com/earth2me/essentials/api/server/CommandSender.java deleted file mode 100644 index 37f9c0e1a..000000000 --- a/Essentials/src/com/earth2me/essentials/api/server/CommandSender.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.earth2me.essentials.api.server; - -public interface CommandSender { - boolean isPlayer(); - - void sendMessage(String message); - - boolean isOp(); - - boolean hasPermission(Permission bukkitPermission); - - void sendMessage(String[] string); -} diff --git a/Essentials/src/com/earth2me/essentials/api/server/Enchantment.java b/Essentials/src/com/earth2me/essentials/api/server/Enchantment.java deleted file mode 100644 index 0aff6843a..000000000 --- a/Essentials/src/com/earth2me/essentials/api/server/Enchantment.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.earth2me.essentials.api.server; - -public abstract class Enchantment { - - public abstract int getMaxLevel(); - -} diff --git a/Essentials/src/com/earth2me/essentials/api/server/IInventory.java b/Essentials/src/com/earth2me/essentials/api/server/IInventory.java deleted file mode 100644 index 301f040da..000000000 --- a/Essentials/src/com/earth2me/essentials/api/server/IInventory.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.earth2me.essentials.api.server; - -import java.util.Map; - -public interface IInventory { - - public boolean containsItem(boolean b, boolean b0, ItemStack itemStack); - - public Map addItem(ItemStack itemStack); - - public Map addItem(boolean b, ItemStack itemStack); - - public Map addItem(boolean b, int oversizedStacksize, ItemStack itemStack); - - public boolean addAllItems(boolean b, ItemStack itemStack); - - public void removeItem(boolean b, boolean b0, ItemStack itemStack); - -} diff --git a/Essentials/src/com/earth2me/essentials/api/server/IPlugin.java b/Essentials/src/com/earth2me/essentials/api/server/IPlugin.java deleted file mode 100644 index 61dadcbd6..000000000 --- a/Essentials/src/com/earth2me/essentials/api/server/IPlugin.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.earth2me.essentials.api.server; - -import java.io.File; -import java.io.InputStream; - - -public interface IPlugin -{ - int scheduleAsyncDelayedTask(final Runnable run); - - int scheduleSyncDelayedTask(final Runnable run); - - int scheduleSyncDelayedTask(final Runnable run, final long delay); - - int scheduleSyncRepeatingTask(final Runnable run, final long delay, final long period); - - File getRootFolder(); - - File getDataFolder(); - - void cancelTask(int taskId); - - String getVersion(); - - Class getClassByName(String name); - - InputStream getResource(String string); - - Location callRespawnEvent(Player player, Location loc, boolean bedSpawn); - - void callSuicideEvent(Player player); -} diff --git a/Essentials/src/com/earth2me/essentials/api/server/IServer.java b/Essentials/src/com/earth2me/essentials/api/server/IServer.java deleted file mode 100644 index f83518116..000000000 --- a/Essentials/src/com/earth2me/essentials/api/server/IServer.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.earth2me.essentials.api.server; - -import java.util.Collection; -import java.util.List; - - -public interface IServer -{ - List getWorlds(); - - World getWorld(String name); - - int broadcastMessage(String message); - - Collection getOnlinePlayers(); - - CommandSender getConsoleSender(); - - void dispatchCommand(CommandSender sender, String command); - - void banIP(String ip); - - T getServiceProvider(Class clazz); - - String getVersion(); - - public void unbanIP(String string); -} diff --git a/Essentials/src/com/earth2me/essentials/api/server/ItemStack.java b/Essentials/src/com/earth2me/essentials/api/server/ItemStack.java deleted file mode 100644 index cb40fafc3..000000000 --- a/Essentials/src/com/earth2me/essentials/api/server/ItemStack.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.earth2me.essentials.api.server; - - -public abstract class ItemStack implements Cloneable -{ - public interface ItemStackFactory - { - ItemStack create(int id, int amount, int data); - ItemStack clone(ItemStack stack); - } - private static ItemStackFactory factory; - - public static void setFactory(final ItemStackFactory factory) - { - ItemStack.factory = factory; - } - - public static ItemStack create(int id, int amount, int data) - { - return factory.create(id, amount, data); - } - - public static ItemStack create(Material mat, int amount, int data) - { - return factory.create(mat.getId(), amount, data); - } - - public abstract Material getType(); - - public abstract int getAmount(); - - public abstract void setAmount(int value); - - public abstract short getDurability(); - - public abstract int getMaxStackSize(); - - public abstract boolean isAir(); - - public abstract void addEnchantment(Enchantment enchantment, int level); - - @Override - public ItemStack clone() - { - return factory.clone(this); - } -} diff --git a/Essentials/src/com/earth2me/essentials/api/server/Location.java b/Essentials/src/com/earth2me/essentials/api/server/Location.java deleted file mode 100644 index 39cc71ca5..000000000 --- a/Essentials/src/com/earth2me/essentials/api/server/Location.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.earth2me.essentials.api.server; - - -public abstract class Location -{ - public interface LocationFactory { - Location create(String worldName, double x, double y, double z, double yaw, double pitch); - Location create(World world, double x, double y, double z, double yaw, double pitch); - } - private static LocationFactory factory; - - public static void setFactory(final LocationFactory factory) { - Location.factory = factory; - } - - public static Location create(String worldName, double x, double y, double z) { - return factory.create(worldName, x, y, z, 0, 0); - } - - public static Location create(String worldName, double x, double y, double z, double yaw, double pitch) { - return factory.create(worldName, x, y, z, yaw, pitch); - } - - public static Location create(World world, double x, double y, double z) { - return factory.create(world, x, y, z, 0, 0); - } - - public static Location create(World world, double x, double y, double z, double yaw, double pitch) { - return factory.create(world, x, y, z, yaw, pitch); - } - - - public abstract double getX(); - - public abstract double getY(); - - public abstract double getZ(); - - public abstract float getYaw(); - - public abstract float getPitch(); - - public abstract int getBlockX(); - - public abstract int getBlockY(); - - public abstract int getBlockZ(); - - public abstract World getWorld(); - - public abstract double distanceSquared(Location location); -} diff --git a/Essentials/src/com/earth2me/essentials/api/server/Material.java b/Essentials/src/com/earth2me/essentials/api/server/Material.java deleted file mode 100644 index d8486ef6d..000000000 --- a/Essentials/src/com/earth2me/essentials/api/server/Material.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.earth2me.essentials.api.server; - -public abstract class Material { - - private static Material instance; - - public static void setInstance(final Material instance) { - Material.instance = instance; - } - - public static Material get(final int id) { - return instance.getMaterialById(id); - } - - public static Material get(final String name) { - return instance.getMaterialByName(name); - } - - public static Material match(String string) - { - return instance.matchMaterial(string); - } - - protected abstract Material getMaterialByName(String name); - - protected abstract Material getMaterialById(int id); - - public abstract int getId(); - - public abstract String getName(); - - public abstract int getMaxStackSize(); - - public abstract int getMaxDurability(); - - protected abstract Material matchMaterial(String string); -} diff --git a/Essentials/src/com/earth2me/essentials/api/server/Permission.java b/Essentials/src/com/earth2me/essentials/api/server/Permission.java deleted file mode 100644 index 71b045d53..000000000 --- a/Essentials/src/com/earth2me/essentials/api/server/Permission.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.earth2me.essentials.api.server; - - -public abstract class Permission -{ - public enum Default - { - TRUE, FALSE, OP, NOT_OP; - } - - - public interface PermissionFactory - { - Permission create(String name, Permission.Default defaultPermission); - } - private static PermissionFactory factory; - - public static void setFactory(final PermissionFactory factory) - { - Permission.factory = factory; - } - - public static Permission create(final String name, Permission.Default defaultPermission) - { - return factory.create(name, defaultPermission); - } -} diff --git a/Essentials/src/com/earth2me/essentials/api/server/Player.java b/Essentials/src/com/earth2me/essentials/api/server/Player.java deleted file mode 100644 index 7da3b80fc..000000000 --- a/Essentials/src/com/earth2me/essentials/api/server/Player.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.earth2me.essentials.api.server; - -import com.earth2me.essentials.api.IUser; - - -public interface Player extends CommandSender -{ - IUser getUser(); - - String getName(); - - String getDisplayName(); - - boolean isOnline(); - - void setBanned(boolean bool); - - void kickPlayer(String reason); - - World getWorld(); - - Location getLocation(); - - Location getEyeLocation(); - - void setFireTicks(int value); - - void setFoodLevel(int value); - - void setSaturation(float value); - - int getHealth(); - - void setHealth(int value); - - void updateInventory(); - - ItemStack getItemInHand(); - - Location getBedSpawnLocation(); - - boolean hasPlayedBefore(); - - IInventory getInventory(); - - void setTotalExperience(final int exp); - - int getTotalExperience(); - - void setDisplayName(String name); - - void setPlayerListName(String name); - - void setSleepingIgnored(boolean b); - - boolean isBanned(); - - void setCompassTarget(Location loc); - - void damage(int value); -} diff --git a/Essentials/src/com/earth2me/essentials/api/server/World.java b/Essentials/src/com/earth2me/essentials/api/server/World.java deleted file mode 100644 index ca3bb04c5..000000000 --- a/Essentials/src/com/earth2me/essentials/api/server/World.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.earth2me.essentials.api.server; - -import java.util.UUID; -import org.bukkit.TreeType; - -public interface World { - String getName(); - - boolean generateTree(Location safeLocation, TreeType tree); - - int getHighestBlockYAt(int topX, int topZ); - - ItemStack dropItem(Location loc, ItemStack stack); - - UUID getUID(); - - Location getSpawnLocation(); - - void dropItemNaturally(Location location, ItemStack overflowStack); - - void setStorm(boolean b); - - void setWeatherDuration(int i); - - long getTime(); -} diff --git a/Essentials/src/com/earth2me/essentials/backup/Backup.java b/Essentials/src/com/earth2me/essentials/backup/Backup.java deleted file mode 100644 index 68eca4566..000000000 --- a/Essentials/src/com/earth2me/essentials/backup/Backup.java +++ /dev/null @@ -1,150 +0,0 @@ -package com.earth2me.essentials.backup; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IBackup; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.api.server.IServer; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.logging.Level; -import lombok.Cleanup; - - -public class Backup implements Runnable, IBackup -{ - private transient final IServer server; - private transient final IEssentials ess; - private transient final AtomicBoolean running = new AtomicBoolean(false); - private transient int taskId = -1; - private transient final AtomicBoolean active = new AtomicBoolean(false); - - public Backup(final IEssentials ess) - { - this.ess = ess; - server = ess.getServer(); - if (!server.getOnlinePlayers().isEmpty()) - { - startTask(); - } - } - - @Override - public final void startTask() - { - if (running.compareAndSet(false, true)) - { - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - final long interval = settings.getData().getGeneral().getBackup().getInterval() * 1200; // minutes -> ticks - if (interval < 1200) - { - running.set(false); - return; - } - taskId = ess.getPlugin().scheduleSyncRepeatingTask(this, interval, interval); - } - } - - @Override - public void run() - { - if (!active.compareAndSet(false, true)) - { - return; - } - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - final String command = settings.getData().getGeneral().getBackup().getCommand(); - if (command == null || command.isEmpty()) - { - return; - } - ess.getLogger().log(Level.INFO, _("backupStarted")); - final CommandSender consoleSender = server.getConsoleSender(); - server.dispatchCommand(consoleSender, "save-all"); - server.dispatchCommand(consoleSender, "save-off"); - - ess.getPlugin().scheduleAsyncDelayedTask(new BackupRunner(command)); - } - - - private class BackupRunner implements Runnable - { - private final transient String command; - - public BackupRunner(final String command) - { - this.command = command; - } - - @Override - public void run() - { - try - { - final ProcessBuilder childBuilder = new ProcessBuilder(command); - childBuilder.redirectErrorStream(true); - childBuilder.directory(ess.getPlugin().getRootFolder()); - final Process child = childBuilder.start(); - final BufferedReader reader = new BufferedReader(new InputStreamReader(child.getInputStream())); - try - { - child.waitFor(); - String line; - do - { - line = reader.readLine(); - if (line != null) - { - ess.getLogger().log(Level.INFO, line); - } - } - while (line != null); - } - finally - { - reader.close(); - } - } - catch (InterruptedException ex) - { - ess.getLogger().log(Level.SEVERE, null, ex); - } - catch (IOException ex) - { - ess.getLogger().log(Level.SEVERE, null, ex); - } - finally - { - ess.getPlugin().scheduleSyncDelayedTask(new EnableSavingRunner()); - } - } - } - - - private class EnableSavingRunner implements Runnable - { - @Override - public void run() - { - server.dispatchCommand(server.getConsoleSender(), "save-on"); - if (server.getOnlinePlayers().isEmpty()) - { - running.set(false); - if (taskId != -1) - { - ess.getPlugin().cancelTask(taskId); - } - } - - active.set(false); - ess.getLogger().log(Level.INFO, _("backupFinished")); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/bukkit/BukkitCommandSender.java b/Essentials/src/com/earth2me/essentials/bukkit/BukkitCommandSender.java deleted file mode 100644 index 70e209691..000000000 --- a/Essentials/src/com/earth2me/essentials/bukkit/BukkitCommandSender.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.earth2me.essentials.bukkit; - -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.api.server.Permission; -import lombok.Delegate; -import lombok.Getter; - - -public class BukkitCommandSender implements CommandSender -{ - @Delegate - @Getter - private org.bukkit.command.CommandSender commandSender; - - public BukkitCommandSender(org.bukkit.command.CommandSender commandSender) - { - this.commandSender = commandSender; - } - - @Override - public boolean isPlayer() - { - return false; - } - - @Override - public boolean isOp() - { - return commandSender.isOp(); - } - - public boolean hasPermission(Permission permission) - { - if (commandSender == null) { - return false; - } else { - return commandSender.hasPermission(((BukkitPermission)permission).getBukkitPermission()); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/bukkit/BukkitItemStack.java b/Essentials/src/com/earth2me/essentials/bukkit/BukkitItemStack.java deleted file mode 100644 index 4e8f18185..000000000 --- a/Essentials/src/com/earth2me/essentials/bukkit/BukkitItemStack.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.earth2me.essentials.bukkit; - -import com.earth2me.essentials.api.server.Enchantment; -import com.earth2me.essentials.api.server.ItemStack; -import com.earth2me.essentials.api.server.Material; -import lombok.Delegate; -import lombok.Getter; - - -public class BukkitItemStack extends com.earth2me.essentials.api.server.ItemStack -{ - public static class BukkitItemStackFactory implements ItemStackFactory - { - @Override - public ItemStack create(int id, int amount, int data) - { - return new BukkitItemStack(new org.bukkit.inventory.ItemStack(id, amount, (short)data)); - } - - @Override - public ItemStack clone(final ItemStack stack) - { - return new BukkitItemStack(((BukkitItemStack)stack).getItemStack().clone()); - } - } - - - private interface Excludes - { - org.bukkit.Material getType(); - } - @Delegate(excludes = - { - Excludes.class - }) - @Getter - private final org.bukkit.inventory.ItemStack itemStack; - - public BukkitItemStack(final org.bukkit.inventory.ItemStack itemStack) - { - super(); - this.itemStack = itemStack; - } - - @Override - public void addEnchantment(Enchantment enchantment, int level) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Material getType() - { - return Material.get(itemStack.getTypeId()); - } - - @Override - public boolean isAir() - { - return itemStack.getTypeId() == 0; - } -} diff --git a/Essentials/src/com/earth2me/essentials/bukkit/BukkitLocation.java b/Essentials/src/com/earth2me/essentials/bukkit/BukkitLocation.java deleted file mode 100644 index c948bb442..000000000 --- a/Essentials/src/com/earth2me/essentials/bukkit/BukkitLocation.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.earth2me.essentials.bukkit; - -import com.earth2me.essentials.api.server.World; -import com.earth2me.essentials.api.server.Location; -import lombok.Delegate; -import lombok.Getter; - - -public class BukkitLocation extends Location -{ - public static class BukkitLocationFactory implements LocationFactory - { - private final org.bukkit.Server server; - - public BukkitLocationFactory(org.bukkit.Server server) - { - this.server = server; - } - - @Override - public Location create(String worldName, double x, double y, double z, double yaw, double pitch) - { - org.bukkit.World world = server.getWorld(worldName); - return new BukkitLocation(new org.bukkit.Location(world, x, y, z, (float)yaw, (float)pitch)); - } - - @Override - public Location create(World world, double x, double y, double z, double yaw, double pitch) - { - return new BukkitLocation(new org.bukkit.Location(((BukkitWorld)world).getBukkitWorld(), x, y, z, (float)yaw, (float)pitch)); - } - } - - - private interface Excludes - { - org.bukkit.World getWorld(); - } - @Delegate(excludes = - { - Excludes.class - }) - @Getter - private final org.bukkit.Location bukkitLocation; - - public BukkitLocation(org.bukkit.Location bukkitLocation) - { - this.bukkitLocation = bukkitLocation; - } - - @Override - public World getWorld() - { - return new BukkitWorld(bukkitLocation.getWorld()); - } - - @Override - public double distanceSquared(final Location location) - { - return bukkitLocation.distanceSquared(((BukkitLocation)location).getBukkitLocation()); - } - -} diff --git a/Essentials/src/com/earth2me/essentials/bukkit/BukkitMaterial.java b/Essentials/src/com/earth2me/essentials/bukkit/BukkitMaterial.java deleted file mode 100644 index 84e485642..000000000 --- a/Essentials/src/com/earth2me/essentials/bukkit/BukkitMaterial.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.earth2me.essentials.bukkit; - -import com.earth2me.essentials.api.server.Material; -import java.util.EnumMap; -import lombok.Delegate; - - -public class BukkitMaterial extends Material -{ - private static EnumMap materials = new EnumMap(org.bukkit.Material.class); - - static - { - for (org.bukkit.Material material : org.bukkit.Material.values()) - { - materials.put(material, new BukkitMaterial(material)); - } - } - private interface Excludes { - short getMaxDurability(); - } - @Delegate(excludes={Excludes.class}) - private final org.bukkit.Material material; - - private BukkitMaterial(final org.bukkit.Material material) - { - this.material = material; - } - - @Override - protected Material getMaterialByName(final String name) - { - final org.bukkit.Material mat = org.bukkit.Material.getMaterial(name); - return materials.get(mat); - } - - @Override - protected Material getMaterialById(final int id) - { - final org.bukkit.Material mat = org.bukkit.Material.getMaterial(id); - return materials.get(mat); - } - - @Override - protected Material matchMaterial(String string) - { - final org.bukkit.Material mat = org.bukkit.Material.matchMaterial(string); - return materials.get(mat); - } - - @Override - public String getName() - { - return this.material.toString(); - } - - @Override - public int getMaxDurability() - { - return (short)this.material.getMaxDurability(); - } -} diff --git a/Essentials/src/com/earth2me/essentials/bukkit/BukkitPermission.java b/Essentials/src/com/earth2me/essentials/bukkit/BukkitPermission.java deleted file mode 100644 index b1cbbe7ca..000000000 --- a/Essentials/src/com/earth2me/essentials/bukkit/BukkitPermission.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.earth2me.essentials.bukkit; - -import com.earth2me.essentials.api.server.Permission; -import java.util.regex.Pattern; -import lombok.Delegate; -import lombok.Getter; -import org.bukkit.Bukkit; -import org.bukkit.permissions.PermissionDefault; -import org.bukkit.plugin.PluginManager; - - -public class BukkitPermission extends Permission -{ - public static class BukkitPermissionFactory implements PermissionFactory - { - private static transient final Pattern DOT_PATTERN = Pattern.compile("\\."); - - @Override - public Permission create(String permission, Permission.Default defaultPerm) - { - final PluginManager pluginManager = Bukkit.getServer().getPluginManager(); - final String[] parts = DOT_PATTERN.split(permission); - final StringBuilder builder = new StringBuilder(permission.length()); - org.bukkit.permissions.Permission parent = null; - for (int i = 0; i < parts.length - 1; i++) - { - builder.append(parts[i]).append(".*"); - String permString = builder.toString(); - org.bukkit.permissions.Permission perm = pluginManager.getPermission(permString); - if (perm == null) - { - perm = new org.bukkit.permissions.Permission(permString, PermissionDefault.FALSE); - pluginManager.addPermission(perm); - if (parent != null) - { - parent.getChildren().put(perm.getName(), Boolean.TRUE); - } - parent = perm; - } - builder.deleteCharAt(builder.length() - 1); - } - org.bukkit.permissions.Permission perm = pluginManager.getPermission(permission); - if (perm == null) - { - perm = new org.bukkit.permissions.Permission(permission, getBukkitDefaultPermission(defaultPerm)); - pluginManager.addPermission(perm); - if (parent != null) - { - parent.getChildren().put(perm.getName(), Boolean.TRUE); - } - parent = perm; - } - perm.recalculatePermissibles(); - return new BukkitPermission(perm); - } - } - @Delegate - @Getter - private final org.bukkit.permissions.Permission bukkitPermission; - - public BukkitPermission(org.bukkit.permissions.Permission bukkitPermission) - { - this.bukkitPermission = bukkitPermission; - } - - public static PermissionDefault getBukkitDefaultPermission(final Permission.Default defaultPerm) - { - switch (defaultPerm) - { - case TRUE: - return PermissionDefault.TRUE; - case OP: - return PermissionDefault.OP; - case NOT_OP: - return PermissionDefault.NOT_OP; - case FALSE: - return PermissionDefault.FALSE; - default: - return PermissionDefault.FALSE; - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/bukkit/BukkitPlayer.java b/Essentials/src/com/earth2me/essentials/bukkit/BukkitPlayer.java deleted file mode 100644 index 5ca9d1da0..000000000 --- a/Essentials/src/com/earth2me/essentials/bukkit/BukkitPlayer.java +++ /dev/null @@ -1,202 +0,0 @@ -package com.earth2me.essentials.bukkit; - -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.*; -import lombok.Delegate; -import lombok.Getter; -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.LivingEntity; - - -public class BukkitPlayer extends BukkitCommandSender implements Player -{ - private interface Excludes - { - org.bukkit.World getWorld(); - - org.bukkit.Location getLocation(); - - org.bukkit.Location getEyeLocation(); - - org.bukkit.inventory.ItemStack getItemInHand(); - - org.bukkit.Location getBedSpawnLocation(); - - org.bukkit.inventory.Inventory getInventory(); - - void setTotalExperience(int i); - - int getTotalExperience(); - } - @Delegate(types = - { - org.bukkit.entity.Player.class, LivingEntity.class - }, excludes = - { - OfflinePlayer.class, org.bukkit.command.CommandSender.class, Excludes.class - }) - @Getter - private transient org.bukkit.entity.Player onlinePlayer; - /** - * a set of data and methods common to both offline and online players. - */ - @Delegate(excludes = - { - Excludes.class - }) - @Getter - private transient OfflinePlayer safePlayer; - private final transient IServer server; - - public BukkitPlayer(final OfflinePlayer player, final IServer server) - { - super(player.getPlayer()); - this.server = server; - if (player.isOnline()) - { - - setOnlinePlayer(player.getPlayer()); - } - else - { - setOfflinePlayer(player); - } - } - - public final void setOfflinePlayer(final OfflinePlayer offlinePlayer) - { - safePlayer = offlinePlayer; - onlinePlayer = null; - } - - public final void setOnlinePlayer(final org.bukkit.entity.Player onlinePlayer) - { - safePlayer = this.onlinePlayer = onlinePlayer; - } - - public String getSafeDisplayName() - { - return onlinePlayer == null ? getName() : getDisplayName(); - } - - @Override - public IUser getUser() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isPlayer() - { - return true; - } - - @Override - public World getWorld() - { - return server.getWorld(onlinePlayer.getWorld().getName()); - } - - @Override - public Location getLocation() - { - return new BukkitLocation(onlinePlayer.getLocation()); - } - - @Override - public Location getEyeLocation() - { - return new BukkitLocation(onlinePlayer.getEyeLocation()); - } - - @Override - public BukkitItemStack getItemInHand() - { - return new BukkitItemStack(onlinePlayer.getItemInHand()); - } - - @Override - public Location getBedSpawnLocation() - { - return new BukkitLocation(onlinePlayer.getBedSpawnLocation()); - } - - @Override - public IInventory getInventory() - { - return new Inventory(onlinePlayer.getInventory()); - } - - @Override - public void setTotalExperience(final int exp) - { - if (exp < 0) - { - throw new IllegalArgumentException("Experience is negative!"); - } - onlinePlayer.setExp(0); - onlinePlayer.setLevel(0); - onlinePlayer.setTotalExperience(0); - int amount = exp; - while (amount > 0) - { - final int expToLevel = getExpToLevel(); - amount -= expToLevel; - if (amount >= 0) - { - // give until next level - onlinePlayer.giveExp(expToLevel); - } - else - { - // give the rest - amount += expToLevel; - onlinePlayer.giveExp(amount); - amount = 0; - } - } - } - - private int getExpToLevel() - { - return getExpToLevel(onlinePlayer.getLevel()); - } - - private static int getExpToLevel(final int level) - { - return 7 + (level * 7 >> 1); - } - - @Override - public int getTotalExperience() - { - int exp = (int) (getExpToLevel() * onlinePlayer.getExp()); - int currentLevel = onlinePlayer.getLevel(); - - while (currentLevel > 0) { - currentLevel--; - exp += getExpToLevel(currentLevel); - } - return exp; - } - - - @Override - public void sendMessage(final String message) - { - onlinePlayer.sendMessage(message); - } - - @Override - public void sendMessage(final String[] string) - { - onlinePlayer.sendMessage(string); - } - - - @Override - public void setCompassTarget(final Location loc) - { - onlinePlayer.setCompassTarget(((BukkitLocation)loc).getBukkitLocation()); - } -} diff --git a/Essentials/src/com/earth2me/essentials/bukkit/BukkitWorld.java b/Essentials/src/com/earth2me/essentials/bukkit/BukkitWorld.java deleted file mode 100644 index 883be669a..000000000 --- a/Essentials/src/com/earth2me/essentials/bukkit/BukkitWorld.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.earth2me.essentials.bukkit; - -import com.earth2me.essentials.api.server.World; -import com.earth2me.essentials.api.server.ItemStack; -import com.earth2me.essentials.api.server.Location; -import lombok.Delegate; -import lombok.Getter; -import org.bukkit.TreeType; - -public class BukkitWorld implements World { - @Delegate - @Getter - private final org.bukkit.World bukkitWorld; - - public BukkitWorld(final org.bukkit.World world) - { - this.bukkitWorld = world; - world.getT - } - - @Override - public boolean generateTree(Location safeLocation, TreeType tree) - { - return bukkitWorld.generateTree(((BukkitLocation)safeLocation).getBukkitLocation(), tree); - } - - @Override - public ItemStack dropItem(Location loc, ItemStack stack) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Location getSpawnLocation() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void dropItemNaturally(Location location, ItemStack overflowStack) - { - throw new UnsupportedOperationException("Not supported yet."); - } - -} diff --git a/Essentials/src/com/earth2me/essentials/bukkit/Enchantments.java b/Essentials/src/com/earth2me/essentials/bukkit/Enchantments.java deleted file mode 100644 index 21c763a30..000000000 --- a/Essentials/src/com/earth2me/essentials/bukkit/Enchantments.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.earth2me.essentials.bukkit; - -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.regex.Pattern; -import org.bukkit.enchantments.Enchantment; - - -public final class Enchantments -{ - - private Enchantments() - { - } - - private static final transient Pattern NUMPATTERN = Pattern.compile("\\d+"); - private static final Map ENCHANTMENTS = new HashMap(); - - static - { - ENCHANTMENTS.put("alldamage", Enchantment.DAMAGE_ALL); - ENCHANTMENTS.put("alldmg", Enchantment.DAMAGE_ALL); - ENCHANTMENTS.put("sharpness", Enchantment.DAMAGE_ALL); - ENCHANTMENTS.put("arthropodsdamage", Enchantment.DAMAGE_ARTHROPODS); - ENCHANTMENTS.put("ardmg", Enchantment.DAMAGE_ARTHROPODS); - ENCHANTMENTS.put("baneofarthropods", Enchantment.DAMAGE_ARTHROPODS); - ENCHANTMENTS.put("undeaddamage", Enchantment.DAMAGE_UNDEAD); - ENCHANTMENTS.put("smite", Enchantment.DAMAGE_UNDEAD); - ENCHANTMENTS.put("digspeed", Enchantment.DIG_SPEED); - ENCHANTMENTS.put("efficiency", Enchantment.DIG_SPEED); - ENCHANTMENTS.put("durability", Enchantment.DURABILITY); - ENCHANTMENTS.put("dura", Enchantment.DURABILITY); - ENCHANTMENTS.put("unbreaking", Enchantment.DURABILITY); - ENCHANTMENTS.put("fireaspect", Enchantment.FIRE_ASPECT); - ENCHANTMENTS.put("fire", Enchantment.FIRE_ASPECT); - ENCHANTMENTS.put("knockback", Enchantment.KNOCKBACK); - ENCHANTMENTS.put("blockslootbonus", Enchantment.LOOT_BONUS_BLOCKS); - ENCHANTMENTS.put("fortune", Enchantment.LOOT_BONUS_BLOCKS); - ENCHANTMENTS.put("mobslootbonus", Enchantment.LOOT_BONUS_MOBS); - ENCHANTMENTS.put("mobloot", Enchantment.LOOT_BONUS_MOBS); - ENCHANTMENTS.put("looting", Enchantment.LOOT_BONUS_MOBS); - ENCHANTMENTS.put("oxygen", Enchantment.OXYGEN); - ENCHANTMENTS.put("respiration", Enchantment.OXYGEN); - ENCHANTMENTS.put("protection", Enchantment.PROTECTION_ENVIRONMENTAL); - ENCHANTMENTS.put("prot", Enchantment.PROTECTION_ENVIRONMENTAL); - ENCHANTMENTS.put("explosionsprotection", Enchantment.PROTECTION_EXPLOSIONS); - ENCHANTMENTS.put("expprot", Enchantment.PROTECTION_EXPLOSIONS); - ENCHANTMENTS.put("blastprotection", Enchantment.PROTECTION_EXPLOSIONS); - ENCHANTMENTS.put("fallprotection", Enchantment.PROTECTION_FALL); - ENCHANTMENTS.put("fallprot", Enchantment.PROTECTION_FALL); - ENCHANTMENTS.put("featherfalling", Enchantment.PROTECTION_FALL); - ENCHANTMENTS.put("fireprotection", Enchantment.PROTECTION_FIRE); - ENCHANTMENTS.put("fireprot", Enchantment.PROTECTION_FIRE); - ENCHANTMENTS.put("projectileprotection", Enchantment.PROTECTION_PROJECTILE); - ENCHANTMENTS.put("projprot", Enchantment.PROTECTION_PROJECTILE); - ENCHANTMENTS.put("silktouch", Enchantment.SILK_TOUCH); - ENCHANTMENTS.put("waterworker", Enchantment.WATER_WORKER); - ENCHANTMENTS.put("aquaaffinity", Enchantment.WATER_WORKER); - ENCHANTMENTS.put("firearrow", Enchantment.ARROW_FIRE); - ENCHANTMENTS.put("arrowdamage", Enchantment.ARROW_DAMAGE); - ENCHANTMENTS.put("arrowknockback", Enchantment.ARROW_KNOCKBACK); - ENCHANTMENTS.put("arrowkb", Enchantment.ARROW_KNOCKBACK); - ENCHANTMENTS.put("infinitearrows", Enchantment.ARROW_INFINITE); - ENCHANTMENTS.put("infarrows", Enchantment.ARROW_INFINITE); - } - - public static Enchantment getByName(final String name) { - Enchantment enchantment; - if (NUMPATTERN.matcher(name).matches()) { - enchantment = Enchantment.getById(Integer.parseInt(name)); - } else { - enchantment = Enchantment.getByName(name.toUpperCase(Locale.ENGLISH)); - } - if (enchantment == null) - { - enchantment = ENCHANTMENTS.get(name.toLowerCase(Locale.ENGLISH)); - } - return enchantment; - } - - public static Set> entrySet() - { - return ENCHANTMENTS.entrySet(); - } -} diff --git a/Essentials/src/com/earth2me/essentials/bukkit/EssentialsPlugin.java b/Essentials/src/com/earth2me/essentials/bukkit/EssentialsPlugin.java deleted file mode 100644 index 7e3dde434..000000000 --- a/Essentials/src/com/earth2me/essentials/bukkit/EssentialsPlugin.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.earth2me.essentials.bukkit; - -import com.earth2me.essentials.Essentials; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.server.*; -import java.util.logging.Level; -import org.bukkit.command.Command; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.java.JavaPlugin; - - -public class EssentialsPlugin extends JavaPlugin -{ - private transient Essentials ess; - - public EssentialsPlugin() - { - Material.setInstance(BukkitMaterial.get(0)); - ItemStack.setFactory(new BukkitItemStack.BukkitItemStackFactory()); - Location.setFactory(new BukkitLocation.BukkitLocationFactory(getServer())); - Permission.setFactory(new BukkitPermission.BukkitPermissionFactory()); - } - - @Override - public void onEnable() - { - - Server server = new Server(getServer()); - final PluginManager pm = this.getServer().getPluginManager(); - pm.registerEvents(server, this); - ess = new Essentials(server, getLogger(), new Plugin(this)); - if (VersionCheck.checkVersion(this)) - { - try - { - ess.onEnable(); - } - catch (RuntimeException ex) - { - if (pm.getPlugin("EssentialsUpdate") == null) - { - getLogger().log(Level.SEVERE, _("essentialsHelp1")); - } - else - { - getLogger().log(Level.SEVERE, _("essentialsHelp2")); - } - getLogger().log(Level.SEVERE, ex.toString()); - pm.registerEvents(new Listener() - { - @EventHandler(priority = EventPriority.LOW) - public void onPlayerJoin(final PlayerJoinEvent event) - { - event.getPlayer().sendMessage("Essentials failed to load, read the log file."); - } - }, this); - for (Player player : getServer().getOnlinePlayers()) - { - player.sendMessage("Essentials failed to load, read the log file."); - } - this.setEnabled(false); - } - } - else - { - this.setEnabled(false); - } - } - - @Override - public void onDisable() - { - if (ess != null) - { - ess.onDisable(); - } - } - - @Override - public boolean onCommand(final org.bukkit.command.CommandSender sender, final Command command, final String label, final String[] args) - { - CommandSender commandSender; - if (sender instanceof org.bukkit.entity.Player) { - commandSender = ((Server)ess.getServer()).getPlayer((org.bukkit.entity.Player)sender); - } else { - commandSender = new BukkitCommandSender(sender); - } - return ess.getCommandHandler().handleCommand(commandSender, command, label, args); - } -} diff --git a/Essentials/src/com/earth2me/essentials/bukkit/Inventory.java b/Essentials/src/com/earth2me/essentials/bukkit/Inventory.java deleted file mode 100644 index fc33ea619..000000000 --- a/Essentials/src/com/earth2me/essentials/bukkit/Inventory.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.earth2me.essentials.bukkit; - -import com.earth2me.essentials.api.server.IInventory; -import com.earth2me.essentials.api.server.ItemStack; -import java.util.Map; -import lombok.Delegate; -import org.bukkit.inventory.PlayerInventory; - -public class Inventory implements IInventory { - @Delegate - private org.bukkit.inventory.PlayerInventory inventory; - - Inventory(PlayerInventory inventory) - { - this.inventory = inventory; - } - - @Override - public boolean containsItem(boolean b, boolean b0, ItemStack itemStack) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Map addItem(boolean b, ItemStack itemStack) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean addAllItems(boolean b, ItemStack itemStack) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void removeItem(boolean b, boolean b0, ItemStack itemStack) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Map addItem(boolean b, int oversizedStacksize, ItemStack itemStack) - { - throw new UnsupportedOperationException("Not supported yet."); - } - -} diff --git a/Essentials/src/com/earth2me/essentials/bukkit/Mob.java b/Essentials/src/com/earth2me/essentials/bukkit/Mob.java deleted file mode 100644 index 3d78b2a82..000000000 --- a/Essentials/src/com/earth2me/essentials/bukkit/Mob.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.earth2me.essentials.bukkit; - -import static com.earth2me.essentials.I18n._; -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 org.bukkit.Location; -import org.bukkit.Server; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; - - -public enum Mob -{ - CHICKEN("Chicken", Enemies.FRIENDLY, EntityType.CHICKEN), - COW("Cow", Enemies.FRIENDLY, EntityType.COW), - CREEPER("Creeper", Enemies.ENEMY, EntityType.CREEPER), - GHAST("Ghast", Enemies.ENEMY, EntityType.GHAST), - GIANT("Giant", Enemies.ENEMY, EntityType.GIANT), - PIG("Pig", Enemies.FRIENDLY, EntityType.PIG), - PIGZOMB("PigZombie", Enemies.NEUTRAL, EntityType.PIG_ZOMBIE), - SHEEP("Sheep", Enemies.FRIENDLY, "", EntityType.SHEEP), - SKELETON("Skeleton", Enemies.ENEMY, EntityType.SKELETON), - SLIME("Slime", Enemies.ENEMY, EntityType.SLIME), - SPIDER("Spider", Enemies.ENEMY, EntityType.SPIDER), - SQUID("Squid", Enemies.FRIENDLY, EntityType.SQUID), - ZOMBIE("Zombie", Enemies.ENEMY, EntityType.ZOMBIE), - WOLF("Wolf", Enemies.NEUTRAL, EntityType.WOLF), - CAVESPIDER("CaveSpider", Enemies.ENEMY, EntityType.CAVE_SPIDER), - ENDERMAN("Enderman", Enemies.ENEMY, "", EntityType.ENDERMAN), - SILVERFISH("Silverfish", Enemies.ENEMY, "", EntityType.SILVERFISH), - ENDERDRAGON("EnderDragon", Enemies.ENEMY, EntityType.ENDER_DRAGON), - VILLAGER("Villager", Enemies.FRIENDLY, EntityType.VILLAGER), - BLAZE("Blaze", Enemies.ENEMY, EntityType.BLAZE), - MUSHROOMCOW("MushroomCow", Enemies.FRIENDLY, EntityType.MUSHROOM_COW), - MAGMACUBE("MagmaCube", Enemies.ENEMY, EntityType.MAGMA_CUBE), - SNOWMAN("Snowman", Enemies.FRIENDLY, "", EntityType.SNOWMAN), - OCELOT("Ocelot", Enemies.NEUTRAL, EntityType.OCELOT), - IRONGOLEM("IronGolem", Enemies.NEUTRAL, EntityType.IRON_GOLEM); - - public static final Logger logger = Logger.getLogger("Minecraft"); - - private Mob(String n, Enemies en, String s, EntityType type) - { - this.suffix = s; - this.name = n; - this.type = en; - this.bukkitType = type; - } - - private Mob(String n, Enemies en, EntityType type) - { - this.name = n; - this.type = en; - this.bukkitType = type; - } - public String suffix = "s"; - final public String name; - final public Enemies type; - final private EntityType bukkitType; - private static final Map hashMap = new HashMap(); - - static - { - for (Mob mob : Mob.values()) - { - hashMap.put(mob.name.toLowerCase(Locale.ENGLISH), mob); - } - } - - public static Set getMobList() { - return Collections.unmodifiableSet(hashMap.keySet()); - } - - public LivingEntity spawn(final Player player, final Server server, final Location loc) throws MobException - { - final LivingEntity entity = player.getWorld().spawn(loc, (Class)this.bukkitType.getEntityClass()); - if (entity == null) - { - logger.log(Level.WARNING, _("unableToSpawnMob")); - throw new MobException(); - } - return entity; - } - - - public enum Enemies - { - FRIENDLY("friendly"), - NEUTRAL("neutral"), - ENEMY("enemy"); - - private 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 class MobException extends Exception - { - private static final long serialVersionUID = 1L; - } -} diff --git a/Essentials/src/com/earth2me/essentials/bukkit/Plugin.java b/Essentials/src/com/earth2me/essentials/bukkit/Plugin.java deleted file mode 100644 index 3dbb452b6..000000000 --- a/Essentials/src/com/earth2me/essentials/bukkit/Plugin.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.earth2me.essentials.bukkit; - -import com.earth2me.essentials.api.server.Player; -import com.earth2me.essentials.api.server.IPlugin; -import com.earth2me.essentials.api.server.Location; -import java.io.File; -import lombok.Delegate; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.player.PlayerRespawnEvent; -import org.bukkit.plugin.java.JavaPluginLoader; - - -public class Plugin implements IPlugin -{ - @Delegate - private final org.bukkit.plugin.Plugin plugin; - - public Plugin(final org.bukkit.plugin.Plugin plugin) - { - this.plugin = plugin; - } - - @Override - public int scheduleAsyncDelayedTask(final Runnable run) - { - return plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, run); - } - - @Override - public int scheduleSyncDelayedTask(final Runnable run) - { - return plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, run); - } - - @Override - public int scheduleSyncDelayedTask(final Runnable run, final long delay) - { - return plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, run, delay); - } - - @Override - public int scheduleSyncRepeatingTask(final Runnable run, final long delay, final long period) - { - return plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, run, delay, period); - } - - @Override - public File getRootFolder() - { - return plugin.getDataFolder().getParentFile().getParentFile(); - } - - @Override - public void cancelTask(final int taskId) - { - plugin.getServer().getScheduler().cancelTask(taskId); - } - - @Override - public String getVersion() - { - return plugin.getDescription().getVersion(); - } - - @Override - public Class getClassByName(final String name) - { - final JavaPluginLoader jpl = (JavaPluginLoader)plugin.getPluginLoader(); - return jpl.getClassByName(name); - } - - @Override - public Location callRespawnEvent(Player player, Location loc, boolean bedSpawn) - { - final PlayerRespawnEvent pre = new PlayerRespawnEvent(((BukkitPlayer)player).getOnlinePlayer(), ((BukkitLocation)loc).getBukkitLocation() , bedSpawn); - getServer().getPluginManager().callEvent(pre); - return new BukkitLocation(pre.getRespawnLocation()); - } - - @Override - public void callSuicideEvent(Player player) - { - EntityDamageEvent ede = new EntityDamageEvent(((BukkitPlayer)player).getOnlinePlayer(), EntityDamageEvent.DamageCause.SUICIDE, 1000); - getServer().getPluginManager().callEvent(ede); - } - -} diff --git a/Essentials/src/com/earth2me/essentials/bukkit/Server.java b/Essentials/src/com/earth2me/essentials/bukkit/Server.java deleted file mode 100644 index b673b2dae..000000000 --- a/Essentials/src/com/earth2me/essentials/bukkit/Server.java +++ /dev/null @@ -1,126 +0,0 @@ -package com.earth2me.essentials.bukkit; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.api.server.Player; -import com.earth2me.essentials.api.server.IServer; -import com.earth2me.essentials.api.server.World; -import java.util.*; -import lombok.Delegate; -import lombok.Getter; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerLoginEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.event.world.WorldLoadEvent; -import org.bukkit.event.world.WorldUnloadEvent; -import org.bukkit.plugin.RegisteredServiceProvider; - - -public class Server implements IServer, Listener -{ - private IEssentials ess; - private interface Excludes - { - List getWorlds(); - - org.bukkit.World getWorld(String name); - - org.bukkit.entity.Player[] getOnlinePlayers(); - - BukkitCommandSender getConsoleSender(); - } - @Delegate(excludes = Excludes.class) - private final org.bukkit.Server server; - @Getter - private List worlds; - private Map worldsMap; - @Getter - private Collection onlinePlayers; - private Map onlinePlayersMap; - @Getter - private CommandSender consoleSender; - - public Server(final org.bukkit.Server server) - { - this.server = server; - consoleSender = new BukkitCommandSender(server.getConsoleSender()); - updateWorlds(); - } - - private void updateWorlds() - { - final ArrayList lworlds = new ArrayList(server.getWorlds().size()); - final HashMap lworldsMap = new HashMap(); - for (org.bukkit.World world : server.getWorlds()) - { - final BukkitWorld w = new BukkitWorld(world); - lworlds.add(w); - lworldsMap.put(world.getName(), w); - lworldsMap.put(world.getName().toLowerCase(Locale.ENGLISH), w); - } - this.worlds = Collections.unmodifiableList(lworlds); - this.worldsMap = Collections.unmodifiableMap(lworldsMap); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public synchronized void onWorldLoadEvent(final WorldLoadEvent event) - { - updateWorlds(); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public synchronized void onWorldUnloadEvent(final WorldUnloadEvent event) - { - updateWorlds(); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public synchronized void onPlayerLoginEvent(final PlayerLoginEvent event) - { - final HashMap oplayersMap = new HashMap(onlinePlayersMap); - BukkitPlayer p = new BukkitPlayer(event.getPlayer(), this); - oplayersMap.put(event.getPlayer(), p); - onlinePlayersMap = Collections.unmodifiableMap(oplayersMap); - onlinePlayers = Collections.unmodifiableCollection(oplayersMap.values()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public synchronized void onPlayerQuitEvent(final PlayerQuitEvent event) - { - final ArrayList oplayers = new ArrayList(onlinePlayers); - final HashMap oplayersMap = new HashMap(onlinePlayersMap); - oplayersMap.remove(event.getPlayer()); - onlinePlayersMap = Collections.unmodifiableMap(oplayersMap); - onlinePlayers = Collections.unmodifiableCollection(oplayersMap.values()); - } - - @Override - public World getWorld(final String name) - { - final World world = worldsMap.get(name); - if (world == null) - { - return worldsMap.get(name.toLowerCase(Locale.ENGLISH)); - } - return world; - } - - @Override - public void dispatchCommand(final CommandSender sender, final String command) - { - server.dispatchCommand(((BukkitCommandSender)sender).getCommandSender(), command); - } - - @Override - public T getServiceProvider(final Class clazz) - { - final RegisteredServiceProvider rsp = server.getServicesManager().getRegistration(clazz); - return rsp.getProvider(); - } - - public Player getPlayer(final org.bukkit.entity.Player player) { - return onlinePlayersMap.get(player); - } -} diff --git a/Essentials/src/com/earth2me/essentials/bukkit/VersionCheck.java b/Essentials/src/com/earth2me/essentials/bukkit/VersionCheck.java deleted file mode 100644 index 516514fa8..000000000 --- a/Essentials/src/com/earth2me/essentials/bukkit/VersionCheck.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.earth2me.essentials.bukkit; - -import static com.earth2me.essentials.I18n._; -import java.util.logging.Level; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import org.bukkit.plugin.PluginManager; - - -public class VersionCheck -{ - public static final int BUKKIT_VERSION = 2015; - private static final Pattern bukkitVersionPattern = Pattern.compile("git-Bukkit-(?:(?:[0-9]+)\\.)+[0-9]+-R[\\.0-9]+-(?:[0-9]+-g[0-9a-f]+-)?b([0-9]+)jnks.*"); - - public static boolean checkVersion(final org.bukkit.plugin.Plugin plugin) - { - final PluginManager pm = plugin.getServer().getPluginManager(); - final String pluginVersion = plugin.getDescription().getVersion(); - for (org.bukkit.plugin.Plugin p : pm.getPlugins()) - { - if (p.getDescription().getName().startsWith("Essentials") - && !p.getDescription().getVersion().equals(pluginVersion)) - { - p.getLogger().log(Level.WARNING, _("versionMismatch", p.getDescription().getName())); - } - } - final Matcher versionMatch = bukkitVersionPattern.matcher(plugin.getServer().getVersion()); - if (versionMatch.matches()) - { - final int versionNumber = Integer.parseInt(versionMatch.group(1)); - if (versionNumber < BUKKIT_VERSION && versionNumber > 100) - { - plugin.getLogger().log(Level.SEVERE, _("notRecommendedBukkit")); - plugin.getLogger().log(Level.SEVERE, _("requiredBukkit", Integer.toString(BUKKIT_VERSION))); - return false; - } - } - else - { - plugin.getLogger().log(Level.INFO, _("bukkitFormatChanged")); - plugin.getLogger().log(Level.INFO, plugin.getServer().getVersion()); - plugin.getLogger().log(Level.INFO, plugin.getServer().getBukkitVersion()); - } - return true; - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandafk.java b/Essentials/src/com/earth2me/essentials/commands/Commandafk.java deleted file mode 100644 index 1bda185b3..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandafk.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.Permissions; -import org.bukkit.entity.Player; -import org.bukkit.permissions.PermissionDefault; - - -public class Commandafk extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length > 0 && Permissions.AFK_OTHERS.isAuthorized(user)) - { - IUser afkUser = ess.getUser((Player)ess.getServer().matchPlayer(args[0])); - if (afkUser != null) - { - toggleAfk(afkUser); - } - } - else - { - toggleAfk(user); - } - } - - private void toggleAfk(IUser user) - { - if (!user.toggleAfk()) - { - //user.sendMessage(_("markedAsNotAway")); - if (!user.isHidden()) - { - ess.broadcastMessage(user, _("userIsNotAway", user.getDisplayName())); - } - user.updateActivity(false); - } - else - { - //user.sendMessage(_("markedAsAway")); - if (!user.isHidden()) - { - ess.broadcastMessage(user, _("userIsAway", user.getDisplayName())); - } - } - } - - @Override - public PermissionDefault getPermissionDefault() - { - return PermissionDefault.TRUE; - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandantioch.java b/Essentials/src/com/earth2me/essentials/commands/Commandantioch.java deleted file mode 100644 index eea30448d..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandantioch.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.utils.LocationUtil; -import org.bukkit.Location; -import org.bukkit.entity.TNTPrimed; - - -public class Commandantioch extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length > 0) - { - ess.broadcastMessage(user, "...lobbest thou thy Holy Hand Grenade of Antioch towards thy foe,"); - ess.broadcastMessage(user, "who being naughty in My sight, shall snuff it."); - } - - final Location loc = LocationUtil.getTarget(user); - loc.getWorld().spawn(loc, TNTPrimed.class); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandback.java b/Essentials/src/com/earth2me/essentials/commands/Commandback.java deleted file mode 100644 index a23b5409c..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandback.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.api.IUser; - - -public class Commandback extends EssentialsCommand -{ - @Override - protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - final Trade charge = new Trade(commandName, ess); - charge.isAffordableFor(user); - user.sendMessage(_("backUsageMsg")); - user.getTeleport().back(charge); - throw new NoChargeException(); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java b/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java deleted file mode 100644 index ab749f9ee..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IBackup; -import com.earth2me.essentials.api.server.CommandSender; -import org.bukkit.command.CommandSender; - - -public class Commandbackup extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - final IBackup backup = ess.getBackup(); - backup.run(); - sender.sendMessage(_("backupStarted")); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java b/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java deleted file mode 100644 index 957536832..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.permissions.Permissions; -import org.bukkit.command.CommandSender; - - -public class Commandbalance extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - sender.sendMessage(_("balance", Util.displayCurrency(getPlayer(args, 0, true).getMoney(), ess))); - } - - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - final double bal = (args.length < 1 - || !Permissions.BALANCE_OTHERS.isAuthorized(user) - ? user - : getPlayer(args, 0, true)).getMoney(); - user.sendMessage(_("balance", Util.displayCurrency(bal, ess))); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbalancetop.java b/Essentials/src/com/earth2me/essentials/commands/Commandbalancetop.java deleted file mode 100644 index 4f0f0b9b3..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbalancetop.java +++ /dev/null @@ -1,180 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.utils.textreader.ArrayListInput; -import com.earth2me.essentials.utils.textreader.TextPager; -import java.text.DateFormat; -import java.util.*; -import java.util.Map.Entry; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import org.bukkit.command.CommandSender; - - -public class Commandbalancetop extends EssentialsCommand -{ - private static final int CACHETIME = 2 * 60 * 1000; - public static final int MINUSERS = 50; - private static ArrayListInput cache = new ArrayListInput(); - private static long cacheage = 0; - private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); - - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - int page = 0; - boolean force = false; - if (args.length > 0) - { - try - { - page = Integer.parseInt(args[0]); - } - catch (NumberFormatException ex) - { - if (args[0].equalsIgnoreCase("force") && sender.isOp()) - { - force = true; - } - } - } - - if (!force && lock.readLock().tryLock()) - { - try - { - if (cacheage > System.currentTimeMillis() - CACHETIME) - { - outputCache(sender, page); - return; - } - if (ess.getUserMap().getUniqueUsers() > MINUSERS) - { - sender.sendMessage(_("orderBalances", ess.getUserMap().getUniqueUsers())); - } - } - finally - { - lock.readLock().unlock(); - } - ess.getPlugin().scheduleAsyncDelayedTask(new Viewer(sender, page, force)); - } - else - { - if (ess.getUserMap().getUniqueUsers() > MINUSERS) - { - sender.sendMessage(_("orderBalances", ess.getUserMap().getUniqueUsers())); - } - ess.getPlugin().scheduleAsyncDelayedTask(new Viewer(sender, page, force)); - } - - } - - private static void outputCache(final CommandSender sender, int page) - { - final Calendar cal = Calendar.getInstance(); - cal.setTimeInMillis(cacheage); - final DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); - sender.sendMessage(_("balanceTop", format.format(cal.getTime()))); - new TextPager(cache).showPage(Integer.toString(page), "", "balancetop", sender); - } - - - private class Calculator implements Runnable - { - private final transient Viewer viewer; - private final boolean force; - - public Calculator(final Viewer viewer, final boolean force) - { - this.viewer = viewer; - this.force = force; - } - - @Override - public void run() - { - lock.writeLock().lock(); - try - { - if (force || cacheage <= System.currentTimeMillis() - CACHETIME) - { - cache.getLines().clear(); - final Map balances = new HashMap(); - double totalMoney = 0d; - for (String u : ess.getUserMap().getAllUniqueUsers()) - { - final IUser user = ess.getUserMap().getUser(u); - if (user != null) - { - final double userMoney = user.getMoney(); - user.updateMoneyCache(userMoney); - totalMoney += userMoney; - balances.put(user.getDisplayName(), userMoney); - } - } - - final List> sortedEntries = new ArrayList>(balances.entrySet()); - Collections.sort(sortedEntries, new Comparator>() - { - @Override - public int compare(final Entry entry1, final Entry entry2) - { - return -entry1.getValue().compareTo(entry2.getValue()); - } - }); - - cache.getLines().add(_("serverTotal", Util.displayCurrency(totalMoney, ess))); - int pos = 1; - for (Map.Entry entry : sortedEntries) - { - cache.getLines().add(pos + ". " + entry.getKey() + ", " + Util.displayCurrency(entry.getValue(), ess)); - pos++; - } - cacheage = System.currentTimeMillis(); - } - } - finally - { - lock.writeLock().unlock(); - } - ess.getPlugin().scheduleAsyncDelayedTask(viewer); - } - } - - - private class Viewer implements Runnable - { - private final transient CommandSender sender; - private final transient int page; - private final transient boolean force; - - public Viewer(final CommandSender sender, final int page, final boolean force) - { - this.sender = sender; - this.page = page; - this.force = force; - } - - @Override - public void run() - { - lock.readLock().lock(); - try - { - if (!force && cacheage > System.currentTimeMillis() - CACHETIME) - { - outputCache(sender, page); - return; - } - } - finally - { - lock.readLock().unlock(); - } - ess.getPlugin().scheduleAsyncDelayedTask(new Calculator(new Viewer(sender, page, force), force)); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandban.java b/Essentials/src/com/earth2me/essentials/commands/Commandban.java deleted file mode 100644 index f26f1e0eb..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandban.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.Console; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.api.server.Player; -import com.earth2me.essentials.permissions.Permissions; -import com.earth2me.essentials.user.Ban; -import lombok.Cleanup; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandban extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - @Cleanup - final IUser user = getPlayer(args, 0, true); - if (!user.isOnline()) - { - if (Permissions.BAN_EXEMPT.isAuthorized(user)) - { - sender.sendMessage(_("banExempt")); - return; - } - } - else - { - if (Permissions.BAN_OFFLINE.isAuthorized(sender)) - { - sender.sendMessage(_("banExempt")); - return; - } - } - - user.acquireWriteLock(); - String banReason; - user.getData().setBan(new Ban()); - if (args.length > 1) - { - banReason = getFinalArg(args, 1); - user.getData().getBan().setReason(banReason); - } - else - { - banReason = _("defaultBanReason"); - } - user.setBanned(true); - user.kickPlayer(banReason); - final String senderName = sender instanceof Player ? ((Player)sender).getDisplayName() : Console.NAME; - - for (IPlayer onlinePlayer : server.getOnlinePlayers()) - { - final IUser player = onlinePlayer.getUser(); - if (Permissions.BAN_NOTIFY.isAuthorized(player)) - { - onlinePlayer.sendMessage(_("playerBanned", senderName, user.getName(), banReason)); - } - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbanip.java b/Essentials/src/com/earth2me/essentials/commands/Commandbanip.java deleted file mode 100644 index e5ede1e91..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbanip.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import lombok.Cleanup; -import org.bukkit.command.CommandSender; - - -public class Commandbanip extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - @Cleanup - final IUser player = ess.getUser(args[0]); - player.acquireReadLock(); - - if (player == null) - { - ess.getServer().banIP(args[0]); - sender.sendMessage(_("banIpAddress")); - } - else - { - final String ipAddress = player.getData().getIpAddress(); - if (ipAddress.length() == 0) - { - throw new Exception(_("playerNotFound")); - } - ess.getServer().banIP(player.getData().getIpAddress()); - sender.sendMessage(_("banIpAddress")); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java b/Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java deleted file mode 100644 index de63fdc29..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.Location; -import com.earth2me.essentials.utils.LocationUtil; -import org.bukkit.TreeType; - - -public class Commandbigtree extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - TreeType tree; - if (args.length > 0 && args[0].equalsIgnoreCase("redwood")) - { - tree = TreeType.TALL_REDWOOD; - } - else if (args.length > 0 && args[0].equalsIgnoreCase("tree")) - { - tree = TreeType.BIG_TREE; - } - else - { - throw new NotEnoughArgumentsException(); - } - - final Location loc = LocationUtil.getTarget(user); - final Location safeLocation = LocationUtil.getSafeDestination(loc); - final boolean success = user.getWorld().generateTree(safeLocation, tree); - if (success) - { - user.sendMessage(_("bigTreeSuccess")); - } - else - { - throw new Exception(_("bigTreeFailure")); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbreak.java b/Essentials/src/com/earth2me/essentials/commands/Commandbreak.java deleted file mode 100644 index 6f6139b59..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbreak.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.Permissions; -import static com.earth2me.essentials.I18n._; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.event.block.BlockBreakEvent; - - -public class Commandbreak extends EssentialsCommand -{ - //TODO: Switch to use util class - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - final Block block = user.getTargetBlock(null, 20); - if (block == null) - { - throw new NoChargeException(); - } - if (block.getType() == Material.AIR) - { - throw new NoChargeException(); - } - if (block.getType() == Material.BEDROCK && !Permissions.BREAK_BEDROCK.isAuthorized(user)) - { - throw new Exception(_("noBreakBedrock")); - } - final BlockBreakEvent event = new BlockBreakEvent(block, user.getBase()); - server.getPluginManager().callEvent(event); - if (event.isCancelled()) - { - throw new NoChargeException(); - } - else - { - block.setType(Material.AIR); - } - } -} \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbroadcast.java b/Essentials/src/com/earth2me/essentials/commands/Commandbroadcast.java deleted file mode 100644 index fe757c99b..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbroadcast.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.server.CommandSender; -import org.bukkit.command.CommandSender; - - -public class Commandbroadcast extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - ess.broadcastMessage(null, _("broadcast", getFinalArg(args, 0))); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandburn.java b/Essentials/src/com/earth2me/essentials/commands/Commandburn.java deleted file mode 100644 index e98cc1c48..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandburn.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.server.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandburn extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new NotEnoughArgumentsException(); - } - - for (Player p : server.matchPlayer(args[0])) - { - p.setFireTicks(Integer.parseInt(args[1]) * 20); - sender.sendMessage(_("burnMsg", p.getDisplayName(), Integer.parseInt(args[1]))); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java b/Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java deleted file mode 100644 index 6be785b33..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.permissions.Permissions; -import java.util.List; -import org.bukkit.entity.Player; - - -public class Commandclearinventory extends EssentialsCommand -{ - //TODO: Cleanup - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length > 0 && Permissions.CLEARINVENTORY_OTHERS.isAuthorized(user)) - { - //TODO: Fix fringe user match case. - if (args[0].length() >= 3) - { - List online = server.matchPlayer(args[0]); - - if (!online.isEmpty()) - { - for (Player p : online) - { - p.getInventory().clear(); - user.sendMessage(_("inventoryClearedOthers", p.getDisplayName())); - } - return; - } - throw new Exception(_("playerNotFound")); - } - else - { - Player p = server.getPlayer(args[0]); - if (p != null) - { - p.getInventory().clear(); - user.sendMessage(_("inventoryClearedOthers", p.getDisplayName())); - } - else - { - throw new Exception(_("playerNotFound")); - } - } - } - else - { - user.getInventory().clear(); - user.sendMessage(_("inventoryCleared")); - } - } - - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - if (args[0].length() >= 3) - { - List online = server.matchPlayer(args[0]); - - if (!online.isEmpty()) - { - for (Player p : online) - { - p.getInventory().clear(); - sender.sendMessage(_("inventoryClearedOthers", p.getDisplayName())); - } - return; - } - throw new Exception(_("playerNotFound")); - } - else - { - Player u = server.getPlayer(args[0]); - if (u != null) - { - u.getInventory().clear(); - sender.sendMessage(_("inventoryClearedOthers", u.getDisplayName())); - } - else - { - throw new Exception(_("playerNotFound")); - } - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandcompass.java b/Essentials/src/com/earth2me/essentials/commands/Commandcompass.java deleted file mode 100644 index 7314f8b6e..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandcompass.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; - - -public class Commandcompass extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - final int bearing = (int)(user.getLocation().getYaw() + 180 + 360) % 360; - String dir; - if (bearing < 23) - { - dir = "N"; - } - else if (bearing < 68) - { - dir = "NE"; - } - else if (bearing < 113) - { - dir = "E"; - } - else if (bearing < 158) - { - dir = "SE"; - } - else if (bearing < 203) - { - dir = "S"; - } - else if (bearing < 248) - { - dir = "SW"; - } - else if (bearing < 293) - { - dir = "W"; - } - else if (bearing < 338) - { - dir = "NW"; - } - else - { - dir = "N"; - } - user.sendMessage(_("compassBearing", dir, bearing)); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddelhome.java b/Essentials/src/com/earth2me/essentials/commands/Commanddelhome.java deleted file mode 100644 index a6f8816f0..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commanddelhome.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.permissions.Permissions; -import java.util.Locale; -import lombok.Cleanup; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commanddelhome extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - @Cleanup - IUser user = sender instanceof Player ? ess.getUser((Player)sender) : null; - String name; - String[] expandedArg; - - //Allowing both formats /sethome khobbits house | /sethome khobbits:house - final String[] nameParts = args[0].split(":"); - if (nameParts[0].length() != args[0].length()) - { - expandedArg = nameParts; - } - else - { - expandedArg = args; - } - - if (expandedArg.length > 1 && (user == null || Permissions.DELHOME_OTHERS.isAuthorized(user))) - { - user = getPlayer(expandedArg, 0, true); - name = expandedArg[1]; - } - else if (user == null) - { - throw new NotEnoughArgumentsException(); - } - else - { - name = expandedArg[0]; - } - //TODO: Think up a nice error message - /* - * if (name.equalsIgnoreCase("bed")) { throw new Exception("You cannot remove the vanilla home point"); } - */ - user.acquireWriteLock(); - user.getData().removeHome(name.toLowerCase(Locale.ENGLISH)); - sender.sendMessage(_("deleteHome", name)); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java b/Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java deleted file mode 100644 index 08649acc3..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.server.CommandSender; -import org.bukkit.command.CommandSender; - - -public class Commanddeljail extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - ess.getJails().removeJail(args[0]); - sender.sendMessage(_("deleteJail", args[0])); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java b/Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java deleted file mode 100644 index f22c60949..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.server.CommandSender; -import org.bukkit.command.CommandSender; - - -public class Commanddelwarp extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - ess.getWarps().removeWarp(args[0]); - sender.sendMessage(_("deleteWarp", args[0])); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddepth.java b/Essentials/src/com/earth2me/essentials/commands/Commanddepth.java deleted file mode 100644 index 73d3c7150..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commanddepth.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; - - -public class Commanddepth extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - final int depth = user.getLocation().getBlockY() - 63; - if (depth > 0) - { - user.sendMessage(_("depthAboveSea", depth)); - } - else if (depth < 0) - { - user.sendMessage(_("depthBelowSea", (-depth))); - } - else - { - user.sendMessage(_("depth")); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandeco.java b/Essentials/src/com/earth2me/essentials/commands/Commandeco.java deleted file mode 100644 index 5e350bd87..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandeco.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.IUser; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.api.server.Player; -import java.util.Locale; -import lombok.Cleanup; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandeco extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new NotEnoughArgumentsException(); - } - EcoCommands cmd; - double amount; - try - { - cmd = EcoCommands.valueOf(args[0].toUpperCase(Locale.ENGLISH)); - amount = Double.parseDouble(args[2].replaceAll("[^0-9\\.]", "")); - } - catch (Exception ex) - { - throw new NotEnoughArgumentsException(ex); - } - - if (args[1].contentEquals("**")) - { - for (String sUser : ess.getUserMap().getAllUniqueUsers()) - { - final IUser player = ess.getUser(sUser); - switch (cmd) - { - case GIVE: - player.giveMoney(amount); - break; - - case TAKE: - if (player.canAfford(amount, false)) - { - player.takeMoney(amount); - } - break; - - case RESET: - @Cleanup - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - player.setMoney(amount == 0 ? settings.getData().getEconomy().getStartingBalance() : amount); - break; - } - } - } - else if (args[1].contentEquals("*")) - { - for (Player onlinePlayer : server.getOnlinePlayers()) - { - final IUser player = onlinePlayer.getUser(); - switch (cmd) - { - case GIVE: - player.giveMoney(amount); - break; - - case TAKE: - if (!player.canAfford(amount, false)) - { - throw new Exception(_("notEnoughMoney")); - } - player.takeMoney(amount); - break; - - case RESET: - @Cleanup - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - player.setMoney(amount == 0 ? settings.getData().getEconomy().getStartingBalance() : amount); - break; - } - } - } - else - { - final IUser player = getPlayer(args, 1, true); - switch (cmd) - { - case GIVE: - player.giveMoney(amount, sender); - break; - - case TAKE: - if (!player.canAfford(amount, false)) - { - throw new Exception(_("notEnoughMoney")); - } - player.takeMoney(amount, sender); - break; - - case RESET: - @Cleanup ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - player.setMoney(amount == 0 ? settings.getData().getEconomy().getStartingBalance() : amount); - break; - } - } - } - - - private enum EcoCommands - { - GIVE, TAKE, RESET - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandenchant.java b/Essentials/src/com/earth2me/essentials/commands/Commandenchant.java deleted file mode 100644 index 114f51a4d..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandenchant.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.bukkit.Enchantments; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.EnchantPermissions; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; - - -public class Commandenchant extends EssentialsCommand -{ - //TODO: Implement charge costs: final Trade charge = new Trade("enchant-" + enchantmentName, ess); - @Override - protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - final ItemStack stack = user.getItemInHand(); - if (stack == null) - { - throw new Exception(_("nothingInHand")); - } - if (args.length == 0) - { - final Set enchantmentslist = new TreeSet(); - for (Map.Entry entry : Enchantments.entrySet()) - { - final String enchantmentName = entry.getValue().getName().toLowerCase(Locale.ENGLISH); - if (enchantmentslist.contains(enchantmentName) || EnchantPermissions.getPermission(enchantmentName).isAuthorized(user)) - { - enchantmentslist.add(entry.getKey()); - //enchantmentslist.add(enchantmentName); - } - } - throw new NotEnoughArgumentsException(_("enchantments", Util.joinList(enchantmentslist.toArray()))); - } - int level = -1; - if (args.length > 1) - { - try - { - level = Integer.parseInt(args[1]); - } - catch (NumberFormatException ex) - { - level = -1; - } - } - final Enchantment enchantment = getEnchantment(args[0], user); - if (level < 0 || level > enchantment.getMaxLevel()) - { - level = enchantment.getMaxLevel(); - } - if (level == 0) - { - stack.removeEnchantment(enchantment); - } - else - { - stack.addEnchantment(enchantment, level); - } - user.getInventory().setItemInHand(stack); - user.updateInventory(); - final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH); - if (level == 0) - { - user.sendMessage(_("enchantmentRemoved", enchantmentName.replace('_', ' '))); - } - else - { - user.sendMessage(_("enchantmentApplied", enchantmentName.replace('_', ' '))); - } - } - - public static Enchantment getEnchantment(final String name, final IUser user) throws Exception - { - - final Enchantment enchantment = Enchantments.getByName(name); - if (enchantment == null) - { - throw new Exception(_("enchantmentNotFound")); - } - final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH); - if (user != null && !EnchantPermissions.getPermission(enchantmentName).isAuthorized(user)) - { - throw new Exception(_("enchantmentPerm", enchantmentName)); - } - return enchantment; - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java b/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java deleted file mode 100644 index fa449be12..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java +++ /dev/null @@ -1,172 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.api.server.Player; -import java.util.HashMap; -import java.util.Map; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; - - -public class Commandessentials extends EssentialsCommand -{ - private transient int taskid; - private final transient Map noteBlocks = new HashMap(); - - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length == 0) - { - run_disabled(sender, args); - } - else if (args[0].equalsIgnoreCase("debug")) - { - run_debug(sender, args); - } - else if (args[0].equalsIgnoreCase("nya")) - { - run_nya(sender, args); - } - else if (args[0].equalsIgnoreCase("moo")) - { - run_moo(sender, args); - } - else - { - run_reload(sender, args); - } - } - - private void run_disabled(final CommandSender sender, final String[] args) throws Exception - { - sender.sendMessage("Essentials " + ess.getPlugin().getVersion()); - sender.sendMessage("/ "); - sender.sendMessage(_("blockList")); - final StringBuilder disabledCommands = new StringBuilder(); - for (Map.Entry entry : ess.getCommandHandler().disabledCommands().entrySet()) - { - if (disabledCommands.length() > 0) - { - disabledCommands.append(", "); - } - disabledCommands.append(entry.getKey()).append(" => ").append(entry.getValue()); - } - sender.sendMessage(disabledCommands.toString()); - } - - private void run_debug(final CommandSender sender, final String[] args) throws Exception - { - ess.getSettings().setDebug(!ess.getSettings().isDebug()); - sender.sendMessage("Essentials " + ess.getPlugin().getVersion() + " debug mode " + (ess.getSettings().isDebug() ? "enabled" : "disabled")); - } - - private void run_reload(final CommandSender sender, final String[] args) throws Exception - { - ess.reload(); - sender.sendMessage(_("essentialsReload", ess.getPlugin().getVersion())); - } - - private void run_nya(final CommandSender sender, final String[] args) throws Exception - { - final Map noteMap = new HashMap(); - noteMap.put("1F#", (byte)0x0); - noteMap.put("1G", (byte)0x1); - noteMap.put("1G#", (byte)0x2); - noteMap.put("1A", (byte)0x3); - noteMap.put("1A#", (byte)0x4); - noteMap.put("1B", (byte)0x5); - noteMap.put("1C", (byte)0x6); - noteMap.put("1C#", (byte)0x7); - noteMap.put("1D", (byte)0x8); - noteMap.put("1D#", (byte)0x9); - noteMap.put("1E", (byte)0xA); - noteMap.put("1F", (byte)0xB); - noteMap.put("2F#", (byte)(0x0 + 0xC)); - noteMap.put("2G", (byte)(0x1 + 0xC)); - noteMap.put("2G#", (byte)(0x2 + 0xC)); - noteMap.put("2A", (byte)(0x3 + 0xC)); - noteMap.put("2A#", (byte)(0x4 + 0xC)); - noteMap.put("2B", (byte)(0x5 + 0xC)); - noteMap.put("2C", (byte)(0x6 + 0xC)); - noteMap.put("2C#", (byte)(0x7 + 0xC)); - noteMap.put("2D", (byte)(0x8 + 0xC)); - noteMap.put("2D#", (byte)(0x9 + 0xC)); - noteMap.put("2E", (byte)(0xA + 0xC)); - noteMap.put("2F", (byte)(0xB + 0xC)); - if (!noteBlocks.isEmpty()) - { - return; - } - final String tuneStr = "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,,"; - final String[] tune = tuneStr.split(","); - for (Player player : server.getOnlinePlayers()) - { - final Location loc = player.getLocation(); - loc.add(0, 3, 0); - while (loc.getBlockY() < player.getLocation().getBlockY() + 10 && loc.getBlock().getTypeId() != 0) - { - loc.add(0, 1, 0); - } - if (loc.getBlock().getTypeId() == 0) - { - noteBlocks.put(player, loc.getBlock()); - player.sendBlockChange(loc, Material.NOTE_BLOCK, (byte)0); - } - } - taskid = ess.getPlugin().scheduleSyncRepeatingTask(new Runnable() - { - int i = 0; - - @Override - public void run() - { - final String note = tune[i]; - i++; - if (i >= tune.length) - { - Commandessentials.this.stopTune(); - } - if (note.isEmpty()) - { - return; - } - Map noteBlocks = Commandessentials.this.noteBlocks; - for (Player onlinePlayer : server.getOnlinePlayers()) - { - final Block block = noteBlocks.get(onlinePlayer); - if (block == null || block.getType() != Material.NOTE_BLOCK) - { - continue; - } - onlinePlayer.playNote(block.getLocation(), (byte)0, noteMap.get(note)); - } - } - }, 20, 2); - } - - private void stopTune() - { - ess.getPlugin().cancelTask(taskid); - for (Block block : noteBlocks.values()) - { - if (block.getType() == Material.NOTE_BLOCK) - { - block.setType(Material.AIR); - } - } - noteBlocks.clear(); - } - - private void run_moo(final CommandSender sender, final String args[]) - { - if(sender == ess.getServer().getConsoleSender()) - sender.sendMessage(new String[]{" (__)", " (oo)", " /------\\/", " / | ||", " * /\\---/\\", " ~~ ~~", "....\"Have you mooed today?\"..." } ); - else - sender.sendMessage(new String[]{" (__)", " (oo)", " /------\\/", " / | | |", " * /\\---/\\", " ~~ ~~", "....\"Have you mooed today?\"..." } ); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandext.java b/Essentials/src/com/earth2me/essentials/commands/Commandext.java deleted file mode 100644 index 50d6a7d5c..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandext.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandext extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - extinguishPlayers(sender, args[0]); - } - - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - user.setFireTicks(0); - user.sendMessage(_("extinguish")); - return; - } - - extinguishPlayers(user, args[0]); - } - - private void extinguishPlayers(final CommandSender sender, final String name) throws Exception - { - for (Player matchPlayer : server.matchPlayer(name)) - { - matchPlayer.setFireTicks(0); - sender.sendMessage(_("extinguishOthers", matchPlayer.getDisplayName())); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandfeed.java b/Essentials/src/com/earth2me/essentials/commands/Commandfeed.java deleted file mode 100644 index cf494b03f..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandfeed.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.Permissions; -import java.util.List; -import org.bukkit.entity.Player; - - -public class Commandfeed extends EssentialsCommand -{ - @Override - protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length > 0 && Permissions.FEED_OTHERS.isAuthorized(user)) - { - feedOtherPlayers(user, args[0]); - } - else - { - user.setFoodLevel(20); - user.setSaturation(10); - user.sendMessage(_("feed")); - } - } - - private void feedOtherPlayers(final ICommandSender sender, final String name) - { - final List players = server.matchPlayer(name); - if (players.isEmpty()) - { - sender.sendMessage(_("playerNotFound")); - return; - } - for (Player player : players) - { - if (ess.getUser(player).isHidden()) - { - continue; - } - player.setFoodLevel(20); - player.setSaturation(10); - sender.sendMessage(_("feedOther", player.getDisplayName())); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandfireball.java b/Essentials/src/com/earth2me/essentials/commands/Commandfireball.java deleted file mode 100644 index f13f3ee75..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandfireball.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.api.IUser; -import org.bukkit.entity.Fireball; -import org.bukkit.entity.SmallFireball; -import org.bukkit.util.Vector; - - -public class Commandfireball extends EssentialsCommand -{ - @Override - protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - boolean small = false; - if (args.length > 0 && args[0].equalsIgnoreCase("small")) - { - small = true; - } - final Vector direction = user.getEyeLocation().getDirection().multiply(2); - final Fireball fireball = user.getWorld().spawn(user.getEyeLocation().add(direction.getX(), direction.getY(), direction.getZ()), small ? SmallFireball.class : Fireball.class); - fireball.setShooter(user.getBase()); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgamemode.java b/Essentials/src/com/earth2me/essentials/commands/Commandgamemode.java deleted file mode 100644 index 10a976c1e..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgamemode.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.permissions.Permissions; -import java.util.Locale; -import org.bukkit.GameMode; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandgamemode extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - gamemodeOtherPlayers(sender, args[0]); - } - - @Override - protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length > 0 && !args[0].trim().isEmpty() && Permissions.GAMEMODE_OTHERS.isAuthorized(user)) - { - gamemodeOtherPlayers(user, args[0]); - return; - } - - user.setGameMode(user.getGameMode() == GameMode.SURVIVAL ? GameMode.CREATIVE : GameMode.SURVIVAL); - user.sendMessage(_("gameMode", _(user.getGameMode().toString().toLowerCase(Locale.ENGLISH)), user.getDisplayName())); - } - - private void gamemodeOtherPlayers(final CommandSender sender, final String name) - { - for (Player matchPlayer : server.matchPlayer(name)) - { - final IUser player = ess.getUser(matchPlayer); - if (player.isHidden()) - { - continue; - } - - player.setGameMode(player.getGameMode() == GameMode.SURVIVAL ? GameMode.CREATIVE : GameMode.SURVIVAL); - sender.sendMessage(_("gameMode", _(player.getGameMode().toString().toLowerCase(Locale.ENGLISH)), player.getDisplayName())); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgc.java b/Essentials/src/com/earth2me/essentials/commands/Commandgc.java deleted file mode 100644 index 92a128d9e..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgc.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.api.server.World; -import org.bukkit.World; -import org.bukkit.command.CommandSender; - - -public class Commandgc extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - sender.sendMessage(_("gcmax", (Runtime.getRuntime().maxMemory() / 1024 / 1024))); - sender.sendMessage(_("gctotal", (Runtime.getRuntime().totalMemory() / 1024 / 1024))); - sender.sendMessage(_("gcfree", (Runtime.getRuntime().freeMemory() / 1024 / 1024))); - - for (World w : server.getWorlds()) - { - sender.sendMessage( - (w.getEnvironment() == World.Environment.NETHER ? "Nether" : "World") + " \"" + w.getName() + "\": " - + w.getLoadedChunks().length + _("gcchunks") - + w.getEntities().size() + _("gcentities")); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java b/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java deleted file mode 100644 index e50e1e39d..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.permissions.Permissions; -import org.bukkit.Location; -import org.bukkit.command.CommandSender; - - -public class Commandgetpos extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length > 0 && Permissions.GETPOS_OTHERS.isAuthorized(user)) - { - final IUser otherUser = getPlayer(args, 0); - outputPosition(user, otherUser.getLocation(), user.getLocation()); - } - else - { - outputPosition(user, user.getLocation(), null); - } - } - - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - final IUser user = getPlayer(args, 0); - outputPosition(sender, user.getLocation(), null); - } - - //TODO: Translate - private void outputPosition(final CommandSender sender, final Location coords, final Location distance) - { - sender.sendMessage("§7World: " + coords.getWorld().getName()); - sender.sendMessage("§7X: " + coords.getBlockX() + " (+East <-> -West)"); - sender.sendMessage("§7Y: " + coords.getBlockY() + " (+Up <-> -Down)"); - sender.sendMessage("§7Z: " + coords.getBlockZ() + " (+South <-> -North)"); - sender.sendMessage("§7Yaw: " + (coords.getYaw() + 180 + 360) % 360 + " (Rotation)"); - sender.sendMessage("§7Pitch: " + coords.getPitch() + " (Head angle)"); - if (distance != null && coords.getWorld().equals(distance.getWorld())) - { - sender.sendMessage("§7Distance: " + coords.distance(distance)); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgive.java b/Essentials/src/com/earth2me/essentials/commands/Commandgive.java deleted file mode 100644 index 5612c35f6..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgive.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.GivePermissions; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.server.CommandSender; -import java.util.Locale; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.command.CommandSender; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - - -public class Commandgive extends EssentialsCommand -{ - //TODO: move these messages to message file - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new NotEnoughArgumentsException(); - } - - final IUser giveTo = getPlayer(args, 0); - - final ItemStack stack = ess.getItemDb().get(args[1], giveTo); - - final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); - if (!GivePermissions.getPermission(stack.getType()).isAuthorized(sender)) - { - throw new Exception(_("cantSpawnItem", itemname)); - } - - if (args.length > 2 && Integer.parseInt(args[2]) > 0) - { - stack.setAmount(Integer.parseInt(args[2])); - } - - if (args.length > 3) - { - for (int i = 3; i < args.length; i++) - { - final String[] split = args[i].split("[:+',;.]", 2); - if (split.length < 1) - { - continue; - } - final Enchantment enchantment = Commandenchant.getEnchantment(split[0], sender instanceof Player ? ess.getUser((Player)sender) : null); - int level; - if (split.length > 1) - { - level = Integer.parseInt(split[1]); - } - else - { - level = enchantment.getMaxLevel(); - } - stack.addEnchantment(enchantment, level); - } - } - - if (stack.getType() == Material.AIR) - { - throw new Exception(_("cantSpawnItem", "Air")); - } - - giveTo.giveItems(stack, false); - - final String itemName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' '); - sender.sendMessage(ChatColor.BLUE + "Giving " + stack.getAmount() + " of " + itemName + " to " + giveTo.getDisplayName() + "."); - - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgod.java b/Essentials/src/com/earth2me/essentials/commands/Commandgod.java deleted file mode 100644 index 9bfc74fca..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgod.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.permissions.Permissions; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandgod extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - godOtherPlayers(sender, args[0]); - } - - @Override - protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length > 0 && !args[0].trim().isEmpty() && Permissions.GOD_OTHERS.isAuthorized(user)) - { - godOtherPlayers(user, args[0]); - return; - } - - user.sendMessage(_("godMode", (user.toggleGodModeEnabled() ? _("enabled") : _("disabled")))); - } - - private void godOtherPlayers(final CommandSender sender, final String name) - { - for (Player matchPlayer : server.matchPlayer(name)) - { - final IUser player = ess.getUser(matchPlayer); - if (player.isHidden()) - { - continue; - } - final boolean enabled = player.toggleGodModeEnabled(); - player.sendMessage(_("godMode", (enabled ? _("enabled") : _("disabled")))); - sender.sendMessage(_("godMode", _(enabled ? "godEnabledFor" : "godDisabledFor", matchPlayer.getDisplayName()))); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandheal.java b/Essentials/src/com/earth2me/essentials/commands/Commandheal.java deleted file mode 100644 index 06fe3de3c..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandheal.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.permissions.Permissions; -import com.earth2me.essentials.user.UserData.TimestampType; -import java.util.List; -import org.bukkit.entity.Player; - - -public class Commandheal extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - - if (args.length > 0 && Permissions.HEAL_OTHERS.isAuthorized(user)) - { - user.checkCooldown(TimestampType.LASTHEAL, ess.getRanks().getHealCooldown(user), true, Permissions.HEAL_COOLDOWN_BYPASS); - - healOtherPlayers(user, args[0]); - return; - } - - user.checkCooldown(TimestampType.LASTHEAL, ess.getRanks().getHealCooldown(user), true, Permissions.HEAL_COOLDOWN_BYPASS); - - user.setHealth(20); - user.setFoodLevel(20); - user.sendMessage(_("heal")); - } - - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - healOtherPlayers(sender, args[0]); - } - - private void healOtherPlayers(final CommandSender sender, final String name) - { - final List players = server.matchPlayer(name); - if (players.isEmpty()) - { - sender.sendMessage(_("playerNotFound")); - return; - } - for (Player p : players) - { - if (ess.getUser(p).isHidden()) - { - continue; - } - p.setHealth(20); - p.setFoodLevel(20); - p.sendMessage(_("heal")); - sender.sendMessage(_("healOther", p.getDisplayName())); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandhelp.java b/Essentials/src/com/earth2me/essentials/commands/Commandhelp.java deleted file mode 100644 index fa32ceada..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandhelp.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.utils.textreader.TextInput; -import com.earth2me.essentials.utils.textreader.IText; -import com.earth2me.essentials.utils.textreader.TextPager; -import com.earth2me.essentials.utils.textreader.HelpInput; -import com.earth2me.essentials.utils.textreader.KeywordReplacer; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import org.bukkit.command.CommandSender; - - -public class Commandhelp extends EssentialsCommand -{ - @Override - protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - IText output; - String pageStr = args.length > 0 ? args[0] : null; - String chapterPageStr = args.length > 1 ? args[1] : null; - final IText input = new TextInput(user, "help", false, ess); - - if (input.getLines().isEmpty()) - { - if (Util.isInt(pageStr) || pageStr == null) - { - output = new HelpInput(user, "", ess); - } - else - { - output = new HelpInput(user, pageStr, ess); - pageStr = chapterPageStr; - } - chapterPageStr = null; - } - else - { - output = new KeywordReplacer(input, user, ess); - } - final TextPager pager = new TextPager(output); - pager.showPage(pageStr, chapterPageStr, commandLabel, user); - } - - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - sender.sendMessage(_("helpConsole")); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java b/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java deleted file mode 100644 index 33fa81b9e..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.Player; -import com.earth2me.essentials.permissions.Permissions; -import java.util.logging.Level; -import org.bukkit.entity.Player; - - -public class Commandhelpop extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - final String message = _("helpOp", user.getDisplayName(), Util.stripColor(getFinalArg(args, 0))); - logger.log(Level.INFO, message); - for (Player onlinePlayer : server.getOnlinePlayers()) - { - final IUser player = onlinePlayer.getUser(); - if (!Permissions.HELPOP_RECEIVE.isAuthorized(player)) - { - continue; - } - player.sendMessage(message); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandhome.java b/Essentials/src/com/earth2me/essentials/commands/Commandhome.java deleted file mode 100644 index f2403b92a..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandhome.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.Permissions; -import java.util.List; -import java.util.Locale; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; - - -public class Commandhome extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - final Trade charge = new Trade(commandName, ess); - charge.isAffordableFor(user); - IUser player = user; - String homeName = ""; - String[] nameParts; - if (args.length > 0) - { - nameParts = args[0].split(":"); - if (nameParts[0].length() == args[0].length() || !Permissions.HOME_OTHERS.isAuthorized(user)) - { - homeName = nameParts[0]; - } - else - { - player = getPlayer(nameParts, 0, true); - if (nameParts.length > 1) - { - homeName = nameParts[1]; - } - } - } - try - { - if ("bed".equalsIgnoreCase(homeName)) - { - final Location bed = player.getBedSpawnLocation(); - if (bed != null && bed.getBlock().getType() == Material.BED_BLOCK) - { - user.getTeleport().teleport(bed, charge, TeleportCause.COMMAND); - throw new NoChargeException(); - } - } - user.getTeleport().home(player, homeName.toLowerCase(Locale.ENGLISH), charge); - } - catch (NotEnoughArgumentsException e) - { - Location bed = player.getBedSpawnLocation(); - if (bed != null && bed.getBlock().getType() != Material.BED_BLOCK) - { - bed = null; - } - final List homes = player.getHomes(); - if (homes.isEmpty() && player.equals(user)) - { - if (bed != null) - { - user.getTeleport().teleport(bed, charge, TeleportCause.COMMAND); - throw new NoChargeException(); - } - user.getTeleport().respawn(charge, TeleportCause.COMMAND); - - } - else if (homes.isEmpty()) - { - throw new Exception(player == user ? _("noHomeSet") : _("noHomeSetPlayer")); - } - else if (homes.size() == 1 && player.equals(user)) - { - user.getTeleport().home(player, homes.get(0), charge); - } - else - { - if (bed != null) - { - homes.add("bed"); - } - user.sendMessage(_("homes", Util.joinList(homes))); - } - } - throw new NoChargeException(); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandignore.java b/Essentials/src/com/earth2me/essentials/commands/Commandignore.java deleted file mode 100644 index 9b3ff71cc..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandignore.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; - - -public class Commandignore extends EssentialsCommand -{ - @Override - protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - IUser player; - try - { - player = getPlayer(args, 0); - } - catch (NoSuchFieldException ex) - { - player = ess.getUser(args[0]); - } - if (player == null) - { - throw new Exception(_("playerNotFound")); - } - final String name = player.getName(); - user.acquireWriteLock(); - if (user.isIgnoringPlayer(name)) - { - user.setIgnoredPlayer(name, false); - user.sendMessage(_("unignorePlayer", player.getName())); - } - else - { - user.setIgnoredPlayer(name, true); - user.sendMessage(_("ignorePlayer", player.getName())); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandinfo.java b/Essentials/src/com/earth2me/essentials/commands/Commandinfo.java deleted file mode 100644 index 2188a9296..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandinfo.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.utils.textreader.IText; -import com.earth2me.essentials.utils.textreader.KeywordReplacer; -import com.earth2me.essentials.utils.textreader.TextInput; -import com.earth2me.essentials.utils.textreader.TextPager; -import org.bukkit.command.CommandSender; - - -public class Commandinfo extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - final IText input = new TextInput(sender, "info", true, ess); - final IText output = new KeywordReplacer(input, sender, ess); - final TextPager pager = new TextPager(output); - pager.showPage(args.length > 0 ? args[0] : null, args.length > 1 ? args[1] : null, commandLabel, sender); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java b/Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java deleted file mode 100644 index 4b772e0ec..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.user.Inventory; -import java.util.Arrays; -import org.bukkit.inventory.ItemStack; - - -public class Commandinvsee extends EssentialsCommand -{ - @Override - protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - - if (args.length < 1 && user.getData().getInventory() == null) - { - throw new NotEnoughArgumentsException(); - } - IUser invUser = user; - if (args.length == 1) - { - invUser = getPlayer(args, 0); - } - user.acquireWriteLock(); - if (invUser == user && user.getData().getInventory() != null) - { - invUser.getInventory().setContents(user.getData().getInventory().getBukkitInventory()); - user.getData().setInventory(null); - user.sendMessage(_("invRestored")); - throw new NoChargeException(); - } - if (user.getData().getInventory() == null) - { - user.getData().setInventory(new Inventory(user.getInventory().getContents())); - } - ItemStack[] invUserStack = invUser.getInventory().getContents(); - final int userStackLength = user.getInventory().getContents().length; - if (invUserStack.length < userStackLength) - { - invUserStack = Arrays.copyOf(invUserStack, userStackLength); - } - if (invUserStack.length > userStackLength) - { - throw new Exception(_("invBigger")); - } - user.getInventory().setContents(invUserStack); - user.sendMessage(_("invSee", invUser.getDisplayName())); - user.sendMessage(_("invSeeHelp")); - throw new NoChargeException(); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanditem.java b/Essentials/src/com/earth2me/essentials/commands/Commanditem.java deleted file mode 100644 index b66377722..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commanditem.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.Enchantment; -import com.earth2me.essentials.api.server.ItemStack; -import com.earth2me.essentials.permissions.ItemPermissions; -import java.util.Locale; - - -public class Commanditem extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - final ItemStack stack = ess.getItemDb().get(args[0], user); - - final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); - if (!ItemPermissions.getPermission(stack.getType()).isAuthorized(user)) - { - throw new Exception(_("cantSpawnItem", itemname)); - } - - if (args.length > 1 && Integer.parseInt(args[1]) > 0) - { - stack.setAmount(Integer.parseInt(args[1])); - } - - if (args.length > 2) - { - for (int i = 2; i < args.length; i++) - { - final String[] split = args[i].split("[:+',;.]", 2); - if (split.length < 1) - { - continue; - } - final Enchantment enchantment = Commandenchant.getEnchantment(split[0], user); - int level; - if (split.length > 1) - { - level = Integer.parseInt(split[1]); - } - else - { - level = enchantment.getMaxLevel(); - } - stack.addEnchantment(enchantment, level); - } - } - - if (stack.isAir()) - { - throw new Exception(_("cantSpawnItem", "Air")); - } - - user.giveItems(stack, false); - - final String displayName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' '); - user.sendMessage(_("itemSpawn", stack.getAmount(), displayName)); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanditemdb.java b/Essentials/src/com/earth2me/essentials/commands/Commanditemdb.java deleted file mode 100644 index 205cdf072..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commanditemdb.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.api.server.CommandSender; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - - -public class Commanditemdb extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - ItemStack itemStack = null; - if (args.length < 1) - { - if (sender instanceof Player) - { - itemStack = ((Player)sender).getItemInHand(); - } - if (itemStack == null) - { - throw new NotEnoughArgumentsException(); - } - } - else - { - itemStack = ess.getItemDb().get(args[0]); - } - sender.sendMessage(itemStack.getType().toString() + "- " + itemStack.getTypeId() + ":" + Integer.toString(itemStack.getData().getData())); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandjails.java b/Essentials/src/com/earth2me/essentials/commands/Commandjails.java deleted file mode 100644 index b1563d799..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandjails.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.utils.Util; -import org.bukkit.command.CommandSender; - - -public class Commandjails extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - sender.sendMessage("§7" + Util.joinList(" ", ess.getJails().getList())); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandjump.java b/Essentials/src/com/earth2me/essentials/commands/Commandjump.java deleted file mode 100644 index ae4832d1d..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandjump.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.ILocation; -import com.earth2me.essentials.utils.LocationUtil; -import org.bukkit.Location; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; - - -public class Commandjump extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - Location loc; - final ILocation cloc = user.getLocation(); - - try - { - loc = LocationUtil.getTarget(user); - loc.setYaw(cloc.getYaw()); - loc.setPitch(cloc.getPitch()); - loc.setY(loc.getY() + 1); - } - catch (NullPointerException ex) - { - throw new Exception(_("jumpError"), ex); - } - - final Trade charge = new Trade(commandName, ess); - charge.isAffordableFor(user); - user.getTeleport().teleport(loc, charge, TeleportCause.COMMAND); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkick.java b/Essentials/src/com/earth2me/essentials/commands/Commandkick.java deleted file mode 100644 index 2b149a6d6..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkick.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.Console; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.api.server.Player; -import com.earth2me.essentials.permissions.Permissions; -import org.bukkit.entity.Player; - - -public class Commandkick extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - final IUser user = getPlayer(args, 0); - if (Permissions.KICK_EXEMPT.isAuthorized(user)) - { - throw new Exception(_("kickExempt")); - } - final String kickReason = args.length > 1 ? getFinalArg(args, 1) : _("kickDefault"); - user.kickPlayer(kickReason); - final String senderName = sender instanceof Player ? ((Player)sender).getDisplayName() : Console.NAME; - - for (Player onlinePlayer : server.getOnlinePlayers()) - { - final IUser player = onlinePlayer.getUser(); - if (Permissions.KICK_NOTIFY.isAuthorized(player)) - { - onlinePlayer.sendMessage(_("playerKicked", senderName, user.getName(), kickReason)); - } - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java b/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java deleted file mode 100644 index 8556f58ff..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.api.server.Player; - - -public class Commandkickall extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - for (Player onlinePlayer : server.getOnlinePlayers()) - { - if (sender.isPlayer() && onlinePlayer.getName().equalsIgnoreCase(((Player)sender).getName())) - { - continue; - } - else - { - onlinePlayer.kickPlayer(args.length > 0 ? getFinalArg(args, 0) : _("kickDefault")); - } - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkill.java b/Essentials/src/com/earth2me/essentials/commands/Commandkill.java deleted file mode 100644 index 1a0ba3965..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkill.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.server.CommandSender; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.event.entity.EntityDamageEvent; - - -public class Commandkill extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - for (Player matchPlayer : server.matchPlayer(args[0])) - { - final EntityDamageEvent ede = new EntityDamageEvent(matchPlayer, sender instanceof Player && ((Player)sender).getName().equals(matchPlayer.getName()) ? EntityDamageEvent.DamageCause.SUICIDE : EntityDamageEvent.DamageCause.CUSTOM, 1000); - server.getPluginManager().callEvent(ede); - if (ede.isCancelled() && !sender.hasPermission("essentials.kill.force")) - { - continue; - } - - matchPlayer.damage(1000); - matchPlayer.setHealth(0); - sender.sendMessage(_("kill", matchPlayer.getDisplayName())); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkillall.java b/Essentials/src/com/earth2me/essentials/commands/Commandkillall.java deleted file mode 100644 index 2b2fc2c3b..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkillall.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.bukkit.Mob; -import java.util.Collections; -import java.util.Locale; -import org.bukkit.Chunk; -import org.bukkit.World; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.*; -import org.bukkit.event.entity.EntityDeathEvent; - - -public class Commandkillall extends EssentialsCommand -{ - //TODO: Tidy - missed this during command cleanup - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - String type = "all"; - int radius = -1; - World world; - if (sender instanceof Player) - { - world = ((Player)sender).getWorld(); - if (args.length == 1) - { - try - { - radius = Integer.parseInt(args[0]); - } - catch (NumberFormatException e1) - { - type = args[0]; - } - } - else if (args.length > 1) - { - type = args[0]; - try - { - radius = Integer.parseInt(args[1]); - } - catch (NumberFormatException e) - { - throw new Exception(_("numberRequired")); - } - } - } - else - { - if (args.length == 0) - { - throw new NotEnoughArgumentsException(); - } - else if (args.length == 1) - { - world = ess.getWorld(args[0]); - } - else - { - type = args[0]; - world = ess.getWorld(args[1]); - } - } - if (radius >= 0) - { - radius *= radius; - } - String killType = type.toLowerCase(Locale.ENGLISH); - boolean animals = killType.startsWith("animal"); - boolean monster = killType.startsWith("monster") || killType.startsWith("mob"); - boolean all = killType.equals("all"); - Class entityClass = null; - if (!animals && !monster && !all) - { - if (Mob.fromName(killType) == null) - { - throw new Exception(_("invalidMob")); - } - entityClass = Mob.fromName(killType).getType().getEntityClass(); - } - int numKills = 0; - for (Chunk chunk : world.getLoadedChunks()) - { - for (Entity entity : chunk.getEntities()) - { - if (sender instanceof Player) - { - if (radius >= 0 && ((Player)sender).getLocation().distanceSquared(entity.getLocation()) > radius) - { - continue; - } - } - if (entity instanceof LivingEntity == false || entity instanceof HumanEntity) - { - continue; - } - if (entity instanceof Wolf) - { - if (((Wolf)entity).isTamed()) - { - continue; - } - } - if (animals) - { - if (entity instanceof Animals || entity instanceof NPC || entity instanceof Snowman || entity instanceof WaterMob) - { - EntityDeathEvent event = new EntityDeathEvent((LivingEntity)entity, Collections.EMPTY_LIST); - ess.getServer().getPluginManager().callEvent(event); - entity.remove(); - numKills++; - } - } - else if (monster) - { - if (entity instanceof Monster || entity instanceof ComplexLivingEntity || entity instanceof Flying || entity instanceof Slime) - { - EntityDeathEvent event = new EntityDeathEvent((LivingEntity)entity, Collections.EMPTY_LIST); - ess.getServer().getPluginManager().callEvent(event); - entity.remove(); - numKills++; - } - } - else if (all) - { - EntityDeathEvent event = new EntityDeathEvent((LivingEntity)entity, Collections.EMPTY_LIST); - ess.getServer().getPluginManager().callEvent(event); - entity.remove(); - numKills++; - } - else if (entityClass != null && entityClass.isAssignableFrom(entity.getClass())) - { - EntityDeathEvent event = new EntityDeathEvent((LivingEntity)entity, Collections.EMPTY_LIST); - ess.getServer().getPluginManager().callEvent(event); - entity.remove(); - numKills++; - } - } - } - sender.sendMessage(_("kill", numKills)); - } -} \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkit.java b/Essentials/src/com/earth2me/essentials/commands/Commandkit.java deleted file mode 100644 index 1bd9e770d..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkit.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.KitPermissions; -import com.earth2me.essentials.settings.Kit; -import java.util.Collection; -import java.util.Locale; - - -public class Commandkit extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - Collection kitList = ess.getKits().getList(); - if (kitList.isEmpty()) - { - user.sendMessage(_("noKits")); - } - else - { - for (String kitName : kitList) - { - if (!KitPermissions.getPermission(kitName).isAuthorized(user)) - { - kitList.remove(kitName); - } - } - user.sendMessage(_("kits", Util.joinList(kitList))); - } - throw new NoChargeException(); - } - else - { - final String kitName = args[0].toLowerCase(Locale.ENGLISH); - final Kit kit = ess.getKits().getKit(kitName); - - if (!KitPermissions.getPermission(kitName).isAuthorized(user)) - { - throw new Exception(_("noKitPermission", "essentials.kit." + kitName)); - } - - //TODO: Check kit delay - - final Trade charge = new Trade("kit-" + kitName, ess); - charge.isAffordableFor(user); - - ess.getKits().sendKit(user, kit); - - //TODO: Merge kit changes from 2.9 - - charge.charge(user); - user.sendMessage(_("kitGive", kitName)); - - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkittycannon.java b/Essentials/src/com/earth2me/essentials/commands/Commandkittycannon.java deleted file mode 100644 index 4c56c81af..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkittycannon.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.bukkit.Mob; -import com.earth2me.essentials.api.IUser; -import java.util.Random; -import org.bukkit.Location; -import org.bukkit.entity.Ocelot; - - -public class Commandkittycannon extends EssentialsCommand -{ - private static Random random = new Random(); - - @Override - protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - final Mob cat = Mob.OCELOT; - final Ocelot ocelot = (Ocelot)cat.spawn(user, server, user.getEyeLocation()); - if (ocelot == null) - { - return; - } - final int i = random.nextInt(Ocelot.Type.values().length); - ocelot.setCatType(Ocelot.Type.values()[i]); - ocelot.setTamed(true); - ocelot.setVelocity(user.getEyeLocation().getDirection().multiply(2)); - ess.getPlugin().scheduleSyncDelayedTask(new Runnable() - { - @Override - public void run() - { - final Location loc = ocelot.getLocation(); - ocelot.remove(); - loc.getWorld().createExplosion(loc, 0F); - } - }, 20); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandlightning.java b/Essentials/src/com/earth2me/essentials/commands/Commandlightning.java deleted file mode 100644 index 82ae1b720..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandlightning.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.permissions.Permissions; -import lombok.Cleanup; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.LightningStrike; -import org.bukkit.entity.Player; - - -public class Commandlightning extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - - IUser user = null; - if (sender instanceof Player) - { - user = ess.getUser(((Player)sender)); - } - if ((args.length < 1 || !Permissions.LIGHTNING_OTHERS.isAuthorized(user)) && user != null) - { - user.getWorld().strikeLightning(user.getTargetBlock(null, 600).getLocation()); - return; - } - - if (server.matchPlayer(args[0]).isEmpty()) - { - throw new Exception(_("playerNotFound")); - } - - int power = 1; - if (args.length > 1) - { - try - { - power = Integer.parseInt(args[1]); - } - catch (NumberFormatException ex) - { - } - } - - for (Player matchPlayer : server.matchPlayer(args[0])) - { - sender.sendMessage(_("lightningUse", matchPlayer.getDisplayName())); - if (power <= 0) - { - matchPlayer.getWorld().strikeLightningEffect(matchPlayer.getLocation()); - } - else - { - LightningStrike strike = matchPlayer.getWorld().strikeLightning(matchPlayer.getLocation()); - matchPlayer.damage(power - 1, strike); - } - if (!ess.getUser(matchPlayer).isGodModeEnabled()) - { - matchPlayer.setHealth(matchPlayer.getHealth() < 5 ? 0 : matchPlayer.getHealth() - 5); - } - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - if (settings.getData().getCommands().getLightning().isWarnPlayer()) - { - matchPlayer.sendMessage(_("lightningSmited")); - } - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandlist.java b/Essentials/src/com/earth2me/essentials/commands/Commandlist.java deleted file mode 100644 index 7525b68cc..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandlist.java +++ /dev/null @@ -1,166 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.api.server.Player; -import com.earth2me.essentials.permissions.Permissions; -import java.util.*; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandlist extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - boolean showhidden = false; - if (Permissions.LIST_HIDDEN.isAuthorized(sender)) - { - showhidden = true; - } - int playerHidden = 0; - for (Player onlinePlayer : server.getOnlinePlayers()) - { - if (onlinePlayer.getUser().isHidden()) - { - playerHidden++; - } - } - - String online; - if (showhidden && playerHidden > 0) - { - online = _("listAmountHidden", server.getOnlinePlayers().size() - playerHidden, playerHidden, server.getMaxPlayers()); - } - else - { - online = _("listAmount", server.getOnlinePlayers().size() - playerHidden, server.getMaxPlayers()); - } - sender.sendMessage(online); - - boolean sortListByGroups = false; - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - try - { - sortListByGroups = settings.getData().getCommands().getList().isSortByGroups(); - } - finally - { - settings.unlock(); - } - - if (sortListByGroups) - { - Map> sort = new HashMap>(); - for (Player onlinePlayer : server.getOnlinePlayers()) - { - final IUser player = onlinePlayer.getUser(); - if (player.isHidden() && !showhidden) - { - continue; - } - final String group = ess.getRanks().getMainGroup(player); - List list = sort.get(group); - if (list == null) - { - list = new ArrayList(); - sort.put(group, list); - } - list.add(player); - } - final String[] groups = sort.keySet().toArray(new String[0]); - Arrays.sort(groups, String.CASE_INSENSITIVE_ORDER); - for (String group : groups) - { - final StringBuilder groupString = new StringBuilder(); - groupString.append(_("listGroupTag",Util.replaceColor(group))); - final List users = sort.get(group); - Collections.sort(users); - boolean first = true; - for (IUser user : users) - { - if (!first) - { - groupString.append(", "); - } - else - { - first = false; - } - user.acquireReadLock(); - try - { - if (user.getData().isAfk()) - { - groupString.append(_("listAfkTag")); - } - } - finally - { - user.unlock(); - } - if (user.isHidden()) - { - groupString.append(_("listHiddenTag")); - } - groupString.append(user.getDisplayName()); - groupString.append("§f"); - } - sender.sendMessage(groupString.toString()); - } - } - else - { - final List users = new ArrayList(); - for (Player onlinePlayer : server.getOnlinePlayers()) - { - final IUser player =onlinePlayer.getUser(); - if (player.isHidden() && !showhidden) - { - continue; - } - users.add(player); - } - Collections.sort(users); - - final StringBuilder onlineUsers = new StringBuilder(); - onlineUsers.append(_("connectedPlayers")); - boolean first = true; - for (IUser user : users) - { - if (!first) - { - onlineUsers.append(", "); - } - else - { - first = false; - } - user.acquireReadLock(); - try - { - if (user.getData().isAfk()) - { - onlineUsers.append(_("listAfkTag")); - } - } - finally - { - user.unlock(); - } - if (user.isHidden()) - { - onlineUsers.append(_("listHiddenTag")); - } - onlineUsers.append(user.getDisplayName()); - onlineUsers.append("§f"); - } - sender.sendMessage(onlineUsers.toString()); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmail.java b/Essentials/src/com/earth2me/essentials/commands/Commandmail.java deleted file mode 100644 index 95abc5b46..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmail.java +++ /dev/null @@ -1,164 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.permissions.Permissions; -import java.util.List; -import org.bukkit.entity.Player; - - -public class Commandmail extends EssentialsCommand -{ - //TODO: Tidy this up - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length >= 1 && "read".equalsIgnoreCase(args[0])) - { - final List mail = user.getData().getMails(); - if (mail == null || mail.isEmpty()) - { - user.sendMessage(_("noMail")); - throw new NoChargeException(); - } - for (String messages : mail) - { - user.sendMessage(messages); - } - user.sendMessage(_("mailClear")); - return; - } - if (args.length >= 3 && "send".equalsIgnoreCase(args[0])) - { - if (!Permissions.MAIL_SEND.isAuthorized(user)) - { - throw new Exception(_("noPerm", "essentials.mail.send")); - } - - Player player = server.getPlayer(args[1]); - IUser u; - if (player != null) - { - u = ess.getUser(player); - } - else - { - u = ess.getUser(args[1]); - } - if (u == null) - { - throw new Exception(_("playerNeverOnServer", args[1])); - } - if (!u.isIgnoringPlayer(user.getName())) - { - final String mail = Util.sanitizeString(Util.stripColor(getFinalArg(args, 2))); - u.addMail(user.getName() + ": " + mail); - } - user.sendMessage(_("mailSent")); - return; - } - if (args.length > 1 && "sendall".equalsIgnoreCase(args[0])) - { - if (!Permissions.MAIL_SENDALL.isAuthorized(user)) - { - throw new Exception(_("noPerm", "essentials.mail.sendall")); - } - ess.getPlugin().scheduleAsyncDelayedTask(new SendAll(user.getName() + ": " + Util.stripColor(getFinalArg(args, 1)))); - user.sendMessage(_("mailSent")); - return; - } - if (args.length >= 1 && "clear".equalsIgnoreCase(args[0])) - { - user.acquireWriteLock(); - user.getData().setMails(null); - user.sendMessage(_("mailCleared")); - return; - } - throw new NotEnoughArgumentsException(); - } - - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length >= 1 && "read".equalsIgnoreCase(args[0])) - { - throw new Exception(_("onlyPlayers", commandName + " read")); - } - else if (args.length >= 1 && "clear".equalsIgnoreCase(args[0])) - { - throw new Exception(_("onlyPlayers", commandName + " clear")); - } - else if (args.length >= 3 && "send".equalsIgnoreCase(args[0])) - { - Player player = server.getPlayer(args[1]); - IUser u; - if (player != null) - { - u = ess.getUser(player); - } - else - { - u = ess.getUser(args[1]); - } - if (u == null) - { - throw new Exception(_("playerNeverOnServer", args[1])); - } - u.addMail("Server: " + getFinalArg(args, 2)); - sender.sendMessage(_("mailSent")); - return; - } - else if (args.length >= 1 && "sendall".equalsIgnoreCase(args[0])) - { - ess.getPlugin().scheduleAsyncDelayedTask(new SendAll("Server: " + getFinalArg(args, 2))); - } - else if (args.length >= 2) - { - //allow sending from console without "send" argument, since it's the only thing the console can do - Player player = server.getPlayer(args[0]); - IUser u; - if (player != null) - { - u = ess.getUser(player); - } - else - { - u = ess.getUser(args[0]); - } - if (u == null) - { - throw new Exception(_("playerNeverOnServer", args[0])); - } - u.addMail("Server: " + getFinalArg(args, 1)); - sender.sendMessage(_("mailSent")); - return; - } - throw new NotEnoughArgumentsException(); - } - - - private class SendAll implements Runnable - { - String message; - - public SendAll(String message) - { - this.message = message; - } - - @Override - public void run() - { - for (String username : ess.getUserMap().getAllUniqueUsers()) - { - IUser user = ess.getUserMap().getUser(username); - 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 deleted file mode 100644 index ad70231fd..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandme.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.Permissions; - - -public class Commandme extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (user.getData().isMuted()) - { - throw new Exception(_("voiceSilenced")); - } - - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - String message = getFinalArg(args, 0); - if (Permissions.CHAT_COLOR.isAuthorized(user)) - { - message = Util.replaceColor(message); - } - else { - message = Util.stripColor(message); - } - - - ess.broadcastMessage(user, _("action", user.getDisplayName(), message)); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmore.java b/Essentials/src/com/earth2me/essentials/commands/Commandmore.java deleted file mode 100644 index fe4985832..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmore.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.ItemStack; -import com.earth2me.essentials.permissions.ItemPermissions; -import com.earth2me.essentials.permissions.Permissions; -import java.util.Locale; -import org.bukkit.inventory.ItemStack; - - -public class Commandmore extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - final ItemStack stack = user.getItemInHand(); - if (stack == null) - { - throw new Exception(_("cantSpawnItem", "Air")); - } - int defaultStackSize = 0; - int oversizedStackSize = 0; - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - try - { - defaultStackSize = settings.getData().getGeneral().getDefaultStacksize(); - oversizedStackSize = settings.getData().getGeneral().getOversizedStacksize(); - } - finally - { - settings.unlock(); - } - if (stack.getAmount() >= (Permissions.OVERSIZEDSTACKS.isAuthorized(user) - ? oversizedStackSize - : defaultStackSize > 0 ? defaultStackSize : stack.getMaxStackSize())) - { - throw new NoChargeException(); - } - final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); - if (!ItemPermissions.getPermission(stack.getType()).isAuthorized(user)) - { - throw new Exception(_("cantSpawnItem", itemname)); - } - if (Permissions.OVERSIZEDSTACKS.isAuthorized(user)) - { - stack.setAmount(oversizedStackSize); - } - else - { - stack.setAmount(defaultStackSize > 0 ? defaultStackSize : stack.getMaxStackSize()); - } - user.updateInventory(); - } -} \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmotd.java b/Essentials/src/com/earth2me/essentials/commands/Commandmotd.java deleted file mode 100644 index daf30e8cc..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmotd.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.utils.textreader.IText; -import com.earth2me.essentials.utils.textreader.KeywordReplacer; -import com.earth2me.essentials.utils.textreader.TextInput; -import com.earth2me.essentials.utils.textreader.TextPager; -import org.bukkit.command.CommandSender; - - -public class Commandmotd extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - final IText input = new TextInput(sender, "motd", true, ess); - final IText output = new KeywordReplacer(input, sender, ess); - final TextPager pager = new TextPager(output); - pager.showPage(args.length > 0 ? args[0] : null, args.length > 1 ? args[1] : null, commandLabel, sender); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmsg.java b/Essentials/src/com/earth2me/essentials/commands/Commandmsg.java deleted file mode 100644 index 2b1d12561..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmsg.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.Console; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IReplyTo; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.permissions.Permissions; -import java.util.List; -import lombok.Cleanup; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandmsg extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2 || args[0].trim().isEmpty() || args[1].trim().isEmpty()) - { - throw new NotEnoughArgumentsException(); - } - - String message = getFinalArg(args, 1); - if (sender instanceof Player) - { - @Cleanup - IUser user = ess.getUser((Player)sender); - user.acquireReadLock(); - if (user.getData().isMuted()) - { - throw new Exception(_("voiceSilenced")); - } - if (Permissions.MSG_COLOR.isAuthorized(user)) - { - message = Util.replaceColor(message); - } - else - { - message = Util.stripColor(message); - } - } - else - { - message = Util.replaceColor(message); - } - - final String translatedMe = _("me"); - - final IReplyTo replyTo = sender instanceof Player ? ess.getUser((Player)sender) : Console.getConsoleReplyTo(); - final String senderName = sender instanceof Player ? ((Player)sender).getDisplayName() : Console.NAME; - - if (args[0].equalsIgnoreCase(Console.NAME)) - { - sender.sendMessage(_("msgFormat", translatedMe, Console.NAME, message)); - CommandSender cs = server.getConsoleSender(); - cs.sendMessage(_("msgFormat", senderName, translatedMe, message)); - replyTo.setReplyTo(cs); - Console.getConsoleReplyTo().setReplyTo(sender); - return; - } - - final List matchedPlayers = server.matchPlayer(args[0]); - - if (matchedPlayers.isEmpty()) - { - throw new Exception(_("playerNotFound")); - } - - int i = 0; - for (Player matchedPlayer : matchedPlayers) - { - final IUser u = ess.getUser(matchedPlayer); - if (u.isHidden()) - { - i++; - } - } - if (i == matchedPlayers.size()) - { - throw new Exception(_("playerNotFound")); - } - - for (Player matchedPlayer : matchedPlayers) - { - sender.sendMessage(_("msgFormat", translatedMe, matchedPlayer.getDisplayName(), message)); - final IUser matchedUser = ess.getUser(matchedPlayer); - if (sender instanceof Player && (matchedUser.isIgnoringPlayer(((Player)sender).getName()) || matchedUser.isHidden())) - { - continue; - } - matchedPlayer.sendMessage(_("msgFormat", senderName, translatedMe, message)); - replyTo.setReplyTo(ess.getUser(matchedPlayer)); - ess.getUser(matchedPlayer).setReplyTo(sender); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmute.java b/Essentials/src/com/earth2me/essentials/commands/Commandmute.java deleted file mode 100644 index 2426df151..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmute.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.permissions.Permissions; -import com.earth2me.essentials.user.UserData.TimestampType; -import com.earth2me.essentials.utils.DateUtil; -import lombok.Cleanup; -import org.bukkit.command.CommandSender; - - -public class Commandmute extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - @Cleanup - final IUser player = getPlayer(args, 0, true); - player.acquireReadLock(); - if (!player.getData().isMuted() && Permissions.MUTE_EXEMPT.isAuthorized(player)) - { - throw new Exception(_("muteExempt")); - } - long muteTimestamp = 0; - if (args.length > 1) - { - String time = getFinalArg(args, 1); - muteTimestamp = DateUtil.parseDateDiff(time, true); - } - player.setTimestamp(TimestampType.MUTE, muteTimestamp); - final boolean muted = player.toggleMuted(); - sender.sendMessage( - muted - ? (muteTimestamp > 0 - ? _("mutedPlayerFor", player.getDisplayName(), DateUtil.formatDateDiff(muteTimestamp)) - : _("mutedPlayer", player.getDisplayName())) - : _("unmutedPlayer", player.getDisplayName())); - player.sendMessage( - muted - ? (muteTimestamp > 0 - ? _("playerMutedFor", DateUtil.formatDateDiff(muteTimestamp)) - : _("playerMuted")) - : _("playerUnmuted")); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandnear.java b/Essentials/src/com/earth2me/essentials/commands/Commandnear.java deleted file mode 100644 index f5cd7a777..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandnear.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.permissions.Permissions; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandnear extends EssentialsCommand -{ - @Override - protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - long radius = 200; - - IUser otherUser = null; - - if (args.length > 0) - { - try - { - otherUser = getPlayer(args, 0); - } - catch (Exception ex) - { - try - { - radius = Long.parseLong(args[0]); - } - catch (NumberFormatException e) - { - } - } - if (args.length > 1 && otherUser != null) - { - try - { - radius = Long.parseLong(args[1]); - } - catch (NumberFormatException e) - { - } - } - } - if (otherUser == null || Permissions.NEAR_OTHERS.isAuthorized(user)) - { - user.sendMessage(_("nearbyPlayers", getLocal(otherUser == null ? user : otherUser, radius))); - } - else - { - user.sendMessage(_("noAccessCommand")); - } - } - - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length == 0) - { - throw new NotEnoughArgumentsException(); - } - final IUser otherUser = getPlayer(args, 0); - long radius = 200; - if (args.length > 1) - { - try - { - radius = Long.parseLong(args[1]); - } - catch (NumberFormatException e) - { - } - } - sender.sendMessage(_("nearbyPlayers", getLocal(otherUser, radius))); - } - - private String getLocal(final IUser user, final long radius) - { - final Location loc = user.getLocation(); - final World world = loc.getWorld(); - final StringBuilder output = new StringBuilder(); - final long radiusSquared = radius * radius; - - for (Player onlinePlayer : server.getOnlinePlayers()) - { - final IUser player = ess.getUser(onlinePlayer); - if (!player.equals(user) && !player.isHidden()) - { - final Location playerLoc = player.getLocation(); - if (playerLoc.getWorld() != world) - { - continue; - } - - final long delta = (long)playerLoc.distanceSquared(loc); - if (delta < radiusSquared) - { - if (output.length() > 0) - { - output.append(", "); - } - output.append(player.getDisplayName()).append("§f(§4").append((long)Math.sqrt(delta)).append("m§f)"); - } - } - } - return output.length() > 1 ? output.toString() : _("none"); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandnick.java b/Essentials/src/com/earth2me/essentials/commands/Commandnick.java deleted file mode 100644 index 1ff098e2c..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandnick.java +++ /dev/null @@ -1,128 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.permissions.Permissions; -import java.util.Locale; -import lombok.Cleanup; -import org.bukkit.Server; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandnick extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - if (!settings.getData().getChat().getChangeDisplayname()) - { - throw new Exception(_("nickDisplayName")); - } - if (args.length > 1) - { - if (!Permissions.NICK_OTHERS.isAuthorized(user)) - { - throw new Exception(_("nickOthersPermission")); - } - setNickname(getPlayer(args, 0), formatNickname(user, args[1])); - user.sendMessage(_("nickChanged")); - return; - } - setNickname(user, formatNickname(user, args[0])); - } - - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new NotEnoughArgumentsException(); - } - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - if (!settings.getData().getChat().getChangeDisplayname()) - { - throw new Exception(_("nickDisplayName")); - } - if ((args[0].equalsIgnoreCase("*") || args[0].equalsIgnoreCase("all")) && args[1].equalsIgnoreCase("off")) - { - resetAllNicknames(server); - } - else - { - setNickname(getPlayer(args, 0), formatNickname(null, args[1])); - } - sender.sendMessage(_("nickChanged")); - } - - private String formatNickname(final IUser user, final String nick) - { - if (user == null || Permissions.NICK_COLOR.isAuthorized(user)) - { - return nick.replace('&', '\u00a7').replaceAll("\u00a7+k", ""); - } else { - return Util.stripColor(nick); - } - } - - private void resetAllNicknames(final Server server) - { - for (Player player : server.getOnlinePlayers()) - { - try - { - setNickname(ess.getUser(player), "off"); - } - catch (Exception ex) - { - } - } - } - - private void setNickname(final IUser target, final String nick) throws Exception - { - if (!nick.matches("^[a-zA-Z_0-9\u00a7]+$")) - { - throw new Exception(_("nickNamesAlpha")); - } - else if ("off".equalsIgnoreCase(nick) || target.getName().equalsIgnoreCase(nick)) - { - target.getData().setNickname(null); - target.updateDisplayName(); - target.sendMessage(_("nickNoMore")); - } - else - { - for (Player p : server.getOnlinePlayers()) - { - if (target.getBase() == p) - { - continue; - } - String dn = p.getDisplayName().toLowerCase(Locale.ENGLISH); - String n = p.getName().toLowerCase(Locale.ENGLISH); - String nk = nick.toLowerCase(Locale.ENGLISH); - if (nk.equals(dn) || nk.equals(n)) - { - throw new Exception(_("nickInUse")); - } - } - - target.getData().setNickname(nick); - target.updateDisplayName(); - target.sendMessage(_("nickSet", target.getDisplayName() + "§7.")); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandnuke.java b/Essentials/src/com/earth2me/essentials/commands/Commandnuke.java deleted file mode 100644 index ec7bc54aa..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandnuke.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.server.CommandSender; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.entity.TNTPrimed; - - -public class Commandnuke extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws NoSuchFieldException, NotEnoughArgumentsException - { - List targets; - if (args.length > 0) - { - targets = new ArrayList(); - int pos = 0; - for (String arg : args) - { - targets.add(getPlayer(args, pos)); - pos++; - } - } - else - { - targets = Arrays.asList(server.getOnlinePlayers()); - } - ess.getTNTListener().enable(); - for (Player player : targets) - { - if (player == null) - { - continue; - } - player.sendMessage(_("nuke")); - final Location loc = player.getLocation(); - final World world = loc.getWorld(); - for (int x = -10; x <= 10; x += 5) - { - for (int z = -10; z <= 10; z += 5) - { - final Location tntloc = new Location(world, loc.getBlockX() + x, world.getMaxHeight(), loc.getBlockZ() + z); - final TNTPrimed tnt = world.spawn(tntloc, TNTPrimed.class); - } - } - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandpay.java b/Essentials/src/com/earth2me/essentials/commands/Commandpay.java deleted file mode 100644 index f79f0150b..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandpay.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.api.IUser; -import org.bukkit.entity.Player; - - -public class Commandpay extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new NotEnoughArgumentsException(); - } - - if (args[0] == "") - { - throw new NotEnoughArgumentsException("You need to specify a player to pay."); - } - - double amount = Double.parseDouble(args[1].replaceAll("[^0-9\\.]", "")); - - Boolean foundUser = false; - for (Player p : server.matchPlayer(args[0])) - { - IUser u = ess.getUser(p); - if (u.isHidden()) - { - continue; - } - user.payUser(u, amount); - Trade.log("Command", "Pay", "Player", user.getName(), new Trade(amount, ess), u.getName(), new Trade(amount, ess), user.getLocation(), ess); - foundUser = true; - } - - if (foundUser == false) - { - throw new NoSuchFieldException(_("playerNotFound")); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandping.java b/Essentials/src/com/earth2me/essentials/commands/Commandping.java deleted file mode 100644 index 9594c3228..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandping.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IUser; - - -public class Commandping extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - user.sendMessage(_("pong")); - } - else - { - user.sendMessage(Util.replaceColor(getFinalArg(args, 0))); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandpowertool.java b/Essentials/src/com/earth2me/essentials/commands/Commandpowertool.java deleted file mode 100644 index 5fab91383..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandpowertool.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.Permissions; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - - -public class Commandpowertool extends EssentialsCommand -{ - @Override - protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - String command = getFinalArg(args, 0); - - // check to see if this is a clear all command - if (command != null && command.equalsIgnoreCase("d:")) - { - user.acquireWriteLock(); - user.getData().clearAllPowertools(); - user.sendMessage(_("powerToolClearAll")); - return; - } - - final ItemStack itemStack = user.getItemInHand(); - if (itemStack == null || itemStack.getType() == Material.AIR) - { - throw new Exception(_("powerToolAir")); - } - - final String itemName = itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replaceAll("_", " "); - List powertools = user.getData().getPowertool(itemStack.getType()); - if (command != null && !command.isEmpty()) - { - if (command.equalsIgnoreCase("l:")) - { - if (powertools == null || powertools.isEmpty()) - { - throw new Exception(_("powerToolListEmpty", itemName)); - } - else - { - user.sendMessage(_("powerToolList", Util.joinList(powertools), itemName)); - } - return; - } - if (command.startsWith("r:")) - { - try - { - command = command.substring(2); - if (!powertools.contains(command)) - { - throw new Exception(_("powerToolNoSuchCommandAssigned", command, itemName)); - } - - powertools.remove(command); - user.sendMessage(_("powerToolRemove", command, itemName)); - } - catch (Exception e) - { - user.sendMessage(e.getMessage()); - return; - } - } - else - { - if (command.startsWith("a:")) - { - if (!Permissions.POWERTOOL_APPEND.isAuthorized(user)) - { - throw new Exception(_("noPerm", "essentials.powertool.append")); - } - command = command.substring(2); - if (powertools.contains(command)) - { - throw new Exception(_("powerToolAlreadySet", command, itemName)); - } - - } - else if (powertools != null && !powertools.isEmpty()) - { - // Replace all commands with this one - powertools.clear(); - } - else - { - powertools = new ArrayList(); - } - - powertools.add(command); - user.sendMessage(_("powerToolAttach", Util.joinList(powertools), itemName)); - } - } - else - { - if (powertools != null) - { - powertools.clear(); - } - user.sendMessage(_("powerToolRemoveAll", itemName)); - } - - user.acquireWriteLock(); - user.getData().setPowertool(itemStack.getType(), powertools); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandpowertooltoggle.java b/Essentials/src/com/earth2me/essentials/commands/Commandpowertooltoggle.java deleted file mode 100644 index 24481bcec..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandpowertooltoggle.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; - - -public class Commandpowertooltoggle extends EssentialsCommand -{ - @Override - protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (!user.getData().hasPowerTools()) - { - user.sendMessage(_("noPowerTools")); - return; - } - user.acquireWriteLock(); - user.getData().setPowerToolsEnabled(!user.getData().isPowerToolsEnabled()); - user.sendMessage(user.getData().isPowerToolsEnabled() - ? _("powerToolsEnabled") - : _("powerToolsDisabled")); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandptime.java b/Essentials/src/com/earth2me/essentials/commands/Commandptime.java deleted file mode 100644 index 35c1a1595..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandptime.java +++ /dev/null @@ -1,229 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.utils.DescParseTickFormat; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.permissions.Permissions; -import java.util.*; -import org.bukkit.World; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandptime extends EssentialsCommand -{ - public static final Set getAliases = new HashSet(); - - static - { - getAliases.add("get"); - getAliases.add("list"); - getAliases.add("show"); - getAliases.add("display"); - } - - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - // Which Players(s) / Users(s) are we interested in? - String userSelector = null; - if (args.length == 2) - { - userSelector = args[1]; - } - Set users = getUsers(sender, userSelector); - - // If no arguments we are reading the time - if (args.length == 0) - { - getUsersTime(sender, users); - return; - } - - IUser user = sender instanceof Player ? ess.getUser((Player)sender) : null; - if ((!users.contains(user) || users.size() > 1) && user != null && !Permissions.PTIME_OTHERS.isAuthorized(user)) - { - user.sendMessage(_("pTimeOthersPermission")); - return; - } - - Long ticks; - // Parse the target time int ticks from args[0] - String timeParam = args[0]; - Boolean relative = true; - if (timeParam.startsWith("@")) - { - relative = false; - timeParam = timeParam.substring(1); - } - - if (getAliases.contains(timeParam)) - { - getUsersTime(sender, users); - return; - } - else if (DescParseTickFormat.meansReset(timeParam)) - { - ticks = null; - } - else - { - try - { - ticks = DescParseTickFormat.parse(timeParam); - } - catch (NumberFormatException e) - { - throw new NotEnoughArgumentsException(); - } - } - - setUsersTime(sender, users, ticks, relative); - } - - /** - * Used to get the time and inform - */ - private void getUsersTime(final CommandSender sender, final Collection users) - { - if (users.size() > 1) - { - sender.sendMessage(_("pTimePlayers")); - } - - for (IUser user : users) - { - if (user.getPlayerTimeOffset() == 0) - { - sender.sendMessage(_("pTimeNormal", user.getName())); - } - else - { - String time = DescParseTickFormat.format(user.getPlayerTime()); - if (!user.isPlayerTimeRelative()) - { - sender.sendMessage(_("pTimeCurrentFixed", user.getName(), time)); - } - else - { - sender.sendMessage(_("pTimeCurrent", user.getName(), time)); - } - } - } - } - - /** - * Used to set the time and inform of the change - */ - private void setUsersTime(final CommandSender sender, final Collection users, final Long ticks, Boolean relative) - { - // Update the time - if (ticks == null) - { - // Reset - for (IUser user : users) - { - user.resetPlayerTime(); - } - } - else - { - // Set - for (IUser user : users) - { - final World world = user.getWorld(); - long time = user.getPlayerTime(); - time -= time % 24000; - time += 24000 + ticks; - if (relative) - { - time -= world.getTime(); - } - user.setPlayerTime(time, relative); - } - } - - final StringBuilder msg = new StringBuilder(); - for (IUser user : users) - { - if (msg.length() > 0) - { - msg.append(", "); - } - - msg.append(user.getName()); - } - - // Inform the sender of the change - if (ticks == null) - { - sender.sendMessage(_("pTimeReset", msg.toString())); - } - else - { - String time = DescParseTickFormat.format(ticks); - if (!relative) - { - sender.sendMessage(_("pTimeSetFixed", time, msg.toString())); - } - else - { - sender.sendMessage(_("pTimeSet", time, msg.toString())); - } - } - } - - /** - * Used to parse an argument of the type "users(s) selector" - */ - private Set getUsers(final CommandSender sender, final String selector) throws Exception - { - final Set users = new TreeSet(); - // If there is no selector we want the sender itself. Or all users if sender isn't a user. - if (selector == null) - { - final IUser user = sender instanceof Player ? ess.getUser((Player)sender) : null; - if (user == null) - { - for (Player player : server.getOnlinePlayers()) - { - users.add(ess.getUser(player)); - } - } - else - { - users.add(user); - } - return users; - } - - // Try to find the user with name = selector - IUser user = null; - final List matchedPlayers = server.matchPlayer(selector); - if (!matchedPlayers.isEmpty()) - { - user = ess.getUser(matchedPlayers.get(0)); - } - - if (user != null) - { - users.add(user); - } - // If that fails, Is the argument something like "*" or "all"? - else if (selector.equalsIgnoreCase("*") || selector.equalsIgnoreCase("all")) - { - for (Player player : server.getOnlinePlayers()) - { - users.add(ess.getUser(player)); - } - } - // We failed to understand the world target... - else - { - throw new Exception(_("playerNotFound")); - } - - return users; - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandr.java b/Essentials/src/com/earth2me/essentials/commands/Commandr.java deleted file mode 100644 index d8bed8769..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandr.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.Console; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IReplyTo; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.permissions.Permissions; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandr extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - String message = getFinalArg(args, 0); - IReplyTo replyTo; - String senderName; - - if (sender instanceof Player) - { - IUser user = ess.getUser((Player)sender); - if (Permissions.MSG_COLOR.isAuthorized(user)) - { - message = Util.replaceColor(message); - } - else - { - message = Util.stripColor(message); - } - replyTo = user; - senderName = user.getDisplayName(); - } - else - { - message = Util.replaceColor(message); - replyTo = Console.getConsoleReplyTo(); - senderName = Console.NAME; - } - - final CommandSender target = replyTo.getReplyTo(); - final String targetName = target instanceof Player ? ((Player)target).getDisplayName() : Console.NAME; - - if (target == null || ((target instanceof Player) && !((Player)target).isOnline())) - { - throw new Exception(_("foreverAlone")); - } - - sender.sendMessage(_("msgFormat", _("me"), targetName, message)); - if (target instanceof Player) - { - IUser player = ess.getUser((Player)target); - if (player.isIgnoringPlayer(sender instanceof Player ? ((Player)sender).getName() : Console.NAME)) - { - return; - } - } - target.sendMessage(_("msgFormat", senderName, _("me"), message)); - replyTo.setReplyTo(target); - if (target != sender) - { - if (target instanceof Player) - { - ess.getUser((Player)target).setReplyTo(sender); - } - else - { - Console.getConsoleReplyTo().setReplyTo(sender); - } - } - } - - @Override - public String getPermissionName() - { - return "essentials.msg"; - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java b/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java deleted file mode 100644 index 8c088b044..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import java.util.Locale; -import lombok.Cleanup; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandrealname extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - @Cleanup - final ISettings settings = ess.getSettings(); - final String whois = args[0].toLowerCase(Locale.ENGLISH); - for (Player onlinePlayer : server.getOnlinePlayers()) - { - final IUser u = ess.getUser(onlinePlayer); - if (u.isHidden()) - { - continue; - } - final String displayName = Util.stripColor(u.getDisplayName()).toLowerCase(Locale.ENGLISH); - settings.acquireReadLock(); - if (!whois.equals(displayName) - && !displayName.equals(Util.stripColor(settings.getData().getChat().getNicknamePrefix()) + whois) - && !whois.equalsIgnoreCase(u.getName())) - { - continue; - } - sender.sendMessage(u.getDisplayName() + " " + _("is") + " " + u.getName()); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandremove.java b/Essentials/src/com/earth2me/essentials/commands/Commandremove.java deleted file mode 100644 index 0a513ff74..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandremove.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import java.util.Locale; -import org.bukkit.Chunk; -import org.bukkit.World; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.*; - - -public class Commandremove extends EssentialsCommand -{ - private enum ToRemove - { - DROPS, - ARROWS, - BOATS, - MINECARTS, - XP, - PAINTINGS - } - - @Override - protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - ToRemove toRemove; - final World world = user.getWorld(); - int radius = 0; - - if (args.length < 2) - { - try - { - radius = Integer.parseInt(args[1]); - } - catch (NumberFormatException e) - { - throw new Exception(_("numberRequired")); - } - } - - try - { - toRemove = ToRemove.valueOf(args[0].toUpperCase(Locale.ENGLISH)); - } - catch (IllegalArgumentException e) - { - throw new NotEnoughArgumentsException(); //TODO: translate and list types - } - - removeEntities(user, world, toRemove, radius); - } - - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new NotEnoughArgumentsException(); - } - World world; - world = ess.getWorld(args[1]); - - if (world == null) - { - throw new Exception(_("invalidWorld")); - } - ToRemove toRemove; - try - { - toRemove = ToRemove.valueOf(args[0].toUpperCase(Locale.ENGLISH)); - } - catch (IllegalArgumentException e) - { - throw new NotEnoughArgumentsException(); //TODO: translate and list types - } - removeEntities(sender, world, toRemove, 0); - } - - protected void removeEntities(final CommandSender sender, final World world, final ToRemove toRemove, int radius) throws Exception - { - int removed = 0; - if (radius > 0) - { - radius *= radius; - } - for (Chunk chunk : world.getLoadedChunks()) - { - for (Entity e : chunk.getEntities()) - { - if (radius > 0) - { - if (((Player)sender).getLocation().distanceSquared(e.getLocation()) > radius) - { - continue; - } - } - if (toRemove == ToRemove.DROPS) - { - if (e instanceof Item) - { - e.remove(); - removed++; - } - } - else if (toRemove == ToRemove.ARROWS) - { - if (e instanceof Projectile) - { - e.remove(); - removed++; - } - } - else if (toRemove == ToRemove.BOATS) - { - if (e instanceof Boat) - { - e.remove(); - removed++; - } - } - else if (toRemove == ToRemove.DROPS) - { - if (e instanceof Minecart) - { - e.remove(); - removed++; - } - } - else if (toRemove == ToRemove.XP) - { - if (e instanceof ExperienceOrb) - { - e.remove(); - removed++; - } - } - else if (toRemove == ToRemove.PAINTINGS) - { - if (e instanceof Painting) - { - e.remove(); - removed++; - } - } - } - } - sender.sendMessage(_("removed", removed)); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandrepair.java b/Essentials/src/com/earth2me/essentials/commands/Commandrepair.java deleted file mode 100644 index 4503e2416..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandrepair.java +++ /dev/null @@ -1,137 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.api.ChargeException; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.Permissions; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - - -public class Commandrepair extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - if (args[0].equalsIgnoreCase("hand")) - { - final ItemStack item = user.getItemInHand(); - if (item == null) - { - throw new Exception(_("repairInvalidType")); - } - - if (!item.getEnchantments().isEmpty() - && !Permissions.REPAIR_ENCHANTED.isAuthorized(user)) - { - throw new Exception(_("repairEnchanted")); - } - - final String itemName = item.getType().toString().toLowerCase(Locale.ENGLISH); - final Trade charge = new Trade("repair-" + itemName.replace('_', '-'), ess); - - charge.isAffordableFor(user); - - repairItem(item); - - charge.charge(user); - - user.sendMessage(_("repair", itemName.replace('_', ' '))); - } - else if (args[0].equalsIgnoreCase("all")) - { - final List repaired = new ArrayList(); - repairItems(user.getInventory().getContents(), user, repaired); - - if (Permissions.REPAIR_ARMOR.isAuthorized(user)) - { - repairItems(user.getInventory().getArmorContents(), user, repaired); - } - - if (repaired.isEmpty()) - { - throw new Exception(_("repairNone")); - } - else - { - user.sendMessage(_("repair", Util.joinList(repaired))); - } - - } - else - { - throw new NotEnoughArgumentsException(); - } - } - - private void repairItem(final ItemStack item) throws Exception - { - final Material material = Material.getMaterial(item.getTypeId()); - if (material.isBlock() || material.getMaxDurability() < 1) - { - throw new Exception(_("repairInvalidType")); - } - - if (item.getDurability() == 0) - { - throw new Exception(_("repairAlreadyFixed")); - } - - item.setDurability((short)0); - } - - private void repairItems(final ItemStack[] items, final IUser user, final List repaired) - { - for (ItemStack item : items) - { - if (item == null) - { - continue; - } - final String itemName = item.getType().toString().toLowerCase(Locale.ENGLISH); - final Trade charge = new Trade("repair-" + itemName.replace('_', '-'), ess); - try - { - charge.isAffordableFor(user); - } - catch (ChargeException ex) - { - user.sendMessage(ex.getMessage()); - continue; - } - if (!item.getEnchantments().isEmpty() - && !Permissions.REPAIR_ENCHANTED.isAuthorized(user)) - { - continue; - } - - try - { - repairItem(item); - } - catch (Exception e) - { - continue; - } - try - { - charge.charge(user); - } - catch (ChargeException ex) - { - user.sendMessage(ex.getMessage()); - } - repaired.add(itemName.replace('_', ' ')); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandrules.java b/Essentials/src/com/earth2me/essentials/commands/Commandrules.java deleted file mode 100644 index dce0b9b00..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandrules.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.utils.textreader.IText; -import com.earth2me.essentials.utils.textreader.KeywordReplacer; -import com.earth2me.essentials.utils.textreader.TextInput; -import com.earth2me.essentials.utils.textreader.TextPager; -import org.bukkit.command.CommandSender; - - -public class Commandrules extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - final IText input = new TextInput(sender, "rules", true, ess); - final IText output = new KeywordReplacer(input, sender, ess); - final TextPager pager = new TextPager(output); - pager.showPage(args.length > 0 ? args[0] : null, args.length > 1 ? args[1] : null, "rules", sender); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandseen.java b/Essentials/src/com/earth2me/essentials/commands/Commandseen.java deleted file mode 100644 index 40b8898cf..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandseen.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.permissions.Permissions; -import com.earth2me.essentials.user.UserData.TimestampType; -import com.earth2me.essentials.utils.DateUtil; -import lombok.Cleanup; -import org.bukkit.command.CommandSender; - - -public class Commandseen extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - seen(sender,args,true); - } - - @Override - protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - seen(user,args,Permissions.SEEN_BANREASON.isAuthorized(user)); - } - - protected void seen (final CommandSender sender, final String[] args, final boolean show) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - try - { - IUser u = getPlayer(args, 0); - sender.sendMessage(_("seenOnline", u.getDisplayName(), DateUtil.formatDateDiff(u.getTimestamp(TimestampType.LOGIN)))); - } - catch (NoSuchFieldException e) - { - @Cleanup - IUser u = ess.getUser(args[0]); - u.acquireReadLock(); - if (u == null) - { - throw new Exception(_("playerNotFound")); - } - sender.sendMessage(_("seenOffline", u.getDisplayName(), DateUtil.formatDateDiff(u.getTimestamp(TimestampType.LOGOUT)))); - if (u.isBanned()) - { - sender.sendMessage(_("whoisBanned", show ? u.getData().getBan().getReason() : _("true"))); - } - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsell.java b/Essentials/src/com/earth2me/essentials/commands/Commandsell.java deleted file mode 100644 index 0b56843cd..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsell.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.craftbukkit.InventoryWorkaround; -import java.util.Locale; -import java.util.logging.Level; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - - -public class Commandsell extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - ItemStack is = null; - if (args[0].equalsIgnoreCase("hand")) - { - is = user.getItemInHand(); - } - else if (args[0].equalsIgnoreCase("inventory") || args[0].equalsIgnoreCase("invent") || args[0].equalsIgnoreCase("all")) - { - for (ItemStack stack : user.getInventory().getContents()) - { - if (stack == null || stack.getType() == Material.AIR) - { - continue; - } - try - { - sellItem(user, stack, args, true); - } - catch (Exception e) - { - } - } - return; - } - else if (args[0].equalsIgnoreCase("blocks")) - { - for (ItemStack stack : user.getInventory().getContents()) - { - if (stack == null || stack.getTypeId() > 255 || stack.getType() == Material.AIR) - { - continue; - } - try - { - sellItem(user, stack, args, true); - } - catch (Exception e) - { - } - } - return; - } - if (is == null) - { - is = ess.getItemDb().get(args[0]); - } - sellItem(user, is, args, false); - } - - private void sellItem(IUser user, ItemStack is, String[] args, boolean isBulkSell) throws Exception - { - if (is == null || is.getType() == Material.AIR) - { - throw new Exception(_("itemSellAir")); - } - int id = is.getTypeId(); - int amount = 0; - if (args.length > 1) - { - amount = Integer.parseInt(args[1].replaceAll("[^0-9]", "")); - if (args[1].startsWith("-")) - { - amount = -amount; - } - } - double worth = ess.getWorth().getPrice(is); - boolean stack = args.length > 1 && args[1].endsWith("s"); - - if (Double.isNaN(worth)) - { - throw new Exception(_("itemCannotBeSold")); - } - - - int max = 0; - for (ItemStack s : user.getInventory().getContents()) - { - if (s == null) - { - continue; - } - if (s.getTypeId() != is.getTypeId()) - { - continue; - } - if (s.getDurability() != is.getDurability()) - { - continue; - } - if (!s.getEnchantments().equals(is.getEnchantments())) - { - continue; - } - max += s.getAmount(); - } - - if (stack) - { - amount *= is.getType().getMaxStackSize(); - } - if (amount < 1) - { - amount += max; - } - - if (amount > max || amount < 1) - { - if (!isBulkSell) - { - user.sendMessage(_("itemNotEnough1")); - user.sendMessage(_("itemNotEnough2")); - throw new Exception(_("itemNotEnough3")); - } - else - { - return; - } - } - - //TODO: Prices for Enchantments - final ItemStack ris = is.clone(); - ris.setAmount(amount); - InventoryWorkaround.removeItem(user.getInventory(), true, true, ris); - user.updateInventory(); - Trade.log("Command", "Sell", "Item", user.getName(), new Trade(ris, ess), user.getName(), new Trade(worth * amount, ess), user.getLocation(), ess); - user.giveMoney(worth * amount); - user.sendMessage(_("itemSold", Util.displayCurrency(worth * amount, ess), amount, is.getType().toString().toLowerCase(Locale.ENGLISH), Util.displayCurrency(worth, ess))); - logger.log(Level.INFO, _("itemSoldConsole", user.getDisplayName(), is.getType().toString().toLowerCase(Locale.ENGLISH), Util.displayCurrency(worth * amount, ess), amount, Util.displayCurrency(worth, ess))); - - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsethome.java b/Essentials/src/com/earth2me/essentials/commands/Commandsethome.java deleted file mode 100644 index 0591b152d..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsethome.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.Permissions; -import java.util.HashMap; -import java.util.Locale; -import lombok.Cleanup; - - -public class Commandsethome extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, String[] args) throws Exception - { - if (args.length > 0) - { - //Allowing both formats /sethome khobbits house | /sethome khobbits:house - final String[] nameParts = args[0].split(":"); - if (nameParts[0].length() != args[0].length()) - { - args = nameParts; - } - - if (args.length < 2) - { - if (Permissions.SETHOME_MULTIPLE.isAuthorized(user)) - { - if ("bed".equals(args[0].toLowerCase(Locale.ENGLISH))) { - throw new NotEnoughArgumentsException(); - } - if ((user.getHomes().size() < ess.getRanks().getHomeLimit(user)) - || (user.getHomes().contains(args[0].toLowerCase(Locale.ENGLISH)))) - { - user.acquireWriteLock(); - if (user.getData().getHomes() == null) - { - user.getData().setHomes(new HashMap()); - } - user.getData().getHomes().put(args[0].toLowerCase(Locale.ENGLISH), new com.earth2me.essentials.storage.StoredLocation(user.getLocation())); - } - else - { - throw new Exception(_("maxHomes", ess.getRanks().getHomeLimit(user))); - } - - } - else - { - throw new Exception(_("maxHomes", 1)); - } - } - else - { - if (Permissions.SETHOME_OTHERS.isAuthorized(user)) - { - @Cleanup - IUser usersHome = ess.getUser(ess.getServer().getPlayer(args[0])); - if (usersHome == null) - { - throw new Exception(_("playerNotFound")); - } - String name = args[1].toLowerCase(Locale.ENGLISH); - if (!Permissions.SETHOME_MULTIPLE.isAuthorized(user)) - { - name = "home"; - } - if ("bed".equals(name.toLowerCase(Locale.ENGLISH))) { - throw new NotEnoughArgumentsException(); - } - - usersHome.acquireWriteLock(); - if (usersHome.getData().getHomes() == null) - { - usersHome.getData().setHomes(new HashMap()); - } - usersHome.getData().getHomes().put(name, new com.earth2me.essentials.storage.StoredLocation(user.getLocation())); - } - } - } - else - { - user.acquireWriteLock(); - if (user.getData().getHomes() == null) - { - user.getData().setHomes(new HashMap()); - } - user.getData().getHomes().put("home", new com.earth2me.essentials.storage.StoredLocation(user.getLocation())); - } - user.sendMessage(_("homeSet")); - - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java b/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java deleted file mode 100644 index 2fcad7bd2..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; - - -public class Commandsetjail extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - ess.getJails().setJail(args[0], user.getLocation()); - user.sendMessage(_("jailSet", args[0])); - - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsetspawn.java b/Essentials/src/com/earth2me/essentials/commands/Commandsetspawn.java deleted file mode 100644 index 3af7e711f..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsetspawn.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.settings.SpawnsHolder; - - -public class Commandsetspawn extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - final String group = args.length > 0 ? getFinalArg(args, 0) : "default"; - ((SpawnsHolder)module).setSpawn(user.getLocation(), group); - user.sendMessage(_("spawnSet", group)); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java b/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java deleted file mode 100644 index 5a0599789..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.IWarps; -import org.bukkit.Location; - - -public class Commandsetwarp extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - if (args[0].matches("[0-9]+")) - { - throw new NotEnoughArgumentsException(); - } - - final Location loc = user.getLocation(); - final IWarps warps = ess.getWarps(); - Location warpLoc = null; - - try - { - warpLoc = warps.getWarp(args[0]); - } - catch (WarpNotFoundException ex) - { - } - - if (warpLoc == null || user.hasPermission("essentials.warp.overwrite." + args[0])) - { - warps.setWarp(args[0], loc); - } - else - { - throw new Exception(_("warpOverwrite")); - } - - user.sendMessage(_("warpSet", args[0])); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsetworth.java b/Essentials/src/com/earth2me/essentials/commands/Commandsetworth.java deleted file mode 100644 index 5c41af83a..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsetworth.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import org.bukkit.command.CommandSender; -import org.bukkit.inventory.ItemStack; - - -public class Commandsetworth extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new NotEnoughArgumentsException(); - } - - ItemStack stack; - String price; - - if (args.length == 1) - { - stack = user.getInventory().getItemInHand(); - price = args[0]; - } - else - { - stack = ess.getItemDb().get(args[0]); - price = args[1]; - } - - ess.getWorth().setPrice(stack, Double.parseDouble(price)); - user.sendMessage(_("worthSet")); - } - - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new NotEnoughArgumentsException(); - } - - ItemStack stack = ess.getItemDb().get(args[0]); - ess.getWorth().setPrice(stack, Double.parseDouble(args[1])); - sender.sendMessage(_("worthSet")); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsocialspy.java b/Essentials/src/com/earth2me/essentials/commands/Commandsocialspy.java deleted file mode 100644 index 86ae15fc8..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsocialspy.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; - - -public class Commandsocialspy extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - user.sendMessage("§7SocialSpy " + (user.toggleSocialSpy() ? _("enabled") : _("disabled"))); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandspawn.java b/Essentials/src/com/earth2me/essentials/commands/Commandspawn.java deleted file mode 100644 index f2ced2336..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandspawn.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.permissions.Permissions; -import com.earth2me.essentials.settings.SpawnsHolder; -import org.bukkit.Location; -import org.bukkit.command.CommandSender; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; - - -public class Commandspawn extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - final Trade charge = new Trade(commandName, ess); - charge.isAffordableFor(user); - if (args.length > 0 && Permissions.SPAWN_OTHERS.isAuthorized(user)) - { - final IUser otherUser = getPlayer(args, 0); - respawn(otherUser, null); - if (!otherUser.equals(user)) - { - otherUser.sendMessage(_("teleportAtoB", user.getDisplayName(), "spawn")); - user.sendMessage(_("teleporting")); - } - } - else - { - respawn(user, null); - } - } - - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - final IUser user = getPlayer(args, 0); - respawn(user, null); - user.sendMessage(_("teleportAtoB", user.getDisplayName(), "spawn")); - sender.sendMessage(_("teleporting")); - } - - private void respawn(final IUser user, final Trade charge) throws Exception - { - final SpawnsHolder spawns = (SpawnsHolder)this.module; - final Location spawn = spawns.getSpawn(ess.getRanks().getMainGroup(user)); - user.getTeleport().teleport(spawn, charge, TeleportCause.COMMAND); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java b/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java deleted file mode 100644 index 1a3b52e1f..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.bukkit.Mob; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.SpawnerPermissions; -import com.earth2me.essentials.utils.LocationUtil; -import com.earth2me.essentials.utils.Util; -import java.util.Locale; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.CreatureSpawner; - - -public class Commandspawner extends EssentialsCommand -{ - @Override - protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1 || args[0].length() < 2) - { - throw new NotEnoughArgumentsException(_("mobsAvailable", Util.joinList(Mob.getMobList()))); - } - - final Location target = LocationUtil.getTarget(user); - if (target == null || target.getBlock().getType() != Material.MOB_SPAWNER) - { - throw new Exception(_("mobSpawnTarget")); - } - - try - { - String name = args[0]; - - Mob mob = null; - mob = Mob.fromName(name); - if (mob == null) - { - user.sendMessage(_("invalidMob")); - return; - } - if (!SpawnerPermissions.getPermission(mob.name).isAuthorized(user)) - { - throw new Exception(_("unableToSpawnMob")); - } - final Trade charge = new Trade("spawner-" + mob.name.toLowerCase(Locale.ENGLISH), ess); - charge.isAffordableFor(user); - ((CreatureSpawner)target.getBlock().getState()).setSpawnedType(mob.getType()); - charge.charge(user); - user.sendMessage(_("setSpawner", mob.name)); - } - catch (Throwable ex) - { - throw new Exception(_("mobSpawnError"), ex); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java b/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java deleted file mode 100644 index 717a578e2..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java +++ /dev/null @@ -1,281 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.bukkit.Mob; -import com.earth2me.essentials.bukkit.Mob.MobException; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.SpawnmobPermissions; -import com.earth2me.essentials.utils.LocationUtil; -import com.earth2me.essentials.utils.Util; -import java.util.HashSet; -import java.util.Locale; -import java.util.Random; -import java.util.Set; -import org.bukkit.DyeColor; -import org.bukkit.Location; -import org.bukkit.block.Block; -import org.bukkit.entity.*; - - -public class Commandspawnmob extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - final Set mobList = Mob.getMobList(); - final Set availableList = new HashSet(); - for (String mob : mobList) - { - if (SpawnmobPermissions.getPermission(mob).isAuthorized(user)) - { - availableList.add(mob); - } - } - if (availableList.isEmpty()) - { - availableList.add(_("none")); - } - throw new NotEnoughArgumentsException(_("mobsAvailable", Util.joinList(availableList))); - } - - - final String[] mountparts = args[0].split(","); - String[] parts = mountparts[0].split(":"); - String mobType = parts[0]; - String mobData = null; - if (parts.length == 2) - { - mobData = parts[1]; - } - String mountType = null; - String mountData = null; - if (mountparts.length > 1) - { - parts = mountparts[1].split(":"); - mountType = parts[0]; - if (parts.length == 2) - { - mountData = parts[1]; - } - } - - - Entity spawnedMob = null; - Mob mob = null; - Entity spawnedMount = null; - Mob mobMount = null; - - mob = Mob.fromName(mobType); - if (mob == null) - { - throw new Exception(_("invalidMob")); - } - - if (!SpawnmobPermissions.getPermission(mob.name).isAuthorized(user)) - { - throw new Exception(_("noPermToSpawnMob")); - } - - final Block block = LocationUtil.getTarget(user).getBlock(); - if (block == null) - { - throw new Exception(_("unableToSpawnMob")); - } - IUser otherUser = null; - if (args.length >= 3) - { - otherUser = getPlayer(args, 2); - } - final Location loc = (otherUser == null) ? block.getLocation() : otherUser.getLocation(); - final Location sloc = LocationUtil.getSafeDestination(loc); - try - { - spawnedMob = mob.spawn(user, server, sloc); - } - catch (MobException e) - { - throw new Exception(_("unableToSpawnMob")); - } - - if (mountType != null) - { - mobMount = Mob.fromName(mountType); - if (mobMount == null) - { - user.sendMessage(_("invalidMob")); - return; - } - - if (!SpawnmobPermissions.getPermission(mobMount.name).isAuthorized(user)) - { - throw new Exception(_("noPermToSpawnMob")); - } - try - { - spawnedMount = mobMount.spawn(user, server, loc); - } - catch (MobException e) - { - throw new Exception(_("unableToSpawnMob")); - } - spawnedMob.setPassenger(spawnedMount); - } - if (mobData != null) - { - changeMobData(mob.getType(), spawnedMob, mobData, user); - } - if (spawnedMount != null && mountData != null) - { - changeMobData(mobMount.getType(), spawnedMount, mountData, user); - } - if (args.length >= 2) - { - int mobCount = Integer.parseInt(args[1]); - int serverLimit = 1; - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - try - { - serverLimit = settings.getData().getCommands().getSpawnmob().getLimit(); - } - finally - { - settings.unlock(); - } - if (mobCount > serverLimit) - { - mobCount = serverLimit; - user.sendMessage(_("mobSpawnLimit")); - } - - try - { - for (int i = 1; i < mobCount; i++) - { - spawnedMob = mob.spawn(user, server, loc); - if (mobMount != null) - { - try - { - spawnedMount = mobMount.spawn(user, server, loc); - } - catch (MobException e) - { - throw new Exception(_("unableToSpawnMob")); - } - spawnedMob.setPassenger(spawnedMount); - } - if (mobData != null) - { - changeMobData(mob.getType(), spawnedMob, mobData, user); - } - if (spawnedMount != null && mountData != null) - { - changeMobData(mobMount.getType(), spawnedMount, mountData, user); - } - } - user.sendMessage(mobCount + " " + mob.name.toLowerCase(Locale.ENGLISH) + mob.suffix + " " + _("spawned")); - } - catch (MobException e1) - { - throw new Exception(_("unableToSpawnMob"), e1); - } - catch (NumberFormatException e2) - { - throw new Exception(_("numberRequired"), e2); - } - catch (NullPointerException np) - { - throw new Exception(_("soloMob"), np); - } - } - else - { - user.sendMessage(mob.name + " " + _("spawned")); - } - } - - private void changeMobData(final EntityType type, final Entity spawned, String data, final IUser user) throws Exception - { - data = data.toLowerCase(Locale.ENGLISH); - if (type == EntityType.SLIME || type == EntityType.MAGMA_CUBE) - { - try - { - ((Slime)spawned).setSize(Integer.parseInt(data)); - } - catch (Exception e) - { - throw new Exception(_("slimeMalformedSize"), e); - } - } - if ((type == EntityType.SHEEP - || type == EntityType.COW - || type == EntityType.MUSHROOM_COW - || type == EntityType.CHICKEN - || type == EntityType.PIG - || type == EntityType.VILLAGER - || type == EntityType.OCELOT - || type == EntityType.WOLF) - && data.contains("baby")) - { - ((Animals)spawned).setBaby(); - return; - } - if (type == EntityType.SHEEP) - { - final String color = data.toUpperCase(Locale.ENGLISH).replace("BABY", ""); - try - { - if (color.equals("RANDOM")) - { - Random rand = new Random(); - ((Sheep)spawned).setColor(DyeColor.values()[rand.nextInt(DyeColor.values().length)]); - } - else - { - ((Sheep)spawned).setColor(DyeColor.valueOf(color)); - } - } - catch (Exception e) - { - throw new Exception(_("sheepMalformedColor"), e); - } - } - if ((type == EntityType.WOLF - || type == EntityType.OCELOT) - && data.contains("tamed")) - { - final Tameable tameable = ((Tameable)spawned); - tameable.setTamed(true); - tameable.setOwner(user.getBase()); - } - if (type == EntityType.WOLF - && data.contains("angry")) - { - ((Wolf)spawned).setAngry(true); - } - if (type == EntityType.CREEPER && data.contains("powered")) - { - ((Creeper)spawned).setPowered(true); - } - if (type == EntityType.OCELOT) - { - if (data.contains("siamese")) - { - ((Ocelot)spawned).setCatType(Ocelot.Type.SIAMESE_CAT); - } - if (data.contains("red")) - { - ((Ocelot)spawned).setCatType(Ocelot.Type.RED_CAT); - } - if (data.contains("black")) - { - ((Ocelot)spawned).setCatType(Ocelot.Type.BLACK_CAT); - } - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsudo.java b/Essentials/src/com/earth2me/essentials/commands/Commandsudo.java deleted file mode 100644 index e7bc50c7e..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsudo.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.permissions.Permissions; - - -public class Commandsudo extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new NotEnoughArgumentsException(); - } - - final IUser user = getPlayer(args, 0, false); - final String command = args[1]; - final String[] arguments = new String[args.length - 2]; - if (arguments.length > 0) - { - System.arraycopy(args, 2, arguments, 0, args.length - 2); - } - - if (Permissions.SUDO_EXEMPT.isAuthorized(user)) - { - throw new Exception(_("sudoExempt")); - } - - sender.sendMessage(_("sudoRun", user.getDisplayName(), command, getFinalArg(arguments, 0))); - - ess.getServer().dispatchCommand(user, command); - final PluginCommand execCommand = ess.getServer().getPluginCommand(command); - if (execCommand != null) - { - execCommand.execute(user.getBase(), command, arguments); - } - - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java b/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java deleted file mode 100644 index cf89f1c68..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import org.bukkit.event.entity.EntityDamageEvent; - - -public class Commandsuicide extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - ess.getPlugin().callSuicideEvent(user.getBase()); - user.damage(1000); - user.setHealth(0); - user.sendMessage(_("suicideMessage")); - ess.broadcastMessage(user,_("suicideSuccess", user.getDisplayName())); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java b/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java deleted file mode 100644 index 774f6957b..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.Console; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.permissions.Permissions; -import com.earth2me.essentials.user.Ban; -import com.earth2me.essentials.utils.DateUtil; -import org.bukkit.OfflinePlayer; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandtempban extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new NotEnoughArgumentsException(); - } - final IUser user = getPlayer(args, 0, true); - if (!user.isOnline()) - { - if (Permissions.TEMPBAN_OFFLINE.isAuthorized(sender)) - { - sender.sendMessage(_("tempbanExempt")); - return; - } - } - else - { - if (Permissions.TEMPBAN_EXEMPT.isAuthorized(user)) - { - sender.sendMessage(_("tempbanExempt")); - return; - } - } - final String time = getFinalArg(args, 1); - final long banTimestamp = DateUtil.parseDateDiff(time, true); - - final String banReason = _("tempBanned", DateUtil.formatDateDiff(banTimestamp)); - user.acquireWriteLock(); - user.getData().setBan(new Ban()); - user.getData().getBan().setReason(banReason); - user.getData().getBan().setTimeout(banTimestamp); - user.setBanned(true); - user.kickPlayer(banReason); - final String senderName = sender instanceof Player ? ((Player)sender).getDisplayName() : Console.NAME; - - for (Player onlinePlayer : server.getOnlinePlayers()) - { - final IUser player = ess.getUser(onlinePlayer); - if (Permissions.BAN_NOTIFY.isAuthorized(player)) - { - onlinePlayer.sendMessage(_("playerBanned", senderName, user.getName(), banReason)); - } - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandthunder.java b/Essentials/src/com/earth2me/essentials/commands/Commandthunder.java deleted file mode 100644 index 23c2e13b9..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandthunder.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import org.bukkit.World; - - -public class Commandthunder extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - final World world = user.getWorld(); - final boolean setThunder = args[0].equalsIgnoreCase("true"); - if (args.length > 1) - { - - world.setThundering(setThunder ? true : false); - world.setThunderDuration(Integer.parseInt(args[1]) * 20); - user.sendMessage(_("thunderDuration", (setThunder ? _("enabled") : _("disabled")), Integer.parseInt(args[1]))); - - } - else - { - world.setThundering(setThunder ? true : false); - user.sendMessage(_("thunder", setThunder ? _("enabled") : _("disabled"))); - } - - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtime.java b/Essentials/src/com/earth2me/essentials/commands/Commandtime.java deleted file mode 100644 index 43ba15ac2..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtime.java +++ /dev/null @@ -1,150 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.utils.DescParseTickFormat; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.permissions.Permissions; -import java.util.*; -import org.bukkit.World; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandtime extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - // Which World(s) are we interested in? - String worldSelector = null; - if (args.length == 2) - { - worldSelector = args[1]; - } - final Set worlds = getWorlds(sender, worldSelector); - - // If no arguments we are reading the time - if (args.length == 0) - { - getWorldsTime(sender, worlds); - return; - } - - if (Permissions.TIME_SET.isAuthorized(sender)) - { - sender.sendMessage(_("timeSetPermission")); - return; - } - - // Parse the target time int ticks from args[0] - long ticks; - try - { - ticks = DescParseTickFormat.parse(args[0]); - } - catch (NumberFormatException e) - { - throw new NotEnoughArgumentsException(); - } - - setWorldsTime(sender, worlds, ticks); - } - - /** - * Used to get the time and inform - */ - private void getWorldsTime(final CommandSender sender, final Collection worlds) - { - if (worlds.size() == 1) - { - final Iterator iter = worlds.iterator(); - sender.sendMessage(DescParseTickFormat.format(iter.next().getTime())); - return; - } - - for (World world : worlds) - { - sender.sendMessage(_("timeWorldCurrent", world.getName(), DescParseTickFormat.format(world.getTime()))); - } - } - - /** - * Used to set the time and inform of the change - */ - private void setWorldsTime(final CommandSender sender, final Collection worlds, final long ticks) - { - // Update the time - for (World world : worlds) - { - long time = world.getTime(); - time -= time % 24000; - world.setTime(time + 24000 + ticks); - } - - final StringBuilder output = new StringBuilder(); - for (World world : worlds) - { - if (output.length() > 0) - { - output.append(", "); - } - - output.append(world.getName()); - } - - sender.sendMessage(_("timeWorldSet", DescParseTickFormat.format(ticks), output.toString())); - } - - /** - * Used to parse an argument of the type "world(s) selector" - */ - private Set getWorlds(final CommandSender sender, final String selector) throws Exception - { - final Set worlds = new TreeSet(new WorldNameComparator()); - - // If there is no selector we want the world the user is currently in. Or all worlds if it isn't a user. - if (selector == null) - { - final IUser user = sender instanceof Player ? ess.getUser((Player)sender) : null; - if (user == null) - { - worlds.addAll(server.getWorlds()); - } - else - { - worlds.add(user.getWorld()); - } - return worlds; - } - - // Try to find the world with name = selector - final World world = server.getWorld(selector); - if (world != null) - { - worlds.add(world); - } - // If that fails, Is the argument something like "*" or "all"? - else if (selector.equalsIgnoreCase("*") || selector.equalsIgnoreCase("all")) - { - worlds.addAll(server.getWorlds()); - } - // We failed to understand the world target... - else - { - throw new Exception(_("invalidWorld")); - } - - return worlds; - } -} - - -class WorldNameComparator implements Comparator -{ - @Override - public int compare(final World a, final World b) - { - return a.getName().compareTo(b.getName()); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java b/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java deleted file mode 100644 index e2b011c5f..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.permissions.Permissions; -import com.earth2me.essentials.user.UserData.TimestampType; -import com.earth2me.essentials.utils.DateUtil; -import lombok.Cleanup; -import org.bukkit.OfflinePlayer; -import org.bukkit.command.CommandSender; - - -public class Commandtogglejail extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - @Cleanup - final IUser player = getPlayer(args, 0, true); - player.acquireReadLock(); - - if (args.length >= 2 && !player.getData().isJailed()) - { - if (!player.isOnline()) - { - if (Permissions.TOGGLEJAIL_OFFLINE.isAuthorized(sender)) - { - sender.sendMessage(_("mayNotJail")); - return; - } - } - else - { - if (Permissions.JAIL_EXEMPT.isAuthorized(player)) - { - sender.sendMessage(_("mayNotJail")); - return; - } - } - if (player.isOnline()) - { - ess.getJails().sendToJail(player, args[1]); - } - else - { - // Check if jail exists - ess.getJails().getJail(args[1]); - } - player.acquireWriteLock(); - player.getData().setJailed(true); - player.sendMessage(_("userJailed")); - player.getData().setJail(args[1]); - long timeDiff = 0; - if (args.length > 2) - { - final String time = getFinalArg(args, 2); - timeDiff = DateUtil.parseDateDiff(time, true); - player.setTimestamp(TimestampType.JAIL, timeDiff); - } - sender.sendMessage((timeDiff > 0 - ? _("playerJailedFor", player.getName(), DateUtil.formatDateDiff(timeDiff)) - : _("playerJailed", player.getName()))); - return; - } - - if (args.length >= 2 && player.getData().isJailed() && !args[1].equalsIgnoreCase(player.getData().getJail())) - { - sender.sendMessage(_("jailAlreadyIncarcerated", player.getData().getJail())); - return; - } - - if (args.length >= 2 && player.getData().isJailed() && args[1].equalsIgnoreCase(player.getData().getJail())) - { - final String time = getFinalArg(args, 2); - final long timeDiff = DateUtil.parseDateDiff(time, true); - player.acquireWriteLock(); - player.setTimestamp(TimestampType.JAIL, timeDiff); - sender.sendMessage(_("jailSentenceExtended", DateUtil.formatDateDiff(timeDiff))); - return; - } - - if (args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase(player.getData().getJail()))) - { - if (!player.getData().isJailed()) - { - throw new NotEnoughArgumentsException(); - } - player.acquireWriteLock(); - player.getData().setJailed(false); - player.setTimestamp(TimestampType.JAIL, 0); - player.sendMessage(_("jailReleasedPlayerNotify")); - player.getData().setJail(null); - if (player.isOnline()) - { - player.getTeleport().back(); - } - sender.sendMessage(_("jailReleased", player.getName())); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtop.java b/Essentials/src/com/earth2me/essentials/commands/Commandtop.java deleted file mode 100644 index 1e9926ecd..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtop.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.api.IUser; -import org.bukkit.Location; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; - - -public class Commandtop extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - final int topX = user.getLocation().getBlockX(); - final int topZ = user.getLocation().getBlockZ(); - final int topY = user.getWorld().getHighestBlockYAt(topX, topZ); - user.getTeleport().teleport(new Location(user.getWorld(), user.getLocation().getX(), topY + 1, user.getLocation().getZ()), new Trade(commandName, ess), TeleportCause.COMMAND); - user.sendMessage(_("teleportTop")); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtp.java b/Essentials/src/com/earth2me/essentials/commands/Commandtp.java deleted file mode 100644 index a0fe7e8b4..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtp.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.Console; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.permissions.Permissions; -import lombok.Cleanup; -import org.bukkit.command.CommandSender; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; - - -public class Commandtp extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - switch (args.length) - { - case 0: - throw new NotEnoughArgumentsException(); - - case 1: - @Cleanup - final IUser player = getPlayer(args, 0); - player.acquireReadLock(); - if (!player.getData().isTeleportEnabled()) - { - throw new Exception(_("teleportDisabled", player.getDisplayName())); - } - user.sendMessage(_("teleporting")); - final Trade charge = new Trade(commandName, ess); - charge.isAffordableFor(user); - user.getTeleport().teleport(player, charge, TeleportCause.COMMAND); - throw new NoChargeException(); - - default: - if (!Permissions.TPOHERE.isAuthorized(user)) - { - throw new Exception(_("needTpohere")); - } - user.sendMessage(_("teleporting")); - final IUser target = getPlayer(args, 0); - final IUser toPlayer = getPlayer(args, 1); - target.getTeleport().now(toPlayer, false, TeleportCause.COMMAND); - target.sendMessage(_("teleportAtoB", user.getDisplayName(), toPlayer.getDisplayName())); - break; - } - } - - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new NotEnoughArgumentsException(); - } - - sender.sendMessage(_("teleporting")); - final IUser target = getPlayer(args, 0); - final IUser toPlayer = getPlayer(args, 1); - target.getTeleport().now(toPlayer, false, TeleportCause.COMMAND); - target.sendMessage(_("teleportAtoB", Console.NAME, toPlayer.getDisplayName())); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java deleted file mode 100644 index 6790883c6..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.IUser; -import lombok.Cleanup; - - -public class Commandtpa extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - @Cleanup - IUser player = getPlayer(args, 0); - player.acquireReadLock(); - if (!player.getData().isTeleportEnabled()) - { - throw new Exception(_("teleportDisabled", player.getDisplayName())); - } - if (!player.isIgnoringPlayer(user.getName())) - { - player.requestTeleport(user, false); - player.sendMessage(_("teleportRequest", user.getDisplayName())); - player.sendMessage(_("typeTpaccept")); - player.sendMessage(_("typeTpdeny")); - int tpaAcceptCancellation = 0; - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - try { - tpaAcceptCancellation = settings.getData().getCommands().getTpa().getTimeout(); - } finally { - settings.unlock(); - } - if (tpaAcceptCancellation != 0) - { - player.sendMessage(_("teleportRequestTimeoutInfo", tpaAcceptCancellation)); - } - } - user.sendMessage(_("requestSent", player.getDisplayName())); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpaall.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpaall.java deleted file mode 100644 index 70b55bc41..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpaall.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import lombok.Cleanup; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandtpaall extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - if (sender instanceof Player) - { - teleportAAllPlayers(sender, ess.getUser((Player)sender)); - return; - } - throw new NotEnoughArgumentsException(); - } - - final IUser player = getPlayer(args, 0); - teleportAAllPlayers(sender, player); - } - - private void teleportAAllPlayers(final CommandSender sender, final IUser user) - { - sender.sendMessage(_("teleportAAll")); - for (Player onlinePlayer : server.getOnlinePlayers()) - { - @Cleanup - final IUser player = ess.getUser(onlinePlayer); - player.acquireReadLock(); - if (user == player) - { - continue; - } - if (!player.getData().isTeleportEnabled()) - { - continue; - } - try - { - player.requestTeleport(user, true); - player.sendMessage(_("teleportHereRequest", user.getDisplayName())); - player.sendMessage(_("typeTpaccept")); - int tpaAcceptCancellation = 0; - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - try - { - tpaAcceptCancellation = settings.getData().getCommands().getTpa().getTimeout(); - } - finally - { - settings.unlock(); - } - if (tpaAcceptCancellation != 0) - { - player.sendMessage(_("teleportRequestTimeoutInfo", tpaAcceptCancellation)); - } - } - catch (Exception ex) - { - ess.getCommandHandler().showCommandError(sender, commandName, ex); - } - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java deleted file mode 100644 index 2953b9c93..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.Permissions; -import org.bukkit.OfflinePlayer; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; - - -public class Commandtpaccept extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (user.getTeleportRequester() == null) - { - throw new Exception(_("noPendingRequest")); - } - - final IUser target = user.getTeleportRequester(); - if (target == null - || !target.isOnline() - || (user.isTeleportRequestHere() && !Permissions.TPAHERE.isAuthorized(target)) - || (!user.isTeleportRequestHere() && !Permissions.TPA.isAuthorized(target) && !Permissions.TPAALL.isAuthorized(target))) - { - throw new Exception(_("noPendingRequest")); - } - - if (args.length > 0 && !target.getName().contains(args[0])) - { - throw new Exception(_("noPendingRequest")); - } - - int tpaAcceptCancellation = 0; - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - try - { - tpaAcceptCancellation = settings.getData().getCommands().getTpa().getTimeout(); - } - finally - { - settings.unlock(); - } - - if (tpaAcceptCancellation != 0 && (System.currentTimeMillis() - user.getTeleportRequestTime()) / 1000 > tpaAcceptCancellation) - { - user.requestTeleport(null, false); - throw new Exception(_("requestTimedOut")); - } - - final Trade charge = new Trade(commandName, ess); - if (user.isTeleportRequestHere()) - { - charge.isAffordableFor(user); - } - else - { - charge.isAffordableFor(target); - } - user.sendMessage(_("requestAccepted")); - target.sendMessage(_("requestAcceptedFrom", user.getDisplayName())); - - if (user.isTeleportRequestHere()) - { - user.getTeleport().teleport(target, charge, TeleportCause.COMMAND); - } - else - { - target.getTeleport().teleport(user, charge, TeleportCause.COMMAND); - } - user.requestTeleport(null, false); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java deleted file mode 100644 index b28898cd6..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.IUser; -import lombok.Cleanup; - - -public class Commandtpahere extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - @Cleanup - final IUser player = getPlayer(args, 0); - player.acquireReadLock(); - if (!player.getData().isTeleportEnabled()) - { - throw new Exception(_("teleportDisabled", player.getDisplayName())); - } - player.requestTeleport(user, true); - player.sendMessage(_("teleportHereRequest", user.getDisplayName())); - player.sendMessage(_("typeTpaccept")); - int tpaAcceptCancellation = 0; - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - try - { - tpaAcceptCancellation = settings.getData().getCommands().getTpa().getTimeout(); - } - finally - { - settings.unlock(); - } - if (tpaAcceptCancellation != 0) - { - player.sendMessage(_("teleportRequestTimeoutInfo", tpaAcceptCancellation)); - } - user.sendMessage(_("requestSent", player.getDisplayName())); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpall.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpall.java deleted file mode 100644 index b34f042a7..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpall.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; - - -public class Commandtpall extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - if (sender instanceof Player) - { - teleportAllPlayers(sender, ess.getUser((Player)sender)); - return; - } - throw new NotEnoughArgumentsException(); - } - - final IUser player = getPlayer(args, 0); - teleportAllPlayers(sender, player); - } - - private void teleportAllPlayers(CommandSender sender, IUser user) - { - sender.sendMessage(_("teleportAll")); - for (Player onlinePlayer : server.getOnlinePlayers()) - { - final IUser player = ess.getUser(onlinePlayer); - if (user == player) - { - continue; - } - try - { - player.getTeleport().now(user, false, TeleportCause.COMMAND); - } - catch (Exception ex) - { - ess.getCommandHandler().showCommandError(sender, commandName, ex); - } - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpdeny.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpdeny.java deleted file mode 100644 index 15d3f7728..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpdeny.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; - - -public class Commandtpdeny extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - final IUser player = user.getTeleportRequester(); - if (player == null) - { - throw new Exception(_("noPendingRequest")); - } - - user.sendMessage(_("requestDenied")); - player.sendMessage(_("requestDeniedFrom", user.getDisplayName())); - user.requestTeleport(null, false); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtphere.java b/Essentials/src/com/earth2me/essentials/commands/Commandtphere.java deleted file mode 100644 index ee137fb38..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtphere.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.api.IUser; -import lombok.Cleanup; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; - - -public class Commandtphere extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - @Cleanup - final IUser player = getPlayer(args, 0); - player.acquireReadLock(); - if (!player.getData().isTeleportEnabled()) - { - throw new Exception(_("teleportDisabled", player.getDisplayName())); - } - player.getTeleport().teleport(user, new Trade(commandName, ess), TeleportCause.COMMAND); - user.sendMessage(_("teleporting")); - player.sendMessage(_("teleporting")); - throw new NoChargeException(); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java deleted file mode 100644 index 5c6cfb195..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.Permissions; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; - - -public class Commandtpo extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - //Just basically the old tp command - final IUser player = getPlayer(args, 0, true); - // Check if user is offline - if (!player.isOnline()) - { - throw new NoSuchFieldException(_("playerNotFound")); - } - - // Verify permission - if (!player.isHidden() || Permissions.TELEPORT_HIDDEN.isAuthorized(user)) - { - user.getTeleport().now(player, false, TeleportCause.COMMAND); - user.sendMessage(_("teleporting")); - } - else - { - throw new NoSuchFieldException(_("playerNotFound")); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java deleted file mode 100644 index 009d0f191..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.Permissions; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; - - -public class Commandtpohere extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - //Just basically the old tphere command - final IUser player = getPlayer(args, 0, true); - - // Check if user is offline - if (!player.isOnline()) - { - throw new NoSuchFieldException(_("playerNotFound")); - } - - // Verify permission - if (!player.isHidden() || Permissions.TELEPORT_HIDDEN.isAuthorized(user)) - { - player.getTeleport().now(user, false, TeleportCause.COMMAND); - user.sendMessage(_("teleporting")); - } - else - { - throw new NoSuchFieldException(_("playerNotFound")); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java b/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java deleted file mode 100644 index 79d803cd1..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.api.IUser; -import org.bukkit.Location; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; - - -public class Commandtppos extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 3) - { - throw new NotEnoughArgumentsException(); - } - - final int x = Integer.parseInt(args[0]); - final int y = Integer.parseInt(args[1]); - final int z = Integer.parseInt(args[2]); - final Location location = new Location(user.getWorld(), x, y, z); - if (args.length > 3) - { - location.setYaw((Float.parseFloat(args[3]) + 180 + 360) % 360); - } - if (args.length > 4) - { - location.setPitch(Float.parseFloat(args[4])); - } - final Trade charge = new Trade(commandName, ess); - charge.isAffordableFor(user); - user.sendMessage(_("teleporting")); - user.getTeleport().teleport(location, charge, TeleportCause.COMMAND); - throw new NoChargeException(); - } -} \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtptoggle.java b/Essentials/src/com/earth2me/essentials/commands/Commandtptoggle.java deleted file mode 100644 index 2c39271ac..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtptoggle.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; - - -public class Commandtptoggle extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - user.sendMessage(user.toggleTeleportEnabled() - ? _("teleportationEnabled") - : _("teleportationDisabled")); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtree.java b/Essentials/src/com/earth2me/essentials/commands/Commandtree.java deleted file mode 100644 index b4e47fbb6..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtree.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.utils.LocationUtil; -import org.bukkit.Location; -import org.bukkit.TreeType; - - -public class Commandtree extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - TreeType tree; - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - else if (args[0].equalsIgnoreCase("birch")) - { - tree = TreeType.BIRCH; - } - else if (args[0].equalsIgnoreCase("redwood")) - { - tree = TreeType.REDWOOD; - } - else if (args[0].equalsIgnoreCase("tree")) - { - tree = TreeType.TREE; - } - else if (args[0].equalsIgnoreCase("redmushroom")) - { - tree = TreeType.RED_MUSHROOM; - } - else if (args[0].equalsIgnoreCase("brownmushroom")) - { - tree = TreeType.BROWN_MUSHROOM; - } - else - { - throw new NotEnoughArgumentsException(); - } - - final Location loc = LocationUtil.getTarget(user); - final Location safeLocation = LocationUtil.getSafeDestination(loc); - final boolean success = user.getWorld().generateTree(safeLocation, tree); - if (success) - { - user.sendMessage(_("treeSpawned")); - } - else - { - user.sendMessage(_("treeFailure")); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandunban.java b/Essentials/src/com/earth2me/essentials/commands/Commandunban.java deleted file mode 100644 index 0aa627ff5..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandunban.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import lombok.Cleanup; -import org.bukkit.command.CommandSender; - - -public class Commandunban extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - try - { - @Cleanup - final IUser player = getPlayer(args, 0, true); - player.acquireWriteLock(); - player.getData().setBan(null); - player.setBanned(false); - sender.sendMessage(_("unbannedPlayer")); - } - catch (NoSuchFieldException e) - { - throw new Exception(_("playerNotFound")); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java b/Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java deleted file mode 100644 index 8cbb5c9b8..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import lombok.Cleanup; -import org.bukkit.command.CommandSender; - - -public class Commandunbanip extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - try - { - @Cleanup - final IUser user = getPlayer(args, 0, true); - user.acquireReadLock(); - ess.getServer().unbanIP(user.getData().getIpAddress()); - } - catch (Exception ex) - { - } - ess.getServer().unbanIP(args[0]); - sender.sendMessage(_("unbannedIP")); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandunlimited.java b/Essentials/src/com/earth2me/essentials/commands/Commandunlimited.java deleted file mode 100644 index eedbd054b..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandunlimited.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.ItemStack; -import com.earth2me.essentials.api.server.Material; -import com.earth2me.essentials.craftbukkit.InventoryWorkaround; -import com.earth2me.essentials.permissions.Permissions; -import com.earth2me.essentials.permissions.UnlimitedItemPermissions; -import java.util.Locale; -import java.util.Set; -import lombok.Cleanup; - - -public class Commandunlimited extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - @Cleanup - IUser target = user; - - if (args.length > 1 && Permissions.UNLIMITED_OTHERS.isAuthorized(user)) - { - target = getPlayer(args, 1); - target.acquireReadLock(); - } - - if (args[0].equalsIgnoreCase("list")) - { - final String list = getList(target); - user.sendMessage(list); - } - else if (args[0].equalsIgnoreCase("clear")) - { - //TODO: Fix this, the clear should always work, even when the player does not have permission. - final Set itemList = target.getData().getUnlimited(); - for(Material mat : itemList) - { - toggleUnlimited(user, target, mat.getName()); - - } - } - else - { - toggleUnlimited(user, target, args[0]); - } - } - - private String getList(final IUser target) - { - final StringBuilder output = new StringBuilder(); - output.append(_("unlimitedItems")).append(" "); - boolean first = true; - final Set items = target.getData().getUnlimited(); - if (items.isEmpty()) - { - output.append(_("none")); - } - for (Material mater : items) - { - if (!first) - { - output.append(", "); - } - first = false; - final String matname = mater.getName().toLowerCase(Locale.ENGLISH).replace("_", ""); - output.append(matname); - } - - return output.toString(); - } - - private Boolean toggleUnlimited(final IUser user, final IUser target, final String item) throws Exception - { - final ItemStack stack = ess.getItemDb().get(item, 1); - stack.setAmount(Math.min(stack.getType().getMaxStackSize(), 2)); - - final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); - if (!UnlimitedItemPermissions.getPermission(stack.getType()).isAuthorized(user)) - { - throw new Exception(_("unlimitedItemPermission", itemname)); - } - - String message = "disableUnlimited"; - Boolean enableUnlimited = false; - if (!target.getData().hasUnlimited(stack.getType())) - { - message = "enableUnlimited"; - enableUnlimited = true; - if (!target.getInventory().containsItem(true, true, stack)) - { - target.getInventory().addItem(stack); - } - } - - if (user != target) - { - user.sendMessage(_(message, itemname, target.getDisplayName())); - } - target.sendMessage(_(message, itemname, target.getDisplayName())); - target.acquireWriteLock(); - target.getData().setUnlimited(stack.getType(), enableUnlimited); - - return true; - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java b/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java deleted file mode 100644 index 58a716fce..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.IWarps; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.permissions.Permissions; -import com.earth2me.essentials.permissions.WarpPermissions; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import org.bukkit.command.CommandSender; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; - - -public class Commandwarp extends EssentialsCommand -{ - private final static int WARPS_PER_PAGE = 20; - - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length == 0 || args[0].matches("[0-9]+")) - { - if (!Permissions.WARP_LIST.isAuthorized(user)) - { - throw new Exception(_("warpListPermission")); - } - warpList(user, args); - throw new NoChargeException(); - } - if (args.length > 0) - { - IUser otherUser = null; - if (args.length == 2 && Permissions.WARP_OTHERS.isAuthorized(user)) - { - otherUser = ess.getUser(server.getPlayer(args[1])); - if (otherUser == null) - { - throw new Exception(_("playerNotFound")); - } - warpUser(otherUser, args[0]); - throw new NoChargeException(); - } - warpUser(user, args[0]); - throw new NoChargeException(); - } - } - - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2 || args[0].matches("[0-9]+")) - { - warpList(sender, args); - throw new NoChargeException(); - } - IUser otherUser = ess.getUser(server.getPlayer(args[1])); - if (otherUser == null) - { - throw new Exception(_("playerNotFound")); - } - otherUser.getTeleport().warp(args[0], null, TeleportCause.COMMAND); - throw new NoChargeException(); - - } - - //TODO: Use one of the new text classes, like /help ? - private void warpList(final CommandSender sender, final String[] args) throws Exception - { - final IWarps warps = ess.getWarps(); - if (warps.isEmpty()) - { - throw new Exception(_("noWarpsDefined")); - } - final List warpNameList = new ArrayList(warps.getList()); - - if (sender instanceof IUser) - { - final Iterator iterator = warpNameList.iterator(); - while (iterator.hasNext()) - { - final String warpName = iterator.next(); - if (!WarpPermissions.getPermission(warpName).isAuthorized(sender)) - { - iterator.remove(); - } - } - } - int page = 1; - if (args.length > 0) - { - page = Integer.parseInt(args[0]); - } - - final int warpPage = (page - 1) * WARPS_PER_PAGE; - final String warpList = Util.joinList(warpNameList.subList(warpPage, warpPage + Math.min(warpNameList.size() - warpPage, WARPS_PER_PAGE))); - - if (warpNameList.size() > WARPS_PER_PAGE) - { - sender.sendMessage(_("warpsCount", warpNameList.size(), page, (int)Math.ceil(warpNameList.size() / (double)WARPS_PER_PAGE))); - sender.sendMessage(warpList); - } - else - { - sender.sendMessage(_("warps", warpList)); - } - } - - private void warpUser(final IUser user, final String name) throws Exception - { - final Trade charge = new Trade("warp-" + name.toLowerCase(Locale.ENGLISH).replace('_', '-'), ess); - charge.isAffordableFor(user); - if (WarpPermissions.getPermission(name).isAuthorized(user)) - { - user.getTeleport().warp(name, charge, TeleportCause.COMMAND); - return; - } - throw new Exception(_("warpUsePermission")); - } -} \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandweather.java b/Essentials/src/com/earth2me/essentials/commands/Commandweather.java deleted file mode 100644 index 64f24645a..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandweather.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.api.server.World; - - -public class Commandweather extends EssentialsCommand -{ - //TODO: Remove duplication - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - final boolean isStorm = args[0].equalsIgnoreCase("storm"); - final World world = user.getWorld(); - if (args.length > 1) - { - - world.setStorm(isStorm ? true : false); - world.setWeatherDuration(Integer.parseInt(args[1]) * 20); - user.sendMessage(isStorm - ? _("weatherStormFor", world.getName(), args[1]) - : _("weatherSunFor", world.getName(), args[1])); - } - else - { - world.setStorm(isStorm ? true : false); - user.sendMessage(isStorm - ? _("weatherStorm", world.getName()) - : _("weatherSun", world.getName())); - } - } - - //TODO: Translate these - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) //running from console means inserting a world arg before other args - { - throw new Exception("When running from console, usage is: /" + commandName + " [duration]"); - } - - final boolean isStorm = args[1].equalsIgnoreCase("storm"); - final World world = server.getWorld(args[0]); - if (world == null) - { - throw new Exception("World named " + args[0] + " not found!"); - } - if (args.length > 2) - { - - world.setStorm(isStorm ? true : false); - world.setWeatherDuration(Integer.parseInt(args[2]) * 20); - sender.sendMessage(isStorm - ? _("weatherStormFor", world.getName(), args[2]) - : _("weatherSunFor", world.getName(), args[2])); - } - else - { - world.setStorm(isStorm ? true : false); - sender.sendMessage(isStorm - ? _("weatherStorm", world.getName()) - : _("weatherSun", world.getName())); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java b/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java deleted file mode 100644 index b1811b947..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.api.server.Player; -import com.earth2me.essentials.permissions.Permissions; -import com.earth2me.essentials.user.UserData; -import com.earth2me.essentials.utils.DateUtil; -import java.util.Locale; -import lombok.Cleanup; - - - -public class Commandwhois extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - boolean showhidden = false; - if (sender instanceof Player) - { - if (Permissions.LIST_HIDDEN.isAuthorized(sender)) - { - showhidden = true; - } - } - else - { - showhidden = true; - } - final String whois = args[0].toLowerCase(Locale.ENGLISH); - @Cleanup - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - final int prefixLength = Util.stripColor(settings.getData().getChat().getNicknamePrefix()).length(); - for (Player onlinePlayer : server.getOnlinePlayers()) - { - @Cleanup - final IUser user = onlinePlayer.getUser(); - - if (user.isHidden() && !showhidden) - { - continue; - } - user.acquireReadLock(); - final String nickName = Util.stripColor(user.getData().getNickname()); - if (!whois.equalsIgnoreCase(nickName) - && !whois.substring(prefixLength).equalsIgnoreCase(nickName) - && !whois.equalsIgnoreCase(user.getName())) - { - continue; - } - sender.sendMessage(""); - sender.sendMessage(_("whoisIs", user.getDisplayName(), user.getName())); - sender.sendMessage(_("whoisHealth", user.getHealth())); - sender.sendMessage(_("whoisOP", (user.isOp() ? _("true") : _("false")))); - sender.sendMessage(_("whoisGod", (user.isGodModeEnabled() ? _("true") : _("false")))); - sender.sendMessage(_("whoisGamemode", _(user.getGameMode().toString().toLowerCase(Locale.ENGLISH)))); - sender.sendMessage(_("whoisLocation", user.getLocation().getWorld().getName(), user.getLocation().getBlockX(), user.getLocation().getBlockY(), user.getLocation().getBlockZ())); - sender.sendMessage(_("whoisMoney", Util.displayCurrency(user.getMoney(), ess))); - sender.sendMessage(_("whoisJail", (user.getData().isJailed() - ? user.getTimestamp(UserData.TimestampType.JAIL) > 0 - ? DateUtil.formatDateDiff(user.getTimestamp(UserData.TimestampType.JAIL)) - : _("true") - : _("false")))); - sender.sendMessage(user.getData().isAfk() - ? _("whoisStatusAway") - : _("whoisStatusAvailable")); - sender.sendMessage(_("whoisIPAddress", user.getAddress().getAddress().toString())); - final String location = user.getData().getGeolocation(); - if (location != null - && Permissions.GEOIP_SHOW.isAuthorized(sender)) - { - sender.sendMessage(_("whoisGeoLocation", location)); - } - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandworld.java b/Essentials/src/com/earth2me/essentials/commands/Commandworld.java deleted file mode 100644 index 063ca33e3..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandworld.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.World; -import com.earth2me.essentials.api.server.Location; -import com.earth2me.essentials.permissions.WorldPermissions; -import java.util.List; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; - - -public class Commandworld extends EssentialsCommand -{ - @Override - protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - World world; - - if (args.length < 1) - { - World nether = null; - - final List worlds = server.getWorlds(); - - for (World world2 : worlds) - { - if (world2.getEnvironment() == World.Environment.NETHER) - { - nether = world2; - break; - } - } - if (nether == null) - { - return; - } - world = user.getWorld() == nether ? worlds.get(0) : nether; - } - else - { - world = ess.getWorld(getFinalArg(args, 0)); - if (world == null) - { - user.sendMessage(_("invalidWorld")); - user.sendMessage(_("possibleWorlds", server.getWorlds().size() - 1)); - user.sendMessage(_("typeWorldName")); - throw new NoChargeException(); - } - } - - - if (!WorldPermissions.getPermission(world.getName()).isAuthorized(user)) - { - user.sendMessage(_("invalidWorld")); //TODO: Make a "world teleport denied" translation - throw new NoChargeException(); - } - - 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) - { - factor = 1.0 / 8.0; - } - else - { - factor = 1.0; - } - - final Location loc = user.getLocation(); - final Location target = Location.create(world, loc.getBlockX() * factor + .5, loc.getBlockY(), loc.getBlockZ() * factor + .5); - - final Trade charge = new Trade(commandName, ess); - charge.isAffordableFor(user); - user.getTeleport().teleport(target, charge, TeleportCause.COMMAND); - throw new NoChargeException(); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandworth.java b/Essentials/src/com/earth2me/essentials/commands/Commandworth.java deleted file mode 100644 index 990bfe5a6..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandworth.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.api.server.ItemStack; -import java.util.Locale; -import org.bukkit.command.CommandSender; - - -public class Commandworth extends EssentialsCommand -{ - //TODO: Remove duplication - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - ItemStack iStack = user.getItemInHand(); - int amount = iStack.getAmount(); - - if (args.length > 0) - { - iStack = ess.getItemDb().get(args[0]); - } - - try - { - if (args.length > 1) - { - amount = Integer.parseInt(args[1]); - } - } - catch (NumberFormatException ex) - { - amount = iStack.getType().getMaxStackSize(); - } - - iStack.setAmount(amount); - final double worth = ess.getWorth().getPrice(iStack); - if (Double.isNaN(worth)) - { - throw new Exception(_("itemCannotBeSold")); - } - - user.sendMessage(iStack.getDurability() != 0 - ? _("worthMeta", - iStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), - iStack.getDurability(), - Util.displayCurrency(worth * amount, ess), - amount, - Util.displayCurrency(worth, ess)) - : _("worth", - iStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), - Util.displayCurrency(worth * amount, ess), - amount, - Util.displayCurrency(worth, ess))); - } - - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - ItemStack iStack = ess.getItemDb().get(args[0]); - int amount = iStack.getAmount(); - - try - { - if (args.length > 1) - { - amount = Integer.parseInt(args[1]); - } - } - catch (NumberFormatException ex) - { - amount = iStack.getType().getMaxStackSize(); - } - - iStack.setAmount(amount); - final double worth = ess.getWorth().getPrice(iStack); - if (Double.isNaN(worth)) - { - throw new Exception(_("itemCannotBeSold")); - } - - sender.sendMessage(iStack.getDurability() != 0 - ? _("worthMeta", - iStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), - iStack.getDurability(), - Util.displayCurrency(worth * amount, ess), - amount, - Util.displayCurrency(worth, ess)) - : _("worth", - iStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), - Util.displayCurrency(worth * amount, ess), - amount, - Util.displayCurrency(worth, ess))); - - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java b/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java deleted file mode 100644 index a7deaac71..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IEssentialsModule; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.api.server.IServer; -import com.earth2me.essentials.api.server.Player; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.permissions.AbstractSuperpermsPermission; -import java.util.List; -import java.util.logging.Logger; -import org.bukkit.command.Command; - - -public abstract class EssentialsCommand extends AbstractSuperpermsPermission implements IEssentialsCommand -{ - protected transient String commandName; - protected transient IEssentials ess; - protected transient IEssentialsModule module; - protected transient IServer server; - protected transient Logger logger; - private transient String permission; - - public void init(final IEssentials ess, final String commandName) - { - this.ess = ess; - this.logger = ess.getLogger(); - this.server = ess.getServer(); - this.commandName = commandName; - this.permission = "essentials." + commandName; - } - - @Override - public void setEssentialsModule(final IEssentialsModule module) - { - this.module = module; - } - - protected IUser getPlayer(final String[] args, final int pos) throws NoSuchFieldException, NotEnoughArgumentsException - { - return getPlayer(args, pos, false); - } - - protected IUser getPlayer(final String[] args, final int pos, final boolean getOffline) throws NoSuchFieldException, NotEnoughArgumentsException - { - if (args.length <= pos) - { - throw new NotEnoughArgumentsException(); - } - if (args[pos].isEmpty()) - { - throw new NoSuchFieldException(_("playerNotFound")); - } - final IUser user = ess.getUser(args[pos]); - if (user != null) - { - if (!getOffline && (!user.isOnline() || user.isHidden())) - { - throw new NoSuchFieldException(_("playerNotFound")); - } - return user; - } - final List matches = server.matchPlayer(args[pos]); - - if (!matches.isEmpty()) - { - for (Player player : matches) - { - final IUser userMatch = player.getUser(); - if (userMatch.getDisplayName().startsWith(args[pos]) && (getOffline || !userMatch.isHidden())) - { - return userMatch; - } - } - final IUser userMatch = matches.get(0).getUser(); - if (getOffline || !userMatch.isHidden()) - { - return userMatch; - } - } - throw new NoSuchFieldException(_("playerNotFound")); - } - - @Override - public final void run(final IUser user, final Command cmd, final String commandLabel, final String[] args) throws Exception - { - final Trade charge = new Trade(commandName, ess); - charge.isAffordableFor(user); - run(user, commandLabel, args); - charge.charge(user); - } - - protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - run((CommandSender)user, commandLabel, args); - } - - @Override - public final void run(final CommandSender sender, final Command cmd, final String commandLabel, final String[] args) throws Exception - { - run(sender, commandLabel, args); - } - - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - throw new Exception(_("onlyPlayers", commandName)); - } - - 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(); - } - - @Override - public String getPermissionName() - { - return permission; - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/EssentialsCommandHandler.java b/Essentials/src/com/earth2me/essentials/commands/EssentialsCommandHandler.java deleted file mode 100644 index 0971b764a..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/EssentialsCommandHandler.java +++ /dev/null @@ -1,317 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.*; -import com.earth2me.essentials.api.server.CommandSender; -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 java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.command.PluginCommand; -import org.bukkit.command.PluginCommandYamlParser; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - - -public class EssentialsCommandHandler implements ICommandHandler -{ - private final transient ClassLoader classLoader; - private final transient String commandPath; - private final transient String permissionPrefix; - private final transient IEssentialsModule module; - private static final transient Logger LOGGER = Bukkit.getLogger(); - private final transient Map> altcommands = new HashMap>(); - private final transient Map disabledList = new HashMap(); - private final transient Map commands = new HashMap(); - private final transient IEssentials ess; - - public EssentialsCommandHandler(ClassLoader classLoader, String commandPath, String permissionPrefix, IEssentials ess) - { - this(classLoader, commandPath, permissionPrefix, null, ess); - } - - public EssentialsCommandHandler(ClassLoader classLoader, String commandPath, String permissionPrefix, IEssentialsModule module, IEssentials ess) - { - this.classLoader = classLoader; - this.commandPath = commandPath; - this.permissionPrefix = permissionPrefix; - this.module = module; - this.ess = ess; - for (Plugin plugin : ess.getServer().getPluginManager().getPlugins()) - { - if (plugin.isEnabled()) - { - addPlugin(plugin); - } - } - } - - @Override - public boolean handleCommand(final CommandSender sender, final Command command, final String commandLabel, final String[] args) - { - boolean disabled = false; - boolean overridden = false; - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - try - { - disabled = settings.getData().getCommands().isDisabled(command.getName()); - overridden = !disabled || settings.getData().getCommands().isOverridden(command.getName()); - } - finally - { - settings.unlock(); - } - // Allow plugins to override the command via onCommand - if (!overridden && (!commandLabel.startsWith("e") || commandLabel.equalsIgnoreCase(command.getName()))) - { - final PluginCommand pc = getAlternative(commandLabel); - if (pc != null) - { - - executed(commandLabel, pc.getLabel()); - try - { - return pc.execute(sender, commandLabel, args); - } - catch (final Exception ex) - { - final ArrayList elements = new ArrayList(Arrays.asList(ex.getStackTrace())); - elements.remove(0); - final ArrayList toRemove = new ArrayList(); - for (final StackTraceElement e : elements) - { - if (e.getClassName().equals("com.earth2me.essentials.Essentials")) - { - toRemove.add(e); - } - } - elements.removeAll(toRemove); - final StackTraceElement[] trace = elements.toArray(new StackTraceElement[elements.size()]); - ex.setStackTrace(trace); - ex.printStackTrace(); - sender.sendMessage(ChatColor.RED + "An internal error occurred while attempting to perform this command"); - return true; - } - } - } - - try - { - IUser user = null; - if (sender instanceof Player) - { - user = ess.getUser((Player)sender); - LOGGER.log(Level.INFO, String.format("[PLAYER_COMMAND] %s: /%s %s ", ((Player)sender).getName(), commandLabel, EssentialsCommand.getFinalArg(args, 0))); - } - - // Check for disabled commands - if (disabled) - { - return true; - } - - final String commandName = command.getName().toLowerCase(Locale.ENGLISH); - IEssentialsCommand cmd = commands.get(commandName); - if (cmd == null) - { - try - { - cmd = (IEssentialsCommand)classLoader.loadClass(commandPath + commandName).newInstance(); - cmd.init(ess, commandName); - cmd.setEssentialsModule(module); - commands.put(commandName, cmd); - } - catch (Exception ex) - { - sender.sendMessage(_("commandNotLoaded", commandName)); - LOGGER.log(Level.SEVERE, _("commandNotLoaded", commandName), ex); - return true; - } - } - - // Check authorization - if (sender != null && !cmd.isAuthorized(sender)) - { - LOGGER.log(Level.WARNING, _("deniedAccessCommand", user.getName())); - user.sendMessage(_("noAccessCommand")); - return true; - } - - // Run the command - try - { - if (user == null) - { - cmd.run(sender, command, commandLabel, args); - } - else - { - user.acquireReadLock(); - try - { - cmd.run(user, command, commandLabel, args); - } - finally - { - user.unlock(); - } - } - return true; - } - catch (NoChargeException ex) - { - return true; - } - catch (NotEnoughArgumentsException ex) - { - sender.sendMessage(command.getDescription()); - sender.sendMessage(command.getUsage().replaceAll("", commandLabel)); - if (!ex.getMessage().isEmpty()) - { - sender.sendMessage(ex.getMessage()); - } - return true; - } - catch (Throwable ex) - { - showCommandError(sender, commandLabel, ex); - return true; - } - } - catch (Throwable ex) - { - LOGGER.log(Level.SEVERE, _("commandFailed", commandLabel), ex); - return true; - } - } - - @Override - public void showCommandError(final CommandSender sender, final String commandLabel, final Throwable exception) - { - sender.sendMessage(_("errorWithMessage", exception.getMessage())); - if (ess.getSettings().isDebug()) - { - LOGGER.log(Level.WARNING, _("errorCallingCommand", commandLabel), exception); - } - } - - @Override - public void onReload() - { - } - - public final void addPlugin(final Plugin plugin) - { - if (plugin.getDescription().getMain().contains("com.earth2me.essentials")) - { - return; - } - final List commands = PluginCommandYamlParser.parse(plugin); - final String pluginName = plugin.getDescription().getName().toLowerCase(Locale.ENGLISH); - - for (Command command : commands) - { - final PluginCommand pc = (PluginCommand)command; - final List labels = new ArrayList(pc.getAliases()); - labels.add(pc.getName()); - - PluginCommand reg = ess.getServer().getPluginCommand(pluginName + ":" + pc.getName().toLowerCase(Locale.ENGLISH)); - if (reg == null) - { - reg = ess.getServer().getPluginCommand(pc.getName().toLowerCase(Locale.ENGLISH)); - } - if (reg == null || !reg.getPlugin().equals(plugin)) - { - continue; - } - for (String label : labels) - { - List plugincommands = altcommands.get(label.toLowerCase(Locale.ENGLISH)); - if (plugincommands == null) - { - plugincommands = new ArrayList(); - altcommands.put(label.toLowerCase(Locale.ENGLISH), plugincommands); - } - boolean found = false; - for (PluginCommand pc2 : plugincommands) - { - if (pc2.getPlugin().equals(plugin)) - { - found = true; - } - } - if (!found) - { - plugincommands.add(reg); - } - } - } - } - - public void removePlugin(final Plugin plugin) - { - final Iterator>> iterator = altcommands.entrySet().iterator(); - while (iterator.hasNext()) - { - final Map.Entry> entry = iterator.next(); - final Iterator pcIterator = entry.getValue().iterator(); - while (pcIterator.hasNext()) - { - final PluginCommand pc = pcIterator.next(); - if (pc.getPlugin() == null || pc.getPlugin().equals(plugin)) - { - pcIterator.remove(); - } - } - if (entry.getValue().isEmpty()) - { - iterator.remove(); - } - } - } - - public PluginCommand getAlternative(final String label) - { - final List commands = altcommands.get(label); - if (commands == null || commands.isEmpty()) - { - return null; - } - if (commands.size() == 1) - { - return commands.get(0); - } - // return the first command that is not an alias - for (PluginCommand command : commands) - { - if (command.getName().equalsIgnoreCase(label)) - { - return command; - } - } - // return the first alias - return commands.get(0); - } - - public void executed(final String label, final String otherLabel) - { - if (ess.getSettings().isDebug()) - { - LOGGER.log(Level.INFO, "Essentials: Alternative command " + label + " found, using " + otherLabel); - } - disabledList.put(label, otherLabel); - } - - public Map disabledCommands() - { - return disabledList; - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/IEssentialsCommand.java b/Essentials/src/com/earth2me/essentials/commands/IEssentialsCommand.java deleted file mode 100644 index 97b5f2767..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/IEssentialsCommand.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IEssentialsModule; -import com.earth2me.essentials.api.IPermission; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import org.bukkit.command.Command; - - -public interface IEssentialsCommand extends IPermission -{ - void run(IUser user, Command cmd, String commandLabel, String[] args) - throws Exception; - - void run(CommandSender sender, Command cmd, String commandLabel, String[] args) - throws Exception; - - void init(IEssentials ess, String commandLabel); - - void setEssentialsModule(IEssentialsModule module); -} diff --git a/Essentials/src/com/earth2me/essentials/commands/NoChargeException.java b/Essentials/src/com/earth2me/essentials/commands/NoChargeException.java deleted file mode 100644 index bb0088792..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/NoChargeException.java +++ /dev/null @@ -1,10 +0,0 @@ -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 deleted file mode 100644 index 0c47b9893..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/NotEnoughArgumentsException.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.earth2me.essentials.commands; - - -public class NotEnoughArgumentsException extends Exception -{ - public NotEnoughArgumentsException() - { - super(""); - } - - public NotEnoughArgumentsException(final String string) - { - super(string); - } - - public NotEnoughArgumentsException(final Throwable ex) - { - super("", ex); - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/WarpNotFoundException.java b/Essentials/src/com/earth2me/essentials/commands/WarpNotFoundException.java deleted file mode 100644 index 6caea6dd2..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/WarpNotFoundException.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.earth2me.essentials.commands; - - -public class WarpNotFoundException extends Exception -{ - public WarpNotFoundException() - { - super(""); - } - - public WarpNotFoundException(String message) - { - super(message); - } -} - - diff --git a/Essentials/src/com/earth2me/essentials/craftbukkit/FakeExplosion.java b/Essentials/src/com/earth2me/essentials/craftbukkit/FakeExplosion.java deleted file mode 100644 index 934d94fa2..000000000 --- a/Essentials/src/com/earth2me/essentials/craftbukkit/FakeExplosion.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.earth2me.essentials.craftbukkit; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; -import net.minecraft.server.ChunkPosition; -import net.minecraft.server.Packet60Explosion; -import org.bukkit.Location; -import org.bukkit.Server; -import org.bukkit.block.Block; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.CraftWorld; -import org.bukkit.entity.Player; -import org.bukkit.event.entity.EntityExplodeEvent; - - -public class FakeExplosion -{ - public static void createExplosion(final EntityExplodeEvent event, final Server server, final Player[] players) - { - try - { - final Set set = new HashSet(event.blockList().size()); - final List blocksUnderPlayers = new ArrayList(players.length); - final Location loc = event.getLocation(); - for (Player player : players) - { - if (player.getWorld().equals(loc.getWorld())) - { - blocksUnderPlayers.add(new ChunkPosition(player.getLocation().getBlockX(), player.getLocation().getBlockY() - 1, player.getLocation().getBlockZ())); - } - } - for (Block block : event.blockList()) - { - final ChunkPosition cp = new ChunkPosition(block.getX(), block.getY(), block.getZ()); - if (!blocksUnderPlayers.contains(cp)) - { - set.add(cp); - } - } - ((CraftServer)server).getHandle().sendPacketNearby(loc.getX(), loc.getY(), loc.getZ(), 64.0, ((CraftWorld)loc.getWorld()).getHandle().worldProvider.dimension, new Packet60Explosion(loc.getX(), loc.getY(), loc.getZ(), 3.0F, set)); - } - catch (Throwable ex) - { - Logger.getLogger("Minecraft").log(Level.SEVERE, null, ex); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/craftbukkit/FakeInventory.java b/Essentials/src/com/earth2me/essentials/craftbukkit/FakeInventory.java deleted file mode 100644 index 01e7bd5b2..000000000 --- a/Essentials/src/com/earth2me/essentials/craftbukkit/FakeInventory.java +++ /dev/null @@ -1,225 +0,0 @@ -package com.earth2me.essentials.craftbukkit; - -import java.util.HashMap; -import java.util.List; -import java.util.ListIterator; -import org.bukkit.Material; -import org.bukkit.entity.HumanEntity; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.ItemStack; - - -public class FakeInventory implements Inventory -{ - ItemStack[] items; - - public FakeInventory(ItemStack[] items) - { - this.items = new ItemStack[items.length]; - for (int i = 0; i < items.length; i++) - { - if (items[i] == null) - { - continue; - } - this.items[i] = items[i].clone(); - } - } - - @Override - public int getSize() - { - return items.length; - } - - @Override - public String getName() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public ItemStack getItem(int i) - { - return items[i]; - } - - @Override - public void setItem(int i, ItemStack is) - { - items[i] = is; - } - - @Override - public HashMap addItem(ItemStack... iss) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public HashMap removeItem(ItemStack... iss) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public ItemStack[] getContents() - { - return items; - } - - @Override - public void setContents(ItemStack[] iss) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean contains(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean contains(Material mtrl) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean contains(ItemStack is) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean contains(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean contains(Material mtrl, int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean contains(ItemStack is, int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public HashMap all(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public HashMap all(Material mtrl) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public HashMap all(ItemStack is) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int first(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int first(Material mtrl) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int first(ItemStack is) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int firstEmpty() - { - for (int i = 0; i < items.length; i++) - { - if (items[i] == null || items[i].getTypeId() == 0) { - return i; - } - } - return -1; - } - - @Override - public void remove(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void remove(Material mtrl) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void remove(ItemStack is) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void clear(int i) - { - items[i] = null; - } - - @Override - public void clear() - { - for (int i = 0; i < items.length; i++) - { - items[i] = null; - } - } - - @Override - public List getViewers() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public String getTitle() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public InventoryType getType() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public InventoryHolder getHolder() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public ListIterator iterator() - { - 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 deleted file mode 100644 index a6d5d4fbc..000000000 --- a/Essentials/src/com/earth2me/essentials/craftbukkit/InventoryWorkaround.java +++ /dev/null @@ -1,322 +0,0 @@ -package com.earth2me.essentials.craftbukkit; - -import java.util.HashMap; -import java.util.Map; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; - -/* - * This class can be removed when https://github.com/Bukkit/CraftBukkit/pull/193 is accepted to CraftBukkit - */ - -public final class InventoryWorkaround -{ - private InventoryWorkaround() - { - } - - public static int first(final Inventory inventory, final ItemStack item, final boolean forceDurability, final boolean forceAmount, final boolean forceEnchantments) - { - return next(inventory, item, 0, forceDurability, forceAmount, forceEnchantments); - } - - public static int next(final Inventory cinventory, final ItemStack item, final int start, final boolean forceDurability, final boolean forceAmount, final boolean forceEnchantments) - { - final ItemStack[] inventory = cinventory.getContents(); - for (int i = start; i < inventory.length; i++) - { - final ItemStack cItem = inventory[i]; - if (cItem == null) - { - continue; - } - if (item.getTypeId() == cItem.getTypeId() && (!forceAmount || item.getAmount() == cItem.getAmount()) && (!forceDurability || cItem.getDurability() == item.getDurability()) && (!forceEnchantments || cItem.getEnchantments().equals(item.getEnchantments()))) - { - return i; - } - } - return -1; - } - - public static int firstPartial(final Inventory cinventory, final ItemStack item, final boolean forceDurability) - { - return firstPartial(cinventory, item, forceDurability, item.getType().getMaxStackSize()); - } - - public static int firstPartial(final Inventory cinventory, final ItemStack item, final boolean forceDurability, final int maxAmount) - { - if (item == null) - { - return -1; - } - final ItemStack[] inventory = cinventory.getContents(); - for (int i = 0; i < inventory.length; i++) - { - final ItemStack cItem = inventory[i]; - if (cItem == null) - { - continue; - } - if (item.getTypeId() == cItem.getTypeId() && cItem.getAmount() < maxAmount && (!forceDurability || cItem.getDurability() == item.getDurability()) && cItem.getEnchantments().equals(item.getEnchantments())) - { - return i; - } - } - return -1; - } - - public static boolean addAllItems(final Inventory cinventory, final boolean forceDurability, final ItemStack... items) - { - final Inventory fake = new FakeInventory(cinventory.getContents()); - if (addItem(fake, forceDurability, items).isEmpty()) - { - addItem(cinventory, forceDurability, items); - return true; - } - else - { - return false; - } - } - - public static Map addItem(final Inventory cinventory, final boolean forceDurability, final ItemStack... items) - { - return addItem(cinventory, forceDurability, 0, items); - } - - public static Map addItem(final Inventory cinventory, final boolean forceDurability, final int oversizedStacks, final ItemStack... items) - { - final Map leftover = new HashMap(); - - /* - * TODO: some optimization - Create a 'firstPartial' with a 'fromIndex' - Record the lastPartial per Material - - * Cache firstEmpty result - */ - - // combine items - - ItemStack[] combined = new ItemStack[items.length]; - for (int i = 0; i < items.length; i++) - { - if (items[i] == null || items[i].getAmount() < 1) - { - continue; - } - for (int j = 0; j < combined.length; j++) - { - if (combined[j] == null) - { - combined[j] = items[i].clone(); - break; - } - if (combined[j].getTypeId() == items[i].getTypeId() && (!forceDurability || combined[j].getDurability() == items[i].getDurability()) && combined[j].getEnchantments().equals(items[i].getEnchantments())) - { - combined[j].setAmount(combined[j].getAmount() + items[i].getAmount()); - break; - } - } - } - - - for (int i = 0; i < combined.length; i++) - { - final ItemStack item = combined[i]; - if (item == null) - { - continue; - } - - while (true) - { - // Do we already have a stack of it? - final int maxAmount = oversizedStacks > item.getType().getMaxStackSize() ? oversizedStacks : item.getType().getMaxStackSize(); - final int firstPartial = firstPartial(cinventory, item, forceDurability, maxAmount); - - // Drat! no partial stack - if (firstPartial == -1) - { - // Find a free spot! - final int firstFree = cinventory.firstEmpty(); - - if (firstFree == -1) - { - // No space at all! - leftover.put(i, item); - break; - } - else - { - // More than a single stack! - if (item.getAmount() > maxAmount) - { - final ItemStack stack = item.clone(); - stack.setAmount(maxAmount); - cinventory.setItem(firstFree, stack); - item.setAmount(item.getAmount() - maxAmount); - } - else - { - // Just store it - cinventory.setItem(firstFree, item); - break; - } - } - } - else - { - // So, apparently it might only partially fit, well lets do just that - final ItemStack partialItem = cinventory.getItem(firstPartial); - - final int amount = item.getAmount(); - final int partialAmount = partialItem.getAmount(); - - // Check if it fully fits - if (amount + partialAmount <= maxAmount) - { - partialItem.setAmount(amount + partialAmount); - break; - } - - // It fits partially - partialItem.setAmount(maxAmount); - item.setAmount(amount + partialAmount - maxAmount); - } - } - } - return leftover; - } - - public static Map removeItem(final Inventory cinventory, final boolean forceDurability, final boolean forceEnchantments, final ItemStack... items) - { - final Map leftover = new HashMap(); - - // TODO: optimization - - for (int i = 0; i < items.length; i++) - { - final ItemStack item = items[i]; - if (item == null) - { - continue; - } - int toDelete = item.getAmount(); - - while (true) - { - - // Bail when done - if (toDelete <= 0) - { - break; - } - - // get first Item, ignore the amount - final int first = first(cinventory, item, forceDurability, false, forceEnchantments); - - // Drat! we don't have this type in the inventory - if (first == -1) - { - item.setAmount(toDelete); - leftover.put(i, item); - break; - } - else - { - final ItemStack itemStack = cinventory.getItem(first); - final int amount = itemStack.getAmount(); - - if (amount <= toDelete) - { - toDelete -= amount; - // clear the slot, all used up - cinventory.clear(first); - } - else - { - // split the stack and store - itemStack.setAmount(amount - toDelete); - cinventory.setItem(first, itemStack); - toDelete = 0; - } - } - } - } - return leftover; - } - - public static boolean containsItem(final Inventory cinventory, final boolean forceDurability, final boolean forceEnchantments, final ItemStack... items) - { - final Map leftover = new HashMap(); - - // TODO: optimization - - // combine items - - ItemStack[] combined = new ItemStack[items.length]; - for (int i = 0; i < items.length; i++) - { - if (items[i] == null) - { - continue; - } - for (int j = 0; j < combined.length; j++) - { - if (combined[j] == null) - { - combined[j] = items[i].clone(); - break; - } - if (combined[j].getTypeId() == items[i].getTypeId() && (!forceDurability || combined[j].getDurability() == items[i].getDurability()) && (!forceEnchantments || combined[j].getEnchantments().equals(items[i].getEnchantments()))) - { - combined[j].setAmount(combined[j].getAmount() + items[i].getAmount()); - break; - } - } - } - - for (int i = 0; i < combined.length; i++) - { - final ItemStack item = combined[i]; - if (item == null) - { - continue; - } - int mustHave = item.getAmount(); - int position = 0; - - while (true) - { - // Bail when done - if (mustHave <= 0) - { - break; - } - - final int slot = next(cinventory, item, position, forceDurability, false, forceEnchantments); - - // Drat! we don't have this type in the inventory - if (slot == -1) - { - leftover.put(i, item); - break; - } - else - { - final ItemStack itemStack = cinventory.getItem(slot); - final int amount = itemStack.getAmount(); - - if (amount <= mustHave) - { - mustHave -= amount; - } - else - { - mustHave = 0; - } - position = slot + 1; - } - } - } - return leftover.isEmpty(); - } -} diff --git a/Essentials/src/com/earth2me/essentials/craftbukkit/SetExpFix.java b/Essentials/src/com/earth2me/essentials/craftbukkit/SetExpFix.java deleted file mode 100644 index d4db5d1a8..000000000 --- a/Essentials/src/com/earth2me/essentials/craftbukkit/SetExpFix.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.earth2me.essentials.craftbukkit; - -import org.bukkit.entity.Player; - - -public class SetExpFix -{ - public static void setTotalExperience(final IPlayer player, final int exp) - { - if (exp < 0) - { - throw new IllegalArgumentException("Experience is negative!"); - } - player.setExp(0); - player.setLevel(0); - player.setTotalExperience(0); - int amount = exp; - while (amount > 0) - { - final int expToLevel = getExpToLevel(player); - amount -= expToLevel; - if (amount >= 0) - { - // give until next level - player.giveExp(expToLevel); - } - else - { - // give the rest - amount += expToLevel; - player.giveExp(amount); - amount = 0; - } - } - } - - private static int getExpToLevel(final IPlayer player) - { - return getExpToLevel(player.getLevel()); - } - - private static int getExpToLevel(final int level) - { - return 7 + (level * 7 >> 1); - } - - public static int getTotalExperience(final IPlayer player) - { - int exp = (int) (getExpToLevel(player) * player.getExp()); - int currentLevel = player.getLevel(); - - while (currentLevel > 0) { - currentLevel--; - exp += getExpToLevel(currentLevel); - } - return exp; - } -} diff --git a/Essentials/src/com/earth2me/essentials/economy/Economy.java b/Essentials/src/com/earth2me/essentials/economy/Economy.java deleted file mode 100644 index 12bc9414c..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/Economy.java +++ /dev/null @@ -1,207 +0,0 @@ -package com.earth2me.essentials.economy; - -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.*; -import com.earth2me.essentials.permissions.Permissions; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - - -public class Economy implements IEconomy -{ - private final IEssentials ess; - private final MoneyHolder npcs; - - public Economy(IEssentials ess) - { - this.ess = ess; - this.npcs = new MoneyHolder(ess); - } - - private double getNPCBalance(String name) throws UserDoesNotExistException - { - npcs.acquireReadLock(); - try - { - Map balances = npcs.getData().getBalances(); - if (balances == null) - { - throw new UserDoesNotExistException(name); - } - Double balance = npcs.getData().getBalances().get(name.toLowerCase(Locale.ENGLISH)); - if (balance == null) - { - throw new UserDoesNotExistException(name); - } - return balance; - } - finally - { - npcs.unlock(); - } - } - - private void setNPCBalance(String name, double balance, boolean checkExistance) throws UserDoesNotExistException - { - npcs.acquireWriteLock(); - try - { - Map balances = npcs.getData().getBalances(); - if (balances == null) - { - balances = new HashMap(); - npcs.getData().setBalances(balances); - } - if (checkExistance && !balances.containsKey(name.toLowerCase(Locale.ENGLISH))) - { - throw new UserDoesNotExistException(name); - } - balances.put(name.toLowerCase(Locale.ENGLISH), balance); - } - finally - { - npcs.unlock(); - } - } - - private double getStartingBalance() - { - double startingBalance = 0; - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - try - { - startingBalance = settings.getData().getEconomy().getStartingBalance(); - } - finally - { - settings.unlock(); - } - return startingBalance; - } - - @Override - public void onReload() - { - this.npcs.onReload(false); - } - - @Override - public double getMoney(String name) throws UserDoesNotExistException - { - IUser user = ess.getUser(name); - if (user == null) - { - return getNPCBalance(name); - } - return user.getMoney(); - } - - @Override - public void setMoney(String name, double balance) throws NoLoanPermittedException, UserDoesNotExistException - { - IUser user = ess.getUser(name); - if (user == null) - { - setNPCBalance(name, balance, true); - return; - } - if (balance < 0.0 && !Permissions.ECO_LOAN.isAuthorized(user)) - { - throw new NoLoanPermittedException(); - } - user.setMoney(balance); - } - - @Override - public void resetBalance(String name) throws NoLoanPermittedException, UserDoesNotExistException - { - setMoney(name, getStartingBalance()); - } - - @Override - public String format(double amount) - { - return Util.displayCurrency(amount, ess); - } - - @Override - public boolean playerExists(String name) - { - try - { - getMoney(name); - return true; - } - catch (UserDoesNotExistException ex) - { - return false; - } - } - - @Override - public boolean isNPC(String name) throws UserDoesNotExistException - { - boolean result = ess.getUser(name) == null; - if (result) - { - getNPCBalance(name); - } - return result; - } - - @Override - public boolean createNPC(String name) - { - try - { - if (isNPC(name)) - { - - setNPCBalance(name, getStartingBalance(), false); - return true; - } - } - catch (UserDoesNotExistException ex) - { - try - { - setNPCBalance(name, getStartingBalance(), false); - return true; - } - catch (UserDoesNotExistException ex1) - { - //This should never happen! - } - } - return false; - } - - @Override - public void removeNPC(String name) throws UserDoesNotExistException - { - npcs.acquireWriteLock(); - try - { - Map balances = npcs.getData().getBalances(); - if (balances == null) - { - balances = new HashMap(); - npcs.getData().setBalances(balances); - } - if (balances.containsKey(name.toLowerCase(Locale.ENGLISH))) - { - balances.remove(name.toLowerCase(Locale.ENGLISH)); - } - else - { - throw new UserDoesNotExistException(name); - } - } - finally - { - npcs.unlock(); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/economy/Money.java b/Essentials/src/com/earth2me/essentials/economy/Money.java deleted file mode 100644 index ff081e609..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/Money.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.earth2me.essentials.economy; - -import com.earth2me.essentials.storage.MapValueType; -import com.earth2me.essentials.storage.StorageObject; -import java.util.HashMap; -import java.util.Map; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Money implements StorageObject -{ - @MapValueType(Double.class) - private Map balances = new HashMap(); -} diff --git a/Essentials/src/com/earth2me/essentials/economy/MoneyHolder.java b/Essentials/src/com/earth2me/essentials/economy/MoneyHolder.java deleted file mode 100644 index 6adfa6c2d..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/MoneyHolder.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.earth2me.essentials.economy; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.storage.AsyncStorageObjectHolder; -import java.io.File; -import java.io.IOException; - - -public class MoneyHolder extends AsyncStorageObjectHolder -{ - public MoneyHolder(IEssentials ess) - { - super(ess, Money.class); - onReload(); - } - - @Override - public File getStorageFile() throws IOException - { - return new File(ess.getPlugin().getDataFolder(), "economy_npcs.yml"); - } -} diff --git a/Essentials/src/com/earth2me/essentials/economy/Trade.java b/Essentials/src/com/earth2me/essentials/economy/Trade.java deleted file mode 100644 index 2e217580d..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/Trade.java +++ /dev/null @@ -1,333 +0,0 @@ -package com.earth2me.essentials.economy; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.ChargeException; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.ItemStack; -import com.earth2me.essentials.api.server.Location; -import com.earth2me.essentials.permissions.NoCommandCostPermissions; -import com.earth2me.essentials.permissions.Permissions; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.text.DateFormat; -import java.util.Date; -import java.util.Locale; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; -import lombok.Cleanup; - - - -public class Trade -{ - private final transient String command; - private final transient Double money; - private final transient ItemStack itemStack; - private final transient Integer exp; - private final transient IEssentials ess; - - public Trade(final String command, final IEssentials ess) - { - this(command, null, null, null, ess); - } - - public Trade(final double money, final IEssentials ess) - { - this(null, money, null, null, ess); - } - - public Trade(final ItemStack items, final IEssentials ess) - { - this(null, null, items, null, ess); - } - - public Trade(final int exp, final IEssentials ess) - { - this(null, null, null, exp, ess); - } - - private Trade(final String command, final Double money, final ItemStack item, final Integer exp, final IEssentials ess) - { - this.command = command; - this.money = money; - this.itemStack = item; - this.exp = exp; - this.ess = ess; - } - - public void isAffordableFor(final IUser user) throws ChargeException - { - final double mon = user.getMoney(); - if (getMoney() != null - && mon < getMoney() - && getMoney() > 0 - && !Permissions.ECO_LOAN.isAuthorized(user)) - { - throw new ChargeException(_("notEnoughMoney")); - } - - if (getItemStack() != null - && !user.getInventory().containsItem(true, true, itemStack)) - { - throw new ChargeException(_("missingItems", getItemStack().getAmount(), getItemStack().getType().toString().toLowerCase(Locale.ENGLISH).replace("_", " "))); - } - - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - - if (command != null && !command.isEmpty() - && !NoCommandCostPermissions.getPermission(command).isAuthorized(user) - && mon < settings.getData().getEconomy().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command) - && 0 < settings.getData().getEconomy().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command) - && !Permissions.ECO_LOAN.isAuthorized(user)) - { - throw new ChargeException(_("notEnoughMoney")); - } - - if (exp != null && exp > 0 - && user.getTotalExperience() < exp) - { - throw new ChargeException(_("notEnoughExperience")); - } - } - - public void pay(final IUser user) - { - pay(user, true); - } - - public boolean pay(final IUser user, final boolean dropItems) - { - boolean success = true; - if (getMoney() != null && getMoney() > 0) - { - user.giveMoney(getMoney()); - } - if (getItemStack() != null) - { - if (dropItems) - { - final Map leftOver = user.getInventory().addItem(true, getItemStack()); - final Location loc = user.getLocation(); - for (ItemStack dropStack : leftOver.values()) - { - final int maxStackSize = dropStack.getType().getMaxStackSize(); - final int stacks = dropStack.getAmount() / maxStackSize; - final int leftover = dropStack.getAmount() % maxStackSize; - final ItemStack[] itemStacks = new ItemStack[stacks + (leftover > 0 ? 1 : 0)]; - for (int i = 0; i < stacks; i++) - { - final ItemStack stack = dropStack.clone(); - stack.setAmount(maxStackSize); - itemStacks[i] = user.getWorld().dropItem(loc, stack); - } - if (leftover > 0) - { - final ItemStack stack = dropStack.clone(); - stack.setAmount(leftover); - itemStacks[stacks] = user.getWorld().dropItem(loc, stack); - } - } - } - else - { - success = user.getInventory().addAllItems(true, getItemStack()); - } - user.updateInventory(); - } - if (getExperience() != null) - { - user.setTotalExperience(user.getTotalExperience() + getExperience()); - } - return success; - } - - public void charge(final IUser user) throws ChargeException - { - if (getMoney() != null) - { - if (!user.canAfford(getMoney()) && getMoney() > 0) - { - throw new ChargeException(_("notEnoughMoney")); - } - user.takeMoney(getMoney()); - } - if (getItemStack() != null) - { - if (!user.getInventory().containsItem(true, true, itemStack)) - { - throw new ChargeException(_("missingItems", getItemStack().getAmount(), getItemStack().getType().toString().toLowerCase(Locale.ENGLISH).replace("_", " "))); - } - user.getInventory().removeItem(true, true, getItemStack()); - user.updateInventory(); - } - if (command != null && !command.isEmpty() - && !NoCommandCostPermissions.getPermission(command).isAuthorized(user)) - { - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - final double cost = settings.getData().getEconomy().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command); - if (!user.canAfford(cost) && cost > 0) - { - throw new ChargeException(_("notEnoughMoney")); - } - user.takeMoney(cost); - } - if (getExperience() != null) - { - final int experience = user.getTotalExperience(); - if (experience < getExperience() && getExperience() > 0) - { - throw new ChargeException(_("notEnoughExperience")); - } - user.setTotalExperience(experience - getExperience()); - } - } - - public Double getMoney() - { - return money; - } - - public ItemStack getItemStack() - { - return itemStack; - } - - public Integer getExperience() - { - return exp; - } - 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) - { - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - if (!settings.getData().getEconomy().isLogEnabled()) - { - return; - } - if (fw == null) - { - try - { - fw = new FileWriter(new File(ess.getPlugin().getDataFolder(), "trade.log"), true); - } - catch (IOException ex) - { - Logger.getLogger("Minecraft").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(settings.getData().getEconomy().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(settings.getData().getEconomy().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("Minecraft").log(Level.SEVERE, null, ex); - } - } - - public static void closeLog() - { - if (fw != null) - { - try - { - fw.close(); - } - catch (IOException ex) - { - Logger.getLogger("Minecraft").log(Level.SEVERE, null, ex); - } - fw = null; - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/economy/Worth.java b/Essentials/src/com/earth2me/essentials/economy/Worth.java deleted file mode 100644 index c8f6a39ae..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/Worth.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.earth2me.essentials.economy; - -import com.earth2me.essentials.storage.EnchantmentLevel; -import com.earth2me.essentials.storage.MapKeyType; -import com.earth2me.essentials.storage.MapValueType; -import com.earth2me.essentials.storage.StorageObject; -import java.util.HashMap; -import java.util.Map; -import lombok.Data; -import lombok.EqualsAndHashCode; -import org.bukkit.Material; -import org.bukkit.material.MaterialData; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Worth implements StorageObject -{ - @MapKeyType(MaterialData.class) - @MapValueType(Double.class) - private Map sell = new HashMap(); - @MapKeyType(MaterialData.class) - @MapValueType(Double.class) - private Map buy = new HashMap(); - @MapKeyType(EnchantmentLevel.class) - @MapValueType(Double.class) - private Map enchantmentMultiplier = new HashMap(); - - public Worth() - { - sell.put(new MaterialData(Material.APPLE, (byte)0), 1.0); - } -} diff --git a/Essentials/src/com/earth2me/essentials/economy/WorthHolder.java b/Essentials/src/com/earth2me/essentials/economy/WorthHolder.java deleted file mode 100644 index c49c705f0..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/WorthHolder.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.earth2me.essentials.economy; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IWorth; -import com.earth2me.essentials.api.server.ItemStack; -import com.earth2me.essentials.storage.AsyncStorageObjectHolder; -import com.earth2me.essentials.storage.EnchantmentLevel; -import java.io.File; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.material.MaterialData; - - -public class WorthHolder extends AsyncStorageObjectHolder implements IWorth -{ - public WorthHolder(final IEssentials ess) - { - super(ess, com.earth2me.essentials.economy.Worth.class); - onReload(false); - } - - @Override - public double getPrice(final ItemStack itemStack) - { - this.acquireReadLock(); - try - { - final Map prices = this.getData().getSell(); - if (prices == null || itemStack == null) - { - return Double.NaN; - } - final Double basePrice = prices.get(itemStack.getData()); - if (basePrice == null || Double.isNaN(basePrice)) - { - return Double.NaN; - } - double multiplier = 1.0; - if (itemStack.getType().getMaxDurability() > 0) { - multiplier *= (double)itemStack.getDurability() / (double)itemStack.getType().getMaxDurability(); - } - if (itemStack.getEnchantments() != null && !itemStack.getEnchantments().isEmpty()) - { - final Map enchantmentMultipliers = this.getData().getEnchantmentMultiplier(); - if (enchantmentMultipliers != null) - { - for (Map.Entry entry : itemStack.getEnchantments().entrySet()) - { - final Double enchMult = enchantmentMultipliers.get(new EnchantmentLevel(entry.getKey(), entry.getValue())); - if (enchMult != null) - { - multiplier *= enchMult; - } - } - } - } - return basePrice * multiplier; - } - finally - { - this.unlock(); - } - } - - @Override - public void setPrice(final ItemStack itemStack, final double price) - { - acquireWriteLock(); - try { - if (getData().getSell() == null) { - getData().setSell(new HashMap()); - } - getData().getSell().put(itemStack.getData(), price); - } finally { - unlock(); - } - } - - @Override - public File getStorageFile() throws IOException - { - return new File(ess.getPlugin().getDataFolder(), "worth.yml"); - } -} diff --git a/Essentials/src/com/earth2me/essentials/economy/register/Method.java b/Essentials/src/com/earth2me/essentials/economy/register/Method.java deleted file mode 100644 index 2b22bfd3f..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/register/Method.java +++ /dev/null @@ -1,210 +0,0 @@ -package com.earth2me.essentials.economy.register; - -import org.bukkit.plugin.Plugin; - - -/** - * Interface to be implemented by a payment method. - * - * @author Nijikokun (@nijikokun) - * @copyright Copyright (C) 2011 - * @license AOL license - */ -public interface Method -{ - /** - * Encodes the Plugin into an Object disguised as the Plugin. If you want the original Plugin Class you must cast it - * to the correct Plugin, to do so you have to verify the name and or version then cast. - * - *
-	 *  if(method.getName().equalsIgnoreCase("iConomy"))
-	 *   iConomy plugin = ((iConomy)method.getPlugin());
- * - * @return - * Object - * @see #getName() - * @see #getVersion() - */ - public Object getPlugin(); - - /** - * Returns the actual name of this method. - * - * @return String Plugin name. - */ - public String getName(); - - /** - * Returns the actual version of this method. - * - * @return String Plugin version. - */ - public String getVersion(); - - /** - * Returns the amount of decimal places that get stored - * NOTE: it will return -1 if there is no rounding - * - * @return int for each decimal place - */ - public int fractionalDigits(); - - /** - * Formats amounts into this payment methods style of currency display. - * - * @param amount Double - * @return String - Formatted Currency Display. - */ - public String format(double amount); - - /** - * Allows the verification of bank API existence in this payment method. - * - * @return boolean - */ - public boolean hasBanks(); - - /** - * Determines the existence of a bank via name. - * - * @param bank Bank name - * @return boolean - * @see #hasBanks - */ - public boolean hasBank(String bank); - - /** - * Determines the existence of an account via name. - * - * @param name Account name - * @return boolean - */ - public boolean hasAccount(String name); - - /** - * Check to see if an account name is tied to a bank. - * - * @param bank Bank name - * @param name Account name - * @return boolean - */ - public boolean hasBankAccount(String bank, String name); - - /** - * Forces an account creation - * - * @param name Account name - * @return boolean - */ - public boolean createAccount(String name); - - /** - * Forces an account creation - * - * @param name Account name - * @param balance Initial account balance - * @return boolean - */ - public boolean createAccount(String name, Double balance); - - /** - * Returns a MethodAccount class for an account name. - * - * @param name Account name - * @return MethodAccount or Null - */ - public MethodAccount getAccount(String name); - - /** - * Returns a MethodBankAccount class for an account name. - * - * @param bank Bank name - * @param name Account name - * @return MethodBankAccount or Null - */ - public MethodBankAccount getBankAccount(String bank, String name); - - /** - * Checks to verify the compatibility between this Method and a plugin. - * Internal usage only, for the most part. - * - * @param plugin Plugin - * @return boolean - */ - public boolean isCompatible(Plugin plugin); - - /** - * Set Plugin data. - * - * @param plugin Plugin - */ - public void setPlugin(Plugin plugin); - - - /** - * Contains Calculator and Balance functions for Accounts. - */ - public interface MethodAccount - { - public double balance(); - - public boolean set(double amount); - - public boolean add(double amount); - - public boolean subtract(double amount); - - public boolean multiply(double amount); - - public boolean divide(double amount); - - public boolean hasEnough(double amount); - - public boolean hasOver(double amount); - - public boolean hasUnder(double amount); - - public boolean isNegative(); - - public boolean remove(); - - @Override - public String toString(); - } - - - /** - * Contains Calculator and Balance functions for Bank Accounts. - */ - public interface MethodBankAccount - { - public double balance(); - - public String getBankName(); - - public int getBankId(); - - public boolean set(double amount); - - public boolean add(double amount); - - public boolean subtract(double amount); - - public boolean multiply(double amount); - - public boolean divide(double amount); - - public boolean hasEnough(double amount); - - public boolean hasOver(double amount); - - public boolean hasUnder(double amount); - - public boolean isNegative(); - - public boolean remove(); - - @Override - public String toString(); - } -} diff --git a/Essentials/src/com/earth2me/essentials/economy/register/Methods.java b/Essentials/src/com/earth2me/essentials/economy/register/Methods.java deleted file mode 100644 index eb3138473..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/register/Methods.java +++ /dev/null @@ -1,296 +0,0 @@ -package com.earth2me.essentials.economy.register; - -import java.util.HashSet; -import java.util.Set; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginManager; - - -/** - * The - * Methods initializes Methods that utilize the Method interface based on a "first come, first served" - * basis. - * - * Allowing you to check whether a payment method exists or not. - * - * Methods also allows you to set a preferred method of payment before it captures payment plugins in the initialization - * process. - * - * in - * bukkit.yml:
- *  economy:
- *      preferred: "iConomy"
- * 
- * - * @author: Nijikokun (@nijikokun) @copyright: Copyright (C) 2011 @license: AOL license - * - */ -public class Methods -{ - private static String version = null; - private static boolean self = false; - private static Method Method = null; - private static String preferred = ""; - private static Set Methods = new HashSet(); - private static Set Dependencies = new HashSet(); - private static Set Attachables = new HashSet(); - - static - { - _init(); - } - - /** - * Implement all methods along with their respective name & class. - */ - private static void _init() - { - addMethod("iConomy", new com.earth2me.essentials.economy.register.methods.iCo6()); - addMethod("iConomy", new com.earth2me.essentials.economy.register.methods.iCo5()); - addMethod("iConomy", new com.earth2me.essentials.economy.register.methods.iCo4()); - addMethod("BOSEconomy", new com.earth2me.essentials.economy.register.methods.BOSE6()); - addMethod("BOSEconomy", new com.earth2me.essentials.economy.register.methods.BOSE7()); - addMethod("Currency", new com.earth2me.essentials.economy.register.methods.MCUR()); - Dependencies.add("MultiCurrency"); - addMethod("Vault", new com.earth2me.essentials.economy.register.methods.VaultEco()); - } - - /** - * Used by the plugin to setup version - * - * @param v version - */ - public static void setVersion(String v) - { - version = v; - } - - /** - * Use to reset methods during disable - */ - public static void reset() - { - version = null; - self = false; - Method = null; - preferred = ""; - Attachables.clear(); - } - - /** - * Use to get version of Register plugin - * - * @return version - */ - public static String getVersion() - { - return version; - } - - /** - * 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(org.bukkit.plugin.Plugin) - */ - public static Set getDependencies() - { - return Dependencies; - } - - /** - * Interprets Plugin class data to verify whether it is compatible with an existing payment method to use for - * 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) - { - if (method.isCompatible(plugin)) - { - method.setPlugin(plugin); - return method; - } - } - - return null; - } - - private static void addMethod(String name, Method method) - { - Dependencies.add(name); - Methods.add(method); - } - - /** - * Verifies if Register has set a payment method for usage yet. - * - * @return - * boolean - * @see #setMethod(org.bukkit.plugin.Plugin) - * @see #checkDisabled(org.bukkit.plugin.Plugin) - */ - public static boolean hasMethod() - { - return (Method != null); - } - - /** - * Checks Plugin Class against a multitude of checks to verify it's usability as a payment method. - * - * @param PluginManager the plugin manager for the server - * @return - * boolean True on success, False on failure. - */ - public static boolean setMethod(PluginManager manager) - { - if (hasMethod()) - { - return true; - } - - if (self) - { - self = false; - return false; - } - - int count = 0; - boolean match = false; - Plugin plugin = null; - - for (String name : getDependencies()) - { - if (hasMethod()) - { - break; - } - - plugin = manager.getPlugin(name); - if (plugin == null || !plugin.isEnabled()) - { - continue; - } - - Method current = createMethod(plugin); - if (current == null) - { - continue; - } - - if (preferred.isEmpty()) - { - Method = current; - } - else - { - Attachables.add(current); - } - } - - if (!preferred.isEmpty()) - { - do - { - if (hasMethod()) - { - match = true; - } - else - { - for (Method attached : Attachables) - { - if (attached == null) - { - continue; - } - - if (hasMethod()) - { - match = true; - break; - } - - if (preferred.isEmpty()) - { - Method = attached; - } - - if (count == 0) - { - if (preferred.equalsIgnoreCase(attached.getName())) - { - Method = attached; - } - else - { - Method = attached; - } - } - } - - count++; - } - } - while (!match); - } - - return hasMethod(); - } - - /** - * Sets the preferred economy - * - * @return - * boolean - */ - public static boolean setPreferred(String check) - { - if (getDependencies().contains(check)) - { - preferred = check; - return true; - } - - return false; - } - - /** - * Grab the existing and initialized (hopefully) Method Class. - * - * @return - * Method or - * Null - */ - public static Method getMethod() - { - return Method; - } - - /** - * Verify is a plugin is disabled, only does this if we there is an existing payment method initialized in Register. - * - * @param method Plugin data from bukkit, Internal Class file. - * @return - * boolean - */ - public static boolean checkDisabled(Plugin method) - { - if (!hasMethod()) - { - return true; - } - - if (Method.isCompatible(method)) - { - Method = null; - } - - return (Method == null); - } -} diff --git a/Essentials/src/com/earth2me/essentials/economy/register/methods/BOSE6.java b/Essentials/src/com/earth2me/essentials/economy/register/methods/BOSE6.java deleted file mode 100644 index 0fd7bb167..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/register/methods/BOSE6.java +++ /dev/null @@ -1,329 +0,0 @@ -package com.earth2me.essentials.economy.register.methods; - -import com.earth2me.essentials.economy.register.Method; -import cosine.boseconomy.BOSEconomy; -import org.bukkit.plugin.Plugin; - - -/** - * BOSEconomy 6 Implementation of Method - * - * @author Nijikokun (@nijikokun) - * @copyright (c) 2011 - * @license AOL license - */ -@SuppressWarnings("deprecation") -public class BOSE6 implements Method -{ - private BOSEconomy BOSEconomy; - - @Override - public BOSEconomy getPlugin() - { - return this.BOSEconomy; - } - - @Override - public String getName() - { - return "BOSEconomy"; - } - - @Override - public String getVersion() - { - return "0.6.2"; - } - - @Override - public int fractionalDigits() - { - return 0; - } - - @Override - public String format(double amount) - { - String currency = this.BOSEconomy.getMoneyNamePlural(); - - if (amount == 1) - { - currency = this.BOSEconomy.getMoneyName(); - } - - return amount + " " + currency; - } - - @Override - public boolean hasBanks() - { - return true; - } - - @Override - public boolean hasBank(String bank) - { - return this.BOSEconomy.bankExists(bank); - } - - @Override - public boolean hasAccount(String name) - { - return this.BOSEconomy.playerRegistered(name, false); - } - - @Override - public boolean hasBankAccount(String bank, String name) - { - return this.BOSEconomy.isBankOwner(bank, name) - || this.BOSEconomy.isBankMember(bank, name); - } - - @Override - public boolean createAccount(String name) - { - if (hasAccount(name)) - { - return false; - } - - this.BOSEconomy.registerPlayer(name); - return true; - } - - @Override - public boolean createAccount(String name, Double balance) - { - if (hasAccount(name)) - { - return false; - } - - this.BOSEconomy.registerPlayer(name); - this.BOSEconomy.setPlayerMoney(name, balance, false); - return true; - } - - @Override - public MethodAccount getAccount(String name) - { - if (!hasAccount(name)) - { - return null; - } - - return new BOSEAccount(name, this.BOSEconomy); - } - - @Override - public MethodBankAccount getBankAccount(String bank, String name) - { - if (!hasBankAccount(bank, name)) - { - return null; - } - - return new BOSEBankAccount(bank, BOSEconomy); - } - - @Override - public boolean isCompatible(Plugin plugin) - { - return plugin.getDescription().getName().equalsIgnoreCase("boseconomy") - && plugin instanceof BOSEconomy - && plugin.getDescription().getVersion().equals("0.6.2"); - } - - @Override - public void setPlugin(Plugin plugin) - { - BOSEconomy = (BOSEconomy)plugin; - } - - - public class BOSEAccount implements MethodAccount - { - private final String name; - private final BOSEconomy BOSEconomy; - - public BOSEAccount(String name, BOSEconomy bOSEconomy) - { - this.name = name; - this.BOSEconomy = bOSEconomy; - } - - @Override - public double balance() - { - return (double)this.BOSEconomy.getPlayerMoney(this.name); - } - - @Override - public boolean set(double amount) - { - int IntAmount = (int)Math.ceil(amount); - return this.BOSEconomy.setPlayerMoney(this.name, IntAmount, false); - } - - @Override - public boolean add(double amount) - { - int IntAmount = (int)Math.ceil(amount); - return this.BOSEconomy.addPlayerMoney(this.name, IntAmount, false); - } - - @Override - public boolean subtract(double amount) - { - int IntAmount = (int)Math.ceil(amount); - int balance = (int)this.balance(); - return this.BOSEconomy.setPlayerMoney(this.name, (balance - IntAmount), false); - } - - @Override - public boolean multiply(double amount) - { - int IntAmount = (int)Math.ceil(amount); - int balance = (int)this.balance(); - return this.BOSEconomy.setPlayerMoney(this.name, (balance * IntAmount), false); - } - - @Override - public boolean divide(double amount) - { - int IntAmount = (int)Math.ceil(amount); - int balance = (int)this.balance(); - return this.BOSEconomy.setPlayerMoney(this.name, (balance / IntAmount), false); - } - - @Override - public boolean hasEnough(double amount) - { - return (this.balance() >= amount); - } - - @Override - public boolean hasOver(double amount) - { - return (this.balance() > amount); - } - - @Override - public boolean hasUnder(double amount) - { - return (this.balance() < amount); - } - - @Override - public boolean isNegative() - { - return (this.balance() < 0); - } - - @Override - public boolean remove() - { - return false; - } - } - - - public class BOSEBankAccount implements MethodBankAccount - { - private final String bank; - private final BOSEconomy BOSEconomy; - - public BOSEBankAccount(String bank, BOSEconomy bOSEconomy) - { - this.bank = bank; - this.BOSEconomy = bOSEconomy; - } - - @Override - public String getBankName() - { - return this.bank; - } - - @Override - public int getBankId() - { - return -1; - } - - @Override - public double balance() - { - return (double)this.BOSEconomy.getBankMoney(bank); - } - - @Override - public boolean set(double amount) - { - int IntAmount = (int)Math.ceil(amount); - return this.BOSEconomy.setBankMoney(bank, IntAmount, true); - } - - @Override - public boolean add(double amount) - { - int IntAmount = (int)Math.ceil(amount); - int balance = (int)this.balance(); - return this.BOSEconomy.setBankMoney(bank, (balance + IntAmount), false); - } - - @Override - public boolean subtract(double amount) - { - int IntAmount = (int)Math.ceil(amount); - int balance = (int)this.balance(); - return this.BOSEconomy.setBankMoney(bank, (balance - IntAmount), false); - } - - @Override - public boolean multiply(double amount) - { - int IntAmount = (int)Math.ceil(amount); - int balance = (int)this.balance(); - return this.BOSEconomy.setBankMoney(bank, (balance * IntAmount), false); - } - - @Override - public boolean divide(double amount) - { - int IntAmount = (int)Math.ceil(amount); - int balance = (int)this.balance(); - return this.BOSEconomy.setBankMoney(bank, (balance / IntAmount), false); - } - - @Override - public boolean hasEnough(double amount) - { - return (this.balance() >= amount); - } - - @Override - public boolean hasOver(double amount) - { - return (this.balance() > amount); - } - - @Override - public boolean hasUnder(double amount) - { - return (this.balance() < amount); - } - - @Override - public boolean isNegative() - { - return (this.balance() < 0); - } - - @Override - public boolean remove() - { - return this.BOSEconomy.removeBank(bank); - } - } -} \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/economy/register/methods/BOSE7.java b/Essentials/src/com/earth2me/essentials/economy/register/methods/BOSE7.java deleted file mode 100644 index aa06589d3..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/register/methods/BOSE7.java +++ /dev/null @@ -1,318 +0,0 @@ -package com.earth2me.essentials.economy.register.methods; - -import com.earth2me.essentials.economy.register.Method; -import cosine.boseconomy.BOSEconomy; -import org.bukkit.plugin.Plugin; - - -/** - * BOSEconomy 7 Implementation of Method - * - * @author Acrobot - * @author Nijikokun (@nijikokun) - * @copyright (c) 2011 - * @license AOL license - */ -public class BOSE7 implements Method -{ - private BOSEconomy BOSEconomy; - - @Override - public BOSEconomy getPlugin() - { - return this.BOSEconomy; - } - - @Override - public String getName() - { - return "BOSEconomy"; - } - - @Override - public String getVersion() - { - return "0.7.0"; - } - - @Override - public int fractionalDigits() - { - return this.BOSEconomy.getFractionalDigits(); - } - - @Override - public String format(double amount) - { - String currency = this.BOSEconomy.getMoneyNamePlural(); - - if (amount == 1) - { - currency = this.BOSEconomy.getMoneyName(); - } - - return amount + " " + currency; - } - - @Override - public boolean hasBanks() - { - return true; - } - - @Override - public boolean hasBank(String bank) - { - return this.BOSEconomy.bankExists(bank); - } - - @Override - public boolean hasAccount(String name) - { - return this.BOSEconomy.playerRegistered(name, false); - } - - @Override - public boolean hasBankAccount(String bank, String name) - { - return this.BOSEconomy.isBankOwner(bank, name) || this.BOSEconomy.isBankMember(bank, name); - } - - @Override - public boolean createAccount(String name) - { - if (hasAccount(name)) - { - return false; - } - - this.BOSEconomy.registerPlayer(name); - return true; - } - - @Override - public boolean createAccount(String name, Double balance) - { - if (hasAccount(name)) - { - return false; - } - - this.BOSEconomy.registerPlayer(name); - this.BOSEconomy.setPlayerMoney(name, balance, false); - return true; - } - - @Override - public MethodAccount getAccount(String name) - { - if (!hasAccount(name)) - { - return null; - } - - return new BOSEAccount(name, this.BOSEconomy); - } - - @Override - public MethodBankAccount getBankAccount(String bank, String name) - { - if (!hasBankAccount(bank, name)) - { - return null; - } - - return new BOSEBankAccount(bank, BOSEconomy); - } - - @Override - public boolean isCompatible(Plugin plugin) - { - return plugin.getDescription().getName().equalsIgnoreCase("boseconomy") - && plugin instanceof BOSEconomy - && !plugin.getDescription().getVersion().equals("0.6.2"); - } - - @Override - public void setPlugin(Plugin plugin) - { - BOSEconomy = (BOSEconomy)plugin; - } - - - public class BOSEAccount implements MethodAccount - { - private String name; - private BOSEconomy BOSEconomy; - - public BOSEAccount(String name, BOSEconomy bOSEconomy) - { - this.name = name; - this.BOSEconomy = bOSEconomy; - } - - @Override - public double balance() - { - return this.BOSEconomy.getPlayerMoneyDouble(this.name); - } - - @Override - public boolean set(double amount) - { - return this.BOSEconomy.setPlayerMoney(this.name, amount, false); - } - - @Override - public boolean add(double amount) - { - return this.BOSEconomy.addPlayerMoney(this.name, amount, false); - } - - @Override - public boolean subtract(double amount) - { - double balance = this.balance(); - return this.BOSEconomy.setPlayerMoney(this.name, (balance - amount), false); - } - - @Override - public boolean multiply(double amount) - { - double balance = this.balance(); - return this.BOSEconomy.setPlayerMoney(this.name, (balance * amount), false); - } - - @Override - public boolean divide(double amount) - { - double balance = this.balance(); - return this.BOSEconomy.setPlayerMoney(this.name, (balance / amount), false); - } - - @Override - public boolean hasEnough(double amount) - { - return (this.balance() >= amount); - } - - @Override - public boolean hasOver(double amount) - { - return (this.balance() > amount); - } - - @Override - public boolean hasUnder(double amount) - { - return (this.balance() < amount); - } - - @Override - public boolean isNegative() - { - return (this.balance() < 0); - } - - @Override - public boolean remove() - { - return false; - } - } - - - public class BOSEBankAccount implements MethodBankAccount - { - private String bank; - private BOSEconomy BOSEconomy; - - public BOSEBankAccount(String bank, BOSEconomy bOSEconomy) - { - this.bank = bank; - this.BOSEconomy = bOSEconomy; - } - - @Override - public String getBankName() - { - return this.bank; - } - - @Override - public int getBankId() - { - return -1; - } - - @Override - public double balance() - { - return this.BOSEconomy.getBankMoneyDouble(bank); - } - - @Override - public boolean set(double amount) - { - return this.BOSEconomy.setBankMoney(bank, amount, true); - } - - @Override - public boolean add(double amount) - { - double balance = this.balance(); - return this.BOSEconomy.setBankMoney(bank, (balance + amount), false); - } - - @Override - public boolean subtract(double amount) - { - double balance = this.balance(); - return this.BOSEconomy.setBankMoney(bank, (balance - amount), false); - } - - @Override - public boolean multiply(double amount) - { - double balance = this.balance(); - return this.BOSEconomy.setBankMoney(bank, (balance * amount), false); - } - - @Override - public boolean divide(double amount) - { - double balance = this.balance(); - return this.BOSEconomy.setBankMoney(bank, (balance / amount), false); - } - - @Override - public boolean hasEnough(double amount) - { - return (this.balance() >= amount); - } - - @Override - public boolean hasOver(double amount) - { - return (this.balance() > amount); - } - - @Override - public boolean hasUnder(double amount) - { - return (this.balance() < amount); - } - - @Override - public boolean isNegative() - { - return (this.balance() < 0); - } - - @Override - public boolean remove() - { - return this.BOSEconomy.removeBank(bank); - } - } -} \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/economy/register/methods/MCUR.java b/Essentials/src/com/earth2me/essentials/economy/register/methods/MCUR.java deleted file mode 100644 index 2c49c3233..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/register/methods/MCUR.java +++ /dev/null @@ -1,191 +0,0 @@ -package com.earth2me.essentials.economy.register.methods; - -import com.earth2me.essentials.economy.register.Method; -import me.ashtheking.currency.Currency; -import me.ashtheking.currency.CurrencyList; -import org.bukkit.plugin.Plugin; - - -/** - * MultiCurrency Method implementation. - * - * @author Acrobot - * @copyright (c) 2011 - * @license AOL license - */ -public class MCUR implements Method -{ - private Currency currencyList; - - @Override - public Object getPlugin() - { - return this.currencyList; - } - - @Override - public String getName() - { - return "MultiCurrency"; - } - - @Override - public String getVersion() - { - return "0.09"; - } - - @Override - public int fractionalDigits() - { - return -1; - } - - @Override - public String format(double amount) - { - return amount + " Currency"; - } - - @Override - public boolean hasBanks() - { - return false; - } - - @Override - public boolean hasBank(String bank) - { - return false; - } - - @Override - public boolean hasAccount(String name) - { - return true; - } - - @Override - public boolean hasBankAccount(String bank, String name) - { - return false; - } - - @Override - public boolean createAccount(String name) - { - CurrencyList.setValue((String)CurrencyList.maxCurrency(name)[0], name, 0); - return true; - } - - @Override - public boolean createAccount(String name, Double balance) - { - CurrencyList.setValue((String)CurrencyList.maxCurrency(name)[0], name, balance); - return true; - } - - @Override - public MethodAccount getAccount(String name) - { - return new MCurrencyAccount(name); - } - - @Override - public MethodBankAccount getBankAccount(String bank, String name) - { - return null; - } - - @Override - public boolean isCompatible(Plugin plugin) - { - return (plugin.getDescription().getName().equalsIgnoreCase("Currency") - || plugin.getDescription().getName().equalsIgnoreCase("MultiCurrency")) - && plugin instanceof Currency; - } - - @Override - public void setPlugin(Plugin plugin) - { - currencyList = (Currency)plugin; - } - - - public class MCurrencyAccount implements MethodAccount - { - private String name; - - public MCurrencyAccount(String name) - { - this.name = name; - } - - @Override - public double balance() - { - return CurrencyList.getValue((String)CurrencyList.maxCurrency(name)[0], name); - } - - @Override - public boolean set(double amount) - { - CurrencyList.setValue((String)CurrencyList.maxCurrency(name)[0], name, amount); - return true; - } - - @Override - public boolean add(double amount) - { - return CurrencyList.add(name, amount); - } - - @Override - public boolean subtract(double amount) - { - return CurrencyList.subtract(name, amount); - } - - @Override - public boolean multiply(double amount) - { - return CurrencyList.multiply(name, amount); - } - - @Override - public boolean divide(double amount) - { - return CurrencyList.divide(name, amount); - } - - @Override - public boolean hasEnough(double amount) - { - return CurrencyList.hasEnough(name, amount); - } - - @Override - public boolean hasOver(double amount) - { - return CurrencyList.hasOver(name, amount); - } - - @Override - public boolean hasUnder(double amount) - { - return CurrencyList.hasUnder(name, amount); - } - - @Override - public boolean isNegative() - { - return CurrencyList.isNegative(name); - } - - @Override - public boolean remove() - { - return CurrencyList.remove(name); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/economy/register/methods/VaultEco.java b/Essentials/src/com/earth2me/essentials/economy/register/methods/VaultEco.java deleted file mode 100644 index fe4c2f513..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/register/methods/VaultEco.java +++ /dev/null @@ -1,337 +0,0 @@ -package com.earth2me.essentials.economy.register.methods; - -import com.earth2me.essentials.economy.register.Method; -import net.milkbowl.vault.Vault; -import net.milkbowl.vault.economy.Economy; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.RegisteredServiceProvider; - - -public class VaultEco implements Method -{ - private Vault vault; - private Economy economy; - - @Override - public Vault getPlugin() - { - return this.vault; - } - - @Override - public boolean createAccount(String name, Double amount) - { - if (hasAccount(name)) - { - return false; - } - - return false; - } - - @Override - public String getName() - { - - return this.vault.getDescription().getName().concat(" - Economy: ").concat(economy == null ? "NoEco" : economy.getName()); - } - - @Override - public String getVersion() - { - return this.vault.getDescription().getVersion(); - } - - @Override - public int fractionalDigits() - { - return 0; - } - - @Override - public String format(double amount) - { - return this.economy.format(amount); - } - - @Override - public boolean hasBanks() - { - return this.economy.hasBankSupport(); - } - - @Override - public boolean hasBank(String bank) - { - return this.economy.getBanks().contains(bank); - } - - @Override - public boolean hasAccount(String name) - { - return this.economy.hasAccount(name); - } - - @Override - public boolean hasBankAccount(String bank, String name) - { - return this.economy.isBankOwner(bank, name).transactionSuccess() - || this.economy.isBankMember(bank, name).transactionSuccess(); - } - - @Override - public boolean createAccount(String name) - { - return this.economy.createBank(name, "").transactionSuccess(); - } - - public boolean createAccount(String name, double balance) - { - if (!this.economy.createBank(name, "").transactionSuccess()) - { - return false; - } - return this.economy.bankDeposit(name, balance).transactionSuccess(); - } - - @Override - public MethodAccount getAccount(String name) - { - if (!hasAccount(name)) - { - return null; - } - - return new VaultAccount(name, this.economy); - } - - @Override - public MethodBankAccount getBankAccount(String bank, String name) - { - if (!hasBankAccount(bank, name)) - { - return null; - } - - return new VaultBankAccount(bank, economy); - } - - @Override - public boolean isCompatible(Plugin plugin) - { - try - { - RegisteredServiceProvider ecoPlugin = plugin.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); - return plugin instanceof Vault && ecoPlugin != null && !ecoPlugin.getProvider().getName().equals("Essentials Economy"); - } - catch (LinkageError e) - { - return false; - } - catch (Exception e) - { - return false; - } - } - - @Override - public void setPlugin(Plugin plugin) - { - this.vault = (Vault)plugin; - RegisteredServiceProvider economyProvider = this.vault.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); - if (economyProvider != null) - { - this.economy = economyProvider.getProvider(); - } - } - - - public class VaultAccount implements MethodAccount - { - private final String name; - private final Economy economy; - - public VaultAccount(String name, Economy economy) - { - this.name = name; - this.economy = economy; - } - - @Override - public double balance() - { - return this.economy.getBalance(this.name); - } - - @Override - public boolean set(double amount) - { - if (!this.economy.withdrawPlayer(this.name, this.balance()).transactionSuccess()) - { - return false; - } - if (amount == 0) - { - return true; - } - return this.economy.depositPlayer(this.name, amount).transactionSuccess(); - } - - @Override - public boolean add(double amount) - { - return this.economy.depositPlayer(this.name, amount).transactionSuccess(); - } - - @Override - public boolean subtract(double amount) - { - return this.economy.withdrawPlayer(this.name, amount).transactionSuccess(); - } - - @Override - public boolean multiply(double amount) - { - double balance = this.balance(); - return this.set(balance * amount); - } - - @Override - public boolean divide(double amount) - { - double balance = this.balance(); - return this.set(balance / amount); - } - - @Override - public boolean hasEnough(double amount) - { - return (this.balance() >= amount); - } - - @Override - public boolean hasOver(double amount) - { - return (this.balance() > amount); - } - - @Override - public boolean hasUnder(double amount) - { - return (this.balance() < amount); - } - - @Override - public boolean isNegative() - { - return (this.balance() < 0); - } - - @Override - public boolean remove() - { - return this.set(0.0); - } - } - - - public class VaultBankAccount implements MethodBankAccount - { - private final String bank; - private final Economy economy; - - public VaultBankAccount(String bank, Economy economy) - { - this.bank = bank; - this.economy = economy; - } - - @Override - public String getBankName() - { - return this.bank; - } - - @Override - public int getBankId() - { - return -1; - } - - @Override - public double balance() - { - return this.economy.bankBalance(this.bank).balance; - } - - @Override - public boolean set(double amount) - { - if (!this.economy.bankWithdraw(this.bank, this.balance()).transactionSuccess()) - { - return false; - } - if (amount == 0) - { - return true; - } - return this.economy.bankDeposit(this.bank, amount).transactionSuccess(); - } - - @Override - public boolean add(double amount) - { - return this.economy.bankDeposit(this.bank, amount).transactionSuccess(); - } - - @Override - public boolean subtract(double amount) - { - return this.economy.bankWithdraw(this.bank, amount).transactionSuccess(); - } - - @Override - public boolean multiply(double amount) - { - double balance = this.balance(); - return this.set(balance * amount); - } - - @Override - public boolean divide(double amount) - { - double balance = this.balance(); - return this.set(balance / amount); - } - - @Override - public boolean hasEnough(double amount) - { - return (this.balance() >= amount); - } - - @Override - public boolean hasOver(double amount) - { - return (this.balance() > amount); - } - - @Override - public boolean hasUnder(double amount) - { - return (this.balance() < amount); - } - - @Override - public boolean isNegative() - { - return (this.balance() < 0); - } - - @Override - public boolean remove() - { - return this.set(0.0); - } - } -} \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/economy/register/methods/iCo4.java b/Essentials/src/com/earth2me/essentials/economy/register/methods/iCo4.java deleted file mode 100644 index 1d2aa111b..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/register/methods/iCo4.java +++ /dev/null @@ -1,251 +0,0 @@ -package com.earth2me.essentials.economy.register.methods; - -import com.earth2me.essentials.economy.register.Method; -import com.nijiko.coelho.iConomy.iConomy; -import com.nijiko.coelho.iConomy.system.Account; -import org.bukkit.plugin.Plugin; - - -/** - * iConomy 4 Implementation of Method - * - * @author Nijikokun (@nijikokun) - * @copyright (c) 2011 - * @license AOL license - */ -public class iCo4 implements Method -{ - private iConomy iConomy; - - @Override - public iConomy getPlugin() - { - return this.iConomy; - } - - @Override - public String getName() - { - return "iConomy"; - } - - @Override - public String getVersion() - { - return "4"; - } - - @Override - public int fractionalDigits() - { - return 2; - } - - @Override - public String format(double amount) - { - return com.nijiko.coelho.iConomy.iConomy.getBank().format(amount); - } - - @Override - public boolean hasBanks() - { - return false; - } - - @Override - public boolean hasBank(String bank) - { - return false; - } - - @Override - public boolean hasAccount(String name) - { - return com.nijiko.coelho.iConomy.iConomy.getBank().hasAccount(name); - } - - @Override - public boolean hasBankAccount(String bank, String name) - { - return false; - } - - @Override - public boolean createAccount(String name) - { - if (hasAccount(name)) - { - return false; - } - - try - { - com.nijiko.coelho.iConomy.iConomy.getBank().addAccount(name); - } - catch (Exception E) - { - return false; - } - - return true; - } - - @Override - public boolean createAccount(String name, Double balance) - { - if (hasAccount(name)) - { - return false; - } - - try - { - com.nijiko.coelho.iConomy.iConomy.getBank().addAccount(name, balance); - } - catch (Exception E) - { - return false; - } - - return true; - } - - @Override - public MethodAccount getAccount(String name) - { - return new iCoAccount(com.nijiko.coelho.iConomy.iConomy.getBank().getAccount(name)); - } - - @Override - public MethodBankAccount getBankAccount(String bank, String name) - { - return null; - } - - @Override - public boolean isCompatible(Plugin plugin) - { - return plugin.getDescription().getName().equalsIgnoreCase("iconomy") - && plugin.getClass().getName().equals("com.nijiko.coelho.iConomy.iConomy") - && plugin instanceof iConomy; - } - - @Override - public void setPlugin(Plugin plugin) - { - iConomy = (iConomy)plugin; - } - - - public class iCoAccount implements MethodAccount - { - private Account account; - - public iCoAccount(Account account) - { - this.account = account; - } - - public Account getiCoAccount() - { - return account; - } - - @Override - public double balance() - { - return this.account.getBalance(); - } - - @Override - public boolean set(double amount) - { - if (this.account == null) - { - return false; - } - this.account.setBalance(amount); - return true; - } - - @Override - public boolean add(double amount) - { - if (this.account == null) - { - return false; - } - this.account.add(amount); - return true; - } - - @Override - public boolean subtract(double amount) - { - if (this.account == null) - { - return false; - } - this.account.subtract(amount); - return true; - } - - @Override - public boolean multiply(double amount) - { - if (this.account == null) - { - return false; - } - this.account.multiply(amount); - return true; - } - - @Override - public boolean divide(double amount) - { - if (this.account == null) - { - return false; - } - this.account.divide(amount); - return true; - } - - @Override - public boolean hasEnough(double amount) - { - return this.account.hasEnough(amount); - } - - @Override - public boolean hasOver(double amount) - { - return this.account.hasOver(amount); - } - - @Override - public boolean hasUnder(double amount) - { - return (this.balance() < amount); - } - - @Override - public boolean isNegative() - { - return this.account.isNegative(); - } - - @Override - public boolean remove() - { - if (this.account == null) - { - return false; - } - this.account.remove(); - return true; - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/economy/register/methods/iCo5.java b/Essentials/src/com/earth2me/essentials/economy/register/methods/iCo5.java deleted file mode 100644 index 2b1c02dfe..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/register/methods/iCo5.java +++ /dev/null @@ -1,371 +0,0 @@ -package com.earth2me.essentials.economy.register.methods; - -import com.earth2me.essentials.economy.register.Method; -import com.iConomy.iConomy; -import com.iConomy.system.Account; -import com.iConomy.system.BankAccount; -import com.iConomy.system.Holdings; -import com.iConomy.util.Constants; -import org.bukkit.plugin.Plugin; - - -/** - * iConomy 5 Implementation of Method - * - * @author Nijikokun (@nijikokun) - * @copyright (c) 2011 - * @license AOL license - */ -public class iCo5 implements Method -{ - private iConomy iConomy; - - @Override - public iConomy getPlugin() - { - return this.iConomy; - } - - @Override - public String getName() - { - return "iConomy"; - } - - @Override - public String getVersion() - { - return "5"; - } - - @Override - public int fractionalDigits() - { - return 2; - } - - @Override - public String format(double amount) - { - return com.iConomy.iConomy.format(amount); - } - - @Override - public boolean hasBanks() - { - return Constants.Banking; - } - - @Override - public boolean hasBank(String bank) - { - return (hasBanks()) && com.iConomy.iConomy.Banks.exists(bank); - } - - @Override - public boolean hasAccount(String name) - { - return com.iConomy.iConomy.hasAccount(name); - } - - @Override - public boolean hasBankAccount(String bank, String name) - { - return (hasBank(bank)) && com.iConomy.iConomy.getBank(bank).hasAccount(name); - } - - @Override - public boolean createAccount(String name) - { - if (hasAccount(name)) - { - return false; - } - - return com.iConomy.iConomy.Accounts.create(name); - } - - @Override - public boolean createAccount(String name, Double balance) - { - if (hasAccount(name)) - { - return false; - } - - if (!com.iConomy.iConomy.Accounts.create(name)) - { - return false; - } - - getAccount(name).set(balance); - - return true; - } - - @Override - public MethodAccount getAccount(String name) - { - return new iCoAccount(com.iConomy.iConomy.getAccount(name)); - } - - @Override - public MethodBankAccount getBankAccount(String bank, String name) - { - return new iCoBankAccount(com.iConomy.iConomy.getBank(bank).getAccount(name)); - } - - @Override - public boolean isCompatible(Plugin plugin) - { - return plugin.getDescription().getName().equalsIgnoreCase("iconomy") - && plugin.getClass().getName().equals("com.iConomy.iConomy") - && plugin instanceof iConomy; - } - - @Override - public void setPlugin(Plugin plugin) - { - iConomy = (iConomy)plugin; - } - - - public class iCoAccount implements MethodAccount - { - private Account account; - private Holdings holdings; - - public iCoAccount(Account account) - { - this.account = account; - this.holdings = account.getHoldings(); - } - - public Account getiCoAccount() - { - return account; - } - - @Override - public double balance() - { - return this.holdings.balance(); - } - - @Override - public boolean set(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.set(amount); - return true; - } - - @Override - public boolean add(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.add(amount); - return true; - } - - @Override - public boolean subtract(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.subtract(amount); - return true; - } - - @Override - public boolean multiply(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.multiply(amount); - return true; - } - - @Override - public boolean divide(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.divide(amount); - return true; - } - - @Override - public boolean hasEnough(double amount) - { - return this.holdings.hasEnough(amount); - } - - @Override - public boolean hasOver(double amount) - { - return this.holdings.hasOver(amount); - } - - @Override - public boolean hasUnder(double amount) - { - return this.holdings.hasUnder(amount); - } - - @Override - public boolean isNegative() - { - return this.holdings.isNegative(); - } - - @Override - public boolean remove() - { - if (this.account == null) - { - return false; - } - this.account.remove(); - return true; - } - } - - - public class iCoBankAccount implements MethodBankAccount - { - private BankAccount account; - private Holdings holdings; - - public iCoBankAccount(BankAccount account) - { - this.account = account; - this.holdings = account.getHoldings(); - } - - public BankAccount getiCoBankAccount() - { - return account; - } - - @Override - public String getBankName() - { - return this.account.getBankName(); - } - - @Override - public int getBankId() - { - return this.account.getBankId(); - } - - @Override - public double balance() - { - return this.holdings.balance(); - } - - @Override - public boolean set(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.set(amount); - return true; - } - - @Override - public boolean add(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.add(amount); - return true; - } - - @Override - public boolean subtract(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.subtract(amount); - return true; - } - - @Override - public boolean multiply(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.multiply(amount); - return true; - } - - @Override - public boolean divide(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.divide(amount); - return true; - } - - @Override - public boolean hasEnough(double amount) - { - return this.holdings.hasEnough(amount); - } - - @Override - public boolean hasOver(double amount) - { - return this.holdings.hasOver(amount); - } - - @Override - public boolean hasUnder(double amount) - { - return this.holdings.hasUnder(amount); - } - - @Override - public boolean isNegative() - { - return this.holdings.isNegative(); - } - - @Override - public boolean remove() - { - if (this.account == null) - { - return false; - } - this.account.remove(); - return true; - } - } -} \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/economy/register/methods/iCo6.java b/Essentials/src/com/earth2me/essentials/economy/register/methods/iCo6.java deleted file mode 100644 index d615a4888..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/register/methods/iCo6.java +++ /dev/null @@ -1,237 +0,0 @@ -package com.earth2me.essentials.economy.register.methods; - -import com.earth2me.essentials.economy.register.Method; -import com.iCo6.iConomy; -import com.iCo6.system.Account; -import com.iCo6.system.Accounts; -import com.iCo6.system.Holdings; -import org.bukkit.plugin.Plugin; - - -/** - * iConomy 6 Implementation of Method - * - * @author Nijikokun (@nijikokun) - * @copyright (c) 2011 - * @license AOL license - */ -public class iCo6 implements Method -{ - private iConomy iConomy; - - @Override - public iConomy getPlugin() - { - return this.iConomy; - } - - @Override - public String getName() - { - return "iConomy"; - } - - @Override - public String getVersion() - { - return "6"; - } - - @Override - public int fractionalDigits() - { - return 2; - } - - @Override - public String format(double amount) - { - return com.iCo6.iConomy.format(amount); - } - - @Override - public boolean hasBanks() - { - return false; - } - - @Override - public boolean hasBank(String bank) - { - return false; - } - - @Override - public boolean hasAccount(String name) - { - return (new Accounts()).exists(name); - } - - @Override - public boolean hasBankAccount(String bank, String name) - { - return false; - } - - @Override - public boolean createAccount(String name) - { - if (hasAccount(name)) - { - return false; - } - - return (new Accounts()).create(name); - } - - @Override - public boolean createAccount(String name, Double balance) - { - if (hasAccount(name)) - { - return false; - } - - return (new Accounts()).create(name, balance); - } - - @Override - public MethodAccount getAccount(String name) - { - return new iCoAccount((new Accounts()).get(name)); - } - - @Override - public MethodBankAccount getBankAccount(String bank, String name) - { - return null; - } - - @Override - public boolean isCompatible(Plugin plugin) - { - return plugin.getDescription().getName().equalsIgnoreCase("iconomy") - && plugin.getClass().getName().equals("com.iCo6.iConomy") - && plugin instanceof iConomy; - } - - @Override - public void setPlugin(Plugin plugin) - { - iConomy = (iConomy)plugin; - } - - - public class iCoAccount implements MethodAccount - { - private Account account; - private Holdings holdings; - - public iCoAccount(Account account) - { - this.account = account; - this.holdings = account.getHoldings(); - } - - public Account getiCoAccount() - { - return account; - } - - @Override - public double balance() - { - return this.holdings.getBalance(); - } - - @Override - public boolean set(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.setBalance(amount); - return true; - } - - @Override - public boolean add(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.add(amount); - return true; - } - - @Override - public boolean subtract(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.subtract(amount); - return true; - } - - @Override - public boolean multiply(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.multiply(amount); - return true; - } - - @Override - public boolean divide(double amount) - { - if (this.holdings == null) - { - return false; - } - this.holdings.divide(amount); - return true; - } - - @Override - public boolean hasEnough(double amount) - { - return this.holdings.hasEnough(amount); - } - - @Override - public boolean hasOver(double amount) - { - return this.holdings.hasOver(amount); - } - - @Override - public boolean hasUnder(double amount) - { - return this.holdings.hasUnder(amount); - } - - @Override - public boolean isNegative() - { - return this.holdings.isNegative(); - } - - @Override - public boolean remove() - { - if (this.account == null) - { - return false; - } - this.account.remove(); - return true; - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/listener/EssentialsBlockListener.java b/Essentials/src/com/earth2me/essentials/listener/EssentialsBlockListener.java deleted file mode 100644 index 4b0dad5e5..000000000 --- a/Essentials/src/com/earth2me/essentials/listener/EssentialsBlockListener.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.earth2me.essentials.listener; - -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import org.bukkit.GameMode; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.inventory.ItemStack; - - -public class EssentialsBlockListener implements Listener -{ - private final transient IEssentials ess; - - public EssentialsBlockListener(final IEssentials ess) - { - super(); - this.ess = ess; - } - - @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onBlockPlace(final BlockPlaceEvent event) - { - // Do not rely on getItemInHand(); - // http://leaky.bukkit.org/issues/663 - final ItemStack itemstack = Util.convertBlockToItem(event.getBlockPlaced()); - if (itemstack == null) - { - return; - } - final IUser user = ess.getUser(event.getPlayer()); - final boolean unlimitedForUser = user.getData().hasUnlimited(itemstack.getType()); - if (unlimitedForUser && user.getGameMode() == GameMode.SURVIVAL) - { - ess.getPlugin().scheduleSyncDelayedTask( - new Runnable() - { - @Override - public void run() - { - user.getInventory().addItem(itemstack); - user.updateInventory(); - } - }); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/listener/EssentialsEntityListener.java b/Essentials/src/com/earth2me/essentials/listener/EssentialsEntityListener.java deleted file mode 100644 index 036da57d2..000000000 --- a/Essentials/src/com/earth2me/essentials/listener/EssentialsEntityListener.java +++ /dev/null @@ -1,138 +0,0 @@ -package com.earth2me.essentials.listener; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.Permissions; -import java.util.List; -import lombok.Cleanup; -import org.bukkit.Material; -import org.bukkit.entity.Animals; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; -import org.bukkit.event.entity.*; -import org.bukkit.inventory.ItemStack; - - -public class EssentialsEntityListener implements Listener -{ - private final transient IEssentials ess; - - public EssentialsEntityListener(final IEssentials ess) - { - this.ess = ess; - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onEntityDamage(final EntityDamageByEntityEvent event) - { - final Entity eAttack = event.getDamager(); - final Entity eDefend = event.getEntity(); - if (eDefend instanceof Player && eAttack instanceof Player) - { - @Cleanup - final IUser attacker = ess.getUser((Player)eAttack); - attacker.acquireReadLock(); - attacker.updateActivity(true); - final ItemStack itemstack = attacker.getItemInHand(); - final List commandList = attacker.getData().getPowertool(itemstack.getType()); - if (commandList != null && !commandList.isEmpty()) - { - for (String command : commandList) - { - if (command != null && !command.isEmpty()) - { - attacker.getServer().dispatchCommand(attacker, command.replaceAll("\\{player\\}", ((Player)eDefend).getName())); - event.setCancelled(true); - return; - } - } - } - } - else if (eDefend instanceof Animals && eAttack instanceof Player) - { - final Player player = (Player)eAttack; - final ItemStack hand = player.getItemInHand(); - if (hand != null && hand.getType() == Material.MILK_BUCKET) - { - ((Animals)eDefend).setBaby(); - hand.setType(Material.BUCKET); - player.setItemInHand(hand); - player.updateInventory(); - event.setCancelled(true); - } - } - } - - @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onEntityDamage(final EntityDamageEvent event) - { - if (event.getEntity() instanceof Player && ess.getUser((Player)event.getEntity()).isGodModeEnabled()) - { - final Player player = (Player)event.getEntity(); - player.setFireTicks(0); - player.setRemainingAir(player.getMaximumAir()); - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onEntityCombust(final EntityCombustEvent event) - { - if (event.getEntity() instanceof Player && ess.getUser((Player)event.getEntity()).isGodModeEnabled()) - { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onPlayerDeathEvent(final PlayerDeathEvent event) - { - final IUser user = ess.getUser((Player)event.getEntity()); - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - if (Permissions.BACK_ONDEATH.isAuthorized(user) && !settings.getData().getCommands().isDisabled("back")) - { - user.setLastLocation(); - user.sendMessage(_("backAfterDeath")); - } - if (!settings.getData().getGeneral().isDeathMessages()) - { - event.setDeathMessage(""); - } - } - - @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onFoodLevelChange(final FoodLevelChangeEvent event) - { - if (event.getEntity() instanceof Player && ess.getUser((Player)event.getEntity()).isGodModeEnabled()) - { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onEntityRegainHealth(final EntityRegainHealthEvent event) - { - - if (event.getRegainReason() == RegainReason.SATIATED && event.getEntity() instanceof Player) - { - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - @Cleanup - final IUser user = ess.getUser((Player)event.getEntity()); - user.acquireReadLock(); - if (user.getData().isAfk() && settings.getData().getCommands().getAfk().isFreezeAFKPlayers()) - { - event.setCancelled(true); - } - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/listener/EssentialsPlayerListener.java b/Essentials/src/com/earth2me/essentials/listener/EssentialsPlayerListener.java deleted file mode 100644 index 978794b75..000000000 --- a/Essentials/src/com/earth2me/essentials/listener/EssentialsPlayerListener.java +++ /dev/null @@ -1,438 +0,0 @@ -package com.earth2me.essentials.listener; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.Permissions; -import com.earth2me.essentials.utils.textreader.IText; -import com.earth2me.essentials.utils.textreader.KeywordReplacer; -import com.earth2me.essentials.utils.textreader.TextInput; -import com.earth2me.essentials.utils.textreader.TextPager; -import com.earth2me.essentials.user.UserData.TimestampType; -import com.earth2me.essentials.utils.LocationUtil; -import java.io.IOException; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.logging.Level; -import java.util.logging.Logger; -import lombok.Cleanup; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Server; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerLoginEvent.Result; -import org.bukkit.event.player.*; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; -import org.bukkit.inventory.ItemStack; - - -public class EssentialsPlayerListener implements Listener -{ - private static final Logger LOGGER = Logger.getLogger("Minecraft"); - private final transient Server server; - private final transient IEssentials ess; - - public EssentialsPlayerListener(final IEssentials parent) - { - super(); - this.ess = parent; - this.server = parent.getServer(); - } - - @EventHandler(priority = EventPriority.NORMAL) - public void onPlayerRespawn(final PlayerRespawnEvent event) - { - final IUser user = ess.getUser(event.getPlayer()); - user.updateCompass(); - user.updateDisplayName(); - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onPlayerChat(final PlayerChatEvent event) - { - @Cleanup - final IUser user = ess.getUser(event.getPlayer()); - user.acquireReadLock(); - if (user.getData().isMuted()) - { - event.setCancelled(true); - user.sendMessage(_("playerMuted")); - LOGGER.info(_("mutedUserSpeaks", user.getName())); - } - final Iterator it = event.getRecipients().iterator(); - while (it.hasNext()) - { - final IUser player = ess.getUser(it.next()); - if (player.isIgnoringPlayer(user.getName())) - { - it.remove(); - } - } - user.updateActivity(true); - user.updateDisplayName(); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerMove(final PlayerMoveEvent event) - { - @Cleanup - final IUser user = ess.getUser(event.getPlayer()); - user.acquireReadLock(); - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - - if (user.getData().isAfk() && settings.getData().getCommands().getAfk().isFreezeAFKPlayers()) - { - final Location from = event.getFrom(); - final Location to = event.getTo().clone(); - to.setX(from.getX()); - to.setY(from.getY()); - to.setZ(from.getZ()); - try - { - event.setTo(LocationUtil.getSafeDestination(to)); - } - catch (Exception ex) - { - event.setTo(to); - } - return; - } - - final Location afk = user.getAfkPosition(); - if (afk == null || !event.getTo().getWorld().equals(afk.getWorld()) || afk.distanceSquared(event.getTo()) > 9) - { - user.updateActivity(true); - } - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerQuit(final PlayerQuitEvent event) - { - @Cleanup - final IUser user = ess.getUser(event.getPlayer()); - user.acquireReadLock(); - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - if (settings.getData().getCommands().getGod().isRemoveOnDisconnect() && user.isGodModeEnabled()) - { - user.toggleGodModeEnabled(); - } - if (user.getData().getInventory() != null) - { - user.getInventory().setContents(user.getData().getInventory().getBukkitInventory()); - user.getData().setInventory(null); - } - user.updateActivity(false); - user.dispose(); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerJoin(final PlayerJoinEvent event) - { - ess.getBackup().startTask(); - @Cleanup - final IUser user = ess.getUser(event.getPlayer()); - user.acquireWriteLock(); - - user.updateDisplayName(); - user.getData().setIpAddress(user.getAddress().getAddress().getHostAddress()); - user.updateActivity(false); - if (Permissions.SLEEPINGIGNORED.isAuthorized(user)) - { - user.setSleepingIgnored(true); - } - - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - - if (!settings.getData().getCommands().isDisabled("motd") && Permissions.MOTD.isAuthorized(user)) - { - try - { - final IText input = new TextInput(user, "motd", true, ess); - final IText output = new KeywordReplacer(input, user, ess); - final TextPager pager = new TextPager(output, true); - pager.showPage("1", null, "motd", user); - } - catch (IOException ex) - { - if (settings.getData().getGeneral().isDebug()) - { - LOGGER.log(Level.WARNING, ex.getMessage(), ex); - } - else - { - LOGGER.log(Level.WARNING, ex.getMessage()); - } - } - } - - if (!settings.getData().getCommands().isDisabled("mail") && Permissions.MAIL.isAuthorized(user)) - { - final List mail = user.getData().getMails(); - if (mail == null || mail.isEmpty()) - { - user.sendMessage(_("noNewMail")); - } - else - { - user.sendMessage(_("youHaveNewMail", mail.size())); - } - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerLogin(final PlayerLoginEvent event) - { - switch (event.getResult()) - { - case ALLOWED: - case KICK_FULL: - case KICK_BANNED: - break; - default: - return; - } - @Cleanup - final IUser user = ess.getUser(event.getPlayer()); - user.acquireWriteLock(); - user.getData().setNpc(false); - - final long currentTime = System.currentTimeMillis(); - final boolean banExpired = user.checkBanTimeout(currentTime); - user.checkMuteTimeout(currentTime); - user.checkJailTimeout(currentTime); - - if (!banExpired && (user.isBanned() || event.getResult() == Result.KICK_BANNED)) - { - final String banReason = user.getData().getBan() == null ? "" : user.getData().getBan().getReason(); - event.disallow(Result.KICK_BANNED, banReason == null || banReason.isEmpty() || banReason.equalsIgnoreCase("ban") ? _("defaultBanReason") : banReason); - return; - } - - if (server.getOnlinePlayers().length >= server.getMaxPlayers() && !Permissions.JOINFULLSERVER.isAuthorized(user)) - { - event.disallow(Result.KICK_FULL, _("serverFull")); - return; - } - event.allow(); - - user.setTimestamp(TimestampType.LOGIN, System.currentTimeMillis()); - user.updateCompass(); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerTeleport(final PlayerTeleportEvent event) - { - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - //There is TeleportCause.COMMMAND but plugins have to actively pass the cause in on their teleports. - if ((event.getCause() == TeleportCause.PLUGIN || event.getCause() == TeleportCause.COMMAND) && settings.getData().getCommands().getBack().isRegisterBackInListener()) - { - final IUser user = ess.getUser(event.getPlayer()); - user.setLastLocation(); - } - - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerEggThrow(final PlayerEggThrowEvent event) - { - @Cleanup - final IUser user = ess.getUser(event.getPlayer()); - user.acquireReadLock(); - final ItemStack hand = new ItemStack(Material.EGG, 1); - if (user.getData().hasUnlimited(hand.getType())) - { - user.getInventory().addItem(hand); - user.updateInventory(); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerBucketEmpty(final PlayerBucketEmptyEvent event) - { - @Cleanup - final IUser user = ess.getUser(event.getPlayer()); - user.acquireReadLock(); - if (user.getData().hasUnlimited(event.getBucket())) - { - event.getItemStack().setType(event.getBucket()); - ess.scheduleSyncDelayedTask(new Runnable() - { - @Override - public void run() - { - user.updateInventory(); - } - }); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerCommandPreprocess(final PlayerCommandPreprocessEvent event) - { - final IUser user = ess.getUser(event.getPlayer()); - final String cmd = event.getMessage().toLowerCase(Locale.ENGLISH).split(" ")[0].replace("/", "").toLowerCase(Locale.ENGLISH); - final List commands = Arrays.asList("msg", "r", "mail", "m", "t", "emsg", "tell", "er", "reply", "ereply", "email"); - if (commands.contains(cmd)) - { - for (Player player : ess.getServer().getOnlinePlayers()) - { - @Cleanup - IUser spyer = ess.getUser(player); - spyer.acquireReadLock(); - if (spyer.getData().isSocialspy() && !user.equals(spyer)) - { - player.sendMessage(user.getDisplayName() + " : " + event.getMessage()); - } - } - } - if (!cmd.equalsIgnoreCase("afk")) - { - user.updateActivity(true); - } - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerChangedWorld(final PlayerChangedWorldEvent event) - { - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - @Cleanup - final IUser user = ess.getUser(event.getPlayer()); - user.acquireReadLock(); - if (settings.getData().getChat().getChangeDisplayname()) - { - user.updateDisplayName(); - } - if (!settings.getData().getWorldOptions(event.getPlayer().getLocation().getWorld().getName()).isGodmode() && !Permissions.NOGOD_OVERRIDE.isAuthorized(user)) - { - if (user.getData().isGodmode()) - { - user.sendMessage(_("noGodWorldWarning")); - } - } - if (settings.getData().getCommands().getTpa().isCancelTpRequestsOnWorldChange()) - { - if (user.getTeleportRequester() != null) - { - user.requestTeleport(null, false); - user.sendMessage(_("teleportRequestsCancelledWorldChange")); - } - } - } - - @EventHandler(priority = EventPriority.NORMAL) - public void onPlayerInteract(final PlayerInteractEvent event) - { - @Cleanup - final IUser user = ess.getUser(event.getPlayer()); - user.acquireReadLock(); - user.updateActivity(true); - switch (event.getAction()) - { - case RIGHT_CLICK_BLOCK: - if (event.isCancelled()) - { - return; - } - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - if (settings.getData().getCommands().getHome().isUpdateBedAtDaytime() && event.getClickedBlock().getType() == Material.BED_BLOCK) - { - event.getPlayer().setBedSpawnLocation(event.getClickedBlock().getLocation()); - } - break; - case LEFT_CLICK_AIR: - case LEFT_CLICK_BLOCK: - if (user.getData().hasPowerTools() && user.getData().isPowerToolsEnabled()) - { - if (usePowertools(user)) - { - event.setCancelled(true); - } - } - break; - default: - break; - } - } - - private boolean usePowertools(final IUser user) - { - final ItemStack is = user.getItemInHand(); - int id; - if (is == null || (id = is.getTypeId()) == 0) - { - return false; - } - - final List commandList = user.getData().getPowertool(is.getType()); - if (commandList == null || commandList.isEmpty()) - { - return false; - } - boolean used = false; - // We need to loop through each command and execute - for (final String command : commandList) - { - if (command.matches(".*\\{player\\}.*")) - { - //user.sendMessage("Click a player to use this command"); - continue; - } - else if (command.startsWith("c:")) - { - used = true; - user.chat(command.substring(2)); - } - else - { - used = true; - ess.scheduleSyncDelayedTask( - new Runnable() - { - @Override - public void run() - { - user.getServer().dispatchCommand(user.getBase(), command); - } - }); - } - } - return used; - } - - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onPlayerPickupItem(final PlayerPickupItemEvent event) - { - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - if (!settings.getData().getCommands().getAfk().isDisableItemPickupWhileAfk()) - { - return; - } - @Cleanup - final IUser user = ess.getUser(event.getPlayer()); - user.acquireReadLock(); - if (user.getData().isAfk()) - { - event.setCancelled(true); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/listener/EssentialsPluginListener.java b/Essentials/src/com/earth2me/essentials/listener/EssentialsPluginListener.java deleted file mode 100644 index edb839aa2..000000000 --- a/Essentials/src/com/earth2me/essentials/listener/EssentialsPluginListener.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.earth2me.essentials.listener; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IReload; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.ranks.GMGroups; -import com.earth2me.essentials.ranks.VaultGroups; -import com.earth2me.essentials.economy.register.Methods; -import com.earth2me.essentials.settings.General; -import com.earth2me.essentials.ranks.RanksStorage; -import java.util.logging.Level; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.server.PluginDisableEvent; -import org.bukkit.event.server.PluginEnableEvent; -import org.bukkit.plugin.Plugin; - - -public class EssentialsPluginListener implements Listener, IReload -{ - private final transient IEssentials ess; - - public EssentialsPluginListener(final IEssentials ess) - { - super(); - this.ess = ess; - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPluginEnable(final PluginEnableEvent event) - { - checkGroups(); - //ess.getPermissionsHandler().checkPermissions(); - ess.getCommandHandler().addPlugin(event.getPlugin()); - if (!Methods.hasMethod() && Methods.setMethod(ess.getServer().getPluginManager())) - { - ess.getLogger().log(Level.INFO, "Payment method found ({0} version: {1})", new Object[] - { - Methods.getMethod().getName(), Methods.getMethod().getVersion() - }); - } - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPluginDisable(final PluginDisableEvent event) - { - checkGroups(); - //ess.getPermissionsHandler().checkPermissions(); - ess.getCommandHandler().removePlugin(event.getPlugin()); - // Check to see if the plugin thats being disabled is the one we are using - if (Methods.hasMethod() && Methods.checkDisabled(event.getPlugin())) - { - Methods.reset(); - ess.getLogger().log(Level.INFO, "Payment method was disabled. No longer accepting payments."); - } - } - - @Override - public void onReload() - { - //ess.getPermissionsHandler().setUseSuperperms(ess.getSettings().useBukkitPermissions()); - } - - private void checkGroups() - { - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - General.GroupStorage storage = General.GroupStorage.FILE; - try - { - storage = settings.getData().getGeneral().getGroupStorage(); - } - finally - { - settings.unlock(); - } - if (storage == General.GroupStorage.GROUPMANAGER) - { - Plugin groupManager = ess.getServer().getPluginManager().getPlugin("GroupManager"); - if (groupManager != null && groupManager.isEnabled() && !(ess.getRanks() instanceof GMGroups)) - { - if (ess.getRanks() instanceof RanksStorage) - { - ess.removeReloadListener((RanksStorage)ess.getRanks()); - } - ess.setRanks(new GMGroups(ess, groupManager)); - return; - } - } - if (storage == General.GroupStorage.VAULT) - { - Plugin vault = ess.getServer().getPluginManager().getPlugin("Vault"); - if (vault != null && vault.isEnabled() && !(ess.getRanks() instanceof VaultGroups)) - { - if (ess.getRanks() instanceof RanksStorage) - { - ess.removeReloadListener((RanksStorage)ess.getRanks()); - } - ess.setRanks(new VaultGroups(ess)); - return; - } - } - if (!(ess.getRanks() instanceof RanksStorage)) - { - ess.setRanks(new RanksStorage(ess)); - ess.addReloadListener((RanksStorage)ess.getRanks()); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/listener/TntExplodeListener.java b/Essentials/src/com/earth2me/essentials/listener/TntExplodeListener.java deleted file mode 100644 index 2bcabb2d4..000000000 --- a/Essentials/src/com/earth2me/essentials/listener/TntExplodeListener.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.earth2me.essentials.listener; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.craftbukkit.FakeExplosion; -import java.util.concurrent.atomic.AtomicBoolean; -import org.bukkit.entity.LivingEntity; -import org.bukkit.event.EventHandler; -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 AtomicBoolean enabled = new AtomicBoolean(false); - private transient int timer = -1; - - public TntExplodeListener(final IEssentials ess) - { - super(); - this.ess = ess; - } - - public void enable() - { - if (enabled.compareAndSet(false, true)) - { - timer = ess.scheduleSyncDelayedTask(this, 1000); - return; - } - if (timer != -1) - { - ess.getServer().getScheduler().cancelTask(timer); - timer = ess.scheduleSyncDelayedTask(this, 1000); - } - } - - @EventHandler(priority = EventPriority.LOW) - public void onEntityExplode(final EntityExplodeEvent event) - { - if (!enabled.get()) - { - return; - } - if (event.getEntity() instanceof LivingEntity) - { - return; - } - FakeExplosion.createExplosion(event, ess.getServer(), ess.getServer().getOnlinePlayers()); - event.setCancelled(true); - } - - @Override - public void run() - { - enabled.set(false); - } -} diff --git a/Essentials/src/com/earth2me/essentials/permissions/AbstractSuperpermsPermission.java b/Essentials/src/com/earth2me/essentials/permissions/AbstractSuperpermsPermission.java deleted file mode 100644 index 66aba8f9c..000000000 --- a/Essentials/src/com/earth2me/essentials/permissions/AbstractSuperpermsPermission.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.earth2me.essentials.permissions; - -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IPermission; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.api.server.Permission; - - -public abstract class AbstractSuperpermsPermission implements IPermission -{ - protected Permission bukkitPerm; - - @Override - public Permission getPermission() - { - if (bukkitPerm != null) - { - return bukkitPerm; - } - else - { - return Permission.create(getPermissionName(), getPermissionDefault()); - } - } - - /** - * PermissionDefault is OP, if the method is not overwritten. - * @return - */ - @Override - public Permission.Default getPermissionDefault() - { - return Permission.Default.OP; - } - - @Override - public boolean isAuthorized(final CommandSender sender) - { - return sender.hasPermission(getPermission()); - } -} diff --git a/Essentials/src/com/earth2me/essentials/permissions/BasePermission.java b/Essentials/src/com/earth2me/essentials/permissions/BasePermission.java deleted file mode 100644 index 973b06d97..000000000 --- a/Essentials/src/com/earth2me/essentials/permissions/BasePermission.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.earth2me.essentials.permissions; - -public class BasePermission extends AbstractSuperpermsPermission { - protected String permission; - - public BasePermission(String base, String permission) - { - super(); - this.permission = base + permission; - } - - public String getPermissionName() - { - return permission; - } -} diff --git a/Essentials/src/com/earth2me/essentials/permissions/EnchantPermissions.java b/Essentials/src/com/earth2me/essentials/permissions/EnchantPermissions.java deleted file mode 100644 index c31aa6f62..000000000 --- a/Essentials/src/com/earth2me/essentials/permissions/EnchantPermissions.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.earth2me.essentials.permissions; - -import com.earth2me.essentials.api.IPermission; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - - -public class EnchantPermissions -{ - private static Map permissions = new HashMap(); - - public static IPermission getPermission(final String enchantName) - { - IPermission perm = permissions.get(enchantName); - if (perm == null) - { - perm = new BasePermission("essentials.enchant.",enchantName.toLowerCase(Locale.ENGLISH)); - permissions.put(enchantName, perm); - } - return perm; - } -} \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/permissions/GivePermissions.java b/Essentials/src/com/earth2me/essentials/permissions/GivePermissions.java deleted file mode 100644 index aa9b354c3..000000000 --- a/Essentials/src/com/earth2me/essentials/permissions/GivePermissions.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.earth2me.essentials.permissions; - -import com.earth2me.essentials.api.IPermission; -import com.earth2me.essentials.api.server.Material; -import com.earth2me.essentials.api.server.Permission; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - - -public class GivePermissions { - private static Map permissions = new HashMap(); - - public static IPermission getPermission(final Material mat) - { - IPermission perm = permissions.get(mat); - if (perm == null) - { - perm = new BasePermission("essentials.give.item-", mat.toString().toLowerCase(Locale.ENGLISH).replace("_", "")) - { - @Override - public Permission.Default getPermissionDefault() - { - return Permission.Default.TRUE; - } - }; - permissions.put(mat, perm); - } - return perm; - } -} diff --git a/Essentials/src/com/earth2me/essentials/permissions/GroupsPermissions.java b/Essentials/src/com/earth2me/essentials/permissions/GroupsPermissions.java deleted file mode 100644 index ed3ca92ff..000000000 --- a/Essentials/src/com/earth2me/essentials/permissions/GroupsPermissions.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.earth2me.essentials.permissions; - -import com.earth2me.essentials.api.IPermission; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - - -public class GroupsPermissions -{ - private static Map permissions = new HashMap(); - - public static IPermission getPermission(final String groupName) - { - IPermission perm = permissions.get(groupName); - if (perm == null) - { - perm = new BasePermission("essentials.groups.",groupName.toLowerCase(Locale.ENGLISH)); - permissions.put(groupName, perm); - } - return perm; - } -} diff --git a/Essentials/src/com/earth2me/essentials/permissions/HelpPermissions.java b/Essentials/src/com/earth2me/essentials/permissions/HelpPermissions.java deleted file mode 100644 index aae5e0ce7..000000000 --- a/Essentials/src/com/earth2me/essentials/permissions/HelpPermissions.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.earth2me.essentials.permissions; - -import com.earth2me.essentials.api.IPermission; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - - -public class HelpPermissions -{ - private static Map permissions = new HashMap(); - - public static IPermission getPermission(final String pluginName) - { - IPermission perm = permissions.get(pluginName); - if (perm == null) - { - perm = new BasePermission("essentials.help.", pluginName.toLowerCase(Locale.ENGLISH)); - permissions.put(pluginName, perm); - } - return perm; - } -} diff --git a/Essentials/src/com/earth2me/essentials/permissions/ItemPermissions.java b/Essentials/src/com/earth2me/essentials/permissions/ItemPermissions.java deleted file mode 100644 index fa4932cca..000000000 --- a/Essentials/src/com/earth2me/essentials/permissions/ItemPermissions.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.earth2me.essentials.permissions; - -import com.earth2me.essentials.api.IPermission; -import com.earth2me.essentials.api.server.Material; -import com.earth2me.essentials.api.server.Permission; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - - - -public class ItemPermissions -{ - private static Map permissions = new HashMap(); - - public static IPermission getPermission(final Material mat) - { - IPermission perm = permissions.get(mat); - if (perm == null) - { - perm = new BasePermission("essentials.itemspawn.item-", mat.toString().toLowerCase(Locale.ENGLISH).replace("_", "")) - { - @Override - public Permission.Default getPermissionDefault() - { - return Permission.Default.TRUE; - } - }; - permissions.put(mat, perm); - } - return perm; - } -} \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/permissions/KitPermissions.java b/Essentials/src/com/earth2me/essentials/permissions/KitPermissions.java deleted file mode 100644 index 420f1abd5..000000000 --- a/Essentials/src/com/earth2me/essentials/permissions/KitPermissions.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.earth2me.essentials.permissions; - -import com.earth2me.essentials.api.IPermission; -import com.earth2me.essentials.api.server.Permission; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - - -public class KitPermissions -{ - private static Map permissions = new HashMap(); - - public static IPermission getPermission(final String kitName) - { - IPermission perm = permissions.get(kitName); - if (perm == null) - { - perm = new BasePermission("essentials.kit.", kitName.toLowerCase(Locale.ENGLISH)) - { - @Override - public Permission.Default getPermissionDefault() - { - return Permission.Default.TRUE; - } - }; - permissions.put(kitName, perm); - } - return perm; - } -} diff --git a/Essentials/src/com/earth2me/essentials/permissions/NoCommandCostPermissions.java b/Essentials/src/com/earth2me/essentials/permissions/NoCommandCostPermissions.java deleted file mode 100644 index 77511e198..000000000 --- a/Essentials/src/com/earth2me/essentials/permissions/NoCommandCostPermissions.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.earth2me.essentials.permissions; - -import com.earth2me.essentials.api.IPermission; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - - -public class NoCommandCostPermissions -{ - private static Map permissions = new HashMap(); - - public static IPermission getPermission(final String command) - { - IPermission perm = permissions.get(command); - if (perm == null) - { - perm = new BasePermission("essentials.nocommandcost.", command.toLowerCase(Locale.ENGLISH)); - permissions.put(command, perm); - } - return perm; - } -} diff --git a/Essentials/src/com/earth2me/essentials/permissions/Permissions.java b/Essentials/src/com/earth2me/essentials/permissions/Permissions.java deleted file mode 100644 index a9df9e04a..000000000 --- a/Essentials/src/com/earth2me/essentials/permissions/Permissions.java +++ /dev/null @@ -1,123 +0,0 @@ -package com.earth2me.essentials.permissions; - -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IPermission; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.api.server.Permission; -import java.util.Locale; - - -public enum Permissions implements IPermission -{ - AFK, - AFK_KICKEXEMPT, - AFK_OTHERS, - BACK_ONDEATH, - BALANCE_OTHERS, - BAN_EXEMPT, - BAN_NOTIFY, - BAN_OFFLINE, - BREAK_BEDROCK, - CHAT_COLOR, - CHAT_SPY, - CLEARINVENTORY_OTHERS, - DELHOME_OTHERS, - ECO_LOAN(Permission.Default.FALSE), - FEED_OTHERS, - GAMEMODE_OTHERS, - GEOIP_HIDE(Permission.Default.FALSE), - GEOIP_SHOW(Permission.Default.TRUE), - GETPOS_OTHERS, - GOD_OTHERS, - HEAL_COOLDOWN_BYPASS, - HEAL_OTHERS, - HELPOP_RECEIVE, - HOME_OTHERS, - JAIL_EXEMPT, - JOINFULLSERVER, - KICK_EXEMPT, - KICK_NOTIFY, - LIST_HIDDEN, - LIGHTNING_OTHERS, - MAIL, - MAIL_SEND, - MAIL_SENDALL, - MOTD, - MSG_COLOR, - MUTE_EXEMPT, - NEAR_OTHERS, - NICK_COLOR, - NICK_OTHERS, - NOGOD_OVERRIDE, - OVERSIZEDSTACKS(Permission.Default.FALSE), - POWERTOOL_APPEND, - PTIME_OTHERS, - REPAIR_ARMOR, - REPAIR_ENCHANTED, - SEEN_BANREASON, - SETHOME_MULTIPLE, - SETHOME_OTHERS, - SLEEPINGIGNORED, - SPAWN_OTHERS, - SUDO_EXEMPT, - TELEPORT_COOLDOWN_BYPASS, - TELEPORT_HIDDEN, - TELEPORT_TIMER_BYPASS, - TEMPBAN_EXEMPT, - TEMPBAN_OFFLINE, - TIME_SET, - TOGGLEJAIL_OFFLINE, - TPA, - TPAALL, - TPAHERE, - TPOHERE, - UNLIMITED_OTHERS, - WARP_LIST(Permission.Default.TRUE), - WARP_OTHERS; - private static final String base = "essentials."; - private final String permission; - private final Permission.Default defaultPerm; - private transient Permission bukkitPerm = null; - - private Permissions() - { - this(Permission.Default.OP); - } - - private Permissions(final Permission.Default defaultPerm) - { - permission = base + toString().toLowerCase(Locale.ENGLISH).replace('_', '.'); - this.defaultPerm = defaultPerm; - } - - @Override - public String getPermissionName() - { - return permission; - } - - @Override - public Permission getPermission() - { - if (bukkitPerm != null) - { - return bukkitPerm; - } - else - { - return Permission.create(getPermissionName(), getPermissionDefault()); - } - } - - @Override - public Permission.Default getPermissionDefault() - { - return this.defaultPerm; - } - - @Override - public boolean isAuthorized(CommandSender sender) - { - return sender.hasPermission(getPermission()); - } -} diff --git a/Essentials/src/com/earth2me/essentials/permissions/SpawnerPermissions.java b/Essentials/src/com/earth2me/essentials/permissions/SpawnerPermissions.java deleted file mode 100644 index 17f8243cf..000000000 --- a/Essentials/src/com/earth2me/essentials/permissions/SpawnerPermissions.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.earth2me.essentials.permissions; - -import com.earth2me.essentials.api.IPermission; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - - -public class SpawnerPermissions -{ - private static Map permissions = new HashMap(); - - public static IPermission getPermission(final String mobName) - { - IPermission perm = permissions.get(mobName); - if (perm == null) - { - perm = new BasePermission("essentials.spawner.", mobName.toLowerCase(Locale.ENGLISH).replace("_", "")); - permissions.put(mobName, perm); - } - return perm; - } -} diff --git a/Essentials/src/com/earth2me/essentials/permissions/SpawnmobPermissions.java b/Essentials/src/com/earth2me/essentials/permissions/SpawnmobPermissions.java deleted file mode 100644 index fa1e26fa0..000000000 --- a/Essentials/src/com/earth2me/essentials/permissions/SpawnmobPermissions.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.earth2me.essentials.permissions; - -import com.earth2me.essentials.api.IPermission; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -public class SpawnmobPermissions { - private static Map permissions = new HashMap(); - - public static IPermission getPermission(final String mobName) - { - IPermission perm = permissions.get(mobName); - if (perm == null) - { - perm = new BasePermission("essentials.spawnmob.", mobName.toLowerCase(Locale.ENGLISH).replace("_", "")); - permissions.put(mobName, perm); - } - return perm; - } -} diff --git a/Essentials/src/com/earth2me/essentials/permissions/UnlimitedItemPermissions.java b/Essentials/src/com/earth2me/essentials/permissions/UnlimitedItemPermissions.java deleted file mode 100644 index 2907d77a6..000000000 --- a/Essentials/src/com/earth2me/essentials/permissions/UnlimitedItemPermissions.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.earth2me.essentials.permissions; - -import com.earth2me.essentials.api.IPermission; -import com.earth2me.essentials.api.server.Material; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -public class UnlimitedItemPermissions -{ - private static Map permissions = new HashMap(); - - public static IPermission getPermission(final Material mat) - { - IPermission perm = permissions.get(mat); - if (perm == null) - { - perm = new BasePermission("essentials.unlimited.item-", mat.toString().toLowerCase(Locale.ENGLISH).replace("_", "")); - permissions.put(mat, perm); - } - return perm; - } -} diff --git a/Essentials/src/com/earth2me/essentials/permissions/WarpPermissions.java b/Essentials/src/com/earth2me/essentials/permissions/WarpPermissions.java deleted file mode 100644 index 83c56a881..000000000 --- a/Essentials/src/com/earth2me/essentials/permissions/WarpPermissions.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.earth2me.essentials.permissions; - -import com.earth2me.essentials.api.IPermission; -import com.earth2me.essentials.api.server.Permission; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - - -public class WarpPermissions -{ - private static Map permissions = new HashMap(); - - public static IPermission getPermission(final String warpName) - { - IPermission perm = permissions.get(warpName); - if (perm == null) - { - perm = new BasePermission("essentials.warp.", warpName.toLowerCase(Locale.ENGLISH)) - { - @Override - public Permission.Default getPermissionDefault() - { - return Permission.Default.TRUE; - } - }; - permissions.put(warpName, perm); - } - return perm; - } -} \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/permissions/WorldPermissions.java b/Essentials/src/com/earth2me/essentials/permissions/WorldPermissions.java deleted file mode 100644 index 303a7214d..000000000 --- a/Essentials/src/com/earth2me/essentials/permissions/WorldPermissions.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.earth2me.essentials.permissions; - -import com.earth2me.essentials.api.IPermission; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -public class WorldPermissions -{ - private static Map permissions = new HashMap(); - - public static IPermission getPermission(final String worldName) - { - IPermission perm = permissions.get(worldName); - if (perm == null) - { - perm = new BasePermission("essentials.world.", worldName.toLowerCase(Locale.ENGLISH)); - permissions.put(worldName, perm); - } - return perm; - } -} diff --git a/Essentials/src/com/earth2me/essentials/ranks/GMGroups.java b/Essentials/src/com/earth2me/essentials/ranks/GMGroups.java deleted file mode 100644 index 244ff8410..000000000 --- a/Essentials/src/com/earth2me/essentials/ranks/GMGroups.java +++ /dev/null @@ -1,143 +0,0 @@ -package com.earth2me.essentials.ranks; - -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IRanks; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.IUser; -import java.text.MessageFormat; -import lombok.Cleanup; -import org.anjocaido.groupmanager.GroupManager; -import org.anjocaido.groupmanager.permissions.AnjoPermissionsHandler; -import org.bukkit.plugin.Plugin; - -public class GMGroups implements IRanks { - private final transient IEssentials ess; - private final transient GroupManager groupManager; - - public GMGroups(final IEssentials ess, final Plugin groupManager) - { - this.ess = ess; - this.groupManager = (GroupManager)groupManager; - } - - @Override - public double getHealCooldown(IUser player) - { - AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); - if (handler == null) - { - return 0; - } - return handler.getPermissionDouble(player.getName(), "healcooldown"); - } - - @Override - public double getTeleportCooldown(IUser player) - { - AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); - if (handler == null) - { - return 0; - } - return handler.getPermissionDouble(player.getName(), "teleportcooldown"); - } - - @Override - public double getTeleportDelay(IUser player) - { - AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); - if (handler == null) - { - return 0; - } - return handler.getPermissionDouble(player.getName(), "teleportdelay"); - } - - @Override - public String getPrefix(IUser player) - { - AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); - if (handler == null) - { - return null; - } - return handler.getUserPrefix(player.getName()); - } - - @Override - public String getSuffix(IUser player) - { - AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); - if (handler == null) - { - return null; - } - return handler.getUserSuffix(player.getName()); - } - - @Override - public int getHomeLimit(IUser player) - { - AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); - if (handler == null) - { - return 0; - } - return handler.getPermissionInteger(player.getName(), "homes"); - } - - @Override - public MessageFormat getChatFormat(final IUser player) - { - String format = getRawChatFormat(player); - format = Util.replaceColor(format); - format = format.replace("{DISPLAYNAME}", "%1$s"); - format = format.replace("{GROUP}", "{0}"); - format = format.replace("{MESSAGE}", "%2$s"); - format = format.replace("{WORLDNAME}", "{1}"); - format = format.replace("{SHORTWORLDNAME}", "{2}"); - format = format.replaceAll("\\{(\\D*)\\}", "\\[$1\\]"); - MessageFormat mFormat = new MessageFormat(format); - return mFormat; - } - - private String getRawChatFormat(final IUser player) - { - AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); - if (handler != null) - { - String chatformat = handler.getPermissionString(player.getName(), "chatformat"); - if (chatformat != null && !chatformat.isEmpty()) { - return chatformat; - } - } - - @Cleanup - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - return settings.getData().getChat().getDefaultFormat(); - } - - @Override - public String getMainGroup(IUser player) - { - final AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); - if (handler == null) - { - return null; - } - return handler.getGroup(player.getName()); - } - - @Override - public boolean inGroup(IUser player, String groupname) - { - AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); - if (handler == null) - { - return false; - } - return handler.inGroup(player.getName(), groupname); - } -} diff --git a/Essentials/src/com/earth2me/essentials/ranks/RankOptions.java b/Essentials/src/com/earth2me/essentials/ranks/RankOptions.java deleted file mode 100644 index 5fa011f9c..000000000 --- a/Essentials/src/com/earth2me/essentials/ranks/RankOptions.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.earth2me.essentials.ranks; - -import com.earth2me.essentials.storage.Comment; -import com.earth2me.essentials.storage.StorageObject; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class RankOptions implements StorageObject -{ - @Comment("Message format of chat messages") - private String messageFormat; - @Comment("Prefix for name") - private String prefix; - @Comment("Suffix for name") - private String suffix; - @Comment("Amount of homes a player can have") - private Integer homes; - @Comment("Cooldown between teleports") - private Integer teleportCooldown; - @Comment("Delay before teleport") - private Integer teleportDelay; - @Comment("Cooldown between heals") - private Integer healCooldown; -} diff --git a/Essentials/src/com/earth2me/essentials/ranks/Ranks.java b/Essentials/src/com/earth2me/essentials/ranks/Ranks.java deleted file mode 100644 index cc11aff2a..000000000 --- a/Essentials/src/com/earth2me/essentials/ranks/Ranks.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.earth2me.essentials.ranks; - -import com.earth2me.essentials.storage.Comment; -import com.earth2me.essentials.storage.MapValueType; -import com.earth2me.essentials.storage.StorageObject; -import java.util.LinkedHashMap; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Ranks implements StorageObject -{ - public Ranks() - { - final RankOptions defaultOptions = new RankOptions(); - ranks.put("default", defaultOptions); - } - @Comment( - { - "The order of the ranks matters, the ranks are checked from top to bottom.", - "All rank names have to be lower case.", - "The ranks can be connected to users using the permission essentials.ranks.rankname" - }) - @MapValueType(RankOptions.class) - private LinkedHashMap ranks = new LinkedHashMap(); -} diff --git a/Essentials/src/com/earth2me/essentials/ranks/RanksStorage.java b/Essentials/src/com/earth2me/essentials/ranks/RanksStorage.java deleted file mode 100644 index 5a38a51aa..000000000 --- a/Essentials/src/com/earth2me/essentials/ranks/RanksStorage.java +++ /dev/null @@ -1,195 +0,0 @@ -package com.earth2me.essentials.ranks; - -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IRanks; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.GroupsPermissions; -import com.earth2me.essentials.storage.AsyncStorageObjectHolder; -import java.io.File; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.Map.Entry; -import lombok.Cleanup; - - -public class RanksStorage extends AsyncStorageObjectHolder implements IRanks -{ - public RanksStorage(final IEssentials ess) - { - super(ess, Ranks.class); - onReload(); - } - - @Override - public File getStorageFile() - { - return new File(ess.getPlugin().getDataFolder(), "ranks.yml"); - } - - public Collection> getGroups(final IUser player) - { - acquireReadLock(); - try - { - final Map groups = getData().getRanks(); - if (groups == null || groups.isEmpty()) - { - return Collections.emptyList(); - } - final ArrayList> list = new ArrayList(); - for (Entry entry : groups.entrySet()) - { - if (GroupsPermissions.getPermission(entry.getKey()).isAuthorized(player)) - { - if(entry.getValue() != null) - { - list.add(entry); - } - } - } - return list; - } - finally - { - unlock(); - } - } - - @Override - public double getHealCooldown(final IUser player) - { - for (Entry groupOptions : getGroups(player)) - { - if (groupOptions.getValue().getHealCooldown() != null) - { - return groupOptions.getValue().getHealCooldown(); - } - } - return 0; - } - - @Override - public double getTeleportCooldown(final IUser player) - { - for (Entry groupOptions : getGroups(player)) - { - if (groupOptions.getValue().getTeleportCooldown() != null) - { - return groupOptions.getValue().getTeleportCooldown(); - } - } - return 0; - } - - @Override - public double getTeleportDelay(final IUser player) - { - for (Entry groupOptions : getGroups(player)) - { - if (groupOptions.getValue().getTeleportDelay() != null) - { - return groupOptions.getValue().getTeleportDelay(); - } - } - return 0; - } - - @Override - public String getPrefix(final IUser player) - { - for (Entry groupOptions : getGroups(player)) - { - if (groupOptions.getValue().getPrefix() != null) - { - return groupOptions.getValue().getPrefix(); - } - } - return ""; - } - - @Override - public String getSuffix(final IUser player) - { - for (Entry groupOptions : getGroups(player)) - { - if (groupOptions.getValue().getSuffix() != null) - { - return groupOptions.getValue().getSuffix(); - } - } - return ""; - } - - @Override - public int getHomeLimit(final IUser player) - { - for (Entry groupOptions : getGroups(player)) - { - if (groupOptions.getValue().getHomes() != null) - { - return groupOptions.getValue().getHomes(); - } - } - return 0; - } - - //TODO: Reimplement caching - @Override - public MessageFormat getChatFormat(final IUser player) - { - String format = getRawChatFormat(player); - format = Util.replaceColor(format); - format = format.replace("{DISPLAYNAME}", "%1$s"); - format = format.replace("{GROUP}", "{0}"); - format = format.replace("{MESSAGE}", "%2$s"); - format = format.replace("{WORLDNAME}", "{1}"); - format = format.replace("{SHORTWORLDNAME}", "{2}"); - format = format.replaceAll("\\{(\\D*)\\}", "\\[$1\\]"); - MessageFormat mFormat = new MessageFormat(format); - return mFormat; - } - - private String getRawChatFormat(final IUser player) - { - for (Entry groupOptions : getGroups(player)) - { - if (groupOptions.getValue().getMessageFormat() != null) - { - return groupOptions.getValue().getMessageFormat(); - } - } - @Cleanup - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - return settings.getData().getChat().getDefaultFormat(); - } - - @Override - public boolean inGroup(IUser player, String groupname) - { - for (Entry groupOptions : getGroups(player)) - { - if (groupOptions.getKey().equalsIgnoreCase(groupname)) - { - return true; - } - } - return false; - } - - @Override - public String getMainGroup(IUser player) - { - for (Entry groupOptions : getGroups(player)) - { - return groupOptions.getKey(); - } - return "default"; - } - -} diff --git a/Essentials/src/com/earth2me/essentials/ranks/VaultGroups.java b/Essentials/src/com/earth2me/essentials/ranks/VaultGroups.java deleted file mode 100644 index 51be20432..000000000 --- a/Essentials/src/com/earth2me/essentials/ranks/VaultGroups.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.earth2me.essentials.ranks; - -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IRanks; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.IUser; -import java.text.MessageFormat; -import lombok.Cleanup; -import net.milkbowl.vault.chat.Chat; -import org.bukkit.plugin.RegisteredServiceProvider; - - -public class VaultGroups implements IRanks -{ - private final IEssentials ess; - - public VaultGroups(final IEssentials ess) - { - this.ess = ess; - } - - @Override - public double getHealCooldown(IUser player) - { - Chat chat = ess.getServer().getServiceProvider(Chat.class); - return chat.getPlayerInfoDouble(player.getBase(), "healcooldown", 0); - } - - @Override - public double getTeleportCooldown(IUser player) - { - Chat chat = ess.getServer().getServiceProvider(Chat.class); - return chat.getPlayerInfoDouble(player.getBase(), "teleportcooldown", 0); - } - - @Override - public double getTeleportDelay(IUser player) - { - Chat chat = ess.getServer().getServiceProvider(Chat.class); - return chat.getPlayerInfoDouble(player.getBase(), "teleportdelay", 0); - } - - @Override - public String getPrefix(IUser player) - { - Chat chat = ess.getServer().getServiceProvider(Chat.class); - return chat.getPlayerPrefix(player.getBase()); - } - - @Override - public String getSuffix(IUser player) - { - Chat chat = ess.getServer().getServiceProvider(Chat.class); - return chat.getPlayerSuffix(player.getBase()); - } - - @Override - public int getHomeLimit(IUser player) - { - Chat chat = ess.getServer().getServiceProvider(Chat.class); - return chat.getPlayerInfoInteger(player.getBase(), "homes", 0); - } - - @Override - public MessageFormat getChatFormat(final IUser player) - { - String format = getRawChatFormat(player); - format = Util.replaceColor(format); - format = format.replace("{DISPLAYNAME}", "%1$s"); - format = format.replace("{GROUP}", "{0}"); - format = format.replace("{MESSAGE}", "%2$s"); - format = format.replace("{WORLDNAME}", "{1}"); - format = format.replace("{SHORTWORLDNAME}", "{2}"); - format = format.replaceAll("\\{(\\D*)\\}", "\\[$1\\]"); - MessageFormat mFormat = new MessageFormat(format); - return mFormat; - } - - private String getRawChatFormat(final IUser player) - { - Chat chat = ess.getServer().getServiceProvider(Chat.class); - String chatformat = chat.getPlayerInfoString(player.getBase(), "chatformat", ""); - if (chatformat != null && !chatformat.isEmpty()) - { - return chatformat; - } - - @Cleanup - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - return settings.getData().getChat().getDefaultFormat(); - } - - @Override - public String getMainGroup(IUser player) - { - Chat chat = ess.getServer().getServiceProvider(Chat.class); - return chat.getPrimaryGroup(player.getBase()); - } - - @Override - public boolean inGroup(IUser player, String groupname) - { - Chat chat = ess.getServer().getServiceProvider(Chat.class); - for (String group : chat.getPlayerGroups(player.getBase())) - { - if (group.equalsIgnoreCase(groupname)) - { - return true; - } - } - return false; - } -} diff --git a/Essentials/src/com/earth2me/essentials/settings/Backup.java b/Essentials/src/com/earth2me/essentials/settings/Backup.java deleted file mode 100644 index f43af47c0..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/Backup.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.earth2me.essentials.settings; - -import com.earth2me.essentials.storage.Comment; -import com.earth2me.essentials.storage.StorageObject; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Backup implements StorageObject -{ - @Comment("Interval in minutes") - private long interval = 60; - @Comment("Add a command that backups your data, e.g. 'rdiff-backup World1 backups/World1'") - private String command; -} diff --git a/Essentials/src/com/earth2me/essentials/settings/Chat.java b/Essentials/src/com/earth2me/essentials/settings/Chat.java deleted file mode 100644 index bbd02ce8e..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/Chat.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.earth2me.essentials.settings; - -import com.earth2me.essentials.storage.Comment; -import com.earth2me.essentials.storage.StorageObject; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Chat implements StorageObject -{ - @Comment("The character(s) to prefix all nicknames, so that you know they are not true usernames.") - private String nicknamePrefix = "~"; - @Comment( - { - "Disable this if you have any other plugin, that modifies the displayname of a user.", - "If it is not set, it will be enabled if EssentialsChat is installed, otherwise not." - }) - private Boolean changeDisplayname = true; - private String displaynameFormat = "{PREFIX}{NICKNAMEPREFIX}{NAME}{SUFFIX}"; - @Comment( - { - "If EssentialsChat is installed, this will define how far a player's voice travels, in blocks. Set to 0 to make all chat global.", - "Note that users with the \"essentials.chat.spy\" permission will hear everything, regardless of this setting.", - "Users with essentials.chat.shout can override this by prefixing text with an exclamation mark (!)", - "Or with essentials.chat.question can override this by prefixing text with a question mark (?)", - "You can add command costs for shout/question by adding chat-shout and chat-question to the command costs section." - }) - private int localRadius = 0; - @Comment("Set the default chat format here, it will be overwritten by group specific chat formats.") - private String defaultFormat = "&7[{GROUP}]&f {DISPLAYNAME}&7:&f {MESSAGE}"; -} diff --git a/Essentials/src/com/earth2me/essentials/settings/Commands.java b/Essentials/src/com/earth2me/essentials/settings/Commands.java deleted file mode 100644 index 1b738d4c9..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/Commands.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.earth2me.essentials.settings; - -import com.earth2me.essentials.settings.commands.*; -import com.earth2me.essentials.storage.Comment; -import com.earth2me.essentials.storage.ListType; -import com.earth2me.essentials.storage.StorageObject; -import java.util.ArrayList; -import java.util.List; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Commands implements StorageObject -{ - private Afk afk = new Afk(); - private Back back = new Back(); - private God god = new God(); - private Help help = new Help(); - private Home home = new Home(); - private Lightning lightning = new Lightning(); - private com.earth2me.essentials.settings.commands.List list = new com.earth2me.essentials.settings.commands.List(); - private Spawnmob spawnmob = new Spawnmob(); - private Tpa tpa = new Tpa(); - @ListType - @Comment( - { - "When a command conflicts with another plugin, by default, Essentials will try to force the OTHER plugin to take", - "priority. If a command is in this list, Essentials will try to give ITSELF priority. This does not always work:", - "usually whichever plugin was updated most recently wins out. However, the full name of the command will always work.", - "For example, if WorldGuard and Essentials are both enabled, and WorldGuard takes control over /god, /essentials:god", - "will still map to Essentials, whereas it might normally get forced upon WorldGuard. Commands prefixed with an \"e\",", - "such as /egod, will always grant Essentials priority.", - "We should try to take priority over /god. If this doesn't work, use /essentials:god or /egod.", - "If god is set using WorldGuard, use /ungod to remove then use whichever you see fit." - }) - private List overridden = new ArrayList(); - @ListType - @Comment("Disabled commands will be completelly unavailable on the server.") - private List disabled = new ArrayList(); - - public boolean isDisabled(final String commandName) - { - if (disabled == null) - { - return false; - } - for (String disabledCommand : disabled) - { - if (commandName.equalsIgnoreCase(disabledCommand)) - { - return true; - } - } - return false; - } - - public boolean isOverridden(final String commandName) - { - if (overridden == null) - { - return false; - } - for (String overriddenCommand : overridden) - { - if (commandName.equalsIgnoreCase(overriddenCommand)) - { - return true; - } - } - return false; - } -} diff --git a/Essentials/src/com/earth2me/essentials/settings/Economy.java b/Essentials/src/com/earth2me/essentials/settings/Economy.java deleted file mode 100644 index ea106f13f..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/Economy.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.earth2me.essentials.settings; - -import com.earth2me.essentials.economy.Worth; -import com.earth2me.essentials.storage.Comment; -import com.earth2me.essentials.storage.MapValueType; -import com.earth2me.essentials.storage.StorageObject; -import java.util.HashMap; -import java.util.Map; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Economy implements StorageObject -{ - @Comment("Defines the balance with which new players begin. Defaults to 0.") - private double startingBalance = 0.0; - @MapValueType(Double.class) - @Comment("Defines the cost to use the given commands PER USE") - private Map commandCosts = new HashMap(); - @Comment("Set this to a currency symbol you want to use.") - private String currencySymbol = "$"; - - public String getCurrencySymbol() - { - return currencySymbol == null || currencySymbol.isEmpty() ? "$" : currencySymbol.substring(0, 1); - } - private final transient static double MAXMONEY = 10000000000000.0; - @Comment( - { - "Set the maximum amount of money a player can have", - "The amount is always limited to 10 trillions because of the limitations of a java double" - }) - private double maxMoney = MAXMONEY; - - public double getMaxMoney() - { - return Math.abs(maxMoney) > MAXMONEY ? MAXMONEY : Math.abs(maxMoney); - } - - @Comment( - { - "Set the minimum amount of money a player can have (must be above the negative of max-money).", - "Setting this to 0, will disable overdrafts/loans completely. Users need 'essentials.eco.loan' perm to go below 0." - }) - private double minMoney = -MAXMONEY; - public double getMinMoney() - { - return Math.abs(minMoney) > MAXMONEY ? -MAXMONEY : minMoney; - } - - @Comment("Enable this to log all interactions with trade/buy/sell signs and sell command") - private boolean logEnabled = false; - private Worth worth = new Worth(); - private boolean tradeInStacks = false; - - public double getCommandCost(String command) - { - if (commandCosts == null) - { - return 0; - } - Double price = commandCosts.get(command); - return price == null || Double.isNaN(price) || Double.isInfinite(price) ? 0 : price; - } -} diff --git a/Essentials/src/com/earth2me/essentials/settings/General.java b/Essentials/src/com/earth2me/essentials/settings/General.java deleted file mode 100644 index 85238977f..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/General.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.earth2me.essentials.settings; - -import com.earth2me.essentials.storage.Comment; -import com.earth2me.essentials.storage.StorageObject; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class General implements StorageObject -{ - @Comment("Backup runs a command while saving is disabled") - private Backup backup = new Backup(); - @Comment("You can disable the death messages of minecraft.") - private boolean deathMessages = true; - @Comment("Turn this on, if you want to see more error messages, if something goes wrong.") - private boolean debug = false; - @Comment( - { - "Set the locale here, if you want to change the language of Essentials.", - "If this is not set, Essentials will use the language of your computer.", - "Available locales: da, de, en, fr, nl" - }) - private String locale; - @Comment( - { - "The number of items given, if the quantity parameter is left out in /item or /give.", - "If this number is below 1, the maximum stack size size is given. If oversized stacks", - "is not enabled, any number higher then the maximum stack size results in more than one stack." - }) - private int defaultStacksize = -1; - @Comment( - { - "Oversized stacks are stacks that ignore the normal max stacksize.", - "They can be obtained using /give and /item, if the player has essentials.oversizedstacks permission.", - "How many items should be in a oversized stack?" - }) - private int oversizedStacksize = 64; - - - public enum GroupStorage - { - FILE, GROUPMANAGER, VAULT - } - @Comment( - { - "Sets the place where group options should be stored:", - " FILE: Options are stored inside groups.yml in the Essentials folder", - " GROUPMANAGER: Options are stored using the GroupManager groups", - " VAULT: Options are stored using a permissions plugin supported by Vault" - }) - private GroupStorage groupStorage = GroupStorage.FILE; -} diff --git a/Essentials/src/com/earth2me/essentials/settings/Jails.java b/Essentials/src/com/earth2me/essentials/settings/Jails.java deleted file mode 100644 index 5793f7d2c..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/Jails.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.earth2me.essentials.settings; - -import com.earth2me.essentials.storage.StoredLocation; -import com.earth2me.essentials.storage.MapValueType; -import com.earth2me.essentials.storage.StorageObject; -import java.util.HashMap; -import java.util.Map; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Jails implements StorageObject -{ - @MapValueType(StoredLocation.class) - private Map jails = new HashMap(); -} diff --git a/Essentials/src/com/earth2me/essentials/settings/Kit.java b/Essentials/src/com/earth2me/essentials/settings/Kit.java deleted file mode 100644 index 19267e6f3..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/Kit.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.earth2me.essentials.settings; - -import com.earth2me.essentials.storage.ListType; -import com.earth2me.essentials.storage.StorageObject; -import java.util.ArrayList; -import java.util.List; -import lombok.Data; -import lombok.EqualsAndHashCode; -import org.bukkit.inventory.ItemStack; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Kit implements StorageObject -{ - @ListType(ItemStack.class) - private List items = new ArrayList(); - private Double delay; -} diff --git a/Essentials/src/com/earth2me/essentials/settings/Kits.java b/Essentials/src/com/earth2me/essentials/settings/Kits.java deleted file mode 100644 index f943c2bb9..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/Kits.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.earth2me.essentials.settings; - -import com.earth2me.essentials.storage.MapValueType; -import com.earth2me.essentials.storage.StorageObject; -import java.util.HashMap; -import java.util.Map; -import lombok.Data; -import lombok.EqualsAndHashCode; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Kits implements StorageObject -{ - public Kits() - { - final Kit kit = new Kit(); - kit.setDelay(10.0); - kit.getItems().add(new ItemStack(Material.DIAMOND_SPADE, 1)); - kit.getItems().add(new ItemStack(Material.DIAMOND_PICKAXE, 1)); - kit.getItems().add(new ItemStack(Material.DIAMOND_AXE, 1)); - kits.put("tools", kit); - } - @MapValueType(Kit.class) - private Map kits = new HashMap(); -} diff --git a/Essentials/src/com/earth2me/essentials/settings/Settings.java b/Essentials/src/com/earth2me/essentials/settings/Settings.java deleted file mode 100644 index 6e5ec9793..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/Settings.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.earth2me.essentials.settings; - -import com.earth2me.essentials.storage.Comment; -import com.earth2me.essentials.storage.MapValueType; -import com.earth2me.essentials.storage.StorageObject; -import java.util.HashMap; -import java.util.Map; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Settings implements StorageObject -{ - @Comment( - { - "##########################################################", - "+------------------------------------------------------+ #", - "| General Settings | #", - "+------------------------------------------------------+ #", - "##########################################################" - }) - private General general = new General(); - @Comment( - { - "##########################################################", - "+------------------------------------------------------+ #", - "| Chat Settings | #", - "+------------------------------------------------------+ #", - "##########################################################" - }) - private Chat chat = new Chat(); - @Comment( - { - "##########################################################", - "+------------------------------------------------------+ #", - "| Economy Settings | #", - "+------------------------------------------------------+ #", - "##########################################################" - }) - private Economy economy = new Economy(); - @Comment( - { - "##########################################################", - "+------------------------------------------------------+ #", - "| Commands Settings | #", - "+------------------------------------------------------+ #", - "##########################################################" - }) - private Commands commands = new Commands(); - @Comment( - { - "##########################################################", - "+------------------------------------------------------+ #", - "| Worlds Settings | #", - "+------------------------------------------------------+ #", - "##########################################################" - }) - @MapValueType(WorldOptions.class) - private Map worlds = new HashMap(); - - public WorldOptions getWorldOptions(final String name) - { - if (worlds == null) - { - worlds = new HashMap(); - } - final WorldOptions options = worlds.get(name); - return (options == null) ? new WorldOptions() : options; - } -} diff --git a/Essentials/src/com/earth2me/essentials/settings/SettingsHolder.java b/Essentials/src/com/earth2me/essentials/settings/SettingsHolder.java deleted file mode 100644 index 22a398a3c..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/SettingsHolder.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.earth2me.essentials.settings; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.storage.AsyncStorageObjectHolder; -import java.io.File; -import java.util.concurrent.atomic.AtomicBoolean; - - -public class SettingsHolder extends AsyncStorageObjectHolder implements ISettings -{ - private final transient AtomicBoolean debug = new AtomicBoolean(false); - public SettingsHolder(final IEssentials ess) - { - super(ess, Settings.class); - onReload(); - } - - @Override - public final void onReload() - { - super.onReload(); - acquireReadLock(); - try { - debug.set(getData().getGeneral().isDebug()); - } finally { - unlock(); - } - } - - @Override - public File getStorageFile() - { - return new File(ess.getPlugin().getDataFolder(), "settings.yml"); - } - - @Override - public String getLocale() - { - acquireReadLock(); - try { - return getData().getGeneral().getLocale(); - } finally { - unlock(); - } - } - - @Override - public boolean isDebug() - { - return debug.get(); - } - - public void setDebug(final boolean set) - { - debug.set(set); - acquireWriteLock(); - try { - getData().getGeneral().setDebug(set); - } finally { - unlock(); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/settings/Spawns.java b/Essentials/src/com/earth2me/essentials/settings/Spawns.java deleted file mode 100644 index c8fcf38b1..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/Spawns.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.earth2me.essentials.settings; - -import com.earth2me.essentials.storage.Comment; -import com.earth2me.essentials.storage.StoredLocation; -import com.earth2me.essentials.storage.MapValueType; -import com.earth2me.essentials.storage.StorageObject; -import java.util.HashMap; -import java.util.Map; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Spawns implements StorageObject -{ - @Comment( - { - "Should we announce to the server when someone logs in for the first time?", - "If so, use this format, replacing {DISPLAYNAME} with the player name.", - "If not, set to ''" - }) - private String newPlayerAnnouncement = "&dWelcome {DISPLAYNAME} to the server!"; - @Comment( - { - "Priority of the respawn event listener", - "Set this to lowest, if you want e.g. Multiverse to handle the respawning", - "Set this to normal, if you want EssentialsSpawn to handle the respawning", - "Set this to highest, if you want to force EssentialsSpawn to handle the respawning" - }) - private String respawnPriority = "normal"; - @Comment({ - "When we spawn for the first time, which spawnpoint do we use?", - "Set to none if you want to use the spawn point of the world." - }) - private String newbieSpawn = "none"; - @Comment("List of all spawnpoints") - @MapValueType(StoredLocation.class) - private Map spawns = new HashMap(); -} diff --git a/Essentials/src/com/earth2me/essentials/settings/SpawnsHolder.java b/Essentials/src/com/earth2me/essentials/settings/SpawnsHolder.java deleted file mode 100644 index e969b8705..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/SpawnsHolder.java +++ /dev/null @@ -1,307 +0,0 @@ -package com.earth2me.essentials.settings; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IEssentialsModule; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.storage.AsyncStorageObjectHolder; -import com.earth2me.essentials.storage.StoredLocation.WorldNotLoadedException; -import com.earth2me.essentials.utils.textreader.IText; -import com.earth2me.essentials.utils.textreader.KeywordReplacer; -import com.earth2me.essentials.utils.textreader.SimpleTextInput; -import com.earth2me.essentials.utils.textreader.SimpleTextPager; -import java.io.File; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.logging.Level; -import org.bukkit.*; -import org.bukkit.event.Event; -import org.bukkit.event.EventException; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerRespawnEvent; -import org.bukkit.event.player.PlayerTeleportEvent; -import org.bukkit.plugin.EventExecutor; - - -public class SpawnsHolder extends AsyncStorageObjectHolder implements IEssentialsModule -{ - public SpawnsHolder(final IEssentials ess) - { - super(ess, Spawns.class); - onReload(); - registerListeners(); - } - - @Override - public File getStorageFile() - { - return new File(ess.getPlugin().getDataFolder(), "spawn.yml"); - } - - public void setSpawn(final Location loc, final String group) - { - acquireWriteLock(); - try - { - if (getData().getSpawns() == null) - { - getData().setSpawns(new HashMap()); - } - getData().getSpawns().put(group.toLowerCase(Locale.ENGLISH), new com.earth2me.essentials.storage.StoredLocation(loc)); - } - finally - { - unlock(); - } - - if ("default".equalsIgnoreCase(group)) - { - loc.getWorld().setSpawnLocation(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); - } - } - - public Location getSpawn(final String group) - { - acquireReadLock(); - try - { - if (getData().getSpawns() == null || group == null) - { - return getWorldSpawn(); - } - final Map spawnMap = getData().getSpawns(); - String groupName = group.toLowerCase(Locale.ENGLISH); - if (!spawnMap.containsKey(groupName)) - { - groupName = "default"; - } - if (!spawnMap.containsKey(groupName)) - { - return getWorldSpawn(); - } - try - { - return spawnMap.get(groupName).getStoredLocation(); - } - catch (WorldNotLoadedException ex) - { - return getWorldSpawn(); - } - } - finally - { - unlock(); - } - } - - private Location getWorldSpawn() - { - for (World world : ess.getServer().getWorlds()) - { - if (world.getEnvironment() != World.Environment.NORMAL) - { - continue; - } - return world.getSpawnLocation(); - } - return ess.getServer().getWorlds().get(0).getSpawnLocation(); - } - - public EventPriority getRespawnPriority() - { - acquireReadLock(); - try - { - for (EventPriority priority : EventPriority.values()) - { - if (priority.toString().equalsIgnoreCase(getData().getRespawnPriority())) - { - return priority; - } - } - return EventPriority.NORMAL; - } - finally - { - unlock(); - } - } - - public Location getNewbieSpawn() - { - acquireReadLock(); - try - { - if (getData().getNewbieSpawn() == null || getData().getNewbieSpawn().isEmpty() - || getData().getNewbieSpawn().equalsIgnoreCase("none")) - { - return null; - } - return getSpawn(getData().getNewbieSpawn()); - } - finally - { - unlock(); - } - } - - public boolean getAnnounceNewPlayers() - { - acquireReadLock(); - try - { - return getData().getNewPlayerAnnouncement() != null && !getData().getNewPlayerAnnouncement().isEmpty(); - } - finally - { - unlock(); - } - } - - public String getAnnounceNewPlayerFormat(IUser user) - { - acquireReadLock(); - try - { - return getData().getNewPlayerAnnouncement().replace('&', '�').replace("��", "&").replace("{PLAYER}", user.getDisplayName()).replace("{DISPLAYNAME}", user.getDisplayName()).replace("{GROUP}", ess.getRanks().getMainGroup(user)).replace("{USERNAME}", user.getName()).replace("{ADDRESS}", user.getAddress().toString()); - } - finally - { - unlock(); - } - } - - private void registerListeners() - { - final SpawnPlayerListener playerListener = new SpawnPlayerListener(ess, this); - ess.getServer().getPluginManager().registerEvent(PlayerRespawnEvent.class, playerListener, getRespawnPriority(), new EventExecutor() - { - @Override - public void execute(final Listener ll, final Event event) throws EventException - { - ((SpawnPlayerListener)ll).onPlayerRespawn((PlayerRespawnEvent)event); - } - }, ess); - ess.getServer().getPluginManager().registerEvent(PlayerJoinEvent.class, playerListener, getRespawnPriority(), new EventExecutor() - { - @Override - public void execute(final Listener ll, final Event event) throws EventException - { - ((SpawnPlayerListener)ll).onPlayerJoin((PlayerJoinEvent)event); - } - }, ess); - } - - - private class SpawnPlayerListener implements Listener - { - private final transient IEssentials ess; - private final transient SpawnsHolder spawns; - - public SpawnPlayerListener(final IEssentials ess, final SpawnsHolder spawns) - { - super(); - this.ess = ess; - this.spawns = spawns; - } - - public void onPlayerRespawn(final PlayerRespawnEvent event) - { - final IUser user = ess.getUser(event.getPlayer()); - - boolean respawnAtHome = false; - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - try - { - respawnAtHome = ess.getSettings().getData().getCommands().getHome().isRespawnAtHome(); - } - finally - { - settings.unlock(); - } - if (respawnAtHome) - { - Location home; - final Location bed = user.getBedSpawnLocation(); - if (bed != null && bed.getBlock().getType() == Material.BED_BLOCK) - { - home = bed; - } - else - { - home = user.getHome(user.getLocation()); - } - if (home != null) - { - event.setRespawnLocation(home); - return; - } - } - final Location spawn = spawns.getSpawn(ess.getRanks().getMainGroup(user)); - if (spawn != null) - { - event.setRespawnLocation(spawn); - } - } - - public void onPlayerJoin(final PlayerJoinEvent event) - { - final IUser user = ess.getUser(event.getPlayer()); - - if (user.hasPlayedBefore()) - { - return; - } - - if (spawns.getNewbieSpawn() != null) - { - ess.getPlugin().scheduleSyncDelayedTask(new NewPlayerTeleport(user), 1L); - } - - if (spawns.getAnnounceNewPlayers()) - { - final IText output = new KeywordReplacer(new SimpleTextInput(spawns.getAnnounceNewPlayerFormat(user)), user, ess); - final SimpleTextPager pager = new SimpleTextPager(output); - ess.broadcastMessage(user, pager.getString(0)); - } - } - - - private class NewPlayerTeleport implements Runnable - { - private final transient IUser user; - - public NewPlayerTeleport(final IUser user) - { - this.user = user; - } - - @Override - public void run() - { - if (user.getBase() instanceof OfflinePlayer) - { - return; - } - - try - { - final Location spawn = spawns.getNewbieSpawn(); - if (spawn != null) - { - user.getTeleport().now(spawn, false, PlayerTeleportEvent.TeleportCause.PLUGIN); - } - } - catch (Exception ex) - { - Bukkit.getLogger().log(Level.WARNING, _("teleportNewPlayerError"), ex); - } - } - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/settings/Warp.java b/Essentials/src/com/earth2me/essentials/settings/Warp.java deleted file mode 100644 index 171f7075f..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/Warp.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.earth2me.essentials.settings; - -import com.earth2me.essentials.storage.StoredLocation; -import com.earth2me.essentials.storage.StorageObject; -import lombok.Data; -import lombok.EqualsAndHashCode; - -@Data -@EqualsAndHashCode(callSuper = false) -public class Warp implements StorageObject -{ - private String name; - private StoredLocation location; -} diff --git a/Essentials/src/com/earth2me/essentials/settings/WarpHolder.java b/Essentials/src/com/earth2me/essentials/settings/WarpHolder.java deleted file mode 100644 index b6a9f2879..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/WarpHolder.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.earth2me.essentials.settings; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IWarp; -import com.earth2me.essentials.api.InvalidNameException; -import com.earth2me.essentials.storage.AsyncStorageObjectHolder; -import java.io.File; -import java.io.IOException; - - -public class WarpHolder extends AsyncStorageObjectHolder implements IWarp -{ - private final String name; - - public WarpHolder(String name, IEssentials ess) - { - super(ess, Warp.class); - this.name = name; - onReload(); - } - - @Override - public File getStorageFile() throws IOException - { - try - { - return ess.getWarps().getWarpFile(name); - } - catch (InvalidNameException ex) - { - throw new IOException(ex.getMessage(), ex); - } - } - -} diff --git a/Essentials/src/com/earth2me/essentials/settings/WorldOptions.java b/Essentials/src/com/earth2me/essentials/settings/WorldOptions.java deleted file mode 100644 index 33271b460..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/WorldOptions.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.earth2me.essentials.settings; - -import com.earth2me.essentials.storage.Comment; -import com.earth2me.essentials.storage.StorageObject; -import lombok.Data; -import lombok.EqualsAndHashCode; - -@Data -@EqualsAndHashCode(callSuper = false) -public class WorldOptions implements StorageObject -{ - @Comment("Disables godmode for all players if they teleport to this world.") - private boolean godmode = true; -} diff --git a/Essentials/src/com/earth2me/essentials/settings/Worlds.java b/Essentials/src/com/earth2me/essentials/settings/Worlds.java deleted file mode 100644 index ed865d94b..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/Worlds.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.earth2me.essentials.settings; - -import com.earth2me.essentials.storage.StorageObject; -import lombok.Data; -import lombok.EqualsAndHashCode; - -@Data -@EqualsAndHashCode(callSuper = false) -public class Worlds implements StorageObject -{ - -} \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/settings/commands/Afk.java b/Essentials/src/com/earth2me/essentials/settings/commands/Afk.java deleted file mode 100644 index f46e52d52..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/commands/Afk.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.earth2me.essentials.settings.commands; - -import com.earth2me.essentials.storage.Comment; -import com.earth2me.essentials.storage.StorageObject; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Afk implements StorageObject -{ - @Comment( - { - "After this timeout in seconds, the user will be set as afk.", - "Set to -1 for no timeout." - }) - private long autoAFK = 300; - @Comment( - { - "Auto-AFK Kick", - "After this timeout in seconds, the user will be kicked from the server.", - "Set to -1 for no timeout." - }) - private long autoAFKKick = -1; - @Comment( - { - "Set this to true, if you want to freeze the player, if he is afk.", - "Other players or monsters can't push him out of afk mode then.", - "This will also enable temporary god mode for the afk player.", - "The player has to use the command /afk to leave the afk mode.", - "You have to add a message to your welcome message or help page,", - "since the player will not get a message, if he tries to move." - }) - private boolean freezeAFKPlayers = false; - - private boolean disableItemPickupWhileAfk = true; -} diff --git a/Essentials/src/com/earth2me/essentials/settings/commands/Back.java b/Essentials/src/com/earth2me/essentials/settings/commands/Back.java deleted file mode 100644 index bd2afdd62..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/commands/Back.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.earth2me.essentials.settings.commands; - -import com.earth2me.essentials.storage.Comment; -import com.earth2me.essentials.storage.StorageObject; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Back implements StorageObject -{ - @Comment( - { - "Do you want essentials to keep track of previous location for /back in the teleport listener?", - "If you set this to true any plugin that uses teleport will have the previous location registered." - }) - private boolean registerBackInListener = false; -} diff --git a/Essentials/src/com/earth2me/essentials/settings/commands/God.java b/Essentials/src/com/earth2me/essentials/settings/commands/God.java deleted file mode 100644 index a6f5dbfc3..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/commands/God.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.earth2me.essentials.settings.commands; - -import com.earth2me.essentials.storage.Comment; -import com.earth2me.essentials.storage.StorageObject; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class God implements StorageObject -{ - @Comment("Turn off god mode when people exit") - private boolean removeOnDisconnect = false; -} diff --git a/Essentials/src/com/earth2me/essentials/settings/commands/Help.java b/Essentials/src/com/earth2me/essentials/settings/commands/Help.java deleted file mode 100644 index 0b4787471..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/commands/Help.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.earth2me.essentials.settings.commands; - -import com.earth2me.essentials.storage.Comment; -import com.earth2me.essentials.storage.StorageObject; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Help implements StorageObject -{ - @Comment("Show other plugins commands in help") - private boolean showNonEssCommandsInHelp = true; - @Comment( - { - "Hide plugins which don't give a permission in their plugin.yml for each command.", - "You can override a true value here for a single plugin by adding a permission to a user/group.", - "The individual permission is: essentials.help., anyone with essentials.* or '*' will see all help this setting reguardless.", - "You can use negative permissions to remove access to just a single plugins help if the following is enabled." - }) - private boolean hidePermissionlessCommands = true; -} diff --git a/Essentials/src/com/earth2me/essentials/settings/commands/Home.java b/Essentials/src/com/earth2me/essentials/settings/commands/Home.java deleted file mode 100644 index b856c881b..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/commands/Home.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.earth2me.essentials.settings.commands; - -import com.earth2me.essentials.storage.Comment; -import com.earth2me.essentials.storage.StorageObject; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Home implements StorageObject -{ - @Comment("When players die, should they respawn at their homes, instead of the spawnpoint?") - private boolean respawnAtHome = false; - @Comment( - { - "When a player interacts with a bed, should their home be set to that location?", - "If you enable this and remove default player access to the /sethome command, ", - "you can make beds the only way for players to set their home location." - }) - private boolean bedSetsHome = false; - @Comment("If no home is set, should the player be send to spawn, when /home is used.") - private boolean spawnIfNoHome = false; - @Comment("Allows people to set their bed at daytime") - private boolean updateBedAtDaytime = true; -} diff --git a/Essentials/src/com/earth2me/essentials/settings/commands/Lightning.java b/Essentials/src/com/earth2me/essentials/settings/commands/Lightning.java deleted file mode 100644 index e40e645da..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/commands/Lightning.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.earth2me.essentials.settings.commands; - -import com.earth2me.essentials.storage.Comment; -import com.earth2me.essentials.storage.StorageObject; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Lightning implements StorageObject -{ - @Comment("Shall we notify users when using /lightning") - private boolean warnPlayer = true; -} diff --git a/Essentials/src/com/earth2me/essentials/settings/commands/List.java b/Essentials/src/com/earth2me/essentials/settings/commands/List.java deleted file mode 100644 index ca2c61d2d..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/commands/List.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.earth2me.essentials.settings.commands; - - -import com.earth2me.essentials.storage.Comment; -import com.earth2me.essentials.storage.StorageObject; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class List implements StorageObject -{ - @Comment("Sort output of /list command by groups") - private boolean sortByGroups = true; -} diff --git a/Essentials/src/com/earth2me/essentials/settings/commands/Spawnmob.java b/Essentials/src/com/earth2me/essentials/settings/commands/Spawnmob.java deleted file mode 100644 index 37d41c296..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/commands/Spawnmob.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.earth2me.essentials.settings.commands; - -import com.earth2me.essentials.storage.Comment; -import com.earth2me.essentials.storage.StorageObject; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Spawnmob implements StorageObject -{ - @Comment("The maximum amount of monsters, a player can spawn with a call of /spawnmob.") - private int limit = 10; -} diff --git a/Essentials/src/com/earth2me/essentials/settings/commands/Tpa.java b/Essentials/src/com/earth2me/essentials/settings/commands/Tpa.java deleted file mode 100644 index 88cbc9a6b..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/commands/Tpa.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.earth2me.essentials.settings.commands; - -import com.earth2me.essentials.storage.Comment; -import com.earth2me.essentials.storage.StorageObject; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Tpa implements StorageObject -{ - @Comment( - { - "Set timeout in seconds for players to accept tpa before request is cancelled.", - "Set to 0 for no timeout." - }) - private int timeout = 0; - @Comment({"Cancels a request made by tpa / tphere on world change to prevent cross world tp"}) - private boolean cancelTpRequestsOnWorldChange = false; -} diff --git a/Essentials/src/com/earth2me/essentials/settings/geoip/Database.java b/Essentials/src/com/earth2me/essentials/settings/geoip/Database.java deleted file mode 100644 index 0e883d0bd..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/geoip/Database.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.earth2me.essentials.settings.geoip; - -import com.earth2me.essentials.storage.StorageObject; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Database implements StorageObject -{ - boolean showCities = false; - boolean downloadIfMissing = true; - String downloadUrlCity = "http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz"; - String downloadUrl = "http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz"; -} diff --git a/Essentials/src/com/earth2me/essentials/settings/geoip/GeoIP.java b/Essentials/src/com/earth2me/essentials/settings/geoip/GeoIP.java deleted file mode 100644 index 65a909ed4..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/geoip/GeoIP.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.earth2me.essentials.settings.geoip; - -import com.earth2me.essentials.storage.StorageObject; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class GeoIP implements StorageObject -{ - private Database database = new Database(); - boolean showOnWhois = true; - boolean showOnLogin = true; -} diff --git a/Essentials/src/com/earth2me/essentials/settings/protect/Prevent.java b/Essentials/src/com/earth2me/essentials/settings/protect/Prevent.java deleted file mode 100644 index 192e93ac1..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/protect/Prevent.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.earth2me.essentials.settings.protect; - -import com.earth2me.essentials.storage.*; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import lombok.Data; -import lombok.EqualsAndHashCode; -import org.bukkit.Material; -import org.bukkit.entity.CreatureType; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Prevent implements StorageObject -{ - @Comment("Which blocks should a piston not be able to push?") - @ListType(Material.class) - private Set pistonPush = new HashSet(); - private boolean lavaFlow = false; - private boolean waterFlow = false; - // private boolean waterbucketFlow = false; TODO: Test if this still works - private boolean firespread = true; - private boolean lavaFirespread = true; - private boolean lightningFirespread = true; - private boolean portalCreation = false; - private boolean tntExplosion = false; - private boolean fireballExplosion = false; - private boolean fireballFire = false; - private boolean creeperExplosion = false; - private boolean creeperBlockdamage = false; - private boolean enderdragonBlockdamage = false; - private boolean endermanPickup = false; - private boolean villagerDeath = false; - @Comment( - { - "Monsters won't follow players", - "permission essentials.protect.entitytarget.bypass disables this" - }) - private boolean entitytarget = false; - @MapKeyType(CreatureType.class) - @MapValueType(Boolean.class) - private Map spawn = new HashMap(); -} \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/settings/protect/Protect.java b/Essentials/src/com/earth2me/essentials/settings/protect/Protect.java deleted file mode 100644 index bb745ad8f..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/protect/Protect.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.earth2me.essentials.settings.protect; - -import com.earth2me.essentials.storage.Comment; -import com.earth2me.essentials.storage.ListType; -import com.earth2me.essentials.storage.StorageObject; -import java.util.HashSet; -import java.util.Set; -import lombok.Data; -import lombok.EqualsAndHashCode; -import org.bukkit.Material; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Protect implements StorageObject -{ - @Comment("Either mysql or sqlite") - private String dbtype = "sqlite"; - @Comment("If you specified MySQL above, you MUST enter the appropriate details here.") - private String dbuser = "root"; - private String dbpassword = ""; - private String dburl = "jdbc:mysql://localhost:3306/minecraft"; - @Comment("For which block types would you like to be alerted?") - @ListType(Material.class) - private Set alertOnPlacement = new HashSet(); - @ListType(Material.class) - private Set alertOnUse = new HashSet(); - @ListType(Material.class) - private Set alertOnBreak = new HashSet(); - @Comment("General physics/behavior modifications") - private Prevent prevent = new Prevent(); - @Comment( - { - "Maximum height the creeper should explode. -1 allows them to explode everywhere.", - "Set prevent.creeper-explosion to true, if you want to disable creeper explosions." - }) - private int creeperMaxHeight = -1; - @Comment("Should we tell people they are not allowed to build") - private boolean warnOnBuildDisallow = true; - @Comment("Disable weather options") - private boolean disableStorm = false; - private boolean disableThunder = false; - private boolean disableLighting = false; - private SignsAndRails signsAndRails = new SignsAndRails(); -} diff --git a/Essentials/src/com/earth2me/essentials/settings/protect/SignsAndRails.java b/Essentials/src/com/earth2me/essentials/settings/protect/SignsAndRails.java deleted file mode 100644 index dae3897c2..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/protect/SignsAndRails.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.earth2me.essentials.settings.protect; - -import com.earth2me.essentials.storage.Comment; -import com.earth2me.essentials.storage.StorageObject; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class SignsAndRails implements StorageObject -{ - @Comment("Protect all signs") - private boolean protectSigns = true; - @Comment("Prevent users from destroying rails") - private boolean protectRails = true; - @Comment( - { - "Blocks below rails/signs are also protected if the respective rail/sign is protected.", - "This makes it more difficult to circumvent protection, and should be enabled.", - "This only has an effect if rails or signs is also enabled." - }) - private boolean blockBelow = true; - @Comment("Prevent placing blocks above protected rails, this is to stop a potential griefing") - private boolean preventBlockAboveRails = false; -} diff --git a/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileReader.java b/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileReader.java deleted file mode 100644 index 6e342590f..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileReader.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.earth2me.essentials.storage; - -import com.earth2me.essentials.Essentials; -import com.earth2me.essentials.api.IEssentials; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.util.concurrent.locks.ReentrantLock; -import java.util.logging.Level; -import org.bukkit.Bukkit; -import org.bukkit.plugin.Plugin; - - -public abstract class AbstractDelayedYamlFileReader implements Runnable -{ - private final transient Class clazz; - private final transient IEssentials ess; - private final transient ReentrantLock lock = new ReentrantLock(); - - public AbstractDelayedYamlFileReader(final IEssentials ess, final Class clazz) - { - this.clazz = clazz; - this.ess = ess; - } - - public void schedule(boolean instant) - { - if (instant) - { - run(); - } - else - { - ess.getPlugin().scheduleAsyncDelayedTask(this); - } - } - - public abstract File onStart() throws IOException; - - @Override - public void run() - { - lock.lock(); - try - { - final File file = onStart(); - try - { - final FileReader reader = new FileReader(file); - try - { - final T object = new YamlStorageReader(reader, ess.getPlugin()).load(clazz); - onSuccess(object); - } - finally - { - try - { - reader.close(); - } - catch (IOException ex) - { - Bukkit.getLogger().log(Level.SEVERE, "File can't be closed: " + file.toString(), ex); - } - } - - } - catch (FileNotFoundException ex) - { - onException(ex); - Bukkit.getLogger().log(Level.INFO, "File not found: {0}", file.toString()); - } - catch (ObjectLoadException ex) - { - onException(ex); - File broken = new File(file.getAbsolutePath() + ".broken." + System.currentTimeMillis()); - file.renameTo(broken); - Bukkit.getLogger().log(Level.SEVERE, "The file " + file.toString() + " is broken, it has been renamed to " + broken.toString(), ex.getCause()); - } - } - catch (IOException ex) - { - Bukkit.getLogger().log(Level.SEVERE, "File could not be opened: " + ex.getMessage(), ex); - } - finally - { - lock.unlock(); - } - } - - public abstract void onSuccess(T object); - - public abstract void onException(Exception exception); -} diff --git a/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileWriter.java b/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileWriter.java deleted file mode 100644 index 6e264cad8..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileWriter.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.earth2me.essentials.storage; - -import com.earth2me.essentials.Essentials; -import com.earth2me.essentials.api.IEssentials; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.concurrent.locks.ReentrantLock; -import java.util.logging.Level; -import org.bukkit.Bukkit; -import org.bukkit.plugin.Plugin; - - -public abstract class AbstractDelayedYamlFileWriter implements Runnable -{ - private final transient IEssentials ess; - private final transient ReentrantLock lock = new ReentrantLock(); - - public AbstractDelayedYamlFileWriter(final IEssentials ess) - { - this.ess = ess; - } - - public void schedule() - { - ess.getPlugin().scheduleAsyncDelayedTask(this); - } - - public abstract File getFile() throws IOException; - - public abstract StorageObject getObject(); - - @Override - public void run() - { - lock.lock(); - try - { - final File file = getFile(); - PrintWriter pw = null; - try - { - final StorageObject object = getObject(); - final File folder = file.getParentFile(); - if (!folder.exists()) - { - folder.mkdirs(); - } - pw = new PrintWriter(file); - new YamlStorageWriter(pw).save(object); - } - catch (FileNotFoundException ex) - { - Bukkit.getLogger().log(Level.SEVERE, file.toString(), ex); - } - finally - { - onFinish(); - if (pw != null) - { - pw.close(); - } - } - } - catch (IOException ex) - { - Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); - } - finally - { - lock.unlock(); - } - } - - public abstract void onFinish(); -} diff --git a/Essentials/src/com/earth2me/essentials/storage/AsyncStorageObjectHolder.java b/Essentials/src/com/earth2me/essentials/storage/AsyncStorageObjectHolder.java deleted file mode 100644 index 8259dbd79..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/AsyncStorageObjectHolder.java +++ /dev/null @@ -1,186 +0,0 @@ -package com.earth2me.essentials.storage; - -import com.earth2me.essentials.api.IEssentials; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.logging.Level; -import org.bukkit.Bukkit; - - -public abstract class AsyncStorageObjectHolder implements IStorageObjectHolder -{ - private transient T data; - private final transient ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); - private final transient Class clazz; - protected final transient IEssentials ess; - private final transient StorageObjectDataWriter writer; - private final transient StorageObjectDataReader reader; - private final transient AtomicBoolean loaded = new AtomicBoolean(false); - - public AsyncStorageObjectHolder(final IEssentials ess, final Class clazz) - { - this.ess = ess; - this.clazz = clazz; - writer = new StorageObjectDataWriter(); - reader = new StorageObjectDataReader(); - try - { - this.data = clazz.newInstance(); - } - catch (Exception ex) - { - Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); - } - } - - /** - * Warning: If you access this method, you have to acquire a read or write lock first - * - * - * @return Object storing all the data - */ - @Override - public T getData() - { - if (!loaded.get()) - { - reader.schedule(true); - } - return data; - } - - @Override - public void acquireReadLock() - { - rwl.readLock().lock(); - } - - @Override - public void acquireWriteLock() - { - while (rwl.getReadHoldCount() > 0) - { - rwl.readLock().unlock(); - } - rwl.writeLock().lock(); - rwl.readLock().lock(); - } - - @Override - public void close() - { - unlock(); - } - - @Override - public void unlock() - { - if (rwl.isWriteLockedByCurrentThread()) - { - rwl.writeLock().unlock(); - writer.schedule(); - } - while (rwl.getReadHoldCount() > 0) - { - rwl.readLock().unlock(); - } - } - - @Override - public void onReload() - { - onReload(true); - } - - public void onReload(final boolean instant) - { - reader.schedule(instant); - } - - public abstract File getStorageFile() throws IOException; - - - private class StorageObjectDataWriter extends AbstractDelayedYamlFileWriter - { - public StorageObjectDataWriter() - { - super(ess); - } - - @Override - public File getFile() throws IOException - { - return getStorageFile(); - } - - @Override - public StorageObject getObject() - { - acquireReadLock(); - return getData(); - } - - @Override - public void onFinish() - { - unlock(); - } - } - - - private class StorageObjectDataReader extends AbstractDelayedYamlFileReader - { - public StorageObjectDataReader() - { - super(ess, clazz); - } - - @Override - public File onStart() throws IOException - { - final File file = getStorageFile(); - while (rwl.getReadHoldCount() > 0) - { - rwl.readLock().unlock(); - } - rwl.writeLock().lock(); - return file; - } - - @Override - public void onSuccess(final T object) - { - if (object != null) - { - data = object; - } - rwl.writeLock().unlock(); - loaded.set(true); - } - - @Override - public void onException(final Exception exception) - { - if (data == null) - { - try - { - data = clazz.newInstance(); - } - catch (Exception ex) - { - Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); - } - } - rwl.writeLock().unlock(); - loaded.set(true); - if (exception instanceof FileNotFoundException) - { - writer.schedule(); - } - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/storage/BukkitConstructor.java b/Essentials/src/com/earth2me/essentials/storage/BukkitConstructor.java deleted file mode 100644 index d05552192..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/BukkitConstructor.java +++ /dev/null @@ -1,439 +0,0 @@ -package com.earth2me.essentials.storage; - -import com.earth2me.essentials.Essentials; -import com.earth2me.essentials.api.server.IPlugin; -import com.earth2me.essentials.api.server.Material; -import java.lang.reflect.Field; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.regex.Pattern; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; -import org.bukkit.material.MaterialData; -import org.yaml.snakeyaml.TypeDescription; -import org.yaml.snakeyaml.constructor.Constructor; -import org.yaml.snakeyaml.error.YAMLException; -import org.yaml.snakeyaml.introspector.Property; -import org.yaml.snakeyaml.nodes.*; - - -public class BukkitConstructor extends Constructor -{ - private final transient Pattern NUMPATTERN = Pattern.compile("\\d+"); - private final transient IPlugin plugin; - - public BukkitConstructor(final Class clazz, final IPlugin plugin) - { - super(clazz); - this.plugin = plugin; - yamlClassConstructors.put(NodeId.scalar, new ConstructBukkitScalar()); - yamlClassConstructors.put(NodeId.mapping, new ConstructBukkitMapping()); - } - - - private class ConstructBukkitScalar extends ConstructScalar - { - @Override - public Object construct(final Node node) - { - if (node.getType().equals(Material.class)) - { - final String val = (String)constructScalar((ScalarNode)node); - Material mat; - if (NUMPATTERN.matcher(val).matches()) - { - final int typeId = Integer.parseInt(val); - mat = Material.getMaterial(typeId); - } - else - { - mat = Material.matchMaterial(val); - } - return mat; - } - if (node.getType().equals(MaterialData.class)) - { - final String val = (String)constructScalar((ScalarNode)node); - if (val.isEmpty()) - { - return null; - } - final String[] split = val.split("[:+',;.]", 2); - if (split.length == 0) - { - return null; - } - Material mat; - if (NUMPATTERN.matcher(split[0]).matches()) - { - final int typeId = Integer.parseInt(split[0]); - mat = Material.get(typeId); - } - else - { - mat = Material.match(split[0]); - } - if (mat == null) - { - return null; - } - byte data = 0; - if (split.length == 2 && NUMPATTERN.matcher(split[1]).matches()) - { - data = Byte.parseByte(split[1]); - } - return new MaterialData(mat, data); - } - if (node.getType().equals(ItemStack.class)) - { - final String val = (String)constructScalar((ScalarNode)node); - if (val.isEmpty()) - { - return null; - } - final String[] split1 = val.split("\\W"); - if (split1.length == 0) - { - return null; - } - final String[] split2 = split1[0].split("[:+',;.]", 2); - if (split2.length == 0) - { - return null; - } - Material mat; - if (NUMPATTERN.matcher(split2[0]).matches()) - { - final int typeId = Integer.parseInt(split2[0]); - mat = Material.getMaterial(typeId); - } - else - { - mat = Material.matchMaterial(split2[0]); - } - if (mat == null) - { - return null; - } - short data = 0; - if (split2.length == 2 && NUMPATTERN.matcher(split2[1]).matches()) - { - data = Short.parseShort(split2[1]); - } - int size = mat.getMaxStackSize(); - if (split1.length > 1 && NUMPATTERN.matcher(split1[1]).matches()) - { - size = Integer.parseInt(split1[1]); - } - final ItemStack stack = new ItemStack(mat, size, data); - if (split1.length > 2) - { - for (int i = 2; i < split1.length; i++) - { - final String[] split3 = split1[0].split("[:+',;.]", 2); - if (split3.length < 1) - { - continue; - } - Enchantment enchantment; - if (NUMPATTERN.matcher(split3[0]).matches()) - { - final int enchantId = Integer.parseInt(split3[0]); - enchantment = Enchantment.getById(enchantId); - } - else - { - enchantment = Enchantment.getByName(split3[0].toUpperCase(Locale.ENGLISH)); - } - if (enchantment == null) - { - continue; - } - int level = enchantment.getStartLevel(); - if (split3.length == 2 && NUMPATTERN.matcher(split3[1]).matches()) - { - level = Integer.parseInt(split3[1]); - } - if (level < enchantment.getStartLevel()) - { - level = enchantment.getStartLevel(); - } - if (level > enchantment.getMaxLevel()) - { - level = enchantment.getMaxLevel(); - } - stack.addUnsafeEnchantment(enchantment, level); - } - } - return stack; - } - if (node.getType().equals(EnchantmentLevel.class)) - { - final String val = (String)constructScalar((ScalarNode)node); - if (val.isEmpty()) - { - return null; - } - final String[] split = val.split("[:+',;.]", 2); - if (split.length == 0) - { - return null; - } - Enchantment enchant; - if (NUMPATTERN.matcher(split[0]).matches()) - { - final int typeId = Integer.parseInt(split[0]); - enchant = Enchantment.getById(typeId); - } - else - { - enchant = Enchantment.getByName(split[0].toUpperCase(Locale.ENGLISH)); - } - if (enchant == null) - { - return null; - } - int level = enchant.getStartLevel(); - if (split.length == 2 && NUMPATTERN.matcher(split[1]).matches()) - { - level = Integer.parseInt(split[1]); - } - if (level < enchant.getStartLevel()) - { - level = enchant.getStartLevel(); - } - if (level > enchant.getMaxLevel()) - { - level = enchant.getMaxLevel(); - } - return new EnchantmentLevel(enchant, level); - } - if (node.getType().isEnum()) - { - final String val = (String)constructScalar((ScalarNode)node); - if (val.isEmpty()) - { - return null; - } - for (Object object : node.getType().getEnumConstants()) - { - if (object.toString().equalsIgnoreCase(val)) - { - return object; - } - } - return null; - } - return super.construct(node); - } - } - - - private class ConstructBukkitMapping extends ConstructMapping - { - @Override - public Object construct(final Node node) - { - if (node.getType().equals(StoredLocation.class)) - { - //TODO: NPE checks - final MappingNode mnode = (MappingNode)node; - String worldName = ""; - double x = 0, y = 0, z = 0; - float yaw = 0, pitch = 0; - if (mnode.getValue().size() < 4) - { - return null; - } - for (NodeTuple nodeTuple : mnode.getValue()) - { - final String key = (String)constructScalar((ScalarNode)nodeTuple.getKeyNode()); - final ScalarNode snode = (ScalarNode)nodeTuple.getValueNode(); - if (key.equalsIgnoreCase("world")) - { - worldName = (String)constructScalar(snode); - } - if (key.equalsIgnoreCase("x")) - { - x = Double.parseDouble((String)constructScalar(snode)); - } - if (key.equalsIgnoreCase("y")) - { - y = Double.parseDouble((String)constructScalar(snode)); - } - if (key.equalsIgnoreCase("z")) - { - z = Double.parseDouble((String)constructScalar(snode)); - } - if (key.equalsIgnoreCase("yaw")) - { - yaw = Float.parseFloat((String)constructScalar(snode)); - } - if (key.equalsIgnoreCase("pitch")) - { - pitch = Float.parseFloat((String)constructScalar(snode)); - } - } - if (worldName == null || worldName.isEmpty()) - { - return null; - } - return new StoredLocation(worldName, x, y, z, yaw, pitch); - } - return super.construct(node); - } - - @Override - protected Object constructJavaBean2ndStep(final MappingNode node, final Object object) - { - Map, TypeDescription> typeDefinitions; - try - { - final Field typeDefField = Constructor.class.getDeclaredField("typeDefinitions"); - typeDefField.setAccessible(true); - typeDefinitions = (Map, TypeDescription>)typeDefField.get((Constructor)BukkitConstructor.this); - if (typeDefinitions == null) - { - throw new NullPointerException(); - } - } - catch (Exception ex) - { - throw new YAMLException(ex); - } - flattenMapping(node); - final Class beanType = node.getType(); - final List nodeValue = node.getValue(); - for (NodeTuple tuple : nodeValue) - { - ScalarNode keyNode; - if (tuple.getKeyNode() instanceof ScalarNode) - { - // key must be scalar - keyNode = (ScalarNode)tuple.getKeyNode(); - } - else - { - throw new YAMLException("Keys must be scalars but found: " + tuple.getKeyNode()); - } - final Node valueNode = tuple.getValueNode(); - // keys can only be Strings - keyNode.setType(String.class); - final String key = (String)constructObject(keyNode); - try - { - Property property; - try - { - property = getProperty(beanType, key); - } - catch (YAMLException e) - { - continue; - } - valueNode.setType(property.getType()); - final TypeDescription memberDescription = typeDefinitions.get(beanType); - boolean typeDetected = false; - if (memberDescription != null) - { - switch (valueNode.getNodeId()) - { - case sequence: - final SequenceNode snode = (SequenceNode)valueNode; - final Class memberType = memberDescription.getListPropertyType(key); - if (memberType != null) - { - snode.setListType(memberType); - typeDetected = true; - } - else if (property.getType().isArray()) - { - snode.setListType(property.getType().getComponentType()); - typeDetected = true; - } - break; - case mapping: - final MappingNode mnode = (MappingNode)valueNode; - final Class keyType = memberDescription.getMapKeyType(key); - if (keyType != null) - { - mnode.setTypes(keyType, memberDescription.getMapValueType(key)); - typeDetected = true; - } - break; - } - } - if (!typeDetected && valueNode.getNodeId() != NodeId.scalar) - { - // only if there is no explicit TypeDescription - final Class[] arguments = property.getActualTypeArguments(); - if (arguments != null) - { - // type safe (generic) collection may contain the - // proper class - if (valueNode.getNodeId() == NodeId.sequence) - { - final Class t = arguments[0]; - final SequenceNode snode = (SequenceNode)valueNode; - snode.setListType(t); - } - else if (valueNode.getTag().equals(Tag.SET)) - { - final Class t = arguments[0]; - final MappingNode mnode = (MappingNode)valueNode; - mnode.setOnlyKeyType(t); - mnode.setUseClassConstructor(true); - } - else if (property.getType().isAssignableFrom(Map.class)) - { - final Class ketType = arguments[0]; - final Class valueType = arguments[1]; - final MappingNode mnode = (MappingNode)valueNode; - mnode.setTypes(ketType, valueType); - mnode.setUseClassConstructor(true); - } - else - { - // the type for collection entries cannot be - // detected - } - } - } - final Object value = constructObject(valueNode); - property.set(object, value); - } - catch (Exception e) - { - throw new YAMLException("Cannot create property=" + key + " for JavaBean=" - + object + "; " + e.getMessage(), e); - } - } - return object; - } - } - - @Override - protected Class getClassForNode(final Node node) - { - Class clazz; - final String name = node.getTag().getClassName(); - if (Essentials.testing) - { - clazz = super.getClassForNode(node); - } - else - { - clazz = plugin.getClassByName(name); - } - - if (clazz == null) - { - throw new YAMLException("Class not found: " + name); - } - else - { - return clazz; - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/storage/Comment.java b/Essentials/src/com/earth2me/essentials/storage/Comment.java deleted file mode 100644 index 8cb9d4d31..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/Comment.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.earth2me.essentials.storage; - -import java.lang.annotation.*; - - -@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 deleted file mode 100644 index 2eb062ae8..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/EnchantmentLevel.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.earth2me.essentials.storage; - -import java.util.Map.Entry; -import org.bukkit.enchantments.Enchantment; - - -public class EnchantmentLevel implements Entry -{ - private Enchantment enchantment; - private int level; - - public EnchantmentLevel(final Enchantment enchantment, final int level) - { - this.enchantment = enchantment; - this.level = level; - } - - public Enchantment getEnchantment() - { - return enchantment; - } - - public void setEnchantment(final Enchantment enchantment) - { - this.enchantment = enchantment; - } - - public int getLevel() - { - return level; - } - - public void setLevel(final int level) - { - this.level = level; - } - - @Override - public Enchantment getKey() - { - return enchantment; - } - - @Override - public Integer getValue() - { - return level; - } - - @Override - public Integer setValue(final Integer v) - { - int t = level; - level = v; - return t; - } - - @Override - public int hashCode() - { - return enchantment.hashCode() ^ level; - } - - @Override - public boolean equals(final Object obj) - { - if (obj instanceof Entry) - { - final Entry entry = (Entry)obj; - if (entry.getKey() instanceof Enchantment - && entry.getValue() instanceof Integer) - { - final Enchantment objEnchantment = (Enchantment)entry.getKey(); - final Integer objLevel = (Integer)entry.getValue(); - return enchantment.equals(objEnchantment) && level == objLevel.intValue(); - } - } - return false; - } -} diff --git a/Essentials/src/com/earth2me/essentials/storage/IStorageObjectHolder.java b/Essentials/src/com/earth2me/essentials/storage/IStorageObjectHolder.java deleted file mode 100644 index 0d582ece8..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/IStorageObjectHolder.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.earth2me.essentials.storage; - -import com.earth2me.essentials.api.IReload; - - -public interface IStorageObjectHolder extends IReload -{ - T getData(); - - void acquireReadLock(); - - void acquireWriteLock(); - - void close(); - - void unlock(); -} diff --git a/Essentials/src/com/earth2me/essentials/storage/IStorageObjectMap.java b/Essentials/src/com/earth2me/essentials/storage/IStorageObjectMap.java deleted file mode 100644 index 788d80e65..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/IStorageObjectMap.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.earth2me.essentials.storage; - -import com.earth2me.essentials.api.IReload; -import com.earth2me.essentials.api.InvalidNameException; -import java.io.File; -import java.util.Set; - - -interface IStorageObjectMap extends IReload -{ - boolean objectExists(final String name); - - I getObject(final String name); - - void removeObject(final String name) throws InvalidNameException; - - Set getAllKeys(); - - int getKeySize(); - - File getStorageFile(final String name) throws InvalidNameException; -} diff --git a/Essentials/src/com/earth2me/essentials/storage/IStorageReader.java b/Essentials/src/com/earth2me/essentials/storage/IStorageReader.java deleted file mode 100644 index e92774809..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/IStorageReader.java +++ /dev/null @@ -1,7 +0,0 @@ -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 deleted file mode 100644 index 5b8498869..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/IStorageWriter.java +++ /dev/null @@ -1,7 +0,0 @@ -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 deleted file mode 100644 index 9bf6e2e64..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/ListType.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.earth2me.essentials.storage; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - - -@Target(ElementType.FIELD) -@Retention(RetentionPolicy.RUNTIME) -public @interface ListType -{ - Class value() default String.class; -} diff --git a/Essentials/src/com/earth2me/essentials/storage/ManagedFile.java b/Essentials/src/com/earth2me/essentials/storage/ManagedFile.java deleted file mode 100644 index aeb9c5dcf..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/ManagedFile.java +++ /dev/null @@ -1,228 +0,0 @@ -package com.earth2me.essentials.storage; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IEssentials; -import java.io.*; -import java.math.BigInteger; -import java.security.DigestInputStream; -import java.security.DigestOutputStream; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.logging.Level; -import org.bukkit.Bukkit; - - -public class ManagedFile -{ - private final static int BUFFERSIZE = 1024 * 8; - private final transient File file; - - public ManagedFile(final String filename, final IEssentials ess) - { - file = new File(ess.getPlugin().getDataFolder(), filename); - - if (file.exists()) - { - try - { - if (checkForVersion(file, ess.getPlugin().getVersion()) && !file.delete()) - { - throw new IOException("Could not delete file " + file.toString()); - } - } - catch (IOException ex) - { - Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); - } - } - - if (!file.exists()) - { - try - { - copyResourceAscii("/" + filename, file); - } - catch (IOException ex) - { - Bukkit.getLogger().log(Level.SEVERE, _("itemsCsvNotLoaded"), ex); - } - } - } - - public static void copyResourceAscii(final String resourceName, final File file) throws IOException - { - final InputStreamReader reader = new InputStreamReader(ManagedFile.class.getResourceAsStream(resourceName)); - try - { - final MessageDigest digest = getDigest(); - final DigestOutputStream digestStream = new DigestOutputStream(new FileOutputStream(file), digest); - try - { - final OutputStreamWriter writer = new OutputStreamWriter(digestStream); - try - { - final char[] buffer = new char[BUFFERSIZE]; - do - { - final int length = reader.read(buffer); - if (length >= 0) - { - writer.write(buffer, 0, length); - } - else - { - break; - } - } - while (true); - writer.write("\n"); - writer.flush(); - final BigInteger hashInt = new BigInteger(1, digest.digest()); - digestStream.on(false); - digestStream.write('#'); - digestStream.write(hashInt.toString(16).getBytes()); - } - finally - { - writer.close(); - } - } - finally - { - digestStream.close(); - } - } - finally - { - reader.close(); - } - } - - public static boolean checkForVersion(final File file, final String version) throws IOException - { - if (file.length() < 33) - { - return false; - } - final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); - try - { - final byte[] buffer = new byte[(int)file.length()]; - int position = 0; - do - { - final int length = bis.read(buffer, position, Math.min((int)file.length() - position, BUFFERSIZE)); - if (length < 0) - { - break; - } - position += length; - } - while (position < file.length()); - final ByteArrayInputStream bais = new ByteArrayInputStream(buffer); - if (bais.skip(file.length() - 33) != file.length() - 33) - { - return false; - } - final BufferedReader reader = new BufferedReader(new InputStreamReader(bais)); - try - { - String hash = reader.readLine(); - if (hash != null && hash.matches("#[a-f0-9]{32}")) - { - hash = hash.substring(1); - bais.reset(); - final String versionline = reader.readLine(); - if (versionline != null && versionline.matches("#version: .+")) - { - final String versioncheck = versionline.substring(10); - if (!versioncheck.equalsIgnoreCase(version)) - { - bais.reset(); - final MessageDigest digest = getDigest(); - final DigestInputStream digestStream = new DigestInputStream(bais, digest); - try - { - final byte[] bytes = new byte[(int)file.length() - 33]; - digestStream.read(bytes); - final BigInteger correct = new BigInteger(hash, 16); - final BigInteger test = new BigInteger(1, digest.digest()); - if (correct.equals(test)) - { - return true; - } - else - { - Bukkit.getLogger().warning("File " + file.toString() + " has been modified by user and file version differs, please update the file manually."); - } - } - finally - { - digestStream.close(); - } - } - } - } - } - finally - { - reader.close(); - } - } - finally - { - bis.close(); - } - return false; - } - - public static MessageDigest getDigest() throws IOException - { - try - { - return MessageDigest.getInstance("MD5"); - } - catch (NoSuchAlgorithmException ex) - { - throw new IOException(ex); - } - } - - public List getLines() - { - try - { - final BufferedReader reader = new BufferedReader(new FileReader(file)); - try - { - final List lines = new ArrayList(); - do - { - final String line = reader.readLine(); - if (line == null) - { - break; - } - else - { - lines.add(line); - } - } - while (true); - return lines; - } - finally - { - reader.close(); - } - } - catch (IOException ex) - { - Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); - return Collections.emptyList(); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/storage/MapKeyType.java b/Essentials/src/com/earth2me/essentials/storage/MapKeyType.java deleted file mode 100644 index aa162e51c..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/MapKeyType.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.earth2me.essentials.storage; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - - -@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 deleted file mode 100644 index 1b5fff978..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/MapValueType.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.earth2me.essentials.storage; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - - -@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 deleted file mode 100644 index 8b804abc3..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/ObjectLoadException.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.earth2me.essentials.storage; - - -public class ObjectLoadException extends Exception -{ - public ObjectLoadException(Throwable thrwbl) - { - super(thrwbl); - } -} diff --git a/Essentials/src/com/earth2me/essentials/storage/StorageObject.java b/Essentials/src/com/earth2me/essentials/storage/StorageObject.java deleted file mode 100644 index 0c66fefcf..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/StorageObject.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.earth2me.essentials.storage; - - -public interface StorageObject -{ -} diff --git a/Essentials/src/com/earth2me/essentials/storage/StorageObjectMap.java b/Essentials/src/com/earth2me/essentials/storage/StorageObjectMap.java deleted file mode 100644 index 3ad231c87..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/StorageObjectMap.java +++ /dev/null @@ -1,137 +0,0 @@ -package com.earth2me.essentials.storage; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.InvalidNameException; -import com.earth2me.essentials.utils.Util; -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.util.concurrent.UncheckedExecutionException; -import java.io.File; -import java.io.IOException; -import java.util.Collections; -import java.util.Locale; -import java.util.Set; -import java.util.concurrent.ConcurrentSkipListSet; -import java.util.concurrent.ExecutionException; -import java.util.logging.Level; - - -public abstract class StorageObjectMap extends CacheLoader implements IStorageObjectMap -{ - protected final transient IEssentials ess; - private final transient File folder; - protected final transient Cache cache = CacheBuilder.newBuilder().softValues().build(this); - protected final transient ConcurrentSkipListSet keys = new ConcurrentSkipListSet(); - - public StorageObjectMap(final IEssentials ess, final String folderName) - { - super(); - this.ess = ess; - this.folder = new File(ess.getPlugin().getDataFolder(), folderName); - if (!folder.exists()) - { - folder.mkdirs(); - } - loadAllObjectsAsync(); - } - - private void loadAllObjectsAsync() - { - ess.getPlugin().scheduleAsyncDelayedTask(new Runnable() - { - @Override - public void run() - { - if (!folder.exists() || !folder.isDirectory()) - { - return; - } - keys.clear(); - cache.invalidateAll(); - for (String string : folder.list()) - { - try - { - if (!string.endsWith(".yml")) - { - continue; - } - final String name = Util.decodeFileName(string.substring(0, string.length() - 4)); - keys.add(name.toLowerCase(Locale.ENGLISH)); - } - catch (InvalidNameException ex) - { - ess.getLogger().log(Level.WARNING, "Invalid filename: " + string, ex); - } - } - } - }); - } - - @Override - public boolean objectExists(final String name) - { - return keys.contains(name.toLowerCase(Locale.ENGLISH)); - } - - @Override - public I getObject(final String name) - { - try - { - return (I)cache.get(name.toLowerCase(Locale.ENGLISH)); - } - catch (ExecutionException ex) - { - return null; - } - catch (UncheckedExecutionException ex) - { - return null; - } - } - - @Override - public abstract I load(final String name) throws Exception; - - @Override - public void removeObject(final String name) throws InvalidNameException - { - keys.remove(name.toLowerCase(Locale.ENGLISH)); - cache.invalidate(name.toLowerCase(Locale.ENGLISH)); - final File file = getStorageFile(name); - if (file.exists()) - { - file.delete(); - } - } - - @Override - public Set getAllKeys() - { - return Collections.unmodifiableSet(keys); - } - - @Override - public int getKeySize() - { - return keys.size(); - } - - @Override - public File getStorageFile(final String name) throws InvalidNameException - { - if (!folder.exists() || !folder.isDirectory()) - { - throw new InvalidNameException(new IOException("Folder does not exists: " + folder)); - } - return new File(folder, Util.sanitizeFileName(name) + ".yml"); - } - - @Override - public void onReload() - { - loadAllObjectsAsync(); - } -} diff --git a/Essentials/src/com/earth2me/essentials/storage/StoredLocation.java b/Essentials/src/com/earth2me/essentials/storage/StoredLocation.java deleted file mode 100644 index d1c188b74..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/StoredLocation.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.earth2me.essentials.storage; - -import com.earth2me.essentials.api.server.World; -import com.earth2me.essentials.api.server.Location; -import java.lang.ref.WeakReference; -import java.util.UUID; - - -public class StoredLocation -{ - private WeakReference location; - private final String worldname; - private UUID worldUID = null; - private final double x; - private final double y; - private final double z; - private final float yaw; - private final float pitch; - - public StoredLocation(Location loc) - { - location = new WeakReference(loc); - worldname = loc.getWorld().getName(); - worldUID = loc.getWorld().getUID(); - x = loc.getX(); - y = loc.getY(); - z = loc.getZ(); - yaw = loc.getYaw(); - pitch = loc.getPitch(); - } - - public StoredLocation(String worldname, double x, double y, double z, float yaw, float pitch) - { - this.worldname = worldname; - this.x = x; - this.y = y; - this.z = z; - this.yaw = yaw; - this.pitch = pitch; - } - - public StoredLocation(String worldname, double x, double y, double z) - { - this.worldname = worldname; - this.x = x; - this.y = y; - this.z = z; - this.yaw = 0f; - this.pitch = 0f; - } - - public Location getStoredLocation() throws WorldNotLoadedException - { - - Location loc = location == null ? null : location.get(); - if (loc == null) - { - World world = null; - if (worldUID != null) - { - world = Bukkit.getWorld(worldUID); - } - if (world == null) - { - world = Bukkit.getWorld(worldname); - } - if (world == null) - { - throw new WorldNotLoadedException(worldname); - } - loc = Location.create(world, getX(), getY(), getZ(), getYaw(), getPitch()); - location = new WeakReference(loc); - } - return loc; - } - - public String getWorldName() - { - return worldname; - } - - public double getX() - { - return x; - } - - public double getY() - { - return y; - } - - public double getZ() - { - return z; - } - - public float getYaw() - { - return yaw; - } - - public float getPitch() - { - return pitch; - } - - - public static class WorldNotLoadedException extends Exception - { - public WorldNotLoadedException(String worldname) - { - super("World " + worldname + " is not loaded."); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/storage/YamlStorageReader.java b/Essentials/src/com/earth2me/essentials/storage/YamlStorageReader.java deleted file mode 100644 index ea9d193fe..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/YamlStorageReader.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.earth2me.essentials.storage; - -import com.earth2me.essentials.api.server.IPlugin; -import java.io.Reader; -import java.lang.reflect.Field; -import java.util.*; -import java.util.concurrent.locks.ReentrantLock; -import org.yaml.snakeyaml.TypeDescription; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.Constructor; - - -public class YamlStorageReader implements IStorageReader -{ - private transient static final Map PREPARED_YAMLS = Collections.synchronizedMap(new HashMap()); - private transient static final Map LOCKS = new HashMap(); - private transient final Reader reader; - private transient final IPlugin plugin; - - public YamlStorageReader(final Reader reader, final IPlugin plugin) - { - this.reader = reader; - this.plugin = plugin; - } - - @Override - public T load(final Class clazz) throws ObjectLoadException - { - Yaml yaml = PREPARED_YAMLS.get(clazz); - if (yaml == null) - { - yaml = new Yaml(prepareConstructor(clazz)); - PREPARED_YAMLS.put(clazz, yaml); - } - ReentrantLock lock; - synchronized (LOCKS) - { - lock = LOCKS.get(clazz); - if (lock == null) - { - lock = new ReentrantLock(); - } - } - lock.lock(); - try - { - T object = (T)yaml.load(reader); - if (object == null) - { - object = clazz.newInstance(); - } - return object; - } - catch (Exception ex) - { - throw new ObjectLoadException(ex); - } - finally - { - lock.unlock(); - } - } - - private Constructor prepareConstructor(final Class clazz) - { - final Constructor constructor = new BukkitConstructor(clazz, plugin); - final Set classes = new HashSet(); - - prepareConstructor(constructor, classes, clazz); - return constructor; - } - - 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()) - { - prepareList(field, description, classes, constructor); - prepareMap(field, description, classes, constructor); - if (StorageObject.class.isAssignableFrom(field.getType()) - && !classes.contains(field.getType())) - { - prepareConstructor(constructor, classes, field.getType()); - } - } - constructor.addTypeDescription(description); - } - - private void prepareList(final Field field, final TypeDescription description, final Set classes, final Constructor constructor) - { - final ListType listType = field.getAnnotation(ListType.class); - if (listType != null) - { - description.putListPropertyType(field.getName(), listType.value()); - if (StorageObject.class.isAssignableFrom(listType.value()) - && !classes.contains(listType.value())) - { - prepareConstructor(constructor, classes, listType.value()); - } - } - } - - private void prepareMap(final Field field, final TypeDescription description, final Set classes, final Constructor constructor) - { - final MapValueType mapType = field.getAnnotation(MapValueType.class); - if (mapType != null) - { - final MapKeyType mapKeyType = field.getAnnotation(MapKeyType.class); - description.putMapPropertyType(field.getName(), - mapKeyType == null ? String.class : mapKeyType.value(), - mapType.value()); - if (StorageObject.class.isAssignableFrom(mapType.value()) - && !classes.contains(mapType.value())) - { - prepareConstructor(constructor, classes, mapType.value()); - } - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/storage/YamlStorageWriter.java b/Essentials/src/com/earth2me/essentials/storage/YamlStorageWriter.java deleted file mode 100644 index a693745b2..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/YamlStorageWriter.java +++ /dev/null @@ -1,348 +0,0 @@ -package com.earth2me.essentials.storage; - -import java.io.PrintWriter; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.Collection; -import java.util.Collections; -import java.util.Locale; -import java.util.Map; -import java.util.Map.Entry; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Pattern; -import org.bukkit.Material; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; -import org.bukkit.material.MaterialData; -import org.yaml.snakeyaml.Yaml; - - -public class YamlStorageWriter implements IStorageWriter -{ - private transient static final Pattern NON_WORD_PATTERN = Pattern.compile("\\W"); - private transient final PrintWriter writer; - private transient static final Yaml YAML = new Yaml(); - - public YamlStorageWriter(final PrintWriter writer) - { - this.writer = writer; - } - - @Override - public void save(final StorageObject object) - { - try - { - writeToFile(object, 0, object.getClass()); - } - catch (IllegalArgumentException ex) - { - Logger.getLogger(YamlStorageWriter.class.getName()).log(Level.SEVERE, null, ex); - } - catch (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()) - { - final int modifier = field.getModifiers(); - if (Modifier.isPrivate(modifier) && !Modifier.isTransient(modifier) && !Modifier.isStatic(modifier)) - { - field.setAccessible(true); - - final Object data = field.get(object); - if (writeKey(field, depth, data)) - { - continue; - } - if (data instanceof StorageObject) - { - writer.println(); - writeToFile(data, depth + 1, data.getClass()); - } - else if (data instanceof Map) - { - writeMap((Map)data, depth + 1); - } - else if (data instanceof Collection) - { - writeCollection((Collection)data, depth + 1); - } - else if (data instanceof StoredLocation) - { - writeLocation((StoredLocation)data, depth + 1); - } - else - { - writeScalar(data); - writer.println(); - } - } - } - } - - private boolean writeKey(final Field field, final int depth, final Object data) - { - final boolean commentPresent = writeComment(field, depth); - if (data == null && !commentPresent) - { - return true; - } - writeIndention(depth); - if (data == null && commentPresent) - { - writer.print('#'); - } - final String name = field.getName(); - writer.print(name); - writer.print(": "); - if (data == null && commentPresent) - { - writer.println(); - writer.println(); - return true; - } - return false; - } - - private boolean writeComment(final Field field, final int depth) - { - final boolean commentPresent = field.isAnnotationPresent(Comment.class); - if (commentPresent) - { - final Comment comments = field.getAnnotation(Comment.class); - for (String comment : comments.value()) - { - final String trimmed = comment.trim(); - if (trimmed.isEmpty()) - { - continue; - } - writeIndention(depth); - writer.print("# "); - writer.print(trimmed); - writer.println(); - } - } - return commentPresent; - } - - private void writeCollection(final Collection data, final int depth) throws IllegalAccessException - { - writer.println(); - if (data.isEmpty()) - { - writer.println(); - } - for (Object entry : data) - { - if (entry != null) - { - writeIndention(depth); - writer.print("- "); - if (entry instanceof StorageObject) - { - writer.println(); - writeToFile(entry, depth + 1, entry.getClass()); - } - else if (entry instanceof StoredLocation) - { - writeLocation((StoredLocation)entry, depth + 1); - } - else - { - writeScalar(entry); - } - } - } - writer.println(); - } - - private void writeMap(final Map data, final int depth) throws IllegalArgumentException, IllegalAccessException - { - writer.println(); - if (data.isEmpty()) - { - writer.println(); - } - for (Entry entry : data.entrySet()) - { - final Object value = entry.getValue(); - if (value != null) - { - writeIndention(depth); - writeKey(entry.getKey()); - writer.print(": "); - if (value instanceof StorageObject) - { - writer.println(); - writeToFile(value, depth + 1, value.getClass()); - } - else if (value instanceof Collection) - { - writeCollection((Collection)value, depth + 1); - } - else if (value instanceof StoredLocation) - { - writeLocation((StoredLocation)value, depth + 1); - } - else - { - writeScalar(value); - writer.println(); - } - } - } - } - - private void writeIndention(final int depth) - { - for (int i = 0; i < depth; i++) - { - writer.print(" "); - } - } - - private void writeScalar(final Object data) - { - if (data instanceof String || data instanceof Boolean || data instanceof Number) - { - synchronized (YAML) - { - YAML.dumpAll(Collections.singletonList(data).iterator(), writer); - } - } - else if (data instanceof Enum) - { - writeMaterial(data.toString()); - writer.println(); - } - else if (data instanceof Material) - { - writeMaterial(data); - writer.println(); - } - else if (data instanceof MaterialData) - { - writeMaterialData(data); - writer.println(); - } - else if (data instanceof ItemStack) - { - writeItemStack(data); - writer.println(); - } - else if (data instanceof EnchantmentLevel) - { - writeEnchantmentLevel(data); - writer.println(); - } - else - { - throw new UnsupportedOperationException(); - } - } - - private void writeKey(final Object data) - { - if (data instanceof String || data instanceof Boolean || data instanceof Number) - { - String output = data.toString(); - if (NON_WORD_PATTERN.matcher(output).find()) - { - writer.print('"'); - writer.print(output.replace("\"", "\\\"")); - writer.print('"'); - } - else - { - writer.print(output); - } - } - else if (data instanceof Enum) - { - writeMaterial(data.toString()); - } - else if (data instanceof Material) - { - writeMaterial(data); - } - else if (data instanceof MaterialData) - { - writeMaterialData(data); - } - else if (data instanceof EnchantmentLevel) - { - writeEnchantmentLevel(data); - } - else - { - throw new UnsupportedOperationException(); - } - } - - private void writeMaterial(final Object data) - { - writer.print(data.toString().toLowerCase(Locale.ENGLISH)); - } - - private void writeMaterialData(final Object data) - { - final MaterialData matData = (MaterialData)data; - writeMaterial(matData.getItemType()); - if (matData.getData() > 0) - { - writer.print(':'); - writer.print(matData.getData()); - } - } - - private void writeItemStack(final Object data) - { - final ItemStack itemStack = (ItemStack)data; - writeMaterialData(itemStack.getData()); - writer.print(' '); - writer.print(itemStack.getAmount()); - for (Entry entry : itemStack.getEnchantments().entrySet()) - { - writer.print(' '); - writeEnchantmentLevel(entry); - } - } - - private void writeEnchantmentLevel(Object data) - { - final Entry enchLevel = (Entry)data; - writer.print(enchLevel.getKey().getName().toLowerCase(Locale.ENGLISH)); - writer.print(':'); - writer.print(enchLevel.getValue()); - } - - private void writeLocation(final StoredLocation entry, final int depth) - { - writer.println(); - writeIndention(depth); - writer.print("world: "); - writeScalar(entry.getWorldName()); - writeIndention(depth); - writer.print("x: "); - writeScalar(entry.getX()); - writeIndention(depth); - writer.print("y: "); - writeScalar(entry.getY()); - writeIndention(depth); - writer.print("z: "); - writeScalar(entry.getZ()); - writeIndention(depth); - writer.print("yaw: "); - writeScalar(entry.getYaw()); - writeIndention(depth); - writer.print("pitch: "); - writeScalar(entry.getPitch()); - } -} diff --git a/Essentials/src/com/earth2me/essentials/user/Ban.java b/Essentials/src/com/earth2me/essentials/user/Ban.java deleted file mode 100644 index ba1c22333..000000000 --- a/Essentials/src/com/earth2me/essentials/user/Ban.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.earth2me.essentials.user; - -import com.earth2me.essentials.storage.StorageObject; -import lombok.Data; -import lombok.EqualsAndHashCode; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Ban implements StorageObject -{ - private String reason; - private long timeout; -} diff --git a/Essentials/src/com/earth2me/essentials/user/CooldownException.java b/Essentials/src/com/earth2me/essentials/user/CooldownException.java deleted file mode 100644 index b986a5552..000000000 --- a/Essentials/src/com/earth2me/essentials/user/CooldownException.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.earth2me.essentials.user; - - -public class CooldownException extends Exception -{ - - public CooldownException(String timeLeft) - { - super(timeLeft); - } - -} diff --git a/Essentials/src/com/earth2me/essentials/user/IOfflinePlayer.java b/Essentials/src/com/earth2me/essentials/user/IOfflinePlayer.java deleted file mode 100644 index 434113f25..000000000 --- a/Essentials/src/com/earth2me/essentials/user/IOfflinePlayer.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.earth2me.essentials.user; - -import org.bukkit.Location; -import org.bukkit.permissions.Permission; - - -public interface IOfflinePlayer -{ - String getName(); - - String getDisplayName(); - - //Location getBedSpawnLocation(); - - void setBanned(boolean bln); - - boolean hasPermission(Permission perm); -} \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/user/IOfflineUser.java b/Essentials/src/com/earth2me/essentials/user/IOfflineUser.java deleted file mode 100644 index 144955f57..000000000 --- a/Essentials/src/com/earth2me/essentials/user/IOfflineUser.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.earth2me.essentials.user; - -import com.earth2me.essentials.storage.IStorageObjectHolder; - - -public interface IOfflineUser extends IStorageObjectHolder//, IOfflinePlayer -{ - -} diff --git a/Essentials/src/com/earth2me/essentials/user/Inventory.java b/Essentials/src/com/earth2me/essentials/user/Inventory.java deleted file mode 100644 index 16ba39937..000000000 --- a/Essentials/src/com/earth2me/essentials/user/Inventory.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.earth2me.essentials.user; - -import com.earth2me.essentials.storage.MapKeyType; -import com.earth2me.essentials.storage.MapValueType; -import com.earth2me.essentials.storage.StorageObject; -import java.util.HashMap; -import java.util.Map; -import lombok.Data; -import lombok.EqualsAndHashCode; -import org.bukkit.inventory.ItemStack; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class Inventory implements StorageObject -{ - private int size; - @MapKeyType(Integer.class) - @MapValueType(ItemStack.class) - private Map items = null; - - public Inventory() - { - } - - public Inventory(ItemStack[] contents) - { - size = contents.length; - if (items == null) { - items = new HashMap(size); - } - items.clear(); - for (int i = 0; i < contents.length; i++) - { - ItemStack itemStack = contents[i]; - if (itemStack == null) { - continue; - } - items.put(i, itemStack); - } - } - - public ItemStack[] getBukkitInventory() - { - if (items == null) { - throw new IllegalStateException(); - } - final ItemStack[] inventory = new ItemStack[size]; - for (Map.Entry entry : items.entrySet()) - { - if (entry.getKey() < 0 || entry.getKey()>= size) { - continue; - } - inventory[entry.getKey()] = entry.getValue(); - } - return inventory; - } -} diff --git a/Essentials/src/com/earth2me/essentials/user/TooManyMatchesException.java b/Essentials/src/com/earth2me/essentials/user/TooManyMatchesException.java deleted file mode 100644 index 61e266958..000000000 --- a/Essentials/src/com/earth2me/essentials/user/TooManyMatchesException.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.earth2me.essentials.user; - -public class TooManyMatchesException extends Exception { - -} diff --git a/Essentials/src/com/earth2me/essentials/user/User.java b/Essentials/src/com/earth2me/essentials/user/User.java deleted file mode 100644 index 4120e4bdf..000000000 --- a/Essentials/src/com/earth2me/essentials/user/User.java +++ /dev/null @@ -1,673 +0,0 @@ -package com.earth2me.essentials.user; - -import com.earth2me.essentials.Console; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.Teleport; -import com.earth2me.essentials.api.*; -import com.earth2me.essentials.api.server.*; -import com.earth2me.essentials.economy.register.Method; -import com.earth2me.essentials.permissions.Permissions; -import com.earth2me.essentials.utils.DateUtil; -import com.earth2me.essentials.utils.Util; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; -import lombok.Cleanup; -import lombok.Getter; -import lombok.Setter; - - -public class User extends UserBase implements IUser -{ - private CommandSender replyTo = null; - @Getter - private transient IUser teleportRequester; - @Getter - private transient boolean teleportRequestHere; - @Getter - private transient final ITeleport teleport; - @Getter - private transient long teleportRequestTime; - @Getter - @Setter - private transient long lastOnlineActivity; - private transient long lastActivity = System.currentTimeMillis(); - @Getter - @Setter - private boolean hidden = false; - private transient Location afkPosition; - private AtomicBoolean gotMailInfo = new AtomicBoolean(false); - - public User(final Player base, final IEssentials ess) - { - super(base, ess); - teleport = new Teleport(this, ess); - } - - public void example() - { - // Cleanup will call close at the end of the function - @Cleanup - final User user = this; - - // read lock allows to read data from the user - user.acquireReadLock(); - final double money = user.getData().getMoney(); - - // write lock allows only one thread to modify the data - user.acquireWriteLock(); - user.getData().setMoney(10 + money); - } - - @Override - public void checkCooldown(final UserData.TimestampType cooldownType, final double cooldown, final boolean set, final IPermission bypassPermission) throws CooldownException - { - final Calendar now = new GregorianCalendar(); - if (getTimestamp(cooldownType) > 0) - { - final Calendar cooldownTime = new GregorianCalendar(); - cooldownTime.setTimeInMillis(getTimestamp(cooldownType)); - cooldownTime.add(Calendar.SECOND, (int)cooldown); - cooldownTime.add(Calendar.MILLISECOND, (int)((cooldown * 1000.0) % 1000.0)); - if (cooldownTime.after(now) && !bypassPermission.isAuthorized(this)) - { - throw new CooldownException(DateUtil.formatDateDiff(cooldownTime.getTimeInMillis())); - } - } - if (set) - { - setTimestamp(cooldownType, now.getTimeInMillis()); - } - } - - @Override - public void giveMoney(final double value) - { - giveMoney(value, null); - } - - @Override - public void giveMoney(final double value, final CommandSender initiator) - { - - if (value == 0) - { - return; - } - acquireWriteLock(); - try - { - setMoney(getMoney() + value); - sendMessage(_("addedToAccount", Util.displayCurrency(value, ess))); - if (initiator != null) - { - initiator.sendMessage(_("addedToOthersAccount", Util.displayCurrency(value, ess), this.getDisplayName())); - } - } - finally - { - unlock(); - } - } - - @Override - public void payUser(final IUser reciever, final double value) throws Exception - { - if (value == 0) - { - return; - } - if (canAfford(value)) - { - setMoney(getMoney() - value); - reciever.setMoney(reciever.getMoney() + value); - sendMessage(_("moneySentTo", Util.displayCurrency(value, ess), reciever.getDisplayName())); - reciever.sendMessage(_("moneyRecievedFrom", Util.displayCurrency(value, ess), getDisplayName())); - } - else - { - throw new Exception(_("notEnoughMoney")); - } - } - - @Override - public void takeMoney(final double value) - { - takeMoney(value, null); - } - - @Override - public void takeMoney(final double value, final CommandSender initiator) - { - if (value == 0) - { - return; - } - setMoney(getMoney() - value); - sendMessage(_("takenFromAccount", Util.displayCurrency(value, ess))); - if (initiator != null) - { - initiator.sendMessage(_("takenFromOthersAccount", Util.displayCurrency(value, ess), this.getDisplayName())); - } - } - - public void setHome() - { - setHome("home", getLocation()); - } - - public void setHome(final String name) - { - setHome(name, getLocation()); - } - - @Override - public void setLastLocation() - { - acquireWriteLock(); - try - { - getData().setLastLocation(new com.earth2me.essentials.storage.StoredLocation(getLocation())); - } - finally - { - unlock(); - } - } - - public void requestTeleport(final User player, final boolean here) - { - teleportRequestTime = System.currentTimeMillis(); - teleportRequester = player; - teleportRequestHere = here; - } - - public String getNick(boolean addprefixsuffix) - { - acquireReadLock(); - try - { - final String nick = getData().getNickname(); - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - final IRanks groups = ess.getRanks(); - // default: {PREFIX}{NICKNAMEPREFIX}{NAME}{SUFFIX} - String displayname = settings.getData().getChat().getDisplaynameFormat(); - if (settings.getData().getCommands().isDisabled("nick") || nick == null || nick.isEmpty() || nick.equals(getName())) - { - displayname = displayname.replace("{NAME}", getName()); - displayname = displayname.replace("{NICKNAMEPREFIX}", ""); - } - else - { - displayname = displayname.replace("{NAME}", nick); - displayname = displayname.replace("{NICKNAMEPREFIX}", settings.getData().getChat().getNicknamePrefix()); - } - - if (displayname.contains("{PREFIX}")) - { - displayname = displayname.replace("{PREFIX}", groups.getPrefix(this)); - } - if (displayname.contains("{SUFFIX}")) - { - displayname = displayname.replace("{SUFFIX}", groups.getSuffix(this)); - } - displayname = displayname.replace("{WORLDNAME}", this.getWorld().getName()); - displayname = displayname.replace('&', '\u00a7'); - displayname = displayname.concat("\u00a7f"); - - return displayname; - } - finally - { - unlock(); - } - } - - public void setDisplayNick() - { - String name = getNick(true); - setDisplayName(name); - if (name.length() > 16) - { - name = getNick(false); - } - if (name.length() > 16) - { - name = name.substring(0, name.charAt(15) == '\u00a7' ? 15 : 16); - } - try - { - setPlayerListName(name); - } - catch (IllegalArgumentException e) - { - ess.getLogger().info("Playerlist for " + name + " was not updated. Use a shorter displayname prefix."); - } - } - - @Override - public String getDisplayName() - { - return super.getDisplayName() == null ? super.getName() : super.getDisplayName(); - } - - @Override - public void updateDisplayName() - { - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - if (isOnline() && settings.getData().getChat().getChangeDisplayname()) - { - setDisplayNick(); - } - } - - @Override - public double getMoney() - { - if (ess.getPaymentMethod().hasMethod()) - { - try - { - final Method method = ess.getPaymentMethod().getMethod(); - if (!method.hasAccount(this.getName())) - { - throw new Exception(); - } - final Method.MethodAccount account = ess.getPaymentMethod().getMethod().getAccount(this.getName()); - return account.balance(); - } - catch (Throwable ex) - { - } - } - return super.getMoney(); - } - - @Override - public void setMoney(final double value) - { - if (ess.getPaymentMethod().hasMethod()) - { - try - { - final Method method = ess.getPaymentMethod().getMethod(); - if (!method.hasAccount(this.getName())) - { - throw new Exception(); - } - final Method.MethodAccount account = ess.getPaymentMethod().getMethod().getAccount(this.getName()); - account.set(value); - } - catch (Throwable ex) - { - } - } - super.setMoney(value); - } - - public void setAfk(final boolean set) - { - acquireWriteLock(); - try - { - this.setSleepingIgnored(Permissions.SLEEPINGIGNORED.isAuthorized(this) ? true : set); - if (set && !getData().isAfk()) - { - afkPosition = getLocation(); - } - getData().setAfk(set); - } - finally - { - unlock(); - } - } - - @Override - public boolean toggleAfk() - { - final boolean now = super.toggleAfk(); - this.setSleepingIgnored(Permissions.SLEEPINGIGNORED.isAuthorized(this) ? true : now); - return now; - } - - //Returns true if status expired during this check - public boolean checkJailTimeout(final long currentTime) - { - acquireReadLock(); - try - { - if (getTimestamp(UserData.TimestampType.JAIL) > 0 && getTimestamp(UserData.TimestampType.JAIL) < currentTime && getData().isJailed()) - { - acquireWriteLock(); - - setTimestamp(UserData.TimestampType.JAIL, 0); - getData().setJailed(false); - sendMessage(_("haveBeenReleased")); - getData().setJail(null); - - try - { - teleport.back(); - } - catch (Exception ex) - { - } - return true; - } - return false; - } - finally - { - unlock(); - } - } - - //Returns true if status expired during this check - public boolean checkMuteTimeout(final long currentTime) - { - acquireReadLock(); - try - { - if (getTimestamp(UserData.TimestampType.MUTE) > 0 && getTimestamp(UserData.TimestampType.MUTE) < currentTime && getData().isMuted()) - { - acquireWriteLock(); - setTimestamp(UserData.TimestampType.MUTE, 0); - sendMessage(_("canTalkAgain")); - getData().setMuted(false); - return true; - } - return false; - } - finally - { - unlock(); - } - } - - //Returns true if status expired during this check - public boolean checkBanTimeout(final long currentTime) - { - acquireReadLock(); - try - { - if (getData().getBan() != null && getData().getBan().getTimeout() > 0 && getData().getBan().getTimeout() < currentTime && isBanned()) - { - acquireWriteLock(); - getData().setBan(null); - setBanned(false); - return true; - } - return false; - } - finally - { - unlock(); - } - } - - public void updateActivity(final boolean broadcast) - { - acquireReadLock(); - try - { - if (getData().isAfk()) - { - acquireWriteLock(); - getData().setAfk(false); - if (broadcast && !hidden) - { - ess.broadcastMessage(this, _("userIsNotAway", getDisplayName())); - } - } - lastActivity = System.currentTimeMillis(); - } - finally - { - unlock(); - } - } - - public void checkActivity() - { - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - final long autoafkkick = settings.getData().getCommands().getAfk().getAutoAFKKick(); - if (autoafkkick > 0 && lastActivity > 0 && (lastActivity + (autoafkkick * 1000)) < System.currentTimeMillis() - && !hidden - && !Permissions.KICK_EXEMPT.isAuthorized(this) - && !Permissions.AFK_KICKEXEMPT.isAuthorized(this)) - { - final String kickReason = _("autoAfkKickReason", autoafkkick / 60.0); - lastActivity = 0; - kickPlayer(kickReason); - - - for (IPlayer player : ess.getServer().getOnlinePlayers()) - { - final IUser user = player.getUser(); - if (Permissions.KICK_NOTIFY.isAuthorized(user)) - { - player.sendMessage(_("playerKicked", Console.NAME, getName(), kickReason)); - } - } - } - final long autoafk = settings.getData().getCommands().getAfk().getAutoAFK(); - acquireReadLock(); - try - { - if (!getData().isAfk() && autoafk > 0 && lastActivity + autoafk * 1000 < System.currentTimeMillis() && Permissions.AFK.isAuthorized(this)) - { - setAfk(true); - if (!hidden) - { - ess.broadcastMessage(this, _("userIsAway", getDisplayName())); - } - } - } - finally - { - unlock(); - } - } - - public Location getAfkPosition() - { - return afkPosition; - } - - public boolean toggleGodModeEnabled() - { - if (!isGodModeEnabled()) - { - setFoodLevel(20); - } - return super.toggleGodmode(); - } - - public boolean isGodModeEnabled() - { - acquireReadLock(); - try - { - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - return (getData().isGodmode() - && !settings.getData().getWorldOptions(getLocation().getWorld().getName()).isGodmode()) - || (getData().isAfk() && settings.getData().getCommands().getAfk().isFreezeAFKPlayers()); - } - finally - { - unlock(); - } - } - - @Override - public Location getHome(String name) throws Exception - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void updateCompass() - { - try - { - Location loc = getHome(getLocation()); - if (loc == null) - { - loc = getBedSpawnLocation(); - } - if (loc != null) - { - setCompassTarget(loc); - } - } - catch (Exception ex) - { - // Ignore - } - } - - @Override - public List getHomes() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int compareTo(final IUser t) - { - return Util.stripColor(this.getDisplayName()).compareTo(Util.stripColor(t.getDisplayName())); - } - - @Override - public void requestTeleport(IUser user, boolean b) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setReplyTo(CommandSender user) - { - replyTo = user; - } - - @Override - public CommandSender getReplyTo() - { - return replyTo; - } - - @Override - public boolean gotMailInfo() - { - return gotMailInfo.getAndSet(true); - } - - @Override - public void addMail(String mail) - { - super.addMail(mail); - gotMailInfo.set(false); - } - - @Override - public void giveItems(ItemStack itemStack, Boolean canSpew) throws ChargeException - { - if (giveItemStack(itemStack, canSpew)) - { - sendMessage(_("InvFull")); - } - updateInventory(); - } - - @Override - public void giveItems(List itemStacks, Boolean canSpew) throws ChargeException - { - boolean spew = false; - for (ItemStack itemStack : itemStacks) - { - if (giveItemStack(itemStack, canSpew)) - { - spew = true; - } - } - if (spew) - { - sendMessage(_("InvFull")); - } - updateInventory(); - } - - private boolean giveItemStack(ItemStack itemStack, Boolean canSpew) throws ChargeException - { - boolean spew = false; - - if (itemStack == null || itemStack.isAir()) - { - return spew; - } - - final Map overfilled; - if (Permissions.OVERSIZEDSTACKS.isAuthorized(this)) - { - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - int oversizedStackSize = settings.getData().getGeneral().getOversizedStacksize(); - - overfilled = getInventory().addItem(true, oversizedStackSize, itemStack); - } - else - { - overfilled = getInventory().addItem(true, itemStack); - } - if (canSpew) - { - for (ItemStack overflowStack : overfilled.values()) - { - getWorld().dropItemNaturally(getLocation(), overflowStack); - spew = true; - } - } - else { - if (!overfilled.isEmpty()) { - throw new ChargeException("Inventory full"); - } - } - return spew; - } - - @Override - public boolean canAfford(final double cost) - { - final double mon = getMoney(); - if (Permissions.ECO_LOAN.isAuthorized(this)) - { - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - return (mon - cost) >= settings.getData().getEconomy().getMinMoney(); - } - return cost <= mon; - } - - public void updateMoneyCache(double userMoney) { - if (super.getMoney() != userMoney) { - super.setMoney(userMoney); - } - } - - public boolean canAfford(double amount, boolean b) { - return true; - } -} diff --git a/Essentials/src/com/earth2me/essentials/user/UserBase.java b/Essentials/src/com/earth2me/essentials/user/UserBase.java deleted file mode 100644 index a48e8dc98..000000000 --- a/Essentials/src/com/earth2me/essentials/user/UserBase.java +++ /dev/null @@ -1,368 +0,0 @@ -package com.earth2me.essentials.user; - -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.InvalidNameException; -import com.earth2me.essentials.api.server.Player; -import com.earth2me.essentials.api.server.Location; -import com.earth2me.essentials.storage.AsyncStorageObjectHolder; -import com.earth2me.essentials.storage.IStorageObjectHolder; -import com.earth2me.essentials.storage.StoredLocation.WorldNotLoadedException; -import java.io.File; -import java.io.IOException; -import java.util.*; -import lombok.Cleanup; -import lombok.Delegate; - - -public abstract class UserBase extends AsyncStorageObjectHolder implements Player, IStorageObjectHolder -{ - @Delegate - protected Player base; - - public UserBase(final Player base, final IEssentials ess) - { - super(ess, UserData.class); - this.base = base; - onReload(); - } - - public final Player getBase() - { - return base; - } - - public final Player setBase(final Player base) - { - return this.base = base; - } - - public void update(final Player base) - { - setBase(base); - } - - - - public void dispose() - { - this.base = null; - } - - @Override - public File getStorageFile() throws IOException - { - try - { - return ess.getUserMap().getUserFile(getName()); - } - catch (InvalidNameException ex) - { - throw new IOException(ex.getMessage(), ex); - } - } - - public long getTimestamp(final UserData.TimestampType name) - { - acquireReadLock(); - try - { - if (getData().getTimestamps() == null) - { - return 0; - } - Long ts = getData().getTimestamps().get(name); - return ts == null ? 0 : ts; - } - finally - { - unlock(); - } - } - - public void setTimestamp(final UserData.TimestampType name, final long value) - { - acquireWriteLock(); - try - { - if (getData().getTimestamps() == null) - { - getData().setTimestamps(new HashMap()); - } - getData().getTimestamps().put(name, value); - } - finally - { - unlock(); - } - } - - public void setMoney(final double value) - { - acquireWriteLock(); - try - { - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - if (Math.abs(value) > settings.getData().getEconomy().getMaxMoney()) - { - getData().setMoney(value < 0 ? -settings.getData().getEconomy().getMaxMoney() : settings.getData().getEconomy().getMaxMoney()); - } - else - { - getData().setMoney(value); - } - } - finally - { - unlock(); - } - } - - public double getMoney() - { - acquireReadLock(); - try - { - Double money = getData().getMoney(); - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - if (money == null) - { - money = (double)settings.getData().getEconomy().getStartingBalance(); - } - if (Math.abs(money) > settings.getData().getEconomy().getMaxMoney()) - { - money = money < 0 ? -settings.getData().getEconomy().getMaxMoney() : settings.getData().getEconomy().getMaxMoney(); - } - return money; - } - finally - { - unlock(); - } - } - - public void setHome(String name, Location loc) - { - acquireWriteLock(); - try - { - Map homes = getData().getHomes(); - if (homes == null) - { - homes = new HashMap(); - getData().setHomes(homes); - } - homes.put(Util.sanitizeKey(name), new com.earth2me.essentials.storage.StoredLocation(loc)); - } - finally - { - unlock(); - } - } - - public boolean toggleAfk() - { - acquireWriteLock(); - try - { - boolean ret = !getData().isAfk(); - getData().setAfk(ret); - return ret; - } - finally - { - unlock(); - } - } - - public boolean toggleGodmode() - { - acquireWriteLock(); - try - { - boolean ret = !getData().isGodmode(); - getData().setGodmode(ret); - return ret; - } - finally - { - unlock(); - } - } - - public boolean toggleMuted() - { - acquireWriteLock(); - try - { - boolean ret = !getData().isMuted(); - getData().setMuted(ret); - return ret; - } - finally - { - unlock(); - } - } - - public boolean toggleSocialSpy() - { - acquireWriteLock(); - try - { - boolean ret = !getData().isSocialspy(); - getData().setSocialspy(ret); - return ret; - } - finally - { - unlock(); - } - } - - public boolean toggleTeleportEnabled() - { - acquireWriteLock(); - try - { - boolean ret = !getData().isTeleportEnabled(); - getData().setTeleportEnabled(ret); - return ret; - } - finally - { - unlock(); - } - } - - public boolean isIgnoringPlayer(final String name) - { - acquireReadLock(); - try - { - return getData().getIgnore() == null ? false : getData().getIgnore().contains(name.toLowerCase(Locale.ENGLISH)); - } - finally - { - unlock(); - } - } - - public void setIgnoredPlayer(final String name, final boolean set) - { - acquireWriteLock(); - try - { - if (getData().getIgnore() == null) - { - getData().setIgnore(new HashSet()); - } - if (set) - { - getData().getIgnore().add(name.toLowerCase(Locale.ENGLISH)); - } - else - { - getData().getIgnore().remove(name.toLowerCase(Locale.ENGLISH)); - } - } - finally - { - unlock(); - } - } - - public void addMail(String string) - { - acquireWriteLock(); - try - { - if (getData().getMails() == null) - { - getData().setMails(new ArrayList()); - } - getData().getMails().add(string); - } - finally - { - unlock(); - } - } - - public List getMails() - { - acquireReadLock(); - try - { - if (getData().getMails() == null) - { - return Collections.emptyList(); - } - else - { - return new ArrayList(getData().getMails()); - } - } - finally - { - unlock(); - } - } - - public Location getHome(Location loc) - { - - acquireReadLock(); - try - { - if (getData().getHomes() == null) - { - return null; - } - ArrayList worldHomes = new ArrayList(); - for (com.earth2me.essentials.storage.StoredLocation location : getData().getHomes().values()) - { - if (location.getWorldName().equals(loc.getWorld().getName())) - { - try - { - worldHomes.add(location.getStoredLocation()); - } - catch (WorldNotLoadedException ex) - { - continue; - } - } - } - if (worldHomes.isEmpty()) - { - return null; - } - if (worldHomes.size() == 1) - { - return worldHomes.get(0); - } - double distance = Double.MAX_VALUE; - Location target = null; - for (Location location : worldHomes) - { - final double d = loc.distanceSquared(location); - if (d < distance) - { - target = location; - distance = d; - } - } - return target; - } - finally - { - unlock(); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/user/UserData.java b/Essentials/src/com/earth2me/essentials/user/UserData.java deleted file mode 100644 index a7046f588..000000000 --- a/Essentials/src/com/earth2me/essentials/user/UserData.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.earth2me.essentials.user; - -import com.earth2me.essentials.api.server.Material; -import com.earth2me.essentials.storage.*; -import java.util.*; -import lombok.Data; -import lombok.EqualsAndHashCode; - - - -@Data -@EqualsAndHashCode(callSuper = false) -public class UserData implements StorageObject -{ - public enum TimestampType - { - JAIL, MUTE, LASTHEAL, LASTTELEPORT, LOGIN, LOGOUT - } - private String nickname; - private Double money; - @MapValueType(StoredLocation.class) - private Map homes = new HashMap(); - @ListType(Material.class) - private Set unlimited = new HashSet(); - @MapValueType(List.class) - @MapKeyType(Material.class) - private Map> powerTools = new HashMap>(); - private StoredLocation lastLocation; - @MapKeyType(TimestampType.class) - @MapValueType(Long.class) - private Map timestamps = new HashMap(); - private String jail; - @ListType - private List mails; - private Inventory inventory; - private boolean teleportEnabled; - @ListType - private Set ignore; - private boolean godmode; - private boolean muted; - private boolean jailed; - private Ban ban; - private String ipAddress; - private boolean afk; - private boolean newplayer = true; - private String geolocation; - private boolean socialspy; - private boolean npc; - private boolean powerToolsEnabled; - - public UserData() - { - timestamps.put(TimestampType.JAIL, Long.MIN_VALUE); - } - - public boolean hasUnlimited(Material mat) - { - return unlimited != null && unlimited.contains(mat); - } - - public void setUnlimited(Material mat, boolean state) - { - if (unlimited.contains(mat)) - { - unlimited.remove(mat); - } - if (state) - { - unlimited.add(mat); - } - } - - public List getPowertool(Material mat) - { - return powerTools == null ? Collections.emptyList() : powerTools.get(mat); - } - - - public boolean hasPowerTools() - { - return powerTools != null && !powerTools.isEmpty(); - } - - public void setPowertool(Material mat, List commands) - { - if (powerTools == null) - { - powerTools = new HashMap>(); - } - powerTools.put(mat, commands); - } - - public void clearAllPowertools() - { - powerTools = null; - } - - public void removeHome(String home) - { - if (homes == null) - { - return; - } - homes.remove(home); - } -} diff --git a/Essentials/src/com/earth2me/essentials/user/UserMap.java b/Essentials/src/com/earth2me/essentials/user/UserMap.java deleted file mode 100644 index d3ab7e17e..000000000 --- a/Essentials/src/com/earth2me/essentials/user/UserMap.java +++ /dev/null @@ -1,255 +0,0 @@ -package com.earth2me.essentials.user; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.IUserMap; -import com.earth2me.essentials.api.InvalidNameException; -import com.earth2me.essentials.api.server.Player; -import com.earth2me.essentials.storage.StorageObjectMap; -import com.earth2me.essentials.utils.Util; -import java.io.File; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import org.bukkit.Bukkit; - - -public class UserMap extends StorageObjectMap implements IUserMap -{ - public UserMap(final IEssentials ess) - { - super(ess, "users"); - } - - @Override - public boolean userExists(final String name) - { - return objectExists(name); - } - - @Override - public IUser getUser(final String name) - { - return getObject(name); - } - - @Override - public IUser load(final String name) throws Exception - { - for (Player player : ess.getServer().getOnlinePlayers()) - { - if (player.getName().equalsIgnoreCase(name)) - { - keys.add(name.toLowerCase(Locale.ENGLISH)); - return new User(player, ess); - } - } - final File userFile = getUserFile(name); - if (userFile.exists()) - { - keys.add(name.toLowerCase(Locale.ENGLISH)); - return new User(Bukkit.getOfflinePlayer(name), ess); - } - throw new Exception("User not found!"); - } - - @Override - public void removeUser(final String name) throws InvalidNameException - { - removeObject(name); - } - - @Override - public Set getAllUniqueUsers() - { - return getAllKeys(); - } - - @Override - public int getUniqueUsers() - { - return getKeySize(); - } - - @Override - public File getUserFile(String name) throws InvalidNameException - { - return getStorageFile(name); - } - - @Override - public IUser getUser(final Player player) - { - if (player instanceof IUser) - { - return (IUser)player; - } - IUser user = getUser(player.getName()); - - if (user == null) - { - user = new User(player, ess); - } - else - { - ((User)user).update(player); - } - return user; - } - - @Override - public IUser matchUser(final String name, final boolean includeHidden, final boolean includeOffline) throws TooManyMatchesException - { - final Set users = matchUsers(name, includeHidden, includeOffline); - if (users == null || users.isEmpty()) - { - return null; - } - else - { - if (users.size() > 1) - { - throw new TooManyMatchesException(); - } - else - { - return users.iterator().next(); - } - } - } - - @Override - public Set matchUsers(final String name, final boolean includeHidden, final boolean includeOffline) - { - final String colorlessName = Util.stripColor(name); - final String[] search = colorlessName.split(","); - final boolean multisearch = search.length > 1; - final Set result = new LinkedHashSet(); - final String nicknamePrefix = Util.stripColor(getNickNamePrefix()); - for (String searchString : search) - { - if (searchString.isEmpty()) - { - continue; - } - - if (searchString.startsWith(nicknamePrefix)) - { - searchString = searchString.substring(nicknamePrefix.length()); - } - searchString = searchString.toLowerCase(Locale.ENGLISH); - final boolean multimatching = searchString.endsWith("*"); - if (multimatching) - { - searchString = searchString.substring(0, searchString.length() - 1); - } - Player match = null; - for (Player player : ess.getServer().getOnlinePlayers()) - { - if (player.getName().equalsIgnoreCase(searchString) - && (includeHidden || (includeOffline && player.getUser().isHidden()))) - { - match = player; - break; - } - } - if (match != null) - { - if (multimatching || multisearch) - { - result.add(match.getUser()); - } - else - { - return Collections.singleton(match.getUser()); - } - } - for (Player player : ess.getServer().getOnlinePlayers()) - { - final String nickname = player.getUser().getData().getNickname(); - if (nickname != null && !nickname.isEmpty() - && nickname.equalsIgnoreCase(searchString) - && (includeHidden || (includeOffline && player.getUser().isHidden()))) - { - if (multimatching || multisearch) - { - result.add(player.getUser()); - } - else - { - return Collections.singleton(player.getUser()); - } - } - } - if (includeOffline) - { - for (String playerName : getAllUniqueUsers()) - { - if (playerName.equals(searchString)) - { - match = getUser(playerName); - break; - } - } - if (match != null) - { - if (multimatching || multisearch) - { - result.add(match.getUser()); - } - else - { - return Collections.singleton(match.getUser()); - } - } - } - if (multimatching || match == null) - { - for (Player player : ess.getServer().getOnlinePlayers()) - { - if (player.getName().toLowerCase(Locale.ENGLISH).startsWith(searchString) - && (includeHidden || (includeOffline && player.getUser().isHidden()))) - { - result.add(player.getUser()); - break; - } - final String nickname = player.getUser().getData().getNickname(); - if (nickname != null && !nickname.isEmpty() - && nickname.toLowerCase(Locale.ENGLISH).startsWith(searchString) - && (includeHidden || (includeOffline && player.getUser().isHidden()))) - { - result.add(player.getUser()); - break; - } - } - if (includeOffline) - { - for (String playerName : getAllUniqueUsers()) - { - if (playerName.startsWith(searchString)) - { - result.add(getUser(playerName)); - break; - } - } - } - } - } - return result; - } - - private String getNickNamePrefix() - { - ess.getSettings().acquireReadLock(); - try - { - return ess.getSettings().getData().getChat().getNicknamePrefix(); - } - finally - { - ess.getSettings().unlock(); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/utils/DateUtil.java b/Essentials/src/com/earth2me/essentials/utils/DateUtil.java deleted file mode 100644 index 3f925e6b5..000000000 --- a/Essentials/src/com/earth2me/essentials/utils/DateUtil.java +++ /dev/null @@ -1,186 +0,0 @@ -package com.earth2me.essentials.utils; - -import static com.earth2me.essentials.I18n._; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class DateUtil { - public static String formatDateDiff(long date) - { - Calendar c = new GregorianCalendar(); - c.setTimeInMillis(date); - Calendar now = new GregorianCalendar(); - return formatDateDiff(now, c); - } - - public static String formatDateDiff(Calendar fromDate, Calendar toDate) - { - boolean future = false; - if (toDate.equals(fromDate)) - { - return _("now"); - } - if (toDate.after(fromDate)) - { - future = true; - } - - 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[] - { - _("year"), - _("years"), - _("month"), - _("months"), - _("day"), - _("days"), - _("hour"), - _("hours"), - _("minute"), - _("minutes"), - _("second"), - _("seconds") - }; - for (int i = 0; i < types.length; i++) - { - int diff = dateDiff(types[i], fromDate, toDate, future); - if (diff > 0) - { - sb.append(" ").append(diff).append(" ").append(names[i * 2 + (diff > 1 ? 1 : 0)]); - } - } - if (sb.length() == 0) - { - return "now"; - } - return sb.toString(); - } - - private static int dateDiff(int type, Calendar fromDate, Calendar toDate, boolean future) - { - int diff = 0; - long savedDate = fromDate.getTimeInMillis(); - while ((future && !fromDate.after(toDate)) || (!future && !fromDate.before(toDate))) - { - savedDate = fromDate.getTimeInMillis(); - fromDate.add(type, future ? 1 : -1); - diff++; - } - diff--; - fromDate.setTimeInMillis(savedDate); - return diff; - } - - public static long parseDateDiff(String time, boolean future) throws Exception - { - 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); - Matcher m = timePattern.matcher(time); - int years = 0; - int months = 0; - int weeks = 0; - int days = 0; - int hours = 0; - int minutes = 0; - int seconds = 0; - boolean found = false; - while (m.find()) - { - if (m.group() == null || m.group().isEmpty()) - { - continue; - } - for (int i = 0; i < m.groupCount(); i++) - { - if (m.group(i) != null && !m.group(i).isEmpty()) - { - found = true; - break; - } - } - if (found) - { - if (m.group(1) != null && !m.group(1).isEmpty()) - { - years = Integer.parseInt(m.group(1)); - } - if (m.group(2) != null && !m.group(2).isEmpty()) - { - months = Integer.parseInt(m.group(2)); - } - if (m.group(3) != null && !m.group(3).isEmpty()) - { - weeks = Integer.parseInt(m.group(3)); - } - if (m.group(4) != null && !m.group(4).isEmpty()) - { - days = Integer.parseInt(m.group(4)); - } - if (m.group(5) != null && !m.group(5).isEmpty()) - { - hours = Integer.parseInt(m.group(5)); - } - if (m.group(6) != null && !m.group(6).isEmpty()) - { - minutes = Integer.parseInt(m.group(6)); - } - if (m.group(7) != null && !m.group(7).isEmpty()) - { - seconds = Integer.parseInt(m.group(7)); - } - break; - } - } - if (!found) - { - throw new Exception(_("illegalDate")); - } - Calendar c = new GregorianCalendar(); - if (years > 0) - { - c.add(Calendar.YEAR, years * (future ? 1 : -1)); - } - if (months > 0) - { - c.add(Calendar.MONTH, months * (future ? 1 : -1)); - } - if (weeks > 0) - { - c.add(Calendar.WEEK_OF_YEAR, weeks * (future ? 1 : -1)); - } - if (days > 0) - { - c.add(Calendar.DAY_OF_MONTH, days * (future ? 1 : -1)); - } - if (hours > 0) - { - c.add(Calendar.HOUR_OF_DAY, hours * (future ? 1 : -1)); - } - if (minutes > 0) - { - c.add(Calendar.MINUTE, minutes * (future ? 1 : -1)); - } - if (seconds > 0) - { - c.add(Calendar.SECOND, seconds * (future ? 1 : -1)); - } - return c.getTimeInMillis(); - } -} diff --git a/Essentials/src/com/earth2me/essentials/utils/DescParseTickFormat.java b/Essentials/src/com/earth2me/essentials/utils/DescParseTickFormat.java deleted file mode 100644 index 987c59e7c..000000000 --- a/Essentials/src/com/earth2me/essentials/utils/DescParseTickFormat.java +++ /dev/null @@ -1,295 +0,0 @@ -package com.earth2me.essentials.utils; - -import static com.earth2me.essentials.I18n._; -import java.text.SimpleDateFormat; -import java.util.*; - - -/** - * 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. - * - * http://www.minecraftwiki.net/wiki/Day/night_cycle - * - * @author Olof Larsson - */ -public final class DescParseTickFormat -{ - public static final Map nameToTicks = new LinkedHashMap(); - public static final Set resetAliases = new HashSet(); - public static final int ticksAtMidnight = 18000; - public static final int ticksPerDay = 24000; - public static final int ticksPerHour = 1000; - public static final double ticksPerMinute = 1000d / 60d; - public static final double ticksPerSecond = 1000d / 60d / 60d; - private static final SimpleDateFormat SDFTwentyFour = new SimpleDateFormat("HH:mm", Locale.ENGLISH); - private static final SimpleDateFormat SDFTwelve = new SimpleDateFormat("h:mmaa", Locale.ENGLISH); - - static - { - SDFTwentyFour.setTimeZone(TimeZone.getTimeZone("GMT")); - SDFTwelve.setTimeZone(TimeZone.getTimeZone("GMT")); - - nameToTicks.put("sunrise", 23000); - nameToTicks.put("dawn", 23000); - - nameToTicks.put("daystart", 0); - nameToTicks.put("day", 0); - - nameToTicks.put("morning", 1000); - - nameToTicks.put("midday", 6000); - nameToTicks.put("noon", 6000); - - nameToTicks.put("afternoon", 9000); - - nameToTicks.put("sunset", 12000); - nameToTicks.put("dusk", 12000); - nameToTicks.put("sundown", 12000); - nameToTicks.put("nightfall", 12000); - - nameToTicks.put("nightstart", 14000); - nameToTicks.put("night", 14000); - - nameToTicks.put("midnight", 18000); - - resetAliases.add("reset"); - resetAliases.add("normal"); - resetAliases.add("default"); - } - - private DescParseTickFormat() - { - } - - // ============================================ - // PARSE. From describing String to int - // -------------------------------------------- - public static long parse(String desc) throws NumberFormatException - { - // Only look at alphanumeric and lowercase and : for 24:00 - desc = desc.toLowerCase(Locale.ENGLISH).replaceAll("[^A-Za-z0-9:]", ""); - - // Detect ticks format - try - { - return parseTicks(desc); - } - catch (Exception e) - { - } - - // Detect 24-hour format - try - { - return parse24(desc); - } - catch (Exception e) - { - } - - // Detect 12-hour format - try - { - return parse12(desc); - } - catch (Exception e) - { - } - - // Detect aliases - try - { - return parseAlias(desc); - } - catch (Exception e) - { - } - - // Well we failed to understand... - throw new NumberFormatException(); - } - - public static long parseTicks(String desc) throws NumberFormatException - { - if (!desc.matches("^[0-9]+ti?c?k?s?$")) - { - throw new NumberFormatException(); - } - - desc = desc.replaceAll("[^0-9]", ""); - - return Long.parseLong(desc) % 24000; - } - - public static long parse24(String desc) throws NumberFormatException - { - if (!desc.matches("^[0-9]{2}[^0-9]?[0-9]{2}$")) - { - throw new NumberFormatException(); - } - - desc = desc.toLowerCase(Locale.ENGLISH).replaceAll("[^0-9]", ""); - - if (desc.length() != 4) - { - throw new NumberFormatException(); - } - - final int hours = Integer.parseInt(desc.substring(0, 2)); - final int minutes = Integer.parseInt(desc.substring(2, 4)); - - return hoursMinutesToTicks(hours, minutes); - } - - public static long parse12(String desc) throws NumberFormatException - { - if (!desc.matches("^[0-9]{1,2}([^0-9]?[0-9]{2})?(pm|am)$")) - { - throw new NumberFormatException(); - } - - int hours = 0; - int minutes = 0; - - desc = desc.toLowerCase(Locale.ENGLISH).replaceAll("[^0-9]", ""); - - if (desc.length() > 4) - { - throw new NumberFormatException(); - } - - if (desc.length() == 4) - { - hours += Integer.parseInt(desc.substring(0, 2)); - minutes += Integer.parseInt(desc.substring(2, 4)); - } - else if (desc.length() == 3) - { - hours += Integer.parseInt(desc.substring(0, 1)); - minutes += Integer.parseInt(desc.substring(1, 3)); - } - else if (desc.length() == 2) - { - hours += Integer.parseInt(desc.substring(0, 2)); - } - else if (desc.length() == 1) - { - hours += Integer.parseInt(desc.substring(0, 1)); - } - else - { - throw new NumberFormatException(); - } - - if (desc.endsWith("pm") && hours != 12) - { - hours += 12; - } - - if (desc.endsWith("am") && hours == 12) - { - hours -= 12; - } - - return hoursMinutesToTicks(hours, minutes); - } - - public static long hoursMinutesToTicks(final int hours, final int minutes) - { - long ret = ticksAtMidnight; - ret += (hours) * ticksPerHour; - - ret += (minutes / 60.0) * ticksPerHour; - - ret %= ticksPerDay; - return ret; - } - - public static long parseAlias(final String desc) throws NumberFormatException - { - final Integer ret = nameToTicks.get(desc); - if (ret == null) - { - throw new NumberFormatException(); - } - - return ret; - } - - public static boolean meansReset(final String desc) - { - return resetAliases.contains(desc); - } - - // ============================================ - // FORMAT. From int to describing String - // -------------------------------------------- - public static String format(final long ticks) - { - return _("timeFormat", format24(ticks), format12(ticks), formatTicks(ticks)); - } - - public static String formatTicks(final long ticks) - { - return (ticks % ticksPerDay) + "ticks"; - } - - public static String format24(final long ticks) - { - synchronized (SDFTwentyFour) - { - return formatDateFormat(ticks, SDFTwentyFour); - } - } - - public static String format12(final long ticks) - { - synchronized (SDFTwelve) - { - return formatDateFormat(ticks, SDFTwelve); - } - } - - public static String formatDateFormat(final long ticks, final SimpleDateFormat format) - { - final Date date = ticksToDate(ticks); - return format.format(date); - } - - public static Date ticksToDate(long ticks) - { - // Assume the server time starts at 0. It would start on a day. - // But we will simulate that the server started with 0 at midnight. - ticks = ticks - ticksAtMidnight + ticksPerDay; - - // How many ingame days have passed since the server start? - final long days = ticks / ticksPerDay; - ticks = ticks - days * ticksPerDay; - - // How many hours on the last day? - final long hours = ticks / ticksPerHour; - ticks = ticks - hours * ticksPerHour; - - // How many minutes on the last day? - final long minutes = (long)Math.floor(ticks / ticksPerMinute); - final double dticks = ticks - minutes * ticksPerMinute; - - // How many seconds on the last day? - final long seconds = (long)Math.floor(dticks / ticksPerSecond); - - // Now we create an english GMT calendar (We wan't no daylight savings) - final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.ENGLISH); - cal.setLenient(true); - - // And we set the time to 0! And append the time that passed! - cal.set(0, Calendar.JANUARY, 1, 0, 0, 0); - cal.add(Calendar.DAY_OF_YEAR, (int)days); - cal.add(Calendar.HOUR_OF_DAY, (int)hours); - cal.add(Calendar.MINUTE, (int)minutes); - cal.add(Calendar.SECOND, (int)seconds + 1); // To solve rounding errors. - - return cal.getTime(); - } -} diff --git a/Essentials/src/com/earth2me/essentials/utils/ExecuteTimer.java b/Essentials/src/com/earth2me/essentials/utils/ExecuteTimer.java deleted file mode 100644 index 9c8d71992..000000000 --- a/Essentials/src/com/earth2me/essentials/utils/ExecuteTimer.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.earth2me.essentials.utils; - -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -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(); - } - - public void start() - { - times.clear(); - mark("start"); - - } - - public void mark(final String label) - { - if (!times.isEmpty() || "start".equals(label)) - { - times.add(new ExecuteRecord(label, System.nanoTime())); - } - } - - public String end() - { - final StringBuilder output = new StringBuilder(); - output.append("execution time: "); - String mark; - long time0 = 0; - long time1 = 0; - long time2 = 0; - double duration; - - for (ExecuteRecord pair : times) - { - mark = (String)pair.getMark(); - time2 = (Long)pair.getTime(); - if (time1 > 0) - { - duration = (time2 - time1)/1000000.0; - output.append(mark).append(": ").append(decimalFormat.format(duration)).append("ms - "); - } - else - { - time0 = time2; - } - time1 = time2; - } - duration = (time1 - time0)/1000000.0; - output.append("Total: ").append(decimalFormat.format(duration)).append("ms"); - times.clear(); - return output.toString(); - } - - - static private class ExecuteRecord - { - private final String mark; - private final long time; - - public ExecuteRecord(final String mark, final long time) - { - this.mark = mark; - this.time = time; - } - - public String getMark() - { - return mark; - } - - public long getTime() - { - return time; - } - } -} \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/utils/LocationUtil.java b/Essentials/src/com/earth2me/essentials/utils/LocationUtil.java deleted file mode 100644 index 49b256417..000000000 --- a/Essentials/src/com/earth2me/essentials/utils/LocationUtil.java +++ /dev/null @@ -1,142 +0,0 @@ -package com.earth2me.essentials.utils; - -import static com.earth2me.essentials.I18n._; -import java.util.HashSet; -import java.util.Set; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.entity.LivingEntity; - -public class LocationUtil { - // The player can stand inside these materials - private static final Set AIR_MATERIALS = new HashSet(); - private static final HashSet AIR_MATERIALS_TARGET = new HashSet(); - - static - { - AIR_MATERIALS.add(Material.AIR.getId()); - AIR_MATERIALS.add(Material.SAPLING.getId()); - AIR_MATERIALS.add(Material.POWERED_RAIL.getId()); - AIR_MATERIALS.add(Material.DETECTOR_RAIL.getId()); - AIR_MATERIALS.add(Material.LONG_GRASS.getId()); - AIR_MATERIALS.add(Material.DEAD_BUSH.getId()); - AIR_MATERIALS.add(Material.YELLOW_FLOWER.getId()); - AIR_MATERIALS.add(Material.RED_ROSE.getId()); - AIR_MATERIALS.add(Material.BROWN_MUSHROOM.getId()); - AIR_MATERIALS.add(Material.RED_MUSHROOM.getId()); - AIR_MATERIALS.add(Material.TORCH.getId()); - AIR_MATERIALS.add(Material.REDSTONE_WIRE.getId()); - AIR_MATERIALS.add(Material.SEEDS.getId()); - AIR_MATERIALS.add(Material.SIGN_POST.getId()); - AIR_MATERIALS.add(Material.WOODEN_DOOR.getId()); - AIR_MATERIALS.add(Material.LADDER.getId()); - AIR_MATERIALS.add(Material.RAILS.getId()); - AIR_MATERIALS.add(Material.WALL_SIGN.getId()); - AIR_MATERIALS.add(Material.LEVER.getId()); - AIR_MATERIALS.add(Material.STONE_PLATE.getId()); - AIR_MATERIALS.add(Material.IRON_DOOR_BLOCK.getId()); - AIR_MATERIALS.add(Material.WOOD_PLATE.getId()); - AIR_MATERIALS.add(Material.REDSTONE_TORCH_OFF.getId()); - AIR_MATERIALS.add(Material.REDSTONE_TORCH_ON.getId()); - AIR_MATERIALS.add(Material.STONE_BUTTON.getId()); - AIR_MATERIALS.add(Material.SUGAR_CANE_BLOCK.getId()); - AIR_MATERIALS.add(Material.DIODE_BLOCK_OFF.getId()); - AIR_MATERIALS.add(Material.DIODE_BLOCK_ON.getId()); - AIR_MATERIALS.add(Material.TRAP_DOOR.getId()); - AIR_MATERIALS.add(Material.PUMPKIN_STEM.getId()); - AIR_MATERIALS.add(Material.MELON_STEM.getId()); - AIR_MATERIALS.add(Material.VINE.getId()); - AIR_MATERIALS.add(Material.NETHER_WARTS.getId()); - AIR_MATERIALS.add(Material.WATER_LILY.getId()); - - for (Integer integer : AIR_MATERIALS) - { - AIR_MATERIALS_TARGET.add(integer.byteValue()); - } - AIR_MATERIALS_TARGET.add((byte)Material.WATER.getId()); - AIR_MATERIALS_TARGET.add((byte)Material.STATIONARY_WATER.getId()); - } - - public static Location getTarget(final LivingEntity entity) throws Exception - { - final Block block = entity.getTargetBlock(AIR_MATERIALS_TARGET, 300); - if (block == null) - { - throw new Exception("Not targeting a block"); - } - return block.getLocation(); - } - - public static Location getSafeDestination(final Location loc) throws Exception - { - if (loc == null || loc.getWorld() == null) - { - throw new Exception(_("destinationNotSet")); - } - final World world = loc.getWorld(); - int x = loc.getBlockX(); - int y = (int)Math.round(loc.getY()); - int z = loc.getBlockZ(); - - while (isBlockAboveAir(world, x, y, z)) - { - y -= 1; - if (y < 0) - { - break; - } - } - - while (isBlockUnsafe(world, x, y, z)) - { - y += 1; - if (y >= world.getHighestBlockYAt(x, z)) - { - x += 1; - break; - } - } - while (isBlockUnsafe(world, x, y, z)) - { - y -= 1; - if (y <= 1) - { - x += 1; - y = world.getHighestBlockYAt(x, z); - if (x - 32 > loc.getBlockX()) - { - throw new Exception(_("holeInFloor")); - } - } - } - return new Location(world, x + 0.5D, y, z + 0.5D, loc.getYaw(), loc.getPitch()); - } - - private static boolean isBlockAboveAir(final World world, final int x, final int y, final int z) - { - return AIR_MATERIALS.contains(world.getBlockAt(x, y - 1, z).getType().getId()); - } - - public static boolean isBlockUnsafe(final World world, final int x, final int y, final int z) - { - final Block below = world.getBlockAt(x, y - 1, z); - if (below.getType() == Material.LAVA || below.getType() == Material.STATIONARY_LAVA) - { - return true; - } - - if (below.getType() == Material.FIRE) - { - return true; - } - - if ((!AIR_MATERIALS.contains(world.getBlockAt(x, y, z).getType().getId())) - || (!AIR_MATERIALS.contains(world.getBlockAt(x, y + 1, z).getType().getId()))) - { - return true; - } - return isBlockAboveAir(world, x, y, z); - } -} diff --git a/Essentials/src/com/earth2me/essentials/utils/Util.java b/Essentials/src/com/earth2me/essentials/utils/Util.java deleted file mode 100644 index 720376c66..000000000 --- a/Essentials/src/com/earth2me/essentials/utils/Util.java +++ /dev/null @@ -1,358 +0,0 @@ -package com.earth2me.essentials.utils; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.InvalidNameException; -import com.earth2me.essentials.utils.gnu.inet.encoding.Punycode; -import com.earth2me.essentials.utils.gnu.inet.encoding.PunycodeException; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.util.Collection; -import java.util.HashSet; -import java.util.Locale; -import java.util.Set; -import java.util.regex.Pattern; -import lombok.Cleanup; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.entity.LivingEntity; -import org.bukkit.inventory.ItemStack; -import org.bukkit.permissions.Permission; -import org.bukkit.permissions.PermissionDefault; -import org.bukkit.plugin.PluginManager; - - -public final class Util -{ - private Util() - { - } - private final static Pattern INVALIDFILECHARS = Pattern.compile("[^\u0020-\u007E\u0085\u00A0-\uD7FF\uE000-\uFFFC]"); - private final static Pattern INVALIDCHARS = Pattern.compile("[^\t\n\r\u0020-\u007E\u0085\u00A0-\uD7FF\uE000-\uFFFC]"); - - public static String sanitizeFileName(String name) throws InvalidNameException - { - try - { - String r = name.toLowerCase(Locale.ENGLISH); - r = r.replace('.', (char)('\ue200' + '.')); - r = r.replace('\\', (char)('\ue200' + '\\')); - r = r.replace('/', (char)('\ue200' + '/')); - r = r.replace('"', (char)('\ue200' + '"')); - r = r.replace('<', (char)('\ue200' + '<')); - r = r.replace('>', (char)('\ue200' + '>')); - r = r.replace('|', (char)('\ue200' + '|')); - r = r.replace('?', (char)('\ue200' + '?')); - r = r.replace('*', (char)('\ue200' + '*')); - r = r.replace(':', (char)('\ue200' + ':')); - r = r.replace('-', (char)('\ue200' + '-')); - r = INVALIDFILECHARS.matcher(r).replaceAll(""); - return Punycode.encode(r); - } - catch (PunycodeException ex) - { - throw new InvalidNameException(ex); - } - } - - public static String decodeFileName(String name) throws InvalidNameException - { - try - { - String r = Punycode.decode(name); - r = r.replace((char)('\ue200' + '.'), '.'); - r = r.replace((char)('\ue200' + '\\'), '\\'); - r = r.replace((char)('\ue200' + '/'), '/'); - r = r.replace((char)('\ue200' + '"'), '"'); - r = r.replace((char)('\ue200' + '<'), '<'); - r = r.replace((char)('\ue200' + '>'), '>'); - r = r.replace((char)('\ue200' + '|'), '|'); - r = r.replace((char)('\ue200' + '?'), '?'); - r = r.replace((char)('\ue200' + '*'), '*'); - r = r.replace((char)('\ue200' + ':'), ':'); - r = r.replace((char)('\ue200' + '-'), '-'); - return r; - } - catch (PunycodeException ex) - { - throw new InvalidNameException(ex); - } - } - - public static String sanitizeKey(String name) - { - return INVALIDCHARS.matcher(name.toLowerCase(Locale.ENGLISH)).replaceAll("_"); - } - - public static String sanitizeString(final String string) - { - return INVALIDCHARS.matcher(string).replaceAll(""); - } - - public static ItemStack convertBlockToItem(final Block block) - { - final ItemStack is = new ItemStack(block.getType(), 1, (short)0, block.getData()); - switch (is.getType()) - { - case WOODEN_DOOR: - is.setType(Material.WOOD_DOOR); - is.setDurability((short)0); - break; - case IRON_DOOR_BLOCK: - is.setType(Material.IRON_DOOR); - is.setDurability((short)0); - break; - case SIGN_POST: - case WALL_SIGN: - is.setType(Material.SIGN); - is.setDurability((short)0); - break; - case CROPS: - is.setType(Material.SEEDS); - is.setDurability((short)0); - break; - case CAKE_BLOCK: - is.setType(Material.CAKE); - is.setDurability((short)0); - break; - case BED_BLOCK: - is.setType(Material.BED); - is.setDurability((short)0); - break; - case REDSTONE_WIRE: - is.setType(Material.REDSTONE); - is.setDurability((short)0); - break; - case REDSTONE_TORCH_OFF: - case REDSTONE_TORCH_ON: - is.setType(Material.REDSTONE_TORCH_ON); - is.setDurability((short)0); - break; - case DIODE_BLOCK_OFF: - case DIODE_BLOCK_ON: - is.setType(Material.DIODE); - is.setDurability((short)0); - break; - case DOUBLE_STEP: - is.setType(Material.STEP); - break; - case TORCH: - case RAILS: - case LADDER: - case WOOD_STAIRS: - case COBBLESTONE_STAIRS: - case LEVER: - case STONE_BUTTON: - case FURNACE: - case DISPENSER: - case PUMPKIN: - case JACK_O_LANTERN: - case WOOD_PLATE: - case STONE_PLATE: - case PISTON_STICKY_BASE: - case PISTON_BASE: - case IRON_FENCE: - case THIN_GLASS: - case TRAP_DOOR: - case FENCE: - case FENCE_GATE: - case NETHER_FENCE: - is.setDurability((short)0); - break; - case FIRE: - return null; - case PUMPKIN_STEM: - is.setType(Material.PUMPKIN_SEEDS); - break; - case MELON_STEM: - is.setType(Material.MELON_SEEDS); - break; - } - return is; - } - private static DecimalFormat dFormat = new DecimalFormat("#0.00", DecimalFormatSymbols.getInstance(Locale.US)); - - public static String formatAsCurrency(final double value) - { - - String str = dFormat.format(value); - if (str.endsWith(".00")) - { - str = str.substring(0, str.length() - 3); - } - return str; - } - - public static String displayCurrency(final double value, final IEssentials ess) - { - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - return _("currency", settings.getData().getEconomy().getCurrencySymbol(), formatAsCurrency(value)); - } - - public static String shortCurrency(final double value, final IEssentials ess) - { - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - return settings.getData().getEconomy().getCurrencySymbol() + formatAsCurrency(value); - } - - public static double roundDouble(final double d) - { - return Math.round(d * 100.0) / 100.0; - } - - public static boolean isInt(final String sInt) - { - try - { - Integer.parseInt(sInt); - } - catch (NumberFormatException e) - { - return false; - } - return true; - } - - public static String joinList(Object... list) - { - return joinList(", ", list); - } - - public static String joinList(String seperator, Object... list) - { - StringBuilder buf = new StringBuilder(); - for (Object each : list) - { - if (buf.length() > 0) - { - buf.append(seperator); - } - - if (each instanceof Collection) - { - buf.append(joinList(seperator, ((Collection)each).toArray())); - } - else - { - try - { - buf.append(each.toString()); - } - catch (Exception e) - { - buf.append(each.toString()); - } - } - } - return buf.toString(); - } - - public static void registerPermissions(String path, Collection nodes, boolean hasDefault, IEssentials ess) - { - if (nodes == null || nodes.isEmpty()) - { - return; - } - final PluginManager pluginManager = ess.getServer().getPluginManager(); - Permission basePerm = pluginManager.getPermission(path + ".*"); - if (basePerm != null && !basePerm.getChildren().isEmpty()) - { - basePerm.getChildren().clear(); - } - if (basePerm == null) - { - basePerm = new Permission(path + ".*", PermissionDefault.OP); - pluginManager.addPermission(basePerm); - Permission mainPerm = pluginManager.getPermission("essentials.*"); - if (mainPerm == null) - { - mainPerm = new Permission("essentials.*", PermissionDefault.OP); - pluginManager.addPermission(mainPerm); - } - mainPerm.getChildren().put(basePerm.getName(), Boolean.TRUE); - } - - for (String nodeName : nodes) - { - final String permissionName = path + "." + nodeName; - Permission perm = pluginManager.getPermission(permissionName); - if (perm == null) - { - final PermissionDefault defaultPerm = hasDefault && nodeName.equalsIgnoreCase("default") ? PermissionDefault.TRUE : PermissionDefault.OP; - perm = new Permission(permissionName, defaultPerm); - pluginManager.addPermission(perm); - } - basePerm.getChildren().put(permissionName, Boolean.TRUE); - } - basePerm.recalculatePermissibles(); - } - private static transient final Pattern DOT_PATTERN = Pattern.compile("\\."); - - public static Permission registerPermission(String permission, PermissionDefault defaultPerm) - { - final PluginManager pluginManager = Bukkit.getServer().getPluginManager(); - final String[] parts = DOT_PATTERN.split(permission); - final StringBuilder builder = new StringBuilder(permission.length()); - Permission parent = null; - for (int i = 0; i < parts.length - 1; i++) - { - builder.append(parts[i]).append(".*"); - String permString = builder.toString(); - Permission perm = pluginManager.getPermission(permString); - if (perm == null) - { - perm = new Permission(permString, PermissionDefault.FALSE); - pluginManager.addPermission(perm); - if (parent != null) - { - parent.getChildren().put(perm.getName(), Boolean.TRUE); - } - parent = perm; - } - builder.deleteCharAt(builder.length() - 1); - } - Permission perm = pluginManager.getPermission(permission); - if (perm == null) - { - perm = new Permission(permission, defaultPerm); - pluginManager.addPermission(perm); - if (parent != null) - { - parent.getChildren().put(perm.getName(), Boolean.TRUE); - } - parent = perm; - } - perm.recalculatePermissibles(); - return perm; - } - private static transient final Pattern VANILLA_COLOR_PATTERN = Pattern.compile("\u00A7+[0-9A-FKa-fk]"); - private static transient final Pattern EASY_COLOR_PATTERN = Pattern.compile("&([0-9a-fk])"); - - public static String stripColor(final String input) - { - if (input == null) - { - return null; - } - - return VANILLA_COLOR_PATTERN.matcher(input).replaceAll(""); - } - - public static String replaceColor(final String input) - { - if (input == null) - { - return null; - } - - return EASY_COLOR_PATTERN.matcher(input).replaceAll("\u00a7$1"); - } -} diff --git a/Essentials/src/com/earth2me/essentials/utils/gnu/inet/encoding/Punycode.java b/Essentials/src/com/earth2me/essentials/utils/gnu/inet/encoding/Punycode.java deleted file mode 100644 index fdca948f6..000000000 --- a/Essentials/src/com/earth2me/essentials/utils/gnu/inet/encoding/Punycode.java +++ /dev/null @@ -1,321 +0,0 @@ -package com.earth2me.essentials.utils.gnu.inet.encoding; - - -/** - * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software - * Foundation, Inc. - * - * Author: Oliver Hitz - * - * This file is part of GNU Libidn. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 - * USA - */ -/** - * This class offers static methods for encoding/decoding strings - * using the Punycode algorithm. - *
    - *
  • RFC3492 Punycode - *
- * Note that this implementation only supports 16-bit Unicode code - * points. - */ -/* - * Changes by snowleo: - * - Correctly catch wrong characters after the delimiter - * - If the string starts with the delimiter, it's an encoded string - * - If there is no delimiter, it's an ascii string. - * - Note: the string should never contain the delimiter. - */ -public class Punycode -{ - /* - * Punycode parameters - */ - final static int TMIN = 1; - final static int TMAX = 26; - final static int BASE = 36; - final static int INITIAL_N = 128; - final static int INITIAL_BIAS = 72; - final static int DAMP = 700; - final static int SKEW = 38; - final static char DELIMITER = '-'; - - /** - * Punycodes a unicode string. - * - * @param input Unicode string. - * @return Punycoded string. - */ - public static String encode(String input) - throws PunycodeException - { - int n = INITIAL_N; - int delta = 0; - int bias = INITIAL_BIAS; - StringBuffer output = new StringBuffer(); - - // Copy all basic code points to the output - int b = 0; - for (int i = 0; i < input.length(); i++) - { - char c = input.charAt(i); - if (isBasic(c)) - { - output.append(c); - b++; - } - } - - // Append delimiter - if (b < input.length()) // Changed by snowleo - { - output.append(DELIMITER); - } - - int h = b; - while (h < input.length()) - { - int m = Integer.MAX_VALUE; - - // Find the minimum code point >= n - for (int i = 0; i < input.length(); i++) - { - int c = input.charAt(i); - if (c >= n && c < m) - { - m = c; - } - } - - if (m - n > (Integer.MAX_VALUE - delta) / (h + 1)) - { - throw new PunycodeException(PunycodeException.OVERFLOW); - } - delta = delta + (m - n) * (h + 1); - n = m; - - for (int j = 0; j < input.length(); j++) - { - int c = input.charAt(j); - if (c < n) - { - delta++; - if (0 == delta) - { - throw new PunycodeException(PunycodeException.OVERFLOW); - } - } - if (c == n) - { - int q = delta; - - for (int k = BASE;; k += BASE) - { - int t; - if (k <= bias) - { - t = TMIN; - } - else if (k >= bias + TMAX) - { - t = TMAX; - } - else - { - t = k - bias; - } - if (q < t) - { - break; - } - output.append((char)digit2codepoint(t + (q - t) % (BASE - t))); - q = (q - t) / (BASE - t); - } - - output.append((char)digit2codepoint(q)); - bias = adapt(delta, h + 1, h == b); - delta = 0; - h++; - } - } - - delta++; - n++; - } - - return output.toString(); - } - - /** - * Decode a punycoded string. - * - * @param input Punycode string - * @return Unicode string. - */ - public static String decode(String input) - throws PunycodeException - { - int n = INITIAL_N; - int i = 0; - int bias = INITIAL_BIAS; - StringBuffer output = new StringBuffer(); - - int d = input.lastIndexOf(DELIMITER); - // Change start by snowleo - if (d < 0) { - return input; - } - else if (d > 0) // Change end by snowleo - { - for (int j = 0; j < d; j++) - { - char c = input.charAt(j); - if (!isBasic(c)) - { - throw new PunycodeException(PunycodeException.BAD_INPUT); - } - output.append(c); - } - d++; - } - else - { - d = 1; // Changed by snowleo - } - - while (d < input.length()) - { - int oldi = i; - int w = 1; - - for (int k = BASE;; k += BASE) - { - if (d == input.length()) - { - throw new PunycodeException(PunycodeException.BAD_INPUT); - } - int c = input.charAt(d++); - int digit = codepoint2digit(c); - if (digit > (Integer.MAX_VALUE - i) / w) - { - throw new PunycodeException(PunycodeException.OVERFLOW); - } - - i = i + digit * w; - - int t; - if (k <= bias) - { - t = TMIN; - } - else if (k >= bias + TMAX) - { - t = TMAX; - } - else - { - t = k - bias; - } - if (digit < t) - { - break; - } - w = w * (BASE - t); - } - - bias = adapt(i - oldi, output.length() + 1, oldi == 0); - - if (i / (output.length() + 1) > Integer.MAX_VALUE - n) - { - throw new PunycodeException(PunycodeException.OVERFLOW); - } - - n = n + i / (output.length() + 1); - i = i % (output.length() + 1); - output.insert(i, (char)n); - i++; - } - - return output.toString(); - } - - public final static int adapt(int delta, int numpoints, boolean first) - { - if (first) - { - delta = delta / DAMP; - } - else - { - delta = delta / 2; - } - - delta = delta + (delta / numpoints); - - int k = 0; - while (delta > ((BASE - TMIN) * TMAX) / 2) - { - delta = delta / (BASE - TMIN); - k = k + BASE; - } - - return k + ((BASE - TMIN + 1) * delta) / (delta + SKEW); - } - - public final static boolean isBasic(char c) - { - return c < 0x80; - } - - public final static int digit2codepoint(int d) - throws PunycodeException - { - if (d < 26) - { - // 0..25 : 'a'..'z' - return d + 'a'; - } - else if (d < 36) - { - // 26..35 : '0'..'9'; - return d - 26 + '0'; - } - else - { - throw new PunycodeException(PunycodeException.BAD_INPUT); - } - } - - public final static int codepoint2digit(int c) - throws PunycodeException - { - if (c - '0' < 10 && c >= '0') // Changed by snowleo - { - // '0'..'9' : 26..35 - return c - '0' + 26; - } - else if (c - 'a' < 26 && c >= 'a') // Changed by snowleo - { - // 'a'..'z' : 0..25 - return c - 'a'; - } - else - { - throw new PunycodeException(PunycodeException.BAD_INPUT); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/utils/gnu/inet/encoding/PunycodeException.java b/Essentials/src/com/earth2me/essentials/utils/gnu/inet/encoding/PunycodeException.java deleted file mode 100644 index 9db00d10d..000000000 --- a/Essentials/src/com/earth2me/essentials/utils/gnu/inet/encoding/PunycodeException.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.earth2me.essentials.utils.gnu.inet.encoding; - - -/** - * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software - * Foundation, Inc. - * - * Author: Oliver Hitz - * - * This file is part of GNU Libidn. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 - * USA - */ -/** - * Exception handling for Punycode class. - */ -public class PunycodeException - extends Exception -{ - public static String OVERFLOW = "Overflow."; - public static String BAD_INPUT = "Bad input."; - - /** - * Creates a new PunycodeException. - * - * @param m message. - */ - public PunycodeException(String m) - { - super(m); - } -} diff --git a/Essentials/src/com/earth2me/essentials/utils/textreader/ArrayListInput.java b/Essentials/src/com/earth2me/essentials/utils/textreader/ArrayListInput.java deleted file mode 100644 index 5943387a5..000000000 --- a/Essentials/src/com/earth2me/essentials/utils/textreader/ArrayListInput.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.earth2me.essentials.utils.textreader; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - - -public class ArrayListInput implements IText -{ - private final transient List lines = new ArrayList(); - - @Override - public List getLines() - { - return lines; - } - - @Override - public List getChapters() - { - return Collections.emptyList(); - } - - @Override - public Map getBookmarks() - { - return Collections.emptyMap(); - } - -} diff --git a/Essentials/src/com/earth2me/essentials/utils/textreader/HelpInput.java b/Essentials/src/com/earth2me/essentials/utils/textreader/HelpInput.java deleted file mode 100644 index 67b946469..000000000 --- a/Essentials/src/com/earth2me/essentials/utils/textreader/HelpInput.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.earth2me.essentials.utils.textreader; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.HelpPermissions; -import java.io.IOException; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; -import lombok.Cleanup; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginDescriptionFile; - - -public class HelpInput implements IText -{ - private static final String DESCRIPTION = "description"; - private static final String PERMISSION = "permission"; - private static final String PERMISSIONS = "permissions"; - private final transient List lines = new ArrayList(); - private final transient List chapters = new ArrayList(); - private final transient Map bookmarks = new HashMap(); - private final static Logger logger = Logger.getLogger("Minecraft"); - - public HelpInput(final IUser user, final String match, final IEssentials ess) throws IOException - { - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - boolean reported = false; - String pluginName = ""; - for (Plugin p : ess.getServer().getPluginManager().getPlugins()) - { - try - { - final PluginDescriptionFile desc = p.getDescription(); - final Map> cmds = desc.getCommands(); - pluginName = p.getDescription().getName().toLowerCase(Locale.ENGLISH); - for (Map.Entry> k : cmds.entrySet()) - { - try - { - if ((!match.equalsIgnoreCase("")) - && (!k.getKey().toLowerCase(Locale.ENGLISH).contains(match)) - && (!(k.getValue().get(DESCRIPTION) instanceof String - && ((String)k.getValue().get(DESCRIPTION)).toLowerCase(Locale.ENGLISH).contains(match))) - && (!pluginName.contains(match))) - { - continue; - } - - if (pluginName.contains("essentials")) - { - final String node = "essentials." + k.getKey(); - if (!settings.getData().getCommands().isDisabled(k.getKey()) && user.hasPermission(node)) - { - lines.add(_("helpLine", k.getKey(), k.getValue().get(DESCRIPTION))); - } - } - else - { - if (settings.getData().getCommands().getHelp().isShowNonEssCommandsInHelp()) - { - final Map value = k.getValue(); - Object permissions = null; - if (value.containsKey(PERMISSION)) - { - permissions = value.get(PERMISSION); - } - else if (value.containsKey(PERMISSIONS)) - { - permissions = value.get(PERMISSIONS); - } - if (HelpPermissions.getPermission(pluginName).isAuthorized(user)) - { - lines.add(_("helpLine", k.getKey(), value.get(DESCRIPTION))); - } - else if (permissions instanceof List && !((List)permissions).isEmpty()) - { - boolean enabled = false; - for (Object o : (List)permissions) - { - if (o instanceof String && user.hasPermission(o.toString())) - { - enabled = true; - break; - } - } - if (enabled) - { - lines.add(_("helpLine", k.getKey(), value.get(DESCRIPTION))); - } - } - else if (permissions instanceof String && !"".equals(permissions)) - { - if (user.hasPermission(permissions.toString())) - { - lines.add(_("helpLine", k.getKey(), value.get(DESCRIPTION))); - } - } - else - { - if (!settings.getData().getCommands().getHelp().isHidePermissionlessCommands()) - { - lines.add(_("helpLine", k.getKey(), value.get(DESCRIPTION))); - } - } - } - } - } - catch (NullPointerException ex) - { - continue; - } - } - } - catch (NullPointerException ex) - { - continue; - } - catch (Exception ex) - { - if (!reported) - { - logger.log(Level.WARNING, _("commandHelpFailedForPlugin", pluginName), ex); - } - reported = true; - continue; - } - } - } - - @Override - public List getLines() - { - return lines; - } - - @Override - public List getChapters() - { - return chapters; - } - - @Override - public Map getBookmarks() - { - return bookmarks; - } -} diff --git a/Essentials/src/com/earth2me/essentials/utils/textreader/IText.java b/Essentials/src/com/earth2me/essentials/utils/textreader/IText.java deleted file mode 100644 index c70554b28..000000000 --- a/Essentials/src/com/earth2me/essentials/utils/textreader/IText.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.earth2me.essentials.utils.textreader; - -import java.util.List; -import java.util.Map; - - -public interface IText -{ - List getLines(); - - List getChapters(); - - Map getBookmarks(); -} diff --git a/Essentials/src/com/earth2me/essentials/utils/textreader/KeywordReplacer.java b/Essentials/src/com/earth2me/essentials/utils/textreader/KeywordReplacer.java deleted file mode 100644 index 52309a892..000000000 --- a/Essentials/src/com/earth2me/essentials/utils/textreader/KeywordReplacer.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.earth2me.essentials.utils.textreader; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.api.server.Player; -import com.earth2me.essentials.api.server.World; -import com.earth2me.essentials.utils.DescParseTickFormat; -import java.text.DateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; -import lombok.Cleanup; -import org.bukkit.plugin.Plugin; - - -public class KeywordReplacer implements IText -{ - private final transient IText input; - private final transient List replaced; - private final transient IEssentials ess; - - public KeywordReplacer(final IText input, final CommandSender sender, final IEssentials ess) - { - this.input = input; - this.replaced = new ArrayList(this.input.getLines().size()); - this.ess = ess; - replaceKeywords(sender); - } - - private void replaceKeywords(final CommandSender sender) - { - String displayName, ipAddress, balance, mails, world; - String worlds, online, unique, playerlist, date, time; - String worldTime12, worldTime24, worldDate, plugins; - String userName, address, version; - if (sender.isPlayer()) - { - @Cleanup - final IUser user = ((Player)sender).getUser(); - user.acquireReadLock(); - displayName = user.getDisplayName(); - userName = user.getName(); - ipAddress = user.getAddress().getAddress().toString(); - address = user.getAddress().toString(); - balance = Double.toString(user.getMoney()); - mails = Integer.toString(user.getData().getMails() == null ? 0 : user.getData().getMails().size()); - world = user.getLocation().getWorld().getName(); - worldTime12 = DescParseTickFormat.format12(user.getWorld().getTime()); - worldTime24 = DescParseTickFormat.format24(user.getWorld().getTime()); - worldDate = DateFormat.getDateInstance(DateFormat.MEDIUM, ess.getI18n().getCurrentLocale()).format(DescParseTickFormat.ticksToDate(user.getWorld().getFullTime())); - } - else - { - displayName = ipAddress = balance = mails = world = worldTime12 = worldTime24 = worldDate = ""; - } - - int playerHidden = 0; - for (Player p : ess.getServer().getOnlinePlayers()) - { - if (p.getUser().isHidden()) - { - playerHidden++; - } - } - online = Integer.toString(ess.getServer().getOnlinePlayers().size() - playerHidden); - unique = Integer.toString(ess.getUserMap().getUniqueUsers()); - - final StringBuilder worldsBuilder = new StringBuilder(); - for (World w : ess.getServer().getWorlds()) - { - if (worldsBuilder.length() > 0) - { - worldsBuilder.append(", "); - } - worldsBuilder.append(w.getName()); - } - worlds = worldsBuilder.toString(); - - final StringBuilder playerlistBuilder = new StringBuilder(); - for (Player p : ess.getServer().getOnlinePlayers()) - { - if (p.getUser().isHidden()) - { - continue; - } - if (playerlistBuilder.length() > 0) - { - playerlistBuilder.append(", "); - } - playerlistBuilder.append(p.getDisplayName()); - } - playerlist = playerlistBuilder.toString(); - - final StringBuilder pluginlistBuilder = new StringBuilder(); - for (Plugin p : ess.getServer().getPluginManager().getPlugins()) - { - if (pluginlistBuilder.length() > 0) - { - pluginlistBuilder.append(", "); - } - pluginlistBuilder.append(p.getDescription().getName()); - } - plugins = pluginlistBuilder.toString(); - - date = DateFormat.getDateInstance(DateFormat.MEDIUM, ess.getI18n().getCurrentLocale()).format(new Date()); - time = DateFormat.getTimeInstance(DateFormat.MEDIUM, ess.getI18n().getCurrentLocale()).format(new Date()); - - version = ess.getServer().getVersion(); - - for (int i = 0; i < input.getLines().size(); i++) - { - String line = input.getLines().get(i); - - line = line.replace("{PLAYER}", displayName); - line = line.replace("{DISPLAYNAME}", displayName); - line = line.replace("{USERNAME}", displayName); - line = line.replace("{IP}", ipAddress); - line = line.replace("{ADDRESS}", ipAddress); - line = line.replace("{BALANCE}", balance); - line = line.replace("{MAILS}", mails); - line = line.replace("{WORLD}", world); - line = line.replace("{ONLINE}", online); - line = line.replace("{UNIQUE}", unique); - line = line.replace("{WORLDS}", worlds); - line = line.replace("{PLAYERLIST}", playerlist); - line = line.replace("{TIME}", time); - line = line.replace("{DATE}", date); - line = line.replace("{WORLDTIME12}", worldTime12); - line = line.replace("{WORLDTIME24}", worldTime24); - line = line.replace("{WORLDDATE}", worldDate); - line = line.replace("{PLUGINS}", plugins); - line = line.replace("{VERSION}", version); - replaced.add(line); - } - } - - @Override - public List getLines() - { - return replaced; - } - - @Override - public List getChapters() - { - return input.getChapters(); - } - - @Override - public Map getBookmarks() - { - return input.getBookmarks(); - } -} diff --git a/Essentials/src/com/earth2me/essentials/utils/textreader/SimpleTextInput.java b/Essentials/src/com/earth2me/essentials/utils/textreader/SimpleTextInput.java deleted file mode 100644 index 4a94126d3..000000000 --- a/Essentials/src/com/earth2me/essentials/utils/textreader/SimpleTextInput.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.earth2me.essentials.utils.textreader; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - - -public class SimpleTextInput implements IText -{ - private final transient List lines = new ArrayList(); - - public SimpleTextInput (final String input) { - lines.add(input); - } - - @Override - public List getLines() - { - return lines; - } - - @Override - public List getChapters() - { - return Collections.emptyList(); - } - - @Override - public Map getBookmarks() - { - return Collections.emptyMap(); - } - -} diff --git a/Essentials/src/com/earth2me/essentials/utils/textreader/SimpleTextPager.java b/Essentials/src/com/earth2me/essentials/utils/textreader/SimpleTextPager.java deleted file mode 100644 index 3c9e9cb55..000000000 --- a/Essentials/src/com/earth2me/essentials/utils/textreader/SimpleTextPager.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.earth2me.essentials.utils.textreader; - -import org.bukkit.command.CommandSender; - - -public class SimpleTextPager -{ - private final transient IText text; - - public SimpleTextPager(final IText text) - { - this.text = text; - } - - public void showPage(final CommandSender sender) - { - for (String line : text.getLines()) - { - sender.sendMessage(line); - } - } - - public String getString(int line) - { - if (text.getLines().size() < line) - { - return null; - } - return text.getLines().get(line); - } -} diff --git a/Essentials/src/com/earth2me/essentials/utils/textreader/TextInput.java b/Essentials/src/com/earth2me/essentials/utils/textreader/TextInput.java deleted file mode 100644 index 77e8aadb5..000000000 --- a/Essentials/src/com/earth2me/essentials/utils/textreader/TextInput.java +++ /dev/null @@ -1,146 +0,0 @@ -package com.earth2me.essentials.utils.textreader; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.InvalidNameException; -import com.earth2me.essentials.api.server.CommandSender; -import com.earth2me.essentials.api.server.Player; -import com.earth2me.essentials.utils.Util; -import java.io.*; -import java.lang.ref.SoftReference; -import java.util.*; -import java.util.logging.Level; - - -public class TextInput implements IText -{ - private final transient List lines; - private final transient List chapters; - private final transient Map bookmarks; - private final transient long lastChange; - private final static HashMap> cache = new HashMap>(); - - public TextInput(final CommandSender sender, final String filename, final boolean createFile, final IEssentials ess) throws IOException - { - - File file = null; - if (sender.isPlayer()) - { - try - { - final IUser user = ((Player)sender).getUser(); - file = new File(ess.getPlugin().getDataFolder(), filename + "_" + Util.sanitizeFileName(user.getName()) + ".txt"); - if (!file.exists()) - { - file = new File(ess.getPlugin().getDataFolder(), filename + "_" + Util.sanitizeFileName(ess.getRanks().getMainGroup(user)) + ".txt"); - } - } - catch (InvalidNameException ex) - { - ess.getLogger().log(Level.WARNING, ex.getMessage(), ex); - } - } - if (file == null || !file.exists()) - { - file = new File(ess.getPlugin().getDataFolder(), filename + ".txt"); - } - if (file.exists()) - { - lastChange = file.lastModified(); - boolean readFromfile; - synchronized (cache) - { - final SoftReference inputRef = cache.get(file.getName()); - TextInput input; - if (inputRef == null || (input = inputRef.get()) == null || input.lastChange < lastChange) - { - lines = new ArrayList(); - chapters = new ArrayList(); - bookmarks = new HashMap(); - cache.put(file.getName(), new SoftReference(this)); - readFromfile = true; - } - else - { - lines = Collections.unmodifiableList(input.getLines()); - chapters = Collections.unmodifiableList(input.getChapters()); - bookmarks = Collections.unmodifiableMap(input.getBookmarks()); - readFromfile = false; - } - } - if (readFromfile) - { - final BufferedReader bufferedReader = new BufferedReader(new FileReader(file)); - try - { - int lineNumber = 0; - while (bufferedReader.ready()) - { - final String line = bufferedReader.readLine(); - if (line == null) - { - break; - } - if (line.length() > 0 && line.charAt(0) == '#') - { - bookmarks.put(line.substring(1).toLowerCase(Locale.ENGLISH).replaceAll("&[0-9a-f]", ""), lineNumber); - chapters.add(line.substring(1).replace('&', '�').replace("�", "&")); - } - lines.add(line.replace('&', '�').replace("�", "&")); - lineNumber++; - } - } - finally - { - bufferedReader.close(); - } - } - } - else - { - lastChange = 0; - lines = Collections.emptyList(); - chapters = Collections.emptyList(); - bookmarks = Collections.emptyMap(); - if (createFile) - { - final InputStream input = ess.getPlugin().getResource(filename + ".txt"); - final OutputStream output = new FileOutputStream(file); - try - { - final byte[] buffer = new byte[1024]; - int length = input.read(buffer); - while (length > 0) - { - output.write(buffer, 0, length); - length = input.read(buffer); - } - } - finally - { - output.close(); - input.close(); - } - throw new FileNotFoundException("File " + filename + ".txt does not exist. Creating one for you."); - } - } - } - - @Override - public List getLines() - { - return lines; - } - - @Override - public List getChapters() - { - return chapters; - } - - @Override - public Map getBookmarks() - { - return bookmarks; - } -} diff --git a/Essentials/src/com/earth2me/essentials/utils/textreader/TextPager.java b/Essentials/src/com/earth2me/essentials/utils/textreader/TextPager.java deleted file mode 100644 index 117d6fd3c..000000000 --- a/Essentials/src/com/earth2me/essentials/utils/textreader/TextPager.java +++ /dev/null @@ -1,183 +0,0 @@ -package com.earth2me.essentials.utils.textreader; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.server.CommandSender; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import org.bukkit.command.CommandSender; - - -public class TextPager -{ - private final transient IText text; - private final transient boolean onePage; - - public TextPager(final IText text) - { - this(text, false); - } - - public TextPager(final IText text, final boolean onePage) - { - this.text = text; - this.onePage = onePage; - } - - public void showPage(final String pageStr, final String chapterPageStr, final String commandName, final CommandSender sender) - { - List lines = text.getLines(); - List chapters = text.getChapters(); - Map bookmarks = text.getBookmarks(); - - if (bookmarks.isEmpty()) - { - int page = 1; - try - { - page = Integer.parseInt(pageStr); - } - catch (Exception ex) - { - page = 1; - } - if (page < 1) - { - page = 1; - } - - final int start = onePage ? 0 : (page - 1) * 9; - final int pages = lines.size() / 9 + (lines.size() % 9 > 0 ? 1 : 0); - if (!onePage) - { - sender.sendMessage(_("infoPages", page, pages)); - } - for (int i = start; i < lines.size() && i < start + (onePage ? 20 : 9); i++) - { - sender.sendMessage(lines.get(i)); - } - if (!onePage && page < pages) - { - sender.sendMessage(_("readNextPage", commandName, page + 1)); - } - return; - } - - if (pageStr == null || pageStr.isEmpty() || pageStr.matches("[0-9]+")) - { - if (lines.get(0).startsWith("#")) - { - if (onePage) - { - return; - } - sender.sendMessage(_("infoChapter")); - final StringBuilder sb = new StringBuilder(); - boolean first = true; - for (String string : chapters) - { - if (!first) - { - sb.append(", "); - } - first = false; - sb.append(string); - } - sender.sendMessage(sb.toString()); - return; - } - else - { - int page = 1; - try - { - page = Integer.parseInt(pageStr); - } - catch (Exception ex) - { - page = 1; - } - if (page < 1) - { - page = 1; - } - - int start = onePage ? 0 : (page - 1) * 9; - int end; - for (end = 0; end < lines.size(); end++) - { - String line = lines.get(end); - if (line.startsWith("#")) - { - break; - } - } - - int pages = end / 9 + (end % 9 > 0 ? 1 : 0); - if (!onePage) - { - - sender.sendMessage(_("infoPages", page, pages)); - } - for (int i = start; i < end && i < start + (onePage ? 20 : 9); i++) - { - sender.sendMessage(lines.get(i)); - } - if (!onePage && page < pages) - { - sender.sendMessage(_("readNextPage", commandName, page + 1)); - } - return; - } - } - - int chapterpage = 0; - if (chapterPageStr != null) - { - try - { - chapterpage = Integer.parseInt(chapterPageStr) - 1; - } - catch (Exception ex) - { - chapterpage = 0; - } - if (chapterpage < 0) - { - chapterpage = 0; - } - } - - if (!bookmarks.containsKey(pageStr.toLowerCase(Locale.ENGLISH))) - { - sender.sendMessage(_("infoUnknownChapter")); - return; - } - final int chapterstart = bookmarks.get(pageStr.toLowerCase(Locale.ENGLISH)) + 1; - int chapterend; - for (chapterend = chapterstart; chapterend < lines.size(); chapterend++) - { - final String line = lines.get(chapterend); - if (line.length() > 0 && line.charAt(0) == '#') - { - break; - } - } - final int start = chapterstart + (onePage ? 0 : chapterpage * 9); - - final int page = chapterpage + 1; - final int pages = (chapterend - chapterstart) / 9 + ((chapterend - chapterstart) % 9 > 0 ? 1 : 0); - if (!onePage) - { - sender.sendMessage(_("infoChapterPages", pageStr, page, pages)); - } - for (int i = start; i < chapterend && i < start + (onePage ? 20 : 9); i++) - { - sender.sendMessage(lines.get(i)); - } - if (!onePage && page < pages) - { - sender.sendMessage(_("readNextPage", commandName, pageStr + " " + (page + 1))); - } - } -} diff --git a/Essentials/src/net/ess3/Console.java b/Essentials/src/net/ess3/Console.java new file mode 100644 index 000000000..4639a531a --- /dev/null +++ b/Essentials/src/net/ess3/Console.java @@ -0,0 +1,33 @@ +package net.ess3; + +import net.ess3.api.IReplyTo; +import net.ess3.api.server.CommandSender; + + +public final class Console implements IReplyTo +{ + private static Console instance = new Console(); + private CommandSender replyTo; + public final static String NAME = "Console"; + + private Console() + { + } + + @Override + public void setReplyTo(final CommandSender user) + { + replyTo = user; + } + + @Override + public CommandSender getReplyTo() + { + return replyTo; + } + + public static Console getConsoleReplyTo() + { + return instance; + } +} diff --git a/Essentials/src/net/ess3/Essentials.java b/Essentials/src/net/ess3/Essentials.java new file mode 100644 index 000000000..12526ffef --- /dev/null +++ b/Essentials/src/net/ess3/Essentials.java @@ -0,0 +1,377 @@ +/* + * Essentials - a bukkit plugin + * Copyright (C) 2011 Essentials Team + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package net.ess3; + +import net.ess3.api.*; +import net.ess3.api.server.Player; +import net.ess3.api.server.IPlugin; +import net.ess3.api.server.IServer; +import net.ess3.api.server.World; +import net.ess3.backup.Backup; +import net.ess3.commands.EssentialsCommandHandler; +import net.ess3.economy.Economy; +import net.ess3.economy.Trade; +import net.ess3.economy.WorthHolder; +import net.ess3.economy.register.Methods; +import net.ess3.listener.*; +import net.ess3.ranks.RanksStorage; +import net.ess3.settings.SettingsHolder; +import net.ess3.settings.SpawnsHolder; +import net.ess3.user.UserMap; +import net.ess3.utils.ExecuteTimer; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import lombok.Getter; +import org.bukkit.Server; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.plugin.InvalidDescriptionException; +import org.yaml.snakeyaml.error.YAMLException; + + +public class Essentials implements IEssentials +{ + private transient ISettings settings; + private final transient TntExplodeListener tntListener = new TntExplodeListener(this); + private transient IJails jails; + private transient IKits kits; + private transient IWarps warps; + private transient IWorth worth; + private transient List reloadList; + private transient IBackup backup; + private transient IItemDb itemDb; + private transient IRanks groups; + private transient SpawnsHolder spawns; + private transient final Methods paymentMethod = new Methods(); + //private transient PermissionsHandler permissionsHandler; + private transient IUserMap userMap; + private transient ExecuteTimer execTimer; + @Getter + private final I18n i18n; + private transient ICommandHandler commandHandler; + private transient Economy economy; + @Getter + private final IServer server; + @Getter + private final Logger logger; + @Getter + private final IPlugin plugin; + public static boolean testing; + + public Essentials(final IServer server, final Logger logger, final IPlugin plugin) + { + this.server = server; + this.logger = logger; + this.plugin = plugin; + this.i18n = new I18n(this); + i18n.onEnable(); + } + + @Override + public ISettings getSettings() + { + return settings; + } + + public void setupForTesting(final Server server) throws IOException, InvalidDescriptionException + { + testing = true; + final File dataFolder = File.createTempFile("essentialstest", ""); + if (!dataFolder.delete()) + { + throw new IOException(); + } + if (!dataFolder.mkdir()) + { + throw new IOException(); + } + + logger.log(Level.INFO, I18n._("usingTempFolderForTesting")); + logger.log(Level.INFO, dataFolder.toString()); + //this.initialize(null, server, new PluginDescriptionFile(new FileReader(new File("src" + File.separator + "plugin.yml"))), dataFolder, null, null); + settings = new SettingsHolder(this); + i18n.updateLocale("en"); + userMap = new UserMap(this); + //permissionsHandler = new PermissionsHandler(this); + economy = new Economy(this); + } + + @Override + public void onEnable() + { + execTimer = new ExecuteTimer(); + execTimer.start(); + + execTimer.mark("I18n1"); + + execTimer.mark("BukkitCheck"); + try + { + //final EssentialsUpgrade upgrade = new EssentialsUpgrade(this); + //upgrade.beforeSettings(); + //execTimer.mark("Upgrade"); + reloadList = new ArrayList(); + settings = new SettingsHolder(this); + reloadList.add(settings); + execTimer.mark("Settings"); + //upgrade.afterSettings(); + //execTimer.mark("Upgrade2"); + i18n.updateLocale(settings.getLocale()); + userMap = new UserMap(this); + reloadList.add(userMap); + execTimer.mark("Init(Usermap)"); + groups = new RanksStorage(this); + reloadList.add((RanksStorage)groups); + warps = new Warps(this); + reloadList.add(warps); + execTimer.mark("Init(Spawn/Warp)"); + worth = new WorthHolder(this); + reloadList.add(worth); + itemDb = new ItemDb(this); + reloadList.add(itemDb); + execTimer.mark("Init(Worth/ItemDB)"); + kits = new Kits(this); + reloadList.add(kits); + commandHandler = new EssentialsCommandHandler(Essentials.class.getClassLoader(), "net.ess3.commands.Command", "essentials.", this); + reloadList.add(commandHandler); + economy = new Economy(this); + reloadList.add(economy); + spawns = new SpawnsHolder(this); + reloadList.add(spawns); + onReload(); + } + catch (YAMLException exception) + { + if (pm.getPlugin("EssentialsUpdate") != null) + { + logger.log(Level.SEVERE, I18n._("essentialsHelp2")); + } + else + { + logger.log(Level.SEVERE, I18n._("essentialsHelp1")); + } + logger.log(Level.SEVERE, exception.toString()); + pm.registerEvents(new Listener() + { + @EventHandler(priority = EventPriority.LOW) + public void onPlayerJoin(final PlayerJoinEvent event) + { + event.getPlayer().sendMessage("Essentials failed to load, read the log file."); + } + }, this); + for (Player player : getServer().getOnlinePlayers()) + { + player.sendMessage("Essentials failed to load, read the log file."); + } + this.setEnabled(false); + return; + } + backup = new Backup(this); + //permissionsHandler = new PermissionsHandler(this); + final EssentialsPluginListener serverListener = new EssentialsPluginListener(this); + pm.registerEvents(serverListener, this); + reloadList.add(serverListener); + + final EssentialsPlayerListener playerListener = new EssentialsPlayerListener(this); + pm.registerEvents(playerListener, this); + + final EssentialsBlockListener blockListener = new EssentialsBlockListener(this); + pm.registerEvents(blockListener, this); + + final EssentialsEntityListener entityListener = new EssentialsEntityListener(this); + pm.registerEvents(entityListener, this); + + jails = new Jails(this); + reloadList.add(jails); + + pm.registerEvents(tntListener, this); + + + final EssentialsTimer timer = new EssentialsTimer(this); + getPlugin().scheduleSyncRepeatingTask(timer, 1, 100); + execTimer.mark("RegListeners"); + final String timeroutput = execTimer.end(); + if (getSettings().isDebug()) + { + logger.log(Level.INFO, "Essentials load {0}", timeroutput); + } + } + + @Override + public void onDisable() + { + i18n.onDisable(); + Trade.closeLog(); + } + + @Override + public void onReload() + { + Trade.closeLog(); + + for (IReload iReload : reloadList) + { + iReload.onReload(); + execTimer.mark("Reload(" + iReload.getClass().getSimpleName() + ")"); + } + + i18n.updateLocale(settings.getLocale()); + } + + @Override + public IJails getJails() + { + return jails; + } + + @Override + public IKits getKits() + { + return kits; + } + + @Override + public IWarps getWarps() + { + return warps; + } + + @Override + public IWorth getWorth() + { + return worth; + } + + @Override + public IBackup getBackup() + { + return backup; + } + + @Override + public IUser getUser(final String playerName) + { + return userMap.getUser(playerName); + } + + @Override + public World getWorld(final String name) + { + if (name.matches("[0-9]+")) + { + final int worldId = Integer.parseInt(name); + if (worldId < getServer().getWorlds().size()) + { + return getServer().getWorlds().get(worldId); + } + } + return getServer().getWorld(name); + } + + @Override + public void addReloadListener(final IReload listener) + { + reloadList.add(listener); + } + + @Override + public Methods getPaymentMethod() + { + return paymentMethod; + } + + @Override + public int broadcastMessage(final IUser sender, final String message) + { + if (sender == null) + { + return getServer().broadcastMessage(message); + } + if (sender.isHidden()) + { + return 0; + } + for (Player player : getServer().getOnlinePlayers()) + { + final IUser user = player.getUser(); + if (!user.isIgnoringPlayer(sender.getName())) + { + player.sendMessage(message); + } + } + + return getServer().getOnlinePlayers().size(); + } + + @Override + public TntExplodeListener getTNTListener() + { + return tntListener; + } + + /* + * @Override public PermissionsHandler getPermissionsHandler() { return permissionsHandler; } + */ + @Override + public IItemDb getItemDb() + { + return itemDb; + } + + @Override + public IUserMap getUserMap() + { + return userMap; + } + + @Override + public IRanks getRanks() + { + return groups; + } + + @Override + public ICommandHandler getCommandHandler() + { + return commandHandler; + } + + @Override + public void setRanks(final IRanks groups) + { + this.groups = groups; + } + + @Override + public void removeReloadListener(IReload groups) + { + this.reloadList.remove(groups); + } + + @Override + public IEconomy getEconomy() + { + return economy; + } +} diff --git a/Essentials/src/net/ess3/EssentialsTimer.java b/Essentials/src/net/ess3/EssentialsTimer.java new file mode 100644 index 000000000..bab8e9e0c --- /dev/null +++ b/Essentials/src/net/ess3/EssentialsTimer.java @@ -0,0 +1,80 @@ +package net.ess3; + +import net.ess3.api.IEssentials; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import net.ess3.user.UserData.TimestampType; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.logging.Level; + + +public class EssentialsTimer implements Runnable +{ + private final transient IEssentials ess; + private final transient Set onlineUsers = new HashSet(); + + EssentialsTimer(final IEssentials ess) + { + this.ess = ess; + } + + @Override + public void run() + { + final long currentTime = System.currentTimeMillis(); + for (Player player : ess.getServer().getOnlinePlayers()) + { + + try + { + final IUser user = player.getUser(); + onlineUsers.add(user); + user.setLastOnlineActivity(currentTime); + user.checkActivity(); + + boolean mailDisabled = false; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try + { + mailDisabled = settings.getData().getCommands().isDisabled("mail"); + } + finally + { + settings.unlock(); + } + // New mail notification + if (user != null && !mailDisabled && Permissions.MAIL.isAuthorized(user) && !user.gotMailInfo()) + { + final List mail = user.getMails(); + if (mail != null && !mail.isEmpty()) + { + user.sendMessage(I18n._("youHaveNewMail", mail.size())); + } + } + } + catch (Exception e) + { + ess.getLogger().log(Level.WARNING, "EssentialsTimer Error:", e); + } + } + + final Iterator iterator = onlineUsers.iterator(); + while (iterator.hasNext()) + { + final IUser user = iterator.next(); + if (user.getLastOnlineActivity() < currentTime && user.getLastOnlineActivity() > user.getTimestamp(TimestampType.LOGOUT)) + { + user.setTimestamp(TimestampType.LOGOUT, user.getLastOnlineActivity()); + iterator.remove(); + continue; + } + user.checkMuteTimeout(currentTime); + user.checkJailTimeout(currentTime); + } + } +} diff --git a/Essentials/src/net/ess3/I18n.java b/Essentials/src/net/ess3/I18n.java new file mode 100644 index 000000000..1aa1906ba --- /dev/null +++ b/Essentials/src/net/ess3/I18n.java @@ -0,0 +1,177 @@ +package net.ess3; + +import net.ess3.api.IEssentials; +import net.ess3.api.II18n; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.text.MessageFormat; +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class I18n implements 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 final transient Map messageFormatCache = new HashMap(); + private final transient IEssentials ess; + + public I18n(final IEssentials ess) + { + this.ess = ess; + customBundle = ResourceBundle.getBundle(MESSAGES, defaultLocale, new FileResClassLoader(I18n.class.getClassLoader(), ess)); + localeBundle = ResourceBundle.getBundle(MESSAGES, defaultLocale); + defaultBundle = ResourceBundle.getBundle(MESSAGES, Locale.ENGLISH); + } + + public void onEnable() + { + instance = this; + } + + public void onDisable() + { + instance = null; + } + + @Override + public Locale getCurrentLocale() + { + return currentLocale; + } + + public String translate(final String string) + { + try + { + try + { + return customBundle.getString(string); + } + catch (MissingResourceException ex) + { + return localeBundle.getString(string); + } + } + catch (MissingResourceException ex) + { + Logger.getLogger("Minecraft").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 _(final String string, final Object... objects) + { + if (instance == null) { + return ""; + } + if (objects.length == 0) + { + return instance.translate(string); + } + else + { + return instance.format(string, objects); + } + } + + public String format(final String string, final Object... objects) + { + final String format = translate(string); + MessageFormat messageFormat = messageFormatCache.get(format); + if (messageFormat == null) + { + messageFormat = new MessageFormat(format); + messageFormatCache.put(format, messageFormat); + } + return messageFormat.format(objects); + } + + public void updateLocale(final String loc) + { + if (loc == null || loc.isEmpty()) + { + return; + } + final String[] parts = loc.split("[_\\.]"); + if (parts.length == 1) + { + currentLocale = new Locale(parts[0]); + } + if (parts.length == 2) + { + currentLocale = new Locale(parts[0], parts[1]); + } + if (parts.length == 3) + { + currentLocale = new Locale(parts[0], parts[1], parts[2]); + } + Logger.getLogger("Minecraft").log(Level.INFO, String.format("Using locale %s", currentLocale.toString())); + customBundle = ResourceBundle.getBundle(MESSAGES, currentLocale, new FileResClassLoader(I18n.class.getClassLoader(), ess)); + localeBundle = ResourceBundle.getBundle(MESSAGES, currentLocale); + } + + 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); + } + + + private static class FileResClassLoader extends ClassLoader + { + private final transient File dataFolder; + + public FileResClassLoader(final ClassLoader classLoader, final IEssentials ess) + { + super(classLoader); + this.dataFolder = ess.getPlugin().getDataFolder(); + } + + @Override + public URL getResource(final String string) + { + final File file = new File(dataFolder, string); + if (file.exists()) + { + try + { + return file.toURI().toURL(); + } + catch (MalformedURLException ex) + { + } + } + return super.getResource(string); + } + + @Override + public InputStream getResourceAsStream(final String string) + { + final File file = new File(dataFolder, string); + if (file.exists()) + { + try + { + return new FileInputStream(file); + } + catch (FileNotFoundException ex) + { + } + } + return super.getResourceAsStream(string); + } + } +} diff --git a/Essentials/src/net/ess3/ItemDb.java b/Essentials/src/net/ess3/ItemDb.java new file mode 100644 index 000000000..1ccc063b1 --- /dev/null +++ b/Essentials/src/net/ess3/ItemDb.java @@ -0,0 +1,151 @@ +package net.ess3; + +import net.ess3.storage.ManagedFile; +import static net.ess3.I18n._; +import net.ess3.api.IEssentials; +import net.ess3.api.IItemDb; +import net.ess3.api.IUser; +import net.ess3.api.server.ItemStack; +import net.ess3.api.server.Material; +import net.ess3.permissions.Permissions; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.regex.Pattern; +import lombok.Cleanup; + + +public class ItemDb implements IItemDb +{ + private final transient IEssentials ess; + + public ItemDb(final IEssentials ess) + { + this.ess = ess; + file = new ManagedFile("items.csv", ess); + } + private final transient Map items = new HashMap(); + private final transient ManagedFile file; + private static final Pattern SPLIT = Pattern.compile("[^a-zA-Z0-9]"); + + @Override + public void onReload() + { + final List lines = file.getLines(); + + if (lines.isEmpty()) + { + return; + } + + items.clear(); + + for (String line : lines) + { + line = line.trim(); + if (line.length() > 0 && line.charAt(0) == '#') + { + continue; + } + + final String[] parts = SPLIT.split(line); + if (parts.length < 2) + { + continue; + } + + final long numeric = Integer.parseInt(parts[1]); + + final long durability = parts.length > 2 && !(parts[2].length() == 1 && parts[2].charAt(0) == '0') ? Short.parseShort(parts[2]) : 0; + items.put(parts[0].toLowerCase(Locale.ENGLISH), numeric | (durability << 32)); + } + } + + public ItemStack get(final String id, final IUser user) throws Exception + { + final ItemStack stack = get(id.toLowerCase(Locale.ENGLISH)); + + @Cleanup + net.ess3.api.ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + + final int defaultStackSize = settings.getData().getGeneral().getDefaultStacksize(); + + if (defaultStackSize > 0) + { + stack.setAmount(defaultStackSize); + } + else + { + final int oversizedStackSize = settings.getData().getGeneral().getOversizedStacksize(); + if (oversizedStackSize > 0 && Permissions.OVERSIZEDSTACKS.isAuthorized(user)) + { + stack.setAmount(oversizedStackSize); + } + } + return stack; + } + + public ItemStack get(final String id, final int quantity) throws Exception + { + final ItemStack retval = get(id.toLowerCase(Locale.ENGLISH)); + retval.setAmount(quantity); + return retval; + } + + public ItemStack get(final String id) throws Exception + { + int itemid = 0; + String itemname = null; + short metaData = 0; + if (id.matches("^\\d+[:+',;.]\\d+$")) + { + itemid = Integer.parseInt(id.split("[:+',;.]")[0]); + metaData = Short.parseShort(id.split("[:+',;.]")[1]); + } + else if (id.matches("^\\d+$")) + { + itemid = Integer.parseInt(id); + } + else if (id.matches("^[^:+',;.]+[:+',;.]\\d+$")) + { + itemname = id.split("[:+',;.]")[0].toLowerCase(Locale.ENGLISH); + metaData = Short.parseShort(id.split("[:+',;.]")[1]); + } + else + { + itemname = id.toLowerCase(Locale.ENGLISH); + } + + if (itemname != null) + { + if (items.containsKey(itemname)) + { + long item = items.get(itemname); + itemid = (int)(item & 0xffffffffL); + if (metaData == 0) + { + metaData = (short)((item >> 32) & 0xffffL); + } + } + else if (Material.get(itemname) != null) + { + itemid = Material.get(itemname).getId(); + metaData = 0; + } + else + { + throw new Exception(_("unknownItemName", id)); + } + } + + final Material mat = Material.get(itemid); + if (mat == null) + { + throw new Exception(_("unknownItemId", itemid)); + } + final ItemStack retval = ItemStack.create(mat, mat.getMaxStackSize(), metaData); + return retval; + } +} diff --git a/Essentials/src/net/ess3/Jails.java b/Essentials/src/net/ess3/Jails.java new file mode 100644 index 000000000..2c3f31bca --- /dev/null +++ b/Essentials/src/net/ess3/Jails.java @@ -0,0 +1,301 @@ +package net.ess3; + +import static net.ess3.I18n._; +import net.ess3.api.IEssentials; +import net.ess3.api.IJails; +import net.ess3.api.IUser; +import net.ess3.storage.AsyncStorageObjectHolder; +import java.io.File; +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; +import lombok.Cleanup; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockDamageEvent; +import org.bukkit.event.block.BlockPlaceEvent; +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; + + +public class Jails extends AsyncStorageObjectHolder implements IJails +{ + private static final transient Logger LOGGER = Bukkit.getLogger(); + + public Jails(final IEssentials ess) + { + super(ess, net.ess3.settings.Jails.class); + onReload(); + registerListeners(); + } + + private void registerListeners() + { + final PluginManager pluginManager = ess.getServer().getPluginManager(); + final JailBlockListener blockListener = new JailBlockListener(); + final JailPlayerListener playerListener = new JailPlayerListener(); + pluginManager.registerEvents(blockListener, ess); + pluginManager.registerEvents(playerListener, ess); + } + + @Override + public File getStorageFile() + { + return new File(ess.getPlugin().getDataFolder(), "jail.yml"); + } + + @Override + public Location getJail(final String jailName) throws Exception + { + acquireReadLock(); + try + { + if (getData().getJails() == null || jailName == null + || !getData().getJails().containsKey(jailName.toLowerCase(Locale.ENGLISH))) + { + throw new Exception(_("jailNotExist")); + } + Location loc = getData().getJails().get(jailName.toLowerCase(Locale.ENGLISH)).getStoredLocation(); + if (loc == null || loc.getWorld() == null) + { + throw new Exception(_("jailNotExist")); + } + return loc; + } + finally + { + unlock(); + } + } + + @Override + public Collection getList() throws Exception + { + acquireReadLock(); + try + { + if (getData().getJails() == null) + { + return Collections.emptyList(); + } + return new ArrayList(getData().getJails().keySet()); + } + finally + { + unlock(); + } + } + + @Override + public void removeJail(final String jail) throws Exception + { + acquireWriteLock(); + try + { + if (getData().getJails() == null) + { + return; + } + getData().getJails().remove(jail.toLowerCase(Locale.ENGLISH)); + } + finally + { + unlock(); + } + } + + @Override + public void sendToJail(final IUser user, final String jail) throws Exception + { + acquireReadLock(); + try + { + if (user.isOnline()) + { + Location loc = getJail(jail); + user.getTeleport().now(loc, false, TeleportCause.COMMAND); + } + user.acquireWriteLock(); + try + { + user.getData().setJail(jail); + } + finally + { + unlock(); + } + } + finally + { + unlock(); + } + } + + @Override + public void setJail(final String jailName, final Location loc) throws Exception + { + acquireWriteLock(); + try + { + if (getData().getJails() == null) + { + getData().setJails(new HashMap()); + } + getData().getJails().put(jailName.toLowerCase(Locale.ENGLISH), new net.ess3.storage.StoredLocation(loc)); + } + finally + { + unlock(); + } + } + + + private class JailBlockListener implements Listener + { + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onBlockBreak(final BlockBreakEvent event) + { + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (user.getData().isJailed()) + { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onBlockPlace(final BlockPlaceEvent event) + { + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (user.getData().isJailed()) + { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onBlockDamage(final BlockDamageEvent event) + { + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (user.getData().isJailed()) + { + event.setCancelled(true); + } + } + } + + + private class JailPlayerListener implements Listener + { + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onPlayerInteract(final PlayerInteractEvent event) + { + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (user.getData().isJailed()) + { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerRespawn(final PlayerRespawnEvent event) + { + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (!user.getData().isJailed() || user.getData().getJail() == null || user.getData().getJail().isEmpty()) + { + return; + } + + try + { + event.setRespawnLocation(getJail(user.getData().getJail())); + } + catch (Exception ex) + { + if (ess.getSettings().isDebug()) + { + LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex); + } + else + { + LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())); + } + } + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerTeleport(final PlayerTeleportEvent event) + { + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (!user.getData().isJailed() || user.getData().getJail() == null || user.getData().getJail().isEmpty()) + { + return; + } + + try + { + event.setTo(getJail(user.getData().getJail())); + } + catch (Exception ex) + { + if (ess.getSettings().isDebug()) + { + LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex); + } + else + { + LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())); + } + } + user.sendMessage(_("jailMessage")); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerJoin(final PlayerJoinEvent event) + { + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (!user.getData().isJailed() || user.getData().getJail() == null || user.getData().getJail().isEmpty()) + { + return; + } + + try + { + sendToJail(user, user.getData().getJail()); + } + catch (Exception ex) + { + if (ess.getSettings().isDebug()) + { + LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex); + } + else + { + LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())); + } + } + user.sendMessage(_("jailMessage")); + } + } +} diff --git a/Essentials/src/net/ess3/Kits.java b/Essentials/src/net/ess3/Kits.java new file mode 100644 index 000000000..e286eb847 --- /dev/null +++ b/Essentials/src/net/ess3/Kits.java @@ -0,0 +1,90 @@ +package net.ess3; + +import static net.ess3.I18n._; +import net.ess3.api.IEssentials; +import net.ess3.api.IKits; +import net.ess3.api.IUser; +import net.ess3.settings.Kit; +import net.ess3.storage.AsyncStorageObjectHolder; +import java.io.File; +import java.io.IOException; +import java.util.*; +import org.bukkit.inventory.ItemStack; + + +public class Kits extends AsyncStorageObjectHolder implements IKits +{ + public Kits(final IEssentials ess) + { + super(ess, net.ess3.settings.Kits.class); + onReload(); + } + + @Override + public File getStorageFile() throws IOException + { + return new File(ess.getPlugin().getDataFolder(), "kits.yml"); + } + + @Override + public Kit getKit(String kitName) throws Exception + { + acquireReadLock(); + try + { + if (getData().getKits() == null || kitName == null + || !getData().getKits().containsKey(kitName.toLowerCase(Locale.ENGLISH))) + { + throw new Exception(_("kitError2")); + } + final Kit kit = getData().getKits().get(kitName.toLowerCase(Locale.ENGLISH)); + if (kit == null) + { + throw new Exception(_("kitError2")); + } + return kit; + } + finally + { + unlock(); + } + } + + @Override + public void sendKit(IUser user, String kitName) throws Exception + { + final Kit kit = getKit(kitName); + sendKit(user, kit); + } + + @Override + public void sendKit(IUser user, Kit kit) throws Exception + { + final List itemList = kit.getItems(); + user.giveItems(itemList, true); + } + + @Override + public Collection getList() throws Exception + { + acquireReadLock(); + try + { + if (getData().getKits() == null) + { + return Collections.emptyList(); + } + return new ArrayList(getData().getKits().keySet()); + } + finally + { + unlock(); + } + } + + @Override + public boolean isEmpty() + { + return getData().getKits().isEmpty(); + } +} diff --git a/Essentials/src/net/ess3/Teleport.java b/Essentials/src/net/ess3/Teleport.java new file mode 100644 index 000000000..83eb8a842 --- /dev/null +++ b/Essentials/src/net/ess3/Teleport.java @@ -0,0 +1,301 @@ +package net.ess3; + +import static net.ess3.I18n._; +import net.ess3.api.IEssentials; +import net.ess3.api.ITeleport; +import net.ess3.api.IUser; +import net.ess3.api.server.Player; +import net.ess3.api.server.Location; +import net.ess3.commands.NotEnoughArgumentsException; +import net.ess3.economy.Trade; +import net.ess3.permissions.Permissions; +import net.ess3.user.CooldownException; +import net.ess3.user.UserData.TimestampType; +import net.ess3.utils.DateUtil; +import net.ess3.utils.LocationUtil; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.logging.Logger; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + + +public class Teleport implements Runnable, ITeleport +{ + private static final double MOVE_CONSTANT = 0.3; + + + private static class Target + { + private final Location location; + private final Player entity; + + public Target(Location location) + { + this.location = location; + this.entity = null; + } + + public Target(Player entity) + { + this.entity = entity; + this.location = null; + } + + public Location getLocation() + { + if (this.entity != null) + { + return this.entity.getLocation(); + } + return location; + } + } + private IUser user; + private int teleTimer = -1; + private long started; // time this task was initiated + private long delay; // how long to delay the teleport + private int 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 + private long initX; + private long initY; + private long initZ; + private Target teleportTarget; + private Trade chargeFor; + private final IEssentials ess; + private static final Logger logger = Logger.getLogger("Minecraft"); + private TeleportCause cause; + + private void initTimer(long delay, Target target, Trade chargeFor, TeleportCause cause) + { + this.started = System.currentTimeMillis(); + this.delay = delay; + this.health = user.getHealth(); + this.initX = Math.round(user.getLocation().getX() * MOVE_CONSTANT); + this.initY = Math.round(user.getLocation().getY() * MOVE_CONSTANT); + this.initZ = Math.round(user.getLocation().getZ() * MOVE_CONSTANT); + this.teleportTarget = target; + this.chargeFor = chargeFor; + this.cause = cause; + } + + @Override + public void run() + { + + if (user == null || !user.isOnline() || user.getLocation() == null) + { + cancel(); + return; + } + if (Math.round(user.getLocation().getX() * MOVE_CONSTANT) != initX + || Math.round(user.getLocation().getY() * MOVE_CONSTANT) != initY + || Math.round(user.getLocation().getZ() * MOVE_CONSTANT) != initZ + || user.getHealth() < health) + { // user moved, cancel teleport + cancel(true); + return; + } + + health = user.getHealth(); // in case user healed, then later gets injured + + long now = System.currentTimeMillis(); + if (now > started + delay) + { + try + { + cooldown(false); + user.sendMessage(_("teleportationCommencing")); + try + { + + now(teleportTarget, cause); + if (chargeFor != null) + { + chargeFor.charge(user); + } + } + catch (Throwable ex) + { + ess.getCommandHandler().showCommandError(user, "teleport", ex); + } + } + catch (Exception ex) + { + user.sendMessage(_("cooldownWithMessage", ex.getMessage())); + } + } + } + + public Teleport(IUser user, IEssentials ess) + { + this.user = user; + this.ess = ess; + } + + public void respawn(final Trade chargeFor, TeleportCause cause) throws Exception + { + final Location bed = user.getBedSpawnLocation(); + final Location respawnLoc = ess.getPlugin().callRespawnEvent(user, bed == null ? user.getWorld().getSpawnLocation() : bed, bed != null); + teleport(new Target(respawnLoc), chargeFor, cause); + } + + public void warp(String warp, Trade chargeFor, TeleportCause cause) throws Exception + { + final Location loc = ess.getWarps().getWarp(warp); + teleport(new Target(loc), chargeFor, cause); + user.sendMessage(_("warpingTo", warp)); + } + + public void cooldown(boolean check) throws Exception + { + try + { + user.checkCooldown(TimestampType.LASTTELEPORT, ess.getRanks().getTeleportCooldown(user), !check, Permissions.TELEPORT_COOLDOWN_BYPASS); + } + catch (CooldownException ex) + { + throw new Exception(_("timeBeforeTeleport", ex.getMessage())); + + } + } + + public void cancel(boolean notifyUser) + { + if (teleTimer == -1) + { + return; + } + try + { + ess.getPlugin().cancelTask(teleTimer); + if (notifyUser) + { + user.sendMessage(_("pendingTeleportCancelled")); + } + } + finally + { + teleTimer = -1; + } + } + + public void cancel() + { + cancel(false); + } + + public void teleport(Location loc, Trade chargeFor) throws Exception + { + teleport(new Target(loc), chargeFor, TeleportCause.PLUGIN); + } + + public void teleport(Location loc, Trade chargeFor, TeleportCause cause) throws Exception + { + teleport(new Target(loc), chargeFor, cause); + } + + public void teleport(Player entity, Trade chargeFor, TeleportCause cause) throws Exception + { + teleport(new Target(entity), chargeFor, cause); + } + + private void teleport(Target target, Trade chargeFor, TeleportCause cause) throws Exception + { + double delay = ess.getRanks().getTeleportDelay(user); + + if (chargeFor != null) + { + chargeFor.isAffordableFor(user); + } + cooldown(true); + if (delay <= 0 || Permissions.TELEPORT_TIMER_BYPASS.isAuthorized(user)) + { + cooldown(false); + now(target, cause); + if (chargeFor != null) + { + chargeFor.charge(user); + } + return; + } + + cancel(); + Calendar c = new GregorianCalendar(); + c.add(Calendar.SECOND, (int)delay); + c.add(Calendar.MILLISECOND, (int)((delay * 1000.0) % 1000.0)); + user.sendMessage(_("dontMoveMessage", DateUtil.formatDateDiff(c.getTimeInMillis()))); + initTimer((long)(delay * 1000.0), target, chargeFor, cause); + + teleTimer = ess.getPlugin().scheduleSyncRepeatingTask(this, 10, 10); + } + + private void now(Target target, TeleportCause cause) throws Exception + { + cancel(); + user.setLastLocation(); + user.getBase().teleport(LocationUtil.getSafeDestination(target.getLocation()), cause); + } + + public void now(Location loc, boolean cooldown, TeleportCause cause) throws Exception + { + if (cooldown) + { + cooldown(false); + } + now(new Target(loc), cause); + } + + public void now(Location loc, Trade chargeFor, TeleportCause cause) throws Exception + { + cooldown(false); + chargeFor.charge(user); + now(new Target(loc), cause); + } + + public void now(Player entity, boolean cooldown, TeleportCause cause) throws Exception + { + if (cooldown) + { + cooldown(false); + } + now(new Target(entity), cause); + } + + public void back(Trade chargeFor) throws Exception + { + user.acquireReadLock(); + try + { + teleport(new Target(user.getData().getLastLocation().getStoredLocation()), chargeFor, TeleportCause.COMMAND); + } + finally + { + user.unlock(); + } + } + + public void back() throws Exception + { + user.acquireReadLock(); + try + { + now(new Target(user.getData().getLastLocation().getStoredLocation()), TeleportCause.COMMAND); + } + finally + { + user.unlock(); + } + } + + public void home(IUser user, String home, Trade chargeFor) throws Exception + { + final Location loc = user.getHome(home); + if (loc == null) + { + throw new NotEnoughArgumentsException(); + } + teleport(new Target(loc), chargeFor, TeleportCause.COMMAND); + } +} diff --git a/Essentials/src/net/ess3/Warps.java b/Essentials/src/net/ess3/Warps.java new file mode 100644 index 000000000..08398b8e1 --- /dev/null +++ b/Essentials/src/net/ess3/Warps.java @@ -0,0 +1,148 @@ +package net.ess3; + +import static net.ess3.I18n._; +import net.ess3.api.IEssentials; +import net.ess3.api.IWarp; +import net.ess3.api.IWarps; +import net.ess3.api.InvalidNameException; +import net.ess3.api.server.Location; +import net.ess3.commands.WarpNotFoundException; +import net.ess3.settings.WarpHolder; +import net.ess3.storage.StorageObjectMap; +import java.io.File; +import java.util.*; + + +public class Warps extends StorageObjectMap implements IWarps +{ + public Warps(IEssentials ess) + { + super(ess, "warps"); + } + + @Override + public boolean isEmpty() + { + return getKeySize() == 0; + } + + @Override + public Collection getList() + { + final List names = new ArrayList(); + for (String key : getAllKeys()) + { + IWarp warp = getObject(key); + if (warp == null) + { + continue; + } + warp.acquireReadLock(); + try + { + names.add(warp.getData().getName()); + } + finally + { + warp.unlock(); + } + } + Collections.sort(names, String.CASE_INSENSITIVE_ORDER); + return names; + } + + @Override + public Location getWarp(final String name) throws Exception + { + IWarp warp = getObject(name); + if (warp == null) + { + throw new WarpNotFoundException(_("warpNotExist")); + } + warp.acquireReadLock(); + try + { + return warp.getData().getLocation().getStoredLocation(); + } + finally + { + warp.unlock(); + } + } + + @Override + public void setWarp(final String name, final Location loc) throws Exception + { + setWarp(name, new net.ess3.storage.StoredLocation(loc)); + } + + public void setWarp(final String name, final net.ess3.storage.StoredLocation loc) throws Exception + { + IWarp warp = getObject(name); + if (warp == null) + { + warp = new WarpHolder(name, ess); + } + warp.acquireWriteLock(); + try + { + warp.getData().setLocation(loc); + } + finally + { + warp.unlock(); + } + } + + @Override + public void removeWarp(final String name) throws Exception + { + removeObject(name); + } + + @Override + public File getWarpFile(String name) throws InvalidNameException + { + return getStorageFile(name); + } + + @Override + public IWarp load(String name) throws Exception + { + final IWarp warp = new WarpHolder(name, ess); + warp.onReload(); + return warp; + } + + + private static class StringIgnoreCase + { + private final String string; + + public StringIgnoreCase(String string) + { + this.string = string; + } + + @Override + public int hashCode() + { + return getString().toLowerCase(Locale.ENGLISH).hashCode(); + } + + @Override + public boolean equals(Object o) + { + if (o instanceof StringIgnoreCase) + { + return getString().equalsIgnoreCase(((StringIgnoreCase)o).getString()); + } + return false; + } + + public String getString() + { + return string; + } + } +} diff --git a/Essentials/src/net/ess3/api/ChargeException.java b/Essentials/src/net/ess3/api/ChargeException.java new file mode 100644 index 000000000..48a004791 --- /dev/null +++ b/Essentials/src/net/ess3/api/ChargeException.java @@ -0,0 +1,15 @@ +package net.ess3.api; + + +public class ChargeException extends Exception +{ + public ChargeException(final String message) + { + super(message); + } + + public ChargeException(final String message, final Throwable throwable) + { + super(message, throwable); + } +} diff --git a/Essentials/src/net/ess3/api/Economy.java b/Essentials/src/net/ess3/api/Economy.java new file mode 100644 index 000000000..b16db0556 --- /dev/null +++ b/Essentials/src/net/ess3/api/Economy.java @@ -0,0 +1,231 @@ +package net.ess3.api; + +import net.ess3.utils.Util; + + +/** + * Instead of using this api directly, we recommend to use the register plugin: + * http://bit.ly/RegisterMethod + */ +public final class Economy +{ + private Economy() + { + } + private static IEssentials ess; + private static final String noCallBeforeLoad = "Essentials API is called before Essentials is loaded."; + + /** + * Returns the balance of a user + * @param name Name of the user + * @return balance + * @throws UserDoesNotExistException + */ + public static double getMoney(String name) throws UserDoesNotExistException + { + if (ess == null) + { + throw new RuntimeException(noCallBeforeLoad); + } + return ess.getEconomy().getMoney(name); + } + + /** + * Sets the balance of a user + * @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 + */ + public static void setMoney(String name, double balance) throws UserDoesNotExistException, NoLoanPermittedException + { + if (ess == null) + { + throw new RuntimeException(noCallBeforeLoad); + } + ess.getEconomy().setMoney(name, balance); + } + + /** + * Adds money to the balance of a user + * @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 + */ + public static void add(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException + { + double result = getMoney(name) + amount; + setMoney(name, result); + } + + /** + * Substracts money from the balance of a user + * @param name Name of the user + * @param amount The money you want to substract + * @throws UserDoesNotExistException If a user by that name does not exists + * @throws NoLoanPermittedException If the user is not allowed to have a negative balance + */ + public static void subtract(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException + { + double result = getMoney(name) - amount; + setMoney(name, result); + } + + /** + * Divides the balance of a user by a value + * @param name Name of the user + * @param value 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 + */ + public static void divide(String name, double value) throws UserDoesNotExistException, NoLoanPermittedException + { + double result = getMoney(name) / value; + setMoney(name, result); + } + + /** + * Multiplies the balance of a user by a value + * @param name Name of the user + * @param value 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 + */ + public static void multiply(String name, double value) throws UserDoesNotExistException, NoLoanPermittedException + { + double result = getMoney(name) * value; + setMoney(name, result); + } + + /** + * Resets the balance of a user to the starting balance + * @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 + */ + public static void resetBalance(String name) throws UserDoesNotExistException, NoLoanPermittedException + { + if (ess == null) + { + throw new RuntimeException(noCallBeforeLoad); + } + ess.getEconomy().resetBalance(name); + } + + /** + * @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 + */ + public static boolean hasEnough(String name, double amount) throws UserDoesNotExistException + { + return amount <= getMoney(name); + } + + /** + * @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 + */ + public static boolean hasMore(String name, double amount) throws UserDoesNotExistException + { + return amount < getMoney(name); + } + + /** + * @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 + */ + public static boolean hasLess(String name, double amount) throws UserDoesNotExistException + { + return amount > getMoney(name); + } + + /** + * Test if the user has a negative balance + * @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 + */ + public static boolean isNegative(String name) throws UserDoesNotExistException + { + return getMoney(name) < 0.0; + } + + /** + * Formats the amount of money like all other Essentials functions. + * Example: $100000 or $12345.67 + * @param amount The amount of money + * @return Formatted money + */ + public static String format(double amount) + { + if (ess == null) + { + throw new RuntimeException(noCallBeforeLoad); + } + return Util.displayCurrency(amount, ess); + } + + /** + * Test if a player exists to avoid the UserDoesNotExistException + * @param name Name of the user + * @return true, if the user exists + */ + public static boolean playerExists(String name) + { + if (ess == null) + { + throw new RuntimeException(noCallBeforeLoad); + } + return ess.getEconomy().playerExists(name); + } + + /** + * 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 + { + if (ess == null) + { + throw new RuntimeException(noCallBeforeLoad); + } + return ess.getEconomy().isNPC(name); + } + + /** + * 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) + { + if (ess == null) + { + throw new RuntimeException(noCallBeforeLoad); + } + return ess.getEconomy().createNPC(name); + } + + /** + * 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 + { + if (ess == null) + { + throw new RuntimeException(noCallBeforeLoad); + } + ess.getEconomy().removeNPC(name); + } +} diff --git a/Essentials/src/net/ess3/api/IBackup.java b/Essentials/src/net/ess3/api/IBackup.java new file mode 100644 index 000000000..03fb232eb --- /dev/null +++ b/Essentials/src/net/ess3/api/IBackup.java @@ -0,0 +1,7 @@ +package net.ess3.api; + + +public interface IBackup extends Runnable +{ + public void startTask(); +} diff --git a/Essentials/src/net/ess3/api/ICommandHandler.java b/Essentials/src/net/ess3/api/ICommandHandler.java new file mode 100644 index 000000000..be7a9e6c4 --- /dev/null +++ b/Essentials/src/net/ess3/api/ICommandHandler.java @@ -0,0 +1,20 @@ +package net.ess3.api; + +import net.ess3.api.server.CommandSender; +import java.util.Map; +import org.bukkit.command.Command; +import org.bukkit.plugin.Plugin; + + +public interface ICommandHandler extends IReload +{ + Map disabledCommands(); + + public void removePlugin(Plugin plugin); + + public void addPlugin(Plugin plugin); + + boolean handleCommand(CommandSender sender, Command command, String commandLabel, String[] args); + + void showCommandError(CommandSender sender, String commandLabel, Throwable exception); +} diff --git a/Essentials/src/net/ess3/api/IComponent.java b/Essentials/src/net/ess3/api/IComponent.java new file mode 100644 index 000000000..a25a19f81 --- /dev/null +++ b/Essentials/src/net/ess3/api/IComponent.java @@ -0,0 +1,13 @@ +package net.ess3.api; + +public interface IComponent extends IReload { + /** + * Enable the component. + */ + void onEnable(); + + /** + * Disable the component. + */ + void onDisable(); +} diff --git a/Essentials/src/net/ess3/api/IEconomy.java b/Essentials/src/net/ess3/api/IEconomy.java new file mode 100644 index 000000000..f0cf6f7fe --- /dev/null +++ b/Essentials/src/net/ess3/api/IEconomy.java @@ -0,0 +1,21 @@ +package net.ess3.api; + + +public interface IEconomy extends IReload +{ + public double getMoney(String name) throws UserDoesNotExistException; + + public void setMoney(String name, double balance) throws UserDoesNotExistException, NoLoanPermittedException; + + public void resetBalance(String name) throws UserDoesNotExistException, NoLoanPermittedException; + + public String format(double amount); + + public boolean playerExists(String name); + + public boolean isNPC(String name) throws UserDoesNotExistException; + + public boolean createNPC(String name); + + public void removeNPC(String name) throws UserDoesNotExistException; +} diff --git a/Essentials/src/net/ess3/api/IEssentials.java b/Essentials/src/net/ess3/api/IEssentials.java new file mode 100644 index 000000000..286d00037 --- /dev/null +++ b/Essentials/src/net/ess3/api/IEssentials.java @@ -0,0 +1,64 @@ +package net.ess3.api; + +import net.ess3.api.server.IPlugin; +import net.ess3.api.server.IServer; +import net.ess3.api.server.World; +import net.ess3.economy.register.Methods; +import net.ess3.listener.TntExplodeListener; +import java.util.logging.Logger; + + +public interface IEssentials extends IComponent +{ + void addReloadListener(IReload listener); + + IUser getUser(String playerName); + + int broadcastMessage(IUser sender, String message); + + II18n getI18n(); + + ISettings getSettings(); + + IRanks getRanks(); + + IJails getJails(); + + IKits getKits(); + + IWarps getWarps(); + + IWorth getWorth(); + + IItemDb getItemDb(); + + IUserMap getUserMap(); + + IBackup getBackup(); + + ICommandHandler getCommandHandler(); + + World getWorld(String name); + + Methods getPaymentMethod(); + + //int scheduleAsyncDelayedTask(Runnable run); + //int scheduleSyncDelayedTask(Runnable run); + //int scheduleSyncDelayedTask(Runnable run, long delay); + //int scheduleSyncRepeatingTask(Runnable run, long delay, long period); + //IPermissionsHandler getPermissionsHandler(); + //void reload(); + TntExplodeListener getTNTListener(); + + void setRanks(IRanks groups); + + void removeReloadListener(IReload groups); + + IEconomy getEconomy(); + + IServer getServer(); + + Logger getLogger(); + + IPlugin getPlugin(); +} diff --git a/Essentials/src/net/ess3/api/IEssentialsModule.java b/Essentials/src/net/ess3/api/IEssentialsModule.java new file mode 100644 index 000000000..c4c6f3a45 --- /dev/null +++ b/Essentials/src/net/ess3/api/IEssentialsModule.java @@ -0,0 +1,6 @@ +package net.ess3.api; + + +public interface IEssentialsModule +{ +} diff --git a/Essentials/src/net/ess3/api/II18n.java b/Essentials/src/net/ess3/api/II18n.java new file mode 100644 index 000000000..198ee47c4 --- /dev/null +++ b/Essentials/src/net/ess3/api/II18n.java @@ -0,0 +1,9 @@ +package net.ess3.api; + +import java.util.Locale; + + +public interface II18n +{ + Locale getCurrentLocale(); +} diff --git a/Essentials/src/net/ess3/api/IItemDb.java b/Essentials/src/net/ess3/api/IItemDb.java new file mode 100644 index 000000000..fa9e1d868 --- /dev/null +++ b/Essentials/src/net/ess3/api/IItemDb.java @@ -0,0 +1,13 @@ +package net.ess3.api; + +import net.ess3.api.server.ItemStack; + + +public interface IItemDb extends IReload +{ + ItemStack get(final String name, final IUser user) throws Exception; + + ItemStack get(final String name, final int quantity) throws Exception; + + ItemStack get(final String name) throws Exception; +} diff --git a/Essentials/src/net/ess3/api/IJails.java b/Essentials/src/net/ess3/api/IJails.java new file mode 100644 index 000000000..c7b01dfdc --- /dev/null +++ b/Essentials/src/net/ess3/api/IJails.java @@ -0,0 +1,18 @@ +package net.ess3.api; + +import java.util.Collection; +import org.bukkit.Location; + + +public interface IJails extends IReload +{ + Location getJail(String jailName) throws Exception; + + Collection getList() throws Exception; + + void removeJail(String jail) throws Exception; + + void sendToJail(IUser user, String jail) throws Exception; + + void setJail(String jailName, Location loc) throws Exception; +} diff --git a/Essentials/src/net/ess3/api/IKits.java b/Essentials/src/net/ess3/api/IKits.java new file mode 100644 index 000000000..33a609c46 --- /dev/null +++ b/Essentials/src/net/ess3/api/IKits.java @@ -0,0 +1,18 @@ +package net.ess3.api; + +import net.ess3.settings.Kit; +import java.util.Collection; + + +public interface IKits extends IReload +{ + Kit getKit(String kit) throws Exception; + + void sendKit(IUser user, String kit) throws Exception; + + void sendKit(IUser user, Kit kit) throws Exception; + + Collection getList() throws Exception; + + boolean isEmpty(); +} diff --git a/Essentials/src/net/ess3/api/IPermission.java b/Essentials/src/net/ess3/api/IPermission.java new file mode 100644 index 000000000..60b0bdb42 --- /dev/null +++ b/Essentials/src/net/ess3/api/IPermission.java @@ -0,0 +1,16 @@ +package net.ess3.api; + +import net.ess3.api.server.CommandSender; +import net.ess3.api.server.Permission; + + +public interface IPermission +{ + String getPermissionName(); + + boolean isAuthorized(CommandSender sender); + + Permission getPermission(); + + Permission.Default getPermissionDefault(); +} diff --git a/Essentials/src/net/ess3/api/IRanks.java b/Essentials/src/net/ess3/api/IRanks.java new file mode 100644 index 000000000..4785bbb70 --- /dev/null +++ b/Essentials/src/net/ess3/api/IRanks.java @@ -0,0 +1,25 @@ +package net.ess3.api; + +import java.text.MessageFormat; + + +public interface IRanks +{ + String getMainGroup(IUser player); + + boolean inGroup(IUser player, String groupname); + + double getHealCooldown(IUser player); + + double getTeleportCooldown(IUser player); + + double getTeleportDelay(IUser player); + + String getPrefix(IUser player); + + String getSuffix(IUser player); + + int getHomeLimit(IUser player); + + MessageFormat getChatFormat(IUser player); +} diff --git a/Essentials/src/net/ess3/api/IReload.java b/Essentials/src/net/ess3/api/IReload.java new file mode 100644 index 000000000..964d88841 --- /dev/null +++ b/Essentials/src/net/ess3/api/IReload.java @@ -0,0 +1,7 @@ +package net.ess3.api; + + +public interface IReload +{ + void onReload(); +} diff --git a/Essentials/src/net/ess3/api/IReplyTo.java b/Essentials/src/net/ess3/api/IReplyTo.java new file mode 100644 index 000000000..6e96166bb --- /dev/null +++ b/Essentials/src/net/ess3/api/IReplyTo.java @@ -0,0 +1,11 @@ +package net.ess3.api; + +import net.ess3.api.server.CommandSender; + + +public interface IReplyTo +{ + void setReplyTo(CommandSender user); + + CommandSender getReplyTo(); +} diff --git a/Essentials/src/net/ess3/api/ISettings.java b/Essentials/src/net/ess3/api/ISettings.java new file mode 100644 index 000000000..971f96871 --- /dev/null +++ b/Essentials/src/net/ess3/api/ISettings.java @@ -0,0 +1,14 @@ +package net.ess3.api; + +import net.ess3.settings.Settings; +import net.ess3.storage.IStorageObjectHolder; + + +public interface ISettings extends IStorageObjectHolder +{ + public String getLocale(); + + public boolean isDebug(); + + public void setDebug(boolean b); +} diff --git a/Essentials/src/net/ess3/api/ITeleport.java b/Essentials/src/net/ess3/api/ITeleport.java new file mode 100644 index 000000000..559a05f39 --- /dev/null +++ b/Essentials/src/net/ess3/api/ITeleport.java @@ -0,0 +1,28 @@ +package net.ess3.api; + +import net.ess3.economy.Trade; +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + + +public interface ITeleport +{ + void now(Location loc, boolean cooldown, TeleportCause cause) throws Exception; + + void now(Entity entity, boolean cooldown, TeleportCause cause) throws Exception; + + void back(Trade chargeFor) throws Exception; + + void teleport(Location bed, Trade charge, TeleportCause teleportCause) throws Exception; + + void teleport(Entity entity, Trade chargeFor, TeleportCause cause) throws Exception; + + void home(IUser player, String toLowerCase, Trade charge) throws Exception; + + void respawn(Trade charge, TeleportCause teleportCause) throws Exception; + + void back() throws Exception; + + public void warp(String name, Trade charge, TeleportCause teleportCause) throws Exception; +} diff --git a/Essentials/src/net/ess3/api/IUser.java b/Essentials/src/net/ess3/api/IUser.java new file mode 100644 index 000000000..30d3fc4f8 --- /dev/null +++ b/Essentials/src/net/ess3/api/IUser.java @@ -0,0 +1,110 @@ +package net.ess3.api; + +import net.ess3.api.server.CommandSender; +import net.ess3.api.server.Player; +import net.ess3.api.server.ItemStack; +import net.ess3.api.server.Location; +import net.ess3.storage.IStorageObjectHolder; +import net.ess3.user.CooldownException; +import net.ess3.user.UserData; +import java.util.List; + + +public interface IUser extends Player, IStorageObjectHolder, IReload, IReplyTo, Comparable +{ + Player getBase(); + + double getMoney(); + + void takeMoney(double value); + + void takeMoney(double value, CommandSender initiator); + + void giveMoney(double value); + + void giveMoney(double value, CommandSender initiator); + + void giveItems(ItemStack itemStack, Boolean canSpew) throws ChargeException; + + void giveItems(List itemStacks, Boolean canSpew) throws ChargeException; + + void setMoney(double value); + + void payUser(final IUser reciever, final double value) throws Exception; + + void setLastLocation(); + + Location getHome(String name) throws Exception; + + Location getHome(Location loc); + + boolean isHidden(); + + ITeleport getTeleport(); + + void checkCooldown(UserData.TimestampType cooldownType, double cooldown, boolean set, IPermission bypassPermission) throws CooldownException; + + boolean toggleAfk(); + + void updateActivity(boolean broadcast); + + void updateDisplayName(); + + boolean checkJailTimeout(long currentTime); + + boolean checkMuteTimeout(long currentTime); + + boolean checkBanTimeout(long currentTime); + + long getTimestamp(UserData.TimestampType name); + + void setTimestamp(UserData.TimestampType name, long value); + + void setLastOnlineActivity(long currentTime); + + void checkActivity(); + + long getLastOnlineActivity(); + + boolean isGodModeEnabled(); + + boolean isIgnoringPlayer(String name); + + void setIgnoredPlayer(String name, boolean set); + + Location getAfkPosition(); + + boolean toggleGodModeEnabled(); + + void dispose(); + + void updateCompass(); + + List getHomes(); + + void addMail(String string); + + boolean toggleMuted(); + + boolean toggleSocialSpy(); + + void requestTeleport(IUser user, boolean b); + + boolean isTeleportRequestHere(); + + IUser getTeleportRequester(); + + boolean toggleTeleportEnabled(); + + long getTeleportRequestTime(); + + boolean gotMailInfo(); + + List getMails(); + + public boolean canAfford(double money); + + public void updateMoneyCache(double userMoney); + + public boolean canAfford(double amount, boolean b); +} diff --git a/Essentials/src/net/ess3/api/IUserMap.java b/Essentials/src/net/ess3/api/IUserMap.java new file mode 100644 index 000000000..887791f7b --- /dev/null +++ b/Essentials/src/net/ess3/api/IUserMap.java @@ -0,0 +1,28 @@ +package net.ess3.api; + +import net.ess3.api.server.Player; +import net.ess3.user.TooManyMatchesException; +import java.io.File; +import java.util.Set; + + +public interface IUserMap extends IReload +{ + boolean userExists(final String name); + + IUser getUser(final Player player); + + IUser getUser(final String playerName); + + void removeUser(final String name) throws InvalidNameException; + + Set getAllUniqueUsers(); + + int getUniqueUsers(); + + File getUserFile(final String name) throws InvalidNameException; + + IUser matchUser(final String name, final boolean includeHidden, final boolean onlineOnly) throws TooManyMatchesException; + + Set matchUsers(final String name, final boolean includeHidden, final boolean onlineOnly); +} diff --git a/Essentials/src/net/ess3/api/IWarp.java b/Essentials/src/net/ess3/api/IWarp.java new file mode 100644 index 000000000..149a9cfc6 --- /dev/null +++ b/Essentials/src/net/ess3/api/IWarp.java @@ -0,0 +1,9 @@ +package net.ess3.api; + +import net.ess3.settings.Warp; +import net.ess3.storage.IStorageObjectHolder; + + +public interface IWarp extends IStorageObjectHolder +{ +} diff --git a/Essentials/src/net/ess3/api/IWarps.java b/Essentials/src/net/ess3/api/IWarps.java new file mode 100644 index 000000000..00939ff7e --- /dev/null +++ b/Essentials/src/net/ess3/api/IWarps.java @@ -0,0 +1,21 @@ +package net.ess3.api; + +import net.ess3.api.server.Location; +import java.io.File; +import java.util.Collection; + + +public interface IWarps extends IReload +{ + Location getWarp(String warp) throws Exception; + + Collection getList(); + + void removeWarp(String name) throws Exception; + + void setWarp(String name, Location loc) throws Exception; + + public boolean isEmpty(); + + public File getWarpFile(String name) throws InvalidNameException; +} diff --git a/Essentials/src/net/ess3/api/IWorth.java b/Essentials/src/net/ess3/api/IWorth.java new file mode 100644 index 000000000..770170c31 --- /dev/null +++ b/Essentials/src/net/ess3/api/IWorth.java @@ -0,0 +1,12 @@ +package net.ess3.api; + +import net.ess3.api.server.ItemStack; + + + +public interface IWorth extends IReload +{ + double getPrice(ItemStack itemStack); + + void setPrice(ItemStack itemStack, double price); +} diff --git a/Essentials/src/net/ess3/api/InvalidNameException.java b/Essentials/src/net/ess3/api/InvalidNameException.java new file mode 100644 index 000000000..7d08d73ad --- /dev/null +++ b/Essentials/src/net/ess3/api/InvalidNameException.java @@ -0,0 +1,10 @@ +package net.ess3.api; + + +public class InvalidNameException extends Exception +{ + public InvalidNameException(Throwable thrwbl) + { + super(thrwbl); + } +} diff --git a/Essentials/src/net/ess3/api/NoLoanPermittedException.java b/Essentials/src/net/ess3/api/NoLoanPermittedException.java new file mode 100644 index 000000000..88a3ec6c7 --- /dev/null +++ b/Essentials/src/net/ess3/api/NoLoanPermittedException.java @@ -0,0 +1,12 @@ +package net.ess3.api; + +import static net.ess3.I18n._; + + +public class NoLoanPermittedException extends Exception +{ + public NoLoanPermittedException() + { + super(_("negativeBalanceError")); + } +} diff --git a/Essentials/src/net/ess3/api/UserDoesNotExistException.java b/Essentials/src/net/ess3/api/UserDoesNotExistException.java new file mode 100644 index 000000000..e18502dd1 --- /dev/null +++ b/Essentials/src/net/ess3/api/UserDoesNotExistException.java @@ -0,0 +1,12 @@ +package net.ess3.api; + +import static net.ess3.I18n._; + + +public class UserDoesNotExistException extends Exception +{ + public UserDoesNotExistException(String name) + { + super(_("userDoesNotExist", name)); + } +} diff --git a/Essentials/src/net/ess3/api/server/CommandSender.java b/Essentials/src/net/ess3/api/server/CommandSender.java new file mode 100644 index 000000000..768dde9bb --- /dev/null +++ b/Essentials/src/net/ess3/api/server/CommandSender.java @@ -0,0 +1,13 @@ +package net.ess3.api.server; + +public interface CommandSender { + boolean isPlayer(); + + void sendMessage(String message); + + boolean isOp(); + + boolean hasPermission(Permission bukkitPermission); + + void sendMessage(String[] string); +} diff --git a/Essentials/src/net/ess3/api/server/Enchantment.java b/Essentials/src/net/ess3/api/server/Enchantment.java new file mode 100644 index 000000000..3e7baa0cf --- /dev/null +++ b/Essentials/src/net/ess3/api/server/Enchantment.java @@ -0,0 +1,7 @@ +package net.ess3.api.server; + +public abstract class Enchantment { + + public abstract int getMaxLevel(); + +} diff --git a/Essentials/src/net/ess3/api/server/IInventory.java b/Essentials/src/net/ess3/api/server/IInventory.java new file mode 100644 index 000000000..783495864 --- /dev/null +++ b/Essentials/src/net/ess3/api/server/IInventory.java @@ -0,0 +1,19 @@ +package net.ess3.api.server; + +import java.util.Map; + +public interface IInventory { + + public boolean containsItem(boolean b, boolean b0, ItemStack itemStack); + + public Map addItem(ItemStack itemStack); + + public Map addItem(boolean b, ItemStack itemStack); + + public Map addItem(boolean b, int oversizedStacksize, ItemStack itemStack); + + public boolean addAllItems(boolean b, ItemStack itemStack); + + public void removeItem(boolean b, boolean b0, ItemStack itemStack); + +} diff --git a/Essentials/src/net/ess3/api/server/IPlugin.java b/Essentials/src/net/ess3/api/server/IPlugin.java new file mode 100644 index 000000000..d1f8719f1 --- /dev/null +++ b/Essentials/src/net/ess3/api/server/IPlugin.java @@ -0,0 +1,32 @@ +package net.ess3.api.server; + +import java.io.File; +import java.io.InputStream; + + +public interface IPlugin +{ + int scheduleAsyncDelayedTask(final Runnable run); + + int scheduleSyncDelayedTask(final Runnable run); + + int scheduleSyncDelayedTask(final Runnable run, final long delay); + + int scheduleSyncRepeatingTask(final Runnable run, final long delay, final long period); + + File getRootFolder(); + + File getDataFolder(); + + void cancelTask(int taskId); + + String getVersion(); + + Class getClassByName(String name); + + InputStream getResource(String string); + + Location callRespawnEvent(Player player, Location loc, boolean bedSpawn); + + void callSuicideEvent(Player player); +} diff --git a/Essentials/src/net/ess3/api/server/IServer.java b/Essentials/src/net/ess3/api/server/IServer.java new file mode 100644 index 000000000..8bd23bb9d --- /dev/null +++ b/Essentials/src/net/ess3/api/server/IServer.java @@ -0,0 +1,28 @@ +package net.ess3.api.server; + +import java.util.Collection; +import java.util.List; + + +public interface IServer +{ + List getWorlds(); + + World getWorld(String name); + + int broadcastMessage(String message); + + Collection getOnlinePlayers(); + + CommandSender getConsoleSender(); + + void dispatchCommand(CommandSender sender, String command); + + void banIP(String ip); + + T getServiceProvider(Class clazz); + + String getVersion(); + + public void unbanIP(String string); +} diff --git a/Essentials/src/net/ess3/api/server/ItemStack.java b/Essentials/src/net/ess3/api/server/ItemStack.java new file mode 100644 index 000000000..d8315974c --- /dev/null +++ b/Essentials/src/net/ess3/api/server/ItemStack.java @@ -0,0 +1,47 @@ +package net.ess3.api.server; + + +public abstract class ItemStack implements Cloneable +{ + public interface ItemStackFactory + { + ItemStack create(int id, int amount, int data); + ItemStack clone(ItemStack stack); + } + private static ItemStackFactory factory; + + public static void setFactory(final ItemStackFactory factory) + { + ItemStack.factory = factory; + } + + public static ItemStack create(int id, int amount, int data) + { + return factory.create(id, amount, data); + } + + public static ItemStack create(Material mat, int amount, int data) + { + return factory.create(mat.getId(), amount, data); + } + + public abstract Material getType(); + + public abstract int getAmount(); + + public abstract void setAmount(int value); + + public abstract short getDurability(); + + public abstract int getMaxStackSize(); + + public abstract boolean isAir(); + + public abstract void addEnchantment(Enchantment enchantment, int level); + + @Override + public ItemStack clone() + { + return factory.clone(this); + } +} diff --git a/Essentials/src/net/ess3/api/server/Location.java b/Essentials/src/net/ess3/api/server/Location.java new file mode 100644 index 000000000..825e2f814 --- /dev/null +++ b/Essentials/src/net/ess3/api/server/Location.java @@ -0,0 +1,52 @@ +package net.ess3.api.server; + + +public abstract class Location +{ + public interface LocationFactory { + Location create(String worldName, double x, double y, double z, double yaw, double pitch); + Location create(World world, double x, double y, double z, double yaw, double pitch); + } + private static LocationFactory factory; + + public static void setFactory(final LocationFactory factory) { + Location.factory = factory; + } + + public static Location create(String worldName, double x, double y, double z) { + return factory.create(worldName, x, y, z, 0, 0); + } + + public static Location create(String worldName, double x, double y, double z, double yaw, double pitch) { + return factory.create(worldName, x, y, z, yaw, pitch); + } + + public static Location create(World world, double x, double y, double z) { + return factory.create(world, x, y, z, 0, 0); + } + + public static Location create(World world, double x, double y, double z, double yaw, double pitch) { + return factory.create(world, x, y, z, yaw, pitch); + } + + + public abstract double getX(); + + public abstract double getY(); + + public abstract double getZ(); + + public abstract float getYaw(); + + public abstract float getPitch(); + + public abstract int getBlockX(); + + public abstract int getBlockY(); + + public abstract int getBlockZ(); + + public abstract World getWorld(); + + public abstract double distanceSquared(Location location); +} diff --git a/Essentials/src/net/ess3/api/server/Material.java b/Essentials/src/net/ess3/api/server/Material.java new file mode 100644 index 000000000..bfda30775 --- /dev/null +++ b/Essentials/src/net/ess3/api/server/Material.java @@ -0,0 +1,37 @@ +package net.ess3.api.server; + +public abstract class Material { + + private static Material instance; + + public static void setInstance(final Material instance) { + Material.instance = instance; + } + + public static Material get(final int id) { + return instance.getMaterialById(id); + } + + public static Material get(final String name) { + return instance.getMaterialByName(name); + } + + public static Material match(String string) + { + return instance.matchMaterial(string); + } + + protected abstract Material getMaterialByName(String name); + + protected abstract Material getMaterialById(int id); + + public abstract int getId(); + + public abstract String getName(); + + public abstract int getMaxStackSize(); + + public abstract int getMaxDurability(); + + protected abstract Material matchMaterial(String string); +} diff --git a/Essentials/src/net/ess3/api/server/Permission.java b/Essentials/src/net/ess3/api/server/Permission.java new file mode 100644 index 000000000..f4fb37cc4 --- /dev/null +++ b/Essentials/src/net/ess3/api/server/Permission.java @@ -0,0 +1,27 @@ +package net.ess3.api.server; + + +public abstract class Permission +{ + public enum Default + { + TRUE, FALSE, OP, NOT_OP; + } + + + public interface PermissionFactory + { + Permission create(String name, Permission.Default defaultPermission); + } + private static PermissionFactory factory; + + public static void setFactory(final PermissionFactory factory) + { + Permission.factory = factory; + } + + public static Permission create(final String name, Permission.Default defaultPermission) + { + return factory.create(name, defaultPermission); + } +} diff --git a/Essentials/src/net/ess3/api/server/Player.java b/Essentials/src/net/ess3/api/server/Player.java new file mode 100644 index 000000000..152c3f0c8 --- /dev/null +++ b/Essentials/src/net/ess3/api/server/Player.java @@ -0,0 +1,61 @@ +package net.ess3.api.server; + +import net.ess3.api.IUser; + + +public interface Player extends CommandSender +{ + IUser getUser(); + + String getName(); + + String getDisplayName(); + + boolean isOnline(); + + void setBanned(boolean bool); + + void kickPlayer(String reason); + + World getWorld(); + + Location getLocation(); + + Location getEyeLocation(); + + void setFireTicks(int value); + + void setFoodLevel(int value); + + void setSaturation(float value); + + int getHealth(); + + void setHealth(int value); + + void updateInventory(); + + ItemStack getItemInHand(); + + Location getBedSpawnLocation(); + + boolean hasPlayedBefore(); + + IInventory getInventory(); + + void setTotalExperience(final int exp); + + int getTotalExperience(); + + void setDisplayName(String name); + + void setPlayerListName(String name); + + void setSleepingIgnored(boolean b); + + boolean isBanned(); + + void setCompassTarget(Location loc); + + void damage(int value); +} diff --git a/Essentials/src/net/ess3/api/server/World.java b/Essentials/src/net/ess3/api/server/World.java new file mode 100644 index 000000000..ecd129609 --- /dev/null +++ b/Essentials/src/net/ess3/api/server/World.java @@ -0,0 +1,26 @@ +package net.ess3.api.server; + +import java.util.UUID; +import org.bukkit.TreeType; + +public interface World { + String getName(); + + boolean generateTree(Location safeLocation, TreeType tree); + + int getHighestBlockYAt(int topX, int topZ); + + ItemStack dropItem(Location loc, ItemStack stack); + + UUID getUID(); + + Location getSpawnLocation(); + + void dropItemNaturally(Location location, ItemStack overflowStack); + + void setStorm(boolean b); + + void setWeatherDuration(int i); + + long getTime(); +} diff --git a/Essentials/src/net/ess3/backup/Backup.java b/Essentials/src/net/ess3/backup/Backup.java new file mode 100644 index 000000000..3aea269e4 --- /dev/null +++ b/Essentials/src/net/ess3/backup/Backup.java @@ -0,0 +1,150 @@ +package net.ess3.backup; + +import static net.ess3.I18n._; +import net.ess3.api.IBackup; +import net.ess3.api.IEssentials; +import net.ess3.api.ISettings; +import net.ess3.api.server.CommandSender; +import net.ess3.api.server.IServer; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.logging.Level; +import lombok.Cleanup; + + +public class Backup implements Runnable, IBackup +{ + private transient final IServer server; + private transient final IEssentials ess; + private transient final AtomicBoolean running = new AtomicBoolean(false); + private transient int taskId = -1; + private transient final AtomicBoolean active = new AtomicBoolean(false); + + public Backup(final IEssentials ess) + { + this.ess = ess; + server = ess.getServer(); + if (!server.getOnlinePlayers().isEmpty()) + { + startTask(); + } + } + + @Override + public final void startTask() + { + if (running.compareAndSet(false, true)) + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + final long interval = settings.getData().getGeneral().getBackup().getInterval() * 1200; // minutes -> ticks + if (interval < 1200) + { + running.set(false); + return; + } + taskId = ess.getPlugin().scheduleSyncRepeatingTask(this, interval, interval); + } + } + + @Override + public void run() + { + if (!active.compareAndSet(false, true)) + { + return; + } + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + final String command = settings.getData().getGeneral().getBackup().getCommand(); + if (command == null || command.isEmpty()) + { + return; + } + ess.getLogger().log(Level.INFO, _("backupStarted")); + final CommandSender consoleSender = server.getConsoleSender(); + server.dispatchCommand(consoleSender, "save-all"); + server.dispatchCommand(consoleSender, "save-off"); + + ess.getPlugin().scheduleAsyncDelayedTask(new BackupRunner(command)); + } + + + private class BackupRunner implements Runnable + { + private final transient String command; + + public BackupRunner(final String command) + { + this.command = command; + } + + @Override + public void run() + { + try + { + final ProcessBuilder childBuilder = new ProcessBuilder(command); + childBuilder.redirectErrorStream(true); + childBuilder.directory(ess.getPlugin().getRootFolder()); + final Process child = childBuilder.start(); + final BufferedReader reader = new BufferedReader(new InputStreamReader(child.getInputStream())); + try + { + child.waitFor(); + String line; + do + { + line = reader.readLine(); + if (line != null) + { + ess.getLogger().log(Level.INFO, line); + } + } + while (line != null); + } + finally + { + reader.close(); + } + } + catch (InterruptedException ex) + { + ess.getLogger().log(Level.SEVERE, null, ex); + } + catch (IOException ex) + { + ess.getLogger().log(Level.SEVERE, null, ex); + } + finally + { + ess.getPlugin().scheduleSyncDelayedTask(new EnableSavingRunner()); + } + } + } + + + private class EnableSavingRunner implements Runnable + { + @Override + public void run() + { + server.dispatchCommand(server.getConsoleSender(), "save-on"); + if (server.getOnlinePlayers().isEmpty()) + { + running.set(false); + if (taskId != -1) + { + ess.getPlugin().cancelTask(taskId); + } + } + + active.set(false); + ess.getLogger().log(Level.INFO, _("backupFinished")); + } + } +} diff --git a/Essentials/src/net/ess3/bukkit/BukkitCommandSender.java b/Essentials/src/net/ess3/bukkit/BukkitCommandSender.java new file mode 100644 index 000000000..60302badc --- /dev/null +++ b/Essentials/src/net/ess3/bukkit/BukkitCommandSender.java @@ -0,0 +1,40 @@ +package net.ess3.bukkit; + +import net.ess3.api.server.CommandSender; +import net.ess3.api.server.Permission; +import lombok.Delegate; +import lombok.Getter; + + +public class BukkitCommandSender implements CommandSender +{ + @Delegate + @Getter + private org.bukkit.command.CommandSender commandSender; + + public BukkitCommandSender(org.bukkit.command.CommandSender commandSender) + { + this.commandSender = commandSender; + } + + @Override + public boolean isPlayer() + { + return false; + } + + @Override + public boolean isOp() + { + return commandSender.isOp(); + } + + public boolean hasPermission(Permission permission) + { + if (commandSender == null) { + return false; + } else { + return commandSender.hasPermission(((BukkitPermission)permission).getBukkitPermission()); + } + } +} diff --git a/Essentials/src/net/ess3/bukkit/BukkitItemStack.java b/Essentials/src/net/ess3/bukkit/BukkitItemStack.java new file mode 100644 index 000000000..819cc734b --- /dev/null +++ b/Essentials/src/net/ess3/bukkit/BukkitItemStack.java @@ -0,0 +1,62 @@ +package net.ess3.bukkit; + +import net.ess3.api.server.Enchantment; +import net.ess3.api.server.ItemStack; +import net.ess3.api.server.Material; +import lombok.Delegate; +import lombok.Getter; + + +public class BukkitItemStack extends net.ess3.api.server.ItemStack +{ + public static class BukkitItemStackFactory implements ItemStackFactory + { + @Override + public ItemStack create(int id, int amount, int data) + { + return new BukkitItemStack(new org.bukkit.inventory.ItemStack(id, amount, (short)data)); + } + + @Override + public ItemStack clone(final ItemStack stack) + { + return new BukkitItemStack(((BukkitItemStack)stack).getItemStack().clone()); + } + } + + + private interface Excludes + { + org.bukkit.Material getType(); + } + @Delegate(excludes = + { + Excludes.class + }) + @Getter + private final org.bukkit.inventory.ItemStack itemStack; + + public BukkitItemStack(final org.bukkit.inventory.ItemStack itemStack) + { + super(); + this.itemStack = itemStack; + } + + @Override + public void addEnchantment(Enchantment enchantment, int level) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Material getType() + { + return Material.get(itemStack.getTypeId()); + } + + @Override + public boolean isAir() + { + return itemStack.getTypeId() == 0; + } +} diff --git a/Essentials/src/net/ess3/bukkit/BukkitLocation.java b/Essentials/src/net/ess3/bukkit/BukkitLocation.java new file mode 100644 index 000000000..21021873c --- /dev/null +++ b/Essentials/src/net/ess3/bukkit/BukkitLocation.java @@ -0,0 +1,63 @@ +package net.ess3.bukkit; + +import net.ess3.api.server.World; +import net.ess3.api.server.Location; +import lombok.Delegate; +import lombok.Getter; + + +public class BukkitLocation extends Location +{ + public static class BukkitLocationFactory implements LocationFactory + { + private final org.bukkit.Server server; + + public BukkitLocationFactory(org.bukkit.Server server) + { + this.server = server; + } + + @Override + public Location create(String worldName, double x, double y, double z, double yaw, double pitch) + { + org.bukkit.World world = server.getWorld(worldName); + return new BukkitLocation(new org.bukkit.Location(world, x, y, z, (float)yaw, (float)pitch)); + } + + @Override + public Location create(World world, double x, double y, double z, double yaw, double pitch) + { + return new BukkitLocation(new org.bukkit.Location(((BukkitWorld)world).getBukkitWorld(), x, y, z, (float)yaw, (float)pitch)); + } + } + + + private interface Excludes + { + org.bukkit.World getWorld(); + } + @Delegate(excludes = + { + Excludes.class + }) + @Getter + private final org.bukkit.Location bukkitLocation; + + public BukkitLocation(org.bukkit.Location bukkitLocation) + { + this.bukkitLocation = bukkitLocation; + } + + @Override + public World getWorld() + { + return new BukkitWorld(bukkitLocation.getWorld()); + } + + @Override + public double distanceSquared(final Location location) + { + return bukkitLocation.distanceSquared(((BukkitLocation)location).getBukkitLocation()); + } + +} diff --git a/Essentials/src/net/ess3/bukkit/BukkitMaterial.java b/Essentials/src/net/ess3/bukkit/BukkitMaterial.java new file mode 100644 index 000000000..b01d68754 --- /dev/null +++ b/Essentials/src/net/ess3/bukkit/BukkitMaterial.java @@ -0,0 +1,62 @@ +package net.ess3.bukkit; + +import net.ess3.api.server.Material; +import java.util.EnumMap; +import lombok.Delegate; + + +public class BukkitMaterial extends Material +{ + private static EnumMap materials = new EnumMap(org.bukkit.Material.class); + + static + { + for (org.bukkit.Material material : org.bukkit.Material.values()) + { + materials.put(material, new BukkitMaterial(material)); + } + } + private interface Excludes { + short getMaxDurability(); + } + @Delegate(excludes={Excludes.class}) + private final org.bukkit.Material material; + + private BukkitMaterial(final org.bukkit.Material material) + { + this.material = material; + } + + @Override + protected Material getMaterialByName(final String name) + { + final org.bukkit.Material mat = org.bukkit.Material.getMaterial(name); + return materials.get(mat); + } + + @Override + protected Material getMaterialById(final int id) + { + final org.bukkit.Material mat = org.bukkit.Material.getMaterial(id); + return materials.get(mat); + } + + @Override + protected Material matchMaterial(String string) + { + final org.bukkit.Material mat = org.bukkit.Material.matchMaterial(string); + return materials.get(mat); + } + + @Override + public String getName() + { + return this.material.toString(); + } + + @Override + public int getMaxDurability() + { + return (short)this.material.getMaxDurability(); + } +} diff --git a/Essentials/src/net/ess3/bukkit/BukkitPermission.java b/Essentials/src/net/ess3/bukkit/BukkitPermission.java new file mode 100644 index 000000000..49f705ccc --- /dev/null +++ b/Essentials/src/net/ess3/bukkit/BukkitPermission.java @@ -0,0 +1,82 @@ +package net.ess3.bukkit; + +import net.ess3.api.server.Permission; +import java.util.regex.Pattern; +import lombok.Delegate; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.permissions.PermissionDefault; +import org.bukkit.plugin.PluginManager; + + +public class BukkitPermission extends Permission +{ + public static class BukkitPermissionFactory implements PermissionFactory + { + private static transient final Pattern DOT_PATTERN = Pattern.compile("\\."); + + @Override + public Permission create(String permission, Permission.Default defaultPerm) + { + final PluginManager pluginManager = Bukkit.getServer().getPluginManager(); + final String[] parts = DOT_PATTERN.split(permission); + final StringBuilder builder = new StringBuilder(permission.length()); + org.bukkit.permissions.Permission parent = null; + for (int i = 0; i < parts.length - 1; i++) + { + builder.append(parts[i]).append(".*"); + String permString = builder.toString(); + org.bukkit.permissions.Permission perm = pluginManager.getPermission(permString); + if (perm == null) + { + perm = new org.bukkit.permissions.Permission(permString, PermissionDefault.FALSE); + pluginManager.addPermission(perm); + if (parent != null) + { + parent.getChildren().put(perm.getName(), Boolean.TRUE); + } + parent = perm; + } + builder.deleteCharAt(builder.length() - 1); + } + org.bukkit.permissions.Permission perm = pluginManager.getPermission(permission); + if (perm == null) + { + perm = new org.bukkit.permissions.Permission(permission, getBukkitDefaultPermission(defaultPerm)); + pluginManager.addPermission(perm); + if (parent != null) + { + parent.getChildren().put(perm.getName(), Boolean.TRUE); + } + parent = perm; + } + perm.recalculatePermissibles(); + return new BukkitPermission(perm); + } + } + @Delegate + @Getter + private final org.bukkit.permissions.Permission bukkitPermission; + + public BukkitPermission(org.bukkit.permissions.Permission bukkitPermission) + { + this.bukkitPermission = bukkitPermission; + } + + public static PermissionDefault getBukkitDefaultPermission(final Permission.Default defaultPerm) + { + switch (defaultPerm) + { + case TRUE: + return PermissionDefault.TRUE; + case OP: + return PermissionDefault.OP; + case NOT_OP: + return PermissionDefault.NOT_OP; + case FALSE: + return PermissionDefault.FALSE; + default: + return PermissionDefault.FALSE; + } + } +} diff --git a/Essentials/src/net/ess3/bukkit/BukkitPlayer.java b/Essentials/src/net/ess3/bukkit/BukkitPlayer.java new file mode 100644 index 000000000..588ad242d --- /dev/null +++ b/Essentials/src/net/ess3/bukkit/BukkitPlayer.java @@ -0,0 +1,202 @@ +package net.ess3.bukkit; + +import net.ess3.api.IUser; +import net.ess3.api.server.*; +import lombok.Delegate; +import lombok.Getter; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.LivingEntity; + + +public class BukkitPlayer extends BukkitCommandSender implements Player +{ + private interface Excludes + { + org.bukkit.World getWorld(); + + org.bukkit.Location getLocation(); + + org.bukkit.Location getEyeLocation(); + + org.bukkit.inventory.ItemStack getItemInHand(); + + org.bukkit.Location getBedSpawnLocation(); + + org.bukkit.inventory.Inventory getInventory(); + + void setTotalExperience(int i); + + int getTotalExperience(); + } + @Delegate(types = + { + org.bukkit.entity.Player.class, LivingEntity.class + }, excludes = + { + OfflinePlayer.class, org.bukkit.command.CommandSender.class, Excludes.class + }) + @Getter + private transient org.bukkit.entity.Player onlinePlayer; + /** + * a set of data and methods common to both offline and online players. + */ + @Delegate(excludes = + { + Excludes.class + }) + @Getter + private transient OfflinePlayer safePlayer; + private final transient IServer server; + + public BukkitPlayer(final OfflinePlayer player, final IServer server) + { + super(player.getPlayer()); + this.server = server; + if (player.isOnline()) + { + + setOnlinePlayer(player.getPlayer()); + } + else + { + setOfflinePlayer(player); + } + } + + public final void setOfflinePlayer(final OfflinePlayer offlinePlayer) + { + safePlayer = offlinePlayer; + onlinePlayer = null; + } + + public final void setOnlinePlayer(final org.bukkit.entity.Player onlinePlayer) + { + safePlayer = this.onlinePlayer = onlinePlayer; + } + + public String getSafeDisplayName() + { + return onlinePlayer == null ? getName() : getDisplayName(); + } + + @Override + public IUser getUser() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isPlayer() + { + return true; + } + + @Override + public World getWorld() + { + return server.getWorld(onlinePlayer.getWorld().getName()); + } + + @Override + public Location getLocation() + { + return new BukkitLocation(onlinePlayer.getLocation()); + } + + @Override + public Location getEyeLocation() + { + return new BukkitLocation(onlinePlayer.getEyeLocation()); + } + + @Override + public BukkitItemStack getItemInHand() + { + return new BukkitItemStack(onlinePlayer.getItemInHand()); + } + + @Override + public Location getBedSpawnLocation() + { + return new BukkitLocation(onlinePlayer.getBedSpawnLocation()); + } + + @Override + public IInventory getInventory() + { + return new Inventory(onlinePlayer.getInventory()); + } + + @Override + public void setTotalExperience(final int exp) + { + if (exp < 0) + { + throw new IllegalArgumentException("Experience is negative!"); + } + onlinePlayer.setExp(0); + onlinePlayer.setLevel(0); + onlinePlayer.setTotalExperience(0); + int amount = exp; + while (amount > 0) + { + final int expToLevel = getExpToLevel(); + amount -= expToLevel; + if (amount >= 0) + { + // give until next level + onlinePlayer.giveExp(expToLevel); + } + else + { + // give the rest + amount += expToLevel; + onlinePlayer.giveExp(amount); + amount = 0; + } + } + } + + private int getExpToLevel() + { + return getExpToLevel(onlinePlayer.getLevel()); + } + + private static int getExpToLevel(final int level) + { + return 7 + (level * 7 >> 1); + } + + @Override + public int getTotalExperience() + { + int exp = (int) (getExpToLevel() * onlinePlayer.getExp()); + int currentLevel = onlinePlayer.getLevel(); + + while (currentLevel > 0) { + currentLevel--; + exp += getExpToLevel(currentLevel); + } + return exp; + } + + + @Override + public void sendMessage(final String message) + { + onlinePlayer.sendMessage(message); + } + + @Override + public void sendMessage(final String[] string) + { + onlinePlayer.sendMessage(string); + } + + + @Override + public void setCompassTarget(final Location loc) + { + onlinePlayer.setCompassTarget(((BukkitLocation)loc).getBukkitLocation()); + } +} diff --git a/Essentials/src/net/ess3/bukkit/BukkitWorld.java b/Essentials/src/net/ess3/bukkit/BukkitWorld.java new file mode 100644 index 000000000..d754de4c9 --- /dev/null +++ b/Essentials/src/net/ess3/bukkit/BukkitWorld.java @@ -0,0 +1,45 @@ +package net.ess3.bukkit; + +import net.ess3.api.server.World; +import net.ess3.api.server.ItemStack; +import net.ess3.api.server.Location; +import lombok.Delegate; +import lombok.Getter; +import org.bukkit.TreeType; + +public class BukkitWorld implements World { + @Delegate + @Getter + private final org.bukkit.World bukkitWorld; + + public BukkitWorld(final org.bukkit.World world) + { + this.bukkitWorld = world; + world.getT + } + + @Override + public boolean generateTree(Location safeLocation, TreeType tree) + { + return bukkitWorld.generateTree(((BukkitLocation)safeLocation).getBukkitLocation(), tree); + } + + @Override + public ItemStack dropItem(Location loc, ItemStack stack) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Location getSpawnLocation() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void dropItemNaturally(Location location, ItemStack overflowStack) + { + throw new UnsupportedOperationException("Not supported yet."); + } + +} diff --git a/Essentials/src/net/ess3/bukkit/Enchantments.java b/Essentials/src/net/ess3/bukkit/Enchantments.java new file mode 100644 index 000000000..f4890848f --- /dev/null +++ b/Essentials/src/net/ess3/bukkit/Enchantments.java @@ -0,0 +1,88 @@ +package net.ess3.bukkit; + +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.regex.Pattern; +import org.bukkit.enchantments.Enchantment; + + +public final class Enchantments +{ + + private Enchantments() + { + } + + private static final transient Pattern NUMPATTERN = Pattern.compile("\\d+"); + private static final Map ENCHANTMENTS = new HashMap(); + + static + { + ENCHANTMENTS.put("alldamage", Enchantment.DAMAGE_ALL); + ENCHANTMENTS.put("alldmg", Enchantment.DAMAGE_ALL); + ENCHANTMENTS.put("sharpness", Enchantment.DAMAGE_ALL); + ENCHANTMENTS.put("arthropodsdamage", Enchantment.DAMAGE_ARTHROPODS); + ENCHANTMENTS.put("ardmg", Enchantment.DAMAGE_ARTHROPODS); + ENCHANTMENTS.put("baneofarthropods", Enchantment.DAMAGE_ARTHROPODS); + ENCHANTMENTS.put("undeaddamage", Enchantment.DAMAGE_UNDEAD); + ENCHANTMENTS.put("smite", Enchantment.DAMAGE_UNDEAD); + ENCHANTMENTS.put("digspeed", Enchantment.DIG_SPEED); + ENCHANTMENTS.put("efficiency", Enchantment.DIG_SPEED); + ENCHANTMENTS.put("durability", Enchantment.DURABILITY); + ENCHANTMENTS.put("dura", Enchantment.DURABILITY); + ENCHANTMENTS.put("unbreaking", Enchantment.DURABILITY); + ENCHANTMENTS.put("fireaspect", Enchantment.FIRE_ASPECT); + ENCHANTMENTS.put("fire", Enchantment.FIRE_ASPECT); + ENCHANTMENTS.put("knockback", Enchantment.KNOCKBACK); + ENCHANTMENTS.put("blockslootbonus", Enchantment.LOOT_BONUS_BLOCKS); + ENCHANTMENTS.put("fortune", Enchantment.LOOT_BONUS_BLOCKS); + ENCHANTMENTS.put("mobslootbonus", Enchantment.LOOT_BONUS_MOBS); + ENCHANTMENTS.put("mobloot", Enchantment.LOOT_BONUS_MOBS); + ENCHANTMENTS.put("looting", Enchantment.LOOT_BONUS_MOBS); + ENCHANTMENTS.put("oxygen", Enchantment.OXYGEN); + ENCHANTMENTS.put("respiration", Enchantment.OXYGEN); + ENCHANTMENTS.put("protection", Enchantment.PROTECTION_ENVIRONMENTAL); + ENCHANTMENTS.put("prot", Enchantment.PROTECTION_ENVIRONMENTAL); + ENCHANTMENTS.put("explosionsprotection", Enchantment.PROTECTION_EXPLOSIONS); + ENCHANTMENTS.put("expprot", Enchantment.PROTECTION_EXPLOSIONS); + ENCHANTMENTS.put("blastprotection", Enchantment.PROTECTION_EXPLOSIONS); + ENCHANTMENTS.put("fallprotection", Enchantment.PROTECTION_FALL); + ENCHANTMENTS.put("fallprot", Enchantment.PROTECTION_FALL); + ENCHANTMENTS.put("featherfalling", Enchantment.PROTECTION_FALL); + ENCHANTMENTS.put("fireprotection", Enchantment.PROTECTION_FIRE); + ENCHANTMENTS.put("fireprot", Enchantment.PROTECTION_FIRE); + ENCHANTMENTS.put("projectileprotection", Enchantment.PROTECTION_PROJECTILE); + ENCHANTMENTS.put("projprot", Enchantment.PROTECTION_PROJECTILE); + ENCHANTMENTS.put("silktouch", Enchantment.SILK_TOUCH); + ENCHANTMENTS.put("waterworker", Enchantment.WATER_WORKER); + ENCHANTMENTS.put("aquaaffinity", Enchantment.WATER_WORKER); + ENCHANTMENTS.put("firearrow", Enchantment.ARROW_FIRE); + ENCHANTMENTS.put("arrowdamage", Enchantment.ARROW_DAMAGE); + ENCHANTMENTS.put("arrowknockback", Enchantment.ARROW_KNOCKBACK); + ENCHANTMENTS.put("arrowkb", Enchantment.ARROW_KNOCKBACK); + ENCHANTMENTS.put("infinitearrows", Enchantment.ARROW_INFINITE); + ENCHANTMENTS.put("infarrows", Enchantment.ARROW_INFINITE); + } + + public static Enchantment getByName(final String name) { + Enchantment enchantment; + if (NUMPATTERN.matcher(name).matches()) { + enchantment = Enchantment.getById(Integer.parseInt(name)); + } else { + enchantment = Enchantment.getByName(name.toUpperCase(Locale.ENGLISH)); + } + if (enchantment == null) + { + enchantment = ENCHANTMENTS.get(name.toLowerCase(Locale.ENGLISH)); + } + return enchantment; + } + + public static Set> entrySet() + { + return ENCHANTMENTS.entrySet(); + } +} diff --git a/Essentials/src/net/ess3/bukkit/EssentialsPlugin.java b/Essentials/src/net/ess3/bukkit/EssentialsPlugin.java new file mode 100644 index 000000000..4f262f329 --- /dev/null +++ b/Essentials/src/net/ess3/bukkit/EssentialsPlugin.java @@ -0,0 +1,95 @@ +package net.ess3.bukkit; + +import net.ess3.Essentials; +import static net.ess3.I18n._; +import net.ess3.api.server.*; +import java.util.logging.Level; +import org.bukkit.command.Command; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + + +public class EssentialsPlugin extends JavaPlugin +{ + private transient Essentials ess; + + public EssentialsPlugin() + { + Material.setInstance(BukkitMaterial.get(0)); + ItemStack.setFactory(new BukkitItemStack.BukkitItemStackFactory()); + Location.setFactory(new BukkitLocation.BukkitLocationFactory(getServer())); + Permission.setFactory(new BukkitPermission.BukkitPermissionFactory()); + } + + @Override + public void onEnable() + { + + Server server = new Server(getServer()); + final PluginManager pm = this.getServer().getPluginManager(); + pm.registerEvents(server, this); + ess = new Essentials(server, getLogger(), new Plugin(this)); + if (VersionCheck.checkVersion(this)) + { + try + { + ess.onEnable(); + } + catch (RuntimeException ex) + { + if (pm.getPlugin("EssentialsUpdate") == null) + { + getLogger().log(Level.SEVERE, _("essentialsHelp1")); + } + else + { + getLogger().log(Level.SEVERE, _("essentialsHelp2")); + } + getLogger().log(Level.SEVERE, ex.toString()); + pm.registerEvents(new Listener() + { + @EventHandler(priority = EventPriority.LOW) + public void onPlayerJoin(final PlayerJoinEvent event) + { + event.getPlayer().sendMessage("Essentials failed to load, read the log file."); + } + }, this); + for (Player player : getServer().getOnlinePlayers()) + { + player.sendMessage("Essentials failed to load, read the log file."); + } + this.setEnabled(false); + } + } + else + { + this.setEnabled(false); + } + } + + @Override + public void onDisable() + { + if (ess != null) + { + ess.onDisable(); + } + } + + @Override + public boolean onCommand(final org.bukkit.command.CommandSender sender, final Command command, final String label, final String[] args) + { + CommandSender commandSender; + if (sender instanceof org.bukkit.entity.Player) { + commandSender = ((Server)ess.getServer()).getPlayer((org.bukkit.entity.Player)sender); + } else { + commandSender = new BukkitCommandSender(sender); + } + return ess.getCommandHandler().handleCommand(commandSender, command, label, args); + } +} diff --git a/Essentials/src/net/ess3/bukkit/Inventory.java b/Essentials/src/net/ess3/bukkit/Inventory.java new file mode 100644 index 000000000..30ddaae52 --- /dev/null +++ b/Essentials/src/net/ess3/bukkit/Inventory.java @@ -0,0 +1,48 @@ +package net.ess3.bukkit; + +import net.ess3.api.server.IInventory; +import net.ess3.api.server.ItemStack; +import java.util.Map; +import lombok.Delegate; +import org.bukkit.inventory.PlayerInventory; + +public class Inventory implements IInventory { + @Delegate + private org.bukkit.inventory.PlayerInventory inventory; + + Inventory(PlayerInventory inventory) + { + this.inventory = inventory; + } + + @Override + public boolean containsItem(boolean b, boolean b0, ItemStack itemStack) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Map addItem(boolean b, ItemStack itemStack) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean addAllItems(boolean b, ItemStack itemStack) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void removeItem(boolean b, boolean b0, ItemStack itemStack) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Map addItem(boolean b, int oversizedStacksize, ItemStack itemStack) + { + throw new UnsupportedOperationException("Not supported yet."); + } + +} diff --git a/Essentials/src/net/ess3/bukkit/Mob.java b/Essentials/src/net/ess3/bukkit/Mob.java new file mode 100644 index 000000000..c618a1038 --- /dev/null +++ b/Essentials/src/net/ess3/bukkit/Mob.java @@ -0,0 +1,120 @@ +package net.ess3.bukkit; + +import static net.ess3.I18n._; +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 org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; + + +public enum Mob +{ + CHICKEN("Chicken", Enemies.FRIENDLY, EntityType.CHICKEN), + COW("Cow", Enemies.FRIENDLY, EntityType.COW), + CREEPER("Creeper", Enemies.ENEMY, EntityType.CREEPER), + GHAST("Ghast", Enemies.ENEMY, EntityType.GHAST), + GIANT("Giant", Enemies.ENEMY, EntityType.GIANT), + PIG("Pig", Enemies.FRIENDLY, EntityType.PIG), + PIGZOMB("PigZombie", Enemies.NEUTRAL, EntityType.PIG_ZOMBIE), + SHEEP("Sheep", Enemies.FRIENDLY, "", EntityType.SHEEP), + SKELETON("Skeleton", Enemies.ENEMY, EntityType.SKELETON), + SLIME("Slime", Enemies.ENEMY, EntityType.SLIME), + SPIDER("Spider", Enemies.ENEMY, EntityType.SPIDER), + SQUID("Squid", Enemies.FRIENDLY, EntityType.SQUID), + ZOMBIE("Zombie", Enemies.ENEMY, EntityType.ZOMBIE), + WOLF("Wolf", Enemies.NEUTRAL, EntityType.WOLF), + CAVESPIDER("CaveSpider", Enemies.ENEMY, EntityType.CAVE_SPIDER), + ENDERMAN("Enderman", Enemies.ENEMY, "", EntityType.ENDERMAN), + SILVERFISH("Silverfish", Enemies.ENEMY, "", EntityType.SILVERFISH), + ENDERDRAGON("EnderDragon", Enemies.ENEMY, EntityType.ENDER_DRAGON), + VILLAGER("Villager", Enemies.FRIENDLY, EntityType.VILLAGER), + BLAZE("Blaze", Enemies.ENEMY, EntityType.BLAZE), + MUSHROOMCOW("MushroomCow", Enemies.FRIENDLY, EntityType.MUSHROOM_COW), + MAGMACUBE("MagmaCube", Enemies.ENEMY, EntityType.MAGMA_CUBE), + SNOWMAN("Snowman", Enemies.FRIENDLY, "", EntityType.SNOWMAN), + OCELOT("Ocelot", Enemies.NEUTRAL, EntityType.OCELOT), + IRONGOLEM("IronGolem", Enemies.NEUTRAL, EntityType.IRON_GOLEM); + + public static final Logger logger = Logger.getLogger("Minecraft"); + + private Mob(String n, Enemies en, String s, EntityType type) + { + this.suffix = s; + this.name = n; + this.type = en; + this.bukkitType = type; + } + + private Mob(String n, Enemies en, EntityType type) + { + this.name = n; + this.type = en; + this.bukkitType = type; + } + public String suffix = "s"; + final public String name; + final public Enemies type; + final private EntityType bukkitType; + private static final Map hashMap = new HashMap(); + + static + { + for (Mob mob : Mob.values()) + { + hashMap.put(mob.name.toLowerCase(Locale.ENGLISH), mob); + } + } + + public static Set getMobList() { + return Collections.unmodifiableSet(hashMap.keySet()); + } + + public LivingEntity spawn(final Player player, final Server server, final Location loc) throws MobException + { + final LivingEntity entity = player.getWorld().spawn(loc, (Class)this.bukkitType.getEntityClass()); + if (entity == null) + { + logger.log(Level.WARNING, _("unableToSpawnMob")); + throw new MobException(); + } + return entity; + } + + + public enum Enemies + { + FRIENDLY("friendly"), + NEUTRAL("neutral"), + ENEMY("enemy"); + + private 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 class MobException extends Exception + { + private static final long serialVersionUID = 1L; + } +} diff --git a/Essentials/src/net/ess3/bukkit/Plugin.java b/Essentials/src/net/ess3/bukkit/Plugin.java new file mode 100644 index 000000000..ea3f85366 --- /dev/null +++ b/Essentials/src/net/ess3/bukkit/Plugin.java @@ -0,0 +1,87 @@ +package net.ess3.bukkit; + +import net.ess3.api.server.Player; +import net.ess3.api.server.IPlugin; +import net.ess3.api.server.Location; +import java.io.File; +import lombok.Delegate; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.plugin.java.JavaPluginLoader; + + +public class Plugin implements IPlugin +{ + @Delegate + private final org.bukkit.plugin.Plugin plugin; + + public Plugin(final org.bukkit.plugin.Plugin plugin) + { + this.plugin = plugin; + } + + @Override + public int scheduleAsyncDelayedTask(final Runnable run) + { + return plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, run); + } + + @Override + public int scheduleSyncDelayedTask(final Runnable run) + { + return plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, run); + } + + @Override + public int scheduleSyncDelayedTask(final Runnable run, final long delay) + { + return plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, run, delay); + } + + @Override + public int scheduleSyncRepeatingTask(final Runnable run, final long delay, final long period) + { + return plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, run, delay, period); + } + + @Override + public File getRootFolder() + { + return plugin.getDataFolder().getParentFile().getParentFile(); + } + + @Override + public void cancelTask(final int taskId) + { + plugin.getServer().getScheduler().cancelTask(taskId); + } + + @Override + public String getVersion() + { + return plugin.getDescription().getVersion(); + } + + @Override + public Class getClassByName(final String name) + { + final JavaPluginLoader jpl = (JavaPluginLoader)plugin.getPluginLoader(); + return jpl.getClassByName(name); + } + + @Override + public Location callRespawnEvent(Player player, Location loc, boolean bedSpawn) + { + final PlayerRespawnEvent pre = new PlayerRespawnEvent(((BukkitPlayer)player).getOnlinePlayer(), ((BukkitLocation)loc).getBukkitLocation() , bedSpawn); + getServer().getPluginManager().callEvent(pre); + return new BukkitLocation(pre.getRespawnLocation()); + } + + @Override + public void callSuicideEvent(Player player) + { + EntityDamageEvent ede = new EntityDamageEvent(((BukkitPlayer)player).getOnlinePlayer(), EntityDamageEvent.DamageCause.SUICIDE, 1000); + getServer().getPluginManager().callEvent(ede); + } + +} diff --git a/Essentials/src/net/ess3/bukkit/Server.java b/Essentials/src/net/ess3/bukkit/Server.java new file mode 100644 index 000000000..e59d7d4f9 --- /dev/null +++ b/Essentials/src/net/ess3/bukkit/Server.java @@ -0,0 +1,126 @@ +package net.ess3.bukkit; + +import net.ess3.api.IEssentials; +import net.ess3.api.server.CommandSender; +import net.ess3.api.server.Player; +import net.ess3.api.server.IServer; +import net.ess3.api.server.World; +import java.util.*; +import lombok.Delegate; +import lombok.Getter; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerLoginEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.world.WorldLoadEvent; +import org.bukkit.event.world.WorldUnloadEvent; +import org.bukkit.plugin.RegisteredServiceProvider; + + +public class Server implements IServer, Listener +{ + private IEssentials ess; + private interface Excludes + { + List getWorlds(); + + org.bukkit.World getWorld(String name); + + org.bukkit.entity.Player[] getOnlinePlayers(); + + BukkitCommandSender getConsoleSender(); + } + @Delegate(excludes = Excludes.class) + private final org.bukkit.Server server; + @Getter + private List worlds; + private Map worldsMap; + @Getter + private Collection onlinePlayers; + private Map onlinePlayersMap; + @Getter + private CommandSender consoleSender; + + public Server(final org.bukkit.Server server) + { + this.server = server; + consoleSender = new BukkitCommandSender(server.getConsoleSender()); + updateWorlds(); + } + + private void updateWorlds() + { + final ArrayList lworlds = new ArrayList(server.getWorlds().size()); + final HashMap lworldsMap = new HashMap(); + for (org.bukkit.World world : server.getWorlds()) + { + final BukkitWorld w = new BukkitWorld(world); + lworlds.add(w); + lworldsMap.put(world.getName(), w); + lworldsMap.put(world.getName().toLowerCase(Locale.ENGLISH), w); + } + this.worlds = Collections.unmodifiableList(lworlds); + this.worldsMap = Collections.unmodifiableMap(lworldsMap); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public synchronized void onWorldLoadEvent(final WorldLoadEvent event) + { + updateWorlds(); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public synchronized void onWorldUnloadEvent(final WorldUnloadEvent event) + { + updateWorlds(); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public synchronized void onPlayerLoginEvent(final PlayerLoginEvent event) + { + final HashMap oplayersMap = new HashMap(onlinePlayersMap); + BukkitPlayer p = new BukkitPlayer(event.getPlayer(), this); + oplayersMap.put(event.getPlayer(), p); + onlinePlayersMap = Collections.unmodifiableMap(oplayersMap); + onlinePlayers = Collections.unmodifiableCollection(oplayersMap.values()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public synchronized void onPlayerQuitEvent(final PlayerQuitEvent event) + { + final ArrayList oplayers = new ArrayList(onlinePlayers); + final HashMap oplayersMap = new HashMap(onlinePlayersMap); + oplayersMap.remove(event.getPlayer()); + onlinePlayersMap = Collections.unmodifiableMap(oplayersMap); + onlinePlayers = Collections.unmodifiableCollection(oplayersMap.values()); + } + + @Override + public World getWorld(final String name) + { + final World world = worldsMap.get(name); + if (world == null) + { + return worldsMap.get(name.toLowerCase(Locale.ENGLISH)); + } + return world; + } + + @Override + public void dispatchCommand(final CommandSender sender, final String command) + { + server.dispatchCommand(((BukkitCommandSender)sender).getCommandSender(), command); + } + + @Override + public T getServiceProvider(final Class clazz) + { + final RegisteredServiceProvider rsp = server.getServicesManager().getRegistration(clazz); + return rsp.getProvider(); + } + + public Player getPlayer(final org.bukkit.entity.Player player) { + return onlinePlayersMap.get(player); + } +} diff --git a/Essentials/src/net/ess3/bukkit/VersionCheck.java b/Essentials/src/net/ess3/bukkit/VersionCheck.java new file mode 100644 index 000000000..0413e15ba --- /dev/null +++ b/Essentials/src/net/ess3/bukkit/VersionCheck.java @@ -0,0 +1,46 @@ +package net.ess3.bukkit; + +import static net.ess3.I18n._; +import java.util.logging.Level; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.bukkit.plugin.PluginManager; + + +public class VersionCheck +{ + public static final int BUKKIT_VERSION = 2015; + private static final Pattern bukkitVersionPattern = Pattern.compile("git-Bukkit-(?:(?:[0-9]+)\\.)+[0-9]+-R[\\.0-9]+-(?:[0-9]+-g[0-9a-f]+-)?b([0-9]+)jnks.*"); + + public static boolean checkVersion(final org.bukkit.plugin.Plugin plugin) + { + final PluginManager pm = plugin.getServer().getPluginManager(); + final String pluginVersion = plugin.getDescription().getVersion(); + for (org.bukkit.plugin.Plugin p : pm.getPlugins()) + { + if (p.getDescription().getName().startsWith("Essentials") + && !p.getDescription().getVersion().equals(pluginVersion)) + { + p.getLogger().log(Level.WARNING, _("versionMismatch", p.getDescription().getName())); + } + } + final Matcher versionMatch = bukkitVersionPattern.matcher(plugin.getServer().getVersion()); + if (versionMatch.matches()) + { + final int versionNumber = Integer.parseInt(versionMatch.group(1)); + if (versionNumber < BUKKIT_VERSION && versionNumber > 100) + { + plugin.getLogger().log(Level.SEVERE, _("notRecommendedBukkit")); + plugin.getLogger().log(Level.SEVERE, _("requiredBukkit", Integer.toString(BUKKIT_VERSION))); + return false; + } + } + else + { + plugin.getLogger().log(Level.INFO, _("bukkitFormatChanged")); + plugin.getLogger().log(Level.INFO, plugin.getServer().getVersion()); + plugin.getLogger().log(Level.INFO, plugin.getServer().getBukkitVersion()); + } + return true; + } +} diff --git a/Essentials/src/net/ess3/commands/Commandafk.java b/Essentials/src/net/ess3/commands/Commandafk.java new file mode 100644 index 000000000..07b452917 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandafk.java @@ -0,0 +1,55 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import org.bukkit.entity.Player; +import org.bukkit.permissions.PermissionDefault; + + +public class Commandafk extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length > 0 && Permissions.AFK_OTHERS.isAuthorized(user)) + { + IUser afkUser = ess.getUser((Player)ess.getServer().matchPlayer(args[0])); + if (afkUser != null) + { + toggleAfk(afkUser); + } + } + else + { + toggleAfk(user); + } + } + + private void toggleAfk(IUser user) + { + if (!user.toggleAfk()) + { + //user.sendMessage(_("markedAsNotAway")); + if (!user.isHidden()) + { + ess.broadcastMessage(user, _("userIsNotAway", user.getDisplayName())); + } + user.updateActivity(false); + } + else + { + //user.sendMessage(_("markedAsAway")); + if (!user.isHidden()) + { + ess.broadcastMessage(user, _("userIsAway", user.getDisplayName())); + } + } + } + + @Override + public PermissionDefault getPermissionDefault() + { + return PermissionDefault.TRUE; + } +} diff --git a/Essentials/src/net/ess3/commands/Commandantioch.java b/Essentials/src/net/ess3/commands/Commandantioch.java new file mode 100644 index 000000000..818d1c97f --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandantioch.java @@ -0,0 +1,23 @@ +package net.ess3.commands; + +import net.ess3.api.IUser; +import net.ess3.utils.LocationUtil; +import org.bukkit.Location; +import org.bukkit.entity.TNTPrimed; + + +public class Commandantioch extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length > 0) + { + ess.broadcastMessage(user, "...lobbest thou thy Holy Hand Grenade of Antioch towards thy foe,"); + ess.broadcastMessage(user, "who being naughty in My sight, shall snuff it."); + } + + final Location loc = LocationUtil.getTarget(user); + loc.getWorld().spawn(loc, TNTPrimed.class); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandback.java b/Essentials/src/net/ess3/commands/Commandback.java new file mode 100644 index 000000000..58537fa11 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandback.java @@ -0,0 +1,19 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.economy.Trade; +import net.ess3.api.IUser; + + +public class Commandback extends EssentialsCommand +{ + @Override + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + final Trade charge = new Trade(commandName, ess); + charge.isAffordableFor(user); + user.sendMessage(_("backUsageMsg")); + user.getTeleport().back(charge); + throw new NoChargeException(); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandbackup.java b/Essentials/src/net/ess3/commands/Commandbackup.java new file mode 100644 index 000000000..38f57ee2c --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandbackup.java @@ -0,0 +1,16 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IBackup; + + +public class Commandbackup extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + final IBackup backup = ess.getBackup(); + backup.run(); + sender.sendMessage(_("backupStarted")); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandbalance.java b/Essentials/src/net/ess3/commands/Commandbalance.java new file mode 100644 index 000000000..d910dfda4 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandbalance.java @@ -0,0 +1,30 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.utils.Util; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; + + +public class Commandbalance extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + sender.sendMessage(_("balance", Util.displayCurrency(getPlayer(args, 0, true).getMoney(), ess))); + } + + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + final double bal = (args.length < 1 + || !Permissions.BALANCE_OTHERS.isAuthorized(user) + ? user + : getPlayer(args, 0, true)).getMoney(); + user.sendMessage(_("balance", Util.displayCurrency(bal, ess))); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandbalancetop.java b/Essentials/src/net/ess3/commands/Commandbalancetop.java new file mode 100644 index 000000000..e72ef955e --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandbalancetop.java @@ -0,0 +1,178 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.utils.Util; +import net.ess3.api.IUser; +import net.ess3.utils.textreader.ArrayListInput; +import net.ess3.utils.textreader.TextPager; +import java.text.DateFormat; +import java.util.*; +import java.util.Map.Entry; +import java.util.concurrent.locks.ReentrantReadWriteLock; + + +public class Commandbalancetop extends EssentialsCommand +{ + private static final int CACHETIME = 2 * 60 * 1000; + public static final int MINUSERS = 50; + private static ArrayListInput cache = new ArrayListInput(); + private static long cacheage = 0; + private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); + + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + int page = 0; + boolean force = false; + if (args.length > 0) + { + try + { + page = Integer.parseInt(args[0]); + } + catch (NumberFormatException ex) + { + if (args[0].equalsIgnoreCase("force") && sender.isOp()) + { + force = true; + } + } + } + + if (!force && lock.readLock().tryLock()) + { + try + { + if (cacheage > System.currentTimeMillis() - CACHETIME) + { + outputCache(sender, page); + return; + } + if (ess.getUserMap().getUniqueUsers() > MINUSERS) + { + sender.sendMessage(_("orderBalances", ess.getUserMap().getUniqueUsers())); + } + } + finally + { + lock.readLock().unlock(); + } + ess.getPlugin().scheduleAsyncDelayedTask(new Viewer(sender, page, force)); + } + else + { + if (ess.getUserMap().getUniqueUsers() > MINUSERS) + { + sender.sendMessage(_("orderBalances", ess.getUserMap().getUniqueUsers())); + } + ess.getPlugin().scheduleAsyncDelayedTask(new Viewer(sender, page, force)); + } + + } + + private static void outputCache(final CommandSender sender, int page) + { + final Calendar cal = Calendar.getInstance(); + cal.setTimeInMillis(cacheage); + final DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); + sender.sendMessage(_("balanceTop", format.format(cal.getTime()))); + new TextPager(cache).showPage(Integer.toString(page), "", "balancetop", sender); + } + + + private class Calculator implements Runnable + { + private final transient Viewer viewer; + private final boolean force; + + public Calculator(final Viewer viewer, final boolean force) + { + this.viewer = viewer; + this.force = force; + } + + @Override + public void run() + { + lock.writeLock().lock(); + try + { + if (force || cacheage <= System.currentTimeMillis() - CACHETIME) + { + cache.getLines().clear(); + final Map balances = new HashMap(); + double totalMoney = 0d; + for (String u : ess.getUserMap().getAllUniqueUsers()) + { + final IUser user = ess.getUserMap().getUser(u); + if (user != null) + { + final double userMoney = user.getMoney(); + user.updateMoneyCache(userMoney); + totalMoney += userMoney; + balances.put(user.getDisplayName(), userMoney); + } + } + + final List> sortedEntries = new ArrayList>(balances.entrySet()); + Collections.sort(sortedEntries, new Comparator>() + { + @Override + public int compare(final Entry entry1, final Entry entry2) + { + return -entry1.getValue().compareTo(entry2.getValue()); + } + }); + + cache.getLines().add(_("serverTotal", Util.displayCurrency(totalMoney, ess))); + int pos = 1; + for (Map.Entry entry : sortedEntries) + { + cache.getLines().add(pos + ". " + entry.getKey() + ", " + Util.displayCurrency(entry.getValue(), ess)); + pos++; + } + cacheage = System.currentTimeMillis(); + } + } + finally + { + lock.writeLock().unlock(); + } + ess.getPlugin().scheduleAsyncDelayedTask(viewer); + } + } + + + private class Viewer implements Runnable + { + private final transient CommandSender sender; + private final transient int page; + private final transient boolean force; + + public Viewer(final CommandSender sender, final int page, final boolean force) + { + this.sender = sender; + this.page = page; + this.force = force; + } + + @Override + public void run() + { + lock.readLock().lock(); + try + { + if (!force && cacheage > System.currentTimeMillis() - CACHETIME) + { + outputCache(sender, page); + return; + } + } + finally + { + lock.readLock().unlock(); + } + ess.getPlugin().scheduleAsyncDelayedTask(new Calculator(new Viewer(sender, page, force), force)); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandban.java b/Essentials/src/net/ess3/commands/Commandban.java new file mode 100644 index 000000000..6b6aee9ae --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandban.java @@ -0,0 +1,64 @@ +package net.ess3.commands; + +import net.ess3.Console; +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import net.ess3.user.Ban; +import lombok.Cleanup; + + +public class Commandban extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + @Cleanup + final IUser user = getPlayer(args, 0, true); + if (!user.isOnline()) + { + if (Permissions.BAN_EXEMPT.isAuthorized(user)) + { + sender.sendMessage(_("banExempt")); + return; + } + } + else + { + if (Permissions.BAN_OFFLINE.isAuthorized(sender)) + { + sender.sendMessage(_("banExempt")); + return; + } + } + + user.acquireWriteLock(); + String banReason; + user.getData().setBan(new Ban()); + if (args.length > 1) + { + banReason = getFinalArg(args, 1); + user.getData().getBan().setReason(banReason); + } + else + { + banReason = _("defaultBanReason"); + } + user.setBanned(true); + user.kickPlayer(banReason); + final String senderName = sender instanceof Player ? ((Player)sender).getDisplayName() : Console.NAME; + + for (IPlayer onlinePlayer : server.getOnlinePlayers()) + { + final IUser player = onlinePlayer.getUser(); + if (Permissions.BAN_NOTIFY.isAuthorized(player)) + { + onlinePlayer.sendMessage(_("playerBanned", senderName, user.getName(), banReason)); + } + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandbanip.java b/Essentials/src/net/ess3/commands/Commandbanip.java new file mode 100644 index 000000000..97f61167d --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandbanip.java @@ -0,0 +1,38 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import lombok.Cleanup; + + +public class Commandbanip extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + @Cleanup + final IUser player = ess.getUser(args[0]); + player.acquireReadLock(); + + if (player == null) + { + ess.getServer().banIP(args[0]); + sender.sendMessage(_("banIpAddress")); + } + else + { + final String ipAddress = player.getData().getIpAddress(); + if (ipAddress.length() == 0) + { + throw new Exception(_("playerNotFound")); + } + ess.getServer().banIP(player.getData().getIpAddress()); + sender.sendMessage(_("banIpAddress")); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandbigtree.java b/Essentials/src/net/ess3/commands/Commandbigtree.java new file mode 100644 index 000000000..645113eb3 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandbigtree.java @@ -0,0 +1,41 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.api.server.Location; +import net.ess3.utils.LocationUtil; +import org.bukkit.TreeType; + + +public class Commandbigtree extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + TreeType tree; + if (args.length > 0 && args[0].equalsIgnoreCase("redwood")) + { + tree = TreeType.TALL_REDWOOD; + } + else if (args.length > 0 && args[0].equalsIgnoreCase("tree")) + { + tree = TreeType.BIG_TREE; + } + else + { + throw new NotEnoughArgumentsException(); + } + + final Location loc = LocationUtil.getTarget(user); + final Location safeLocation = LocationUtil.getSafeDestination(loc); + final boolean success = user.getWorld().generateTree(safeLocation, tree); + if (success) + { + user.sendMessage(_("bigTreeSuccess")); + } + else + { + throw new Exception(_("bigTreeFailure")); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandbreak.java b/Essentials/src/net/ess3/commands/Commandbreak.java new file mode 100644 index 000000000..340cdea40 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandbreak.java @@ -0,0 +1,41 @@ +package net.ess3.commands; + +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import static net.ess3.I18n._; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.event.block.BlockBreakEvent; + + +public class Commandbreak extends EssentialsCommand +{ + //TODO: Switch to use util class + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + final Block block = user.getTargetBlock(null, 20); + if (block == null) + { + throw new NoChargeException(); + } + if (block.getType() == Material.AIR) + { + throw new NoChargeException(); + } + if (block.getType() == Material.BEDROCK && !Permissions.BREAK_BEDROCK.isAuthorized(user)) + { + throw new Exception(_("noBreakBedrock")); + } + final BlockBreakEvent event = new BlockBreakEvent(block, user.getBase()); + server.getPluginManager().callEvent(event); + if (event.isCancelled()) + { + throw new NoChargeException(); + } + else + { + block.setType(Material.AIR); + } + } +} \ No newline at end of file diff --git a/Essentials/src/net/ess3/commands/Commandbroadcast.java b/Essentials/src/net/ess3/commands/Commandbroadcast.java new file mode 100644 index 000000000..8490e8605 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandbroadcast.java @@ -0,0 +1,18 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; + + +public class Commandbroadcast extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + ess.broadcastMessage(null, _("broadcast", getFinalArg(args, 0))); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandburn.java b/Essentials/src/net/ess3/commands/Commandburn.java new file mode 100644 index 000000000..098538feb --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandburn.java @@ -0,0 +1,24 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.server.CommandSender; +import org.bukkit.entity.Player; + + +public class Commandburn extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 2) + { + throw new NotEnoughArgumentsException(); + } + + for (Player p : server.matchPlayer(args[0])) + { + p.setFireTicks(Integer.parseInt(args[1]) * 20); + sender.sendMessage(_("burnMsg", p.getDisplayName(), Integer.parseInt(args[1]))); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandclearinventory.java b/Essentials/src/net/ess3/commands/Commandclearinventory.java new file mode 100644 index 000000000..e5599a91f --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandclearinventory.java @@ -0,0 +1,93 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.api.server.CommandSender; +import net.ess3.permissions.Permissions; +import java.util.List; +import org.bukkit.entity.Player; + + +public class Commandclearinventory extends EssentialsCommand +{ + //TODO: Cleanup + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length > 0 && Permissions.CLEARINVENTORY_OTHERS.isAuthorized(user)) + { + //TODO: Fix fringe user match case. + if (args[0].length() >= 3) + { + List online = server.matchPlayer(args[0]); + + if (!online.isEmpty()) + { + for (Player p : online) + { + p.getInventory().clear(); + user.sendMessage(_("inventoryClearedOthers", p.getDisplayName())); + } + return; + } + throw new Exception(_("playerNotFound")); + } + else + { + Player p = server.getPlayer(args[0]); + if (p != null) + { + p.getInventory().clear(); + user.sendMessage(_("inventoryClearedOthers", p.getDisplayName())); + } + else + { + throw new Exception(_("playerNotFound")); + } + } + } + else + { + user.getInventory().clear(); + user.sendMessage(_("inventoryCleared")); + } + } + + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + if (args[0].length() >= 3) + { + List online = server.matchPlayer(args[0]); + + if (!online.isEmpty()) + { + for (Player p : online) + { + p.getInventory().clear(); + sender.sendMessage(_("inventoryClearedOthers", p.getDisplayName())); + } + return; + } + throw new Exception(_("playerNotFound")); + } + else + { + Player u = server.getPlayer(args[0]); + if (u != null) + { + u.getInventory().clear(); + sender.sendMessage(_("inventoryClearedOthers", u.getDisplayName())); + } + else + { + throw new Exception(_("playerNotFound")); + } + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandcompass.java b/Essentials/src/net/ess3/commands/Commandcompass.java new file mode 100644 index 000000000..8554c4608 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandcompass.java @@ -0,0 +1,52 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; + + +public class Commandcompass extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + final int bearing = (int)(user.getLocation().getYaw() + 180 + 360) % 360; + String dir; + if (bearing < 23) + { + dir = "N"; + } + else if (bearing < 68) + { + dir = "NE"; + } + else if (bearing < 113) + { + dir = "E"; + } + else if (bearing < 158) + { + dir = "SE"; + } + else if (bearing < 203) + { + dir = "S"; + } + else if (bearing < 248) + { + dir = "SW"; + } + else if (bearing < 293) + { + dir = "W"; + } + else if (bearing < 338) + { + dir = "NW"; + } + else + { + dir = "N"; + } + user.sendMessage(_("compassBearing", dir, bearing)); + } +} diff --git a/Essentials/src/net/ess3/commands/Commanddelhome.java b/Essentials/src/net/ess3/commands/Commanddelhome.java new file mode 100644 index 000000000..7b0e85c50 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commanddelhome.java @@ -0,0 +1,58 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import java.util.Locale; +import lombok.Cleanup; +import org.bukkit.entity.Player; + + +public class Commanddelhome extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + @Cleanup + IUser user = sender instanceof Player ? ess.getUser((Player)sender) : null; + String name; + String[] expandedArg; + + //Allowing both formats /sethome khobbits house | /sethome khobbits:house + final String[] nameParts = args[0].split(":"); + if (nameParts[0].length() != args[0].length()) + { + expandedArg = nameParts; + } + else + { + expandedArg = args; + } + + if (expandedArg.length > 1 && (user == null || Permissions.DELHOME_OTHERS.isAuthorized(user))) + { + user = getPlayer(expandedArg, 0, true); + name = expandedArg[1]; + } + else if (user == null) + { + throw new NotEnoughArgumentsException(); + } + else + { + name = expandedArg[0]; + } + //TODO: Think up a nice error message + /* + * if (name.equalsIgnoreCase("bed")) { throw new Exception("You cannot remove the vanilla home point"); } + */ + user.acquireWriteLock(); + user.getData().removeHome(name.toLowerCase(Locale.ENGLISH)); + sender.sendMessage(_("deleteHome", name)); + } +} diff --git a/Essentials/src/net/ess3/commands/Commanddeljail.java b/Essentials/src/net/ess3/commands/Commanddeljail.java new file mode 100644 index 000000000..f8fdc8594 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commanddeljail.java @@ -0,0 +1,18 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; + + +public class Commanddeljail extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + ess.getJails().removeJail(args[0]); + sender.sendMessage(_("deleteJail", args[0])); + } +} diff --git a/Essentials/src/net/ess3/commands/Commanddelwarp.java b/Essentials/src/net/ess3/commands/Commanddelwarp.java new file mode 100644 index 000000000..9e3ec97fb --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commanddelwarp.java @@ -0,0 +1,18 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; + + +public class Commanddelwarp extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + ess.getWarps().removeWarp(args[0]); + sender.sendMessage(_("deleteWarp", args[0])); + } +} diff --git a/Essentials/src/net/ess3/commands/Commanddepth.java b/Essentials/src/net/ess3/commands/Commanddepth.java new file mode 100644 index 000000000..31f621767 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commanddepth.java @@ -0,0 +1,26 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; + + +public class Commanddepth extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + final int depth = user.getLocation().getBlockY() - 63; + if (depth > 0) + { + user.sendMessage(_("depthAboveSea", depth)); + } + else if (depth < 0) + { + user.sendMessage(_("depthBelowSea", (-depth))); + } + else + { + user.sendMessage(_("depth")); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandeco.java b/Essentials/src/net/ess3/commands/Commandeco.java new file mode 100644 index 000000000..a5a9fbce0 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandeco.java @@ -0,0 +1,118 @@ +package net.ess3.commands; + +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import static net.ess3.I18n._; + +import java.util.Locale; +import lombok.Cleanup; + + +public class Commandeco extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 2) + { + throw new NotEnoughArgumentsException(); + } + EcoCommands cmd; + double amount; + try + { + cmd = EcoCommands.valueOf(args[0].toUpperCase(Locale.ENGLISH)); + amount = Double.parseDouble(args[2].replaceAll("[^0-9\\.]", "")); + } + catch (Exception ex) + { + throw new NotEnoughArgumentsException(ex); + } + + if (args[1].contentEquals("**")) + { + for (String sUser : ess.getUserMap().getAllUniqueUsers()) + { + final IUser player = ess.getUser(sUser); + switch (cmd) + { + case GIVE: + player.giveMoney(amount); + break; + + case TAKE: + if (player.canAfford(amount, false)) + { + player.takeMoney(amount); + } + break; + + case RESET: + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + player.setMoney(amount == 0 ? settings.getData().getEconomy().getStartingBalance() : amount); + break; + } + } + } + else if (args[1].contentEquals("*")) + { + for (Player onlinePlayer : server.getOnlinePlayers()) + { + final IUser player = onlinePlayer.getUser(); + switch (cmd) + { + case GIVE: + player.giveMoney(amount); + break; + + case TAKE: + if (!player.canAfford(amount, false)) + { + throw new Exception(_("notEnoughMoney")); + } + player.takeMoney(amount); + break; + + case RESET: + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + player.setMoney(amount == 0 ? settings.getData().getEconomy().getStartingBalance() : amount); + break; + } + } + } + else + { + final IUser player = getPlayer(args, 1, true); + switch (cmd) + { + case GIVE: + player.giveMoney(amount, sender); + break; + + case TAKE: + if (!player.canAfford(amount, false)) + { + throw new Exception(_("notEnoughMoney")); + } + player.takeMoney(amount, sender); + break; + + case RESET: + @Cleanup ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + player.setMoney(amount == 0 ? settings.getData().getEconomy().getStartingBalance() : amount); + break; + } + } + } + + + private enum EcoCommands + { + GIVE, TAKE, RESET + } +} diff --git a/Essentials/src/net/ess3/commands/Commandenchant.java b/Essentials/src/net/ess3/commands/Commandenchant.java new file mode 100644 index 000000000..7e38d13fc --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandenchant.java @@ -0,0 +1,94 @@ +package net.ess3.commands; + +import net.ess3.bukkit.Enchantments; +import static net.ess3.I18n._; +import net.ess3.utils.Util; +import net.ess3.api.IUser; +import net.ess3.permissions.EnchantPermissions; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; + + +public class Commandenchant extends EssentialsCommand +{ + //TODO: Implement charge costs: final Trade charge = new Trade("enchant-" + enchantmentName, ess); + @Override + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + final ItemStack stack = user.getItemInHand(); + if (stack == null) + { + throw new Exception(_("nothingInHand")); + } + if (args.length == 0) + { + final Set enchantmentslist = new TreeSet(); + for (Map.Entry entry : Enchantments.entrySet()) + { + final String enchantmentName = entry.getValue().getName().toLowerCase(Locale.ENGLISH); + if (enchantmentslist.contains(enchantmentName) || EnchantPermissions.getPermission(enchantmentName).isAuthorized(user)) + { + enchantmentslist.add(entry.getKey()); + //enchantmentslist.add(enchantmentName); + } + } + throw new NotEnoughArgumentsException(_("enchantments", Util.joinList(enchantmentslist.toArray()))); + } + int level = -1; + if (args.length > 1) + { + try + { + level = Integer.parseInt(args[1]); + } + catch (NumberFormatException ex) + { + level = -1; + } + } + final Enchantment enchantment = getEnchantment(args[0], user); + if (level < 0 || level > enchantment.getMaxLevel()) + { + level = enchantment.getMaxLevel(); + } + if (level == 0) + { + stack.removeEnchantment(enchantment); + } + else + { + stack.addEnchantment(enchantment, level); + } + user.getInventory().setItemInHand(stack); + user.updateInventory(); + final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH); + if (level == 0) + { + user.sendMessage(_("enchantmentRemoved", enchantmentName.replace('_', ' '))); + } + else + { + user.sendMessage(_("enchantmentApplied", enchantmentName.replace('_', ' '))); + } + } + + public static Enchantment getEnchantment(final String name, final IUser user) throws Exception + { + + final Enchantment enchantment = Enchantments.getByName(name); + if (enchantment == null) + { + throw new Exception(_("enchantmentNotFound")); + } + final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH); + if (user != null && !EnchantPermissions.getPermission(enchantmentName).isAuthorized(user)) + { + throw new Exception(_("enchantmentPerm", enchantmentName)); + } + return enchantment; + } +} diff --git a/Essentials/src/net/ess3/commands/Commandessentials.java b/Essentials/src/net/ess3/commands/Commandessentials.java new file mode 100644 index 000000000..44cf8536c --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandessentials.java @@ -0,0 +1,170 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; + +import net.ess3.api.server.Player; +import java.util.HashMap; +import java.util.Map; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; + + +public class Commandessentials extends EssentialsCommand +{ + private transient int taskid; + private final transient Map noteBlocks = new HashMap(); + + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length == 0) + { + run_disabled(sender, args); + } + else if (args[0].equalsIgnoreCase("debug")) + { + run_debug(sender, args); + } + else if (args[0].equalsIgnoreCase("nya")) + { + run_nya(sender, args); + } + else if (args[0].equalsIgnoreCase("moo")) + { + run_moo(sender, args); + } + else + { + run_reload(sender, args); + } + } + + private void run_disabled(final CommandSender sender, final String[] args) throws Exception + { + sender.sendMessage("Essentials " + ess.getPlugin().getVersion()); + sender.sendMessage("/ "); + sender.sendMessage(_("blockList")); + final StringBuilder disabledCommands = new StringBuilder(); + for (Map.Entry entry : ess.getCommandHandler().disabledCommands().entrySet()) + { + if (disabledCommands.length() > 0) + { + disabledCommands.append(", "); + } + disabledCommands.append(entry.getKey()).append(" => ").append(entry.getValue()); + } + sender.sendMessage(disabledCommands.toString()); + } + + private void run_debug(final CommandSender sender, final String[] args) throws Exception + { + ess.getSettings().setDebug(!ess.getSettings().isDebug()); + sender.sendMessage("Essentials " + ess.getPlugin().getVersion() + " debug mode " + (ess.getSettings().isDebug() ? "enabled" : "disabled")); + } + + private void run_reload(final CommandSender sender, final String[] args) throws Exception + { + ess.reload(); + sender.sendMessage(_("essentialsReload", ess.getPlugin().getVersion())); + } + + private void run_nya(final CommandSender sender, final String[] args) throws Exception + { + final Map noteMap = new HashMap(); + noteMap.put("1F#", (byte)0x0); + noteMap.put("1G", (byte)0x1); + noteMap.put("1G#", (byte)0x2); + noteMap.put("1A", (byte)0x3); + noteMap.put("1A#", (byte)0x4); + noteMap.put("1B", (byte)0x5); + noteMap.put("1C", (byte)0x6); + noteMap.put("1C#", (byte)0x7); + noteMap.put("1D", (byte)0x8); + noteMap.put("1D#", (byte)0x9); + noteMap.put("1E", (byte)0xA); + noteMap.put("1F", (byte)0xB); + noteMap.put("2F#", (byte)(0x0 + 0xC)); + noteMap.put("2G", (byte)(0x1 + 0xC)); + noteMap.put("2G#", (byte)(0x2 + 0xC)); + noteMap.put("2A", (byte)(0x3 + 0xC)); + noteMap.put("2A#", (byte)(0x4 + 0xC)); + noteMap.put("2B", (byte)(0x5 + 0xC)); + noteMap.put("2C", (byte)(0x6 + 0xC)); + noteMap.put("2C#", (byte)(0x7 + 0xC)); + noteMap.put("2D", (byte)(0x8 + 0xC)); + noteMap.put("2D#", (byte)(0x9 + 0xC)); + noteMap.put("2E", (byte)(0xA + 0xC)); + noteMap.put("2F", (byte)(0xB + 0xC)); + if (!noteBlocks.isEmpty()) + { + return; + } + final String tuneStr = "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,,"; + final String[] tune = tuneStr.split(","); + for (Player player : server.getOnlinePlayers()) + { + final Location loc = player.getLocation(); + loc.add(0, 3, 0); + while (loc.getBlockY() < player.getLocation().getBlockY() + 10 && loc.getBlock().getTypeId() != 0) + { + loc.add(0, 1, 0); + } + if (loc.getBlock().getTypeId() == 0) + { + noteBlocks.put(player, loc.getBlock()); + player.sendBlockChange(loc, Material.NOTE_BLOCK, (byte)0); + } + } + taskid = ess.getPlugin().scheduleSyncRepeatingTask(new Runnable() + { + int i = 0; + + @Override + public void run() + { + final String note = tune[i]; + i++; + if (i >= tune.length) + { + Commandessentials.this.stopTune(); + } + if (note.isEmpty()) + { + return; + } + Map noteBlocks = Commandessentials.this.noteBlocks; + for (Player onlinePlayer : server.getOnlinePlayers()) + { + final Block block = noteBlocks.get(onlinePlayer); + if (block == null || block.getType() != Material.NOTE_BLOCK) + { + continue; + } + onlinePlayer.playNote(block.getLocation(), (byte)0, noteMap.get(note)); + } + } + }, 20, 2); + } + + private void stopTune() + { + ess.getPlugin().cancelTask(taskid); + for (Block block : noteBlocks.values()) + { + if (block.getType() == Material.NOTE_BLOCK) + { + block.setType(Material.AIR); + } + } + noteBlocks.clear(); + } + + private void run_moo(final CommandSender sender, final String args[]) + { + if(sender == ess.getServer().getConsoleSender()) + sender.sendMessage(new String[]{" (__)", " (oo)", " /------\\/", " / | ||", " * /\\---/\\", " ~~ ~~", "....\"Have you mooed today?\"..." } ); + else + sender.sendMessage(new String[]{" (__)", " (oo)", " /------\\/", " / | | |", " * /\\---/\\", " ~~ ~~", "....\"Have you mooed today?\"..." } ); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandext.java b/Essentials/src/net/ess3/commands/Commandext.java new file mode 100644 index 000000000..1f7c1a51b --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandext.java @@ -0,0 +1,43 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.api.server.CommandSender; +import org.bukkit.entity.Player; + + +public class Commandext extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + extinguishPlayers(sender, args[0]); + } + + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + user.setFireTicks(0); + user.sendMessage(_("extinguish")); + return; + } + + extinguishPlayers(user, args[0]); + } + + private void extinguishPlayers(final CommandSender sender, final String name) throws Exception + { + for (Player matchPlayer : server.matchPlayer(name)) + { + matchPlayer.setFireTicks(0); + sender.sendMessage(_("extinguishOthers", matchPlayer.getDisplayName())); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandfeed.java b/Essentials/src/net/ess3/commands/Commandfeed.java new file mode 100644 index 000000000..21e47682f --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandfeed.java @@ -0,0 +1,46 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import java.util.List; +import org.bukkit.entity.Player; + + +public class Commandfeed extends EssentialsCommand +{ + @Override + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length > 0 && Permissions.FEED_OTHERS.isAuthorized(user)) + { + feedOtherPlayers(user, args[0]); + } + else + { + user.setFoodLevel(20); + user.setSaturation(10); + user.sendMessage(_("feed")); + } + } + + private void feedOtherPlayers(final ICommandSender sender, final String name) + { + final List players = server.matchPlayer(name); + if (players.isEmpty()) + { + sender.sendMessage(_("playerNotFound")); + return; + } + for (Player player : players) + { + if (ess.getUser(player).isHidden()) + { + continue; + } + player.setFoodLevel(20); + player.setSaturation(10); + sender.sendMessage(_("feedOther", player.getDisplayName())); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandfireball.java b/Essentials/src/net/ess3/commands/Commandfireball.java new file mode 100644 index 000000000..8882f0106 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandfireball.java @@ -0,0 +1,23 @@ +package net.ess3.commands; + +import net.ess3.api.IUser; +import org.bukkit.entity.Fireball; +import org.bukkit.entity.SmallFireball; +import org.bukkit.util.Vector; + + +public class Commandfireball extends EssentialsCommand +{ + @Override + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + boolean small = false; + if (args.length > 0 && args[0].equalsIgnoreCase("small")) + { + small = true; + } + final Vector direction = user.getEyeLocation().getDirection().multiply(2); + final Fireball fireball = user.getWorld().spawn(user.getEyeLocation().add(direction.getX(), direction.getY(), direction.getZ()), small ? SmallFireball.class : Fireball.class); + fireball.setShooter(user.getBase()); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandgamemode.java b/Essentials/src/net/ess3/commands/Commandgamemode.java new file mode 100644 index 000000000..3a708d0cf --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandgamemode.java @@ -0,0 +1,51 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import java.util.Locale; +import org.bukkit.GameMode; +import org.bukkit.entity.Player; + + +public class Commandgamemode extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + gamemodeOtherPlayers(sender, args[0]); + } + + @Override + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length > 0 && !args[0].trim().isEmpty() && Permissions.GAMEMODE_OTHERS.isAuthorized(user)) + { + gamemodeOtherPlayers(user, args[0]); + return; + } + + user.setGameMode(user.getGameMode() == GameMode.SURVIVAL ? GameMode.CREATIVE : GameMode.SURVIVAL); + user.sendMessage(_("gameMode", _(user.getGameMode().toString().toLowerCase(Locale.ENGLISH)), user.getDisplayName())); + } + + private void gamemodeOtherPlayers(final CommandSender sender, final String name) + { + for (Player matchPlayer : server.matchPlayer(name)) + { + final IUser player = ess.getUser(matchPlayer); + if (player.isHidden()) + { + continue; + } + + player.setGameMode(player.getGameMode() == GameMode.SURVIVAL ? GameMode.CREATIVE : GameMode.SURVIVAL); + sender.sendMessage(_("gameMode", _(player.getGameMode().toString().toLowerCase(Locale.ENGLISH)), player.getDisplayName())); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandgc.java b/Essentials/src/net/ess3/commands/Commandgc.java new file mode 100644 index 000000000..a440d0474 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandgc.java @@ -0,0 +1,23 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; + + +public class Commandgc extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + sender.sendMessage(_("gcmax", (Runtime.getRuntime().maxMemory() / 1024 / 1024))); + sender.sendMessage(_("gctotal", (Runtime.getRuntime().totalMemory() / 1024 / 1024))); + sender.sendMessage(_("gcfree", (Runtime.getRuntime().freeMemory() / 1024 / 1024))); + + for (World w : server.getWorlds()) + { + sender.sendMessage( + (w.getEnvironment() == World.Environment.NETHER ? "Nether" : "World") + " \"" + w.getName() + "\": " + + w.getLoadedChunks().length + _("gcchunks") + + w.getEntities().size() + _("gcentities")); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandgetpos.java b/Essentials/src/net/ess3/commands/Commandgetpos.java new file mode 100644 index 000000000..202b7b2b4 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandgetpos.java @@ -0,0 +1,49 @@ +package net.ess3.commands; + +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import org.bukkit.Location; + + +public class Commandgetpos extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length > 0 && Permissions.GETPOS_OTHERS.isAuthorized(user)) + { + final IUser otherUser = getPlayer(args, 0); + outputPosition(user, otherUser.getLocation(), user.getLocation()); + } + else + { + outputPosition(user, user.getLocation(), null); + } + } + + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + final IUser user = getPlayer(args, 0); + outputPosition(sender, user.getLocation(), null); + } + + //TODO: Translate + private void outputPosition(final CommandSender sender, final Location coords, final Location distance) + { + sender.sendMessage("§7World: " + coords.getWorld().getName()); + sender.sendMessage("§7X: " + coords.getBlockX() + " (+East <-> -West)"); + sender.sendMessage("§7Y: " + coords.getBlockY() + " (+Up <-> -Down)"); + sender.sendMessage("§7Z: " + coords.getBlockZ() + " (+South <-> -North)"); + sender.sendMessage("§7Yaw: " + (coords.getYaw() + 180 + 360) % 360 + " (Rotation)"); + sender.sendMessage("§7Pitch: " + coords.getPitch() + " (Head angle)"); + if (distance != null && coords.getWorld().equals(distance.getWorld())) + { + sender.sendMessage("§7Distance: " + coords.distance(distance)); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandgive.java b/Essentials/src/net/ess3/commands/Commandgive.java new file mode 100644 index 000000000..b42323d4a --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandgive.java @@ -0,0 +1,75 @@ +package net.ess3.commands; + +import net.ess3.api.IUser; +import net.ess3.permissions.GivePermissions; +import static net.ess3.I18n._; + +import java.util.Locale; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + + +public class Commandgive extends EssentialsCommand +{ + //TODO: move these messages to message file + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 2) + { + throw new NotEnoughArgumentsException(); + } + + final IUser giveTo = getPlayer(args, 0); + + final ItemStack stack = ess.getItemDb().get(args[1], giveTo); + + final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); + if (!GivePermissions.getPermission(stack.getType()).isAuthorized(sender)) + { + throw new Exception(_("cantSpawnItem", itemname)); + } + + if (args.length > 2 && Integer.parseInt(args[2]) > 0) + { + stack.setAmount(Integer.parseInt(args[2])); + } + + if (args.length > 3) + { + for (int i = 3; i < args.length; i++) + { + final String[] split = args[i].split("[:+',;.]", 2); + if (split.length < 1) + { + continue; + } + final Enchantment enchantment = Commandenchant.getEnchantment(split[0], sender instanceof Player ? ess.getUser((Player)sender) : null); + int level; + if (split.length > 1) + { + level = Integer.parseInt(split[1]); + } + else + { + level = enchantment.getMaxLevel(); + } + stack.addEnchantment(enchantment, level); + } + } + + if (stack.getType() == Material.AIR) + { + throw new Exception(_("cantSpawnItem", "Air")); + } + + giveTo.giveItems(stack, false); + + final String itemName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' '); + sender.sendMessage(ChatColor.BLUE + "Giving " + stack.getAmount() + " of " + itemName + " to " + giveTo.getDisplayName() + "."); + + } +} diff --git a/Essentials/src/net/ess3/commands/Commandgod.java b/Essentials/src/net/ess3/commands/Commandgod.java new file mode 100644 index 000000000..f2f3164da --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandgod.java @@ -0,0 +1,48 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import org.bukkit.entity.Player; + + +public class Commandgod extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + godOtherPlayers(sender, args[0]); + } + + @Override + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length > 0 && !args[0].trim().isEmpty() && Permissions.GOD_OTHERS.isAuthorized(user)) + { + godOtherPlayers(user, args[0]); + return; + } + + user.sendMessage(_("godMode", (user.toggleGodModeEnabled() ? _("enabled") : _("disabled")))); + } + + private void godOtherPlayers(final CommandSender sender, final String name) + { + for (Player matchPlayer : server.matchPlayer(name)) + { + final IUser player = ess.getUser(matchPlayer); + if (player.isHidden()) + { + continue; + } + final boolean enabled = player.toggleGodModeEnabled(); + player.sendMessage(_("godMode", (enabled ? _("enabled") : _("disabled")))); + sender.sendMessage(_("godMode", _(enabled ? "godEnabledFor" : "godDisabledFor", matchPlayer.getDisplayName()))); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandheal.java b/Essentials/src/net/ess3/commands/Commandheal.java new file mode 100644 index 000000000..eb5f34854 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandheal.java @@ -0,0 +1,64 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.api.server.CommandSender; +import net.ess3.permissions.Permissions; +import net.ess3.user.UserData.TimestampType; +import java.util.List; +import org.bukkit.entity.Player; + + +public class Commandheal extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + + if (args.length > 0 && Permissions.HEAL_OTHERS.isAuthorized(user)) + { + user.checkCooldown(TimestampType.LASTHEAL, ess.getRanks().getHealCooldown(user), true, Permissions.HEAL_COOLDOWN_BYPASS); + + healOtherPlayers(user, args[0]); + return; + } + + user.checkCooldown(TimestampType.LASTHEAL, ess.getRanks().getHealCooldown(user), true, Permissions.HEAL_COOLDOWN_BYPASS); + + user.setHealth(20); + user.setFoodLevel(20); + user.sendMessage(_("heal")); + } + + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + healOtherPlayers(sender, args[0]); + } + + private void healOtherPlayers(final CommandSender sender, final String name) + { + final List players = server.matchPlayer(name); + if (players.isEmpty()) + { + sender.sendMessage(_("playerNotFound")); + return; + } + for (Player p : players) + { + if (ess.getUser(p).isHidden()) + { + continue; + } + p.setHealth(20); + p.setFoodLevel(20); + p.sendMessage(_("heal")); + sender.sendMessage(_("healOther", p.getDisplayName())); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandhelp.java b/Essentials/src/net/ess3/commands/Commandhelp.java new file mode 100644 index 000000000..401259fa2 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandhelp.java @@ -0,0 +1,49 @@ +package net.ess3.commands; + +import net.ess3.utils.textreader.TextInput; +import net.ess3.utils.textreader.IText; +import net.ess3.utils.textreader.TextPager; +import net.ess3.utils.textreader.HelpInput; +import net.ess3.utils.textreader.KeywordReplacer; +import static net.ess3.I18n._; +import net.ess3.utils.Util; +import net.ess3.api.IUser; + + +public class Commandhelp extends EssentialsCommand +{ + @Override + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + IText output; + String pageStr = args.length > 0 ? args[0] : null; + String chapterPageStr = args.length > 1 ? args[1] : null; + final IText input = new TextInput(user, "help", false, ess); + + if (input.getLines().isEmpty()) + { + if (Util.isInt(pageStr) || pageStr == null) + { + output = new HelpInput(user, "", ess); + } + else + { + output = new HelpInput(user, pageStr, ess); + pageStr = chapterPageStr; + } + chapterPageStr = null; + } + else + { + output = new KeywordReplacer(input, user, ess); + } + final TextPager pager = new TextPager(output); + pager.showPage(pageStr, chapterPageStr, commandLabel, user); + } + + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + sender.sendMessage(_("helpConsole")); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandhelpop.java b/Essentials/src/net/ess3/commands/Commandhelpop.java new file mode 100644 index 000000000..e36cb1871 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandhelpop.java @@ -0,0 +1,32 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.utils.Util; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import java.util.logging.Level; + + +public class Commandhelpop extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + final String message = _("helpOp", user.getDisplayName(), Util.stripColor(getFinalArg(args, 0))); + logger.log(Level.INFO, message); + for (Player onlinePlayer : server.getOnlinePlayers()) + { + final IUser player = onlinePlayer.getUser(); + if (!Permissions.HELPOP_RECEIVE.isAuthorized(player)) + { + continue; + } + player.sendMessage(message); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandhome.java b/Essentials/src/net/ess3/commands/Commandhome.java new file mode 100644 index 000000000..755676609 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandhome.java @@ -0,0 +1,91 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.economy.Trade; +import net.ess3.utils.Util; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import java.util.List; +import java.util.Locale; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + + +public class Commandhome extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + final Trade charge = new Trade(commandName, ess); + charge.isAffordableFor(user); + IUser player = user; + String homeName = ""; + String[] nameParts; + if (args.length > 0) + { + nameParts = args[0].split(":"); + if (nameParts[0].length() == args[0].length() || !Permissions.HOME_OTHERS.isAuthorized(user)) + { + homeName = nameParts[0]; + } + else + { + player = getPlayer(nameParts, 0, true); + if (nameParts.length > 1) + { + homeName = nameParts[1]; + } + } + } + try + { + if ("bed".equalsIgnoreCase(homeName)) + { + final Location bed = player.getBedSpawnLocation(); + if (bed != null && bed.getBlock().getType() == Material.BED_BLOCK) + { + user.getTeleport().teleport(bed, charge, TeleportCause.COMMAND); + throw new NoChargeException(); + } + } + user.getTeleport().home(player, homeName.toLowerCase(Locale.ENGLISH), charge); + } + catch (NotEnoughArgumentsException e) + { + Location bed = player.getBedSpawnLocation(); + if (bed != null && bed.getBlock().getType() != Material.BED_BLOCK) + { + bed = null; + } + final List homes = player.getHomes(); + if (homes.isEmpty() && player.equals(user)) + { + if (bed != null) + { + user.getTeleport().teleport(bed, charge, TeleportCause.COMMAND); + throw new NoChargeException(); + } + user.getTeleport().respawn(charge, TeleportCause.COMMAND); + + } + else if (homes.isEmpty()) + { + throw new Exception(player == user ? _("noHomeSet") : _("noHomeSetPlayer")); + } + else if (homes.size() == 1 && player.equals(user)) + { + user.getTeleport().home(player, homes.get(0), charge); + } + else + { + if (bed != null) + { + homes.add("bed"); + } + user.sendMessage(_("homes", Util.joinList(homes))); + } + } + throw new NoChargeException(); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandignore.java b/Essentials/src/net/ess3/commands/Commandignore.java new file mode 100644 index 000000000..82bb57cae --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandignore.java @@ -0,0 +1,42 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; + + +public class Commandignore extends EssentialsCommand +{ + @Override + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + IUser player; + try + { + player = getPlayer(args, 0); + } + catch (NoSuchFieldException ex) + { + player = ess.getUser(args[0]); + } + if (player == null) + { + throw new Exception(_("playerNotFound")); + } + final String name = player.getName(); + user.acquireWriteLock(); + if (user.isIgnoringPlayer(name)) + { + user.setIgnoredPlayer(name, false); + user.sendMessage(_("unignorePlayer", player.getName())); + } + else + { + user.setIgnoredPlayer(name, true); + user.sendMessage(_("ignorePlayer", player.getName())); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandinfo.java b/Essentials/src/net/ess3/commands/Commandinfo.java new file mode 100644 index 000000000..c38039b55 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandinfo.java @@ -0,0 +1,19 @@ +package net.ess3.commands; + +import net.ess3.utils.textreader.IText; +import net.ess3.utils.textreader.KeywordReplacer; +import net.ess3.utils.textreader.TextInput; +import net.ess3.utils.textreader.TextPager; + + +public class Commandinfo extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + final IText input = new TextInput(sender, "info", true, ess); + final IText output = new KeywordReplacer(input, sender, ess); + final TextPager pager = new TextPager(output); + pager.showPage(args.length > 0 ? args[0] : null, args.length > 1 ? args[1] : null, commandLabel, sender); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandinvsee.java b/Essentials/src/net/ess3/commands/Commandinvsee.java new file mode 100644 index 000000000..4fa7ceb90 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandinvsee.java @@ -0,0 +1,52 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.user.Inventory; +import java.util.Arrays; +import org.bukkit.inventory.ItemStack; + + +public class Commandinvsee extends EssentialsCommand +{ + @Override + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + + if (args.length < 1 && user.getData().getInventory() == null) + { + throw new NotEnoughArgumentsException(); + } + IUser invUser = user; + if (args.length == 1) + { + invUser = getPlayer(args, 0); + } + user.acquireWriteLock(); + if (invUser == user && user.getData().getInventory() != null) + { + invUser.getInventory().setContents(user.getData().getInventory().getBukkitInventory()); + user.getData().setInventory(null); + user.sendMessage(_("invRestored")); + throw new NoChargeException(); + } + if (user.getData().getInventory() == null) + { + user.getData().setInventory(new Inventory(user.getInventory().getContents())); + } + ItemStack[] invUserStack = invUser.getInventory().getContents(); + final int userStackLength = user.getInventory().getContents().length; + if (invUserStack.length < userStackLength) + { + invUserStack = Arrays.copyOf(invUserStack, userStackLength); + } + if (invUserStack.length > userStackLength) + { + throw new Exception(_("invBigger")); + } + user.getInventory().setContents(invUserStack); + user.sendMessage(_("invSee", invUser.getDisplayName())); + user.sendMessage(_("invSeeHelp")); + throw new NoChargeException(); + } +} diff --git a/Essentials/src/net/ess3/commands/Commanditem.java b/Essentials/src/net/ess3/commands/Commanditem.java new file mode 100644 index 000000000..132e1d4aa --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commanditem.java @@ -0,0 +1,66 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.api.server.Enchantment; +import net.ess3.api.server.ItemStack; +import net.ess3.permissions.ItemPermissions; +import java.util.Locale; + + +public class Commanditem extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + final ItemStack stack = ess.getItemDb().get(args[0], user); + + final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); + if (!ItemPermissions.getPermission(stack.getType()).isAuthorized(user)) + { + throw new Exception(_("cantSpawnItem", itemname)); + } + + if (args.length > 1 && Integer.parseInt(args[1]) > 0) + { + stack.setAmount(Integer.parseInt(args[1])); + } + + if (args.length > 2) + { + for (int i = 2; i < args.length; i++) + { + final String[] split = args[i].split("[:+',;.]", 2); + if (split.length < 1) + { + continue; + } + final Enchantment enchantment = Commandenchant.getEnchantment(split[0], user); + int level; + if (split.length > 1) + { + level = Integer.parseInt(split[1]); + } + else + { + level = enchantment.getMaxLevel(); + } + stack.addEnchantment(enchantment, level); + } + } + + if (stack.isAir()) + { + throw new Exception(_("cantSpawnItem", "Air")); + } + + user.giveItems(stack, false); + + final String displayName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' '); + user.sendMessage(_("itemSpawn", stack.getAmount(), displayName)); + } +} diff --git a/Essentials/src/net/ess3/commands/Commanditemdb.java b/Essentials/src/net/ess3/commands/Commanditemdb.java new file mode 100644 index 000000000..2c4129fd5 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commanditemdb.java @@ -0,0 +1,30 @@ +package net.ess3.commands; + +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + + +public class Commanditemdb extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + ItemStack itemStack = null; + if (args.length < 1) + { + if (sender instanceof Player) + { + itemStack = ((Player)sender).getItemInHand(); + } + if (itemStack == null) + { + throw new NotEnoughArgumentsException(); + } + } + else + { + itemStack = ess.getItemDb().get(args[0]); + } + sender.sendMessage(itemStack.getType().toString() + "- " + itemStack.getTypeId() + ":" + Integer.toString(itemStack.getData().getData())); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandjails.java b/Essentials/src/net/ess3/commands/Commandjails.java new file mode 100644 index 000000000..ae443e19d --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandjails.java @@ -0,0 +1,13 @@ +package net.ess3.commands; + +import net.ess3.utils.Util; + + +public class Commandjails extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + sender.sendMessage("§7" + Util.joinList(" ", ess.getJails().getList())); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandjump.java b/Essentials/src/net/ess3/commands/Commandjump.java new file mode 100644 index 000000000..4e9eb491e --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandjump.java @@ -0,0 +1,36 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.economy.Trade; +import net.ess3.api.IUser; +import net.ess3.api.server.ILocation; +import net.ess3.utils.LocationUtil; +import org.bukkit.Location; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + + +public class Commandjump extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + Location loc; + final ILocation cloc = user.getLocation(); + + try + { + loc = LocationUtil.getTarget(user); + loc.setYaw(cloc.getYaw()); + loc.setPitch(cloc.getPitch()); + loc.setY(loc.getY() + 1); + } + catch (NullPointerException ex) + { + throw new Exception(_("jumpError"), ex); + } + + final Trade charge = new Trade(commandName, ess); + charge.isAffordableFor(user); + user.getTeleport().teleport(loc, charge, TeleportCause.COMMAND); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandkick.java b/Essentials/src/net/ess3/commands/Commandkick.java new file mode 100644 index 000000000..b4164f46e --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandkick.java @@ -0,0 +1,38 @@ +package net.ess3.commands; + +import net.ess3.Console; +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.api.server.CommandSender; +import net.ess3.permissions.Permissions; + + +public class Commandkick extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + final IUser user = getPlayer(args, 0); + if (Permissions.KICK_EXEMPT.isAuthorized(user)) + { + throw new Exception(_("kickExempt")); + } + final String kickReason = args.length > 1 ? getFinalArg(args, 1) : _("kickDefault"); + user.kickPlayer(kickReason); + final String senderName = sender instanceof Player ? ((Player)sender).getDisplayName() : Console.NAME; + + for (Player onlinePlayer : server.getOnlinePlayers()) + { + final IUser player = onlinePlayer.getUser(); + if (Permissions.KICK_NOTIFY.isAuthorized(player)) + { + onlinePlayer.sendMessage(_("playerKicked", senderName, user.getName(), kickReason)); + } + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandkickall.java b/Essentials/src/net/ess3/commands/Commandkickall.java new file mode 100644 index 000000000..e66409f69 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandkickall.java @@ -0,0 +1,25 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.server.CommandSender; +import net.ess3.api.server.Player; + + +public class Commandkickall extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + for (Player onlinePlayer : server.getOnlinePlayers()) + { + if (sender.isPlayer() && onlinePlayer.getName().equalsIgnoreCase(((Player)sender).getName())) + { + continue; + } + else + { + onlinePlayer.kickPlayer(args.length > 0 ? getFinalArg(args, 0) : _("kickDefault")); + } + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandkill.java b/Essentials/src/net/ess3/commands/Commandkill.java new file mode 100644 index 000000000..401302177 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandkill.java @@ -0,0 +1,33 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; + +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageEvent; + + +public class Commandkill extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + for (Player matchPlayer : server.matchPlayer(args[0])) + { + final EntityDamageEvent ede = new EntityDamageEvent(matchPlayer, sender instanceof Player && ((Player)sender).getName().equals(matchPlayer.getName()) ? EntityDamageEvent.DamageCause.SUICIDE : EntityDamageEvent.DamageCause.CUSTOM, 1000); + server.getPluginManager().callEvent(ede); + if (ede.isCancelled() && !sender.hasPermission("essentials.kill.force")) + { + continue; + } + + matchPlayer.damage(1000); + matchPlayer.setHealth(0); + sender.sendMessage(_("kill", matchPlayer.getDisplayName())); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandkillall.java b/Essentials/src/net/ess3/commands/Commandkillall.java new file mode 100644 index 000000000..b3b3390b4 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandkillall.java @@ -0,0 +1,144 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; + +import net.ess3.bukkit.Mob; +import java.util.Collections; +import java.util.Locale; +import org.bukkit.Chunk; +import org.bukkit.World; +import org.bukkit.entity.*; +import org.bukkit.event.entity.EntityDeathEvent; + + +public class Commandkillall extends EssentialsCommand +{ + //TODO: Tidy - missed this during command cleanup + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + String type = "all"; + int radius = -1; + World world; + if (sender instanceof Player) + { + world = ((Player)sender).getWorld(); + if (args.length == 1) + { + try + { + radius = Integer.parseInt(args[0]); + } + catch (NumberFormatException e1) + { + type = args[0]; + } + } + else if (args.length > 1) + { + type = args[0]; + try + { + radius = Integer.parseInt(args[1]); + } + catch (NumberFormatException e) + { + throw new Exception(_("numberRequired")); + } + } + } + else + { + if (args.length == 0) + { + throw new NotEnoughArgumentsException(); + } + else if (args.length == 1) + { + world = ess.getWorld(args[0]); + } + else + { + type = args[0]; + world = ess.getWorld(args[1]); + } + } + if (radius >= 0) + { + radius *= radius; + } + String killType = type.toLowerCase(Locale.ENGLISH); + boolean animals = killType.startsWith("animal"); + boolean monster = killType.startsWith("monster") || killType.startsWith("mob"); + boolean all = killType.equals("all"); + Class entityClass = null; + if (!animals && !monster && !all) + { + if (Mob.fromName(killType) == null) + { + throw new Exception(_("invalidMob")); + } + entityClass = Mob.fromName(killType).getType().getEntityClass(); + } + int numKills = 0; + for (Chunk chunk : world.getLoadedChunks()) + { + for (Entity entity : chunk.getEntities()) + { + if (sender instanceof Player) + { + if (radius >= 0 && ((Player)sender).getLocation().distanceSquared(entity.getLocation()) > radius) + { + continue; + } + } + if (entity instanceof LivingEntity == false || entity instanceof HumanEntity) + { + continue; + } + if (entity instanceof Wolf) + { + if (((Wolf)entity).isTamed()) + { + continue; + } + } + if (animals) + { + if (entity instanceof Animals || entity instanceof NPC || entity instanceof Snowman || entity instanceof WaterMob) + { + EntityDeathEvent event = new EntityDeathEvent((LivingEntity)entity, Collections.EMPTY_LIST); + ess.getServer().getPluginManager().callEvent(event); + entity.remove(); + numKills++; + } + } + else if (monster) + { + if (entity instanceof Monster || entity instanceof ComplexLivingEntity || entity instanceof Flying || entity instanceof Slime) + { + EntityDeathEvent event = new EntityDeathEvent((LivingEntity)entity, Collections.EMPTY_LIST); + ess.getServer().getPluginManager().callEvent(event); + entity.remove(); + numKills++; + } + } + else if (all) + { + EntityDeathEvent event = new EntityDeathEvent((LivingEntity)entity, Collections.EMPTY_LIST); + ess.getServer().getPluginManager().callEvent(event); + entity.remove(); + numKills++; + } + else if (entityClass != null && entityClass.isAssignableFrom(entity.getClass())) + { + EntityDeathEvent event = new EntityDeathEvent((LivingEntity)entity, Collections.EMPTY_LIST); + ess.getServer().getPluginManager().callEvent(event); + entity.remove(); + numKills++; + } + } + } + sender.sendMessage(_("kill", numKills)); + } +} \ No newline at end of file diff --git a/Essentials/src/net/ess3/commands/Commandkit.java b/Essentials/src/net/ess3/commands/Commandkit.java new file mode 100644 index 000000000..f3ea78ce1 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandkit.java @@ -0,0 +1,62 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.economy.Trade; +import net.ess3.utils.Util; +import net.ess3.api.IUser; +import net.ess3.permissions.KitPermissions; +import net.ess3.settings.Kit; +import java.util.Collection; +import java.util.Locale; + + +public class Commandkit extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + Collection kitList = ess.getKits().getList(); + if (kitList.isEmpty()) + { + user.sendMessage(_("noKits")); + } + else + { + for (String kitName : kitList) + { + if (!KitPermissions.getPermission(kitName).isAuthorized(user)) + { + kitList.remove(kitName); + } + } + user.sendMessage(_("kits", Util.joinList(kitList))); + } + throw new NoChargeException(); + } + else + { + final String kitName = args[0].toLowerCase(Locale.ENGLISH); + final Kit kit = ess.getKits().getKit(kitName); + + if (!KitPermissions.getPermission(kitName).isAuthorized(user)) + { + throw new Exception(_("noKitPermission", "essentials.kit." + kitName)); + } + + //TODO: Check kit delay + + final Trade charge = new Trade("kit-" + kitName, ess); + charge.isAffordableFor(user); + + ess.getKits().sendKit(user, kit); + + //TODO: Merge kit changes from 2.9 + + charge.charge(user); + user.sendMessage(_("kitGive", kitName)); + + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandkittycannon.java b/Essentials/src/net/ess3/commands/Commandkittycannon.java new file mode 100644 index 000000000..fc625e986 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandkittycannon.java @@ -0,0 +1,38 @@ +package net.ess3.commands; + +import net.ess3.bukkit.Mob; +import net.ess3.api.IUser; +import java.util.Random; +import org.bukkit.Location; +import org.bukkit.entity.Ocelot; + + +public class Commandkittycannon extends EssentialsCommand +{ + private static Random random = new Random(); + + @Override + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + final Mob cat = Mob.OCELOT; + final Ocelot ocelot = (Ocelot)cat.spawn(user, server, user.getEyeLocation()); + if (ocelot == null) + { + return; + } + final int i = random.nextInt(Ocelot.Type.values().length); + ocelot.setCatType(Ocelot.Type.values()[i]); + ocelot.setTamed(true); + ocelot.setVelocity(user.getEyeLocation().getDirection().multiply(2)); + ess.getPlugin().scheduleSyncDelayedTask(new Runnable() + { + @Override + public void run() + { + final Location loc = ocelot.getLocation(); + ocelot.remove(); + loc.getWorld().createExplosion(loc, 0F); + } + }, 20); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandlightning.java b/Essentials/src/net/ess3/commands/Commandlightning.java new file mode 100644 index 000000000..07d8ec10b --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandlightning.java @@ -0,0 +1,71 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import lombok.Cleanup; +import org.bukkit.entity.LightningStrike; +import org.bukkit.entity.Player; + + +public class Commandlightning extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + + IUser user = null; + if (sender instanceof Player) + { + user = ess.getUser(((Player)sender)); + } + if ((args.length < 1 || !Permissions.LIGHTNING_OTHERS.isAuthorized(user)) && user != null) + { + user.getWorld().strikeLightning(user.getTargetBlock(null, 600).getLocation()); + return; + } + + if (server.matchPlayer(args[0]).isEmpty()) + { + throw new Exception(_("playerNotFound")); + } + + int power = 1; + if (args.length > 1) + { + try + { + power = Integer.parseInt(args[1]); + } + catch (NumberFormatException ex) + { + } + } + + for (Player matchPlayer : server.matchPlayer(args[0])) + { + sender.sendMessage(_("lightningUse", matchPlayer.getDisplayName())); + if (power <= 0) + { + matchPlayer.getWorld().strikeLightningEffect(matchPlayer.getLocation()); + } + else + { + LightningStrike strike = matchPlayer.getWorld().strikeLightning(matchPlayer.getLocation()); + matchPlayer.damage(power - 1, strike); + } + if (!ess.getUser(matchPlayer).isGodModeEnabled()) + { + matchPlayer.setHealth(matchPlayer.getHealth() < 5 ? 0 : matchPlayer.getHealth() - 5); + } + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (settings.getData().getCommands().getLightning().isWarnPlayer()) + { + matchPlayer.sendMessage(_("lightningSmited")); + } + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandlist.java b/Essentials/src/net/ess3/commands/Commandlist.java new file mode 100644 index 000000000..1a026d970 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandlist.java @@ -0,0 +1,162 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.utils.Util; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import java.util.*; + + +public class Commandlist extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + boolean showhidden = false; + if (Permissions.LIST_HIDDEN.isAuthorized(sender)) + { + showhidden = true; + } + int playerHidden = 0; + for (Player onlinePlayer : server.getOnlinePlayers()) + { + if (onlinePlayer.getUser().isHidden()) + { + playerHidden++; + } + } + + String online; + if (showhidden && playerHidden > 0) + { + online = _("listAmountHidden", server.getOnlinePlayers().size() - playerHidden, playerHidden, server.getMaxPlayers()); + } + else + { + online = _("listAmount", server.getOnlinePlayers().size() - playerHidden, server.getMaxPlayers()); + } + sender.sendMessage(online); + + boolean sortListByGroups = false; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try + { + sortListByGroups = settings.getData().getCommands().getList().isSortByGroups(); + } + finally + { + settings.unlock(); + } + + if (sortListByGroups) + { + Map> sort = new HashMap>(); + for (Player onlinePlayer : server.getOnlinePlayers()) + { + final IUser player = onlinePlayer.getUser(); + if (player.isHidden() && !showhidden) + { + continue; + } + final String group = ess.getRanks().getMainGroup(player); + List list = sort.get(group); + if (list == null) + { + list = new ArrayList(); + sort.put(group, list); + } + list.add(player); + } + final String[] groups = sort.keySet().toArray(new String[0]); + Arrays.sort(groups, String.CASE_INSENSITIVE_ORDER); + for (String group : groups) + { + final StringBuilder groupString = new StringBuilder(); + groupString.append(_("listGroupTag",Util.replaceColor(group))); + final List users = sort.get(group); + Collections.sort(users); + boolean first = true; + for (IUser user : users) + { + if (!first) + { + groupString.append(", "); + } + else + { + first = false; + } + user.acquireReadLock(); + try + { + if (user.getData().isAfk()) + { + groupString.append(_("listAfkTag")); + } + } + finally + { + user.unlock(); + } + if (user.isHidden()) + { + groupString.append(_("listHiddenTag")); + } + groupString.append(user.getDisplayName()); + groupString.append("§f"); + } + sender.sendMessage(groupString.toString()); + } + } + else + { + final List users = new ArrayList(); + for (Player onlinePlayer : server.getOnlinePlayers()) + { + final IUser player =onlinePlayer.getUser(); + if (player.isHidden() && !showhidden) + { + continue; + } + users.add(player); + } + Collections.sort(users); + + final StringBuilder onlineUsers = new StringBuilder(); + onlineUsers.append(_("connectedPlayers")); + boolean first = true; + for (IUser user : users) + { + if (!first) + { + onlineUsers.append(", "); + } + else + { + first = false; + } + user.acquireReadLock(); + try + { + if (user.getData().isAfk()) + { + onlineUsers.append(_("listAfkTag")); + } + } + finally + { + user.unlock(); + } + if (user.isHidden()) + { + onlineUsers.append(_("listHiddenTag")); + } + onlineUsers.append(user.getDisplayName()); + onlineUsers.append("§f"); + } + sender.sendMessage(onlineUsers.toString()); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandmail.java b/Essentials/src/net/ess3/commands/Commandmail.java new file mode 100644 index 000000000..4f94f067c --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandmail.java @@ -0,0 +1,164 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.utils.Util; +import net.ess3.api.IUser; +import net.ess3.api.server.CommandSender; +import net.ess3.permissions.Permissions; +import java.util.List; +import org.bukkit.entity.Player; + + +public class Commandmail extends EssentialsCommand +{ + //TODO: Tidy this up + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length >= 1 && "read".equalsIgnoreCase(args[0])) + { + final List mail = user.getData().getMails(); + if (mail == null || mail.isEmpty()) + { + user.sendMessage(_("noMail")); + throw new NoChargeException(); + } + for (String messages : mail) + { + user.sendMessage(messages); + } + user.sendMessage(_("mailClear")); + return; + } + if (args.length >= 3 && "send".equalsIgnoreCase(args[0])) + { + if (!Permissions.MAIL_SEND.isAuthorized(user)) + { + throw new Exception(_("noPerm", "essentials.mail.send")); + } + + Player player = server.getPlayer(args[1]); + IUser u; + if (player != null) + { + u = ess.getUser(player); + } + else + { + u = ess.getUser(args[1]); + } + if (u == null) + { + throw new Exception(_("playerNeverOnServer", args[1])); + } + if (!u.isIgnoringPlayer(user.getName())) + { + final String mail = Util.sanitizeString(Util.stripColor(getFinalArg(args, 2))); + u.addMail(user.getName() + ": " + mail); + } + user.sendMessage(_("mailSent")); + return; + } + if (args.length > 1 && "sendall".equalsIgnoreCase(args[0])) + { + if (!Permissions.MAIL_SENDALL.isAuthorized(user)) + { + throw new Exception(_("noPerm", "essentials.mail.sendall")); + } + ess.getPlugin().scheduleAsyncDelayedTask(new SendAll(user.getName() + ": " + Util.stripColor(getFinalArg(args, 1)))); + user.sendMessage(_("mailSent")); + return; + } + if (args.length >= 1 && "clear".equalsIgnoreCase(args[0])) + { + user.acquireWriteLock(); + user.getData().setMails(null); + user.sendMessage(_("mailCleared")); + return; + } + throw new NotEnoughArgumentsException(); + } + + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length >= 1 && "read".equalsIgnoreCase(args[0])) + { + throw new Exception(_("onlyPlayers", commandName + " read")); + } + else if (args.length >= 1 && "clear".equalsIgnoreCase(args[0])) + { + throw new Exception(_("onlyPlayers", commandName + " clear")); + } + else if (args.length >= 3 && "send".equalsIgnoreCase(args[0])) + { + Player player = server.getPlayer(args[1]); + IUser u; + if (player != null) + { + u = ess.getUser(player); + } + else + { + u = ess.getUser(args[1]); + } + if (u == null) + { + throw new Exception(_("playerNeverOnServer", args[1])); + } + u.addMail("Server: " + getFinalArg(args, 2)); + sender.sendMessage(_("mailSent")); + return; + } + else if (args.length >= 1 && "sendall".equalsIgnoreCase(args[0])) + { + ess.getPlugin().scheduleAsyncDelayedTask(new SendAll("Server: " + getFinalArg(args, 2))); + } + else if (args.length >= 2) + { + //allow sending from console without "send" argument, since it's the only thing the console can do + Player player = server.getPlayer(args[0]); + IUser u; + if (player != null) + { + u = ess.getUser(player); + } + else + { + u = ess.getUser(args[0]); + } + if (u == null) + { + throw new Exception(_("playerNeverOnServer", args[0])); + } + u.addMail("Server: " + getFinalArg(args, 1)); + sender.sendMessage(_("mailSent")); + return; + } + throw new NotEnoughArgumentsException(); + } + + + private class SendAll implements Runnable + { + String message; + + public SendAll(String message) + { + this.message = message; + } + + @Override + public void run() + { + for (String username : ess.getUserMap().getAllUniqueUsers()) + { + IUser user = ess.getUserMap().getUser(username); + if (user != null) + { + user.addMail(message); + } + } + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandme.java b/Essentials/src/net/ess3/commands/Commandme.java new file mode 100644 index 000000000..7b756a592 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandme.java @@ -0,0 +1,36 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.utils.Util; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; + + +public class Commandme extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (user.getData().isMuted()) + { + throw new Exception(_("voiceSilenced")); + } + + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + String message = getFinalArg(args, 0); + if (Permissions.CHAT_COLOR.isAuthorized(user)) + { + message = Util.replaceColor(message); + } + else { + message = Util.stripColor(message); + } + + + ess.broadcastMessage(user, _("action", user.getDisplayName(), message)); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandmore.java b/Essentials/src/net/ess3/commands/Commandmore.java new file mode 100644 index 000000000..78269a022 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandmore.java @@ -0,0 +1,55 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.permissions.ItemPermissions; +import net.ess3.permissions.Permissions; +import java.util.Locale; + + +public class Commandmore extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + final ItemStack stack = user.getItemInHand(); + if (stack == null) + { + throw new Exception(_("cantSpawnItem", "Air")); + } + int defaultStackSize = 0; + int oversizedStackSize = 0; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try + { + defaultStackSize = settings.getData().getGeneral().getDefaultStacksize(); + oversizedStackSize = settings.getData().getGeneral().getOversizedStacksize(); + } + finally + { + settings.unlock(); + } + if (stack.getAmount() >= (Permissions.OVERSIZEDSTACKS.isAuthorized(user) + ? oversizedStackSize + : defaultStackSize > 0 ? defaultStackSize : stack.getMaxStackSize())) + { + throw new NoChargeException(); + } + final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); + if (!ItemPermissions.getPermission(stack.getType()).isAuthorized(user)) + { + throw new Exception(_("cantSpawnItem", itemname)); + } + if (Permissions.OVERSIZEDSTACKS.isAuthorized(user)) + { + stack.setAmount(oversizedStackSize); + } + else + { + stack.setAmount(defaultStackSize > 0 ? defaultStackSize : stack.getMaxStackSize()); + } + user.updateInventory(); + } +} \ No newline at end of file diff --git a/Essentials/src/net/ess3/commands/Commandmotd.java b/Essentials/src/net/ess3/commands/Commandmotd.java new file mode 100644 index 000000000..91470a1af --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandmotd.java @@ -0,0 +1,19 @@ +package net.ess3.commands; + +import net.ess3.utils.textreader.IText; +import net.ess3.utils.textreader.KeywordReplacer; +import net.ess3.utils.textreader.TextInput; +import net.ess3.utils.textreader.TextPager; + + +public class Commandmotd extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + final IText input = new TextInput(sender, "motd", true, ess); + final IText output = new KeywordReplacer(input, sender, ess); + final TextPager pager = new TextPager(output); + pager.showPage(args.length > 0 ? args[0] : null, args.length > 1 ? args[1] : null, commandLabel, sender); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandmsg.java b/Essentials/src/net/ess3/commands/Commandmsg.java new file mode 100644 index 000000000..77705d36c --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandmsg.java @@ -0,0 +1,98 @@ +package net.ess3.commands; + +import net.ess3.Console; +import static net.ess3.I18n._; + +import net.ess3.utils.Util; +import net.ess3.api.IReplyTo; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import java.util.List; +import lombok.Cleanup; +import org.bukkit.entity.Player; + + +public class Commandmsg extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 2 || args[0].trim().isEmpty() || args[1].trim().isEmpty()) + { + throw new NotEnoughArgumentsException(); + } + + String message = getFinalArg(args, 1); + if (sender instanceof Player) + { + @Cleanup + IUser user = ess.getUser((Player)sender); + user.acquireReadLock(); + if (user.getData().isMuted()) + { + throw new Exception(_("voiceSilenced")); + } + if (Permissions.MSG_COLOR.isAuthorized(user)) + { + message = Util.replaceColor(message); + } + else + { + message = Util.stripColor(message); + } + } + else + { + message = Util.replaceColor(message); + } + + final String translatedMe = _("me"); + + final IReplyTo replyTo = sender instanceof Player ? ess.getUser((Player)sender) : Console.getConsoleReplyTo(); + final String senderName = sender instanceof Player ? ((Player)sender).getDisplayName() : Console.NAME; + + if (args[0].equalsIgnoreCase(Console.NAME)) + { + sender.sendMessage(_("msgFormat", translatedMe, Console.NAME, message)); + CommandSender cs = server.getConsoleSender(); + cs.sendMessage(_("msgFormat", senderName, translatedMe, message)); + replyTo.setReplyTo(cs); + Console.getConsoleReplyTo().setReplyTo(sender); + return; + } + + final List matchedPlayers = server.matchPlayer(args[0]); + + if (matchedPlayers.isEmpty()) + { + throw new Exception(_("playerNotFound")); + } + + int i = 0; + for (Player matchedPlayer : matchedPlayers) + { + final IUser u = ess.getUser(matchedPlayer); + if (u.isHidden()) + { + i++; + } + } + if (i == matchedPlayers.size()) + { + throw new Exception(_("playerNotFound")); + } + + for (Player matchedPlayer : matchedPlayers) + { + sender.sendMessage(_("msgFormat", translatedMe, matchedPlayer.getDisplayName(), message)); + final IUser matchedUser = ess.getUser(matchedPlayer); + if (sender instanceof Player && (matchedUser.isIgnoringPlayer(((Player)sender).getName()) || matchedUser.isHidden())) + { + continue; + } + matchedPlayer.sendMessage(_("msgFormat", senderName, translatedMe, message)); + replyTo.setReplyTo(ess.getUser(matchedPlayer)); + ess.getUser(matchedPlayer).setReplyTo(sender); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandmute.java b/Essentials/src/net/ess3/commands/Commandmute.java new file mode 100644 index 000000000..d0e257b33 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandmute.java @@ -0,0 +1,50 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; + +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import net.ess3.user.UserData.TimestampType; +import net.ess3.utils.DateUtil; +import lombok.Cleanup; + + +public class Commandmute extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + @Cleanup + final IUser player = getPlayer(args, 0, true); + player.acquireReadLock(); + if (!player.getData().isMuted() && Permissions.MUTE_EXEMPT.isAuthorized(player)) + { + throw new Exception(_("muteExempt")); + } + long muteTimestamp = 0; + if (args.length > 1) + { + String time = getFinalArg(args, 1); + muteTimestamp = DateUtil.parseDateDiff(time, true); + } + player.setTimestamp(TimestampType.MUTE, muteTimestamp); + final boolean muted = player.toggleMuted(); + sender.sendMessage( + muted + ? (muteTimestamp > 0 + ? _("mutedPlayerFor", player.getDisplayName(), DateUtil.formatDateDiff(muteTimestamp)) + : _("mutedPlayer", player.getDisplayName())) + : _("unmutedPlayer", player.getDisplayName())); + player.sendMessage( + muted + ? (muteTimestamp > 0 + ? _("playerMutedFor", DateUtil.formatDateDiff(muteTimestamp)) + : _("playerMuted")) + : _("playerUnmuted")); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandnear.java b/Essentials/src/net/ess3/commands/Commandnear.java new file mode 100644 index 000000000..1ea933474 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandnear.java @@ -0,0 +1,110 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; + + +public class Commandnear extends EssentialsCommand +{ + @Override + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + long radius = 200; + + IUser otherUser = null; + + if (args.length > 0) + { + try + { + otherUser = getPlayer(args, 0); + } + catch (Exception ex) + { + try + { + radius = Long.parseLong(args[0]); + } + catch (NumberFormatException e) + { + } + } + if (args.length > 1 && otherUser != null) + { + try + { + radius = Long.parseLong(args[1]); + } + catch (NumberFormatException e) + { + } + } + } + if (otherUser == null || Permissions.NEAR_OTHERS.isAuthorized(user)) + { + user.sendMessage(_("nearbyPlayers", getLocal(otherUser == null ? user : otherUser, radius))); + } + else + { + user.sendMessage(_("noAccessCommand")); + } + } + + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length == 0) + { + throw new NotEnoughArgumentsException(); + } + final IUser otherUser = getPlayer(args, 0); + long radius = 200; + if (args.length > 1) + { + try + { + radius = Long.parseLong(args[1]); + } + catch (NumberFormatException e) + { + } + } + sender.sendMessage(_("nearbyPlayers", getLocal(otherUser, radius))); + } + + private String getLocal(final IUser user, final long radius) + { + final Location loc = user.getLocation(); + final World world = loc.getWorld(); + final StringBuilder output = new StringBuilder(); + final long radiusSquared = radius * radius; + + for (Player onlinePlayer : server.getOnlinePlayers()) + { + final IUser player = ess.getUser(onlinePlayer); + if (!player.equals(user) && !player.isHidden()) + { + final Location playerLoc = player.getLocation(); + if (playerLoc.getWorld() != world) + { + continue; + } + + final long delta = (long)playerLoc.distanceSquared(loc); + if (delta < radiusSquared) + { + if (output.length() > 0) + { + output.append(", "); + } + output.append(player.getDisplayName()).append("§f(§4").append((long)Math.sqrt(delta)).append("m§f)"); + } + } + } + return output.length() > 1 ? output.toString() : _("none"); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandnick.java b/Essentials/src/net/ess3/commands/Commandnick.java new file mode 100644 index 000000000..96455e85e --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandnick.java @@ -0,0 +1,126 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.utils.Util; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import java.util.Locale; +import lombok.Cleanup; +import org.bukkit.Server; +import org.bukkit.entity.Player; + + +public class Commandnick extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (!settings.getData().getChat().getChangeDisplayname()) + { + throw new Exception(_("nickDisplayName")); + } + if (args.length > 1) + { + if (!Permissions.NICK_OTHERS.isAuthorized(user)) + { + throw new Exception(_("nickOthersPermission")); + } + setNickname(getPlayer(args, 0), formatNickname(user, args[1])); + user.sendMessage(_("nickChanged")); + return; + } + setNickname(user, formatNickname(user, args[0])); + } + + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 2) + { + throw new NotEnoughArgumentsException(); + } + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (!settings.getData().getChat().getChangeDisplayname()) + { + throw new Exception(_("nickDisplayName")); + } + if ((args[0].equalsIgnoreCase("*") || args[0].equalsIgnoreCase("all")) && args[1].equalsIgnoreCase("off")) + { + resetAllNicknames(server); + } + else + { + setNickname(getPlayer(args, 0), formatNickname(null, args[1])); + } + sender.sendMessage(_("nickChanged")); + } + + private String formatNickname(final IUser user, final String nick) + { + if (user == null || Permissions.NICK_COLOR.isAuthorized(user)) + { + return nick.replace('&', '\u00a7').replaceAll("\u00a7+k", ""); + } else { + return Util.stripColor(nick); + } + } + + private void resetAllNicknames(final Server server) + { + for (Player player : server.getOnlinePlayers()) + { + try + { + setNickname(ess.getUser(player), "off"); + } + catch (Exception ex) + { + } + } + } + + private void setNickname(final IUser target, final String nick) throws Exception + { + if (!nick.matches("^[a-zA-Z_0-9\u00a7]+$")) + { + throw new Exception(_("nickNamesAlpha")); + } + else if ("off".equalsIgnoreCase(nick) || target.getName().equalsIgnoreCase(nick)) + { + target.getData().setNickname(null); + target.updateDisplayName(); + target.sendMessage(_("nickNoMore")); + } + else + { + for (Player p : server.getOnlinePlayers()) + { + if (target.getBase() == p) + { + continue; + } + String dn = p.getDisplayName().toLowerCase(Locale.ENGLISH); + String n = p.getName().toLowerCase(Locale.ENGLISH); + String nk = nick.toLowerCase(Locale.ENGLISH); + if (nk.equals(dn) || nk.equals(n)) + { + throw new Exception(_("nickInUse")); + } + } + + target.getData().setNickname(nick); + target.updateDisplayName(); + target.sendMessage(_("nickSet", target.getDisplayName() + "§7.")); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandnuke.java b/Essentials/src/net/ess3/commands/Commandnuke.java new file mode 100644 index 000000000..bde21f7e1 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandnuke.java @@ -0,0 +1,54 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.entity.TNTPrimed; + + +public class Commandnuke extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws NoSuchFieldException, NotEnoughArgumentsException + { + List targets; + if (args.length > 0) + { + targets = new ArrayList(); + int pos = 0; + for (String arg : args) + { + targets.add(getPlayer(args, pos)); + pos++; + } + } + else + { + targets = Arrays.asList(server.getOnlinePlayers()); + } + ess.getTNTListener().enable(); + for (Player player : targets) + { + if (player == null) + { + continue; + } + player.sendMessage(_("nuke")); + final Location loc = player.getLocation(); + final World world = loc.getWorld(); + for (int x = -10; x <= 10; x += 5) + { + for (int z = -10; z <= 10; z += 5) + { + final Location tntloc = new Location(world, loc.getBlockX() + x, world.getMaxHeight(), loc.getBlockZ() + z); + final TNTPrimed tnt = world.spawn(tntloc, TNTPrimed.class); + } + } + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandpay.java b/Essentials/src/net/ess3/commands/Commandpay.java new file mode 100644 index 000000000..f1894d337 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandpay.java @@ -0,0 +1,44 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.economy.Trade; +import net.ess3.api.IUser; +import org.bukkit.entity.Player; + + +public class Commandpay extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 2) + { + throw new NotEnoughArgumentsException(); + } + + if (args[0] == "") + { + throw new NotEnoughArgumentsException("You need to specify a player to pay."); + } + + double amount = Double.parseDouble(args[1].replaceAll("[^0-9\\.]", "")); + + Boolean foundUser = false; + for (Player p : server.matchPlayer(args[0])) + { + IUser u = ess.getUser(p); + if (u.isHidden()) + { + continue; + } + user.payUser(u, amount); + Trade.log("Command", "Pay", "Player", user.getName(), new Trade(amount, ess), u.getName(), new Trade(amount, ess), user.getLocation(), ess); + foundUser = true; + } + + if (foundUser == false) + { + throw new NoSuchFieldException(_("playerNotFound")); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandping.java b/Essentials/src/net/ess3/commands/Commandping.java new file mode 100644 index 000000000..77b7a82c0 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandping.java @@ -0,0 +1,22 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.utils.Util; +import net.ess3.api.IUser; + + +public class Commandping extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage(_("pong")); + } + else + { + user.sendMessage(Util.replaceColor(getFinalArg(args, 0))); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandpowertool.java b/Essentials/src/net/ess3/commands/Commandpowertool.java new file mode 100644 index 000000000..ad201f5c8 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandpowertool.java @@ -0,0 +1,112 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.utils.Util; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + + +public class Commandpowertool extends EssentialsCommand +{ + @Override + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + String command = getFinalArg(args, 0); + + // check to see if this is a clear all command + if (command != null && command.equalsIgnoreCase("d:")) + { + user.acquireWriteLock(); + user.getData().clearAllPowertools(); + user.sendMessage(_("powerToolClearAll")); + return; + } + + final ItemStack itemStack = user.getItemInHand(); + if (itemStack == null || itemStack.getType() == Material.AIR) + { + throw new Exception(_("powerToolAir")); + } + + final String itemName = itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replaceAll("_", " "); + List powertools = user.getData().getPowertool(itemStack.getType()); + if (command != null && !command.isEmpty()) + { + if (command.equalsIgnoreCase("l:")) + { + if (powertools == null || powertools.isEmpty()) + { + throw new Exception(_("powerToolListEmpty", itemName)); + } + else + { + user.sendMessage(_("powerToolList", Util.joinList(powertools), itemName)); + } + return; + } + if (command.startsWith("r:")) + { + try + { + command = command.substring(2); + if (!powertools.contains(command)) + { + throw new Exception(_("powerToolNoSuchCommandAssigned", command, itemName)); + } + + powertools.remove(command); + user.sendMessage(_("powerToolRemove", command, itemName)); + } + catch (Exception e) + { + user.sendMessage(e.getMessage()); + return; + } + } + else + { + if (command.startsWith("a:")) + { + if (!Permissions.POWERTOOL_APPEND.isAuthorized(user)) + { + throw new Exception(_("noPerm", "essentials.powertool.append")); + } + command = command.substring(2); + if (powertools.contains(command)) + { + throw new Exception(_("powerToolAlreadySet", command, itemName)); + } + + } + else if (powertools != null && !powertools.isEmpty()) + { + // Replace all commands with this one + powertools.clear(); + } + else + { + powertools = new ArrayList(); + } + + powertools.add(command); + user.sendMessage(_("powerToolAttach", Util.joinList(powertools), itemName)); + } + } + else + { + if (powertools != null) + { + powertools.clear(); + } + user.sendMessage(_("powerToolRemoveAll", itemName)); + } + + user.acquireWriteLock(); + user.getData().setPowertool(itemStack.getType(), powertools); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandpowertooltoggle.java b/Essentials/src/net/ess3/commands/Commandpowertooltoggle.java new file mode 100644 index 000000000..a7875e1b7 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandpowertooltoggle.java @@ -0,0 +1,23 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; + + +public class Commandpowertooltoggle extends EssentialsCommand +{ + @Override + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (!user.getData().hasPowerTools()) + { + user.sendMessage(_("noPowerTools")); + return; + } + user.acquireWriteLock(); + user.getData().setPowerToolsEnabled(!user.getData().isPowerToolsEnabled()); + user.sendMessage(user.getData().isPowerToolsEnabled() + ? _("powerToolsEnabled") + : _("powerToolsDisabled")); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandptime.java b/Essentials/src/net/ess3/commands/Commandptime.java new file mode 100644 index 000000000..f3185c25e --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandptime.java @@ -0,0 +1,227 @@ +package net.ess3.commands; + +import net.ess3.utils.DescParseTickFormat; +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import java.util.*; +import org.bukkit.World; +import org.bukkit.entity.Player; + + +public class Commandptime extends EssentialsCommand +{ + public static final Set getAliases = new HashSet(); + + static + { + getAliases.add("get"); + getAliases.add("list"); + getAliases.add("show"); + getAliases.add("display"); + } + + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + // Which Players(s) / Users(s) are we interested in? + String userSelector = null; + if (args.length == 2) + { + userSelector = args[1]; + } + Set users = getUsers(sender, userSelector); + + // If no arguments we are reading the time + if (args.length == 0) + { + getUsersTime(sender, users); + return; + } + + IUser user = sender instanceof Player ? ess.getUser((Player)sender) : null; + if ((!users.contains(user) || users.size() > 1) && user != null && !Permissions.PTIME_OTHERS.isAuthorized(user)) + { + user.sendMessage(_("pTimeOthersPermission")); + return; + } + + Long ticks; + // Parse the target time int ticks from args[0] + String timeParam = args[0]; + Boolean relative = true; + if (timeParam.startsWith("@")) + { + relative = false; + timeParam = timeParam.substring(1); + } + + if (getAliases.contains(timeParam)) + { + getUsersTime(sender, users); + return; + } + else if (DescParseTickFormat.meansReset(timeParam)) + { + ticks = null; + } + else + { + try + { + ticks = DescParseTickFormat.parse(timeParam); + } + catch (NumberFormatException e) + { + throw new NotEnoughArgumentsException(); + } + } + + setUsersTime(sender, users, ticks, relative); + } + + /** + * Used to get the time and inform + */ + private void getUsersTime(final CommandSender sender, final Collection users) + { + if (users.size() > 1) + { + sender.sendMessage(_("pTimePlayers")); + } + + for (IUser user : users) + { + if (user.getPlayerTimeOffset() == 0) + { + sender.sendMessage(_("pTimeNormal", user.getName())); + } + else + { + String time = DescParseTickFormat.format(user.getPlayerTime()); + if (!user.isPlayerTimeRelative()) + { + sender.sendMessage(_("pTimeCurrentFixed", user.getName(), time)); + } + else + { + sender.sendMessage(_("pTimeCurrent", user.getName(), time)); + } + } + } + } + + /** + * Used to set the time and inform of the change + */ + private void setUsersTime(final CommandSender sender, final Collection users, final Long ticks, Boolean relative) + { + // Update the time + if (ticks == null) + { + // Reset + for (IUser user : users) + { + user.resetPlayerTime(); + } + } + else + { + // Set + for (IUser user : users) + { + final World world = user.getWorld(); + long time = user.getPlayerTime(); + time -= time % 24000; + time += 24000 + ticks; + if (relative) + { + time -= world.getTime(); + } + user.setPlayerTime(time, relative); + } + } + + final StringBuilder msg = new StringBuilder(); + for (IUser user : users) + { + if (msg.length() > 0) + { + msg.append(", "); + } + + msg.append(user.getName()); + } + + // Inform the sender of the change + if (ticks == null) + { + sender.sendMessage(_("pTimeReset", msg.toString())); + } + else + { + String time = DescParseTickFormat.format(ticks); + if (!relative) + { + sender.sendMessage(_("pTimeSetFixed", time, msg.toString())); + } + else + { + sender.sendMessage(_("pTimeSet", time, msg.toString())); + } + } + } + + /** + * Used to parse an argument of the type "users(s) selector" + */ + private Set getUsers(final CommandSender sender, final String selector) throws Exception + { + final Set users = new TreeSet(); + // If there is no selector we want the sender itself. Or all users if sender isn't a user. + if (selector == null) + { + final IUser user = sender instanceof Player ? ess.getUser((Player)sender) : null; + if (user == null) + { + for (Player player : server.getOnlinePlayers()) + { + users.add(ess.getUser(player)); + } + } + else + { + users.add(user); + } + return users; + } + + // Try to find the user with name = selector + IUser user = null; + final List matchedPlayers = server.matchPlayer(selector); + if (!matchedPlayers.isEmpty()) + { + user = ess.getUser(matchedPlayers.get(0)); + } + + if (user != null) + { + users.add(user); + } + // If that fails, Is the argument something like "*" or "all"? + else if (selector.equalsIgnoreCase("*") || selector.equalsIgnoreCase("all")) + { + for (Player player : server.getOnlinePlayers()) + { + users.add(ess.getUser(player)); + } + } + // We failed to understand the world target... + else + { + throw new Exception(_("playerNotFound")); + } + + return users; + } +} diff --git a/Essentials/src/net/ess3/commands/Commandr.java b/Essentials/src/net/ess3/commands/Commandr.java new file mode 100644 index 000000000..0dc62ea6d --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandr.java @@ -0,0 +1,84 @@ +package net.ess3.commands; + +import net.ess3.Console; +import static net.ess3.I18n._; +import net.ess3.utils.Util; +import net.ess3.api.IReplyTo; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import org.bukkit.entity.Player; + + +public class Commandr extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + String message = getFinalArg(args, 0); + IReplyTo replyTo; + String senderName; + + if (sender instanceof Player) + { + IUser user = ess.getUser((Player)sender); + if (Permissions.MSG_COLOR.isAuthorized(user)) + { + message = Util.replaceColor(message); + } + else + { + message = Util.stripColor(message); + } + replyTo = user; + senderName = user.getDisplayName(); + } + else + { + message = Util.replaceColor(message); + replyTo = Console.getConsoleReplyTo(); + senderName = Console.NAME; + } + + final CommandSender target = replyTo.getReplyTo(); + final String targetName = target instanceof Player ? ((Player)target).getDisplayName() : Console.NAME; + + if (target == null || ((target instanceof Player) && !((Player)target).isOnline())) + { + throw new Exception(_("foreverAlone")); + } + + sender.sendMessage(_("msgFormat", _("me"), targetName, message)); + if (target instanceof Player) + { + IUser player = ess.getUser((Player)target); + if (player.isIgnoringPlayer(sender instanceof Player ? ((Player)sender).getName() : Console.NAME)) + { + return; + } + } + target.sendMessage(_("msgFormat", senderName, _("me"), message)); + replyTo.setReplyTo(target); + if (target != sender) + { + if (target instanceof Player) + { + ess.getUser((Player)target).setReplyTo(sender); + } + else + { + Console.getConsoleReplyTo().setReplyTo(sender); + } + } + } + + @Override + public String getPermissionName() + { + return "essentials.msg"; + } +} diff --git a/Essentials/src/net/ess3/commands/Commandrealname.java b/Essentials/src/net/ess3/commands/Commandrealname.java new file mode 100644 index 000000000..f699f2417 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandrealname.java @@ -0,0 +1,43 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.utils.Util; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; + +import java.util.Locale; +import lombok.Cleanup; +import org.bukkit.entity.Player; + + +public class Commandrealname extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + @Cleanup + final ISettings settings = ess.getSettings(); + final String whois = args[0].toLowerCase(Locale.ENGLISH); + for (Player onlinePlayer : server.getOnlinePlayers()) + { + final IUser u = ess.getUser(onlinePlayer); + if (u.isHidden()) + { + continue; + } + final String displayName = Util.stripColor(u.getDisplayName()).toLowerCase(Locale.ENGLISH); + settings.acquireReadLock(); + if (!whois.equals(displayName) + && !displayName.equals(Util.stripColor(settings.getData().getChat().getNicknamePrefix()) + whois) + && !whois.equalsIgnoreCase(u.getName())) + { + continue; + } + sender.sendMessage(u.getDisplayName() + " " + _("is") + " " + u.getName()); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandremove.java b/Essentials/src/net/ess3/commands/Commandremove.java new file mode 100644 index 000000000..8339b13a2 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandremove.java @@ -0,0 +1,155 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; + +import java.util.Locale; +import org.bukkit.Chunk; +import org.bukkit.World; +import org.bukkit.entity.*; + + +public class Commandremove extends EssentialsCommand +{ + private enum ToRemove + { + DROPS, + ARROWS, + BOATS, + MINECARTS, + XP, + PAINTINGS + } + + @Override + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + ToRemove toRemove; + final World world = user.getWorld(); + int radius = 0; + + if (args.length < 2) + { + try + { + radius = Integer.parseInt(args[1]); + } + catch (NumberFormatException e) + { + throw new Exception(_("numberRequired")); + } + } + + try + { + toRemove = ToRemove.valueOf(args[0].toUpperCase(Locale.ENGLISH)); + } + catch (IllegalArgumentException e) + { + throw new NotEnoughArgumentsException(); //TODO: translate and list types + } + + removeEntities(user, world, toRemove, radius); + } + + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 2) + { + throw new NotEnoughArgumentsException(); + } + World world; + world = ess.getWorld(args[1]); + + if (world == null) + { + throw new Exception(_("invalidWorld")); + } + ToRemove toRemove; + try + { + toRemove = ToRemove.valueOf(args[0].toUpperCase(Locale.ENGLISH)); + } + catch (IllegalArgumentException e) + { + throw new NotEnoughArgumentsException(); //TODO: translate and list types + } + removeEntities(sender, world, toRemove, 0); + } + + protected void removeEntities(final CommandSender sender, final World world, final ToRemove toRemove, int radius) throws Exception + { + int removed = 0; + if (radius > 0) + { + radius *= radius; + } + for (Chunk chunk : world.getLoadedChunks()) + { + for (Entity e : chunk.getEntities()) + { + if (radius > 0) + { + if (((Player)sender).getLocation().distanceSquared(e.getLocation()) > radius) + { + continue; + } + } + if (toRemove == ToRemove.DROPS) + { + if (e instanceof Item) + { + e.remove(); + removed++; + } + } + else if (toRemove == ToRemove.ARROWS) + { + if (e instanceof Projectile) + { + e.remove(); + removed++; + } + } + else if (toRemove == ToRemove.BOATS) + { + if (e instanceof Boat) + { + e.remove(); + removed++; + } + } + else if (toRemove == ToRemove.DROPS) + { + if (e instanceof Minecart) + { + e.remove(); + removed++; + } + } + else if (toRemove == ToRemove.XP) + { + if (e instanceof ExperienceOrb) + { + e.remove(); + removed++; + } + } + else if (toRemove == ToRemove.PAINTINGS) + { + if (e instanceof Painting) + { + e.remove(); + removed++; + } + } + } + } + sender.sendMessage(_("removed", removed)); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandrepair.java b/Essentials/src/net/ess3/commands/Commandrepair.java new file mode 100644 index 000000000..e1845e76b --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandrepair.java @@ -0,0 +1,137 @@ +package net.ess3.commands; + +import net.ess3.api.ChargeException; +import static net.ess3.I18n._; +import net.ess3.economy.Trade; +import net.ess3.utils.Util; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + + +public class Commandrepair extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + if (args[0].equalsIgnoreCase("hand")) + { + final ItemStack item = user.getItemInHand(); + if (item == null) + { + throw new Exception(_("repairInvalidType")); + } + + if (!item.getEnchantments().isEmpty() + && !Permissions.REPAIR_ENCHANTED.isAuthorized(user)) + { + throw new Exception(_("repairEnchanted")); + } + + final String itemName = item.getType().toString().toLowerCase(Locale.ENGLISH); + final Trade charge = new Trade("repair-" + itemName.replace('_', '-'), ess); + + charge.isAffordableFor(user); + + repairItem(item); + + charge.charge(user); + + user.sendMessage(_("repair", itemName.replace('_', ' '))); + } + else if (args[0].equalsIgnoreCase("all")) + { + final List repaired = new ArrayList(); + repairItems(user.getInventory().getContents(), user, repaired); + + if (Permissions.REPAIR_ARMOR.isAuthorized(user)) + { + repairItems(user.getInventory().getArmorContents(), user, repaired); + } + + if (repaired.isEmpty()) + { + throw new Exception(_("repairNone")); + } + else + { + user.sendMessage(_("repair", Util.joinList(repaired))); + } + + } + else + { + throw new NotEnoughArgumentsException(); + } + } + + private void repairItem(final ItemStack item) throws Exception + { + final Material material = Material.getMaterial(item.getTypeId()); + if (material.isBlock() || material.getMaxDurability() < 1) + { + throw new Exception(_("repairInvalidType")); + } + + if (item.getDurability() == 0) + { + throw new Exception(_("repairAlreadyFixed")); + } + + item.setDurability((short)0); + } + + private void repairItems(final ItemStack[] items, final IUser user, final List repaired) + { + for (ItemStack item : items) + { + if (item == null) + { + continue; + } + final String itemName = item.getType().toString().toLowerCase(Locale.ENGLISH); + final Trade charge = new Trade("repair-" + itemName.replace('_', '-'), ess); + try + { + charge.isAffordableFor(user); + } + catch (ChargeException ex) + { + user.sendMessage(ex.getMessage()); + continue; + } + if (!item.getEnchantments().isEmpty() + && !Permissions.REPAIR_ENCHANTED.isAuthorized(user)) + { + continue; + } + + try + { + repairItem(item); + } + catch (Exception e) + { + continue; + } + try + { + charge.charge(user); + } + catch (ChargeException ex) + { + user.sendMessage(ex.getMessage()); + } + repaired.add(itemName.replace('_', ' ')); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandrules.java b/Essentials/src/net/ess3/commands/Commandrules.java new file mode 100644 index 000000000..7681b987e --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandrules.java @@ -0,0 +1,19 @@ +package net.ess3.commands; + +import net.ess3.utils.textreader.IText; +import net.ess3.utils.textreader.KeywordReplacer; +import net.ess3.utils.textreader.TextInput; +import net.ess3.utils.textreader.TextPager; + + +public class Commandrules extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + final IText input = new TextInput(sender, "rules", true, ess); + final IText output = new KeywordReplacer(input, sender, ess); + final TextPager pager = new TextPager(output); + pager.showPage(args.length > 0 ? args[0] : null, args.length > 1 ? args[1] : null, "rules", sender); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandseen.java b/Essentials/src/net/ess3/commands/Commandseen.java new file mode 100644 index 000000000..9c5889bdd --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandseen.java @@ -0,0 +1,53 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; + +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import net.ess3.user.UserData.TimestampType; +import net.ess3.utils.DateUtil; +import lombok.Cleanup; + + +public class Commandseen extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + seen(sender,args,true); + } + + @Override + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + seen(user,args,Permissions.SEEN_BANREASON.isAuthorized(user)); + } + + protected void seen (final CommandSender sender, final String[] args, final boolean show) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + try + { + IUser u = getPlayer(args, 0); + sender.sendMessage(_("seenOnline", u.getDisplayName(), DateUtil.formatDateDiff(u.getTimestamp(TimestampType.LOGIN)))); + } + catch (NoSuchFieldException e) + { + @Cleanup + IUser u = ess.getUser(args[0]); + u.acquireReadLock(); + if (u == null) + { + throw new Exception(_("playerNotFound")); + } + sender.sendMessage(_("seenOffline", u.getDisplayName(), DateUtil.formatDateDiff(u.getTimestamp(TimestampType.LOGOUT)))); + if (u.isBanned()) + { + sender.sendMessage(_("whoisBanned", show ? u.getData().getBan().getReason() : _("true"))); + } + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandsell.java b/Essentials/src/net/ess3/commands/Commandsell.java new file mode 100644 index 000000000..a4e73661d --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandsell.java @@ -0,0 +1,152 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.economy.Trade; +import net.ess3.utils.Util; +import net.ess3.api.IUser; +import net.ess3.craftbukkit.InventoryWorkaround; +import java.util.Locale; +import java.util.logging.Level; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + + +public class Commandsell extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + ItemStack is = null; + if (args[0].equalsIgnoreCase("hand")) + { + is = user.getItemInHand(); + } + else if (args[0].equalsIgnoreCase("inventory") || args[0].equalsIgnoreCase("invent") || args[0].equalsIgnoreCase("all")) + { + for (ItemStack stack : user.getInventory().getContents()) + { + if (stack == null || stack.getType() == Material.AIR) + { + continue; + } + try + { + sellItem(user, stack, args, true); + } + catch (Exception e) + { + } + } + return; + } + else if (args[0].equalsIgnoreCase("blocks")) + { + for (ItemStack stack : user.getInventory().getContents()) + { + if (stack == null || stack.getTypeId() > 255 || stack.getType() == Material.AIR) + { + continue; + } + try + { + sellItem(user, stack, args, true); + } + catch (Exception e) + { + } + } + return; + } + if (is == null) + { + is = ess.getItemDb().get(args[0]); + } + sellItem(user, is, args, false); + } + + private void sellItem(IUser user, ItemStack is, String[] args, boolean isBulkSell) throws Exception + { + if (is == null || is.getType() == Material.AIR) + { + throw new Exception(_("itemSellAir")); + } + int id = is.getTypeId(); + int amount = 0; + if (args.length > 1) + { + amount = Integer.parseInt(args[1].replaceAll("[^0-9]", "")); + if (args[1].startsWith("-")) + { + amount = -amount; + } + } + double worth = ess.getWorth().getPrice(is); + boolean stack = args.length > 1 && args[1].endsWith("s"); + + if (Double.isNaN(worth)) + { + throw new Exception(_("itemCannotBeSold")); + } + + + int max = 0; + for (ItemStack s : user.getInventory().getContents()) + { + if (s == null) + { + continue; + } + if (s.getTypeId() != is.getTypeId()) + { + continue; + } + if (s.getDurability() != is.getDurability()) + { + continue; + } + if (!s.getEnchantments().equals(is.getEnchantments())) + { + continue; + } + max += s.getAmount(); + } + + if (stack) + { + amount *= is.getType().getMaxStackSize(); + } + if (amount < 1) + { + amount += max; + } + + if (amount > max || amount < 1) + { + if (!isBulkSell) + { + user.sendMessage(_("itemNotEnough1")); + user.sendMessage(_("itemNotEnough2")); + throw new Exception(_("itemNotEnough3")); + } + else + { + return; + } + } + + //TODO: Prices for Enchantments + final ItemStack ris = is.clone(); + ris.setAmount(amount); + InventoryWorkaround.removeItem(user.getInventory(), true, true, ris); + user.updateInventory(); + Trade.log("Command", "Sell", "Item", user.getName(), new Trade(ris, ess), user.getName(), new Trade(worth * amount, ess), user.getLocation(), ess); + user.giveMoney(worth * amount); + user.sendMessage(_("itemSold", Util.displayCurrency(worth * amount, ess), amount, is.getType().toString().toLowerCase(Locale.ENGLISH), Util.displayCurrency(worth, ess))); + logger.log(Level.INFO, _("itemSoldConsole", user.getDisplayName(), is.getType().toString().toLowerCase(Locale.ENGLISH), Util.displayCurrency(worth * amount, ess), amount, Util.displayCurrency(worth, ess))); + + } +} diff --git a/Essentials/src/net/ess3/commands/Commandsethome.java b/Essentials/src/net/ess3/commands/Commandsethome.java new file mode 100644 index 000000000..91b07286d --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandsethome.java @@ -0,0 +1,93 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import java.util.HashMap; +import java.util.Locale; +import lombok.Cleanup; + + +public class Commandsethome extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, String[] args) throws Exception + { + if (args.length > 0) + { + //Allowing both formats /sethome khobbits house | /sethome khobbits:house + final String[] nameParts = args[0].split(":"); + if (nameParts[0].length() != args[0].length()) + { + args = nameParts; + } + + if (args.length < 2) + { + if (Permissions.SETHOME_MULTIPLE.isAuthorized(user)) + { + if ("bed".equals(args[0].toLowerCase(Locale.ENGLISH))) { + throw new NotEnoughArgumentsException(); + } + if ((user.getHomes().size() < ess.getRanks().getHomeLimit(user)) + || (user.getHomes().contains(args[0].toLowerCase(Locale.ENGLISH)))) + { + user.acquireWriteLock(); + if (user.getData().getHomes() == null) + { + user.getData().setHomes(new HashMap()); + } + user.getData().getHomes().put(args[0].toLowerCase(Locale.ENGLISH), new net.ess3.storage.StoredLocation(user.getLocation())); + } + else + { + throw new Exception(_("maxHomes", ess.getRanks().getHomeLimit(user))); + } + + } + else + { + throw new Exception(_("maxHomes", 1)); + } + } + else + { + if (Permissions.SETHOME_OTHERS.isAuthorized(user)) + { + @Cleanup + IUser usersHome = ess.getUser(ess.getServer().getPlayer(args[0])); + if (usersHome == null) + { + throw new Exception(_("playerNotFound")); + } + String name = args[1].toLowerCase(Locale.ENGLISH); + if (!Permissions.SETHOME_MULTIPLE.isAuthorized(user)) + { + name = "home"; + } + if ("bed".equals(name.toLowerCase(Locale.ENGLISH))) { + throw new NotEnoughArgumentsException(); + } + + usersHome.acquireWriteLock(); + if (usersHome.getData().getHomes() == null) + { + usersHome.getData().setHomes(new HashMap()); + } + usersHome.getData().getHomes().put(name, new net.ess3.storage.StoredLocation(user.getLocation())); + } + } + } + else + { + user.acquireWriteLock(); + if (user.getData().getHomes() == null) + { + user.getData().setHomes(new HashMap()); + } + user.getData().getHomes().put("home", new net.ess3.storage.StoredLocation(user.getLocation())); + } + user.sendMessage(_("homeSet")); + + } +} diff --git a/Essentials/src/net/ess3/commands/Commandsetjail.java b/Essentials/src/net/ess3/commands/Commandsetjail.java new file mode 100644 index 000000000..344b41fc9 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandsetjail.java @@ -0,0 +1,20 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; + + +public class Commandsetjail extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + ess.getJails().setJail(args[0], user.getLocation()); + user.sendMessage(_("jailSet", args[0])); + + } +} diff --git a/Essentials/src/net/ess3/commands/Commandsetspawn.java b/Essentials/src/net/ess3/commands/Commandsetspawn.java new file mode 100644 index 000000000..ccf319892 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandsetspawn.java @@ -0,0 +1,17 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.settings.SpawnsHolder; + + +public class Commandsetspawn extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + final String group = args.length > 0 ? getFinalArg(args, 0) : "default"; + ((SpawnsHolder)module).setSpawn(user.getLocation(), group); + user.sendMessage(_("spawnSet", group)); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandsetwarp.java b/Essentials/src/net/ess3/commands/Commandsetwarp.java new file mode 100644 index 000000000..5ec5382c1 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandsetwarp.java @@ -0,0 +1,47 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.api.IWarps; +import org.bukkit.Location; + + +public class Commandsetwarp extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + if (args[0].matches("[0-9]+")) + { + throw new NotEnoughArgumentsException(); + } + + final Location loc = user.getLocation(); + final IWarps warps = ess.getWarps(); + Location warpLoc = null; + + try + { + warpLoc = warps.getWarp(args[0]); + } + catch (WarpNotFoundException ex) + { + } + + if (warpLoc == null || user.hasPermission("essentials.warp.overwrite." + args[0])) + { + warps.setWarp(args[0], loc); + } + else + { + throw new Exception(_("warpOverwrite")); + } + + user.sendMessage(_("warpSet", args[0])); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandsetworth.java b/Essentials/src/net/ess3/commands/Commandsetworth.java new file mode 100644 index 000000000..3ea844f69 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandsetworth.java @@ -0,0 +1,48 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import org.bukkit.inventory.ItemStack; + + +public class Commandsetworth extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 2) + { + throw new NotEnoughArgumentsException(); + } + + ItemStack stack; + String price; + + if (args.length == 1) + { + stack = user.getInventory().getItemInHand(); + price = args[0]; + } + else + { + stack = ess.getItemDb().get(args[0]); + price = args[1]; + } + + ess.getWorth().setPrice(stack, Double.parseDouble(price)); + user.sendMessage(_("worthSet")); + } + + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 2) + { + throw new NotEnoughArgumentsException(); + } + + ItemStack stack = ess.getItemDb().get(args[0]); + ess.getWorth().setPrice(stack, Double.parseDouble(args[1])); + sender.sendMessage(_("worthSet")); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandsocialspy.java b/Essentials/src/net/ess3/commands/Commandsocialspy.java new file mode 100644 index 000000000..c466af842 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandsocialspy.java @@ -0,0 +1,14 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; + + +public class Commandsocialspy extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + user.sendMessage("§7SocialSpy " + (user.toggleSocialSpy() ? _("enabled") : _("disabled"))); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandspawn.java b/Essentials/src/net/ess3/commands/Commandspawn.java new file mode 100644 index 000000000..5772cf821 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandspawn.java @@ -0,0 +1,54 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.economy.Trade; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import net.ess3.settings.SpawnsHolder; +import org.bukkit.Location; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + + +public class Commandspawn extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + final Trade charge = new Trade(commandName, ess); + charge.isAffordableFor(user); + if (args.length > 0 && Permissions.SPAWN_OTHERS.isAuthorized(user)) + { + final IUser otherUser = getPlayer(args, 0); + respawn(otherUser, null); + if (!otherUser.equals(user)) + { + otherUser.sendMessage(_("teleportAtoB", user.getDisplayName(), "spawn")); + user.sendMessage(_("teleporting")); + } + } + else + { + respawn(user, null); + } + } + + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + final IUser user = getPlayer(args, 0); + respawn(user, null); + user.sendMessage(_("teleportAtoB", user.getDisplayName(), "spawn")); + sender.sendMessage(_("teleporting")); + } + + private void respawn(final IUser user, final Trade charge) throws Exception + { + final SpawnsHolder spawns = (SpawnsHolder)this.module; + final Location spawn = spawns.getSpawn(ess.getRanks().getMainGroup(user)); + user.getTeleport().teleport(spawn, charge, TeleportCause.COMMAND); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandspawner.java b/Essentials/src/net/ess3/commands/Commandspawner.java new file mode 100644 index 000000000..8d0993cb1 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandspawner.java @@ -0,0 +1,58 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.bukkit.Mob; +import net.ess3.economy.Trade; +import net.ess3.api.IUser; +import net.ess3.permissions.SpawnerPermissions; +import net.ess3.utils.LocationUtil; +import net.ess3.utils.Util; +import java.util.Locale; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.CreatureSpawner; + + +public class Commandspawner extends EssentialsCommand +{ + @Override + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1 || args[0].length() < 2) + { + throw new NotEnoughArgumentsException(_("mobsAvailable", Util.joinList(Mob.getMobList()))); + } + + final Location target = LocationUtil.getTarget(user); + if (target == null || target.getBlock().getType() != Material.MOB_SPAWNER) + { + throw new Exception(_("mobSpawnTarget")); + } + + try + { + String name = args[0]; + + Mob mob = null; + mob = Mob.fromName(name); + if (mob == null) + { + user.sendMessage(_("invalidMob")); + return; + } + if (!SpawnerPermissions.getPermission(mob.name).isAuthorized(user)) + { + throw new Exception(_("unableToSpawnMob")); + } + final Trade charge = new Trade("spawner-" + mob.name.toLowerCase(Locale.ENGLISH), ess); + charge.isAffordableFor(user); + ((CreatureSpawner)target.getBlock().getState()).setSpawnedType(mob.getType()); + charge.charge(user); + user.sendMessage(_("setSpawner", mob.name)); + } + catch (Throwable ex) + { + throw new Exception(_("mobSpawnError"), ex); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandspawnmob.java b/Essentials/src/net/ess3/commands/Commandspawnmob.java new file mode 100644 index 000000000..c836589da --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandspawnmob.java @@ -0,0 +1,281 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.bukkit.Mob; +import net.ess3.bukkit.Mob.MobException; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.permissions.SpawnmobPermissions; +import net.ess3.utils.LocationUtil; +import net.ess3.utils.Util; +import java.util.HashSet; +import java.util.Locale; +import java.util.Random; +import java.util.Set; +import org.bukkit.DyeColor; +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.entity.*; + + +public class Commandspawnmob extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + final Set mobList = Mob.getMobList(); + final Set availableList = new HashSet(); + for (String mob : mobList) + { + if (SpawnmobPermissions.getPermission(mob).isAuthorized(user)) + { + availableList.add(mob); + } + } + if (availableList.isEmpty()) + { + availableList.add(_("none")); + } + throw new NotEnoughArgumentsException(_("mobsAvailable", Util.joinList(availableList))); + } + + + final String[] mountparts = args[0].split(","); + String[] parts = mountparts[0].split(":"); + String mobType = parts[0]; + String mobData = null; + if (parts.length == 2) + { + mobData = parts[1]; + } + String mountType = null; + String mountData = null; + if (mountparts.length > 1) + { + parts = mountparts[1].split(":"); + mountType = parts[0]; + if (parts.length == 2) + { + mountData = parts[1]; + } + } + + + Entity spawnedMob = null; + Mob mob = null; + Entity spawnedMount = null; + Mob mobMount = null; + + mob = Mob.fromName(mobType); + if (mob == null) + { + throw new Exception(_("invalidMob")); + } + + if (!SpawnmobPermissions.getPermission(mob.name).isAuthorized(user)) + { + throw new Exception(_("noPermToSpawnMob")); + } + + final Block block = LocationUtil.getTarget(user).getBlock(); + if (block == null) + { + throw new Exception(_("unableToSpawnMob")); + } + IUser otherUser = null; + if (args.length >= 3) + { + otherUser = getPlayer(args, 2); + } + final Location loc = (otherUser == null) ? block.getLocation() : otherUser.getLocation(); + final Location sloc = LocationUtil.getSafeDestination(loc); + try + { + spawnedMob = mob.spawn(user, server, sloc); + } + catch (MobException e) + { + throw new Exception(_("unableToSpawnMob")); + } + + if (mountType != null) + { + mobMount = Mob.fromName(mountType); + if (mobMount == null) + { + user.sendMessage(_("invalidMob")); + return; + } + + if (!SpawnmobPermissions.getPermission(mobMount.name).isAuthorized(user)) + { + throw new Exception(_("noPermToSpawnMob")); + } + try + { + spawnedMount = mobMount.spawn(user, server, loc); + } + catch (MobException e) + { + throw new Exception(_("unableToSpawnMob")); + } + spawnedMob.setPassenger(spawnedMount); + } + if (mobData != null) + { + changeMobData(mob.getType(), spawnedMob, mobData, user); + } + if (spawnedMount != null && mountData != null) + { + changeMobData(mobMount.getType(), spawnedMount, mountData, user); + } + if (args.length >= 2) + { + int mobCount = Integer.parseInt(args[1]); + int serverLimit = 1; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try + { + serverLimit = settings.getData().getCommands().getSpawnmob().getLimit(); + } + finally + { + settings.unlock(); + } + if (mobCount > serverLimit) + { + mobCount = serverLimit; + user.sendMessage(_("mobSpawnLimit")); + } + + try + { + for (int i = 1; i < mobCount; i++) + { + spawnedMob = mob.spawn(user, server, loc); + if (mobMount != null) + { + try + { + spawnedMount = mobMount.spawn(user, server, loc); + } + catch (MobException e) + { + throw new Exception(_("unableToSpawnMob")); + } + spawnedMob.setPassenger(spawnedMount); + } + if (mobData != null) + { + changeMobData(mob.getType(), spawnedMob, mobData, user); + } + if (spawnedMount != null && mountData != null) + { + changeMobData(mobMount.getType(), spawnedMount, mountData, user); + } + } + user.sendMessage(mobCount + " " + mob.name.toLowerCase(Locale.ENGLISH) + mob.suffix + " " + _("spawned")); + } + catch (MobException e1) + { + throw new Exception(_("unableToSpawnMob"), e1); + } + catch (NumberFormatException e2) + { + throw new Exception(_("numberRequired"), e2); + } + catch (NullPointerException np) + { + throw new Exception(_("soloMob"), np); + } + } + else + { + user.sendMessage(mob.name + " " + _("spawned")); + } + } + + private void changeMobData(final EntityType type, final Entity spawned, String data, final IUser user) throws Exception + { + data = data.toLowerCase(Locale.ENGLISH); + if (type == EntityType.SLIME || type == EntityType.MAGMA_CUBE) + { + try + { + ((Slime)spawned).setSize(Integer.parseInt(data)); + } + catch (Exception e) + { + throw new Exception(_("slimeMalformedSize"), e); + } + } + if ((type == EntityType.SHEEP + || type == EntityType.COW + || type == EntityType.MUSHROOM_COW + || type == EntityType.CHICKEN + || type == EntityType.PIG + || type == EntityType.VILLAGER + || type == EntityType.OCELOT + || type == EntityType.WOLF) + && data.contains("baby")) + { + ((Animals)spawned).setBaby(); + return; + } + if (type == EntityType.SHEEP) + { + final String color = data.toUpperCase(Locale.ENGLISH).replace("BABY", ""); + try + { + if (color.equals("RANDOM")) + { + Random rand = new Random(); + ((Sheep)spawned).setColor(DyeColor.values()[rand.nextInt(DyeColor.values().length)]); + } + else + { + ((Sheep)spawned).setColor(DyeColor.valueOf(color)); + } + } + catch (Exception e) + { + throw new Exception(_("sheepMalformedColor"), e); + } + } + if ((type == EntityType.WOLF + || type == EntityType.OCELOT) + && data.contains("tamed")) + { + final Tameable tameable = ((Tameable)spawned); + tameable.setTamed(true); + tameable.setOwner(user.getBase()); + } + if (type == EntityType.WOLF + && data.contains("angry")) + { + ((Wolf)spawned).setAngry(true); + } + if (type == EntityType.CREEPER && data.contains("powered")) + { + ((Creeper)spawned).setPowered(true); + } + if (type == EntityType.OCELOT) + { + if (data.contains("siamese")) + { + ((Ocelot)spawned).setCatType(Ocelot.Type.SIAMESE_CAT); + } + if (data.contains("red")) + { + ((Ocelot)spawned).setCatType(Ocelot.Type.RED_CAT); + } + if (data.contains("black")) + { + ((Ocelot)spawned).setCatType(Ocelot.Type.BLACK_CAT); + } + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandsudo.java b/Essentials/src/net/ess3/commands/Commandsudo.java new file mode 100644 index 000000000..d77241348 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandsudo.java @@ -0,0 +1,42 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.api.server.CommandSender; +import net.ess3.permissions.Permissions; + + +public class Commandsudo extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 2) + { + throw new NotEnoughArgumentsException(); + } + + final IUser user = getPlayer(args, 0, false); + final String command = args[1]; + final String[] arguments = new String[args.length - 2]; + if (arguments.length > 0) + { + System.arraycopy(args, 2, arguments, 0, args.length - 2); + } + + if (Permissions.SUDO_EXEMPT.isAuthorized(user)) + { + throw new Exception(_("sudoExempt")); + } + + sender.sendMessage(_("sudoRun", user.getDisplayName(), command, getFinalArg(arguments, 0))); + + ess.getServer().dispatchCommand(user, command); + final PluginCommand execCommand = ess.getServer().getPluginCommand(command); + if (execCommand != null) + { + execCommand.execute(user.getBase(), command, arguments); + } + + } +} diff --git a/Essentials/src/net/ess3/commands/Commandsuicide.java b/Essentials/src/net/ess3/commands/Commandsuicide.java new file mode 100644 index 000000000..d1d666d7c --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandsuicide.java @@ -0,0 +1,18 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; + + +public class Commandsuicide extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + ess.getPlugin().callSuicideEvent(user.getBase()); + user.damage(1000); + user.setHealth(0); + user.sendMessage(_("suicideMessage")); + ess.broadcastMessage(user,_("suicideSuccess", user.getDisplayName())); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandtempban.java b/Essentials/src/net/ess3/commands/Commandtempban.java new file mode 100644 index 000000000..209ab8098 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtempban.java @@ -0,0 +1,60 @@ +package net.ess3.commands; + +import net.ess3.Console; +import static net.ess3.I18n._; + +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import net.ess3.user.Ban; +import net.ess3.utils.DateUtil; +import org.bukkit.entity.Player; + + +public class Commandtempban extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 2) + { + throw new NotEnoughArgumentsException(); + } + final IUser user = getPlayer(args, 0, true); + if (!user.isOnline()) + { + if (Permissions.TEMPBAN_OFFLINE.isAuthorized(sender)) + { + sender.sendMessage(_("tempbanExempt")); + return; + } + } + else + { + if (Permissions.TEMPBAN_EXEMPT.isAuthorized(user)) + { + sender.sendMessage(_("tempbanExempt")); + return; + } + } + final String time = getFinalArg(args, 1); + final long banTimestamp = DateUtil.parseDateDiff(time, true); + + final String banReason = _("tempBanned", DateUtil.formatDateDiff(banTimestamp)); + user.acquireWriteLock(); + user.getData().setBan(new Ban()); + user.getData().getBan().setReason(banReason); + user.getData().getBan().setTimeout(banTimestamp); + user.setBanned(true); + user.kickPlayer(banReason); + final String senderName = sender instanceof Player ? ((Player)sender).getDisplayName() : Console.NAME; + + for (Player onlinePlayer : server.getOnlinePlayers()) + { + final IUser player = ess.getUser(onlinePlayer); + if (Permissions.BAN_NOTIFY.isAuthorized(player)) + { + onlinePlayer.sendMessage(_("playerBanned", senderName, user.getName(), banReason)); + } + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandthunder.java b/Essentials/src/net/ess3/commands/Commandthunder.java new file mode 100644 index 000000000..eb7d9e1e2 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandthunder.java @@ -0,0 +1,35 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import org.bukkit.World; + + +public class Commandthunder extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + final World world = user.getWorld(); + final boolean setThunder = args[0].equalsIgnoreCase("true"); + if (args.length > 1) + { + + world.setThundering(setThunder ? true : false); + world.setThunderDuration(Integer.parseInt(args[1]) * 20); + user.sendMessage(_("thunderDuration", (setThunder ? _("enabled") : _("disabled")), Integer.parseInt(args[1]))); + + } + else + { + world.setThundering(setThunder ? true : false); + user.sendMessage(_("thunder", setThunder ? _("enabled") : _("disabled"))); + } + + } +} diff --git a/Essentials/src/net/ess3/commands/Commandtime.java b/Essentials/src/net/ess3/commands/Commandtime.java new file mode 100644 index 000000000..8ba2ff13f --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtime.java @@ -0,0 +1,148 @@ +package net.ess3.commands; + +import net.ess3.utils.DescParseTickFormat; +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import java.util.*; +import org.bukkit.World; +import org.bukkit.entity.Player; + + +public class Commandtime extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + // Which World(s) are we interested in? + String worldSelector = null; + if (args.length == 2) + { + worldSelector = args[1]; + } + final Set worlds = getWorlds(sender, worldSelector); + + // If no arguments we are reading the time + if (args.length == 0) + { + getWorldsTime(sender, worlds); + return; + } + + if (Permissions.TIME_SET.isAuthorized(sender)) + { + sender.sendMessage(_("timeSetPermission")); + return; + } + + // Parse the target time int ticks from args[0] + long ticks; + try + { + ticks = DescParseTickFormat.parse(args[0]); + } + catch (NumberFormatException e) + { + throw new NotEnoughArgumentsException(); + } + + setWorldsTime(sender, worlds, ticks); + } + + /** + * Used to get the time and inform + */ + private void getWorldsTime(final CommandSender sender, final Collection worlds) + { + if (worlds.size() == 1) + { + final Iterator iter = worlds.iterator(); + sender.sendMessage(DescParseTickFormat.format(iter.next().getTime())); + return; + } + + for (World world : worlds) + { + sender.sendMessage(_("timeWorldCurrent", world.getName(), DescParseTickFormat.format(world.getTime()))); + } + } + + /** + * Used to set the time and inform of the change + */ + private void setWorldsTime(final CommandSender sender, final Collection worlds, final long ticks) + { + // Update the time + for (World world : worlds) + { + long time = world.getTime(); + time -= time % 24000; + world.setTime(time + 24000 + ticks); + } + + final StringBuilder output = new StringBuilder(); + for (World world : worlds) + { + if (output.length() > 0) + { + output.append(", "); + } + + output.append(world.getName()); + } + + sender.sendMessage(_("timeWorldSet", DescParseTickFormat.format(ticks), output.toString())); + } + + /** + * Used to parse an argument of the type "world(s) selector" + */ + private Set getWorlds(final CommandSender sender, final String selector) throws Exception + { + final Set worlds = new TreeSet(new WorldNameComparator()); + + // If there is no selector we want the world the user is currently in. Or all worlds if it isn't a user. + if (selector == null) + { + final IUser user = sender instanceof Player ? ess.getUser((Player)sender) : null; + if (user == null) + { + worlds.addAll(server.getWorlds()); + } + else + { + worlds.add(user.getWorld()); + } + return worlds; + } + + // Try to find the world with name = selector + final World world = server.getWorld(selector); + if (world != null) + { + worlds.add(world); + } + // If that fails, Is the argument something like "*" or "all"? + else if (selector.equalsIgnoreCase("*") || selector.equalsIgnoreCase("all")) + { + worlds.addAll(server.getWorlds()); + } + // We failed to understand the world target... + else + { + throw new Exception(_("invalidWorld")); + } + + return worlds; + } +} + + +class WorldNameComparator implements Comparator +{ + @Override + public int compare(final World a, final World b) + { + return a.getName().compareTo(b.getName()); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandtogglejail.java b/Essentials/src/net/ess3/commands/Commandtogglejail.java new file mode 100644 index 000000000..ca781c23f --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtogglejail.java @@ -0,0 +1,104 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; + +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import net.ess3.user.UserData.TimestampType; +import net.ess3.utils.DateUtil; +import lombok.Cleanup; + + +public class Commandtogglejail extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + @Cleanup + final IUser player = getPlayer(args, 0, true); + player.acquireReadLock(); + + if (args.length >= 2 && !player.getData().isJailed()) + { + if (!player.isOnline()) + { + if (Permissions.TOGGLEJAIL_OFFLINE.isAuthorized(sender)) + { + sender.sendMessage(_("mayNotJail")); + return; + } + } + else + { + if (Permissions.JAIL_EXEMPT.isAuthorized(player)) + { + sender.sendMessage(_("mayNotJail")); + return; + } + } + if (player.isOnline()) + { + ess.getJails().sendToJail(player, args[1]); + } + else + { + // Check if jail exists + ess.getJails().getJail(args[1]); + } + player.acquireWriteLock(); + player.getData().setJailed(true); + player.sendMessage(_("userJailed")); + player.getData().setJail(args[1]); + long timeDiff = 0; + if (args.length > 2) + { + final String time = getFinalArg(args, 2); + timeDiff = DateUtil.parseDateDiff(time, true); + player.setTimestamp(TimestampType.JAIL, timeDiff); + } + sender.sendMessage((timeDiff > 0 + ? _("playerJailedFor", player.getName(), DateUtil.formatDateDiff(timeDiff)) + : _("playerJailed", player.getName()))); + return; + } + + if (args.length >= 2 && player.getData().isJailed() && !args[1].equalsIgnoreCase(player.getData().getJail())) + { + sender.sendMessage(_("jailAlreadyIncarcerated", player.getData().getJail())); + return; + } + + if (args.length >= 2 && player.getData().isJailed() && args[1].equalsIgnoreCase(player.getData().getJail())) + { + final String time = getFinalArg(args, 2); + final long timeDiff = DateUtil.parseDateDiff(time, true); + player.acquireWriteLock(); + player.setTimestamp(TimestampType.JAIL, timeDiff); + sender.sendMessage(_("jailSentenceExtended", DateUtil.formatDateDiff(timeDiff))); + return; + } + + if (args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase(player.getData().getJail()))) + { + if (!player.getData().isJailed()) + { + throw new NotEnoughArgumentsException(); + } + player.acquireWriteLock(); + player.getData().setJailed(false); + player.setTimestamp(TimestampType.JAIL, 0); + player.sendMessage(_("jailReleasedPlayerNotify")); + player.getData().setJail(null); + if (player.isOnline()) + { + player.getTeleport().back(); + } + sender.sendMessage(_("jailReleased", player.getName())); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandtop.java b/Essentials/src/net/ess3/commands/Commandtop.java new file mode 100644 index 000000000..3298f8acd --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtop.java @@ -0,0 +1,21 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.economy.Trade; +import net.ess3.api.IUser; +import org.bukkit.Location; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + + +public class Commandtop extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + final int topX = user.getLocation().getBlockX(); + final int topZ = user.getLocation().getBlockZ(); + final int topY = user.getWorld().getHighestBlockYAt(topX, topZ); + user.getTeleport().teleport(new Location(user.getWorld(), user.getLocation().getX(), topY + 1, user.getLocation().getZ()), new Trade(commandName, ess), TeleportCause.COMMAND); + user.sendMessage(_("teleportTop")); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandtp.java b/Essentials/src/net/ess3/commands/Commandtp.java new file mode 100644 index 000000000..93bd2a798 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtp.java @@ -0,0 +1,64 @@ +package net.ess3.commands; + +import net.ess3.Console; +import static net.ess3.I18n._; +import net.ess3.economy.Trade; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import lombok.Cleanup; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + + +public class Commandtp extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + switch (args.length) + { + case 0: + throw new NotEnoughArgumentsException(); + + case 1: + @Cleanup + final IUser player = getPlayer(args, 0); + player.acquireReadLock(); + if (!player.getData().isTeleportEnabled()) + { + throw new Exception(_("teleportDisabled", player.getDisplayName())); + } + user.sendMessage(_("teleporting")); + final Trade charge = new Trade(commandName, ess); + charge.isAffordableFor(user); + user.getTeleport().teleport(player, charge, TeleportCause.COMMAND); + throw new NoChargeException(); + + default: + if (!Permissions.TPOHERE.isAuthorized(user)) + { + throw new Exception(_("needTpohere")); + } + user.sendMessage(_("teleporting")); + final IUser target = getPlayer(args, 0); + final IUser toPlayer = getPlayer(args, 1); + target.getTeleport().now(toPlayer, false, TeleportCause.COMMAND); + target.sendMessage(_("teleportAtoB", user.getDisplayName(), toPlayer.getDisplayName())); + break; + } + } + + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 2) + { + throw new NotEnoughArgumentsException(); + } + + sender.sendMessage(_("teleporting")); + final IUser target = getPlayer(args, 0); + final IUser toPlayer = getPlayer(args, 1); + target.getTeleport().now(toPlayer, false, TeleportCause.COMMAND); + target.sendMessage(_("teleportAtoB", Console.NAME, toPlayer.getDisplayName())); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandtpa.java b/Essentials/src/net/ess3/commands/Commandtpa.java new file mode 100644 index 000000000..84f674538 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtpa.java @@ -0,0 +1,47 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import lombok.Cleanup; + + +public class Commandtpa extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + @Cleanup + IUser player = getPlayer(args, 0); + player.acquireReadLock(); + if (!player.getData().isTeleportEnabled()) + { + throw new Exception(_("teleportDisabled", player.getDisplayName())); + } + if (!player.isIgnoringPlayer(user.getName())) + { + player.requestTeleport(user, false); + player.sendMessage(_("teleportRequest", user.getDisplayName())); + player.sendMessage(_("typeTpaccept")); + player.sendMessage(_("typeTpdeny")); + int tpaAcceptCancellation = 0; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try { + tpaAcceptCancellation = settings.getData().getCommands().getTpa().getTimeout(); + } finally { + settings.unlock(); + } + if (tpaAcceptCancellation != 0) + { + player.sendMessage(_("teleportRequestTimeoutInfo", tpaAcceptCancellation)); + } + } + user.sendMessage(_("requestSent", player.getDisplayName())); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandtpaall.java b/Essentials/src/net/ess3/commands/Commandtpaall.java new file mode 100644 index 000000000..0dbbdd59a --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtpaall.java @@ -0,0 +1,72 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import lombok.Cleanup; +import org.bukkit.entity.Player; + + +public class Commandtpaall extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + if (sender instanceof Player) + { + teleportAAllPlayers(sender, ess.getUser((Player)sender)); + return; + } + throw new NotEnoughArgumentsException(); + } + + final IUser player = getPlayer(args, 0); + teleportAAllPlayers(sender, player); + } + + private void teleportAAllPlayers(final CommandSender sender, final IUser user) + { + sender.sendMessage(_("teleportAAll")); + for (Player onlinePlayer : server.getOnlinePlayers()) + { + @Cleanup + final IUser player = ess.getUser(onlinePlayer); + player.acquireReadLock(); + if (user == player) + { + continue; + } + if (!player.getData().isTeleportEnabled()) + { + continue; + } + try + { + player.requestTeleport(user, true); + player.sendMessage(_("teleportHereRequest", user.getDisplayName())); + player.sendMessage(_("typeTpaccept")); + int tpaAcceptCancellation = 0; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try + { + tpaAcceptCancellation = settings.getData().getCommands().getTpa().getTimeout(); + } + finally + { + settings.unlock(); + } + if (tpaAcceptCancellation != 0) + { + player.sendMessage(_("teleportRequestTimeoutInfo", tpaAcceptCancellation)); + } + } + catch (Exception ex) + { + ess.getCommandHandler().showCommandError(sender, commandName, ex); + } + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandtpaccept.java b/Essentials/src/net/ess3/commands/Commandtpaccept.java new file mode 100644 index 000000000..7aaa58f3e --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtpaccept.java @@ -0,0 +1,75 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.economy.Trade; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + + +public class Commandtpaccept extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (user.getTeleportRequester() == null) + { + throw new Exception(_("noPendingRequest")); + } + + final IUser target = user.getTeleportRequester(); + if (target == null + || !target.isOnline() + || (user.isTeleportRequestHere() && !Permissions.TPAHERE.isAuthorized(target)) + || (!user.isTeleportRequestHere() && !Permissions.TPA.isAuthorized(target) && !Permissions.TPAALL.isAuthorized(target))) + { + throw new Exception(_("noPendingRequest")); + } + + if (args.length > 0 && !target.getName().contains(args[0])) + { + throw new Exception(_("noPendingRequest")); + } + + int tpaAcceptCancellation = 0; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try + { + tpaAcceptCancellation = settings.getData().getCommands().getTpa().getTimeout(); + } + finally + { + settings.unlock(); + } + + if (tpaAcceptCancellation != 0 && (System.currentTimeMillis() - user.getTeleportRequestTime()) / 1000 > tpaAcceptCancellation) + { + user.requestTeleport(null, false); + throw new Exception(_("requestTimedOut")); + } + + final Trade charge = new Trade(commandName, ess); + if (user.isTeleportRequestHere()) + { + charge.isAffordableFor(user); + } + else + { + charge.isAffordableFor(target); + } + user.sendMessage(_("requestAccepted")); + target.sendMessage(_("requestAcceptedFrom", user.getDisplayName())); + + if (user.isTeleportRequestHere()) + { + user.getTeleport().teleport(target, charge, TeleportCause.COMMAND); + } + else + { + target.getTeleport().teleport(user, charge, TeleportCause.COMMAND); + } + user.requestTeleport(null, false); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandtpahere.java b/Essentials/src/net/ess3/commands/Commandtpahere.java new file mode 100644 index 000000000..fc4a30083 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtpahere.java @@ -0,0 +1,46 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import lombok.Cleanup; + + +public class Commandtpahere extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + @Cleanup + final IUser player = getPlayer(args, 0); + player.acquireReadLock(); + if (!player.getData().isTeleportEnabled()) + { + throw new Exception(_("teleportDisabled", player.getDisplayName())); + } + player.requestTeleport(user, true); + player.sendMessage(_("teleportHereRequest", user.getDisplayName())); + player.sendMessage(_("typeTpaccept")); + int tpaAcceptCancellation = 0; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try + { + tpaAcceptCancellation = settings.getData().getCommands().getTpa().getTimeout(); + } + finally + { + settings.unlock(); + } + if (tpaAcceptCancellation != 0) + { + player.sendMessage(_("teleportRequestTimeoutInfo", tpaAcceptCancellation)); + } + user.sendMessage(_("requestSent", player.getDisplayName())); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandtpall.java b/Essentials/src/net/ess3/commands/Commandtpall.java new file mode 100644 index 000000000..db0c676be --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtpall.java @@ -0,0 +1,48 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + + +public class Commandtpall extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + if (sender instanceof Player) + { + teleportAllPlayers(sender, ess.getUser((Player)sender)); + return; + } + throw new NotEnoughArgumentsException(); + } + + final IUser player = getPlayer(args, 0); + teleportAllPlayers(sender, player); + } + + private void teleportAllPlayers(CommandSender sender, IUser user) + { + sender.sendMessage(_("teleportAll")); + for (Player onlinePlayer : server.getOnlinePlayers()) + { + final IUser player = ess.getUser(onlinePlayer); + if (user == player) + { + continue; + } + try + { + player.getTeleport().now(user, false, TeleportCause.COMMAND); + } + catch (Exception ex) + { + ess.getCommandHandler().showCommandError(sender, commandName, ex); + } + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandtpdeny.java b/Essentials/src/net/ess3/commands/Commandtpdeny.java new file mode 100644 index 000000000..e7744939b --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtpdeny.java @@ -0,0 +1,22 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; + + +public class Commandtpdeny extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + final IUser player = user.getTeleportRequester(); + if (player == null) + { + throw new Exception(_("noPendingRequest")); + } + + user.sendMessage(_("requestDenied")); + player.sendMessage(_("requestDeniedFrom", user.getDisplayName())); + user.requestTeleport(null, false); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandtphere.java b/Essentials/src/net/ess3/commands/Commandtphere.java new file mode 100644 index 000000000..c628c3519 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtphere.java @@ -0,0 +1,27 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.economy.Trade; +import net.ess3.api.IUser; +import lombok.Cleanup; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + + +public class Commandtphere extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + @Cleanup + final IUser player = getPlayer(args, 0); + player.acquireReadLock(); + if (!player.getData().isTeleportEnabled()) + { + throw new Exception(_("teleportDisabled", player.getDisplayName())); + } + player.getTeleport().teleport(user, new Trade(commandName, ess), TeleportCause.COMMAND); + user.sendMessage(_("teleporting")); + player.sendMessage(_("teleporting")); + throw new NoChargeException(); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandtpo.java b/Essentials/src/net/ess3/commands/Commandtpo.java new file mode 100644 index 000000000..529fbd8f8 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtpo.java @@ -0,0 +1,38 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + + +public class Commandtpo extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + //Just basically the old tp command + final IUser player = getPlayer(args, 0, true); + // Check if user is offline + if (!player.isOnline()) + { + throw new NoSuchFieldException(_("playerNotFound")); + } + + // Verify permission + if (!player.isHidden() || Permissions.TELEPORT_HIDDEN.isAuthorized(user)) + { + user.getTeleport().now(player, false, TeleportCause.COMMAND); + user.sendMessage(_("teleporting")); + } + else + { + throw new NoSuchFieldException(_("playerNotFound")); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandtpohere.java b/Essentials/src/net/ess3/commands/Commandtpohere.java new file mode 100644 index 000000000..a3f9fcb74 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtpohere.java @@ -0,0 +1,39 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + + +public class Commandtpohere extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + //Just basically the old tphere command + final IUser player = getPlayer(args, 0, true); + + // Check if user is offline + if (!player.isOnline()) + { + throw new NoSuchFieldException(_("playerNotFound")); + } + + // Verify permission + if (!player.isHidden() || Permissions.TELEPORT_HIDDEN.isAuthorized(user)) + { + player.getTeleport().now(user, false, TeleportCause.COMMAND); + user.sendMessage(_("teleporting")); + } + else + { + throw new NoSuchFieldException(_("playerNotFound")); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandtppos.java b/Essentials/src/net/ess3/commands/Commandtppos.java new file mode 100644 index 000000000..abbdeaae9 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtppos.java @@ -0,0 +1,38 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.economy.Trade; +import net.ess3.api.IUser; +import org.bukkit.Location; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + + +public class Commandtppos extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 3) + { + throw new NotEnoughArgumentsException(); + } + + final int x = Integer.parseInt(args[0]); + final int y = Integer.parseInt(args[1]); + final int z = Integer.parseInt(args[2]); + final Location location = new Location(user.getWorld(), x, y, z); + if (args.length > 3) + { + location.setYaw((Float.parseFloat(args[3]) + 180 + 360) % 360); + } + if (args.length > 4) + { + location.setPitch(Float.parseFloat(args[4])); + } + final Trade charge = new Trade(commandName, ess); + charge.isAffordableFor(user); + user.sendMessage(_("teleporting")); + user.getTeleport().teleport(location, charge, TeleportCause.COMMAND); + throw new NoChargeException(); + } +} \ No newline at end of file diff --git a/Essentials/src/net/ess3/commands/Commandtptoggle.java b/Essentials/src/net/ess3/commands/Commandtptoggle.java new file mode 100644 index 000000000..0b525baa3 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtptoggle.java @@ -0,0 +1,16 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; + + +public class Commandtptoggle extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + user.sendMessage(user.toggleTeleportEnabled() + ? _("teleportationEnabled") + : _("teleportationDisabled")); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandtree.java b/Essentials/src/net/ess3/commands/Commandtree.java new file mode 100644 index 000000000..dd498d66a --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtree.java @@ -0,0 +1,57 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.utils.LocationUtil; +import org.bukkit.Location; +import org.bukkit.TreeType; + + +public class Commandtree extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + TreeType tree; + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + else if (args[0].equalsIgnoreCase("birch")) + { + tree = TreeType.BIRCH; + } + else if (args[0].equalsIgnoreCase("redwood")) + { + tree = TreeType.REDWOOD; + } + else if (args[0].equalsIgnoreCase("tree")) + { + tree = TreeType.TREE; + } + else if (args[0].equalsIgnoreCase("redmushroom")) + { + tree = TreeType.RED_MUSHROOM; + } + else if (args[0].equalsIgnoreCase("brownmushroom")) + { + tree = TreeType.BROWN_MUSHROOM; + } + else + { + throw new NotEnoughArgumentsException(); + } + + final Location loc = LocationUtil.getTarget(user); + final Location safeLocation = LocationUtil.getSafeDestination(loc); + final boolean success = user.getWorld().generateTree(safeLocation, tree); + if (success) + { + user.sendMessage(_("treeSpawned")); + } + else + { + user.sendMessage(_("treeFailure")); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandunban.java b/Essentials/src/net/ess3/commands/Commandunban.java new file mode 100644 index 000000000..b8e43e93b --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandunban.java @@ -0,0 +1,32 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import lombok.Cleanup; + + +public class Commandunban extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + try + { + @Cleanup + final IUser player = getPlayer(args, 0, true); + player.acquireWriteLock(); + player.getData().setBan(null); + player.setBanned(false); + sender.sendMessage(_("unbannedPlayer")); + } + catch (NoSuchFieldException e) + { + throw new Exception(_("playerNotFound")); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandunbanip.java b/Essentials/src/net/ess3/commands/Commandunbanip.java new file mode 100644 index 000000000..77017c244 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandunbanip.java @@ -0,0 +1,30 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import lombok.Cleanup; + + +public class Commandunbanip extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + try + { + @Cleanup + final IUser user = getPlayer(args, 0, true); + user.acquireReadLock(); + ess.getServer().unbanIP(user.getData().getIpAddress()); + } + catch (Exception ex) + { + } + ess.getServer().unbanIP(args[0]); + sender.sendMessage(_("unbannedIP")); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandunlimited.java b/Essentials/src/net/ess3/commands/Commandunlimited.java new file mode 100644 index 000000000..d3a53d1cb --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandunlimited.java @@ -0,0 +1,111 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.api.server.ItemStack; +import net.ess3.api.server.Material; +import net.ess3.permissions.Permissions; +import net.ess3.permissions.UnlimitedItemPermissions; +import java.util.Locale; +import java.util.Set; +import lombok.Cleanup; + + +public class Commandunlimited extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + @Cleanup + IUser target = user; + + if (args.length > 1 && Permissions.UNLIMITED_OTHERS.isAuthorized(user)) + { + target = getPlayer(args, 1); + target.acquireReadLock(); + } + + if (args[0].equalsIgnoreCase("list")) + { + final String list = getList(target); + user.sendMessage(list); + } + else if (args[0].equalsIgnoreCase("clear")) + { + //TODO: Fix this, the clear should always work, even when the player does not have permission. + final Set itemList = target.getData().getUnlimited(); + for(Material mat : itemList) + { + toggleUnlimited(user, target, mat.getName()); + + } + } + else + { + toggleUnlimited(user, target, args[0]); + } + } + + private String getList(final IUser target) + { + final StringBuilder output = new StringBuilder(); + output.append(_("unlimitedItems")).append(" "); + boolean first = true; + final Set items = target.getData().getUnlimited(); + if (items.isEmpty()) + { + output.append(_("none")); + } + for (Material mater : items) + { + if (!first) + { + output.append(", "); + } + first = false; + final String matname = mater.getName().toLowerCase(Locale.ENGLISH).replace("_", ""); + output.append(matname); + } + + return output.toString(); + } + + private Boolean toggleUnlimited(final IUser user, final IUser target, final String item) throws Exception + { + final ItemStack stack = ess.getItemDb().get(item, 1); + stack.setAmount(Math.min(stack.getType().getMaxStackSize(), 2)); + + final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); + if (!UnlimitedItemPermissions.getPermission(stack.getType()).isAuthorized(user)) + { + throw new Exception(_("unlimitedItemPermission", itemname)); + } + + String message = "disableUnlimited"; + Boolean enableUnlimited = false; + if (!target.getData().hasUnlimited(stack.getType())) + { + message = "enableUnlimited"; + enableUnlimited = true; + if (!target.getInventory().containsItem(true, true, stack)) + { + target.getInventory().addItem(stack); + } + } + + if (user != target) + { + user.sendMessage(_(message, itemname, target.getDisplayName())); + } + target.sendMessage(_(message, itemname, target.getDisplayName())); + target.acquireWriteLock(); + target.getData().setUnlimited(stack.getType(), enableUnlimited); + + return true; + } +} diff --git a/Essentials/src/net/ess3/commands/Commandwarp.java b/Essentials/src/net/ess3/commands/Commandwarp.java new file mode 100644 index 000000000..93fa4a003 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandwarp.java @@ -0,0 +1,123 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.economy.Trade; +import net.ess3.utils.Util; +import net.ess3.api.IUser; +import net.ess3.api.IWarps; +import net.ess3.permissions.Permissions; +import net.ess3.permissions.WarpPermissions; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; + +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + + +public class Commandwarp extends EssentialsCommand +{ + private final static int WARPS_PER_PAGE = 20; + + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length == 0 || args[0].matches("[0-9]+")) + { + if (!Permissions.WARP_LIST.isAuthorized(user)) + { + throw new Exception(_("warpListPermission")); + } + warpList(user, args); + throw new NoChargeException(); + } + if (args.length > 0) + { + IUser otherUser = null; + if (args.length == 2 && Permissions.WARP_OTHERS.isAuthorized(user)) + { + otherUser = ess.getUser(server.getPlayer(args[1])); + if (otherUser == null) + { + throw new Exception(_("playerNotFound")); + } + warpUser(otherUser, args[0]); + throw new NoChargeException(); + } + warpUser(user, args[0]); + throw new NoChargeException(); + } + } + + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 2 || args[0].matches("[0-9]+")) + { + warpList(sender, args); + throw new NoChargeException(); + } + IUser otherUser = ess.getUser(server.getPlayer(args[1])); + if (otherUser == null) + { + throw new Exception(_("playerNotFound")); + } + otherUser.getTeleport().warp(args[0], null, TeleportCause.COMMAND); + throw new NoChargeException(); + + } + + //TODO: Use one of the new text classes, like /help ? + private void warpList(final CommandSender sender, final String[] args) throws Exception + { + final IWarps warps = ess.getWarps(); + if (warps.isEmpty()) + { + throw new Exception(_("noWarpsDefined")); + } + final List warpNameList = new ArrayList(warps.getList()); + + if (sender instanceof IUser) + { + final Iterator iterator = warpNameList.iterator(); + while (iterator.hasNext()) + { + final String warpName = iterator.next(); + if (!WarpPermissions.getPermission(warpName).isAuthorized(sender)) + { + iterator.remove(); + } + } + } + int page = 1; + if (args.length > 0) + { + page = Integer.parseInt(args[0]); + } + + final int warpPage = (page - 1) * WARPS_PER_PAGE; + final String warpList = Util.joinList(warpNameList.subList(warpPage, warpPage + Math.min(warpNameList.size() - warpPage, WARPS_PER_PAGE))); + + if (warpNameList.size() > WARPS_PER_PAGE) + { + sender.sendMessage(_("warpsCount", warpNameList.size(), page, (int)Math.ceil(warpNameList.size() / (double)WARPS_PER_PAGE))); + sender.sendMessage(warpList); + } + else + { + sender.sendMessage(_("warps", warpList)); + } + } + + private void warpUser(final IUser user, final String name) throws Exception + { + final Trade charge = new Trade("warp-" + name.toLowerCase(Locale.ENGLISH).replace('_', '-'), ess); + charge.isAffordableFor(user); + if (WarpPermissions.getPermission(name).isAuthorized(user)) + { + user.getTeleport().warp(name, charge, TeleportCause.COMMAND); + return; + } + throw new Exception(_("warpUsePermission")); + } +} \ No newline at end of file diff --git a/Essentials/src/net/ess3/commands/Commandweather.java b/Essentials/src/net/ess3/commands/Commandweather.java new file mode 100644 index 000000000..7ed487873 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandweather.java @@ -0,0 +1,72 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.api.server.CommandSender; +import net.ess3.api.server.World; + + +public class Commandweather extends EssentialsCommand +{ + //TODO: Remove duplication + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + final boolean isStorm = args[0].equalsIgnoreCase("storm"); + final World world = user.getWorld(); + if (args.length > 1) + { + + world.setStorm(isStorm ? true : false); + world.setWeatherDuration(Integer.parseInt(args[1]) * 20); + user.sendMessage(isStorm + ? _("weatherStormFor", world.getName(), args[1]) + : _("weatherSunFor", world.getName(), args[1])); + } + else + { + world.setStorm(isStorm ? true : false); + user.sendMessage(isStorm + ? _("weatherStorm", world.getName()) + : _("weatherSun", world.getName())); + } + } + + //TODO: Translate these + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 2) //running from console means inserting a world arg before other args + { + throw new Exception("When running from console, usage is: /" + commandName + " [duration]"); + } + + final boolean isStorm = args[1].equalsIgnoreCase("storm"); + final World world = server.getWorld(args[0]); + if (world == null) + { + throw new Exception("World named " + args[0] + " not found!"); + } + if (args.length > 2) + { + + world.setStorm(isStorm ? true : false); + world.setWeatherDuration(Integer.parseInt(args[2]) * 20); + sender.sendMessage(isStorm + ? _("weatherStormFor", world.getName(), args[2]) + : _("weatherSunFor", world.getName(), args[2])); + } + else + { + world.setStorm(isStorm ? true : false); + sender.sendMessage(isStorm + ? _("weatherStorm", world.getName()) + : _("weatherSun", world.getName())); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandwhois.java b/Essentials/src/net/ess3/commands/Commandwhois.java new file mode 100644 index 000000000..4344d5f11 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandwhois.java @@ -0,0 +1,85 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.utils.Util; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.api.server.CommandSender; +import net.ess3.api.server.Player; +import net.ess3.permissions.Permissions; +import net.ess3.user.UserData; +import net.ess3.utils.DateUtil; +import java.util.Locale; +import lombok.Cleanup; + + + +public class Commandwhois extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + boolean showhidden = false; + if (sender instanceof Player) + { + if (Permissions.LIST_HIDDEN.isAuthorized(sender)) + { + showhidden = true; + } + } + else + { + showhidden = true; + } + final String whois = args[0].toLowerCase(Locale.ENGLISH); + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + final int prefixLength = Util.stripColor(settings.getData().getChat().getNicknamePrefix()).length(); + for (Player onlinePlayer : server.getOnlinePlayers()) + { + @Cleanup + final IUser user = onlinePlayer.getUser(); + + if (user.isHidden() && !showhidden) + { + continue; + } + user.acquireReadLock(); + final String nickName = Util.stripColor(user.getData().getNickname()); + if (!whois.equalsIgnoreCase(nickName) + && !whois.substring(prefixLength).equalsIgnoreCase(nickName) + && !whois.equalsIgnoreCase(user.getName())) + { + continue; + } + sender.sendMessage(""); + sender.sendMessage(_("whoisIs", user.getDisplayName(), user.getName())); + sender.sendMessage(_("whoisHealth", user.getHealth())); + sender.sendMessage(_("whoisOP", (user.isOp() ? _("true") : _("false")))); + sender.sendMessage(_("whoisGod", (user.isGodModeEnabled() ? _("true") : _("false")))); + sender.sendMessage(_("whoisGamemode", _(user.getGameMode().toString().toLowerCase(Locale.ENGLISH)))); + sender.sendMessage(_("whoisLocation", user.getLocation().getWorld().getName(), user.getLocation().getBlockX(), user.getLocation().getBlockY(), user.getLocation().getBlockZ())); + sender.sendMessage(_("whoisMoney", Util.displayCurrency(user.getMoney(), ess))); + sender.sendMessage(_("whoisJail", (user.getData().isJailed() + ? user.getTimestamp(UserData.TimestampType.JAIL) > 0 + ? DateUtil.formatDateDiff(user.getTimestamp(UserData.TimestampType.JAIL)) + : _("true") + : _("false")))); + sender.sendMessage(user.getData().isAfk() + ? _("whoisStatusAway") + : _("whoisStatusAvailable")); + sender.sendMessage(_("whoisIPAddress", user.getAddress().getAddress().toString())); + final String location = user.getData().getGeolocation(); + if (location != null + && Permissions.GEOIP_SHOW.isAuthorized(sender)) + { + sender.sendMessage(_("whoisGeoLocation", location)); + } + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandworld.java b/Essentials/src/net/ess3/commands/Commandworld.java new file mode 100644 index 000000000..261b2914e --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandworld.java @@ -0,0 +1,81 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.economy.Trade; +import net.ess3.api.IUser; +import net.ess3.api.server.World; +import net.ess3.api.server.Location; +import net.ess3.permissions.WorldPermissions; +import java.util.List; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + + +public class Commandworld extends EssentialsCommand +{ + @Override + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + World world; + + if (args.length < 1) + { + World nether = null; + + final List worlds = server.getWorlds(); + + for (World world2 : worlds) + { + if (world2.getEnvironment() == World.Environment.NETHER) + { + nether = world2; + break; + } + } + if (nether == null) + { + return; + } + world = user.getWorld() == nether ? worlds.get(0) : nether; + } + else + { + world = ess.getWorld(getFinalArg(args, 0)); + if (world == null) + { + user.sendMessage(_("invalidWorld")); + user.sendMessage(_("possibleWorlds", server.getWorlds().size() - 1)); + user.sendMessage(_("typeWorldName")); + throw new NoChargeException(); + } + } + + + if (!WorldPermissions.getPermission(world.getName()).isAuthorized(user)) + { + user.sendMessage(_("invalidWorld")); //TODO: Make a "world teleport denied" translation + throw new NoChargeException(); + } + + 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) + { + factor = 1.0 / 8.0; + } + else + { + factor = 1.0; + } + + final Location loc = user.getLocation(); + final Location target = Location.create(world, loc.getBlockX() * factor + .5, loc.getBlockY(), loc.getBlockZ() * factor + .5); + + final Trade charge = new Trade(commandName, ess); + charge.isAffordableFor(user); + user.getTeleport().teleport(target, charge, TeleportCause.COMMAND); + throw new NoChargeException(); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandworth.java b/Essentials/src/net/ess3/commands/Commandworth.java new file mode 100644 index 000000000..9b0939f8f --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandworth.java @@ -0,0 +1,101 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.utils.Util; +import net.ess3.api.IUser; +import net.ess3.api.server.ItemStack; +import java.util.Locale; + + +public class Commandworth extends EssentialsCommand +{ + //TODO: Remove duplication + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + ItemStack iStack = user.getItemInHand(); + int amount = iStack.getAmount(); + + if (args.length > 0) + { + iStack = ess.getItemDb().get(args[0]); + } + + try + { + if (args.length > 1) + { + amount = Integer.parseInt(args[1]); + } + } + catch (NumberFormatException ex) + { + amount = iStack.getType().getMaxStackSize(); + } + + iStack.setAmount(amount); + final double worth = ess.getWorth().getPrice(iStack); + if (Double.isNaN(worth)) + { + throw new Exception(_("itemCannotBeSold")); + } + + user.sendMessage(iStack.getDurability() != 0 + ? _("worthMeta", + iStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), + iStack.getDurability(), + Util.displayCurrency(worth * amount, ess), + amount, + Util.displayCurrency(worth, ess)) + : _("worth", + iStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), + Util.displayCurrency(worth * amount, ess), + amount, + Util.displayCurrency(worth, ess))); + } + + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + ItemStack iStack = ess.getItemDb().get(args[0]); + int amount = iStack.getAmount(); + + try + { + if (args.length > 1) + { + amount = Integer.parseInt(args[1]); + } + } + catch (NumberFormatException ex) + { + amount = iStack.getType().getMaxStackSize(); + } + + iStack.setAmount(amount); + final double worth = ess.getWorth().getPrice(iStack); + if (Double.isNaN(worth)) + { + throw new Exception(_("itemCannotBeSold")); + } + + sender.sendMessage(iStack.getDurability() != 0 + ? _("worthMeta", + iStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), + iStack.getDurability(), + Util.displayCurrency(worth * amount, ess), + amount, + Util.displayCurrency(worth, ess)) + : _("worth", + iStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), + Util.displayCurrency(worth * amount, ess), + amount, + Util.displayCurrency(worth, ess))); + + } +} diff --git a/Essentials/src/net/ess3/commands/EssentialsCommand.java b/Essentials/src/net/ess3/commands/EssentialsCommand.java new file mode 100644 index 000000000..d54e3d309 --- /dev/null +++ b/Essentials/src/net/ess3/commands/EssentialsCommand.java @@ -0,0 +1,130 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IEssentials; +import net.ess3.api.IEssentialsModule; +import net.ess3.api.IUser; +import net.ess3.api.server.CommandSender; +import net.ess3.api.server.IServer; +import net.ess3.api.server.Player; +import net.ess3.economy.Trade; +import net.ess3.permissions.AbstractSuperpermsPermission; +import java.util.List; +import java.util.logging.Logger; +import org.bukkit.command.Command; + + +public abstract class EssentialsCommand extends AbstractSuperpermsPermission implements IEssentialsCommand +{ + protected transient String commandName; + protected transient IEssentials ess; + protected transient IEssentialsModule module; + protected transient IServer server; + protected transient Logger logger; + private transient String permission; + + public void init(final IEssentials ess, final String commandName) + { + this.ess = ess; + this.logger = ess.getLogger(); + this.server = ess.getServer(); + this.commandName = commandName; + this.permission = "essentials." + commandName; + } + + @Override + public void setEssentialsModule(final IEssentialsModule module) + { + this.module = module; + } + + protected IUser getPlayer(final String[] args, final int pos) throws NoSuchFieldException, NotEnoughArgumentsException + { + return getPlayer(args, pos, false); + } + + protected IUser getPlayer(final String[] args, final int pos, final boolean getOffline) throws NoSuchFieldException, NotEnoughArgumentsException + { + if (args.length <= pos) + { + throw new NotEnoughArgumentsException(); + } + if (args[pos].isEmpty()) + { + throw new NoSuchFieldException(_("playerNotFound")); + } + final IUser user = ess.getUser(args[pos]); + if (user != null) + { + if (!getOffline && (!user.isOnline() || user.isHidden())) + { + throw new NoSuchFieldException(_("playerNotFound")); + } + return user; + } + final List matches = server.matchPlayer(args[pos]); + + if (!matches.isEmpty()) + { + for (Player player : matches) + { + final IUser userMatch = player.getUser(); + if (userMatch.getDisplayName().startsWith(args[pos]) && (getOffline || !userMatch.isHidden())) + { + return userMatch; + } + } + final IUser userMatch = matches.get(0).getUser(); + if (getOffline || !userMatch.isHidden()) + { + return userMatch; + } + } + throw new NoSuchFieldException(_("playerNotFound")); + } + + @Override + public final void run(final IUser user, final Command cmd, final String commandLabel, final String[] args) throws Exception + { + final Trade charge = new Trade(commandName, ess); + charge.isAffordableFor(user); + run(user, commandLabel, args); + charge.charge(user); + } + + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + run((CommandSender)user, commandLabel, args); + } + + @Override + public final void run(final CommandSender sender, final Command cmd, final String commandLabel, final String[] args) throws Exception + { + run(sender, commandLabel, args); + } + + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + throw new Exception(_("onlyPlayers", commandName)); + } + + 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(); + } + + @Override + public String getPermissionName() + { + return permission; + } +} diff --git a/Essentials/src/net/ess3/commands/EssentialsCommandHandler.java b/Essentials/src/net/ess3/commands/EssentialsCommandHandler.java new file mode 100644 index 000000000..c4ef7bd78 --- /dev/null +++ b/Essentials/src/net/ess3/commands/EssentialsCommandHandler.java @@ -0,0 +1,312 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.*; + +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.PluginCommand; +import org.bukkit.command.PluginCommandYamlParser; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + + +public class EssentialsCommandHandler implements ICommandHandler +{ + private final transient ClassLoader classLoader; + private final transient String commandPath; + private final transient String permissionPrefix; + private final transient IEssentialsModule module; + private static final transient Logger LOGGER = Bukkit.getLogger(); + private final transient Map> altcommands = new HashMap>(); + private final transient Map disabledList = new HashMap(); + private final transient Map commands = new HashMap(); + private final transient IEssentials ess; + + public EssentialsCommandHandler(ClassLoader classLoader, String commandPath, String permissionPrefix, IEssentials ess) + { + this(classLoader, commandPath, permissionPrefix, null, ess); + } + + public EssentialsCommandHandler(ClassLoader classLoader, String commandPath, String permissionPrefix, IEssentialsModule module, IEssentials ess) + { + this.classLoader = classLoader; + this.commandPath = commandPath; + this.permissionPrefix = permissionPrefix; + this.module = module; + this.ess = ess; + for (Plugin plugin : ess.getServer().getPluginManager().getPlugins()) + { + if (plugin.isEnabled()) + { + addPlugin(plugin); + } + } + } + + @Override + public boolean handleCommand(final CommandSender sender, final Command command, final String commandLabel, final String[] args) + { + boolean disabled = false; + boolean overridden = false; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try + { + disabled = settings.getData().getCommands().isDisabled(command.getName()); + overridden = !disabled || settings.getData().getCommands().isOverridden(command.getName()); + } + finally + { + settings.unlock(); + } + // Allow plugins to override the command via onCommand + if (!overridden && (!commandLabel.startsWith("e") || commandLabel.equalsIgnoreCase(command.getName()))) + { + final PluginCommand pc = getAlternative(commandLabel); + if (pc != null) + { + + executed(commandLabel, pc.getLabel()); + try + { + return pc.execute(sender, commandLabel, args); + } + catch (final Exception ex) + { + final ArrayList elements = new ArrayList(Arrays.asList(ex.getStackTrace())); + elements.remove(0); + final ArrayList toRemove = new ArrayList(); + for (final StackTraceElement e : elements) + { + if (e.getClassName().equals("net.ess3.Essentials")) + { + toRemove.add(e); + } + } + elements.removeAll(toRemove); + final StackTraceElement[] trace = elements.toArray(new StackTraceElement[elements.size()]); + ex.setStackTrace(trace); + ex.printStackTrace(); + sender.sendMessage(ChatColor.RED + "An internal error occurred while attempting to perform this command"); + return true; + } + } + } + + try + { + IUser user = null; + if (sender instanceof Player) + { + user = ess.getUser((Player)sender); + LOGGER.log(Level.INFO, String.format("[PLAYER_COMMAND] %s: /%s %s ", ((Player)sender).getName(), commandLabel, EssentialsCommand.getFinalArg(args, 0))); + } + + // Check for disabled commands + if (disabled) + { + return true; + } + + final String commandName = command.getName().toLowerCase(Locale.ENGLISH); + IEssentialsCommand cmd = commands.get(commandName); + if (cmd == null) + { + try + { + cmd = (IEssentialsCommand)classLoader.loadClass(commandPath + commandName).newInstance(); + cmd.init(ess, commandName); + cmd.setEssentialsModule(module); + commands.put(commandName, cmd); + } + catch (Exception ex) + { + sender.sendMessage(_("commandNotLoaded", commandName)); + LOGGER.log(Level.SEVERE, _("commandNotLoaded", commandName), ex); + return true; + } + } + + // Check authorization + if (sender != null && !cmd.isAuthorized(sender)) + { + LOGGER.log(Level.WARNING, _("deniedAccessCommand", user.getName())); + user.sendMessage(_("noAccessCommand")); + return true; + } + + // Run the command + try + { + if (user == null) + { + cmd.run(sender, command, commandLabel, args); + } + else + { + user.acquireReadLock(); + try + { + cmd.run(user, command, commandLabel, args); + } + finally + { + user.unlock(); + } + } + return true; + } + catch (NoChargeException ex) + { + return true; + } + catch (NotEnoughArgumentsException ex) + { + sender.sendMessage(command.getDescription()); + sender.sendMessage(command.getUsage().replaceAll("", commandLabel)); + if (!ex.getMessage().isEmpty()) + { + sender.sendMessage(ex.getMessage()); + } + return true; + } + catch (Throwable ex) + { + showCommandError(sender, commandLabel, ex); + return true; + } + } + catch (Throwable ex) + { + LOGGER.log(Level.SEVERE, _("commandFailed", commandLabel), ex); + return true; + } + } + + @Override + public void showCommandError(final CommandSender sender, final String commandLabel, final Throwable exception) + { + sender.sendMessage(_("errorWithMessage", exception.getMessage())); + if (ess.getSettings().isDebug()) + { + LOGGER.log(Level.WARNING, _("errorCallingCommand", commandLabel), exception); + } + } + + @Override + public void onReload() + { + } + + public final void addPlugin(final Plugin plugin) + { + if (plugin.getDescription().getMain().contains("com.earth2me.essentials")) + { + return; + } + final List commands = PluginCommandYamlParser.parse(plugin); + final String pluginName = plugin.getDescription().getName().toLowerCase(Locale.ENGLISH); + + for (Command command : commands) + { + final PluginCommand pc = (PluginCommand)command; + final List labels = new ArrayList(pc.getAliases()); + labels.add(pc.getName()); + + PluginCommand reg = ess.getServer().getPluginCommand(pluginName + ":" + pc.getName().toLowerCase(Locale.ENGLISH)); + if (reg == null) + { + reg = ess.getServer().getPluginCommand(pc.getName().toLowerCase(Locale.ENGLISH)); + } + if (reg == null || !reg.getPlugin().equals(plugin)) + { + continue; + } + for (String label : labels) + { + List plugincommands = altcommands.get(label.toLowerCase(Locale.ENGLISH)); + if (plugincommands == null) + { + plugincommands = new ArrayList(); + altcommands.put(label.toLowerCase(Locale.ENGLISH), plugincommands); + } + boolean found = false; + for (PluginCommand pc2 : plugincommands) + { + if (pc2.getPlugin().equals(plugin)) + { + found = true; + } + } + if (!found) + { + plugincommands.add(reg); + } + } + } + } + + public void removePlugin(final Plugin plugin) + { + final Iterator>> iterator = altcommands.entrySet().iterator(); + while (iterator.hasNext()) + { + final Map.Entry> entry = iterator.next(); + final Iterator pcIterator = entry.getValue().iterator(); + while (pcIterator.hasNext()) + { + final PluginCommand pc = pcIterator.next(); + if (pc.getPlugin() == null || pc.getPlugin().equals(plugin)) + { + pcIterator.remove(); + } + } + if (entry.getValue().isEmpty()) + { + iterator.remove(); + } + } + } + + public PluginCommand getAlternative(final String label) + { + final List commands = altcommands.get(label); + if (commands == null || commands.isEmpty()) + { + return null; + } + if (commands.size() == 1) + { + return commands.get(0); + } + // return the first command that is not an alias + for (PluginCommand command : commands) + { + if (command.getName().equalsIgnoreCase(label)) + { + return command; + } + } + // return the first alias + return commands.get(0); + } + + public void executed(final String label, final String otherLabel) + { + if (ess.getSettings().isDebug()) + { + LOGGER.log(Level.INFO, "Essentials: Alternative command " + label + " found, using " + otherLabel); + } + disabledList.put(label, otherLabel); + } + + public Map disabledCommands() + { + return disabledList; + } +} diff --git a/Essentials/src/net/ess3/commands/IEssentialsCommand.java b/Essentials/src/net/ess3/commands/IEssentialsCommand.java new file mode 100644 index 000000000..2466b4c55 --- /dev/null +++ b/Essentials/src/net/ess3/commands/IEssentialsCommand.java @@ -0,0 +1,22 @@ +package net.ess3.commands; + +import net.ess3.api.IEssentials; +import net.ess3.api.IEssentialsModule; +import net.ess3.api.IPermission; +import net.ess3.api.IUser; +import net.ess3.api.server.CommandSender; +import org.bukkit.command.Command; + + +public interface IEssentialsCommand extends IPermission +{ + void run(IUser user, Command cmd, String commandLabel, String[] args) + throws Exception; + + void run(CommandSender sender, Command cmd, String commandLabel, String[] args) + throws Exception; + + void init(IEssentials ess, String commandLabel); + + void setEssentialsModule(IEssentialsModule module); +} diff --git a/Essentials/src/net/ess3/commands/NoChargeException.java b/Essentials/src/net/ess3/commands/NoChargeException.java new file mode 100644 index 000000000..e3cd20131 --- /dev/null +++ b/Essentials/src/net/ess3/commands/NoChargeException.java @@ -0,0 +1,10 @@ +package net.ess3.commands; + + +public class NoChargeException extends Exception +{ + public NoChargeException() + { + super("Will charge later"); + } +} diff --git a/Essentials/src/net/ess3/commands/NotEnoughArgumentsException.java b/Essentials/src/net/ess3/commands/NotEnoughArgumentsException.java new file mode 100644 index 000000000..38a2915c7 --- /dev/null +++ b/Essentials/src/net/ess3/commands/NotEnoughArgumentsException.java @@ -0,0 +1,20 @@ +package net.ess3.commands; + + +public class NotEnoughArgumentsException extends Exception +{ + public NotEnoughArgumentsException() + { + super(""); + } + + public NotEnoughArgumentsException(final String string) + { + super(string); + } + + public NotEnoughArgumentsException(final Throwable ex) + { + super("", ex); + } +} diff --git a/Essentials/src/net/ess3/commands/WarpNotFoundException.java b/Essentials/src/net/ess3/commands/WarpNotFoundException.java new file mode 100644 index 000000000..4c948560d --- /dev/null +++ b/Essentials/src/net/ess3/commands/WarpNotFoundException.java @@ -0,0 +1,17 @@ +package net.ess3.commands; + + +public class WarpNotFoundException extends Exception +{ + public WarpNotFoundException() + { + super(""); + } + + public WarpNotFoundException(String message) + { + super(message); + } +} + + diff --git a/Essentials/src/net/ess3/craftbukkit/FakeExplosion.java b/Essentials/src/net/ess3/craftbukkit/FakeExplosion.java new file mode 100644 index 000000000..01f117cfa --- /dev/null +++ b/Essentials/src/net/ess3/craftbukkit/FakeExplosion.java @@ -0,0 +1,51 @@ +package net.ess3.craftbukkit; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; +import net.minecraft.server.ChunkPosition; +import net.minecraft.server.Packet60Explosion; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.block.Block; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityExplodeEvent; + + +public class FakeExplosion +{ + public static void createExplosion(final EntityExplodeEvent event, final Server server, final Player[] players) + { + try + { + final Set set = new HashSet(event.blockList().size()); + final List blocksUnderPlayers = new ArrayList(players.length); + final Location loc = event.getLocation(); + for (Player player : players) + { + if (player.getWorld().equals(loc.getWorld())) + { + blocksUnderPlayers.add(new ChunkPosition(player.getLocation().getBlockX(), player.getLocation().getBlockY() - 1, player.getLocation().getBlockZ())); + } + } + for (Block block : event.blockList()) + { + final ChunkPosition cp = new ChunkPosition(block.getX(), block.getY(), block.getZ()); + if (!blocksUnderPlayers.contains(cp)) + { + set.add(cp); + } + } + ((CraftServer)server).getHandle().sendPacketNearby(loc.getX(), loc.getY(), loc.getZ(), 64.0, ((CraftWorld)loc.getWorld()).getHandle().worldProvider.dimension, new Packet60Explosion(loc.getX(), loc.getY(), loc.getZ(), 3.0F, set)); + } + catch (Throwable ex) + { + Logger.getLogger("Minecraft").log(Level.SEVERE, null, ex); + } + } +} diff --git a/Essentials/src/net/ess3/craftbukkit/FakeInventory.java b/Essentials/src/net/ess3/craftbukkit/FakeInventory.java new file mode 100644 index 000000000..9d07c9dbd --- /dev/null +++ b/Essentials/src/net/ess3/craftbukkit/FakeInventory.java @@ -0,0 +1,225 @@ +package net.ess3.craftbukkit; + +import java.util.HashMap; +import java.util.List; +import java.util.ListIterator; +import org.bukkit.Material; +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.ItemStack; + + +public class FakeInventory implements Inventory +{ + ItemStack[] items; + + public FakeInventory(ItemStack[] items) + { + this.items = new ItemStack[items.length]; + for (int i = 0; i < items.length; i++) + { + if (items[i] == null) + { + continue; + } + this.items[i] = items[i].clone(); + } + } + + @Override + public int getSize() + { + return items.length; + } + + @Override + public String getName() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public ItemStack getItem(int i) + { + return items[i]; + } + + @Override + public void setItem(int i, ItemStack is) + { + items[i] = is; + } + + @Override + public HashMap addItem(ItemStack... iss) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public HashMap removeItem(ItemStack... iss) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public ItemStack[] getContents() + { + return items; + } + + @Override + public void setContents(ItemStack[] iss) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean contains(int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean contains(Material mtrl) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean contains(ItemStack is) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean contains(int i, int i1) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean contains(Material mtrl, int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean contains(ItemStack is, int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public HashMap all(int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public HashMap all(Material mtrl) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public HashMap all(ItemStack is) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int first(int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int first(Material mtrl) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int first(ItemStack is) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int firstEmpty() + { + for (int i = 0; i < items.length; i++) + { + if (items[i] == null || items[i].getTypeId() == 0) { + return i; + } + } + return -1; + } + + @Override + public void remove(int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void remove(Material mtrl) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void remove(ItemStack is) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void clear(int i) + { + items[i] = null; + } + + @Override + public void clear() + { + for (int i = 0; i < items.length; i++) + { + items[i] = null; + } + } + + @Override + public List getViewers() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public String getTitle() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public InventoryType getType() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public InventoryHolder getHolder() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public ListIterator iterator() + { + throw new UnsupportedOperationException("Not supported yet."); + } +} diff --git a/Essentials/src/net/ess3/craftbukkit/InventoryWorkaround.java b/Essentials/src/net/ess3/craftbukkit/InventoryWorkaround.java new file mode 100644 index 000000000..c8f070bab --- /dev/null +++ b/Essentials/src/net/ess3/craftbukkit/InventoryWorkaround.java @@ -0,0 +1,322 @@ +package net.ess3.craftbukkit; + +import java.util.HashMap; +import java.util.Map; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +/* + * This class can be removed when https://github.com/Bukkit/CraftBukkit/pull/193 is accepted to CraftBukkit + */ + +public final class InventoryWorkaround +{ + private InventoryWorkaround() + { + } + + public static int first(final Inventory inventory, final ItemStack item, final boolean forceDurability, final boolean forceAmount, final boolean forceEnchantments) + { + return next(inventory, item, 0, forceDurability, forceAmount, forceEnchantments); + } + + public static int next(final Inventory cinventory, final ItemStack item, final int start, final boolean forceDurability, final boolean forceAmount, final boolean forceEnchantments) + { + final ItemStack[] inventory = cinventory.getContents(); + for (int i = start; i < inventory.length; i++) + { + final ItemStack cItem = inventory[i]; + if (cItem == null) + { + continue; + } + if (item.getTypeId() == cItem.getTypeId() && (!forceAmount || item.getAmount() == cItem.getAmount()) && (!forceDurability || cItem.getDurability() == item.getDurability()) && (!forceEnchantments || cItem.getEnchantments().equals(item.getEnchantments()))) + { + return i; + } + } + return -1; + } + + public static int firstPartial(final Inventory cinventory, final ItemStack item, final boolean forceDurability) + { + return firstPartial(cinventory, item, forceDurability, item.getType().getMaxStackSize()); + } + + public static int firstPartial(final Inventory cinventory, final ItemStack item, final boolean forceDurability, final int maxAmount) + { + if (item == null) + { + return -1; + } + final ItemStack[] inventory = cinventory.getContents(); + for (int i = 0; i < inventory.length; i++) + { + final ItemStack cItem = inventory[i]; + if (cItem == null) + { + continue; + } + if (item.getTypeId() == cItem.getTypeId() && cItem.getAmount() < maxAmount && (!forceDurability || cItem.getDurability() == item.getDurability()) && cItem.getEnchantments().equals(item.getEnchantments())) + { + return i; + } + } + return -1; + } + + public static boolean addAllItems(final Inventory cinventory, final boolean forceDurability, final ItemStack... items) + { + final Inventory fake = new FakeInventory(cinventory.getContents()); + if (addItem(fake, forceDurability, items).isEmpty()) + { + addItem(cinventory, forceDurability, items); + return true; + } + else + { + return false; + } + } + + public static Map addItem(final Inventory cinventory, final boolean forceDurability, final ItemStack... items) + { + return addItem(cinventory, forceDurability, 0, items); + } + + public static Map addItem(final Inventory cinventory, final boolean forceDurability, final int oversizedStacks, final ItemStack... items) + { + final Map leftover = new HashMap(); + + /* + * TODO: some optimization - Create a 'firstPartial' with a 'fromIndex' - Record the lastPartial per Material - + * Cache firstEmpty result + */ + + // combine items + + ItemStack[] combined = new ItemStack[items.length]; + for (int i = 0; i < items.length; i++) + { + if (items[i] == null || items[i].getAmount() < 1) + { + continue; + } + for (int j = 0; j < combined.length; j++) + { + if (combined[j] == null) + { + combined[j] = items[i].clone(); + break; + } + if (combined[j].getTypeId() == items[i].getTypeId() && (!forceDurability || combined[j].getDurability() == items[i].getDurability()) && combined[j].getEnchantments().equals(items[i].getEnchantments())) + { + combined[j].setAmount(combined[j].getAmount() + items[i].getAmount()); + break; + } + } + } + + + for (int i = 0; i < combined.length; i++) + { + final ItemStack item = combined[i]; + if (item == null) + { + continue; + } + + while (true) + { + // Do we already have a stack of it? + final int maxAmount = oversizedStacks > item.getType().getMaxStackSize() ? oversizedStacks : item.getType().getMaxStackSize(); + final int firstPartial = firstPartial(cinventory, item, forceDurability, maxAmount); + + // Drat! no partial stack + if (firstPartial == -1) + { + // Find a free spot! + final int firstFree = cinventory.firstEmpty(); + + if (firstFree == -1) + { + // No space at all! + leftover.put(i, item); + break; + } + else + { + // More than a single stack! + if (item.getAmount() > maxAmount) + { + final ItemStack stack = item.clone(); + stack.setAmount(maxAmount); + cinventory.setItem(firstFree, stack); + item.setAmount(item.getAmount() - maxAmount); + } + else + { + // Just store it + cinventory.setItem(firstFree, item); + break; + } + } + } + else + { + // So, apparently it might only partially fit, well lets do just that + final ItemStack partialItem = cinventory.getItem(firstPartial); + + final int amount = item.getAmount(); + final int partialAmount = partialItem.getAmount(); + + // Check if it fully fits + if (amount + partialAmount <= maxAmount) + { + partialItem.setAmount(amount + partialAmount); + break; + } + + // It fits partially + partialItem.setAmount(maxAmount); + item.setAmount(amount + partialAmount - maxAmount); + } + } + } + return leftover; + } + + public static Map removeItem(final Inventory cinventory, final boolean forceDurability, final boolean forceEnchantments, final ItemStack... items) + { + final Map leftover = new HashMap(); + + // TODO: optimization + + for (int i = 0; i < items.length; i++) + { + final ItemStack item = items[i]; + if (item == null) + { + continue; + } + int toDelete = item.getAmount(); + + while (true) + { + + // Bail when done + if (toDelete <= 0) + { + break; + } + + // get first Item, ignore the amount + final int first = first(cinventory, item, forceDurability, false, forceEnchantments); + + // Drat! we don't have this type in the inventory + if (first == -1) + { + item.setAmount(toDelete); + leftover.put(i, item); + break; + } + else + { + final ItemStack itemStack = cinventory.getItem(first); + final int amount = itemStack.getAmount(); + + if (amount <= toDelete) + { + toDelete -= amount; + // clear the slot, all used up + cinventory.clear(first); + } + else + { + // split the stack and store + itemStack.setAmount(amount - toDelete); + cinventory.setItem(first, itemStack); + toDelete = 0; + } + } + } + } + return leftover; + } + + public static boolean containsItem(final Inventory cinventory, final boolean forceDurability, final boolean forceEnchantments, final ItemStack... items) + { + final Map leftover = new HashMap(); + + // TODO: optimization + + // combine items + + ItemStack[] combined = new ItemStack[items.length]; + for (int i = 0; i < items.length; i++) + { + if (items[i] == null) + { + continue; + } + for (int j = 0; j < combined.length; j++) + { + if (combined[j] == null) + { + combined[j] = items[i].clone(); + break; + } + if (combined[j].getTypeId() == items[i].getTypeId() && (!forceDurability || combined[j].getDurability() == items[i].getDurability()) && (!forceEnchantments || combined[j].getEnchantments().equals(items[i].getEnchantments()))) + { + combined[j].setAmount(combined[j].getAmount() + items[i].getAmount()); + break; + } + } + } + + for (int i = 0; i < combined.length; i++) + { + final ItemStack item = combined[i]; + if (item == null) + { + continue; + } + int mustHave = item.getAmount(); + int position = 0; + + while (true) + { + // Bail when done + if (mustHave <= 0) + { + break; + } + + final int slot = next(cinventory, item, position, forceDurability, false, forceEnchantments); + + // Drat! we don't have this type in the inventory + if (slot == -1) + { + leftover.put(i, item); + break; + } + else + { + final ItemStack itemStack = cinventory.getItem(slot); + final int amount = itemStack.getAmount(); + + if (amount <= mustHave) + { + mustHave -= amount; + } + else + { + mustHave = 0; + } + position = slot + 1; + } + } + } + return leftover.isEmpty(); + } +} diff --git a/Essentials/src/net/ess3/craftbukkit/SetExpFix.java b/Essentials/src/net/ess3/craftbukkit/SetExpFix.java new file mode 100644 index 000000000..2bf6ec32e --- /dev/null +++ b/Essentials/src/net/ess3/craftbukkit/SetExpFix.java @@ -0,0 +1,56 @@ +package net.ess3.craftbukkit; + + +public class SetExpFix +{ + public static void setTotalExperience(final IPlayer player, final int exp) + { + if (exp < 0) + { + throw new IllegalArgumentException("Experience is negative!"); + } + player.setExp(0); + player.setLevel(0); + player.setTotalExperience(0); + int amount = exp; + while (amount > 0) + { + final int expToLevel = getExpToLevel(player); + amount -= expToLevel; + if (amount >= 0) + { + // give until next level + player.giveExp(expToLevel); + } + else + { + // give the rest + amount += expToLevel; + player.giveExp(amount); + amount = 0; + } + } + } + + private static int getExpToLevel(final IPlayer player) + { + return getExpToLevel(player.getLevel()); + } + + private static int getExpToLevel(final int level) + { + return 7 + (level * 7 >> 1); + } + + public static int getTotalExperience(final IPlayer player) + { + int exp = (int) (getExpToLevel(player) * player.getExp()); + int currentLevel = player.getLevel(); + + while (currentLevel > 0) { + currentLevel--; + exp += getExpToLevel(currentLevel); + } + return exp; + } +} diff --git a/Essentials/src/net/ess3/economy/Economy.java b/Essentials/src/net/ess3/economy/Economy.java new file mode 100644 index 000000000..4ba48a3d9 --- /dev/null +++ b/Essentials/src/net/ess3/economy/Economy.java @@ -0,0 +1,207 @@ +package net.ess3.economy; + +import net.ess3.utils.Util; +import net.ess3.api.*; +import net.ess3.permissions.Permissions; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + + +public class Economy implements IEconomy +{ + private final IEssentials ess; + private final MoneyHolder npcs; + + public Economy(IEssentials ess) + { + this.ess = ess; + this.npcs = new MoneyHolder(ess); + } + + private double getNPCBalance(String name) throws UserDoesNotExistException + { + npcs.acquireReadLock(); + try + { + Map balances = npcs.getData().getBalances(); + if (balances == null) + { + throw new UserDoesNotExistException(name); + } + Double balance = npcs.getData().getBalances().get(name.toLowerCase(Locale.ENGLISH)); + if (balance == null) + { + throw new UserDoesNotExistException(name); + } + return balance; + } + finally + { + npcs.unlock(); + } + } + + private void setNPCBalance(String name, double balance, boolean checkExistance) throws UserDoesNotExistException + { + npcs.acquireWriteLock(); + try + { + Map balances = npcs.getData().getBalances(); + if (balances == null) + { + balances = new HashMap(); + npcs.getData().setBalances(balances); + } + if (checkExistance && !balances.containsKey(name.toLowerCase(Locale.ENGLISH))) + { + throw new UserDoesNotExistException(name); + } + balances.put(name.toLowerCase(Locale.ENGLISH), balance); + } + finally + { + npcs.unlock(); + } + } + + private double getStartingBalance() + { + double startingBalance = 0; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try + { + startingBalance = settings.getData().getEconomy().getStartingBalance(); + } + finally + { + settings.unlock(); + } + return startingBalance; + } + + @Override + public void onReload() + { + this.npcs.onReload(false); + } + + @Override + public double getMoney(String name) throws UserDoesNotExistException + { + IUser user = ess.getUser(name); + if (user == null) + { + return getNPCBalance(name); + } + return user.getMoney(); + } + + @Override + public void setMoney(String name, double balance) throws NoLoanPermittedException, UserDoesNotExistException + { + IUser user = ess.getUser(name); + if (user == null) + { + setNPCBalance(name, balance, true); + return; + } + if (balance < 0.0 && !Permissions.ECO_LOAN.isAuthorized(user)) + { + throw new NoLoanPermittedException(); + } + user.setMoney(balance); + } + + @Override + public void resetBalance(String name) throws NoLoanPermittedException, UserDoesNotExistException + { + setMoney(name, getStartingBalance()); + } + + @Override + public String format(double amount) + { + return Util.displayCurrency(amount, ess); + } + + @Override + public boolean playerExists(String name) + { + try + { + getMoney(name); + return true; + } + catch (UserDoesNotExistException ex) + { + return false; + } + } + + @Override + public boolean isNPC(String name) throws UserDoesNotExistException + { + boolean result = ess.getUser(name) == null; + if (result) + { + getNPCBalance(name); + } + return result; + } + + @Override + public boolean createNPC(String name) + { + try + { + if (isNPC(name)) + { + + setNPCBalance(name, getStartingBalance(), false); + return true; + } + } + catch (UserDoesNotExistException ex) + { + try + { + setNPCBalance(name, getStartingBalance(), false); + return true; + } + catch (UserDoesNotExistException ex1) + { + //This should never happen! + } + } + return false; + } + + @Override + public void removeNPC(String name) throws UserDoesNotExistException + { + npcs.acquireWriteLock(); + try + { + Map balances = npcs.getData().getBalances(); + if (balances == null) + { + balances = new HashMap(); + npcs.getData().setBalances(balances); + } + if (balances.containsKey(name.toLowerCase(Locale.ENGLISH))) + { + balances.remove(name.toLowerCase(Locale.ENGLISH)); + } + else + { + throw new UserDoesNotExistException(name); + } + } + finally + { + npcs.unlock(); + } + } +} diff --git a/Essentials/src/net/ess3/economy/Money.java b/Essentials/src/net/ess3/economy/Money.java new file mode 100644 index 000000000..20eea3544 --- /dev/null +++ b/Essentials/src/net/ess3/economy/Money.java @@ -0,0 +1,17 @@ +package net.ess3.economy; + +import net.ess3.storage.MapValueType; +import net.ess3.storage.StorageObject; +import java.util.HashMap; +import java.util.Map; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Money implements StorageObject +{ + @MapValueType(Double.class) + private Map balances = new HashMap(); +} diff --git a/Essentials/src/net/ess3/economy/MoneyHolder.java b/Essentials/src/net/ess3/economy/MoneyHolder.java new file mode 100644 index 000000000..b4355edd8 --- /dev/null +++ b/Essentials/src/net/ess3/economy/MoneyHolder.java @@ -0,0 +1,22 @@ +package net.ess3.economy; + +import net.ess3.api.IEssentials; +import net.ess3.storage.AsyncStorageObjectHolder; +import java.io.File; +import java.io.IOException; + + +public class MoneyHolder extends AsyncStorageObjectHolder +{ + public MoneyHolder(IEssentials ess) + { + super(ess, Money.class); + onReload(); + } + + @Override + public File getStorageFile() throws IOException + { + return new File(ess.getPlugin().getDataFolder(), "economy_npcs.yml"); + } +} diff --git a/Essentials/src/net/ess3/economy/Trade.java b/Essentials/src/net/ess3/economy/Trade.java new file mode 100644 index 000000000..a760d5730 --- /dev/null +++ b/Essentials/src/net/ess3/economy/Trade.java @@ -0,0 +1,333 @@ +package net.ess3.economy; + +import static net.ess3.I18n._; +import net.ess3.api.ChargeException; +import net.ess3.api.IEssentials; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.api.server.ItemStack; +import net.ess3.api.server.Location; +import net.ess3.permissions.NoCommandCostPermissions; +import net.ess3.permissions.Permissions; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.text.DateFormat; +import java.util.Date; +import java.util.Locale; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; +import lombok.Cleanup; + + + +public class Trade +{ + private final transient String command; + private final transient Double money; + private final transient ItemStack itemStack; + private final transient Integer exp; + private final transient IEssentials ess; + + public Trade(final String command, final IEssentials ess) + { + this(command, null, null, null, ess); + } + + public Trade(final double money, final IEssentials ess) + { + this(null, money, null, null, ess); + } + + public Trade(final ItemStack items, final IEssentials ess) + { + this(null, null, items, null, ess); + } + + public Trade(final int exp, final IEssentials ess) + { + this(null, null, null, exp, ess); + } + + private Trade(final String command, final Double money, final ItemStack item, final Integer exp, final IEssentials ess) + { + this.command = command; + this.money = money; + this.itemStack = item; + this.exp = exp; + this.ess = ess; + } + + public void isAffordableFor(final IUser user) throws ChargeException + { + final double mon = user.getMoney(); + if (getMoney() != null + && mon < getMoney() + && getMoney() > 0 + && !Permissions.ECO_LOAN.isAuthorized(user)) + { + throw new ChargeException(_("notEnoughMoney")); + } + + if (getItemStack() != null + && !user.getInventory().containsItem(true, true, itemStack)) + { + throw new ChargeException(_("missingItems", getItemStack().getAmount(), getItemStack().getType().toString().toLowerCase(Locale.ENGLISH).replace("_", " "))); + } + + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + + if (command != null && !command.isEmpty() + && !NoCommandCostPermissions.getPermission(command).isAuthorized(user) + && mon < settings.getData().getEconomy().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command) + && 0 < settings.getData().getEconomy().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command) + && !Permissions.ECO_LOAN.isAuthorized(user)) + { + throw new ChargeException(_("notEnoughMoney")); + } + + if (exp != null && exp > 0 + && user.getTotalExperience() < exp) + { + throw new ChargeException(_("notEnoughExperience")); + } + } + + public void pay(final IUser user) + { + pay(user, true); + } + + public boolean pay(final IUser user, final boolean dropItems) + { + boolean success = true; + if (getMoney() != null && getMoney() > 0) + { + user.giveMoney(getMoney()); + } + if (getItemStack() != null) + { + if (dropItems) + { + final Map leftOver = user.getInventory().addItem(true, getItemStack()); + final Location loc = user.getLocation(); + for (ItemStack dropStack : leftOver.values()) + { + final int maxStackSize = dropStack.getType().getMaxStackSize(); + final int stacks = dropStack.getAmount() / maxStackSize; + final int leftover = dropStack.getAmount() % maxStackSize; + final ItemStack[] itemStacks = new ItemStack[stacks + (leftover > 0 ? 1 : 0)]; + for (int i = 0; i < stacks; i++) + { + final ItemStack stack = dropStack.clone(); + stack.setAmount(maxStackSize); + itemStacks[i] = user.getWorld().dropItem(loc, stack); + } + if (leftover > 0) + { + final ItemStack stack = dropStack.clone(); + stack.setAmount(leftover); + itemStacks[stacks] = user.getWorld().dropItem(loc, stack); + } + } + } + else + { + success = user.getInventory().addAllItems(true, getItemStack()); + } + user.updateInventory(); + } + if (getExperience() != null) + { + user.setTotalExperience(user.getTotalExperience() + getExperience()); + } + return success; + } + + public void charge(final IUser user) throws ChargeException + { + if (getMoney() != null) + { + if (!user.canAfford(getMoney()) && getMoney() > 0) + { + throw new ChargeException(_("notEnoughMoney")); + } + user.takeMoney(getMoney()); + } + if (getItemStack() != null) + { + if (!user.getInventory().containsItem(true, true, itemStack)) + { + throw new ChargeException(_("missingItems", getItemStack().getAmount(), getItemStack().getType().toString().toLowerCase(Locale.ENGLISH).replace("_", " "))); + } + user.getInventory().removeItem(true, true, getItemStack()); + user.updateInventory(); + } + if (command != null && !command.isEmpty() + && !NoCommandCostPermissions.getPermission(command).isAuthorized(user)) + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + final double cost = settings.getData().getEconomy().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command); + if (!user.canAfford(cost) && cost > 0) + { + throw new ChargeException(_("notEnoughMoney")); + } + user.takeMoney(cost); + } + if (getExperience() != null) + { + final int experience = user.getTotalExperience(); + if (experience < getExperience() && getExperience() > 0) + { + throw new ChargeException(_("notEnoughExperience")); + } + user.setTotalExperience(experience - getExperience()); + } + } + + public Double getMoney() + { + return money; + } + + public ItemStack getItemStack() + { + return itemStack; + } + + public Integer getExperience() + { + return exp; + } + 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) + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (!settings.getData().getEconomy().isLogEnabled()) + { + return; + } + if (fw == null) + { + try + { + fw = new FileWriter(new File(ess.getPlugin().getDataFolder(), "trade.log"), true); + } + catch (IOException ex) + { + Logger.getLogger("Minecraft").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(settings.getData().getEconomy().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(settings.getData().getEconomy().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("Minecraft").log(Level.SEVERE, null, ex); + } + } + + public static void closeLog() + { + if (fw != null) + { + try + { + fw.close(); + } + catch (IOException ex) + { + Logger.getLogger("Minecraft").log(Level.SEVERE, null, ex); + } + fw = null; + } + } +} diff --git a/Essentials/src/net/ess3/economy/Worth.java b/Essentials/src/net/ess3/economy/Worth.java new file mode 100644 index 000000000..91fa254b7 --- /dev/null +++ b/Essentials/src/net/ess3/economy/Worth.java @@ -0,0 +1,33 @@ +package net.ess3.economy; + +import net.ess3.storage.EnchantmentLevel; +import net.ess3.storage.MapKeyType; +import net.ess3.storage.MapValueType; +import net.ess3.storage.StorageObject; +import java.util.HashMap; +import java.util.Map; +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.bukkit.Material; +import org.bukkit.material.MaterialData; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Worth implements StorageObject +{ + @MapKeyType(MaterialData.class) + @MapValueType(Double.class) + private Map sell = new HashMap(); + @MapKeyType(MaterialData.class) + @MapValueType(Double.class) + private Map buy = new HashMap(); + @MapKeyType(EnchantmentLevel.class) + @MapValueType(Double.class) + private Map enchantmentMultiplier = new HashMap(); + + public Worth() + { + sell.put(new MaterialData(Material.APPLE, (byte)0), 1.0); + } +} diff --git a/Essentials/src/net/ess3/economy/WorthHolder.java b/Essentials/src/net/ess3/economy/WorthHolder.java new file mode 100644 index 000000000..f43441f0d --- /dev/null +++ b/Essentials/src/net/ess3/economy/WorthHolder.java @@ -0,0 +1,86 @@ +package net.ess3.economy; + +import net.ess3.api.IEssentials; +import net.ess3.api.IWorth; +import net.ess3.api.server.ItemStack; +import net.ess3.storage.AsyncStorageObjectHolder; +import net.ess3.storage.EnchantmentLevel; +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.material.MaterialData; + + +public class WorthHolder extends AsyncStorageObjectHolder implements IWorth +{ + public WorthHolder(final IEssentials ess) + { + super(ess, net.ess3.economy.Worth.class); + onReload(false); + } + + @Override + public double getPrice(final ItemStack itemStack) + { + this.acquireReadLock(); + try + { + final Map prices = this.getData().getSell(); + if (prices == null || itemStack == null) + { + return Double.NaN; + } + final Double basePrice = prices.get(itemStack.getData()); + if (basePrice == null || Double.isNaN(basePrice)) + { + return Double.NaN; + } + double multiplier = 1.0; + if (itemStack.getType().getMaxDurability() > 0) { + multiplier *= (double)itemStack.getDurability() / (double)itemStack.getType().getMaxDurability(); + } + if (itemStack.getEnchantments() != null && !itemStack.getEnchantments().isEmpty()) + { + final Map enchantmentMultipliers = this.getData().getEnchantmentMultiplier(); + if (enchantmentMultipliers != null) + { + for (Map.Entry entry : itemStack.getEnchantments().entrySet()) + { + final Double enchMult = enchantmentMultipliers.get(new EnchantmentLevel(entry.getKey(), entry.getValue())); + if (enchMult != null) + { + multiplier *= enchMult; + } + } + } + } + return basePrice * multiplier; + } + finally + { + this.unlock(); + } + } + + @Override + public void setPrice(final ItemStack itemStack, final double price) + { + acquireWriteLock(); + try { + if (getData().getSell() == null) { + getData().setSell(new HashMap()); + } + getData().getSell().put(itemStack.getData(), price); + } finally { + unlock(); + } + } + + @Override + public File getStorageFile() throws IOException + { + return new File(ess.getPlugin().getDataFolder(), "worth.yml"); + } +} diff --git a/Essentials/src/net/ess3/economy/register/Method.java b/Essentials/src/net/ess3/economy/register/Method.java new file mode 100644 index 000000000..228e92569 --- /dev/null +++ b/Essentials/src/net/ess3/economy/register/Method.java @@ -0,0 +1,210 @@ +package net.ess3.economy.register; + +import org.bukkit.plugin.Plugin; + + +/** + * Interface to be implemented by a payment method. + * + * @author Nijikokun (@nijikokun) + * @copyright Copyright (C) 2011 + * @license AOL license + */ +public interface Method +{ + /** + * Encodes the Plugin into an Object disguised as the Plugin. If you want the original Plugin Class you must cast it + * to the correct Plugin, to do so you have to verify the name and or version then cast. + * + *
+	 *  if(method.getName().equalsIgnoreCase("iConomy"))
+	 *   iConomy plugin = ((iConomy)method.getPlugin());
+ * + * @return + * Object + * @see #getName() + * @see #getVersion() + */ + public Object getPlugin(); + + /** + * Returns the actual name of this method. + * + * @return String Plugin name. + */ + public String getName(); + + /** + * Returns the actual version of this method. + * + * @return String Plugin version. + */ + public String getVersion(); + + /** + * Returns the amount of decimal places that get stored + * NOTE: it will return -1 if there is no rounding + * + * @return int for each decimal place + */ + public int fractionalDigits(); + + /** + * Formats amounts into this payment methods style of currency display. + * + * @param amount Double + * @return String - Formatted Currency Display. + */ + public String format(double amount); + + /** + * Allows the verification of bank API existence in this payment method. + * + * @return boolean + */ + public boolean hasBanks(); + + /** + * Determines the existence of a bank via name. + * + * @param bank Bank name + * @return boolean + * @see #hasBanks + */ + public boolean hasBank(String bank); + + /** + * Determines the existence of an account via name. + * + * @param name Account name + * @return boolean + */ + public boolean hasAccount(String name); + + /** + * Check to see if an account name is tied to a bank. + * + * @param bank Bank name + * @param name Account name + * @return boolean + */ + public boolean hasBankAccount(String bank, String name); + + /** + * Forces an account creation + * + * @param name Account name + * @return boolean + */ + public boolean createAccount(String name); + + /** + * Forces an account creation + * + * @param name Account name + * @param balance Initial account balance + * @return boolean + */ + public boolean createAccount(String name, Double balance); + + /** + * Returns a MethodAccount class for an account name. + * + * @param name Account name + * @return MethodAccount or Null + */ + public MethodAccount getAccount(String name); + + /** + * Returns a MethodBankAccount class for an account name. + * + * @param bank Bank name + * @param name Account name + * @return MethodBankAccount or Null + */ + public MethodBankAccount getBankAccount(String bank, String name); + + /** + * Checks to verify the compatibility between this Method and a plugin. + * Internal usage only, for the most part. + * + * @param plugin Plugin + * @return boolean + */ + public boolean isCompatible(Plugin plugin); + + /** + * Set Plugin data. + * + * @param plugin Plugin + */ + public void setPlugin(Plugin plugin); + + + /** + * Contains Calculator and Balance functions for Accounts. + */ + public interface MethodAccount + { + public double balance(); + + public boolean set(double amount); + + public boolean add(double amount); + + public boolean subtract(double amount); + + public boolean multiply(double amount); + + public boolean divide(double amount); + + public boolean hasEnough(double amount); + + public boolean hasOver(double amount); + + public boolean hasUnder(double amount); + + public boolean isNegative(); + + public boolean remove(); + + @Override + public String toString(); + } + + + /** + * Contains Calculator and Balance functions for Bank Accounts. + */ + public interface MethodBankAccount + { + public double balance(); + + public String getBankName(); + + public int getBankId(); + + public boolean set(double amount); + + public boolean add(double amount); + + public boolean subtract(double amount); + + public boolean multiply(double amount); + + public boolean divide(double amount); + + public boolean hasEnough(double amount); + + public boolean hasOver(double amount); + + public boolean hasUnder(double amount); + + public boolean isNegative(); + + public boolean remove(); + + @Override + public String toString(); + } +} diff --git a/Essentials/src/net/ess3/economy/register/Methods.java b/Essentials/src/net/ess3/economy/register/Methods.java new file mode 100644 index 000000000..04208b4cb --- /dev/null +++ b/Essentials/src/net/ess3/economy/register/Methods.java @@ -0,0 +1,296 @@ +package net.ess3.economy.register; + +import java.util.HashSet; +import java.util.Set; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginManager; + + +/** + * The + * Methods initializes Methods that utilize the Method interface based on a "first come, first served" + * basis. + * + * Allowing you to check whether a payment method exists or not. + * + * Methods also allows you to set a preferred method of payment before it captures payment plugins in the initialization + * process. + * + * in + * bukkit.yml:
+ *  economy:
+ *      preferred: "iConomy"
+ * 
+ * + * @author: Nijikokun (@nijikokun) @copyright: Copyright (C) 2011 @license: AOL license + * + */ +public class Methods +{ + private static String version = null; + private static boolean self = false; + private static Method Method = null; + private static String preferred = ""; + private static Set Methods = new HashSet(); + private static Set Dependencies = new HashSet(); + private static Set Attachables = new HashSet(); + + static + { + _init(); + } + + /** + * Implement all methods along with their respective name & class. + */ + private static void _init() + { + addMethod("iConomy", new net.ess3.economy.register.methods.iCo6()); + addMethod("iConomy", new net.ess3.economy.register.methods.iCo5()); + addMethod("iConomy", new net.ess3.economy.register.methods.iCo4()); + addMethod("BOSEconomy", new net.ess3.economy.register.methods.BOSE6()); + addMethod("BOSEconomy", new net.ess3.economy.register.methods.BOSE7()); + addMethod("Currency", new net.ess3.economy.register.methods.MCUR()); + Dependencies.add("MultiCurrency"); + addMethod("Vault", new net.ess3.economy.register.methods.VaultEco()); + } + + /** + * Used by the plugin to setup version + * + * @param v version + */ + public static void setVersion(String v) + { + version = v; + } + + /** + * Use to reset methods during disable + */ + public static void reset() + { + version = null; + self = false; + Method = null; + preferred = ""; + Attachables.clear(); + } + + /** + * Use to get version of Register plugin + * + * @return version + */ + public static String getVersion() + { + return version; + } + + /** + * 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(org.bukkit.plugin.Plugin) + */ + public static Set getDependencies() + { + return Dependencies; + } + + /** + * Interprets Plugin class data to verify whether it is compatible with an existing payment method to use for + * 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) + { + if (method.isCompatible(plugin)) + { + method.setPlugin(plugin); + return method; + } + } + + return null; + } + + private static void addMethod(String name, Method method) + { + Dependencies.add(name); + Methods.add(method); + } + + /** + * Verifies if Register has set a payment method for usage yet. + * + * @return + * boolean + * @see #setMethod(org.bukkit.plugin.Plugin) + * @see #checkDisabled(org.bukkit.plugin.Plugin) + */ + public static boolean hasMethod() + { + return (Method != null); + } + + /** + * Checks Plugin Class against a multitude of checks to verify it's usability as a payment method. + * + * @param PluginManager the plugin manager for the server + * @return + * boolean True on success, False on failure. + */ + public static boolean setMethod(PluginManager manager) + { + if (hasMethod()) + { + return true; + } + + if (self) + { + self = false; + return false; + } + + int count = 0; + boolean match = false; + Plugin plugin = null; + + for (String name : getDependencies()) + { + if (hasMethod()) + { + break; + } + + plugin = manager.getPlugin(name); + if (plugin == null || !plugin.isEnabled()) + { + continue; + } + + Method current = createMethod(plugin); + if (current == null) + { + continue; + } + + if (preferred.isEmpty()) + { + Method = current; + } + else + { + Attachables.add(current); + } + } + + if (!preferred.isEmpty()) + { + do + { + if (hasMethod()) + { + match = true; + } + else + { + for (Method attached : Attachables) + { + if (attached == null) + { + continue; + } + + if (hasMethod()) + { + match = true; + break; + } + + if (preferred.isEmpty()) + { + Method = attached; + } + + if (count == 0) + { + if (preferred.equalsIgnoreCase(attached.getName())) + { + Method = attached; + } + else + { + Method = attached; + } + } + } + + count++; + } + } + while (!match); + } + + return hasMethod(); + } + + /** + * Sets the preferred economy + * + * @return + * boolean + */ + public static boolean setPreferred(String check) + { + if (getDependencies().contains(check)) + { + preferred = check; + return true; + } + + return false; + } + + /** + * Grab the existing and initialized (hopefully) Method Class. + * + * @return + * Method or + * Null + */ + public static Method getMethod() + { + return Method; + } + + /** + * Verify is a plugin is disabled, only does this if we there is an existing payment method initialized in Register. + * + * @param method Plugin data from bukkit, Internal Class file. + * @return + * boolean + */ + public static boolean checkDisabled(Plugin method) + { + if (!hasMethod()) + { + return true; + } + + if (Method.isCompatible(method)) + { + Method = null; + } + + return (Method == null); + } +} diff --git a/Essentials/src/net/ess3/economy/register/methods/BOSE6.java b/Essentials/src/net/ess3/economy/register/methods/BOSE6.java new file mode 100644 index 000000000..051ac92a3 --- /dev/null +++ b/Essentials/src/net/ess3/economy/register/methods/BOSE6.java @@ -0,0 +1,329 @@ +package net.ess3.economy.register.methods; + +import net.ess3.economy.register.Method; +import cosine.boseconomy.BOSEconomy; +import org.bukkit.plugin.Plugin; + + +/** + * BOSEconomy 6 Implementation of Method + * + * @author Nijikokun (@nijikokun) + * @copyright (c) 2011 + * @license AOL license + */ +@SuppressWarnings("deprecation") +public class BOSE6 implements Method +{ + private BOSEconomy BOSEconomy; + + @Override + public BOSEconomy getPlugin() + { + return this.BOSEconomy; + } + + @Override + public String getName() + { + return "BOSEconomy"; + } + + @Override + public String getVersion() + { + return "0.6.2"; + } + + @Override + public int fractionalDigits() + { + return 0; + } + + @Override + public String format(double amount) + { + String currency = this.BOSEconomy.getMoneyNamePlural(); + + if (amount == 1) + { + currency = this.BOSEconomy.getMoneyName(); + } + + return amount + " " + currency; + } + + @Override + public boolean hasBanks() + { + return true; + } + + @Override + public boolean hasBank(String bank) + { + return this.BOSEconomy.bankExists(bank); + } + + @Override + public boolean hasAccount(String name) + { + return this.BOSEconomy.playerRegistered(name, false); + } + + @Override + public boolean hasBankAccount(String bank, String name) + { + return this.BOSEconomy.isBankOwner(bank, name) + || this.BOSEconomy.isBankMember(bank, name); + } + + @Override + public boolean createAccount(String name) + { + if (hasAccount(name)) + { + return false; + } + + this.BOSEconomy.registerPlayer(name); + return true; + } + + @Override + public boolean createAccount(String name, Double balance) + { + if (hasAccount(name)) + { + return false; + } + + this.BOSEconomy.registerPlayer(name); + this.BOSEconomy.setPlayerMoney(name, balance, false); + return true; + } + + @Override + public MethodAccount getAccount(String name) + { + if (!hasAccount(name)) + { + return null; + } + + return new BOSEAccount(name, this.BOSEconomy); + } + + @Override + public MethodBankAccount getBankAccount(String bank, String name) + { + if (!hasBankAccount(bank, name)) + { + return null; + } + + return new BOSEBankAccount(bank, BOSEconomy); + } + + @Override + public boolean isCompatible(Plugin plugin) + { + return plugin.getDescription().getName().equalsIgnoreCase("boseconomy") + && plugin instanceof BOSEconomy + && plugin.getDescription().getVersion().equals("0.6.2"); + } + + @Override + public void setPlugin(Plugin plugin) + { + BOSEconomy = (BOSEconomy)plugin; + } + + + public class BOSEAccount implements MethodAccount + { + private final String name; + private final BOSEconomy BOSEconomy; + + public BOSEAccount(String name, BOSEconomy bOSEconomy) + { + this.name = name; + this.BOSEconomy = bOSEconomy; + } + + @Override + public double balance() + { + return (double)this.BOSEconomy.getPlayerMoney(this.name); + } + + @Override + public boolean set(double amount) + { + int IntAmount = (int)Math.ceil(amount); + return this.BOSEconomy.setPlayerMoney(this.name, IntAmount, false); + } + + @Override + public boolean add(double amount) + { + int IntAmount = (int)Math.ceil(amount); + return this.BOSEconomy.addPlayerMoney(this.name, IntAmount, false); + } + + @Override + public boolean subtract(double amount) + { + int IntAmount = (int)Math.ceil(amount); + int balance = (int)this.balance(); + return this.BOSEconomy.setPlayerMoney(this.name, (balance - IntAmount), false); + } + + @Override + public boolean multiply(double amount) + { + int IntAmount = (int)Math.ceil(amount); + int balance = (int)this.balance(); + return this.BOSEconomy.setPlayerMoney(this.name, (balance * IntAmount), false); + } + + @Override + public boolean divide(double amount) + { + int IntAmount = (int)Math.ceil(amount); + int balance = (int)this.balance(); + return this.BOSEconomy.setPlayerMoney(this.name, (balance / IntAmount), false); + } + + @Override + public boolean hasEnough(double amount) + { + return (this.balance() >= amount); + } + + @Override + public boolean hasOver(double amount) + { + return (this.balance() > amount); + } + + @Override + public boolean hasUnder(double amount) + { + return (this.balance() < amount); + } + + @Override + public boolean isNegative() + { + return (this.balance() < 0); + } + + @Override + public boolean remove() + { + return false; + } + } + + + public class BOSEBankAccount implements MethodBankAccount + { + private final String bank; + private final BOSEconomy BOSEconomy; + + public BOSEBankAccount(String bank, BOSEconomy bOSEconomy) + { + this.bank = bank; + this.BOSEconomy = bOSEconomy; + } + + @Override + public String getBankName() + { + return this.bank; + } + + @Override + public int getBankId() + { + return -1; + } + + @Override + public double balance() + { + return (double)this.BOSEconomy.getBankMoney(bank); + } + + @Override + public boolean set(double amount) + { + int IntAmount = (int)Math.ceil(amount); + return this.BOSEconomy.setBankMoney(bank, IntAmount, true); + } + + @Override + public boolean add(double amount) + { + int IntAmount = (int)Math.ceil(amount); + int balance = (int)this.balance(); + return this.BOSEconomy.setBankMoney(bank, (balance + IntAmount), false); + } + + @Override + public boolean subtract(double amount) + { + int IntAmount = (int)Math.ceil(amount); + int balance = (int)this.balance(); + return this.BOSEconomy.setBankMoney(bank, (balance - IntAmount), false); + } + + @Override + public boolean multiply(double amount) + { + int IntAmount = (int)Math.ceil(amount); + int balance = (int)this.balance(); + return this.BOSEconomy.setBankMoney(bank, (balance * IntAmount), false); + } + + @Override + public boolean divide(double amount) + { + int IntAmount = (int)Math.ceil(amount); + int balance = (int)this.balance(); + return this.BOSEconomy.setBankMoney(bank, (balance / IntAmount), false); + } + + @Override + public boolean hasEnough(double amount) + { + return (this.balance() >= amount); + } + + @Override + public boolean hasOver(double amount) + { + return (this.balance() > amount); + } + + @Override + public boolean hasUnder(double amount) + { + return (this.balance() < amount); + } + + @Override + public boolean isNegative() + { + return (this.balance() < 0); + } + + @Override + public boolean remove() + { + return this.BOSEconomy.removeBank(bank); + } + } +} \ No newline at end of file diff --git a/Essentials/src/net/ess3/economy/register/methods/BOSE7.java b/Essentials/src/net/ess3/economy/register/methods/BOSE7.java new file mode 100644 index 000000000..59e2f5bb5 --- /dev/null +++ b/Essentials/src/net/ess3/economy/register/methods/BOSE7.java @@ -0,0 +1,318 @@ +package net.ess3.economy.register.methods; + +import net.ess3.economy.register.Method; +import cosine.boseconomy.BOSEconomy; +import org.bukkit.plugin.Plugin; + + +/** + * BOSEconomy 7 Implementation of Method + * + * @author Acrobot + * @author Nijikokun (@nijikokun) + * @copyright (c) 2011 + * @license AOL license + */ +public class BOSE7 implements Method +{ + private BOSEconomy BOSEconomy; + + @Override + public BOSEconomy getPlugin() + { + return this.BOSEconomy; + } + + @Override + public String getName() + { + return "BOSEconomy"; + } + + @Override + public String getVersion() + { + return "0.7.0"; + } + + @Override + public int fractionalDigits() + { + return this.BOSEconomy.getFractionalDigits(); + } + + @Override + public String format(double amount) + { + String currency = this.BOSEconomy.getMoneyNamePlural(); + + if (amount == 1) + { + currency = this.BOSEconomy.getMoneyName(); + } + + return amount + " " + currency; + } + + @Override + public boolean hasBanks() + { + return true; + } + + @Override + public boolean hasBank(String bank) + { + return this.BOSEconomy.bankExists(bank); + } + + @Override + public boolean hasAccount(String name) + { + return this.BOSEconomy.playerRegistered(name, false); + } + + @Override + public boolean hasBankAccount(String bank, String name) + { + return this.BOSEconomy.isBankOwner(bank, name) || this.BOSEconomy.isBankMember(bank, name); + } + + @Override + public boolean createAccount(String name) + { + if (hasAccount(name)) + { + return false; + } + + this.BOSEconomy.registerPlayer(name); + return true; + } + + @Override + public boolean createAccount(String name, Double balance) + { + if (hasAccount(name)) + { + return false; + } + + this.BOSEconomy.registerPlayer(name); + this.BOSEconomy.setPlayerMoney(name, balance, false); + return true; + } + + @Override + public MethodAccount getAccount(String name) + { + if (!hasAccount(name)) + { + return null; + } + + return new BOSEAccount(name, this.BOSEconomy); + } + + @Override + public MethodBankAccount getBankAccount(String bank, String name) + { + if (!hasBankAccount(bank, name)) + { + return null; + } + + return new BOSEBankAccount(bank, BOSEconomy); + } + + @Override + public boolean isCompatible(Plugin plugin) + { + return plugin.getDescription().getName().equalsIgnoreCase("boseconomy") + && plugin instanceof BOSEconomy + && !plugin.getDescription().getVersion().equals("0.6.2"); + } + + @Override + public void setPlugin(Plugin plugin) + { + BOSEconomy = (BOSEconomy)plugin; + } + + + public class BOSEAccount implements MethodAccount + { + private String name; + private BOSEconomy BOSEconomy; + + public BOSEAccount(String name, BOSEconomy bOSEconomy) + { + this.name = name; + this.BOSEconomy = bOSEconomy; + } + + @Override + public double balance() + { + return this.BOSEconomy.getPlayerMoneyDouble(this.name); + } + + @Override + public boolean set(double amount) + { + return this.BOSEconomy.setPlayerMoney(this.name, amount, false); + } + + @Override + public boolean add(double amount) + { + return this.BOSEconomy.addPlayerMoney(this.name, amount, false); + } + + @Override + public boolean subtract(double amount) + { + double balance = this.balance(); + return this.BOSEconomy.setPlayerMoney(this.name, (balance - amount), false); + } + + @Override + public boolean multiply(double amount) + { + double balance = this.balance(); + return this.BOSEconomy.setPlayerMoney(this.name, (balance * amount), false); + } + + @Override + public boolean divide(double amount) + { + double balance = this.balance(); + return this.BOSEconomy.setPlayerMoney(this.name, (balance / amount), false); + } + + @Override + public boolean hasEnough(double amount) + { + return (this.balance() >= amount); + } + + @Override + public boolean hasOver(double amount) + { + return (this.balance() > amount); + } + + @Override + public boolean hasUnder(double amount) + { + return (this.balance() < amount); + } + + @Override + public boolean isNegative() + { + return (this.balance() < 0); + } + + @Override + public boolean remove() + { + return false; + } + } + + + public class BOSEBankAccount implements MethodBankAccount + { + private String bank; + private BOSEconomy BOSEconomy; + + public BOSEBankAccount(String bank, BOSEconomy bOSEconomy) + { + this.bank = bank; + this.BOSEconomy = bOSEconomy; + } + + @Override + public String getBankName() + { + return this.bank; + } + + @Override + public int getBankId() + { + return -1; + } + + @Override + public double balance() + { + return this.BOSEconomy.getBankMoneyDouble(bank); + } + + @Override + public boolean set(double amount) + { + return this.BOSEconomy.setBankMoney(bank, amount, true); + } + + @Override + public boolean add(double amount) + { + double balance = this.balance(); + return this.BOSEconomy.setBankMoney(bank, (balance + amount), false); + } + + @Override + public boolean subtract(double amount) + { + double balance = this.balance(); + return this.BOSEconomy.setBankMoney(bank, (balance - amount), false); + } + + @Override + public boolean multiply(double amount) + { + double balance = this.balance(); + return this.BOSEconomy.setBankMoney(bank, (balance * amount), false); + } + + @Override + public boolean divide(double amount) + { + double balance = this.balance(); + return this.BOSEconomy.setBankMoney(bank, (balance / amount), false); + } + + @Override + public boolean hasEnough(double amount) + { + return (this.balance() >= amount); + } + + @Override + public boolean hasOver(double amount) + { + return (this.balance() > amount); + } + + @Override + public boolean hasUnder(double amount) + { + return (this.balance() < amount); + } + + @Override + public boolean isNegative() + { + return (this.balance() < 0); + } + + @Override + public boolean remove() + { + return this.BOSEconomy.removeBank(bank); + } + } +} \ No newline at end of file diff --git a/Essentials/src/net/ess3/economy/register/methods/MCUR.java b/Essentials/src/net/ess3/economy/register/methods/MCUR.java new file mode 100644 index 000000000..e7c1287eb --- /dev/null +++ b/Essentials/src/net/ess3/economy/register/methods/MCUR.java @@ -0,0 +1,191 @@ +package net.ess3.economy.register.methods; + +import net.ess3.economy.register.Method; +import me.ashtheking.currency.Currency; +import me.ashtheking.currency.CurrencyList; +import org.bukkit.plugin.Plugin; + + +/** + * MultiCurrency Method implementation. + * + * @author Acrobot + * @copyright (c) 2011 + * @license AOL license + */ +public class MCUR implements Method +{ + private Currency currencyList; + + @Override + public Object getPlugin() + { + return this.currencyList; + } + + @Override + public String getName() + { + return "MultiCurrency"; + } + + @Override + public String getVersion() + { + return "0.09"; + } + + @Override + public int fractionalDigits() + { + return -1; + } + + @Override + public String format(double amount) + { + return amount + " Currency"; + } + + @Override + public boolean hasBanks() + { + return false; + } + + @Override + public boolean hasBank(String bank) + { + return false; + } + + @Override + public boolean hasAccount(String name) + { + return true; + } + + @Override + public boolean hasBankAccount(String bank, String name) + { + return false; + } + + @Override + public boolean createAccount(String name) + { + CurrencyList.setValue((String)CurrencyList.maxCurrency(name)[0], name, 0); + return true; + } + + @Override + public boolean createAccount(String name, Double balance) + { + CurrencyList.setValue((String)CurrencyList.maxCurrency(name)[0], name, balance); + return true; + } + + @Override + public MethodAccount getAccount(String name) + { + return new MCurrencyAccount(name); + } + + @Override + public MethodBankAccount getBankAccount(String bank, String name) + { + return null; + } + + @Override + public boolean isCompatible(Plugin plugin) + { + return (plugin.getDescription().getName().equalsIgnoreCase("Currency") + || plugin.getDescription().getName().equalsIgnoreCase("MultiCurrency")) + && plugin instanceof Currency; + } + + @Override + public void setPlugin(Plugin plugin) + { + currencyList = (Currency)plugin; + } + + + public class MCurrencyAccount implements MethodAccount + { + private String name; + + public MCurrencyAccount(String name) + { + this.name = name; + } + + @Override + public double balance() + { + return CurrencyList.getValue((String)CurrencyList.maxCurrency(name)[0], name); + } + + @Override + public boolean set(double amount) + { + CurrencyList.setValue((String)CurrencyList.maxCurrency(name)[0], name, amount); + return true; + } + + @Override + public boolean add(double amount) + { + return CurrencyList.add(name, amount); + } + + @Override + public boolean subtract(double amount) + { + return CurrencyList.subtract(name, amount); + } + + @Override + public boolean multiply(double amount) + { + return CurrencyList.multiply(name, amount); + } + + @Override + public boolean divide(double amount) + { + return CurrencyList.divide(name, amount); + } + + @Override + public boolean hasEnough(double amount) + { + return CurrencyList.hasEnough(name, amount); + } + + @Override + public boolean hasOver(double amount) + { + return CurrencyList.hasOver(name, amount); + } + + @Override + public boolean hasUnder(double amount) + { + return CurrencyList.hasUnder(name, amount); + } + + @Override + public boolean isNegative() + { + return CurrencyList.isNegative(name); + } + + @Override + public boolean remove() + { + return CurrencyList.remove(name); + } + } +} diff --git a/Essentials/src/net/ess3/economy/register/methods/VaultEco.java b/Essentials/src/net/ess3/economy/register/methods/VaultEco.java new file mode 100644 index 000000000..804770773 --- /dev/null +++ b/Essentials/src/net/ess3/economy/register/methods/VaultEco.java @@ -0,0 +1,337 @@ +package net.ess3.economy.register.methods; + +import net.ess3.economy.register.Method; +import net.milkbowl.vault.Vault; +import net.milkbowl.vault.economy.Economy; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.RegisteredServiceProvider; + + +public class VaultEco implements Method +{ + private Vault vault; + private Economy economy; + + @Override + public Vault getPlugin() + { + return this.vault; + } + + @Override + public boolean createAccount(String name, Double amount) + { + if (hasAccount(name)) + { + return false; + } + + return false; + } + + @Override + public String getName() + { + + return this.vault.getDescription().getName().concat(" - Economy: ").concat(economy == null ? "NoEco" : economy.getName()); + } + + @Override + public String getVersion() + { + return this.vault.getDescription().getVersion(); + } + + @Override + public int fractionalDigits() + { + return 0; + } + + @Override + public String format(double amount) + { + return this.economy.format(amount); + } + + @Override + public boolean hasBanks() + { + return this.economy.hasBankSupport(); + } + + @Override + public boolean hasBank(String bank) + { + return this.economy.getBanks().contains(bank); + } + + @Override + public boolean hasAccount(String name) + { + return this.economy.hasAccount(name); + } + + @Override + public boolean hasBankAccount(String bank, String name) + { + return this.economy.isBankOwner(bank, name).transactionSuccess() + || this.economy.isBankMember(bank, name).transactionSuccess(); + } + + @Override + public boolean createAccount(String name) + { + return this.economy.createBank(name, "").transactionSuccess(); + } + + public boolean createAccount(String name, double balance) + { + if (!this.economy.createBank(name, "").transactionSuccess()) + { + return false; + } + return this.economy.bankDeposit(name, balance).transactionSuccess(); + } + + @Override + public MethodAccount getAccount(String name) + { + if (!hasAccount(name)) + { + return null; + } + + return new VaultAccount(name, this.economy); + } + + @Override + public MethodBankAccount getBankAccount(String bank, String name) + { + if (!hasBankAccount(bank, name)) + { + return null; + } + + return new VaultBankAccount(bank, economy); + } + + @Override + public boolean isCompatible(Plugin plugin) + { + try + { + RegisteredServiceProvider ecoPlugin = plugin.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); + return plugin instanceof Vault && ecoPlugin != null && !ecoPlugin.getProvider().getName().equals("Essentials Economy"); + } + catch (LinkageError e) + { + return false; + } + catch (Exception e) + { + return false; + } + } + + @Override + public void setPlugin(Plugin plugin) + { + this.vault = (Vault)plugin; + RegisteredServiceProvider economyProvider = this.vault.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); + if (economyProvider != null) + { + this.economy = economyProvider.getProvider(); + } + } + + + public class VaultAccount implements MethodAccount + { + private final String name; + private final Economy economy; + + public VaultAccount(String name, Economy economy) + { + this.name = name; + this.economy = economy; + } + + @Override + public double balance() + { + return this.economy.getBalance(this.name); + } + + @Override + public boolean set(double amount) + { + if (!this.economy.withdrawPlayer(this.name, this.balance()).transactionSuccess()) + { + return false; + } + if (amount == 0) + { + return true; + } + return this.economy.depositPlayer(this.name, amount).transactionSuccess(); + } + + @Override + public boolean add(double amount) + { + return this.economy.depositPlayer(this.name, amount).transactionSuccess(); + } + + @Override + public boolean subtract(double amount) + { + return this.economy.withdrawPlayer(this.name, amount).transactionSuccess(); + } + + @Override + public boolean multiply(double amount) + { + double balance = this.balance(); + return this.set(balance * amount); + } + + @Override + public boolean divide(double amount) + { + double balance = this.balance(); + return this.set(balance / amount); + } + + @Override + public boolean hasEnough(double amount) + { + return (this.balance() >= amount); + } + + @Override + public boolean hasOver(double amount) + { + return (this.balance() > amount); + } + + @Override + public boolean hasUnder(double amount) + { + return (this.balance() < amount); + } + + @Override + public boolean isNegative() + { + return (this.balance() < 0); + } + + @Override + public boolean remove() + { + return this.set(0.0); + } + } + + + public class VaultBankAccount implements MethodBankAccount + { + private final String bank; + private final Economy economy; + + public VaultBankAccount(String bank, Economy economy) + { + this.bank = bank; + this.economy = economy; + } + + @Override + public String getBankName() + { + return this.bank; + } + + @Override + public int getBankId() + { + return -1; + } + + @Override + public double balance() + { + return this.economy.bankBalance(this.bank).balance; + } + + @Override + public boolean set(double amount) + { + if (!this.economy.bankWithdraw(this.bank, this.balance()).transactionSuccess()) + { + return false; + } + if (amount == 0) + { + return true; + } + return this.economy.bankDeposit(this.bank, amount).transactionSuccess(); + } + + @Override + public boolean add(double amount) + { + return this.economy.bankDeposit(this.bank, amount).transactionSuccess(); + } + + @Override + public boolean subtract(double amount) + { + return this.economy.bankWithdraw(this.bank, amount).transactionSuccess(); + } + + @Override + public boolean multiply(double amount) + { + double balance = this.balance(); + return this.set(balance * amount); + } + + @Override + public boolean divide(double amount) + { + double balance = this.balance(); + return this.set(balance / amount); + } + + @Override + public boolean hasEnough(double amount) + { + return (this.balance() >= amount); + } + + @Override + public boolean hasOver(double amount) + { + return (this.balance() > amount); + } + + @Override + public boolean hasUnder(double amount) + { + return (this.balance() < amount); + } + + @Override + public boolean isNegative() + { + return (this.balance() < 0); + } + + @Override + public boolean remove() + { + return this.set(0.0); + } + } +} \ No newline at end of file diff --git a/Essentials/src/net/ess3/economy/register/methods/iCo4.java b/Essentials/src/net/ess3/economy/register/methods/iCo4.java new file mode 100644 index 000000000..adb1c5eb1 --- /dev/null +++ b/Essentials/src/net/ess3/economy/register/methods/iCo4.java @@ -0,0 +1,251 @@ +package net.ess3.economy.register.methods; + +import net.ess3.economy.register.Method; +import com.nijiko.coelho.iConomy.iConomy; +import com.nijiko.coelho.iConomy.system.Account; +import org.bukkit.plugin.Plugin; + + +/** + * iConomy 4 Implementation of Method + * + * @author Nijikokun (@nijikokun) + * @copyright (c) 2011 + * @license AOL license + */ +public class iCo4 implements Method +{ + private iConomy iConomy; + + @Override + public iConomy getPlugin() + { + return this.iConomy; + } + + @Override + public String getName() + { + return "iConomy"; + } + + @Override + public String getVersion() + { + return "4"; + } + + @Override + public int fractionalDigits() + { + return 2; + } + + @Override + public String format(double amount) + { + return com.nijiko.coelho.iConomy.iConomy.getBank().format(amount); + } + + @Override + public boolean hasBanks() + { + return false; + } + + @Override + public boolean hasBank(String bank) + { + return false; + } + + @Override + public boolean hasAccount(String name) + { + return com.nijiko.coelho.iConomy.iConomy.getBank().hasAccount(name); + } + + @Override + public boolean hasBankAccount(String bank, String name) + { + return false; + } + + @Override + public boolean createAccount(String name) + { + if (hasAccount(name)) + { + return false; + } + + try + { + com.nijiko.coelho.iConomy.iConomy.getBank().addAccount(name); + } + catch (Exception E) + { + return false; + } + + return true; + } + + @Override + public boolean createAccount(String name, Double balance) + { + if (hasAccount(name)) + { + return false; + } + + try + { + com.nijiko.coelho.iConomy.iConomy.getBank().addAccount(name, balance); + } + catch (Exception E) + { + return false; + } + + return true; + } + + @Override + public MethodAccount getAccount(String name) + { + return new iCoAccount(com.nijiko.coelho.iConomy.iConomy.getBank().getAccount(name)); + } + + @Override + public MethodBankAccount getBankAccount(String bank, String name) + { + return null; + } + + @Override + public boolean isCompatible(Plugin plugin) + { + return plugin.getDescription().getName().equalsIgnoreCase("iconomy") + && plugin.getClass().getName().equals("com.nijiko.coelho.iConomy.iConomy") + && plugin instanceof iConomy; + } + + @Override + public void setPlugin(Plugin plugin) + { + iConomy = (iConomy)plugin; + } + + + public class iCoAccount implements MethodAccount + { + private Account account; + + public iCoAccount(Account account) + { + this.account = account; + } + + public Account getiCoAccount() + { + return account; + } + + @Override + public double balance() + { + return this.account.getBalance(); + } + + @Override + public boolean set(double amount) + { + if (this.account == null) + { + return false; + } + this.account.setBalance(amount); + return true; + } + + @Override + public boolean add(double amount) + { + if (this.account == null) + { + return false; + } + this.account.add(amount); + return true; + } + + @Override + public boolean subtract(double amount) + { + if (this.account == null) + { + return false; + } + this.account.subtract(amount); + return true; + } + + @Override + public boolean multiply(double amount) + { + if (this.account == null) + { + return false; + } + this.account.multiply(amount); + return true; + } + + @Override + public boolean divide(double amount) + { + if (this.account == null) + { + return false; + } + this.account.divide(amount); + return true; + } + + @Override + public boolean hasEnough(double amount) + { + return this.account.hasEnough(amount); + } + + @Override + public boolean hasOver(double amount) + { + return this.account.hasOver(amount); + } + + @Override + public boolean hasUnder(double amount) + { + return (this.balance() < amount); + } + + @Override + public boolean isNegative() + { + return this.account.isNegative(); + } + + @Override + public boolean remove() + { + if (this.account == null) + { + return false; + } + this.account.remove(); + return true; + } + } +} diff --git a/Essentials/src/net/ess3/economy/register/methods/iCo5.java b/Essentials/src/net/ess3/economy/register/methods/iCo5.java new file mode 100644 index 000000000..7867446de --- /dev/null +++ b/Essentials/src/net/ess3/economy/register/methods/iCo5.java @@ -0,0 +1,371 @@ +package net.ess3.economy.register.methods; + +import net.ess3.economy.register.Method; +import com.iConomy.iConomy; +import com.iConomy.system.Account; +import com.iConomy.system.BankAccount; +import com.iConomy.system.Holdings; +import com.iConomy.util.Constants; +import org.bukkit.plugin.Plugin; + + +/** + * iConomy 5 Implementation of Method + * + * @author Nijikokun (@nijikokun) + * @copyright (c) 2011 + * @license AOL license + */ +public class iCo5 implements Method +{ + private iConomy iConomy; + + @Override + public iConomy getPlugin() + { + return this.iConomy; + } + + @Override + public String getName() + { + return "iConomy"; + } + + @Override + public String getVersion() + { + return "5"; + } + + @Override + public int fractionalDigits() + { + return 2; + } + + @Override + public String format(double amount) + { + return com.iConomy.iConomy.format(amount); + } + + @Override + public boolean hasBanks() + { + return Constants.Banking; + } + + @Override + public boolean hasBank(String bank) + { + return (hasBanks()) && com.iConomy.iConomy.Banks.exists(bank); + } + + @Override + public boolean hasAccount(String name) + { + return com.iConomy.iConomy.hasAccount(name); + } + + @Override + public boolean hasBankAccount(String bank, String name) + { + return (hasBank(bank)) && com.iConomy.iConomy.getBank(bank).hasAccount(name); + } + + @Override + public boolean createAccount(String name) + { + if (hasAccount(name)) + { + return false; + } + + return com.iConomy.iConomy.Accounts.create(name); + } + + @Override + public boolean createAccount(String name, Double balance) + { + if (hasAccount(name)) + { + return false; + } + + if (!com.iConomy.iConomy.Accounts.create(name)) + { + return false; + } + + getAccount(name).set(balance); + + return true; + } + + @Override + public MethodAccount getAccount(String name) + { + return new iCoAccount(com.iConomy.iConomy.getAccount(name)); + } + + @Override + public MethodBankAccount getBankAccount(String bank, String name) + { + return new iCoBankAccount(com.iConomy.iConomy.getBank(bank).getAccount(name)); + } + + @Override + public boolean isCompatible(Plugin plugin) + { + return plugin.getDescription().getName().equalsIgnoreCase("iconomy") + && plugin.getClass().getName().equals("com.iConomy.iConomy") + && plugin instanceof iConomy; + } + + @Override + public void setPlugin(Plugin plugin) + { + iConomy = (iConomy)plugin; + } + + + public class iCoAccount implements MethodAccount + { + private Account account; + private Holdings holdings; + + public iCoAccount(Account account) + { + this.account = account; + this.holdings = account.getHoldings(); + } + + public Account getiCoAccount() + { + return account; + } + + @Override + public double balance() + { + return this.holdings.balance(); + } + + @Override + public boolean set(double amount) + { + if (this.holdings == null) + { + return false; + } + this.holdings.set(amount); + return true; + } + + @Override + public boolean add(double amount) + { + if (this.holdings == null) + { + return false; + } + this.holdings.add(amount); + return true; + } + + @Override + public boolean subtract(double amount) + { + if (this.holdings == null) + { + return false; + } + this.holdings.subtract(amount); + return true; + } + + @Override + public boolean multiply(double amount) + { + if (this.holdings == null) + { + return false; + } + this.holdings.multiply(amount); + return true; + } + + @Override + public boolean divide(double amount) + { + if (this.holdings == null) + { + return false; + } + this.holdings.divide(amount); + return true; + } + + @Override + public boolean hasEnough(double amount) + { + return this.holdings.hasEnough(amount); + } + + @Override + public boolean hasOver(double amount) + { + return this.holdings.hasOver(amount); + } + + @Override + public boolean hasUnder(double amount) + { + return this.holdings.hasUnder(amount); + } + + @Override + public boolean isNegative() + { + return this.holdings.isNegative(); + } + + @Override + public boolean remove() + { + if (this.account == null) + { + return false; + } + this.account.remove(); + return true; + } + } + + + public class iCoBankAccount implements MethodBankAccount + { + private BankAccount account; + private Holdings holdings; + + public iCoBankAccount(BankAccount account) + { + this.account = account; + this.holdings = account.getHoldings(); + } + + public BankAccount getiCoBankAccount() + { + return account; + } + + @Override + public String getBankName() + { + return this.account.getBankName(); + } + + @Override + public int getBankId() + { + return this.account.getBankId(); + } + + @Override + public double balance() + { + return this.holdings.balance(); + } + + @Override + public boolean set(double amount) + { + if (this.holdings == null) + { + return false; + } + this.holdings.set(amount); + return true; + } + + @Override + public boolean add(double amount) + { + if (this.holdings == null) + { + return false; + } + this.holdings.add(amount); + return true; + } + + @Override + public boolean subtract(double amount) + { + if (this.holdings == null) + { + return false; + } + this.holdings.subtract(amount); + return true; + } + + @Override + public boolean multiply(double amount) + { + if (this.holdings == null) + { + return false; + } + this.holdings.multiply(amount); + return true; + } + + @Override + public boolean divide(double amount) + { + if (this.holdings == null) + { + return false; + } + this.holdings.divide(amount); + return true; + } + + @Override + public boolean hasEnough(double amount) + { + return this.holdings.hasEnough(amount); + } + + @Override + public boolean hasOver(double amount) + { + return this.holdings.hasOver(amount); + } + + @Override + public boolean hasUnder(double amount) + { + return this.holdings.hasUnder(amount); + } + + @Override + public boolean isNegative() + { + return this.holdings.isNegative(); + } + + @Override + public boolean remove() + { + if (this.account == null) + { + return false; + } + this.account.remove(); + return true; + } + } +} \ No newline at end of file diff --git a/Essentials/src/net/ess3/economy/register/methods/iCo6.java b/Essentials/src/net/ess3/economy/register/methods/iCo6.java new file mode 100644 index 000000000..961aadef4 --- /dev/null +++ b/Essentials/src/net/ess3/economy/register/methods/iCo6.java @@ -0,0 +1,237 @@ +package net.ess3.economy.register.methods; + +import net.ess3.economy.register.Method; +import com.iCo6.iConomy; +import com.iCo6.system.Account; +import com.iCo6.system.Accounts; +import com.iCo6.system.Holdings; +import org.bukkit.plugin.Plugin; + + +/** + * iConomy 6 Implementation of Method + * + * @author Nijikokun (@nijikokun) + * @copyright (c) 2011 + * @license AOL license + */ +public class iCo6 implements Method +{ + private iConomy iConomy; + + @Override + public iConomy getPlugin() + { + return this.iConomy; + } + + @Override + public String getName() + { + return "iConomy"; + } + + @Override + public String getVersion() + { + return "6"; + } + + @Override + public int fractionalDigits() + { + return 2; + } + + @Override + public String format(double amount) + { + return com.iCo6.iConomy.format(amount); + } + + @Override + public boolean hasBanks() + { + return false; + } + + @Override + public boolean hasBank(String bank) + { + return false; + } + + @Override + public boolean hasAccount(String name) + { + return (new Accounts()).exists(name); + } + + @Override + public boolean hasBankAccount(String bank, String name) + { + return false; + } + + @Override + public boolean createAccount(String name) + { + if (hasAccount(name)) + { + return false; + } + + return (new Accounts()).create(name); + } + + @Override + public boolean createAccount(String name, Double balance) + { + if (hasAccount(name)) + { + return false; + } + + return (new Accounts()).create(name, balance); + } + + @Override + public MethodAccount getAccount(String name) + { + return new iCoAccount((new Accounts()).get(name)); + } + + @Override + public MethodBankAccount getBankAccount(String bank, String name) + { + return null; + } + + @Override + public boolean isCompatible(Plugin plugin) + { + return plugin.getDescription().getName().equalsIgnoreCase("iconomy") + && plugin.getClass().getName().equals("com.iCo6.iConomy") + && plugin instanceof iConomy; + } + + @Override + public void setPlugin(Plugin plugin) + { + iConomy = (iConomy)plugin; + } + + + public class iCoAccount implements MethodAccount + { + private Account account; + private Holdings holdings; + + public iCoAccount(Account account) + { + this.account = account; + this.holdings = account.getHoldings(); + } + + public Account getiCoAccount() + { + return account; + } + + @Override + public double balance() + { + return this.holdings.getBalance(); + } + + @Override + public boolean set(double amount) + { + if (this.holdings == null) + { + return false; + } + this.holdings.setBalance(amount); + return true; + } + + @Override + public boolean add(double amount) + { + if (this.holdings == null) + { + return false; + } + this.holdings.add(amount); + return true; + } + + @Override + public boolean subtract(double amount) + { + if (this.holdings == null) + { + return false; + } + this.holdings.subtract(amount); + return true; + } + + @Override + public boolean multiply(double amount) + { + if (this.holdings == null) + { + return false; + } + this.holdings.multiply(amount); + return true; + } + + @Override + public boolean divide(double amount) + { + if (this.holdings == null) + { + return false; + } + this.holdings.divide(amount); + return true; + } + + @Override + public boolean hasEnough(double amount) + { + return this.holdings.hasEnough(amount); + } + + @Override + public boolean hasOver(double amount) + { + return this.holdings.hasOver(amount); + } + + @Override + public boolean hasUnder(double amount) + { + return this.holdings.hasUnder(amount); + } + + @Override + public boolean isNegative() + { + return this.holdings.isNegative(); + } + + @Override + public boolean remove() + { + if (this.account == null) + { + return false; + } + this.account.remove(); + return true; + } + } +} diff --git a/Essentials/src/net/ess3/listener/EssentialsBlockListener.java b/Essentials/src/net/ess3/listener/EssentialsBlockListener.java new file mode 100644 index 000000000..9393d8dbe --- /dev/null +++ b/Essentials/src/net/ess3/listener/EssentialsBlockListener.java @@ -0,0 +1,50 @@ +package net.ess3.listener; + +import net.ess3.utils.Util; +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import org.bukkit.GameMode; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.inventory.ItemStack; + + +public class EssentialsBlockListener implements Listener +{ + private final transient IEssentials ess; + + public EssentialsBlockListener(final IEssentials ess) + { + super(); + this.ess = ess; + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onBlockPlace(final BlockPlaceEvent event) + { + // Do not rely on getItemInHand(); + // http://leaky.bukkit.org/issues/663 + final ItemStack itemstack = Util.convertBlockToItem(event.getBlockPlaced()); + if (itemstack == null) + { + return; + } + final IUser user = ess.getUser(event.getPlayer()); + final boolean unlimitedForUser = user.getData().hasUnlimited(itemstack.getType()); + if (unlimitedForUser && user.getGameMode() == GameMode.SURVIVAL) + { + ess.getPlugin().scheduleSyncDelayedTask( + new Runnable() + { + @Override + public void run() + { + user.getInventory().addItem(itemstack); + user.updateInventory(); + } + }); + } + } +} diff --git a/Essentials/src/net/ess3/listener/EssentialsEntityListener.java b/Essentials/src/net/ess3/listener/EssentialsEntityListener.java new file mode 100644 index 000000000..14fcd74ff --- /dev/null +++ b/Essentials/src/net/ess3/listener/EssentialsEntityListener.java @@ -0,0 +1,138 @@ +package net.ess3.listener; + +import static net.ess3.I18n._; +import net.ess3.api.IEssentials; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import java.util.List; +import lombok.Cleanup; +import org.bukkit.Material; +import org.bukkit.entity.Animals; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; +import org.bukkit.event.entity.*; +import org.bukkit.inventory.ItemStack; + + +public class EssentialsEntityListener implements Listener +{ + private final transient IEssentials ess; + + public EssentialsEntityListener(final IEssentials ess) + { + this.ess = ess; + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onEntityDamage(final EntityDamageByEntityEvent event) + { + final Entity eAttack = event.getDamager(); + final Entity eDefend = event.getEntity(); + if (eDefend instanceof Player && eAttack instanceof Player) + { + @Cleanup + final IUser attacker = ess.getUser((Player)eAttack); + attacker.acquireReadLock(); + attacker.updateActivity(true); + final ItemStack itemstack = attacker.getItemInHand(); + final List commandList = attacker.getData().getPowertool(itemstack.getType()); + if (commandList != null && !commandList.isEmpty()) + { + for (String command : commandList) + { + if (command != null && !command.isEmpty()) + { + attacker.getServer().dispatchCommand(attacker, command.replaceAll("\\{player\\}", ((Player)eDefend).getName())); + event.setCancelled(true); + return; + } + } + } + } + else if (eDefend instanceof Animals && eAttack instanceof Player) + { + final Player player = (Player)eAttack; + final ItemStack hand = player.getItemInHand(); + if (hand != null && hand.getType() == Material.MILK_BUCKET) + { + ((Animals)eDefend).setBaby(); + hand.setType(Material.BUCKET); + player.setItemInHand(hand); + player.updateInventory(); + event.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onEntityDamage(final EntityDamageEvent event) + { + if (event.getEntity() instanceof Player && ess.getUser((Player)event.getEntity()).isGodModeEnabled()) + { + final Player player = (Player)event.getEntity(); + player.setFireTicks(0); + player.setRemainingAir(player.getMaximumAir()); + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onEntityCombust(final EntityCombustEvent event) + { + if (event.getEntity() instanceof Player && ess.getUser((Player)event.getEntity()).isGodModeEnabled()) + { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onPlayerDeathEvent(final PlayerDeathEvent event) + { + final IUser user = ess.getUser((Player)event.getEntity()); + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (Permissions.BACK_ONDEATH.isAuthorized(user) && !settings.getData().getCommands().isDisabled("back")) + { + user.setLastLocation(); + user.sendMessage(_("backAfterDeath")); + } + if (!settings.getData().getGeneral().isDeathMessages()) + { + event.setDeathMessage(""); + } + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onFoodLevelChange(final FoodLevelChangeEvent event) + { + if (event.getEntity() instanceof Player && ess.getUser((Player)event.getEntity()).isGodModeEnabled()) + { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onEntityRegainHealth(final EntityRegainHealthEvent event) + { + + if (event.getRegainReason() == RegainReason.SATIATED && event.getEntity() instanceof Player) + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + @Cleanup + final IUser user = ess.getUser((Player)event.getEntity()); + user.acquireReadLock(); + if (user.getData().isAfk() && settings.getData().getCommands().getAfk().isFreezeAFKPlayers()) + { + event.setCancelled(true); + } + } + } +} diff --git a/Essentials/src/net/ess3/listener/EssentialsPlayerListener.java b/Essentials/src/net/ess3/listener/EssentialsPlayerListener.java new file mode 100644 index 000000000..129178b84 --- /dev/null +++ b/Essentials/src/net/ess3/listener/EssentialsPlayerListener.java @@ -0,0 +1,438 @@ +package net.ess3.listener; + +import static net.ess3.I18n._; +import net.ess3.api.IEssentials; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import net.ess3.utils.textreader.IText; +import net.ess3.utils.textreader.KeywordReplacer; +import net.ess3.utils.textreader.TextInput; +import net.ess3.utils.textreader.TextPager; +import net.ess3.user.UserData.TimestampType; +import net.ess3.utils.LocationUtil; +import java.io.IOException; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.logging.Level; +import java.util.logging.Logger; +import lombok.Cleanup; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Server; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerLoginEvent.Result; +import org.bukkit.event.player.*; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import org.bukkit.inventory.ItemStack; + + +public class EssentialsPlayerListener implements Listener +{ + private static final Logger LOGGER = Logger.getLogger("Minecraft"); + private final transient Server server; + private final transient IEssentials ess; + + public EssentialsPlayerListener(final IEssentials parent) + { + super(); + this.ess = parent; + this.server = parent.getServer(); + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onPlayerRespawn(final PlayerRespawnEvent event) + { + final IUser user = ess.getUser(event.getPlayer()); + user.updateCompass(); + user.updateDisplayName(); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onPlayerChat(final PlayerChatEvent event) + { + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (user.getData().isMuted()) + { + event.setCancelled(true); + user.sendMessage(_("playerMuted")); + LOGGER.info(_("mutedUserSpeaks", user.getName())); + } + final Iterator it = event.getRecipients().iterator(); + while (it.hasNext()) + { + final IUser player = ess.getUser(it.next()); + if (player.isIgnoringPlayer(user.getName())) + { + it.remove(); + } + } + user.updateActivity(true); + user.updateDisplayName(); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerMove(final PlayerMoveEvent event) + { + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + + if (user.getData().isAfk() && settings.getData().getCommands().getAfk().isFreezeAFKPlayers()) + { + final Location from = event.getFrom(); + final Location to = event.getTo().clone(); + to.setX(from.getX()); + to.setY(from.getY()); + to.setZ(from.getZ()); + try + { + event.setTo(LocationUtil.getSafeDestination(to)); + } + catch (Exception ex) + { + event.setTo(to); + } + return; + } + + final Location afk = user.getAfkPosition(); + if (afk == null || !event.getTo().getWorld().equals(afk.getWorld()) || afk.distanceSquared(event.getTo()) > 9) + { + user.updateActivity(true); + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerQuit(final PlayerQuitEvent event) + { + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (settings.getData().getCommands().getGod().isRemoveOnDisconnect() && user.isGodModeEnabled()) + { + user.toggleGodModeEnabled(); + } + if (user.getData().getInventory() != null) + { + user.getInventory().setContents(user.getData().getInventory().getBukkitInventory()); + user.getData().setInventory(null); + } + user.updateActivity(false); + user.dispose(); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerJoin(final PlayerJoinEvent event) + { + ess.getBackup().startTask(); + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireWriteLock(); + + user.updateDisplayName(); + user.getData().setIpAddress(user.getAddress().getAddress().getHostAddress()); + user.updateActivity(false); + if (Permissions.SLEEPINGIGNORED.isAuthorized(user)) + { + user.setSleepingIgnored(true); + } + + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + + if (!settings.getData().getCommands().isDisabled("motd") && Permissions.MOTD.isAuthorized(user)) + { + try + { + final IText input = new TextInput(user, "motd", true, ess); + final IText output = new KeywordReplacer(input, user, ess); + final TextPager pager = new TextPager(output, true); + pager.showPage("1", null, "motd", user); + } + catch (IOException ex) + { + if (settings.getData().getGeneral().isDebug()) + { + LOGGER.log(Level.WARNING, ex.getMessage(), ex); + } + else + { + LOGGER.log(Level.WARNING, ex.getMessage()); + } + } + } + + if (!settings.getData().getCommands().isDisabled("mail") && Permissions.MAIL.isAuthorized(user)) + { + final List mail = user.getData().getMails(); + if (mail == null || mail.isEmpty()) + { + user.sendMessage(_("noNewMail")); + } + else + { + user.sendMessage(_("youHaveNewMail", mail.size())); + } + } + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerLogin(final PlayerLoginEvent event) + { + switch (event.getResult()) + { + case ALLOWED: + case KICK_FULL: + case KICK_BANNED: + break; + default: + return; + } + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireWriteLock(); + user.getData().setNpc(false); + + final long currentTime = System.currentTimeMillis(); + final boolean banExpired = user.checkBanTimeout(currentTime); + user.checkMuteTimeout(currentTime); + user.checkJailTimeout(currentTime); + + if (!banExpired && (user.isBanned() || event.getResult() == Result.KICK_BANNED)) + { + final String banReason = user.getData().getBan() == null ? "" : user.getData().getBan().getReason(); + event.disallow(Result.KICK_BANNED, banReason == null || banReason.isEmpty() || banReason.equalsIgnoreCase("ban") ? _("defaultBanReason") : banReason); + return; + } + + if (server.getOnlinePlayers().length >= server.getMaxPlayers() && !Permissions.JOINFULLSERVER.isAuthorized(user)) + { + event.disallow(Result.KICK_FULL, _("serverFull")); + return; + } + event.allow(); + + user.setTimestamp(TimestampType.LOGIN, System.currentTimeMillis()); + user.updateCompass(); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerTeleport(final PlayerTeleportEvent event) + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + //There is TeleportCause.COMMMAND but plugins have to actively pass the cause in on their teleports. + if ((event.getCause() == TeleportCause.PLUGIN || event.getCause() == TeleportCause.COMMAND) && settings.getData().getCommands().getBack().isRegisterBackInListener()) + { + final IUser user = ess.getUser(event.getPlayer()); + user.setLastLocation(); + } + + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerEggThrow(final PlayerEggThrowEvent event) + { + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + final ItemStack hand = new ItemStack(Material.EGG, 1); + if (user.getData().hasUnlimited(hand.getType())) + { + user.getInventory().addItem(hand); + user.updateInventory(); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerBucketEmpty(final PlayerBucketEmptyEvent event) + { + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (user.getData().hasUnlimited(event.getBucket())) + { + event.getItemStack().setType(event.getBucket()); + ess.scheduleSyncDelayedTask(new Runnable() + { + @Override + public void run() + { + user.updateInventory(); + } + }); + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlayerCommandPreprocess(final PlayerCommandPreprocessEvent event) + { + final IUser user = ess.getUser(event.getPlayer()); + final String cmd = event.getMessage().toLowerCase(Locale.ENGLISH).split(" ")[0].replace("/", "").toLowerCase(Locale.ENGLISH); + final List commands = Arrays.asList("msg", "r", "mail", "m", "t", "emsg", "tell", "er", "reply", "ereply", "email"); + if (commands.contains(cmd)) + { + for (Player player : ess.getServer().getOnlinePlayers()) + { + @Cleanup + IUser spyer = ess.getUser(player); + spyer.acquireReadLock(); + if (spyer.getData().isSocialspy() && !user.equals(spyer)) + { + player.sendMessage(user.getDisplayName() + " : " + event.getMessage()); + } + } + } + if (!cmd.equalsIgnoreCase("afk")) + { + user.updateActivity(true); + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerChangedWorld(final PlayerChangedWorldEvent event) + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (settings.getData().getChat().getChangeDisplayname()) + { + user.updateDisplayName(); + } + if (!settings.getData().getWorldOptions(event.getPlayer().getLocation().getWorld().getName()).isGodmode() && !Permissions.NOGOD_OVERRIDE.isAuthorized(user)) + { + if (user.getData().isGodmode()) + { + user.sendMessage(_("noGodWorldWarning")); + } + } + if (settings.getData().getCommands().getTpa().isCancelTpRequestsOnWorldChange()) + { + if (user.getTeleportRequester() != null) + { + user.requestTeleport(null, false); + user.sendMessage(_("teleportRequestsCancelledWorldChange")); + } + } + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onPlayerInteract(final PlayerInteractEvent event) + { + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + user.updateActivity(true); + switch (event.getAction()) + { + case RIGHT_CLICK_BLOCK: + if (event.isCancelled()) + { + return; + } + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (settings.getData().getCommands().getHome().isUpdateBedAtDaytime() && event.getClickedBlock().getType() == Material.BED_BLOCK) + { + event.getPlayer().setBedSpawnLocation(event.getClickedBlock().getLocation()); + } + break; + case LEFT_CLICK_AIR: + case LEFT_CLICK_BLOCK: + if (user.getData().hasPowerTools() && user.getData().isPowerToolsEnabled()) + { + if (usePowertools(user)) + { + event.setCancelled(true); + } + } + break; + default: + break; + } + } + + private boolean usePowertools(final IUser user) + { + final ItemStack is = user.getItemInHand(); + int id; + if (is == null || (id = is.getTypeId()) == 0) + { + return false; + } + + final List commandList = user.getData().getPowertool(is.getType()); + if (commandList == null || commandList.isEmpty()) + { + return false; + } + boolean used = false; + // We need to loop through each command and execute + for (final String command : commandList) + { + if (command.matches(".*\\{player\\}.*")) + { + //user.sendMessage("Click a player to use this command"); + continue; + } + else if (command.startsWith("c:")) + { + used = true; + user.chat(command.substring(2)); + } + else + { + used = true; + ess.scheduleSyncDelayedTask( + new Runnable() + { + @Override + public void run() + { + user.getServer().dispatchCommand(user.getBase(), command); + } + }); + } + } + return used; + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onPlayerPickupItem(final PlayerPickupItemEvent event) + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (!settings.getData().getCommands().getAfk().isDisableItemPickupWhileAfk()) + { + return; + } + @Cleanup + final IUser user = ess.getUser(event.getPlayer()); + user.acquireReadLock(); + if (user.getData().isAfk()) + { + event.setCancelled(true); + } + } +} diff --git a/Essentials/src/net/ess3/listener/EssentialsPluginListener.java b/Essentials/src/net/ess3/listener/EssentialsPluginListener.java new file mode 100644 index 000000000..2d5e7a9d4 --- /dev/null +++ b/Essentials/src/net/ess3/listener/EssentialsPluginListener.java @@ -0,0 +1,110 @@ +package net.ess3.listener; + +import net.ess3.api.IEssentials; +import net.ess3.api.IReload; +import net.ess3.api.ISettings; +import net.ess3.ranks.GMGroups; +import net.ess3.ranks.VaultGroups; +import net.ess3.economy.register.Methods; +import net.ess3.settings.General; +import net.ess3.ranks.RanksStorage; +import java.util.logging.Level; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.server.PluginDisableEvent; +import org.bukkit.event.server.PluginEnableEvent; +import org.bukkit.plugin.Plugin; + + +public class EssentialsPluginListener implements Listener, IReload +{ + private final transient IEssentials ess; + + public EssentialsPluginListener(final IEssentials ess) + { + super(); + this.ess = ess; + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPluginEnable(final PluginEnableEvent event) + { + checkGroups(); + //ess.getPermissionsHandler().checkPermissions(); + ess.getCommandHandler().addPlugin(event.getPlugin()); + if (!Methods.hasMethod() && Methods.setMethod(ess.getServer().getPluginManager())) + { + ess.getLogger().log(Level.INFO, "Payment method found ({0} version: {1})", new Object[] + { + Methods.getMethod().getName(), Methods.getMethod().getVersion() + }); + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPluginDisable(final PluginDisableEvent event) + { + checkGroups(); + //ess.getPermissionsHandler().checkPermissions(); + ess.getCommandHandler().removePlugin(event.getPlugin()); + // Check to see if the plugin thats being disabled is the one we are using + if (Methods.hasMethod() && Methods.checkDisabled(event.getPlugin())) + { + Methods.reset(); + ess.getLogger().log(Level.INFO, "Payment method was disabled. No longer accepting payments."); + } + } + + @Override + public void onReload() + { + //ess.getPermissionsHandler().setUseSuperperms(ess.getSettings().useBukkitPermissions()); + } + + private void checkGroups() + { + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + General.GroupStorage storage = General.GroupStorage.FILE; + try + { + storage = settings.getData().getGeneral().getGroupStorage(); + } + finally + { + settings.unlock(); + } + if (storage == General.GroupStorage.GROUPMANAGER) + { + Plugin groupManager = ess.getServer().getPluginManager().getPlugin("GroupManager"); + if (groupManager != null && groupManager.isEnabled() && !(ess.getRanks() instanceof GMGroups)) + { + if (ess.getRanks() instanceof RanksStorage) + { + ess.removeReloadListener((RanksStorage)ess.getRanks()); + } + ess.setRanks(new GMGroups(ess, groupManager)); + return; + } + } + if (storage == General.GroupStorage.VAULT) + { + Plugin vault = ess.getServer().getPluginManager().getPlugin("Vault"); + if (vault != null && vault.isEnabled() && !(ess.getRanks() instanceof VaultGroups)) + { + if (ess.getRanks() instanceof RanksStorage) + { + ess.removeReloadListener((RanksStorage)ess.getRanks()); + } + ess.setRanks(new VaultGroups(ess)); + return; + } + } + if (!(ess.getRanks() instanceof RanksStorage)) + { + ess.setRanks(new RanksStorage(ess)); + ess.addReloadListener((RanksStorage)ess.getRanks()); + } + } +} diff --git a/Essentials/src/net/ess3/listener/TntExplodeListener.java b/Essentials/src/net/ess3/listener/TntExplodeListener.java new file mode 100644 index 000000000..5a423a027 --- /dev/null +++ b/Essentials/src/net/ess3/listener/TntExplodeListener.java @@ -0,0 +1,59 @@ +package net.ess3.listener; + +import net.ess3.api.IEssentials; +import net.ess3.craftbukkit.FakeExplosion; +import java.util.concurrent.atomic.AtomicBoolean; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.EventHandler; +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 AtomicBoolean enabled = new AtomicBoolean(false); + private transient int timer = -1; + + public TntExplodeListener(final IEssentials ess) + { + super(); + this.ess = ess; + } + + public void enable() + { + if (enabled.compareAndSet(false, true)) + { + timer = ess.scheduleSyncDelayedTask(this, 1000); + return; + } + if (timer != -1) + { + ess.getServer().getScheduler().cancelTask(timer); + timer = ess.scheduleSyncDelayedTask(this, 1000); + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onEntityExplode(final EntityExplodeEvent event) + { + if (!enabled.get()) + { + return; + } + if (event.getEntity() instanceof LivingEntity) + { + return; + } + FakeExplosion.createExplosion(event, ess.getServer(), ess.getServer().getOnlinePlayers()); + event.setCancelled(true); + } + + @Override + public void run() + { + enabled.set(false); + } +} diff --git a/Essentials/src/net/ess3/permissions/AbstractSuperpermsPermission.java b/Essentials/src/net/ess3/permissions/AbstractSuperpermsPermission.java new file mode 100644 index 000000000..291284f87 --- /dev/null +++ b/Essentials/src/net/ess3/permissions/AbstractSuperpermsPermission.java @@ -0,0 +1,40 @@ +package net.ess3.permissions; + +import net.ess3.api.IPermission; +import net.ess3.api.server.CommandSender; +import net.ess3.api.server.Permission; + + +public abstract class AbstractSuperpermsPermission implements IPermission +{ + protected Permission bukkitPerm; + + @Override + public Permission getPermission() + { + if (bukkitPerm != null) + { + return bukkitPerm; + } + else + { + return Permission.create(getPermissionName(), getPermissionDefault()); + } + } + + /** + * PermissionDefault is OP, if the method is not overwritten. + * @return + */ + @Override + public Permission.Default getPermissionDefault() + { + return Permission.Default.OP; + } + + @Override + public boolean isAuthorized(final CommandSender sender) + { + return sender.hasPermission(getPermission()); + } +} diff --git a/Essentials/src/net/ess3/permissions/BasePermission.java b/Essentials/src/net/ess3/permissions/BasePermission.java new file mode 100644 index 000000000..c8198c1e2 --- /dev/null +++ b/Essentials/src/net/ess3/permissions/BasePermission.java @@ -0,0 +1,16 @@ +package net.ess3.permissions; + +public class BasePermission extends AbstractSuperpermsPermission { + protected String permission; + + public BasePermission(String base, String permission) + { + super(); + this.permission = base + permission; + } + + public String getPermissionName() + { + return permission; + } +} diff --git a/Essentials/src/net/ess3/permissions/EnchantPermissions.java b/Essentials/src/net/ess3/permissions/EnchantPermissions.java new file mode 100644 index 000000000..996477338 --- /dev/null +++ b/Essentials/src/net/ess3/permissions/EnchantPermissions.java @@ -0,0 +1,23 @@ +package net.ess3.permissions; + +import net.ess3.api.IPermission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + + +public class EnchantPermissions +{ + private static Map permissions = new HashMap(); + + public static IPermission getPermission(final String enchantName) + { + IPermission perm = permissions.get(enchantName); + if (perm == null) + { + perm = new BasePermission("essentials.enchant.",enchantName.toLowerCase(Locale.ENGLISH)); + permissions.put(enchantName, perm); + } + return perm; + } +} \ No newline at end of file diff --git a/Essentials/src/net/ess3/permissions/GivePermissions.java b/Essentials/src/net/ess3/permissions/GivePermissions.java new file mode 100644 index 000000000..a3ced5155 --- /dev/null +++ b/Essentials/src/net/ess3/permissions/GivePermissions.java @@ -0,0 +1,31 @@ +package net.ess3.permissions; + +import net.ess3.api.IPermission; +import net.ess3.api.server.Material; +import net.ess3.api.server.Permission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + + +public class GivePermissions { + private static Map permissions = new HashMap(); + + public static IPermission getPermission(final Material mat) + { + IPermission perm = permissions.get(mat); + if (perm == null) + { + perm = new BasePermission("essentials.give.item-", mat.toString().toLowerCase(Locale.ENGLISH).replace("_", "")) + { + @Override + public Permission.Default getPermissionDefault() + { + return Permission.Default.TRUE; + } + }; + permissions.put(mat, perm); + } + return perm; + } +} diff --git a/Essentials/src/net/ess3/permissions/GroupsPermissions.java b/Essentials/src/net/ess3/permissions/GroupsPermissions.java new file mode 100644 index 000000000..330cb7fb8 --- /dev/null +++ b/Essentials/src/net/ess3/permissions/GroupsPermissions.java @@ -0,0 +1,23 @@ +package net.ess3.permissions; + +import net.ess3.api.IPermission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + + +public class GroupsPermissions +{ + private static Map permissions = new HashMap(); + + public static IPermission getPermission(final String groupName) + { + IPermission perm = permissions.get(groupName); + if (perm == null) + { + perm = new BasePermission("essentials.groups.",groupName.toLowerCase(Locale.ENGLISH)); + permissions.put(groupName, perm); + } + return perm; + } +} diff --git a/Essentials/src/net/ess3/permissions/HelpPermissions.java b/Essentials/src/net/ess3/permissions/HelpPermissions.java new file mode 100644 index 000000000..3e7b251bd --- /dev/null +++ b/Essentials/src/net/ess3/permissions/HelpPermissions.java @@ -0,0 +1,23 @@ +package net.ess3.permissions; + +import net.ess3.api.IPermission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + + +public class HelpPermissions +{ + private static Map permissions = new HashMap(); + + public static IPermission getPermission(final String pluginName) + { + IPermission perm = permissions.get(pluginName); + if (perm == null) + { + perm = new BasePermission("essentials.help.", pluginName.toLowerCase(Locale.ENGLISH)); + permissions.put(pluginName, perm); + } + return perm; + } +} diff --git a/Essentials/src/net/ess3/permissions/ItemPermissions.java b/Essentials/src/net/ess3/permissions/ItemPermissions.java new file mode 100644 index 000000000..c0d4b587d --- /dev/null +++ b/Essentials/src/net/ess3/permissions/ItemPermissions.java @@ -0,0 +1,33 @@ +package net.ess3.permissions; + +import net.ess3.api.IPermission; +import net.ess3.api.server.Material; +import net.ess3.api.server.Permission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + + + +public class ItemPermissions +{ + private static Map permissions = new HashMap(); + + public static IPermission getPermission(final Material mat) + { + IPermission perm = permissions.get(mat); + if (perm == null) + { + perm = new BasePermission("essentials.itemspawn.item-", mat.toString().toLowerCase(Locale.ENGLISH).replace("_", "")) + { + @Override + public Permission.Default getPermissionDefault() + { + return Permission.Default.TRUE; + } + }; + permissions.put(mat, perm); + } + return perm; + } +} \ No newline at end of file diff --git a/Essentials/src/net/ess3/permissions/KitPermissions.java b/Essentials/src/net/ess3/permissions/KitPermissions.java new file mode 100644 index 000000000..fb02392c0 --- /dev/null +++ b/Essentials/src/net/ess3/permissions/KitPermissions.java @@ -0,0 +1,31 @@ +package net.ess3.permissions; + +import net.ess3.api.IPermission; +import net.ess3.api.server.Permission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + + +public class KitPermissions +{ + private static Map permissions = new HashMap(); + + public static IPermission getPermission(final String kitName) + { + IPermission perm = permissions.get(kitName); + if (perm == null) + { + perm = new BasePermission("essentials.kit.", kitName.toLowerCase(Locale.ENGLISH)) + { + @Override + public Permission.Default getPermissionDefault() + { + return Permission.Default.TRUE; + } + }; + permissions.put(kitName, perm); + } + return perm; + } +} diff --git a/Essentials/src/net/ess3/permissions/NoCommandCostPermissions.java b/Essentials/src/net/ess3/permissions/NoCommandCostPermissions.java new file mode 100644 index 000000000..54cd18624 --- /dev/null +++ b/Essentials/src/net/ess3/permissions/NoCommandCostPermissions.java @@ -0,0 +1,23 @@ +package net.ess3.permissions; + +import net.ess3.api.IPermission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + + +public class NoCommandCostPermissions +{ + private static Map permissions = new HashMap(); + + public static IPermission getPermission(final String command) + { + IPermission perm = permissions.get(command); + if (perm == null) + { + perm = new BasePermission("essentials.nocommandcost.", command.toLowerCase(Locale.ENGLISH)); + permissions.put(command, perm); + } + return perm; + } +} diff --git a/Essentials/src/net/ess3/permissions/Permissions.java b/Essentials/src/net/ess3/permissions/Permissions.java new file mode 100644 index 000000000..2f1c83dfe --- /dev/null +++ b/Essentials/src/net/ess3/permissions/Permissions.java @@ -0,0 +1,122 @@ +package net.ess3.permissions; + +import net.ess3.api.IPermission; +import net.ess3.api.server.CommandSender; +import net.ess3.api.server.Permission; +import java.util.Locale; + + +public enum Permissions implements IPermission +{ + AFK, + AFK_KICKEXEMPT, + AFK_OTHERS, + BACK_ONDEATH, + BALANCE_OTHERS, + BAN_EXEMPT, + BAN_NOTIFY, + BAN_OFFLINE, + BREAK_BEDROCK, + CHAT_COLOR, + CHAT_SPY, + CLEARINVENTORY_OTHERS, + DELHOME_OTHERS, + ECO_LOAN(Permission.Default.FALSE), + FEED_OTHERS, + GAMEMODE_OTHERS, + GEOIP_HIDE(Permission.Default.FALSE), + GEOIP_SHOW(Permission.Default.TRUE), + GETPOS_OTHERS, + GOD_OTHERS, + HEAL_COOLDOWN_BYPASS, + HEAL_OTHERS, + HELPOP_RECEIVE, + HOME_OTHERS, + JAIL_EXEMPT, + JOINFULLSERVER, + KICK_EXEMPT, + KICK_NOTIFY, + LIST_HIDDEN, + LIGHTNING_OTHERS, + MAIL, + MAIL_SEND, + MAIL_SENDALL, + MOTD, + MSG_COLOR, + MUTE_EXEMPT, + NEAR_OTHERS, + NICK_COLOR, + NICK_OTHERS, + NOGOD_OVERRIDE, + OVERSIZEDSTACKS(Permission.Default.FALSE), + POWERTOOL_APPEND, + PTIME_OTHERS, + REPAIR_ARMOR, + REPAIR_ENCHANTED, + SEEN_BANREASON, + SETHOME_MULTIPLE, + SETHOME_OTHERS, + SLEEPINGIGNORED, + SPAWN_OTHERS, + SUDO_EXEMPT, + TELEPORT_COOLDOWN_BYPASS, + TELEPORT_HIDDEN, + TELEPORT_TIMER_BYPASS, + TEMPBAN_EXEMPT, + TEMPBAN_OFFLINE, + TIME_SET, + TOGGLEJAIL_OFFLINE, + TPA, + TPAALL, + TPAHERE, + TPOHERE, + UNLIMITED_OTHERS, + WARP_LIST(Permission.Default.TRUE), + WARP_OTHERS; + private static final String base = "essentials."; + private final String permission; + private final Permission.Default defaultPerm; + private transient Permission bukkitPerm = null; + + private Permissions() + { + this(Permission.Default.OP); + } + + private Permissions(final Permission.Default defaultPerm) + { + permission = base + toString().toLowerCase(Locale.ENGLISH).replace('_', '.'); + this.defaultPerm = defaultPerm; + } + + @Override + public String getPermissionName() + { + return permission; + } + + @Override + public Permission getPermission() + { + if (bukkitPerm != null) + { + return bukkitPerm; + } + else + { + return Permission.create(getPermissionName(), getPermissionDefault()); + } + } + + @Override + public Permission.Default getPermissionDefault() + { + return this.defaultPerm; + } + + @Override + public boolean isAuthorized(CommandSender sender) + { + return sender.hasPermission(getPermission()); + } +} diff --git a/Essentials/src/net/ess3/permissions/SpawnerPermissions.java b/Essentials/src/net/ess3/permissions/SpawnerPermissions.java new file mode 100644 index 000000000..67674370a --- /dev/null +++ b/Essentials/src/net/ess3/permissions/SpawnerPermissions.java @@ -0,0 +1,23 @@ +package net.ess3.permissions; + +import net.ess3.api.IPermission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + + +public class SpawnerPermissions +{ + private static Map permissions = new HashMap(); + + public static IPermission getPermission(final String mobName) + { + IPermission perm = permissions.get(mobName); + if (perm == null) + { + perm = new BasePermission("essentials.spawner.", mobName.toLowerCase(Locale.ENGLISH).replace("_", "")); + permissions.put(mobName, perm); + } + return perm; + } +} diff --git a/Essentials/src/net/ess3/permissions/SpawnmobPermissions.java b/Essentials/src/net/ess3/permissions/SpawnmobPermissions.java new file mode 100644 index 000000000..ce8441706 --- /dev/null +++ b/Essentials/src/net/ess3/permissions/SpawnmobPermissions.java @@ -0,0 +1,21 @@ +package net.ess3.permissions; + +import net.ess3.api.IPermission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +public class SpawnmobPermissions { + private static Map permissions = new HashMap(); + + public static IPermission getPermission(final String mobName) + { + IPermission perm = permissions.get(mobName); + if (perm == null) + { + perm = new BasePermission("essentials.spawnmob.", mobName.toLowerCase(Locale.ENGLISH).replace("_", "")); + permissions.put(mobName, perm); + } + return perm; + } +} diff --git a/Essentials/src/net/ess3/permissions/UnlimitedItemPermissions.java b/Essentials/src/net/ess3/permissions/UnlimitedItemPermissions.java new file mode 100644 index 000000000..4387e6ba2 --- /dev/null +++ b/Essentials/src/net/ess3/permissions/UnlimitedItemPermissions.java @@ -0,0 +1,23 @@ +package net.ess3.permissions; + +import net.ess3.api.IPermission; +import net.ess3.api.server.Material; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +public class UnlimitedItemPermissions +{ + private static Map permissions = new HashMap(); + + public static IPermission getPermission(final Material mat) + { + IPermission perm = permissions.get(mat); + if (perm == null) + { + perm = new BasePermission("essentials.unlimited.item-", mat.toString().toLowerCase(Locale.ENGLISH).replace("_", "")); + permissions.put(mat, perm); + } + return perm; + } +} diff --git a/Essentials/src/net/ess3/permissions/WarpPermissions.java b/Essentials/src/net/ess3/permissions/WarpPermissions.java new file mode 100644 index 000000000..fe977ccce --- /dev/null +++ b/Essentials/src/net/ess3/permissions/WarpPermissions.java @@ -0,0 +1,31 @@ +package net.ess3.permissions; + +import net.ess3.api.IPermission; +import net.ess3.api.server.Permission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + + +public class WarpPermissions +{ + private static Map permissions = new HashMap(); + + public static IPermission getPermission(final String warpName) + { + IPermission perm = permissions.get(warpName); + if (perm == null) + { + perm = new BasePermission("essentials.warp.", warpName.toLowerCase(Locale.ENGLISH)) + { + @Override + public Permission.Default getPermissionDefault() + { + return Permission.Default.TRUE; + } + }; + permissions.put(warpName, perm); + } + return perm; + } +} \ No newline at end of file diff --git a/Essentials/src/net/ess3/permissions/WorldPermissions.java b/Essentials/src/net/ess3/permissions/WorldPermissions.java new file mode 100644 index 000000000..d86e22546 --- /dev/null +++ b/Essentials/src/net/ess3/permissions/WorldPermissions.java @@ -0,0 +1,22 @@ +package net.ess3.permissions; + +import net.ess3.api.IPermission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +public class WorldPermissions +{ + private static Map permissions = new HashMap(); + + public static IPermission getPermission(final String worldName) + { + IPermission perm = permissions.get(worldName); + if (perm == null) + { + perm = new BasePermission("essentials.world.", worldName.toLowerCase(Locale.ENGLISH)); + permissions.put(worldName, perm); + } + return perm; + } +} diff --git a/Essentials/src/net/ess3/ranks/GMGroups.java b/Essentials/src/net/ess3/ranks/GMGroups.java new file mode 100644 index 000000000..976cd89ea --- /dev/null +++ b/Essentials/src/net/ess3/ranks/GMGroups.java @@ -0,0 +1,143 @@ +package net.ess3.ranks; + +import net.ess3.utils.Util; +import net.ess3.api.IEssentials; +import net.ess3.api.IRanks; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import java.text.MessageFormat; +import lombok.Cleanup; +import org.anjocaido.groupmanager.GroupManager; +import org.anjocaido.groupmanager.permissions.AnjoPermissionsHandler; +import org.bukkit.plugin.Plugin; + +public class GMGroups implements IRanks { + private final transient IEssentials ess; + private final transient GroupManager groupManager; + + public GMGroups(final IEssentials ess, final Plugin groupManager) + { + this.ess = ess; + this.groupManager = (GroupManager)groupManager; + } + + @Override + public double getHealCooldown(IUser player) + { + AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); + if (handler == null) + { + return 0; + } + return handler.getPermissionDouble(player.getName(), "healcooldown"); + } + + @Override + public double getTeleportCooldown(IUser player) + { + AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); + if (handler == null) + { + return 0; + } + return handler.getPermissionDouble(player.getName(), "teleportcooldown"); + } + + @Override + public double getTeleportDelay(IUser player) + { + AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); + if (handler == null) + { + return 0; + } + return handler.getPermissionDouble(player.getName(), "teleportdelay"); + } + + @Override + public String getPrefix(IUser player) + { + AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); + if (handler == null) + { + return null; + } + return handler.getUserPrefix(player.getName()); + } + + @Override + public String getSuffix(IUser player) + { + AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); + if (handler == null) + { + return null; + } + return handler.getUserSuffix(player.getName()); + } + + @Override + public int getHomeLimit(IUser player) + { + AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); + if (handler == null) + { + return 0; + } + return handler.getPermissionInteger(player.getName(), "homes"); + } + + @Override + public MessageFormat getChatFormat(final IUser player) + { + String format = getRawChatFormat(player); + format = Util.replaceColor(format); + format = format.replace("{DISPLAYNAME}", "%1$s"); + format = format.replace("{GROUP}", "{0}"); + format = format.replace("{MESSAGE}", "%2$s"); + format = format.replace("{WORLDNAME}", "{1}"); + format = format.replace("{SHORTWORLDNAME}", "{2}"); + format = format.replaceAll("\\{(\\D*)\\}", "\\[$1\\]"); + MessageFormat mFormat = new MessageFormat(format); + return mFormat; + } + + private String getRawChatFormat(final IUser player) + { + AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); + if (handler != null) + { + String chatformat = handler.getPermissionString(player.getName(), "chatformat"); + if (chatformat != null && !chatformat.isEmpty()) { + return chatformat; + } + } + + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + return settings.getData().getChat().getDefaultFormat(); + } + + @Override + public String getMainGroup(IUser player) + { + final AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); + if (handler == null) + { + return null; + } + return handler.getGroup(player.getName()); + } + + @Override + public boolean inGroup(IUser player, String groupname) + { + AnjoPermissionsHandler handler = groupManager.getWorldsHolder().getWorldPermissions(player.getBase()); + if (handler == null) + { + return false; + } + return handler.inGroup(player.getName(), groupname); + } +} diff --git a/Essentials/src/net/ess3/ranks/RankOptions.java b/Essentials/src/net/ess3/ranks/RankOptions.java new file mode 100644 index 000000000..a8a8c3298 --- /dev/null +++ b/Essentials/src/net/ess3/ranks/RankOptions.java @@ -0,0 +1,27 @@ +package net.ess3.ranks; + +import net.ess3.storage.Comment; +import net.ess3.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class RankOptions implements StorageObject +{ + @Comment("Message format of chat messages") + private String messageFormat; + @Comment("Prefix for name") + private String prefix; + @Comment("Suffix for name") + private String suffix; + @Comment("Amount of homes a player can have") + private Integer homes; + @Comment("Cooldown between teleports") + private Integer teleportCooldown; + @Comment("Delay before teleport") + private Integer teleportDelay; + @Comment("Cooldown between heals") + private Integer healCooldown; +} diff --git a/Essentials/src/net/ess3/ranks/Ranks.java b/Essentials/src/net/ess3/ranks/Ranks.java new file mode 100644 index 000000000..a77f09846 --- /dev/null +++ b/Essentials/src/net/ess3/ranks/Ranks.java @@ -0,0 +1,28 @@ +package net.ess3.ranks; + +import net.ess3.storage.Comment; +import net.ess3.storage.MapValueType; +import net.ess3.storage.StorageObject; +import java.util.LinkedHashMap; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Ranks implements StorageObject +{ + public Ranks() + { + final RankOptions defaultOptions = new RankOptions(); + ranks.put("default", defaultOptions); + } + @Comment( + { + "The order of the ranks matters, the ranks are checked from top to bottom.", + "All rank names have to be lower case.", + "The ranks can be connected to users using the permission essentials.ranks.rankname" + }) + @MapValueType(RankOptions.class) + private LinkedHashMap ranks = new LinkedHashMap(); +} diff --git a/Essentials/src/net/ess3/ranks/RanksStorage.java b/Essentials/src/net/ess3/ranks/RanksStorage.java new file mode 100644 index 000000000..2e6096837 --- /dev/null +++ b/Essentials/src/net/ess3/ranks/RanksStorage.java @@ -0,0 +1,195 @@ +package net.ess3.ranks; + +import net.ess3.utils.Util; +import net.ess3.api.IEssentials; +import net.ess3.api.IRanks; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.permissions.GroupsPermissions; +import net.ess3.storage.AsyncStorageObjectHolder; +import java.io.File; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Map.Entry; +import lombok.Cleanup; + + +public class RanksStorage extends AsyncStorageObjectHolder implements IRanks +{ + public RanksStorage(final IEssentials ess) + { + super(ess, Ranks.class); + onReload(); + } + + @Override + public File getStorageFile() + { + return new File(ess.getPlugin().getDataFolder(), "ranks.yml"); + } + + public Collection> getGroups(final IUser player) + { + acquireReadLock(); + try + { + final Map groups = getData().getRanks(); + if (groups == null || groups.isEmpty()) + { + return Collections.emptyList(); + } + final ArrayList> list = new ArrayList(); + for (Entry entry : groups.entrySet()) + { + if (GroupsPermissions.getPermission(entry.getKey()).isAuthorized(player)) + { + if(entry.getValue() != null) + { + list.add(entry); + } + } + } + return list; + } + finally + { + unlock(); + } + } + + @Override + public double getHealCooldown(final IUser player) + { + for (Entry groupOptions : getGroups(player)) + { + if (groupOptions.getValue().getHealCooldown() != null) + { + return groupOptions.getValue().getHealCooldown(); + } + } + return 0; + } + + @Override + public double getTeleportCooldown(final IUser player) + { + for (Entry groupOptions : getGroups(player)) + { + if (groupOptions.getValue().getTeleportCooldown() != null) + { + return groupOptions.getValue().getTeleportCooldown(); + } + } + return 0; + } + + @Override + public double getTeleportDelay(final IUser player) + { + for (Entry groupOptions : getGroups(player)) + { + if (groupOptions.getValue().getTeleportDelay() != null) + { + return groupOptions.getValue().getTeleportDelay(); + } + } + return 0; + } + + @Override + public String getPrefix(final IUser player) + { + for (Entry groupOptions : getGroups(player)) + { + if (groupOptions.getValue().getPrefix() != null) + { + return groupOptions.getValue().getPrefix(); + } + } + return ""; + } + + @Override + public String getSuffix(final IUser player) + { + for (Entry groupOptions : getGroups(player)) + { + if (groupOptions.getValue().getSuffix() != null) + { + return groupOptions.getValue().getSuffix(); + } + } + return ""; + } + + @Override + public int getHomeLimit(final IUser player) + { + for (Entry groupOptions : getGroups(player)) + { + if (groupOptions.getValue().getHomes() != null) + { + return groupOptions.getValue().getHomes(); + } + } + return 0; + } + + //TODO: Reimplement caching + @Override + public MessageFormat getChatFormat(final IUser player) + { + String format = getRawChatFormat(player); + format = Util.replaceColor(format); + format = format.replace("{DISPLAYNAME}", "%1$s"); + format = format.replace("{GROUP}", "{0}"); + format = format.replace("{MESSAGE}", "%2$s"); + format = format.replace("{WORLDNAME}", "{1}"); + format = format.replace("{SHORTWORLDNAME}", "{2}"); + format = format.replaceAll("\\{(\\D*)\\}", "\\[$1\\]"); + MessageFormat mFormat = new MessageFormat(format); + return mFormat; + } + + private String getRawChatFormat(final IUser player) + { + for (Entry groupOptions : getGroups(player)) + { + if (groupOptions.getValue().getMessageFormat() != null) + { + return groupOptions.getValue().getMessageFormat(); + } + } + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + return settings.getData().getChat().getDefaultFormat(); + } + + @Override + public boolean inGroup(IUser player, String groupname) + { + for (Entry groupOptions : getGroups(player)) + { + if (groupOptions.getKey().equalsIgnoreCase(groupname)) + { + return true; + } + } + return false; + } + + @Override + public String getMainGroup(IUser player) + { + for (Entry groupOptions : getGroups(player)) + { + return groupOptions.getKey(); + } + return "default"; + } + +} diff --git a/Essentials/src/net/ess3/ranks/VaultGroups.java b/Essentials/src/net/ess3/ranks/VaultGroups.java new file mode 100644 index 000000000..eddc367f8 --- /dev/null +++ b/Essentials/src/net/ess3/ranks/VaultGroups.java @@ -0,0 +1,114 @@ +package net.ess3.ranks; + +import net.ess3.utils.Util; +import net.ess3.api.IEssentials; +import net.ess3.api.IRanks; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import java.text.MessageFormat; +import lombok.Cleanup; +import net.milkbowl.vault.chat.Chat; + + +public class VaultGroups implements IRanks +{ + private final IEssentials ess; + + public VaultGroups(final IEssentials ess) + { + this.ess = ess; + } + + @Override + public double getHealCooldown(IUser player) + { + Chat chat = ess.getServer().getServiceProvider(Chat.class); + return chat.getPlayerInfoDouble(player.getBase(), "healcooldown", 0); + } + + @Override + public double getTeleportCooldown(IUser player) + { + Chat chat = ess.getServer().getServiceProvider(Chat.class); + return chat.getPlayerInfoDouble(player.getBase(), "teleportcooldown", 0); + } + + @Override + public double getTeleportDelay(IUser player) + { + Chat chat = ess.getServer().getServiceProvider(Chat.class); + return chat.getPlayerInfoDouble(player.getBase(), "teleportdelay", 0); + } + + @Override + public String getPrefix(IUser player) + { + Chat chat = ess.getServer().getServiceProvider(Chat.class); + return chat.getPlayerPrefix(player.getBase()); + } + + @Override + public String getSuffix(IUser player) + { + Chat chat = ess.getServer().getServiceProvider(Chat.class); + return chat.getPlayerSuffix(player.getBase()); + } + + @Override + public int getHomeLimit(IUser player) + { + Chat chat = ess.getServer().getServiceProvider(Chat.class); + return chat.getPlayerInfoInteger(player.getBase(), "homes", 0); + } + + @Override + public MessageFormat getChatFormat(final IUser player) + { + String format = getRawChatFormat(player); + format = Util.replaceColor(format); + format = format.replace("{DISPLAYNAME}", "%1$s"); + format = format.replace("{GROUP}", "{0}"); + format = format.replace("{MESSAGE}", "%2$s"); + format = format.replace("{WORLDNAME}", "{1}"); + format = format.replace("{SHORTWORLDNAME}", "{2}"); + format = format.replaceAll("\\{(\\D*)\\}", "\\[$1\\]"); + MessageFormat mFormat = new MessageFormat(format); + return mFormat; + } + + private String getRawChatFormat(final IUser player) + { + Chat chat = ess.getServer().getServiceProvider(Chat.class); + String chatformat = chat.getPlayerInfoString(player.getBase(), "chatformat", ""); + if (chatformat != null && !chatformat.isEmpty()) + { + return chatformat; + } + + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + return settings.getData().getChat().getDefaultFormat(); + } + + @Override + public String getMainGroup(IUser player) + { + Chat chat = ess.getServer().getServiceProvider(Chat.class); + return chat.getPrimaryGroup(player.getBase()); + } + + @Override + public boolean inGroup(IUser player, String groupname) + { + Chat chat = ess.getServer().getServiceProvider(Chat.class); + for (String group : chat.getPlayerGroups(player.getBase())) + { + if (group.equalsIgnoreCase(groupname)) + { + return true; + } + } + return false; + } +} diff --git a/Essentials/src/net/ess3/settings/Backup.java b/Essentials/src/net/ess3/settings/Backup.java new file mode 100644 index 000000000..9b2ce28cf --- /dev/null +++ b/Essentials/src/net/ess3/settings/Backup.java @@ -0,0 +1,17 @@ +package net.ess3.settings; + +import net.ess3.storage.Comment; +import net.ess3.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Backup implements StorageObject +{ + @Comment("Interval in minutes") + private long interval = 60; + @Comment("Add a command that backups your data, e.g. 'rdiff-backup World1 backups/World1'") + private String command; +} diff --git a/Essentials/src/net/ess3/settings/Chat.java b/Essentials/src/net/ess3/settings/Chat.java new file mode 100644 index 000000000..44bafc395 --- /dev/null +++ b/Essentials/src/net/ess3/settings/Chat.java @@ -0,0 +1,33 @@ +package net.ess3.settings; + +import net.ess3.storage.Comment; +import net.ess3.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Chat implements StorageObject +{ + @Comment("The character(s) to prefix all nicknames, so that you know they are not true usernames.") + private String nicknamePrefix = "~"; + @Comment( + { + "Disable this if you have any other plugin, that modifies the displayname of a user.", + "If it is not set, it will be enabled if EssentialsChat is installed, otherwise not." + }) + private Boolean changeDisplayname = true; + private String displaynameFormat = "{PREFIX}{NICKNAMEPREFIX}{NAME}{SUFFIX}"; + @Comment( + { + "If EssentialsChat is installed, this will define how far a player's voice travels, in blocks. Set to 0 to make all chat global.", + "Note that users with the \"essentials.chat.spy\" permission will hear everything, regardless of this setting.", + "Users with essentials.chat.shout can override this by prefixing text with an exclamation mark (!)", + "Or with essentials.chat.question can override this by prefixing text with a question mark (?)", + "You can add command costs for shout/question by adding chat-shout and chat-question to the command costs section." + }) + private int localRadius = 0; + @Comment("Set the default chat format here, it will be overwritten by group specific chat formats.") + private String defaultFormat = "&7[{GROUP}]&f {DISPLAYNAME}&7:&f {MESSAGE}"; +} diff --git a/Essentials/src/net/ess3/settings/Commands.java b/Essentials/src/net/ess3/settings/Commands.java new file mode 100644 index 000000000..899ba6b1d --- /dev/null +++ b/Essentials/src/net/ess3/settings/Commands.java @@ -0,0 +1,74 @@ +package net.ess3.settings; + +import net.ess3.settings.commands.*; +import net.ess3.storage.Comment; +import net.ess3.storage.ListType; +import net.ess3.storage.StorageObject; +import java.util.ArrayList; +import java.util.List; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Commands implements StorageObject +{ + private Afk afk = new Afk(); + private Back back = new Back(); + private God god = new God(); + private Help help = new Help(); + private Home home = new Home(); + private Lightning lightning = new Lightning(); + private net.ess3.settings.commands.List list = new net.ess3.settings.commands.List(); + private Spawnmob spawnmob = new Spawnmob(); + private Tpa tpa = new Tpa(); + @ListType + @Comment( + { + "When a command conflicts with another plugin, by default, Essentials will try to force the OTHER plugin to take", + "priority. If a command is in this list, Essentials will try to give ITSELF priority. This does not always work:", + "usually whichever plugin was updated most recently wins out. However, the full name of the command will always work.", + "For example, if WorldGuard and Essentials are both enabled, and WorldGuard takes control over /god, /essentials:god", + "will still map to Essentials, whereas it might normally get forced upon WorldGuard. Commands prefixed with an \"e\",", + "such as /egod, will always grant Essentials priority.", + "We should try to take priority over /god. If this doesn't work, use /essentials:god or /egod.", + "If god is set using WorldGuard, use /ungod to remove then use whichever you see fit." + }) + private List overridden = new ArrayList(); + @ListType + @Comment("Disabled commands will be completelly unavailable on the server.") + private List disabled = new ArrayList(); + + public boolean isDisabled(final String commandName) + { + if (disabled == null) + { + return false; + } + for (String disabledCommand : disabled) + { + if (commandName.equalsIgnoreCase(disabledCommand)) + { + return true; + } + } + return false; + } + + public boolean isOverridden(final String commandName) + { + if (overridden == null) + { + return false; + } + for (String overriddenCommand : overridden) + { + if (commandName.equalsIgnoreCase(overriddenCommand)) + { + return true; + } + } + return false; + } +} diff --git a/Essentials/src/net/ess3/settings/Economy.java b/Essentials/src/net/ess3/settings/Economy.java new file mode 100644 index 000000000..d1eced963 --- /dev/null +++ b/Essentials/src/net/ess3/settings/Economy.java @@ -0,0 +1,67 @@ +package net.ess3.settings; + +import net.ess3.economy.Worth; +import net.ess3.storage.Comment; +import net.ess3.storage.MapValueType; +import net.ess3.storage.StorageObject; +import java.util.HashMap; +import java.util.Map; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Economy implements StorageObject +{ + @Comment("Defines the balance with which new players begin. Defaults to 0.") + private double startingBalance = 0.0; + @MapValueType(Double.class) + @Comment("Defines the cost to use the given commands PER USE") + private Map commandCosts = new HashMap(); + @Comment("Set this to a currency symbol you want to use.") + private String currencySymbol = "$"; + + public String getCurrencySymbol() + { + return currencySymbol == null || currencySymbol.isEmpty() ? "$" : currencySymbol.substring(0, 1); + } + private final transient static double MAXMONEY = 10000000000000.0; + @Comment( + { + "Set the maximum amount of money a player can have", + "The amount is always limited to 10 trillions because of the limitations of a java double" + }) + private double maxMoney = MAXMONEY; + + public double getMaxMoney() + { + return Math.abs(maxMoney) > MAXMONEY ? MAXMONEY : Math.abs(maxMoney); + } + + @Comment( + { + "Set the minimum amount of money a player can have (must be above the negative of max-money).", + "Setting this to 0, will disable overdrafts/loans completely. Users need 'essentials.eco.loan' perm to go below 0." + }) + private double minMoney = -MAXMONEY; + public double getMinMoney() + { + return Math.abs(minMoney) > MAXMONEY ? -MAXMONEY : minMoney; + } + + @Comment("Enable this to log all interactions with trade/buy/sell signs and sell command") + private boolean logEnabled = false; + private Worth worth = new Worth(); + private boolean tradeInStacks = false; + + public double getCommandCost(String command) + { + if (commandCosts == null) + { + return 0; + } + Double price = commandCosts.get(command); + return price == null || Double.isNaN(price) || Double.isInfinite(price) ? 0 : price; + } +} diff --git a/Essentials/src/net/ess3/settings/General.java b/Essentials/src/net/ess3/settings/General.java new file mode 100644 index 000000000..eb20ba4f4 --- /dev/null +++ b/Essentials/src/net/ess3/settings/General.java @@ -0,0 +1,54 @@ +package net.ess3.settings; + +import net.ess3.storage.Comment; +import net.ess3.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class General implements StorageObject +{ + @Comment("Backup runs a command while saving is disabled") + private Backup backup = new Backup(); + @Comment("You can disable the death messages of minecraft.") + private boolean deathMessages = true; + @Comment("Turn this on, if you want to see more error messages, if something goes wrong.") + private boolean debug = false; + @Comment( + { + "Set the locale here, if you want to change the language of Essentials.", + "If this is not set, Essentials will use the language of your computer.", + "Available locales: da, de, en, fr, nl" + }) + private String locale; + @Comment( + { + "The number of items given, if the quantity parameter is left out in /item or /give.", + "If this number is below 1, the maximum stack size size is given. If oversized stacks", + "is not enabled, any number higher then the maximum stack size results in more than one stack." + }) + private int defaultStacksize = -1; + @Comment( + { + "Oversized stacks are stacks that ignore the normal max stacksize.", + "They can be obtained using /give and /item, if the player has essentials.oversizedstacks permission.", + "How many items should be in a oversized stack?" + }) + private int oversizedStacksize = 64; + + + public enum GroupStorage + { + FILE, GROUPMANAGER, VAULT + } + @Comment( + { + "Sets the place where group options should be stored:", + " FILE: Options are stored inside groups.yml in the Essentials folder", + " GROUPMANAGER: Options are stored using the GroupManager groups", + " VAULT: Options are stored using a permissions plugin supported by Vault" + }) + private GroupStorage groupStorage = GroupStorage.FILE; +} diff --git a/Essentials/src/net/ess3/settings/Jails.java b/Essentials/src/net/ess3/settings/Jails.java new file mode 100644 index 000000000..69bf76643 --- /dev/null +++ b/Essentials/src/net/ess3/settings/Jails.java @@ -0,0 +1,18 @@ +package net.ess3.settings; + +import net.ess3.storage.StoredLocation; +import net.ess3.storage.MapValueType; +import net.ess3.storage.StorageObject; +import java.util.HashMap; +import java.util.Map; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Jails implements StorageObject +{ + @MapValueType(StoredLocation.class) + private Map jails = new HashMap(); +} diff --git a/Essentials/src/net/ess3/settings/Kit.java b/Essentials/src/net/ess3/settings/Kit.java new file mode 100644 index 000000000..6d7800e00 --- /dev/null +++ b/Essentials/src/net/ess3/settings/Kit.java @@ -0,0 +1,19 @@ +package net.ess3.settings; + +import net.ess3.storage.ListType; +import net.ess3.storage.StorageObject; +import java.util.ArrayList; +import java.util.List; +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.bukkit.inventory.ItemStack; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Kit implements StorageObject +{ + @ListType(ItemStack.class) + private List items = new ArrayList(); + private Double delay; +} diff --git a/Essentials/src/net/ess3/settings/Kits.java b/Essentials/src/net/ess3/settings/Kits.java new file mode 100644 index 000000000..7992b9867 --- /dev/null +++ b/Essentials/src/net/ess3/settings/Kits.java @@ -0,0 +1,28 @@ +package net.ess3.settings; + +import net.ess3.storage.MapValueType; +import net.ess3.storage.StorageObject; +import java.util.HashMap; +import java.util.Map; +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Kits implements StorageObject +{ + public Kits() + { + final Kit kit = new Kit(); + kit.setDelay(10.0); + kit.getItems().add(new ItemStack(Material.DIAMOND_SPADE, 1)); + kit.getItems().add(new ItemStack(Material.DIAMOND_PICKAXE, 1)); + kit.getItems().add(new ItemStack(Material.DIAMOND_AXE, 1)); + kits.put("tools", kit); + } + @MapValueType(Kit.class) + private Map kits = new HashMap(); +} diff --git a/Essentials/src/net/ess3/settings/Settings.java b/Essentials/src/net/ess3/settings/Settings.java new file mode 100644 index 000000000..11705f493 --- /dev/null +++ b/Essentials/src/net/ess3/settings/Settings.java @@ -0,0 +1,72 @@ +package net.ess3.settings; + +import net.ess3.storage.Comment; +import net.ess3.storage.MapValueType; +import net.ess3.storage.StorageObject; +import java.util.HashMap; +import java.util.Map; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Settings implements StorageObject +{ + @Comment( + { + "##########################################################", + "+------------------------------------------------------+ #", + "| General Settings | #", + "+------------------------------------------------------+ #", + "##########################################################" + }) + private General general = new General(); + @Comment( + { + "##########################################################", + "+------------------------------------------------------+ #", + "| Chat Settings | #", + "+------------------------------------------------------+ #", + "##########################################################" + }) + private Chat chat = new Chat(); + @Comment( + { + "##########################################################", + "+------------------------------------------------------+ #", + "| Economy Settings | #", + "+------------------------------------------------------+ #", + "##########################################################" + }) + private Economy economy = new Economy(); + @Comment( + { + "##########################################################", + "+------------------------------------------------------+ #", + "| Commands Settings | #", + "+------------------------------------------------------+ #", + "##########################################################" + }) + private Commands commands = new Commands(); + @Comment( + { + "##########################################################", + "+------------------------------------------------------+ #", + "| Worlds Settings | #", + "+------------------------------------------------------+ #", + "##########################################################" + }) + @MapValueType(WorldOptions.class) + private Map worlds = new HashMap(); + + public WorldOptions getWorldOptions(final String name) + { + if (worlds == null) + { + worlds = new HashMap(); + } + final WorldOptions options = worlds.get(name); + return (options == null) ? new WorldOptions() : options; + } +} diff --git a/Essentials/src/net/ess3/settings/SettingsHolder.java b/Essentials/src/net/ess3/settings/SettingsHolder.java new file mode 100644 index 000000000..22238ffa9 --- /dev/null +++ b/Essentials/src/net/ess3/settings/SettingsHolder.java @@ -0,0 +1,64 @@ +package net.ess3.settings; + +import net.ess3.api.IEssentials; +import net.ess3.api.ISettings; +import net.ess3.storage.AsyncStorageObjectHolder; +import java.io.File; +import java.util.concurrent.atomic.AtomicBoolean; + + +public class SettingsHolder extends AsyncStorageObjectHolder implements ISettings +{ + private final transient AtomicBoolean debug = new AtomicBoolean(false); + public SettingsHolder(final IEssentials ess) + { + super(ess, Settings.class); + onReload(); + } + + @Override + public final void onReload() + { + super.onReload(); + acquireReadLock(); + try { + debug.set(getData().getGeneral().isDebug()); + } finally { + unlock(); + } + } + + @Override + public File getStorageFile() + { + return new File(ess.getPlugin().getDataFolder(), "settings.yml"); + } + + @Override + public String getLocale() + { + acquireReadLock(); + try { + return getData().getGeneral().getLocale(); + } finally { + unlock(); + } + } + + @Override + public boolean isDebug() + { + return debug.get(); + } + + public void setDebug(final boolean set) + { + debug.set(set); + acquireWriteLock(); + try { + getData().getGeneral().setDebug(set); + } finally { + unlock(); + } + } +} diff --git a/Essentials/src/net/ess3/settings/Spawns.java b/Essentials/src/net/ess3/settings/Spawns.java new file mode 100644 index 000000000..ec3b6fe5d --- /dev/null +++ b/Essentials/src/net/ess3/settings/Spawns.java @@ -0,0 +1,40 @@ +package net.ess3.settings; + +import net.ess3.storage.Comment; +import net.ess3.storage.StoredLocation; +import net.ess3.storage.MapValueType; +import net.ess3.storage.StorageObject; +import java.util.HashMap; +import java.util.Map; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Spawns implements StorageObject +{ + @Comment( + { + "Should we announce to the server when someone logs in for the first time?", + "If so, use this format, replacing {DISPLAYNAME} with the player name.", + "If not, set to ''" + }) + private String newPlayerAnnouncement = "&dWelcome {DISPLAYNAME} to the server!"; + @Comment( + { + "Priority of the respawn event listener", + "Set this to lowest, if you want e.g. Multiverse to handle the respawning", + "Set this to normal, if you want EssentialsSpawn to handle the respawning", + "Set this to highest, if you want to force EssentialsSpawn to handle the respawning" + }) + private String respawnPriority = "normal"; + @Comment({ + "When we spawn for the first time, which spawnpoint do we use?", + "Set to none if you want to use the spawn point of the world." + }) + private String newbieSpawn = "none"; + @Comment("List of all spawnpoints") + @MapValueType(StoredLocation.class) + private Map spawns = new HashMap(); +} diff --git a/Essentials/src/net/ess3/settings/SpawnsHolder.java b/Essentials/src/net/ess3/settings/SpawnsHolder.java new file mode 100644 index 000000000..652ff8f49 --- /dev/null +++ b/Essentials/src/net/ess3/settings/SpawnsHolder.java @@ -0,0 +1,307 @@ +package net.ess3.settings; + +import static net.ess3.I18n._; +import net.ess3.api.IEssentials; +import net.ess3.api.IEssentialsModule; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.storage.AsyncStorageObjectHolder; +import net.ess3.storage.StoredLocation.WorldNotLoadedException; +import net.ess3.utils.textreader.IText; +import net.ess3.utils.textreader.KeywordReplacer; +import net.ess3.utils.textreader.SimpleTextInput; +import net.ess3.utils.textreader.SimpleTextPager; +import java.io.File; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.logging.Level; +import org.bukkit.*; +import org.bukkit.event.Event; +import org.bukkit.event.EventException; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.plugin.EventExecutor; + + +public class SpawnsHolder extends AsyncStorageObjectHolder implements IEssentialsModule +{ + public SpawnsHolder(final IEssentials ess) + { + super(ess, Spawns.class); + onReload(); + registerListeners(); + } + + @Override + public File getStorageFile() + { + return new File(ess.getPlugin().getDataFolder(), "spawn.yml"); + } + + public void setSpawn(final Location loc, final String group) + { + acquireWriteLock(); + try + { + if (getData().getSpawns() == null) + { + getData().setSpawns(new HashMap()); + } + getData().getSpawns().put(group.toLowerCase(Locale.ENGLISH), new net.ess3.storage.StoredLocation(loc)); + } + finally + { + unlock(); + } + + if ("default".equalsIgnoreCase(group)) + { + loc.getWorld().setSpawnLocation(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); + } + } + + public Location getSpawn(final String group) + { + acquireReadLock(); + try + { + if (getData().getSpawns() == null || group == null) + { + return getWorldSpawn(); + } + final Map spawnMap = getData().getSpawns(); + String groupName = group.toLowerCase(Locale.ENGLISH); + if (!spawnMap.containsKey(groupName)) + { + groupName = "default"; + } + if (!spawnMap.containsKey(groupName)) + { + return getWorldSpawn(); + } + try + { + return spawnMap.get(groupName).getStoredLocation(); + } + catch (WorldNotLoadedException ex) + { + return getWorldSpawn(); + } + } + finally + { + unlock(); + } + } + + private Location getWorldSpawn() + { + for (World world : ess.getServer().getWorlds()) + { + if (world.getEnvironment() != World.Environment.NORMAL) + { + continue; + } + return world.getSpawnLocation(); + } + return ess.getServer().getWorlds().get(0).getSpawnLocation(); + } + + public EventPriority getRespawnPriority() + { + acquireReadLock(); + try + { + for (EventPriority priority : EventPriority.values()) + { + if (priority.toString().equalsIgnoreCase(getData().getRespawnPriority())) + { + return priority; + } + } + return EventPriority.NORMAL; + } + finally + { + unlock(); + } + } + + public Location getNewbieSpawn() + { + acquireReadLock(); + try + { + if (getData().getNewbieSpawn() == null || getData().getNewbieSpawn().isEmpty() + || getData().getNewbieSpawn().equalsIgnoreCase("none")) + { + return null; + } + return getSpawn(getData().getNewbieSpawn()); + } + finally + { + unlock(); + } + } + + public boolean getAnnounceNewPlayers() + { + acquireReadLock(); + try + { + return getData().getNewPlayerAnnouncement() != null && !getData().getNewPlayerAnnouncement().isEmpty(); + } + finally + { + unlock(); + } + } + + public String getAnnounceNewPlayerFormat(IUser user) + { + acquireReadLock(); + try + { + return getData().getNewPlayerAnnouncement().replace('&', '�').replace("��", "&").replace("{PLAYER}", user.getDisplayName()).replace("{DISPLAYNAME}", user.getDisplayName()).replace("{GROUP}", ess.getRanks().getMainGroup(user)).replace("{USERNAME}", user.getName()).replace("{ADDRESS}", user.getAddress().toString()); + } + finally + { + unlock(); + } + } + + private void registerListeners() + { + final SpawnPlayerListener playerListener = new SpawnPlayerListener(ess, this); + ess.getServer().getPluginManager().registerEvent(PlayerRespawnEvent.class, playerListener, getRespawnPriority(), new EventExecutor() + { + @Override + public void execute(final Listener ll, final Event event) throws EventException + { + ((SpawnPlayerListener)ll).onPlayerRespawn((PlayerRespawnEvent)event); + } + }, ess); + ess.getServer().getPluginManager().registerEvent(PlayerJoinEvent.class, playerListener, getRespawnPriority(), new EventExecutor() + { + @Override + public void execute(final Listener ll, final Event event) throws EventException + { + ((SpawnPlayerListener)ll).onPlayerJoin((PlayerJoinEvent)event); + } + }, ess); + } + + + private class SpawnPlayerListener implements Listener + { + private final transient IEssentials ess; + private final transient SpawnsHolder spawns; + + public SpawnPlayerListener(final IEssentials ess, final SpawnsHolder spawns) + { + super(); + this.ess = ess; + this.spawns = spawns; + } + + public void onPlayerRespawn(final PlayerRespawnEvent event) + { + final IUser user = ess.getUser(event.getPlayer()); + + boolean respawnAtHome = false; + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try + { + respawnAtHome = ess.getSettings().getData().getCommands().getHome().isRespawnAtHome(); + } + finally + { + settings.unlock(); + } + if (respawnAtHome) + { + Location home; + final Location bed = user.getBedSpawnLocation(); + if (bed != null && bed.getBlock().getType() == Material.BED_BLOCK) + { + home = bed; + } + else + { + home = user.getHome(user.getLocation()); + } + if (home != null) + { + event.setRespawnLocation(home); + return; + } + } + final Location spawn = spawns.getSpawn(ess.getRanks().getMainGroup(user)); + if (spawn != null) + { + event.setRespawnLocation(spawn); + } + } + + public void onPlayerJoin(final PlayerJoinEvent event) + { + final IUser user = ess.getUser(event.getPlayer()); + + if (user.hasPlayedBefore()) + { + return; + } + + if (spawns.getNewbieSpawn() != null) + { + ess.getPlugin().scheduleSyncDelayedTask(new NewPlayerTeleport(user), 1L); + } + + if (spawns.getAnnounceNewPlayers()) + { + final IText output = new KeywordReplacer(new SimpleTextInput(spawns.getAnnounceNewPlayerFormat(user)), user, ess); + final SimpleTextPager pager = new SimpleTextPager(output); + ess.broadcastMessage(user, pager.getString(0)); + } + } + + + private class NewPlayerTeleport implements Runnable + { + private final transient IUser user; + + public NewPlayerTeleport(final IUser user) + { + this.user = user; + } + + @Override + public void run() + { + if (user.getBase() instanceof OfflinePlayer) + { + return; + } + + try + { + final Location spawn = spawns.getNewbieSpawn(); + if (spawn != null) + { + user.getTeleport().now(spawn, false, PlayerTeleportEvent.TeleportCause.PLUGIN); + } + } + catch (Exception ex) + { + Bukkit.getLogger().log(Level.WARNING, _("teleportNewPlayerError"), ex); + } + } + } + } +} diff --git a/Essentials/src/net/ess3/settings/Warp.java b/Essentials/src/net/ess3/settings/Warp.java new file mode 100644 index 000000000..30384a83e --- /dev/null +++ b/Essentials/src/net/ess3/settings/Warp.java @@ -0,0 +1,14 @@ +package net.ess3.settings; + +import net.ess3.storage.StoredLocation; +import net.ess3.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = false) +public class Warp implements StorageObject +{ + private String name; + private StoredLocation location; +} diff --git a/Essentials/src/net/ess3/settings/WarpHolder.java b/Essentials/src/net/ess3/settings/WarpHolder.java new file mode 100644 index 000000000..a02d77e41 --- /dev/null +++ b/Essentials/src/net/ess3/settings/WarpHolder.java @@ -0,0 +1,35 @@ +package net.ess3.settings; + +import net.ess3.api.IEssentials; +import net.ess3.api.IWarp; +import net.ess3.api.InvalidNameException; +import net.ess3.storage.AsyncStorageObjectHolder; +import java.io.File; +import java.io.IOException; + + +public class WarpHolder extends AsyncStorageObjectHolder implements IWarp +{ + private final String name; + + public WarpHolder(String name, IEssentials ess) + { + super(ess, Warp.class); + this.name = name; + onReload(); + } + + @Override + public File getStorageFile() throws IOException + { + try + { + return ess.getWarps().getWarpFile(name); + } + catch (InvalidNameException ex) + { + throw new IOException(ex.getMessage(), ex); + } + } + +} diff --git a/Essentials/src/net/ess3/settings/WorldOptions.java b/Essentials/src/net/ess3/settings/WorldOptions.java new file mode 100644 index 000000000..cc75a0e63 --- /dev/null +++ b/Essentials/src/net/ess3/settings/WorldOptions.java @@ -0,0 +1,14 @@ +package net.ess3.settings; + +import net.ess3.storage.Comment; +import net.ess3.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = false) +public class WorldOptions implements StorageObject +{ + @Comment("Disables godmode for all players if they teleport to this world.") + private boolean godmode = true; +} diff --git a/Essentials/src/net/ess3/settings/Worlds.java b/Essentials/src/net/ess3/settings/Worlds.java new file mode 100644 index 000000000..0d9fdb754 --- /dev/null +++ b/Essentials/src/net/ess3/settings/Worlds.java @@ -0,0 +1,12 @@ +package net.ess3.settings; + +import net.ess3.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = false) +public class Worlds implements StorageObject +{ + +} \ No newline at end of file diff --git a/Essentials/src/net/ess3/settings/commands/Afk.java b/Essentials/src/net/ess3/settings/commands/Afk.java new file mode 100644 index 000000000..0b337e049 --- /dev/null +++ b/Essentials/src/net/ess3/settings/commands/Afk.java @@ -0,0 +1,38 @@ +package net.ess3.settings.commands; + +import net.ess3.storage.Comment; +import net.ess3.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Afk implements StorageObject +{ + @Comment( + { + "After this timeout in seconds, the user will be set as afk.", + "Set to -1 for no timeout." + }) + private long autoAFK = 300; + @Comment( + { + "Auto-AFK Kick", + "After this timeout in seconds, the user will be kicked from the server.", + "Set to -1 for no timeout." + }) + private long autoAFKKick = -1; + @Comment( + { + "Set this to true, if you want to freeze the player, if he is afk.", + "Other players or monsters can't push him out of afk mode then.", + "This will also enable temporary god mode for the afk player.", + "The player has to use the command /afk to leave the afk mode.", + "You have to add a message to your welcome message or help page,", + "since the player will not get a message, if he tries to move." + }) + private boolean freezeAFKPlayers = false; + + private boolean disableItemPickupWhileAfk = true; +} diff --git a/Essentials/src/net/ess3/settings/commands/Back.java b/Essentials/src/net/ess3/settings/commands/Back.java new file mode 100644 index 000000000..54a4aa246 --- /dev/null +++ b/Essentials/src/net/ess3/settings/commands/Back.java @@ -0,0 +1,19 @@ +package net.ess3.settings.commands; + +import net.ess3.storage.Comment; +import net.ess3.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Back implements StorageObject +{ + @Comment( + { + "Do you want essentials to keep track of previous location for /back in the teleport listener?", + "If you set this to true any plugin that uses teleport will have the previous location registered." + }) + private boolean registerBackInListener = false; +} diff --git a/Essentials/src/net/ess3/settings/commands/God.java b/Essentials/src/net/ess3/settings/commands/God.java new file mode 100644 index 000000000..32ab65c97 --- /dev/null +++ b/Essentials/src/net/ess3/settings/commands/God.java @@ -0,0 +1,15 @@ +package net.ess3.settings.commands; + +import net.ess3.storage.Comment; +import net.ess3.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class God implements StorageObject +{ + @Comment("Turn off god mode when people exit") + private boolean removeOnDisconnect = false; +} diff --git a/Essentials/src/net/ess3/settings/commands/Help.java b/Essentials/src/net/ess3/settings/commands/Help.java new file mode 100644 index 000000000..92d5774c7 --- /dev/null +++ b/Essentials/src/net/ess3/settings/commands/Help.java @@ -0,0 +1,23 @@ +package net.ess3.settings.commands; + +import net.ess3.storage.Comment; +import net.ess3.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Help implements StorageObject +{ + @Comment("Show other plugins commands in help") + private boolean showNonEssCommandsInHelp = true; + @Comment( + { + "Hide plugins which don't give a permission in their plugin.yml for each command.", + "You can override a true value here for a single plugin by adding a permission to a user/group.", + "The individual permission is: essentials.help., anyone with essentials.* or '*' will see all help this setting reguardless.", + "You can use negative permissions to remove access to just a single plugins help if the following is enabled." + }) + private boolean hidePermissionlessCommands = true; +} diff --git a/Essentials/src/net/ess3/settings/commands/Home.java b/Essentials/src/net/ess3/settings/commands/Home.java new file mode 100644 index 000000000..f23af4646 --- /dev/null +++ b/Essentials/src/net/ess3/settings/commands/Home.java @@ -0,0 +1,26 @@ +package net.ess3.settings.commands; + +import net.ess3.storage.Comment; +import net.ess3.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Home implements StorageObject +{ + @Comment("When players die, should they respawn at their homes, instead of the spawnpoint?") + private boolean respawnAtHome = false; + @Comment( + { + "When a player interacts with a bed, should their home be set to that location?", + "If you enable this and remove default player access to the /sethome command, ", + "you can make beds the only way for players to set their home location." + }) + private boolean bedSetsHome = false; + @Comment("If no home is set, should the player be send to spawn, when /home is used.") + private boolean spawnIfNoHome = false; + @Comment("Allows people to set their bed at daytime") + private boolean updateBedAtDaytime = true; +} diff --git a/Essentials/src/net/ess3/settings/commands/Lightning.java b/Essentials/src/net/ess3/settings/commands/Lightning.java new file mode 100644 index 000000000..ee0d2ba3e --- /dev/null +++ b/Essentials/src/net/ess3/settings/commands/Lightning.java @@ -0,0 +1,15 @@ +package net.ess3.settings.commands; + +import net.ess3.storage.Comment; +import net.ess3.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Lightning implements StorageObject +{ + @Comment("Shall we notify users when using /lightning") + private boolean warnPlayer = true; +} diff --git a/Essentials/src/net/ess3/settings/commands/List.java b/Essentials/src/net/ess3/settings/commands/List.java new file mode 100644 index 000000000..6258123f8 --- /dev/null +++ b/Essentials/src/net/ess3/settings/commands/List.java @@ -0,0 +1,16 @@ +package net.ess3.settings.commands; + + +import net.ess3.storage.Comment; +import net.ess3.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class List implements StorageObject +{ + @Comment("Sort output of /list command by groups") + private boolean sortByGroups = true; +} diff --git a/Essentials/src/net/ess3/settings/commands/Spawnmob.java b/Essentials/src/net/ess3/settings/commands/Spawnmob.java new file mode 100644 index 000000000..4f9a524f2 --- /dev/null +++ b/Essentials/src/net/ess3/settings/commands/Spawnmob.java @@ -0,0 +1,15 @@ +package net.ess3.settings.commands; + +import net.ess3.storage.Comment; +import net.ess3.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Spawnmob implements StorageObject +{ + @Comment("The maximum amount of monsters, a player can spawn with a call of /spawnmob.") + private int limit = 10; +} diff --git a/Essentials/src/net/ess3/settings/commands/Tpa.java b/Essentials/src/net/ess3/settings/commands/Tpa.java new file mode 100644 index 000000000..b11e71035 --- /dev/null +++ b/Essentials/src/net/ess3/settings/commands/Tpa.java @@ -0,0 +1,21 @@ +package net.ess3.settings.commands; + +import net.ess3.storage.Comment; +import net.ess3.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Tpa implements StorageObject +{ + @Comment( + { + "Set timeout in seconds for players to accept tpa before request is cancelled.", + "Set to 0 for no timeout." + }) + private int timeout = 0; + @Comment({"Cancels a request made by tpa / tphere on world change to prevent cross world tp"}) + private boolean cancelTpRequestsOnWorldChange = false; +} diff --git a/Essentials/src/net/ess3/settings/geoip/Database.java b/Essentials/src/net/ess3/settings/geoip/Database.java new file mode 100644 index 000000000..3573a9e16 --- /dev/null +++ b/Essentials/src/net/ess3/settings/geoip/Database.java @@ -0,0 +1,16 @@ +package net.ess3.settings.geoip; + +import net.ess3.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Database implements StorageObject +{ + boolean showCities = false; + boolean downloadIfMissing = true; + String downloadUrlCity = "http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz"; + String downloadUrl = "http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz"; +} diff --git a/Essentials/src/net/ess3/settings/geoip/GeoIP.java b/Essentials/src/net/ess3/settings/geoip/GeoIP.java new file mode 100644 index 000000000..c245dcd7a --- /dev/null +++ b/Essentials/src/net/ess3/settings/geoip/GeoIP.java @@ -0,0 +1,15 @@ +package net.ess3.settings.geoip; + +import net.ess3.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class GeoIP implements StorageObject +{ + private Database database = new Database(); + boolean showOnWhois = true; + boolean showOnLogin = true; +} diff --git a/Essentials/src/net/ess3/settings/protect/Prevent.java b/Essentials/src/net/ess3/settings/protect/Prevent.java new file mode 100644 index 000000000..e52be9f54 --- /dev/null +++ b/Essentials/src/net/ess3/settings/protect/Prevent.java @@ -0,0 +1,45 @@ +package net.ess3.settings.protect; + +import net.ess3.storage.*; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.bukkit.Material; +import org.bukkit.entity.CreatureType; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Prevent implements StorageObject +{ + @Comment("Which blocks should a piston not be able to push?") + @ListType(Material.class) + private Set pistonPush = new HashSet(); + private boolean lavaFlow = false; + private boolean waterFlow = false; + // private boolean waterbucketFlow = false; TODO: Test if this still works + private boolean firespread = true; + private boolean lavaFirespread = true; + private boolean lightningFirespread = true; + private boolean portalCreation = false; + private boolean tntExplosion = false; + private boolean fireballExplosion = false; + private boolean fireballFire = false; + private boolean creeperExplosion = false; + private boolean creeperBlockdamage = false; + private boolean enderdragonBlockdamage = false; + private boolean endermanPickup = false; + private boolean villagerDeath = false; + @Comment( + { + "Monsters won't follow players", + "permission essentials.protect.entitytarget.bypass disables this" + }) + private boolean entitytarget = false; + @MapKeyType(CreatureType.class) + @MapValueType(Boolean.class) + private Map spawn = new HashMap(); +} \ No newline at end of file diff --git a/Essentials/src/net/ess3/settings/protect/Protect.java b/Essentials/src/net/ess3/settings/protect/Protect.java new file mode 100644 index 000000000..1f7b3b9c6 --- /dev/null +++ b/Essentials/src/net/ess3/settings/protect/Protect.java @@ -0,0 +1,45 @@ +package net.ess3.settings.protect; + +import net.ess3.storage.Comment; +import net.ess3.storage.ListType; +import net.ess3.storage.StorageObject; +import java.util.HashSet; +import java.util.Set; +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.bukkit.Material; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Protect implements StorageObject +{ + @Comment("Either mysql or sqlite") + private String dbtype = "sqlite"; + @Comment("If you specified MySQL above, you MUST enter the appropriate details here.") + private String dbuser = "root"; + private String dbpassword = ""; + private String dburl = "jdbc:mysql://localhost:3306/minecraft"; + @Comment("For which block types would you like to be alerted?") + @ListType(Material.class) + private Set alertOnPlacement = new HashSet(); + @ListType(Material.class) + private Set alertOnUse = new HashSet(); + @ListType(Material.class) + private Set alertOnBreak = new HashSet(); + @Comment("General physics/behavior modifications") + private Prevent prevent = new Prevent(); + @Comment( + { + "Maximum height the creeper should explode. -1 allows them to explode everywhere.", + "Set prevent.creeper-explosion to true, if you want to disable creeper explosions." + }) + private int creeperMaxHeight = -1; + @Comment("Should we tell people they are not allowed to build") + private boolean warnOnBuildDisallow = true; + @Comment("Disable weather options") + private boolean disableStorm = false; + private boolean disableThunder = false; + private boolean disableLighting = false; + private SignsAndRails signsAndRails = new SignsAndRails(); +} diff --git a/Essentials/src/net/ess3/settings/protect/SignsAndRails.java b/Essentials/src/net/ess3/settings/protect/SignsAndRails.java new file mode 100644 index 000000000..aba39305d --- /dev/null +++ b/Essentials/src/net/ess3/settings/protect/SignsAndRails.java @@ -0,0 +1,26 @@ +package net.ess3.settings.protect; + +import net.ess3.storage.Comment; +import net.ess3.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class SignsAndRails implements StorageObject +{ + @Comment("Protect all signs") + private boolean protectSigns = true; + @Comment("Prevent users from destroying rails") + private boolean protectRails = true; + @Comment( + { + "Blocks below rails/signs are also protected if the respective rail/sign is protected.", + "This makes it more difficult to circumvent protection, and should be enabled.", + "This only has an effect if rails or signs is also enabled." + }) + private boolean blockBelow = true; + @Comment("Prevent placing blocks above protected rails, this is to stop a potential griefing") + private boolean preventBlockAboveRails = false; +} diff --git a/Essentials/src/net/ess3/storage/AbstractDelayedYamlFileReader.java b/Essentials/src/net/ess3/storage/AbstractDelayedYamlFileReader.java new file mode 100644 index 000000000..a8d0ff158 --- /dev/null +++ b/Essentials/src/net/ess3/storage/AbstractDelayedYamlFileReader.java @@ -0,0 +1,93 @@ +package net.ess3.storage; + +import net.ess3.api.IEssentials; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.util.concurrent.locks.ReentrantLock; +import java.util.logging.Level; +import org.bukkit.Bukkit; + + +public abstract class AbstractDelayedYamlFileReader implements Runnable +{ + private final transient Class clazz; + private final transient IEssentials ess; + private final transient ReentrantLock lock = new ReentrantLock(); + + public AbstractDelayedYamlFileReader(final IEssentials ess, final Class clazz) + { + this.clazz = clazz; + this.ess = ess; + } + + public void schedule(boolean instant) + { + if (instant) + { + run(); + } + else + { + ess.getPlugin().scheduleAsyncDelayedTask(this); + } + } + + public abstract File onStart() throws IOException; + + @Override + public void run() + { + lock.lock(); + try + { + final File file = onStart(); + try + { + final FileReader reader = new FileReader(file); + try + { + final T object = new YamlStorageReader(reader, ess.getPlugin()).load(clazz); + onSuccess(object); + } + finally + { + try + { + reader.close(); + } + catch (IOException ex) + { + Bukkit.getLogger().log(Level.SEVERE, "File can't be closed: " + file.toString(), ex); + } + } + + } + catch (FileNotFoundException ex) + { + onException(ex); + Bukkit.getLogger().log(Level.INFO, "File not found: {0}", file.toString()); + } + catch (ObjectLoadException ex) + { + onException(ex); + File broken = new File(file.getAbsolutePath() + ".broken." + System.currentTimeMillis()); + file.renameTo(broken); + Bukkit.getLogger().log(Level.SEVERE, "The file " + file.toString() + " is broken, it has been renamed to " + broken.toString(), ex.getCause()); + } + } + catch (IOException ex) + { + Bukkit.getLogger().log(Level.SEVERE, "File could not be opened: " + ex.getMessage(), ex); + } + finally + { + lock.unlock(); + } + } + + public abstract void onSuccess(T object); + + public abstract void onException(Exception exception); +} diff --git a/Essentials/src/net/ess3/storage/AbstractDelayedYamlFileWriter.java b/Essentials/src/net/ess3/storage/AbstractDelayedYamlFileWriter.java new file mode 100644 index 000000000..baeee2ce8 --- /dev/null +++ b/Essentials/src/net/ess3/storage/AbstractDelayedYamlFileWriter.java @@ -0,0 +1,75 @@ +package net.ess3.storage; + +import net.ess3.api.IEssentials; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.concurrent.locks.ReentrantLock; +import java.util.logging.Level; +import org.bukkit.Bukkit; + + +public abstract class AbstractDelayedYamlFileWriter implements Runnable +{ + private final transient IEssentials ess; + private final transient ReentrantLock lock = new ReentrantLock(); + + public AbstractDelayedYamlFileWriter(final IEssentials ess) + { + this.ess = ess; + } + + public void schedule() + { + ess.getPlugin().scheduleAsyncDelayedTask(this); + } + + public abstract File getFile() throws IOException; + + public abstract StorageObject getObject(); + + @Override + public void run() + { + lock.lock(); + try + { + final File file = getFile(); + PrintWriter pw = null; + try + { + final StorageObject object = getObject(); + final File folder = file.getParentFile(); + if (!folder.exists()) + { + folder.mkdirs(); + } + pw = new PrintWriter(file); + new YamlStorageWriter(pw).save(object); + } + catch (FileNotFoundException ex) + { + Bukkit.getLogger().log(Level.SEVERE, file.toString(), ex); + } + finally + { + onFinish(); + if (pw != null) + { + pw.close(); + } + } + } + catch (IOException ex) + { + Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); + } + finally + { + lock.unlock(); + } + } + + public abstract void onFinish(); +} diff --git a/Essentials/src/net/ess3/storage/AsyncStorageObjectHolder.java b/Essentials/src/net/ess3/storage/AsyncStorageObjectHolder.java new file mode 100644 index 000000000..8e904dea9 --- /dev/null +++ b/Essentials/src/net/ess3/storage/AsyncStorageObjectHolder.java @@ -0,0 +1,186 @@ +package net.ess3.storage; + +import net.ess3.api.IEssentials; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.logging.Level; +import org.bukkit.Bukkit; + + +public abstract class AsyncStorageObjectHolder implements IStorageObjectHolder +{ + private transient T data; + private final transient ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); + private final transient Class clazz; + protected final transient IEssentials ess; + private final transient StorageObjectDataWriter writer; + private final transient StorageObjectDataReader reader; + private final transient AtomicBoolean loaded = new AtomicBoolean(false); + + public AsyncStorageObjectHolder(final IEssentials ess, final Class clazz) + { + this.ess = ess; + this.clazz = clazz; + writer = new StorageObjectDataWriter(); + reader = new StorageObjectDataReader(); + try + { + this.data = clazz.newInstance(); + } + catch (Exception ex) + { + Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); + } + } + + /** + * Warning: If you access this method, you have to acquire a read or write lock first + * + * + * @return Object storing all the data + */ + @Override + public T getData() + { + if (!loaded.get()) + { + reader.schedule(true); + } + return data; + } + + @Override + public void acquireReadLock() + { + rwl.readLock().lock(); + } + + @Override + public void acquireWriteLock() + { + while (rwl.getReadHoldCount() > 0) + { + rwl.readLock().unlock(); + } + rwl.writeLock().lock(); + rwl.readLock().lock(); + } + + @Override + public void close() + { + unlock(); + } + + @Override + public void unlock() + { + if (rwl.isWriteLockedByCurrentThread()) + { + rwl.writeLock().unlock(); + writer.schedule(); + } + while (rwl.getReadHoldCount() > 0) + { + rwl.readLock().unlock(); + } + } + + @Override + public void onReload() + { + onReload(true); + } + + public void onReload(final boolean instant) + { + reader.schedule(instant); + } + + public abstract File getStorageFile() throws IOException; + + + private class StorageObjectDataWriter extends AbstractDelayedYamlFileWriter + { + public StorageObjectDataWriter() + { + super(ess); + } + + @Override + public File getFile() throws IOException + { + return getStorageFile(); + } + + @Override + public StorageObject getObject() + { + acquireReadLock(); + return getData(); + } + + @Override + public void onFinish() + { + unlock(); + } + } + + + private class StorageObjectDataReader extends AbstractDelayedYamlFileReader + { + public StorageObjectDataReader() + { + super(ess, clazz); + } + + @Override + public File onStart() throws IOException + { + final File file = getStorageFile(); + while (rwl.getReadHoldCount() > 0) + { + rwl.readLock().unlock(); + } + rwl.writeLock().lock(); + return file; + } + + @Override + public void onSuccess(final T object) + { + if (object != null) + { + data = object; + } + rwl.writeLock().unlock(); + loaded.set(true); + } + + @Override + public void onException(final Exception exception) + { + if (data == null) + { + try + { + data = clazz.newInstance(); + } + catch (Exception ex) + { + Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); + } + } + rwl.writeLock().unlock(); + loaded.set(true); + if (exception instanceof FileNotFoundException) + { + writer.schedule(); + } + } + } +} diff --git a/Essentials/src/net/ess3/storage/BukkitConstructor.java b/Essentials/src/net/ess3/storage/BukkitConstructor.java new file mode 100644 index 000000000..068d31608 --- /dev/null +++ b/Essentials/src/net/ess3/storage/BukkitConstructor.java @@ -0,0 +1,439 @@ +package net.ess3.storage; + +import net.ess3.Essentials; +import net.ess3.api.server.IPlugin; +import net.ess3.api.server.Material; +import java.lang.reflect.Field; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.regex.Pattern; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; +import org.bukkit.material.MaterialData; +import org.yaml.snakeyaml.TypeDescription; +import org.yaml.snakeyaml.constructor.Constructor; +import org.yaml.snakeyaml.error.YAMLException; +import org.yaml.snakeyaml.introspector.Property; +import org.yaml.snakeyaml.nodes.*; + + +public class BukkitConstructor extends Constructor +{ + private final transient Pattern NUMPATTERN = Pattern.compile("\\d+"); + private final transient IPlugin plugin; + + public BukkitConstructor(final Class clazz, final IPlugin plugin) + { + super(clazz); + this.plugin = plugin; + yamlClassConstructors.put(NodeId.scalar, new ConstructBukkitScalar()); + yamlClassConstructors.put(NodeId.mapping, new ConstructBukkitMapping()); + } + + + private class ConstructBukkitScalar extends ConstructScalar + { + @Override + public Object construct(final Node node) + { + if (node.getType().equals(Material.class)) + { + final String val = (String)constructScalar((ScalarNode)node); + Material mat; + if (NUMPATTERN.matcher(val).matches()) + { + final int typeId = Integer.parseInt(val); + mat = Material.getMaterial(typeId); + } + else + { + mat = Material.matchMaterial(val); + } + return mat; + } + if (node.getType().equals(MaterialData.class)) + { + final String val = (String)constructScalar((ScalarNode)node); + if (val.isEmpty()) + { + return null; + } + final String[] split = val.split("[:+',;.]", 2); + if (split.length == 0) + { + return null; + } + Material mat; + if (NUMPATTERN.matcher(split[0]).matches()) + { + final int typeId = Integer.parseInt(split[0]); + mat = Material.get(typeId); + } + else + { + mat = Material.match(split[0]); + } + if (mat == null) + { + return null; + } + byte data = 0; + if (split.length == 2 && NUMPATTERN.matcher(split[1]).matches()) + { + data = Byte.parseByte(split[1]); + } + return new MaterialData(mat, data); + } + if (node.getType().equals(ItemStack.class)) + { + final String val = (String)constructScalar((ScalarNode)node); + if (val.isEmpty()) + { + return null; + } + final String[] split1 = val.split("\\W"); + if (split1.length == 0) + { + return null; + } + final String[] split2 = split1[0].split("[:+',;.]", 2); + if (split2.length == 0) + { + return null; + } + Material mat; + if (NUMPATTERN.matcher(split2[0]).matches()) + { + final int typeId = Integer.parseInt(split2[0]); + mat = Material.getMaterial(typeId); + } + else + { + mat = Material.matchMaterial(split2[0]); + } + if (mat == null) + { + return null; + } + short data = 0; + if (split2.length == 2 && NUMPATTERN.matcher(split2[1]).matches()) + { + data = Short.parseShort(split2[1]); + } + int size = mat.getMaxStackSize(); + if (split1.length > 1 && NUMPATTERN.matcher(split1[1]).matches()) + { + size = Integer.parseInt(split1[1]); + } + final ItemStack stack = new ItemStack(mat, size, data); + if (split1.length > 2) + { + for (int i = 2; i < split1.length; i++) + { + final String[] split3 = split1[0].split("[:+',;.]", 2); + if (split3.length < 1) + { + continue; + } + Enchantment enchantment; + if (NUMPATTERN.matcher(split3[0]).matches()) + { + final int enchantId = Integer.parseInt(split3[0]); + enchantment = Enchantment.getById(enchantId); + } + else + { + enchantment = Enchantment.getByName(split3[0].toUpperCase(Locale.ENGLISH)); + } + if (enchantment == null) + { + continue; + } + int level = enchantment.getStartLevel(); + if (split3.length == 2 && NUMPATTERN.matcher(split3[1]).matches()) + { + level = Integer.parseInt(split3[1]); + } + if (level < enchantment.getStartLevel()) + { + level = enchantment.getStartLevel(); + } + if (level > enchantment.getMaxLevel()) + { + level = enchantment.getMaxLevel(); + } + stack.addUnsafeEnchantment(enchantment, level); + } + } + return stack; + } + if (node.getType().equals(EnchantmentLevel.class)) + { + final String val = (String)constructScalar((ScalarNode)node); + if (val.isEmpty()) + { + return null; + } + final String[] split = val.split("[:+',;.]", 2); + if (split.length == 0) + { + return null; + } + Enchantment enchant; + if (NUMPATTERN.matcher(split[0]).matches()) + { + final int typeId = Integer.parseInt(split[0]); + enchant = Enchantment.getById(typeId); + } + else + { + enchant = Enchantment.getByName(split[0].toUpperCase(Locale.ENGLISH)); + } + if (enchant == null) + { + return null; + } + int level = enchant.getStartLevel(); + if (split.length == 2 && NUMPATTERN.matcher(split[1]).matches()) + { + level = Integer.parseInt(split[1]); + } + if (level < enchant.getStartLevel()) + { + level = enchant.getStartLevel(); + } + if (level > enchant.getMaxLevel()) + { + level = enchant.getMaxLevel(); + } + return new EnchantmentLevel(enchant, level); + } + if (node.getType().isEnum()) + { + final String val = (String)constructScalar((ScalarNode)node); + if (val.isEmpty()) + { + return null; + } + for (Object object : node.getType().getEnumConstants()) + { + if (object.toString().equalsIgnoreCase(val)) + { + return object; + } + } + return null; + } + return super.construct(node); + } + } + + + private class ConstructBukkitMapping extends ConstructMapping + { + @Override + public Object construct(final Node node) + { + if (node.getType().equals(StoredLocation.class)) + { + //TODO: NPE checks + final MappingNode mnode = (MappingNode)node; + String worldName = ""; + double x = 0, y = 0, z = 0; + float yaw = 0, pitch = 0; + if (mnode.getValue().size() < 4) + { + return null; + } + for (NodeTuple nodeTuple : mnode.getValue()) + { + final String key = (String)constructScalar((ScalarNode)nodeTuple.getKeyNode()); + final ScalarNode snode = (ScalarNode)nodeTuple.getValueNode(); + if (key.equalsIgnoreCase("world")) + { + worldName = (String)constructScalar(snode); + } + if (key.equalsIgnoreCase("x")) + { + x = Double.parseDouble((String)constructScalar(snode)); + } + if (key.equalsIgnoreCase("y")) + { + y = Double.parseDouble((String)constructScalar(snode)); + } + if (key.equalsIgnoreCase("z")) + { + z = Double.parseDouble((String)constructScalar(snode)); + } + if (key.equalsIgnoreCase("yaw")) + { + yaw = Float.parseFloat((String)constructScalar(snode)); + } + if (key.equalsIgnoreCase("pitch")) + { + pitch = Float.parseFloat((String)constructScalar(snode)); + } + } + if (worldName == null || worldName.isEmpty()) + { + return null; + } + return new StoredLocation(worldName, x, y, z, yaw, pitch); + } + return super.construct(node); + } + + @Override + protected Object constructJavaBean2ndStep(final MappingNode node, final Object object) + { + Map, TypeDescription> typeDefinitions; + try + { + final Field typeDefField = Constructor.class.getDeclaredField("typeDefinitions"); + typeDefField.setAccessible(true); + typeDefinitions = (Map, TypeDescription>)typeDefField.get((Constructor)BukkitConstructor.this); + if (typeDefinitions == null) + { + throw new NullPointerException(); + } + } + catch (Exception ex) + { + throw new YAMLException(ex); + } + flattenMapping(node); + final Class beanType = node.getType(); + final List nodeValue = node.getValue(); + for (NodeTuple tuple : nodeValue) + { + ScalarNode keyNode; + if (tuple.getKeyNode() instanceof ScalarNode) + { + // key must be scalar + keyNode = (ScalarNode)tuple.getKeyNode(); + } + else + { + throw new YAMLException("Keys must be scalars but found: " + tuple.getKeyNode()); + } + final Node valueNode = tuple.getValueNode(); + // keys can only be Strings + keyNode.setType(String.class); + final String key = (String)constructObject(keyNode); + try + { + Property property; + try + { + property = getProperty(beanType, key); + } + catch (YAMLException e) + { + continue; + } + valueNode.setType(property.getType()); + final TypeDescription memberDescription = typeDefinitions.get(beanType); + boolean typeDetected = false; + if (memberDescription != null) + { + switch (valueNode.getNodeId()) + { + case sequence: + final SequenceNode snode = (SequenceNode)valueNode; + final Class memberType = memberDescription.getListPropertyType(key); + if (memberType != null) + { + snode.setListType(memberType); + typeDetected = true; + } + else if (property.getType().isArray()) + { + snode.setListType(property.getType().getComponentType()); + typeDetected = true; + } + break; + case mapping: + final MappingNode mnode = (MappingNode)valueNode; + final Class keyType = memberDescription.getMapKeyType(key); + if (keyType != null) + { + mnode.setTypes(keyType, memberDescription.getMapValueType(key)); + typeDetected = true; + } + break; + } + } + if (!typeDetected && valueNode.getNodeId() != NodeId.scalar) + { + // only if there is no explicit TypeDescription + final Class[] arguments = property.getActualTypeArguments(); + if (arguments != null) + { + // type safe (generic) collection may contain the + // proper class + if (valueNode.getNodeId() == NodeId.sequence) + { + final Class t = arguments[0]; + final SequenceNode snode = (SequenceNode)valueNode; + snode.setListType(t); + } + else if (valueNode.getTag().equals(Tag.SET)) + { + final Class t = arguments[0]; + final MappingNode mnode = (MappingNode)valueNode; + mnode.setOnlyKeyType(t); + mnode.setUseClassConstructor(true); + } + else if (property.getType().isAssignableFrom(Map.class)) + { + final Class ketType = arguments[0]; + final Class valueType = arguments[1]; + final MappingNode mnode = (MappingNode)valueNode; + mnode.setTypes(ketType, valueType); + mnode.setUseClassConstructor(true); + } + else + { + // the type for collection entries cannot be + // detected + } + } + } + final Object value = constructObject(valueNode); + property.set(object, value); + } + catch (Exception e) + { + throw new YAMLException("Cannot create property=" + key + " for JavaBean=" + + object + "; " + e.getMessage(), e); + } + } + return object; + } + } + + @Override + protected Class getClassForNode(final Node node) + { + Class clazz; + final String name = node.getTag().getClassName(); + if (Essentials.testing) + { + clazz = super.getClassForNode(node); + } + else + { + clazz = plugin.getClassByName(name); + } + + if (clazz == null) + { + throw new YAMLException("Class not found: " + name); + } + else + { + return clazz; + } + } +} diff --git a/Essentials/src/net/ess3/storage/Comment.java b/Essentials/src/net/ess3/storage/Comment.java new file mode 100644 index 000000000..ed65e59ef --- /dev/null +++ b/Essentials/src/net/ess3/storage/Comment.java @@ -0,0 +1,12 @@ +package net.ess3.storage; + +import java.lang.annotation.*; + + +@Target(ElementType.FIELD) +@Documented +@Retention(RetentionPolicy.RUNTIME) +public @interface Comment +{ + String[] value() default ""; +} \ No newline at end of file diff --git a/Essentials/src/net/ess3/storage/EnchantmentLevel.java b/Essentials/src/net/ess3/storage/EnchantmentLevel.java new file mode 100644 index 000000000..ad583f17f --- /dev/null +++ b/Essentials/src/net/ess3/storage/EnchantmentLevel.java @@ -0,0 +1,80 @@ +package net.ess3.storage; + +import java.util.Map.Entry; +import org.bukkit.enchantments.Enchantment; + + +public class EnchantmentLevel implements Entry +{ + private Enchantment enchantment; + private int level; + + public EnchantmentLevel(final Enchantment enchantment, final int level) + { + this.enchantment = enchantment; + this.level = level; + } + + public Enchantment getEnchantment() + { + return enchantment; + } + + public void setEnchantment(final Enchantment enchantment) + { + this.enchantment = enchantment; + } + + public int getLevel() + { + return level; + } + + public void setLevel(final int level) + { + this.level = level; + } + + @Override + public Enchantment getKey() + { + return enchantment; + } + + @Override + public Integer getValue() + { + return level; + } + + @Override + public Integer setValue(final Integer v) + { + int t = level; + level = v; + return t; + } + + @Override + public int hashCode() + { + return enchantment.hashCode() ^ level; + } + + @Override + public boolean equals(final Object obj) + { + if (obj instanceof Entry) + { + final Entry entry = (Entry)obj; + if (entry.getKey() instanceof Enchantment + && entry.getValue() instanceof Integer) + { + final Enchantment objEnchantment = (Enchantment)entry.getKey(); + final Integer objLevel = (Integer)entry.getValue(); + return enchantment.equals(objEnchantment) && level == objLevel.intValue(); + } + } + return false; + } +} diff --git a/Essentials/src/net/ess3/storage/IStorageObjectHolder.java b/Essentials/src/net/ess3/storage/IStorageObjectHolder.java new file mode 100644 index 000000000..da5e24c49 --- /dev/null +++ b/Essentials/src/net/ess3/storage/IStorageObjectHolder.java @@ -0,0 +1,17 @@ +package net.ess3.storage; + +import net.ess3.api.IReload; + + +public interface IStorageObjectHolder extends IReload +{ + T getData(); + + void acquireReadLock(); + + void acquireWriteLock(); + + void close(); + + void unlock(); +} diff --git a/Essentials/src/net/ess3/storage/IStorageObjectMap.java b/Essentials/src/net/ess3/storage/IStorageObjectMap.java new file mode 100644 index 000000000..5facaf200 --- /dev/null +++ b/Essentials/src/net/ess3/storage/IStorageObjectMap.java @@ -0,0 +1,22 @@ +package net.ess3.storage; + +import net.ess3.api.IReload; +import net.ess3.api.InvalidNameException; +import java.io.File; +import java.util.Set; + + +interface IStorageObjectMap extends IReload +{ + boolean objectExists(final String name); + + I getObject(final String name); + + void removeObject(final String name) throws InvalidNameException; + + Set getAllKeys(); + + int getKeySize(); + + File getStorageFile(final String name) throws InvalidNameException; +} diff --git a/Essentials/src/net/ess3/storage/IStorageReader.java b/Essentials/src/net/ess3/storage/IStorageReader.java new file mode 100644 index 000000000..1d3d26f33 --- /dev/null +++ b/Essentials/src/net/ess3/storage/IStorageReader.java @@ -0,0 +1,7 @@ +package net.ess3.storage; + + +public interface IStorageReader +{ + T load(final Class clazz) throws ObjectLoadException; +} diff --git a/Essentials/src/net/ess3/storage/IStorageWriter.java b/Essentials/src/net/ess3/storage/IStorageWriter.java new file mode 100644 index 000000000..8cba4122b --- /dev/null +++ b/Essentials/src/net/ess3/storage/IStorageWriter.java @@ -0,0 +1,7 @@ +package net.ess3.storage; + + +public interface IStorageWriter +{ + void save(final StorageObject object); +} diff --git a/Essentials/src/net/ess3/storage/ListType.java b/Essentials/src/net/ess3/storage/ListType.java new file mode 100644 index 000000000..17dd134a9 --- /dev/null +++ b/Essentials/src/net/ess3/storage/ListType.java @@ -0,0 +1,14 @@ +package net.ess3.storage; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +public @interface ListType +{ + Class value() default String.class; +} diff --git a/Essentials/src/net/ess3/storage/ManagedFile.java b/Essentials/src/net/ess3/storage/ManagedFile.java new file mode 100644 index 000000000..bbe9bd212 --- /dev/null +++ b/Essentials/src/net/ess3/storage/ManagedFile.java @@ -0,0 +1,228 @@ +package net.ess3.storage; + +import static net.ess3.I18n._; +import net.ess3.api.IEssentials; +import java.io.*; +import java.math.BigInteger; +import java.security.DigestInputStream; +import java.security.DigestOutputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.logging.Level; +import org.bukkit.Bukkit; + + +public class ManagedFile +{ + private final static int BUFFERSIZE = 1024 * 8; + private final transient File file; + + public ManagedFile(final String filename, final IEssentials ess) + { + file = new File(ess.getPlugin().getDataFolder(), filename); + + if (file.exists()) + { + try + { + if (checkForVersion(file, ess.getPlugin().getVersion()) && !file.delete()) + { + throw new IOException("Could not delete file " + file.toString()); + } + } + catch (IOException ex) + { + Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); + } + } + + if (!file.exists()) + { + try + { + copyResourceAscii("/" + filename, file); + } + catch (IOException ex) + { + Bukkit.getLogger().log(Level.SEVERE, _("itemsCsvNotLoaded"), ex); + } + } + } + + public static void copyResourceAscii(final String resourceName, final File file) throws IOException + { + final InputStreamReader reader = new InputStreamReader(ManagedFile.class.getResourceAsStream(resourceName)); + try + { + final MessageDigest digest = getDigest(); + final DigestOutputStream digestStream = new DigestOutputStream(new FileOutputStream(file), digest); + try + { + final OutputStreamWriter writer = new OutputStreamWriter(digestStream); + try + { + final char[] buffer = new char[BUFFERSIZE]; + do + { + final int length = reader.read(buffer); + if (length >= 0) + { + writer.write(buffer, 0, length); + } + else + { + break; + } + } + while (true); + writer.write("\n"); + writer.flush(); + final BigInteger hashInt = new BigInteger(1, digest.digest()); + digestStream.on(false); + digestStream.write('#'); + digestStream.write(hashInt.toString(16).getBytes()); + } + finally + { + writer.close(); + } + } + finally + { + digestStream.close(); + } + } + finally + { + reader.close(); + } + } + + public static boolean checkForVersion(final File file, final String version) throws IOException + { + if (file.length() < 33) + { + return false; + } + final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); + try + { + final byte[] buffer = new byte[(int)file.length()]; + int position = 0; + do + { + final int length = bis.read(buffer, position, Math.min((int)file.length() - position, BUFFERSIZE)); + if (length < 0) + { + break; + } + position += length; + } + while (position < file.length()); + final ByteArrayInputStream bais = new ByteArrayInputStream(buffer); + if (bais.skip(file.length() - 33) != file.length() - 33) + { + return false; + } + final BufferedReader reader = new BufferedReader(new InputStreamReader(bais)); + try + { + String hash = reader.readLine(); + if (hash != null && hash.matches("#[a-f0-9]{32}")) + { + hash = hash.substring(1); + bais.reset(); + final String versionline = reader.readLine(); + if (versionline != null && versionline.matches("#version: .+")) + { + final String versioncheck = versionline.substring(10); + if (!versioncheck.equalsIgnoreCase(version)) + { + bais.reset(); + final MessageDigest digest = getDigest(); + final DigestInputStream digestStream = new DigestInputStream(bais, digest); + try + { + final byte[] bytes = new byte[(int)file.length() - 33]; + digestStream.read(bytes); + final BigInteger correct = new BigInteger(hash, 16); + final BigInteger test = new BigInteger(1, digest.digest()); + if (correct.equals(test)) + { + return true; + } + else + { + Bukkit.getLogger().warning("File " + file.toString() + " has been modified by user and file version differs, please update the file manually."); + } + } + finally + { + digestStream.close(); + } + } + } + } + } + finally + { + reader.close(); + } + } + finally + { + bis.close(); + } + return false; + } + + public static MessageDigest getDigest() throws IOException + { + try + { + return MessageDigest.getInstance("MD5"); + } + catch (NoSuchAlgorithmException ex) + { + throw new IOException(ex); + } + } + + public List getLines() + { + try + { + final BufferedReader reader = new BufferedReader(new FileReader(file)); + try + { + final List lines = new ArrayList(); + do + { + final String line = reader.readLine(); + if (line == null) + { + break; + } + else + { + lines.add(line); + } + } + while (true); + return lines; + } + finally + { + reader.close(); + } + } + catch (IOException ex) + { + Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); + return Collections.emptyList(); + } + } +} diff --git a/Essentials/src/net/ess3/storage/MapKeyType.java b/Essentials/src/net/ess3/storage/MapKeyType.java new file mode 100644 index 000000000..2da042f33 --- /dev/null +++ b/Essentials/src/net/ess3/storage/MapKeyType.java @@ -0,0 +1,14 @@ +package net.ess3.storage; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + +@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/net/ess3/storage/MapValueType.java b/Essentials/src/net/ess3/storage/MapValueType.java new file mode 100644 index 000000000..5e0bee09b --- /dev/null +++ b/Essentials/src/net/ess3/storage/MapValueType.java @@ -0,0 +1,14 @@ +package net.ess3.storage; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + +@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/net/ess3/storage/ObjectLoadException.java b/Essentials/src/net/ess3/storage/ObjectLoadException.java new file mode 100644 index 000000000..4ea962db2 --- /dev/null +++ b/Essentials/src/net/ess3/storage/ObjectLoadException.java @@ -0,0 +1,10 @@ +package net.ess3.storage; + + +public class ObjectLoadException extends Exception +{ + public ObjectLoadException(Throwable thrwbl) + { + super(thrwbl); + } +} diff --git a/Essentials/src/net/ess3/storage/StorageObject.java b/Essentials/src/net/ess3/storage/StorageObject.java new file mode 100644 index 000000000..3a632224d --- /dev/null +++ b/Essentials/src/net/ess3/storage/StorageObject.java @@ -0,0 +1,6 @@ +package net.ess3.storage; + + +public interface StorageObject +{ +} diff --git a/Essentials/src/net/ess3/storage/StorageObjectMap.java b/Essentials/src/net/ess3/storage/StorageObjectMap.java new file mode 100644 index 000000000..6c246e62f --- /dev/null +++ b/Essentials/src/net/ess3/storage/StorageObjectMap.java @@ -0,0 +1,137 @@ +package net.ess3.storage; + +import net.ess3.api.IEssentials; +import net.ess3.api.InvalidNameException; +import net.ess3.utils.Util; +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.util.concurrent.UncheckedExecutionException; +import java.io.File; +import java.io.IOException; +import java.util.Collections; +import java.util.Locale; +import java.util.Set; +import java.util.concurrent.ConcurrentSkipListSet; +import java.util.concurrent.ExecutionException; +import java.util.logging.Level; + + +public abstract class StorageObjectMap extends CacheLoader implements IStorageObjectMap +{ + protected final transient IEssentials ess; + private final transient File folder; + protected final transient Cache cache = CacheBuilder.newBuilder().softValues().build(this); + protected final transient ConcurrentSkipListSet keys = new ConcurrentSkipListSet(); + + public StorageObjectMap(final IEssentials ess, final String folderName) + { + super(); + this.ess = ess; + this.folder = new File(ess.getPlugin().getDataFolder(), folderName); + if (!folder.exists()) + { + folder.mkdirs(); + } + loadAllObjectsAsync(); + } + + private void loadAllObjectsAsync() + { + ess.getPlugin().scheduleAsyncDelayedTask(new Runnable() + { + @Override + public void run() + { + if (!folder.exists() || !folder.isDirectory()) + { + return; + } + keys.clear(); + cache.invalidateAll(); + for (String string : folder.list()) + { + try + { + if (!string.endsWith(".yml")) + { + continue; + } + final String name = Util.decodeFileName(string.substring(0, string.length() - 4)); + keys.add(name.toLowerCase(Locale.ENGLISH)); + } + catch (InvalidNameException ex) + { + ess.getLogger().log(Level.WARNING, "Invalid filename: " + string, ex); + } + } + } + }); + } + + @Override + public boolean objectExists(final String name) + { + return keys.contains(name.toLowerCase(Locale.ENGLISH)); + } + + @Override + public I getObject(final String name) + { + try + { + return (I)cache.get(name.toLowerCase(Locale.ENGLISH)); + } + catch (ExecutionException ex) + { + return null; + } + catch (UncheckedExecutionException ex) + { + return null; + } + } + + @Override + public abstract I load(final String name) throws Exception; + + @Override + public void removeObject(final String name) throws InvalidNameException + { + keys.remove(name.toLowerCase(Locale.ENGLISH)); + cache.invalidate(name.toLowerCase(Locale.ENGLISH)); + final File file = getStorageFile(name); + if (file.exists()) + { + file.delete(); + } + } + + @Override + public Set getAllKeys() + { + return Collections.unmodifiableSet(keys); + } + + @Override + public int getKeySize() + { + return keys.size(); + } + + @Override + public File getStorageFile(final String name) throws InvalidNameException + { + if (!folder.exists() || !folder.isDirectory()) + { + throw new InvalidNameException(new IOException("Folder does not exists: " + folder)); + } + return new File(folder, Util.sanitizeFileName(name) + ".yml"); + } + + @Override + public void onReload() + { + loadAllObjectsAsync(); + } +} diff --git a/Essentials/src/net/ess3/storage/StoredLocation.java b/Essentials/src/net/ess3/storage/StoredLocation.java new file mode 100644 index 000000000..00ace6791 --- /dev/null +++ b/Essentials/src/net/ess3/storage/StoredLocation.java @@ -0,0 +1,115 @@ +package net.ess3.storage; + +import net.ess3.api.server.World; +import net.ess3.api.server.Location; +import java.lang.ref.WeakReference; +import java.util.UUID; + + +public class StoredLocation +{ + private WeakReference location; + private final String worldname; + private UUID worldUID = null; + private final double x; + private final double y; + private final double z; + private final float yaw; + private final float pitch; + + public StoredLocation(Location loc) + { + location = new WeakReference(loc); + worldname = loc.getWorld().getName(); + worldUID = loc.getWorld().getUID(); + x = loc.getX(); + y = loc.getY(); + z = loc.getZ(); + yaw = loc.getYaw(); + pitch = loc.getPitch(); + } + + public StoredLocation(String worldname, double x, double y, double z, float yaw, float pitch) + { + this.worldname = worldname; + this.x = x; + this.y = y; + this.z = z; + this.yaw = yaw; + this.pitch = pitch; + } + + public StoredLocation(String worldname, double x, double y, double z) + { + this.worldname = worldname; + this.x = x; + this.y = y; + this.z = z; + this.yaw = 0f; + this.pitch = 0f; + } + + public Location getStoredLocation() throws WorldNotLoadedException + { + + Location loc = location == null ? null : location.get(); + if (loc == null) + { + World world = null; + if (worldUID != null) + { + world = Bukkit.getWorld(worldUID); + } + if (world == null) + { + world = Bukkit.getWorld(worldname); + } + if (world == null) + { + throw new WorldNotLoadedException(worldname); + } + loc = Location.create(world, getX(), getY(), getZ(), getYaw(), getPitch()); + location = new WeakReference(loc); + } + return loc; + } + + public String getWorldName() + { + return worldname; + } + + public double getX() + { + return x; + } + + public double getY() + { + return y; + } + + public double getZ() + { + return z; + } + + public float getYaw() + { + return yaw; + } + + public float getPitch() + { + return pitch; + } + + + public static class WorldNotLoadedException extends Exception + { + public WorldNotLoadedException(String worldname) + { + super("World " + worldname + " is not loaded."); + } + } +} diff --git a/Essentials/src/net/ess3/storage/YamlStorageReader.java b/Essentials/src/net/ess3/storage/YamlStorageReader.java new file mode 100644 index 000000000..dc5c24d91 --- /dev/null +++ b/Essentials/src/net/ess3/storage/YamlStorageReader.java @@ -0,0 +1,120 @@ +package net.ess3.storage; + +import net.ess3.api.server.IPlugin; +import java.io.Reader; +import java.lang.reflect.Field; +import java.util.*; +import java.util.concurrent.locks.ReentrantLock; +import org.yaml.snakeyaml.TypeDescription; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + + +public class YamlStorageReader implements IStorageReader +{ + private transient static final Map PREPARED_YAMLS = Collections.synchronizedMap(new HashMap()); + private transient static final Map LOCKS = new HashMap(); + private transient final Reader reader; + private transient final IPlugin plugin; + + public YamlStorageReader(final Reader reader, final IPlugin plugin) + { + this.reader = reader; + this.plugin = plugin; + } + + @Override + public T load(final Class clazz) throws ObjectLoadException + { + Yaml yaml = PREPARED_YAMLS.get(clazz); + if (yaml == null) + { + yaml = new Yaml(prepareConstructor(clazz)); + PREPARED_YAMLS.put(clazz, yaml); + } + ReentrantLock lock; + synchronized (LOCKS) + { + lock = LOCKS.get(clazz); + if (lock == null) + { + lock = new ReentrantLock(); + } + } + lock.lock(); + try + { + T object = (T)yaml.load(reader); + if (object == null) + { + object = clazz.newInstance(); + } + return object; + } + catch (Exception ex) + { + throw new ObjectLoadException(ex); + } + finally + { + lock.unlock(); + } + } + + private Constructor prepareConstructor(final Class clazz) + { + final Constructor constructor = new BukkitConstructor(clazz, plugin); + final Set classes = new HashSet(); + + prepareConstructor(constructor, classes, clazz); + return constructor; + } + + 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()) + { + prepareList(field, description, classes, constructor); + prepareMap(field, description, classes, constructor); + if (StorageObject.class.isAssignableFrom(field.getType()) + && !classes.contains(field.getType())) + { + prepareConstructor(constructor, classes, field.getType()); + } + } + constructor.addTypeDescription(description); + } + + private void prepareList(final Field field, final TypeDescription description, final Set classes, final Constructor constructor) + { + final ListType listType = field.getAnnotation(ListType.class); + if (listType != null) + { + description.putListPropertyType(field.getName(), listType.value()); + if (StorageObject.class.isAssignableFrom(listType.value()) + && !classes.contains(listType.value())) + { + prepareConstructor(constructor, classes, listType.value()); + } + } + } + + private void prepareMap(final Field field, final TypeDescription description, final Set classes, final Constructor constructor) + { + final MapValueType mapType = field.getAnnotation(MapValueType.class); + if (mapType != null) + { + final MapKeyType mapKeyType = field.getAnnotation(MapKeyType.class); + description.putMapPropertyType(field.getName(), + mapKeyType == null ? String.class : mapKeyType.value(), + mapType.value()); + if (StorageObject.class.isAssignableFrom(mapType.value()) + && !classes.contains(mapType.value())) + { + prepareConstructor(constructor, classes, mapType.value()); + } + } + } +} diff --git a/Essentials/src/net/ess3/storage/YamlStorageWriter.java b/Essentials/src/net/ess3/storage/YamlStorageWriter.java new file mode 100644 index 000000000..793ac67fd --- /dev/null +++ b/Essentials/src/net/ess3/storage/YamlStorageWriter.java @@ -0,0 +1,348 @@ +package net.ess3.storage; + +import java.io.PrintWriter; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.Collection; +import java.util.Collections; +import java.util.Locale; +import java.util.Map; +import java.util.Map.Entry; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Pattern; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; +import org.bukkit.material.MaterialData; +import org.yaml.snakeyaml.Yaml; + + +public class YamlStorageWriter implements IStorageWriter +{ + private transient static final Pattern NON_WORD_PATTERN = Pattern.compile("\\W"); + private transient final PrintWriter writer; + private transient static final Yaml YAML = new Yaml(); + + public YamlStorageWriter(final PrintWriter writer) + { + this.writer = writer; + } + + @Override + public void save(final StorageObject object) + { + try + { + writeToFile(object, 0, object.getClass()); + } + catch (IllegalArgumentException ex) + { + Logger.getLogger(YamlStorageWriter.class.getName()).log(Level.SEVERE, null, ex); + } + catch (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()) + { + final int modifier = field.getModifiers(); + if (Modifier.isPrivate(modifier) && !Modifier.isTransient(modifier) && !Modifier.isStatic(modifier)) + { + field.setAccessible(true); + + final Object data = field.get(object); + if (writeKey(field, depth, data)) + { + continue; + } + if (data instanceof StorageObject) + { + writer.println(); + writeToFile(data, depth + 1, data.getClass()); + } + else if (data instanceof Map) + { + writeMap((Map)data, depth + 1); + } + else if (data instanceof Collection) + { + writeCollection((Collection)data, depth + 1); + } + else if (data instanceof StoredLocation) + { + writeLocation((StoredLocation)data, depth + 1); + } + else + { + writeScalar(data); + writer.println(); + } + } + } + } + + private boolean writeKey(final Field field, final int depth, final Object data) + { + final boolean commentPresent = writeComment(field, depth); + if (data == null && !commentPresent) + { + return true; + } + writeIndention(depth); + if (data == null && commentPresent) + { + writer.print('#'); + } + final String name = field.getName(); + writer.print(name); + writer.print(": "); + if (data == null && commentPresent) + { + writer.println(); + writer.println(); + return true; + } + return false; + } + + private boolean writeComment(final Field field, final int depth) + { + final boolean commentPresent = field.isAnnotationPresent(Comment.class); + if (commentPresent) + { + final Comment comments = field.getAnnotation(Comment.class); + for (String comment : comments.value()) + { + final String trimmed = comment.trim(); + if (trimmed.isEmpty()) + { + continue; + } + writeIndention(depth); + writer.print("# "); + writer.print(trimmed); + writer.println(); + } + } + return commentPresent; + } + + private void writeCollection(final Collection data, final int depth) throws IllegalAccessException + { + writer.println(); + if (data.isEmpty()) + { + writer.println(); + } + for (Object entry : data) + { + if (entry != null) + { + writeIndention(depth); + writer.print("- "); + if (entry instanceof StorageObject) + { + writer.println(); + writeToFile(entry, depth + 1, entry.getClass()); + } + else if (entry instanceof StoredLocation) + { + writeLocation((StoredLocation)entry, depth + 1); + } + else + { + writeScalar(entry); + } + } + } + writer.println(); + } + + private void writeMap(final Map data, final int depth) throws IllegalArgumentException, IllegalAccessException + { + writer.println(); + if (data.isEmpty()) + { + writer.println(); + } + for (Entry entry : data.entrySet()) + { + final Object value = entry.getValue(); + if (value != null) + { + writeIndention(depth); + writeKey(entry.getKey()); + writer.print(": "); + if (value instanceof StorageObject) + { + writer.println(); + writeToFile(value, depth + 1, value.getClass()); + } + else if (value instanceof Collection) + { + writeCollection((Collection)value, depth + 1); + } + else if (value instanceof StoredLocation) + { + writeLocation((StoredLocation)value, depth + 1); + } + else + { + writeScalar(value); + writer.println(); + } + } + } + } + + private void writeIndention(final int depth) + { + for (int i = 0; i < depth; i++) + { + writer.print(" "); + } + } + + private void writeScalar(final Object data) + { + if (data instanceof String || data instanceof Boolean || data instanceof Number) + { + synchronized (YAML) + { + YAML.dumpAll(Collections.singletonList(data).iterator(), writer); + } + } + else if (data instanceof Enum) + { + writeMaterial(data.toString()); + writer.println(); + } + else if (data instanceof Material) + { + writeMaterial(data); + writer.println(); + } + else if (data instanceof MaterialData) + { + writeMaterialData(data); + writer.println(); + } + else if (data instanceof ItemStack) + { + writeItemStack(data); + writer.println(); + } + else if (data instanceof EnchantmentLevel) + { + writeEnchantmentLevel(data); + writer.println(); + } + else + { + throw new UnsupportedOperationException(); + } + } + + private void writeKey(final Object data) + { + if (data instanceof String || data instanceof Boolean || data instanceof Number) + { + String output = data.toString(); + if (NON_WORD_PATTERN.matcher(output).find()) + { + writer.print('"'); + writer.print(output.replace("\"", "\\\"")); + writer.print('"'); + } + else + { + writer.print(output); + } + } + else if (data instanceof Enum) + { + writeMaterial(data.toString()); + } + else if (data instanceof Material) + { + writeMaterial(data); + } + else if (data instanceof MaterialData) + { + writeMaterialData(data); + } + else if (data instanceof EnchantmentLevel) + { + writeEnchantmentLevel(data); + } + else + { + throw new UnsupportedOperationException(); + } + } + + private void writeMaterial(final Object data) + { + writer.print(data.toString().toLowerCase(Locale.ENGLISH)); + } + + private void writeMaterialData(final Object data) + { + final MaterialData matData = (MaterialData)data; + writeMaterial(matData.getItemType()); + if (matData.getData() > 0) + { + writer.print(':'); + writer.print(matData.getData()); + } + } + + private void writeItemStack(final Object data) + { + final ItemStack itemStack = (ItemStack)data; + writeMaterialData(itemStack.getData()); + writer.print(' '); + writer.print(itemStack.getAmount()); + for (Entry entry : itemStack.getEnchantments().entrySet()) + { + writer.print(' '); + writeEnchantmentLevel(entry); + } + } + + private void writeEnchantmentLevel(Object data) + { + final Entry enchLevel = (Entry)data; + writer.print(enchLevel.getKey().getName().toLowerCase(Locale.ENGLISH)); + writer.print(':'); + writer.print(enchLevel.getValue()); + } + + private void writeLocation(final StoredLocation entry, final int depth) + { + writer.println(); + writeIndention(depth); + writer.print("world: "); + writeScalar(entry.getWorldName()); + writeIndention(depth); + writer.print("x: "); + writeScalar(entry.getX()); + writeIndention(depth); + writer.print("y: "); + writeScalar(entry.getY()); + writeIndention(depth); + writer.print("z: "); + writeScalar(entry.getZ()); + writeIndention(depth); + writer.print("yaw: "); + writeScalar(entry.getYaw()); + writeIndention(depth); + writer.print("pitch: "); + writeScalar(entry.getPitch()); + } +} diff --git a/Essentials/src/net/ess3/user/Ban.java b/Essentials/src/net/ess3/user/Ban.java new file mode 100644 index 000000000..3fd5d1192 --- /dev/null +++ b/Essentials/src/net/ess3/user/Ban.java @@ -0,0 +1,14 @@ +package net.ess3.user; + +import net.ess3.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Ban implements StorageObject +{ + private String reason; + private long timeout; +} diff --git a/Essentials/src/net/ess3/user/CooldownException.java b/Essentials/src/net/ess3/user/CooldownException.java new file mode 100644 index 000000000..6875e59cb --- /dev/null +++ b/Essentials/src/net/ess3/user/CooldownException.java @@ -0,0 +1,12 @@ +package net.ess3.user; + + +public class CooldownException extends Exception +{ + + public CooldownException(String timeLeft) + { + super(timeLeft); + } + +} diff --git a/Essentials/src/net/ess3/user/IOfflinePlayer.java b/Essentials/src/net/ess3/user/IOfflinePlayer.java new file mode 100644 index 000000000..f594ad669 --- /dev/null +++ b/Essentials/src/net/ess3/user/IOfflinePlayer.java @@ -0,0 +1,17 @@ +package net.ess3.user; + +import org.bukkit.permissions.Permission; + + +public interface IOfflinePlayer +{ + String getName(); + + String getDisplayName(); + + //Location getBedSpawnLocation(); + + void setBanned(boolean bln); + + boolean hasPermission(Permission perm); +} \ No newline at end of file diff --git a/Essentials/src/net/ess3/user/IOfflineUser.java b/Essentials/src/net/ess3/user/IOfflineUser.java new file mode 100644 index 000000000..19431d982 --- /dev/null +++ b/Essentials/src/net/ess3/user/IOfflineUser.java @@ -0,0 +1,9 @@ +package net.ess3.user; + +import net.ess3.storage.IStorageObjectHolder; + + +public interface IOfflineUser extends IStorageObjectHolder//, IOfflinePlayer +{ + +} diff --git a/Essentials/src/net/ess3/user/Inventory.java b/Essentials/src/net/ess3/user/Inventory.java new file mode 100644 index 000000000..621163e33 --- /dev/null +++ b/Essentials/src/net/ess3/user/Inventory.java @@ -0,0 +1,58 @@ +package net.ess3.user; + +import net.ess3.storage.MapKeyType; +import net.ess3.storage.MapValueType; +import net.ess3.storage.StorageObject; +import java.util.HashMap; +import java.util.Map; +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.bukkit.inventory.ItemStack; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class Inventory implements StorageObject +{ + private int size; + @MapKeyType(Integer.class) + @MapValueType(ItemStack.class) + private Map items = null; + + public Inventory() + { + } + + public Inventory(ItemStack[] contents) + { + size = contents.length; + if (items == null) { + items = new HashMap(size); + } + items.clear(); + for (int i = 0; i < contents.length; i++) + { + ItemStack itemStack = contents[i]; + if (itemStack == null) { + continue; + } + items.put(i, itemStack); + } + } + + public ItemStack[] getBukkitInventory() + { + if (items == null) { + throw new IllegalStateException(); + } + final ItemStack[] inventory = new ItemStack[size]; + for (Map.Entry entry : items.entrySet()) + { + if (entry.getKey() < 0 || entry.getKey()>= size) { + continue; + } + inventory[entry.getKey()] = entry.getValue(); + } + return inventory; + } +} diff --git a/Essentials/src/net/ess3/user/TooManyMatchesException.java b/Essentials/src/net/ess3/user/TooManyMatchesException.java new file mode 100644 index 000000000..d55e6b6c4 --- /dev/null +++ b/Essentials/src/net/ess3/user/TooManyMatchesException.java @@ -0,0 +1,5 @@ +package net.ess3.user; + +public class TooManyMatchesException extends Exception { + +} diff --git a/Essentials/src/net/ess3/user/User.java b/Essentials/src/net/ess3/user/User.java new file mode 100644 index 000000000..60bd802f0 --- /dev/null +++ b/Essentials/src/net/ess3/user/User.java @@ -0,0 +1,673 @@ +package net.ess3.user; + +import net.ess3.Console; +import static net.ess3.I18n._; +import net.ess3.Teleport; +import net.ess3.api.*; +import net.ess3.api.server.*; +import net.ess3.economy.register.Method; +import net.ess3.permissions.Permissions; +import net.ess3.utils.DateUtil; +import net.ess3.utils.Util; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; +import lombok.Cleanup; +import lombok.Getter; +import lombok.Setter; + + +public class User extends UserBase implements IUser +{ + private CommandSender replyTo = null; + @Getter + private transient IUser teleportRequester; + @Getter + private transient boolean teleportRequestHere; + @Getter + private transient final ITeleport teleport; + @Getter + private transient long teleportRequestTime; + @Getter + @Setter + private transient long lastOnlineActivity; + private transient long lastActivity = System.currentTimeMillis(); + @Getter + @Setter + private boolean hidden = false; + private transient Location afkPosition; + private AtomicBoolean gotMailInfo = new AtomicBoolean(false); + + public User(final Player base, final IEssentials ess) + { + super(base, ess); + teleport = new Teleport(this, ess); + } + + public void example() + { + // Cleanup will call close at the end of the function + @Cleanup + final User user = this; + + // read lock allows to read data from the user + user.acquireReadLock(); + final double money = user.getData().getMoney(); + + // write lock allows only one thread to modify the data + user.acquireWriteLock(); + user.getData().setMoney(10 + money); + } + + @Override + public void checkCooldown(final UserData.TimestampType cooldownType, final double cooldown, final boolean set, final IPermission bypassPermission) throws CooldownException + { + final Calendar now = new GregorianCalendar(); + if (getTimestamp(cooldownType) > 0) + { + final Calendar cooldownTime = new GregorianCalendar(); + cooldownTime.setTimeInMillis(getTimestamp(cooldownType)); + cooldownTime.add(Calendar.SECOND, (int)cooldown); + cooldownTime.add(Calendar.MILLISECOND, (int)((cooldown * 1000.0) % 1000.0)); + if (cooldownTime.after(now) && !bypassPermission.isAuthorized(this)) + { + throw new CooldownException(DateUtil.formatDateDiff(cooldownTime.getTimeInMillis())); + } + } + if (set) + { + setTimestamp(cooldownType, now.getTimeInMillis()); + } + } + + @Override + public void giveMoney(final double value) + { + giveMoney(value, null); + } + + @Override + public void giveMoney(final double value, final CommandSender initiator) + { + + if (value == 0) + { + return; + } + acquireWriteLock(); + try + { + setMoney(getMoney() + value); + sendMessage(_("addedToAccount", Util.displayCurrency(value, ess))); + if (initiator != null) + { + initiator.sendMessage(_("addedToOthersAccount", Util.displayCurrency(value, ess), this.getDisplayName())); + } + } + finally + { + unlock(); + } + } + + @Override + public void payUser(final IUser reciever, final double value) throws Exception + { + if (value == 0) + { + return; + } + if (canAfford(value)) + { + setMoney(getMoney() - value); + reciever.setMoney(reciever.getMoney() + value); + sendMessage(_("moneySentTo", Util.displayCurrency(value, ess), reciever.getDisplayName())); + reciever.sendMessage(_("moneyRecievedFrom", Util.displayCurrency(value, ess), getDisplayName())); + } + else + { + throw new Exception(_("notEnoughMoney")); + } + } + + @Override + public void takeMoney(final double value) + { + takeMoney(value, null); + } + + @Override + public void takeMoney(final double value, final CommandSender initiator) + { + if (value == 0) + { + return; + } + setMoney(getMoney() - value); + sendMessage(_("takenFromAccount", Util.displayCurrency(value, ess))); + if (initiator != null) + { + initiator.sendMessage(_("takenFromOthersAccount", Util.displayCurrency(value, ess), this.getDisplayName())); + } + } + + public void setHome() + { + setHome("home", getLocation()); + } + + public void setHome(final String name) + { + setHome(name, getLocation()); + } + + @Override + public void setLastLocation() + { + acquireWriteLock(); + try + { + getData().setLastLocation(new net.ess3.storage.StoredLocation(getLocation())); + } + finally + { + unlock(); + } + } + + public void requestTeleport(final User player, final boolean here) + { + teleportRequestTime = System.currentTimeMillis(); + teleportRequester = player; + teleportRequestHere = here; + } + + public String getNick(boolean addprefixsuffix) + { + acquireReadLock(); + try + { + final String nick = getData().getNickname(); + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + final IRanks groups = ess.getRanks(); + // default: {PREFIX}{NICKNAMEPREFIX}{NAME}{SUFFIX} + String displayname = settings.getData().getChat().getDisplaynameFormat(); + if (settings.getData().getCommands().isDisabled("nick") || nick == null || nick.isEmpty() || nick.equals(getName())) + { + displayname = displayname.replace("{NAME}", getName()); + displayname = displayname.replace("{NICKNAMEPREFIX}", ""); + } + else + { + displayname = displayname.replace("{NAME}", nick); + displayname = displayname.replace("{NICKNAMEPREFIX}", settings.getData().getChat().getNicknamePrefix()); + } + + if (displayname.contains("{PREFIX}")) + { + displayname = displayname.replace("{PREFIX}", groups.getPrefix(this)); + } + if (displayname.contains("{SUFFIX}")) + { + displayname = displayname.replace("{SUFFIX}", groups.getSuffix(this)); + } + displayname = displayname.replace("{WORLDNAME}", this.getWorld().getName()); + displayname = displayname.replace('&', '\u00a7'); + displayname = displayname.concat("\u00a7f"); + + return displayname; + } + finally + { + unlock(); + } + } + + public void setDisplayNick() + { + String name = getNick(true); + setDisplayName(name); + if (name.length() > 16) + { + name = getNick(false); + } + if (name.length() > 16) + { + name = name.substring(0, name.charAt(15) == '\u00a7' ? 15 : 16); + } + try + { + setPlayerListName(name); + } + catch (IllegalArgumentException e) + { + ess.getLogger().info("Playerlist for " + name + " was not updated. Use a shorter displayname prefix."); + } + } + + @Override + public String getDisplayName() + { + return super.getDisplayName() == null ? super.getName() : super.getDisplayName(); + } + + @Override + public void updateDisplayName() + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (isOnline() && settings.getData().getChat().getChangeDisplayname()) + { + setDisplayNick(); + } + } + + @Override + public double getMoney() + { + if (ess.getPaymentMethod().hasMethod()) + { + try + { + final Method method = ess.getPaymentMethod().getMethod(); + if (!method.hasAccount(this.getName())) + { + throw new Exception(); + } + final Method.MethodAccount account = ess.getPaymentMethod().getMethod().getAccount(this.getName()); + return account.balance(); + } + catch (Throwable ex) + { + } + } + return super.getMoney(); + } + + @Override + public void setMoney(final double value) + { + if (ess.getPaymentMethod().hasMethod()) + { + try + { + final Method method = ess.getPaymentMethod().getMethod(); + if (!method.hasAccount(this.getName())) + { + throw new Exception(); + } + final Method.MethodAccount account = ess.getPaymentMethod().getMethod().getAccount(this.getName()); + account.set(value); + } + catch (Throwable ex) + { + } + } + super.setMoney(value); + } + + public void setAfk(final boolean set) + { + acquireWriteLock(); + try + { + this.setSleepingIgnored(Permissions.SLEEPINGIGNORED.isAuthorized(this) ? true : set); + if (set && !getData().isAfk()) + { + afkPosition = getLocation(); + } + getData().setAfk(set); + } + finally + { + unlock(); + } + } + + @Override + public boolean toggleAfk() + { + final boolean now = super.toggleAfk(); + this.setSleepingIgnored(Permissions.SLEEPINGIGNORED.isAuthorized(this) ? true : now); + return now; + } + + //Returns true if status expired during this check + public boolean checkJailTimeout(final long currentTime) + { + acquireReadLock(); + try + { + if (getTimestamp(UserData.TimestampType.JAIL) > 0 && getTimestamp(UserData.TimestampType.JAIL) < currentTime && getData().isJailed()) + { + acquireWriteLock(); + + setTimestamp(UserData.TimestampType.JAIL, 0); + getData().setJailed(false); + sendMessage(_("haveBeenReleased")); + getData().setJail(null); + + try + { + teleport.back(); + } + catch (Exception ex) + { + } + return true; + } + return false; + } + finally + { + unlock(); + } + } + + //Returns true if status expired during this check + public boolean checkMuteTimeout(final long currentTime) + { + acquireReadLock(); + try + { + if (getTimestamp(UserData.TimestampType.MUTE) > 0 && getTimestamp(UserData.TimestampType.MUTE) < currentTime && getData().isMuted()) + { + acquireWriteLock(); + setTimestamp(UserData.TimestampType.MUTE, 0); + sendMessage(_("canTalkAgain")); + getData().setMuted(false); + return true; + } + return false; + } + finally + { + unlock(); + } + } + + //Returns true if status expired during this check + public boolean checkBanTimeout(final long currentTime) + { + acquireReadLock(); + try + { + if (getData().getBan() != null && getData().getBan().getTimeout() > 0 && getData().getBan().getTimeout() < currentTime && isBanned()) + { + acquireWriteLock(); + getData().setBan(null); + setBanned(false); + return true; + } + return false; + } + finally + { + unlock(); + } + } + + public void updateActivity(final boolean broadcast) + { + acquireReadLock(); + try + { + if (getData().isAfk()) + { + acquireWriteLock(); + getData().setAfk(false); + if (broadcast && !hidden) + { + ess.broadcastMessage(this, _("userIsNotAway", getDisplayName())); + } + } + lastActivity = System.currentTimeMillis(); + } + finally + { + unlock(); + } + } + + public void checkActivity() + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + final long autoafkkick = settings.getData().getCommands().getAfk().getAutoAFKKick(); + if (autoafkkick > 0 && lastActivity > 0 && (lastActivity + (autoafkkick * 1000)) < System.currentTimeMillis() + && !hidden + && !Permissions.KICK_EXEMPT.isAuthorized(this) + && !Permissions.AFK_KICKEXEMPT.isAuthorized(this)) + { + final String kickReason = _("autoAfkKickReason", autoafkkick / 60.0); + lastActivity = 0; + kickPlayer(kickReason); + + + for (IPlayer player : ess.getServer().getOnlinePlayers()) + { + final IUser user = player.getUser(); + if (Permissions.KICK_NOTIFY.isAuthorized(user)) + { + player.sendMessage(_("playerKicked", Console.NAME, getName(), kickReason)); + } + } + } + final long autoafk = settings.getData().getCommands().getAfk().getAutoAFK(); + acquireReadLock(); + try + { + if (!getData().isAfk() && autoafk > 0 && lastActivity + autoafk * 1000 < System.currentTimeMillis() && Permissions.AFK.isAuthorized(this)) + { + setAfk(true); + if (!hidden) + { + ess.broadcastMessage(this, _("userIsAway", getDisplayName())); + } + } + } + finally + { + unlock(); + } + } + + public Location getAfkPosition() + { + return afkPosition; + } + + public boolean toggleGodModeEnabled() + { + if (!isGodModeEnabled()) + { + setFoodLevel(20); + } + return super.toggleGodmode(); + } + + public boolean isGodModeEnabled() + { + acquireReadLock(); + try + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + return (getData().isGodmode() + && !settings.getData().getWorldOptions(getLocation().getWorld().getName()).isGodmode()) + || (getData().isAfk() && settings.getData().getCommands().getAfk().isFreezeAFKPlayers()); + } + finally + { + unlock(); + } + } + + @Override + public Location getHome(String name) throws Exception + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void updateCompass() + { + try + { + Location loc = getHome(getLocation()); + if (loc == null) + { + loc = getBedSpawnLocation(); + } + if (loc != null) + { + setCompassTarget(loc); + } + } + catch (Exception ex) + { + // Ignore + } + } + + @Override + public List getHomes() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int compareTo(final IUser t) + { + return Util.stripColor(this.getDisplayName()).compareTo(Util.stripColor(t.getDisplayName())); + } + + @Override + public void requestTeleport(IUser user, boolean b) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setReplyTo(CommandSender user) + { + replyTo = user; + } + + @Override + public CommandSender getReplyTo() + { + return replyTo; + } + + @Override + public boolean gotMailInfo() + { + return gotMailInfo.getAndSet(true); + } + + @Override + public void addMail(String mail) + { + super.addMail(mail); + gotMailInfo.set(false); + } + + @Override + public void giveItems(ItemStack itemStack, Boolean canSpew) throws ChargeException + { + if (giveItemStack(itemStack, canSpew)) + { + sendMessage(_("InvFull")); + } + updateInventory(); + } + + @Override + public void giveItems(List itemStacks, Boolean canSpew) throws ChargeException + { + boolean spew = false; + for (ItemStack itemStack : itemStacks) + { + if (giveItemStack(itemStack, canSpew)) + { + spew = true; + } + } + if (spew) + { + sendMessage(_("InvFull")); + } + updateInventory(); + } + + private boolean giveItemStack(ItemStack itemStack, Boolean canSpew) throws ChargeException + { + boolean spew = false; + + if (itemStack == null || itemStack.isAir()) + { + return spew; + } + + final Map overfilled; + if (Permissions.OVERSIZEDSTACKS.isAuthorized(this)) + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + int oversizedStackSize = settings.getData().getGeneral().getOversizedStacksize(); + + overfilled = getInventory().addItem(true, oversizedStackSize, itemStack); + } + else + { + overfilled = getInventory().addItem(true, itemStack); + } + if (canSpew) + { + for (ItemStack overflowStack : overfilled.values()) + { + getWorld().dropItemNaturally(getLocation(), overflowStack); + spew = true; + } + } + else { + if (!overfilled.isEmpty()) { + throw new ChargeException("Inventory full"); + } + } + return spew; + } + + @Override + public boolean canAfford(final double cost) + { + final double mon = getMoney(); + if (Permissions.ECO_LOAN.isAuthorized(this)) + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + return (mon - cost) >= settings.getData().getEconomy().getMinMoney(); + } + return cost <= mon; + } + + public void updateMoneyCache(double userMoney) { + if (super.getMoney() != userMoney) { + super.setMoney(userMoney); + } + } + + public boolean canAfford(double amount, boolean b) { + return true; + } +} diff --git a/Essentials/src/net/ess3/user/UserBase.java b/Essentials/src/net/ess3/user/UserBase.java new file mode 100644 index 000000000..ebd0dc361 --- /dev/null +++ b/Essentials/src/net/ess3/user/UserBase.java @@ -0,0 +1,368 @@ +package net.ess3.user; + +import net.ess3.utils.Util; +import net.ess3.api.IEssentials; +import net.ess3.api.ISettings; +import net.ess3.api.InvalidNameException; +import net.ess3.api.server.Player; +import net.ess3.api.server.Location; +import net.ess3.storage.AsyncStorageObjectHolder; +import net.ess3.storage.IStorageObjectHolder; +import net.ess3.storage.StoredLocation.WorldNotLoadedException; +import java.io.File; +import java.io.IOException; +import java.util.*; +import lombok.Cleanup; +import lombok.Delegate; + + +public abstract class UserBase extends AsyncStorageObjectHolder implements Player, IStorageObjectHolder +{ + @Delegate + protected Player base; + + public UserBase(final Player base, final IEssentials ess) + { + super(ess, UserData.class); + this.base = base; + onReload(); + } + + public final Player getBase() + { + return base; + } + + public final Player setBase(final Player base) + { + return this.base = base; + } + + public void update(final Player base) + { + setBase(base); + } + + + + public void dispose() + { + this.base = null; + } + + @Override + public File getStorageFile() throws IOException + { + try + { + return ess.getUserMap().getUserFile(getName()); + } + catch (InvalidNameException ex) + { + throw new IOException(ex.getMessage(), ex); + } + } + + public long getTimestamp(final UserData.TimestampType name) + { + acquireReadLock(); + try + { + if (getData().getTimestamps() == null) + { + return 0; + } + Long ts = getData().getTimestamps().get(name); + return ts == null ? 0 : ts; + } + finally + { + unlock(); + } + } + + public void setTimestamp(final UserData.TimestampType name, final long value) + { + acquireWriteLock(); + try + { + if (getData().getTimestamps() == null) + { + getData().setTimestamps(new HashMap()); + } + getData().getTimestamps().put(name, value); + } + finally + { + unlock(); + } + } + + public void setMoney(final double value) + { + acquireWriteLock(); + try + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (Math.abs(value) > settings.getData().getEconomy().getMaxMoney()) + { + getData().setMoney(value < 0 ? -settings.getData().getEconomy().getMaxMoney() : settings.getData().getEconomy().getMaxMoney()); + } + else + { + getData().setMoney(value); + } + } + finally + { + unlock(); + } + } + + public double getMoney() + { + acquireReadLock(); + try + { + Double money = getData().getMoney(); + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (money == null) + { + money = (double)settings.getData().getEconomy().getStartingBalance(); + } + if (Math.abs(money) > settings.getData().getEconomy().getMaxMoney()) + { + money = money < 0 ? -settings.getData().getEconomy().getMaxMoney() : settings.getData().getEconomy().getMaxMoney(); + } + return money; + } + finally + { + unlock(); + } + } + + public void setHome(String name, Location loc) + { + acquireWriteLock(); + try + { + Map homes = getData().getHomes(); + if (homes == null) + { + homes = new HashMap(); + getData().setHomes(homes); + } + homes.put(Util.sanitizeKey(name), new net.ess3.storage.StoredLocation(loc)); + } + finally + { + unlock(); + } + } + + public boolean toggleAfk() + { + acquireWriteLock(); + try + { + boolean ret = !getData().isAfk(); + getData().setAfk(ret); + return ret; + } + finally + { + unlock(); + } + } + + public boolean toggleGodmode() + { + acquireWriteLock(); + try + { + boolean ret = !getData().isGodmode(); + getData().setGodmode(ret); + return ret; + } + finally + { + unlock(); + } + } + + public boolean toggleMuted() + { + acquireWriteLock(); + try + { + boolean ret = !getData().isMuted(); + getData().setMuted(ret); + return ret; + } + finally + { + unlock(); + } + } + + public boolean toggleSocialSpy() + { + acquireWriteLock(); + try + { + boolean ret = !getData().isSocialspy(); + getData().setSocialspy(ret); + return ret; + } + finally + { + unlock(); + } + } + + public boolean toggleTeleportEnabled() + { + acquireWriteLock(); + try + { + boolean ret = !getData().isTeleportEnabled(); + getData().setTeleportEnabled(ret); + return ret; + } + finally + { + unlock(); + } + } + + public boolean isIgnoringPlayer(final String name) + { + acquireReadLock(); + try + { + return getData().getIgnore() == null ? false : getData().getIgnore().contains(name.toLowerCase(Locale.ENGLISH)); + } + finally + { + unlock(); + } + } + + public void setIgnoredPlayer(final String name, final boolean set) + { + acquireWriteLock(); + try + { + if (getData().getIgnore() == null) + { + getData().setIgnore(new HashSet()); + } + if (set) + { + getData().getIgnore().add(name.toLowerCase(Locale.ENGLISH)); + } + else + { + getData().getIgnore().remove(name.toLowerCase(Locale.ENGLISH)); + } + } + finally + { + unlock(); + } + } + + public void addMail(String string) + { + acquireWriteLock(); + try + { + if (getData().getMails() == null) + { + getData().setMails(new ArrayList()); + } + getData().getMails().add(string); + } + finally + { + unlock(); + } + } + + public List getMails() + { + acquireReadLock(); + try + { + if (getData().getMails() == null) + { + return Collections.emptyList(); + } + else + { + return new ArrayList(getData().getMails()); + } + } + finally + { + unlock(); + } + } + + public Location getHome(Location loc) + { + + acquireReadLock(); + try + { + if (getData().getHomes() == null) + { + return null; + } + ArrayList worldHomes = new ArrayList(); + for (net.ess3.storage.StoredLocation location : getData().getHomes().values()) + { + if (location.getWorldName().equals(loc.getWorld().getName())) + { + try + { + worldHomes.add(location.getStoredLocation()); + } + catch (WorldNotLoadedException ex) + { + continue; + } + } + } + if (worldHomes.isEmpty()) + { + return null; + } + if (worldHomes.size() == 1) + { + return worldHomes.get(0); + } + double distance = Double.MAX_VALUE; + Location target = null; + for (Location location : worldHomes) + { + final double d = loc.distanceSquared(location); + if (d < distance) + { + target = location; + distance = d; + } + } + return target; + } + finally + { + unlock(); + } + } +} diff --git a/Essentials/src/net/ess3/user/UserData.java b/Essentials/src/net/ess3/user/UserData.java new file mode 100644 index 000000000..aecd32ced --- /dev/null +++ b/Essentials/src/net/ess3/user/UserData.java @@ -0,0 +1,106 @@ +package net.ess3.user; + +import net.ess3.api.server.Material; +import net.ess3.storage.*; +import java.util.*; +import lombok.Data; +import lombok.EqualsAndHashCode; + + + +@Data +@EqualsAndHashCode(callSuper = false) +public class UserData implements StorageObject +{ + public enum TimestampType + { + JAIL, MUTE, LASTHEAL, LASTTELEPORT, LOGIN, LOGOUT + } + private String nickname; + private Double money; + @MapValueType(StoredLocation.class) + private Map homes = new HashMap(); + @ListType(Material.class) + private Set unlimited = new HashSet(); + @MapValueType(List.class) + @MapKeyType(Material.class) + private Map> powerTools = new HashMap>(); + private StoredLocation lastLocation; + @MapKeyType(TimestampType.class) + @MapValueType(Long.class) + private Map timestamps = new HashMap(); + private String jail; + @ListType + private List mails; + private Inventory inventory; + private boolean teleportEnabled; + @ListType + private Set ignore; + private boolean godmode; + private boolean muted; + private boolean jailed; + private Ban ban; + private String ipAddress; + private boolean afk; + private boolean newplayer = true; + private String geolocation; + private boolean socialspy; + private boolean npc; + private boolean powerToolsEnabled; + + public UserData() + { + timestamps.put(TimestampType.JAIL, Long.MIN_VALUE); + } + + public boolean hasUnlimited(Material mat) + { + return unlimited != null && unlimited.contains(mat); + } + + public void setUnlimited(Material mat, boolean state) + { + if (unlimited.contains(mat)) + { + unlimited.remove(mat); + } + if (state) + { + unlimited.add(mat); + } + } + + public List getPowertool(Material mat) + { + return powerTools == null ? Collections.emptyList() : powerTools.get(mat); + } + + + public boolean hasPowerTools() + { + return powerTools != null && !powerTools.isEmpty(); + } + + public void setPowertool(Material mat, List commands) + { + if (powerTools == null) + { + powerTools = new HashMap>(); + } + powerTools.put(mat, commands); + } + + public void clearAllPowertools() + { + powerTools = null; + } + + public void removeHome(String home) + { + if (homes == null) + { + return; + } + homes.remove(home); + } +} diff --git a/Essentials/src/net/ess3/user/UserMap.java b/Essentials/src/net/ess3/user/UserMap.java new file mode 100644 index 000000000..cac3985ab --- /dev/null +++ b/Essentials/src/net/ess3/user/UserMap.java @@ -0,0 +1,254 @@ +package net.ess3.user; + +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import net.ess3.api.IUserMap; +import net.ess3.api.InvalidNameException; +import net.ess3.api.server.Player; +import net.ess3.storage.StorageObjectMap; +import net.ess3.utils.Util; +import java.io.File; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.Locale; +import java.util.Set; +import org.bukkit.Bukkit; + + +public class UserMap extends StorageObjectMap implements IUserMap +{ + public UserMap(final IEssentials ess) + { + super(ess, "users"); + } + + @Override + public boolean userExists(final String name) + { + return objectExists(name); + } + + @Override + public IUser getUser(final String name) + { + return getObject(name); + } + + @Override + public IUser load(final String name) throws Exception + { + for (Player player : ess.getServer().getOnlinePlayers()) + { + if (player.getName().equalsIgnoreCase(name)) + { + keys.add(name.toLowerCase(Locale.ENGLISH)); + return new User(player, ess); + } + } + final File userFile = getUserFile(name); + if (userFile.exists()) + { + keys.add(name.toLowerCase(Locale.ENGLISH)); + return new User(Bukkit.getOfflinePlayer(name), ess); + } + throw new Exception("User not found!"); + } + + @Override + public void removeUser(final String name) throws InvalidNameException + { + removeObject(name); + } + + @Override + public Set getAllUniqueUsers() + { + return getAllKeys(); + } + + @Override + public int getUniqueUsers() + { + return getKeySize(); + } + + @Override + public File getUserFile(String name) throws InvalidNameException + { + return getStorageFile(name); + } + + @Override + public IUser getUser(final Player player) + { + if (player instanceof IUser) + { + return (IUser)player; + } + IUser user = getUser(player.getName()); + + if (user == null) + { + user = new User(player, ess); + } + else + { + ((User)user).update(player); + } + return user; + } + + @Override + public IUser matchUser(final String name, final boolean includeHidden, final boolean includeOffline) throws TooManyMatchesException + { + final Set users = matchUsers(name, includeHidden, includeOffline); + if (users == null || users.isEmpty()) + { + return null; + } + else + { + if (users.size() > 1) + { + throw new TooManyMatchesException(); + } + else + { + return users.iterator().next(); + } + } + } + + @Override + public Set matchUsers(final String name, final boolean includeHidden, final boolean includeOffline) + { + final String colorlessName = Util.stripColor(name); + final String[] search = colorlessName.split(","); + final boolean multisearch = search.length > 1; + final Set result = new LinkedHashSet(); + final String nicknamePrefix = Util.stripColor(getNickNamePrefix()); + for (String searchString : search) + { + if (searchString.isEmpty()) + { + continue; + } + + if (searchString.startsWith(nicknamePrefix)) + { + searchString = searchString.substring(nicknamePrefix.length()); + } + searchString = searchString.toLowerCase(Locale.ENGLISH); + final boolean multimatching = searchString.endsWith("*"); + if (multimatching) + { + searchString = searchString.substring(0, searchString.length() - 1); + } + Player match = null; + for (Player player : ess.getServer().getOnlinePlayers()) + { + if (player.getName().equalsIgnoreCase(searchString) + && (includeHidden || (includeOffline && player.getUser().isHidden()))) + { + match = player; + break; + } + } + if (match != null) + { + if (multimatching || multisearch) + { + result.add(match.getUser()); + } + else + { + return Collections.singleton(match.getUser()); + } + } + for (Player player : ess.getServer().getOnlinePlayers()) + { + final String nickname = player.getUser().getData().getNickname(); + if (nickname != null && !nickname.isEmpty() + && nickname.equalsIgnoreCase(searchString) + && (includeHidden || (includeOffline && player.getUser().isHidden()))) + { + if (multimatching || multisearch) + { + result.add(player.getUser()); + } + else + { + return Collections.singleton(player.getUser()); + } + } + } + if (includeOffline) + { + for (String playerName : getAllUniqueUsers()) + { + if (playerName.equals(searchString)) + { + match = getUser(playerName); + break; + } + } + if (match != null) + { + if (multimatching || multisearch) + { + result.add(match.getUser()); + } + else + { + return Collections.singleton(match.getUser()); + } + } + } + if (multimatching || match == null) + { + for (Player player : ess.getServer().getOnlinePlayers()) + { + if (player.getName().toLowerCase(Locale.ENGLISH).startsWith(searchString) + && (includeHidden || (includeOffline && player.getUser().isHidden()))) + { + result.add(player.getUser()); + break; + } + final String nickname = player.getUser().getData().getNickname(); + if (nickname != null && !nickname.isEmpty() + && nickname.toLowerCase(Locale.ENGLISH).startsWith(searchString) + && (includeHidden || (includeOffline && player.getUser().isHidden()))) + { + result.add(player.getUser()); + break; + } + } + if (includeOffline) + { + for (String playerName : getAllUniqueUsers()) + { + if (playerName.startsWith(searchString)) + { + result.add(getUser(playerName)); + break; + } + } + } + } + } + return result; + } + + private String getNickNamePrefix() + { + ess.getSettings().acquireReadLock(); + try + { + return ess.getSettings().getData().getChat().getNicknamePrefix(); + } + finally + { + ess.getSettings().unlock(); + } + } +} diff --git a/Essentials/src/net/ess3/utils/DateUtil.java b/Essentials/src/net/ess3/utils/DateUtil.java new file mode 100644 index 000000000..02916139c --- /dev/null +++ b/Essentials/src/net/ess3/utils/DateUtil.java @@ -0,0 +1,186 @@ +package net.ess3.utils; + +import static net.ess3.I18n._; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class DateUtil { + public static String formatDateDiff(long date) + { + Calendar c = new GregorianCalendar(); + c.setTimeInMillis(date); + Calendar now = new GregorianCalendar(); + return formatDateDiff(now, c); + } + + public static String formatDateDiff(Calendar fromDate, Calendar toDate) + { + boolean future = false; + if (toDate.equals(fromDate)) + { + return _("now"); + } + if (toDate.after(fromDate)) + { + future = true; + } + + 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[] + { + _("year"), + _("years"), + _("month"), + _("months"), + _("day"), + _("days"), + _("hour"), + _("hours"), + _("minute"), + _("minutes"), + _("second"), + _("seconds") + }; + for (int i = 0; i < types.length; i++) + { + int diff = dateDiff(types[i], fromDate, toDate, future); + if (diff > 0) + { + sb.append(" ").append(diff).append(" ").append(names[i * 2 + (diff > 1 ? 1 : 0)]); + } + } + if (sb.length() == 0) + { + return "now"; + } + return sb.toString(); + } + + private static int dateDiff(int type, Calendar fromDate, Calendar toDate, boolean future) + { + int diff = 0; + long savedDate = fromDate.getTimeInMillis(); + while ((future && !fromDate.after(toDate)) || (!future && !fromDate.before(toDate))) + { + savedDate = fromDate.getTimeInMillis(); + fromDate.add(type, future ? 1 : -1); + diff++; + } + diff--; + fromDate.setTimeInMillis(savedDate); + return diff; + } + + public static long parseDateDiff(String time, boolean future) throws Exception + { + 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); + Matcher m = timePattern.matcher(time); + int years = 0; + int months = 0; + int weeks = 0; + int days = 0; + int hours = 0; + int minutes = 0; + int seconds = 0; + boolean found = false; + while (m.find()) + { + if (m.group() == null || m.group().isEmpty()) + { + continue; + } + for (int i = 0; i < m.groupCount(); i++) + { + if (m.group(i) != null && !m.group(i).isEmpty()) + { + found = true; + break; + } + } + if (found) + { + if (m.group(1) != null && !m.group(1).isEmpty()) + { + years = Integer.parseInt(m.group(1)); + } + if (m.group(2) != null && !m.group(2).isEmpty()) + { + months = Integer.parseInt(m.group(2)); + } + if (m.group(3) != null && !m.group(3).isEmpty()) + { + weeks = Integer.parseInt(m.group(3)); + } + if (m.group(4) != null && !m.group(4).isEmpty()) + { + days = Integer.parseInt(m.group(4)); + } + if (m.group(5) != null && !m.group(5).isEmpty()) + { + hours = Integer.parseInt(m.group(5)); + } + if (m.group(6) != null && !m.group(6).isEmpty()) + { + minutes = Integer.parseInt(m.group(6)); + } + if (m.group(7) != null && !m.group(7).isEmpty()) + { + seconds = Integer.parseInt(m.group(7)); + } + break; + } + } + if (!found) + { + throw new Exception(_("illegalDate")); + } + Calendar c = new GregorianCalendar(); + if (years > 0) + { + c.add(Calendar.YEAR, years * (future ? 1 : -1)); + } + if (months > 0) + { + c.add(Calendar.MONTH, months * (future ? 1 : -1)); + } + if (weeks > 0) + { + c.add(Calendar.WEEK_OF_YEAR, weeks * (future ? 1 : -1)); + } + if (days > 0) + { + c.add(Calendar.DAY_OF_MONTH, days * (future ? 1 : -1)); + } + if (hours > 0) + { + c.add(Calendar.HOUR_OF_DAY, hours * (future ? 1 : -1)); + } + if (minutes > 0) + { + c.add(Calendar.MINUTE, minutes * (future ? 1 : -1)); + } + if (seconds > 0) + { + c.add(Calendar.SECOND, seconds * (future ? 1 : -1)); + } + return c.getTimeInMillis(); + } +} diff --git a/Essentials/src/net/ess3/utils/DescParseTickFormat.java b/Essentials/src/net/ess3/utils/DescParseTickFormat.java new file mode 100644 index 000000000..8c3fbadfe --- /dev/null +++ b/Essentials/src/net/ess3/utils/DescParseTickFormat.java @@ -0,0 +1,295 @@ +package net.ess3.utils; + +import static net.ess3.I18n._; +import java.text.SimpleDateFormat; +import java.util.*; + + +/** + * 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. + * + * http://www.minecraftwiki.net/wiki/Day/night_cycle + * + * @author Olof Larsson + */ +public final class DescParseTickFormat +{ + public static final Map nameToTicks = new LinkedHashMap(); + public static final Set resetAliases = new HashSet(); + public static final int ticksAtMidnight = 18000; + public static final int ticksPerDay = 24000; + public static final int ticksPerHour = 1000; + public static final double ticksPerMinute = 1000d / 60d; + public static final double ticksPerSecond = 1000d / 60d / 60d; + private static final SimpleDateFormat SDFTwentyFour = new SimpleDateFormat("HH:mm", Locale.ENGLISH); + private static final SimpleDateFormat SDFTwelve = new SimpleDateFormat("h:mmaa", Locale.ENGLISH); + + static + { + SDFTwentyFour.setTimeZone(TimeZone.getTimeZone("GMT")); + SDFTwelve.setTimeZone(TimeZone.getTimeZone("GMT")); + + nameToTicks.put("sunrise", 23000); + nameToTicks.put("dawn", 23000); + + nameToTicks.put("daystart", 0); + nameToTicks.put("day", 0); + + nameToTicks.put("morning", 1000); + + nameToTicks.put("midday", 6000); + nameToTicks.put("noon", 6000); + + nameToTicks.put("afternoon", 9000); + + nameToTicks.put("sunset", 12000); + nameToTicks.put("dusk", 12000); + nameToTicks.put("sundown", 12000); + nameToTicks.put("nightfall", 12000); + + nameToTicks.put("nightstart", 14000); + nameToTicks.put("night", 14000); + + nameToTicks.put("midnight", 18000); + + resetAliases.add("reset"); + resetAliases.add("normal"); + resetAliases.add("default"); + } + + private DescParseTickFormat() + { + } + + // ============================================ + // PARSE. From describing String to int + // -------------------------------------------- + public static long parse(String desc) throws NumberFormatException + { + // Only look at alphanumeric and lowercase and : for 24:00 + desc = desc.toLowerCase(Locale.ENGLISH).replaceAll("[^A-Za-z0-9:]", ""); + + // Detect ticks format + try + { + return parseTicks(desc); + } + catch (Exception e) + { + } + + // Detect 24-hour format + try + { + return parse24(desc); + } + catch (Exception e) + { + } + + // Detect 12-hour format + try + { + return parse12(desc); + } + catch (Exception e) + { + } + + // Detect aliases + try + { + return parseAlias(desc); + } + catch (Exception e) + { + } + + // Well we failed to understand... + throw new NumberFormatException(); + } + + public static long parseTicks(String desc) throws NumberFormatException + { + if (!desc.matches("^[0-9]+ti?c?k?s?$")) + { + throw new NumberFormatException(); + } + + desc = desc.replaceAll("[^0-9]", ""); + + return Long.parseLong(desc) % 24000; + } + + public static long parse24(String desc) throws NumberFormatException + { + if (!desc.matches("^[0-9]{2}[^0-9]?[0-9]{2}$")) + { + throw new NumberFormatException(); + } + + desc = desc.toLowerCase(Locale.ENGLISH).replaceAll("[^0-9]", ""); + + if (desc.length() != 4) + { + throw new NumberFormatException(); + } + + final int hours = Integer.parseInt(desc.substring(0, 2)); + final int minutes = Integer.parseInt(desc.substring(2, 4)); + + return hoursMinutesToTicks(hours, minutes); + } + + public static long parse12(String desc) throws NumberFormatException + { + if (!desc.matches("^[0-9]{1,2}([^0-9]?[0-9]{2})?(pm|am)$")) + { + throw new NumberFormatException(); + } + + int hours = 0; + int minutes = 0; + + desc = desc.toLowerCase(Locale.ENGLISH).replaceAll("[^0-9]", ""); + + if (desc.length() > 4) + { + throw new NumberFormatException(); + } + + if (desc.length() == 4) + { + hours += Integer.parseInt(desc.substring(0, 2)); + minutes += Integer.parseInt(desc.substring(2, 4)); + } + else if (desc.length() == 3) + { + hours += Integer.parseInt(desc.substring(0, 1)); + minutes += Integer.parseInt(desc.substring(1, 3)); + } + else if (desc.length() == 2) + { + hours += Integer.parseInt(desc.substring(0, 2)); + } + else if (desc.length() == 1) + { + hours += Integer.parseInt(desc.substring(0, 1)); + } + else + { + throw new NumberFormatException(); + } + + if (desc.endsWith("pm") && hours != 12) + { + hours += 12; + } + + if (desc.endsWith("am") && hours == 12) + { + hours -= 12; + } + + return hoursMinutesToTicks(hours, minutes); + } + + public static long hoursMinutesToTicks(final int hours, final int minutes) + { + long ret = ticksAtMidnight; + ret += (hours) * ticksPerHour; + + ret += (minutes / 60.0) * ticksPerHour; + + ret %= ticksPerDay; + return ret; + } + + public static long parseAlias(final String desc) throws NumberFormatException + { + final Integer ret = nameToTicks.get(desc); + if (ret == null) + { + throw new NumberFormatException(); + } + + return ret; + } + + public static boolean meansReset(final String desc) + { + return resetAliases.contains(desc); + } + + // ============================================ + // FORMAT. From int to describing String + // -------------------------------------------- + public static String format(final long ticks) + { + return _("timeFormat", format24(ticks), format12(ticks), formatTicks(ticks)); + } + + public static String formatTicks(final long ticks) + { + return (ticks % ticksPerDay) + "ticks"; + } + + public static String format24(final long ticks) + { + synchronized (SDFTwentyFour) + { + return formatDateFormat(ticks, SDFTwentyFour); + } + } + + public static String format12(final long ticks) + { + synchronized (SDFTwelve) + { + return formatDateFormat(ticks, SDFTwelve); + } + } + + public static String formatDateFormat(final long ticks, final SimpleDateFormat format) + { + final Date date = ticksToDate(ticks); + return format.format(date); + } + + public static Date ticksToDate(long ticks) + { + // Assume the server time starts at 0. It would start on a day. + // But we will simulate that the server started with 0 at midnight. + ticks = ticks - ticksAtMidnight + ticksPerDay; + + // How many ingame days have passed since the server start? + final long days = ticks / ticksPerDay; + ticks = ticks - days * ticksPerDay; + + // How many hours on the last day? + final long hours = ticks / ticksPerHour; + ticks = ticks - hours * ticksPerHour; + + // How many minutes on the last day? + final long minutes = (long)Math.floor(ticks / ticksPerMinute); + final double dticks = ticks - minutes * ticksPerMinute; + + // How many seconds on the last day? + final long seconds = (long)Math.floor(dticks / ticksPerSecond); + + // Now we create an english GMT calendar (We wan't no daylight savings) + final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.ENGLISH); + cal.setLenient(true); + + // And we set the time to 0! And append the time that passed! + cal.set(0, Calendar.JANUARY, 1, 0, 0, 0); + cal.add(Calendar.DAY_OF_YEAR, (int)days); + cal.add(Calendar.HOUR_OF_DAY, (int)hours); + cal.add(Calendar.MINUTE, (int)minutes); + cal.add(Calendar.SECOND, (int)seconds + 1); // To solve rounding errors. + + return cal.getTime(); + } +} diff --git a/Essentials/src/net/ess3/utils/ExecuteTimer.java b/Essentials/src/net/ess3/utils/ExecuteTimer.java new file mode 100644 index 000000000..2f0c7a5f6 --- /dev/null +++ b/Essentials/src/net/ess3/utils/ExecuteTimer.java @@ -0,0 +1,89 @@ +package net.ess3.utils; + +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +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(); + } + + public void start() + { + times.clear(); + mark("start"); + + } + + public void mark(final String label) + { + if (!times.isEmpty() || "start".equals(label)) + { + times.add(new ExecuteRecord(label, System.nanoTime())); + } + } + + public String end() + { + final StringBuilder output = new StringBuilder(); + output.append("execution time: "); + String mark; + long time0 = 0; + long time1 = 0; + long time2 = 0; + double duration; + + for (ExecuteRecord pair : times) + { + mark = (String)pair.getMark(); + time2 = (Long)pair.getTime(); + if (time1 > 0) + { + duration = (time2 - time1)/1000000.0; + output.append(mark).append(": ").append(decimalFormat.format(duration)).append("ms - "); + } + else + { + time0 = time2; + } + time1 = time2; + } + duration = (time1 - time0)/1000000.0; + output.append("Total: ").append(decimalFormat.format(duration)).append("ms"); + times.clear(); + return output.toString(); + } + + + static private class ExecuteRecord + { + private final String mark; + private final long time; + + public ExecuteRecord(final String mark, final long time) + { + this.mark = mark; + this.time = time; + } + + public String getMark() + { + return mark; + } + + public long getTime() + { + return time; + } + } +} \ No newline at end of file diff --git a/Essentials/src/net/ess3/utils/LocationUtil.java b/Essentials/src/net/ess3/utils/LocationUtil.java new file mode 100644 index 000000000..61cdcec6e --- /dev/null +++ b/Essentials/src/net/ess3/utils/LocationUtil.java @@ -0,0 +1,142 @@ +package net.ess3.utils; + +import static net.ess3.I18n._; +import java.util.HashSet; +import java.util.Set; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.entity.LivingEntity; + +public class LocationUtil { + // The player can stand inside these materials + private static final Set AIR_MATERIALS = new HashSet(); + private static final HashSet AIR_MATERIALS_TARGET = new HashSet(); + + static + { + AIR_MATERIALS.add(Material.AIR.getId()); + AIR_MATERIALS.add(Material.SAPLING.getId()); + AIR_MATERIALS.add(Material.POWERED_RAIL.getId()); + AIR_MATERIALS.add(Material.DETECTOR_RAIL.getId()); + AIR_MATERIALS.add(Material.LONG_GRASS.getId()); + AIR_MATERIALS.add(Material.DEAD_BUSH.getId()); + AIR_MATERIALS.add(Material.YELLOW_FLOWER.getId()); + AIR_MATERIALS.add(Material.RED_ROSE.getId()); + AIR_MATERIALS.add(Material.BROWN_MUSHROOM.getId()); + AIR_MATERIALS.add(Material.RED_MUSHROOM.getId()); + AIR_MATERIALS.add(Material.TORCH.getId()); + AIR_MATERIALS.add(Material.REDSTONE_WIRE.getId()); + AIR_MATERIALS.add(Material.SEEDS.getId()); + AIR_MATERIALS.add(Material.SIGN_POST.getId()); + AIR_MATERIALS.add(Material.WOODEN_DOOR.getId()); + AIR_MATERIALS.add(Material.LADDER.getId()); + AIR_MATERIALS.add(Material.RAILS.getId()); + AIR_MATERIALS.add(Material.WALL_SIGN.getId()); + AIR_MATERIALS.add(Material.LEVER.getId()); + AIR_MATERIALS.add(Material.STONE_PLATE.getId()); + AIR_MATERIALS.add(Material.IRON_DOOR_BLOCK.getId()); + AIR_MATERIALS.add(Material.WOOD_PLATE.getId()); + AIR_MATERIALS.add(Material.REDSTONE_TORCH_OFF.getId()); + AIR_MATERIALS.add(Material.REDSTONE_TORCH_ON.getId()); + AIR_MATERIALS.add(Material.STONE_BUTTON.getId()); + AIR_MATERIALS.add(Material.SUGAR_CANE_BLOCK.getId()); + AIR_MATERIALS.add(Material.DIODE_BLOCK_OFF.getId()); + AIR_MATERIALS.add(Material.DIODE_BLOCK_ON.getId()); + AIR_MATERIALS.add(Material.TRAP_DOOR.getId()); + AIR_MATERIALS.add(Material.PUMPKIN_STEM.getId()); + AIR_MATERIALS.add(Material.MELON_STEM.getId()); + AIR_MATERIALS.add(Material.VINE.getId()); + AIR_MATERIALS.add(Material.NETHER_WARTS.getId()); + AIR_MATERIALS.add(Material.WATER_LILY.getId()); + + for (Integer integer : AIR_MATERIALS) + { + AIR_MATERIALS_TARGET.add(integer.byteValue()); + } + AIR_MATERIALS_TARGET.add((byte)Material.WATER.getId()); + AIR_MATERIALS_TARGET.add((byte)Material.STATIONARY_WATER.getId()); + } + + public static Location getTarget(final LivingEntity entity) throws Exception + { + final Block block = entity.getTargetBlock(AIR_MATERIALS_TARGET, 300); + if (block == null) + { + throw new Exception("Not targeting a block"); + } + return block.getLocation(); + } + + public static Location getSafeDestination(final Location loc) throws Exception + { + if (loc == null || loc.getWorld() == null) + { + throw new Exception(_("destinationNotSet")); + } + final World world = loc.getWorld(); + int x = loc.getBlockX(); + int y = (int)Math.round(loc.getY()); + int z = loc.getBlockZ(); + + while (isBlockAboveAir(world, x, y, z)) + { + y -= 1; + if (y < 0) + { + break; + } + } + + while (isBlockUnsafe(world, x, y, z)) + { + y += 1; + if (y >= world.getHighestBlockYAt(x, z)) + { + x += 1; + break; + } + } + while (isBlockUnsafe(world, x, y, z)) + { + y -= 1; + if (y <= 1) + { + x += 1; + y = world.getHighestBlockYAt(x, z); + if (x - 32 > loc.getBlockX()) + { + throw new Exception(_("holeInFloor")); + } + } + } + return new Location(world, x + 0.5D, y, z + 0.5D, loc.getYaw(), loc.getPitch()); + } + + private static boolean isBlockAboveAir(final World world, final int x, final int y, final int z) + { + return AIR_MATERIALS.contains(world.getBlockAt(x, y - 1, z).getType().getId()); + } + + public static boolean isBlockUnsafe(final World world, final int x, final int y, final int z) + { + final Block below = world.getBlockAt(x, y - 1, z); + if (below.getType() == Material.LAVA || below.getType() == Material.STATIONARY_LAVA) + { + return true; + } + + if (below.getType() == Material.FIRE) + { + return true; + } + + if ((!AIR_MATERIALS.contains(world.getBlockAt(x, y, z).getType().getId())) + || (!AIR_MATERIALS.contains(world.getBlockAt(x, y + 1, z).getType().getId()))) + { + return true; + } + return isBlockAboveAir(world, x, y, z); + } +} diff --git a/Essentials/src/net/ess3/utils/Util.java b/Essentials/src/net/ess3/utils/Util.java new file mode 100644 index 000000000..f00570685 --- /dev/null +++ b/Essentials/src/net/ess3/utils/Util.java @@ -0,0 +1,353 @@ +package net.ess3.utils; + +import static net.ess3.I18n._; +import net.ess3.api.IEssentials; +import net.ess3.api.ISettings; +import net.ess3.api.InvalidNameException; +import net.ess3.utils.gnu.inet.encoding.Punycode; +import net.ess3.utils.gnu.inet.encoding.PunycodeException; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.Collection; +import java.util.Locale; +import java.util.regex.Pattern; +import lombok.Cleanup; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.inventory.ItemStack; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; +import org.bukkit.plugin.PluginManager; + + +public final class Util +{ + private Util() + { + } + private final static Pattern INVALIDFILECHARS = Pattern.compile("[^\u0020-\u007E\u0085\u00A0-\uD7FF\uE000-\uFFFC]"); + private final static Pattern INVALIDCHARS = Pattern.compile("[^\t\n\r\u0020-\u007E\u0085\u00A0-\uD7FF\uE000-\uFFFC]"); + + public static String sanitizeFileName(String name) throws InvalidNameException + { + try + { + String r = name.toLowerCase(Locale.ENGLISH); + r = r.replace('.', (char)('\ue200' + '.')); + r = r.replace('\\', (char)('\ue200' + '\\')); + r = r.replace('/', (char)('\ue200' + '/')); + r = r.replace('"', (char)('\ue200' + '"')); + r = r.replace('<', (char)('\ue200' + '<')); + r = r.replace('>', (char)('\ue200' + '>')); + r = r.replace('|', (char)('\ue200' + '|')); + r = r.replace('?', (char)('\ue200' + '?')); + r = r.replace('*', (char)('\ue200' + '*')); + r = r.replace(':', (char)('\ue200' + ':')); + r = r.replace('-', (char)('\ue200' + '-')); + r = INVALIDFILECHARS.matcher(r).replaceAll(""); + return Punycode.encode(r); + } + catch (PunycodeException ex) + { + throw new InvalidNameException(ex); + } + } + + public static String decodeFileName(String name) throws InvalidNameException + { + try + { + String r = Punycode.decode(name); + r = r.replace((char)('\ue200' + '.'), '.'); + r = r.replace((char)('\ue200' + '\\'), '\\'); + r = r.replace((char)('\ue200' + '/'), '/'); + r = r.replace((char)('\ue200' + '"'), '"'); + r = r.replace((char)('\ue200' + '<'), '<'); + r = r.replace((char)('\ue200' + '>'), '>'); + r = r.replace((char)('\ue200' + '|'), '|'); + r = r.replace((char)('\ue200' + '?'), '?'); + r = r.replace((char)('\ue200' + '*'), '*'); + r = r.replace((char)('\ue200' + ':'), ':'); + r = r.replace((char)('\ue200' + '-'), '-'); + return r; + } + catch (PunycodeException ex) + { + throw new InvalidNameException(ex); + } + } + + public static String sanitizeKey(String name) + { + return INVALIDCHARS.matcher(name.toLowerCase(Locale.ENGLISH)).replaceAll("_"); + } + + public static String sanitizeString(final String string) + { + return INVALIDCHARS.matcher(string).replaceAll(""); + } + + public static ItemStack convertBlockToItem(final Block block) + { + final ItemStack is = new ItemStack(block.getType(), 1, (short)0, block.getData()); + switch (is.getType()) + { + case WOODEN_DOOR: + is.setType(Material.WOOD_DOOR); + is.setDurability((short)0); + break; + case IRON_DOOR_BLOCK: + is.setType(Material.IRON_DOOR); + is.setDurability((short)0); + break; + case SIGN_POST: + case WALL_SIGN: + is.setType(Material.SIGN); + is.setDurability((short)0); + break; + case CROPS: + is.setType(Material.SEEDS); + is.setDurability((short)0); + break; + case CAKE_BLOCK: + is.setType(Material.CAKE); + is.setDurability((short)0); + break; + case BED_BLOCK: + is.setType(Material.BED); + is.setDurability((short)0); + break; + case REDSTONE_WIRE: + is.setType(Material.REDSTONE); + is.setDurability((short)0); + break; + case REDSTONE_TORCH_OFF: + case REDSTONE_TORCH_ON: + is.setType(Material.REDSTONE_TORCH_ON); + is.setDurability((short)0); + break; + case DIODE_BLOCK_OFF: + case DIODE_BLOCK_ON: + is.setType(Material.DIODE); + is.setDurability((short)0); + break; + case DOUBLE_STEP: + is.setType(Material.STEP); + break; + case TORCH: + case RAILS: + case LADDER: + case WOOD_STAIRS: + case COBBLESTONE_STAIRS: + case LEVER: + case STONE_BUTTON: + case FURNACE: + case DISPENSER: + case PUMPKIN: + case JACK_O_LANTERN: + case WOOD_PLATE: + case STONE_PLATE: + case PISTON_STICKY_BASE: + case PISTON_BASE: + case IRON_FENCE: + case THIN_GLASS: + case TRAP_DOOR: + case FENCE: + case FENCE_GATE: + case NETHER_FENCE: + is.setDurability((short)0); + break; + case FIRE: + return null; + case PUMPKIN_STEM: + is.setType(Material.PUMPKIN_SEEDS); + break; + case MELON_STEM: + is.setType(Material.MELON_SEEDS); + break; + } + return is; + } + private static DecimalFormat dFormat = new DecimalFormat("#0.00", DecimalFormatSymbols.getInstance(Locale.US)); + + public static String formatAsCurrency(final double value) + { + + String str = dFormat.format(value); + if (str.endsWith(".00")) + { + str = str.substring(0, str.length() - 3); + } + return str; + } + + public static String displayCurrency(final double value, final IEssentials ess) + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + return _("currency", settings.getData().getEconomy().getCurrencySymbol(), formatAsCurrency(value)); + } + + public static String shortCurrency(final double value, final IEssentials ess) + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + return settings.getData().getEconomy().getCurrencySymbol() + formatAsCurrency(value); + } + + public static double roundDouble(final double d) + { + return Math.round(d * 100.0) / 100.0; + } + + public static boolean isInt(final String sInt) + { + try + { + Integer.parseInt(sInt); + } + catch (NumberFormatException e) + { + return false; + } + return true; + } + + public static String joinList(Object... list) + { + return joinList(", ", list); + } + + public static String joinList(String seperator, Object... list) + { + StringBuilder buf = new StringBuilder(); + for (Object each : list) + { + if (buf.length() > 0) + { + buf.append(seperator); + } + + if (each instanceof Collection) + { + buf.append(joinList(seperator, ((Collection)each).toArray())); + } + else + { + try + { + buf.append(each.toString()); + } + catch (Exception e) + { + buf.append(each.toString()); + } + } + } + return buf.toString(); + } + + public static void registerPermissions(String path, Collection nodes, boolean hasDefault, IEssentials ess) + { + if (nodes == null || nodes.isEmpty()) + { + return; + } + final PluginManager pluginManager = ess.getServer().getPluginManager(); + Permission basePerm = pluginManager.getPermission(path + ".*"); + if (basePerm != null && !basePerm.getChildren().isEmpty()) + { + basePerm.getChildren().clear(); + } + if (basePerm == null) + { + basePerm = new Permission(path + ".*", PermissionDefault.OP); + pluginManager.addPermission(basePerm); + Permission mainPerm = pluginManager.getPermission("essentials.*"); + if (mainPerm == null) + { + mainPerm = new Permission("essentials.*", PermissionDefault.OP); + pluginManager.addPermission(mainPerm); + } + mainPerm.getChildren().put(basePerm.getName(), Boolean.TRUE); + } + + for (String nodeName : nodes) + { + final String permissionName = path + "." + nodeName; + Permission perm = pluginManager.getPermission(permissionName); + if (perm == null) + { + final PermissionDefault defaultPerm = hasDefault && nodeName.equalsIgnoreCase("default") ? PermissionDefault.TRUE : PermissionDefault.OP; + perm = new Permission(permissionName, defaultPerm); + pluginManager.addPermission(perm); + } + basePerm.getChildren().put(permissionName, Boolean.TRUE); + } + basePerm.recalculatePermissibles(); + } + private static transient final Pattern DOT_PATTERN = Pattern.compile("\\."); + + public static Permission registerPermission(String permission, PermissionDefault defaultPerm) + { + final PluginManager pluginManager = Bukkit.getServer().getPluginManager(); + final String[] parts = DOT_PATTERN.split(permission); + final StringBuilder builder = new StringBuilder(permission.length()); + Permission parent = null; + for (int i = 0; i < parts.length - 1; i++) + { + builder.append(parts[i]).append(".*"); + String permString = builder.toString(); + Permission perm = pluginManager.getPermission(permString); + if (perm == null) + { + perm = new Permission(permString, PermissionDefault.FALSE); + pluginManager.addPermission(perm); + if (parent != null) + { + parent.getChildren().put(perm.getName(), Boolean.TRUE); + } + parent = perm; + } + builder.deleteCharAt(builder.length() - 1); + } + Permission perm = pluginManager.getPermission(permission); + if (perm == null) + { + perm = new Permission(permission, defaultPerm); + pluginManager.addPermission(perm); + if (parent != null) + { + parent.getChildren().put(perm.getName(), Boolean.TRUE); + } + parent = perm; + } + perm.recalculatePermissibles(); + return perm; + } + private static transient final Pattern VANILLA_COLOR_PATTERN = Pattern.compile("\u00A7+[0-9A-FKa-fk]"); + private static transient final Pattern EASY_COLOR_PATTERN = Pattern.compile("&([0-9a-fk])"); + + public static String stripColor(final String input) + { + if (input == null) + { + return null; + } + + return VANILLA_COLOR_PATTERN.matcher(input).replaceAll(""); + } + + public static String replaceColor(final String input) + { + if (input == null) + { + return null; + } + + return EASY_COLOR_PATTERN.matcher(input).replaceAll("\u00a7$1"); + } +} diff --git a/Essentials/src/net/ess3/utils/gnu/inet/encoding/Punycode.java b/Essentials/src/net/ess3/utils/gnu/inet/encoding/Punycode.java new file mode 100644 index 000000000..8d8aa3750 --- /dev/null +++ b/Essentials/src/net/ess3/utils/gnu/inet/encoding/Punycode.java @@ -0,0 +1,321 @@ +package net.ess3.utils.gnu.inet.encoding; + + +/** + * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software + * Foundation, Inc. + * + * Author: Oliver Hitz + * + * This file is part of GNU Libidn. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License + * as published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 + * USA + */ +/** + * This class offers static methods for encoding/decoding strings + * using the Punycode algorithm. + *
    + *
  • RFC3492 Punycode + *
+ * Note that this implementation only supports 16-bit Unicode code + * points. + */ +/* + * Changes by snowleo: + * - Correctly catch wrong characters after the delimiter + * - If the string starts with the delimiter, it's an encoded string + * - If there is no delimiter, it's an ascii string. + * - Note: the string should never contain the delimiter. + */ +public class Punycode +{ + /* + * Punycode parameters + */ + final static int TMIN = 1; + final static int TMAX = 26; + final static int BASE = 36; + final static int INITIAL_N = 128; + final static int INITIAL_BIAS = 72; + final static int DAMP = 700; + final static int SKEW = 38; + final static char DELIMITER = '-'; + + /** + * Punycodes a unicode string. + * + * @param input Unicode string. + * @return Punycoded string. + */ + public static String encode(String input) + throws PunycodeException + { + int n = INITIAL_N; + int delta = 0; + int bias = INITIAL_BIAS; + StringBuffer output = new StringBuffer(); + + // Copy all basic code points to the output + int b = 0; + for (int i = 0; i < input.length(); i++) + { + char c = input.charAt(i); + if (isBasic(c)) + { + output.append(c); + b++; + } + } + + // Append delimiter + if (b < input.length()) // Changed by snowleo + { + output.append(DELIMITER); + } + + int h = b; + while (h < input.length()) + { + int m = Integer.MAX_VALUE; + + // Find the minimum code point >= n + for (int i = 0; i < input.length(); i++) + { + int c = input.charAt(i); + if (c >= n && c < m) + { + m = c; + } + } + + if (m - n > (Integer.MAX_VALUE - delta) / (h + 1)) + { + throw new PunycodeException(PunycodeException.OVERFLOW); + } + delta = delta + (m - n) * (h + 1); + n = m; + + for (int j = 0; j < input.length(); j++) + { + int c = input.charAt(j); + if (c < n) + { + delta++; + if (0 == delta) + { + throw new PunycodeException(PunycodeException.OVERFLOW); + } + } + if (c == n) + { + int q = delta; + + for (int k = BASE;; k += BASE) + { + int t; + if (k <= bias) + { + t = TMIN; + } + else if (k >= bias + TMAX) + { + t = TMAX; + } + else + { + t = k - bias; + } + if (q < t) + { + break; + } + output.append((char)digit2codepoint(t + (q - t) % (BASE - t))); + q = (q - t) / (BASE - t); + } + + output.append((char)digit2codepoint(q)); + bias = adapt(delta, h + 1, h == b); + delta = 0; + h++; + } + } + + delta++; + n++; + } + + return output.toString(); + } + + /** + * Decode a punycoded string. + * + * @param input Punycode string + * @return Unicode string. + */ + public static String decode(String input) + throws PunycodeException + { + int n = INITIAL_N; + int i = 0; + int bias = INITIAL_BIAS; + StringBuffer output = new StringBuffer(); + + int d = input.lastIndexOf(DELIMITER); + // Change start by snowleo + if (d < 0) { + return input; + } + else if (d > 0) // Change end by snowleo + { + for (int j = 0; j < d; j++) + { + char c = input.charAt(j); + if (!isBasic(c)) + { + throw new PunycodeException(PunycodeException.BAD_INPUT); + } + output.append(c); + } + d++; + } + else + { + d = 1; // Changed by snowleo + } + + while (d < input.length()) + { + int oldi = i; + int w = 1; + + for (int k = BASE;; k += BASE) + { + if (d == input.length()) + { + throw new PunycodeException(PunycodeException.BAD_INPUT); + } + int c = input.charAt(d++); + int digit = codepoint2digit(c); + if (digit > (Integer.MAX_VALUE - i) / w) + { + throw new PunycodeException(PunycodeException.OVERFLOW); + } + + i = i + digit * w; + + int t; + if (k <= bias) + { + t = TMIN; + } + else if (k >= bias + TMAX) + { + t = TMAX; + } + else + { + t = k - bias; + } + if (digit < t) + { + break; + } + w = w * (BASE - t); + } + + bias = adapt(i - oldi, output.length() + 1, oldi == 0); + + if (i / (output.length() + 1) > Integer.MAX_VALUE - n) + { + throw new PunycodeException(PunycodeException.OVERFLOW); + } + + n = n + i / (output.length() + 1); + i = i % (output.length() + 1); + output.insert(i, (char)n); + i++; + } + + return output.toString(); + } + + public final static int adapt(int delta, int numpoints, boolean first) + { + if (first) + { + delta = delta / DAMP; + } + else + { + delta = delta / 2; + } + + delta = delta + (delta / numpoints); + + int k = 0; + while (delta > ((BASE - TMIN) * TMAX) / 2) + { + delta = delta / (BASE - TMIN); + k = k + BASE; + } + + return k + ((BASE - TMIN + 1) * delta) / (delta + SKEW); + } + + public final static boolean isBasic(char c) + { + return c < 0x80; + } + + public final static int digit2codepoint(int d) + throws PunycodeException + { + if (d < 26) + { + // 0..25 : 'a'..'z' + return d + 'a'; + } + else if (d < 36) + { + // 26..35 : '0'..'9'; + return d - 26 + '0'; + } + else + { + throw new PunycodeException(PunycodeException.BAD_INPUT); + } + } + + public final static int codepoint2digit(int c) + throws PunycodeException + { + if (c - '0' < 10 && c >= '0') // Changed by snowleo + { + // '0'..'9' : 26..35 + return c - '0' + 26; + } + else if (c - 'a' < 26 && c >= 'a') // Changed by snowleo + { + // 'a'..'z' : 0..25 + return c - 'a'; + } + else + { + throw new PunycodeException(PunycodeException.BAD_INPUT); + } + } +} diff --git a/Essentials/src/net/ess3/utils/gnu/inet/encoding/PunycodeException.java b/Essentials/src/net/ess3/utils/gnu/inet/encoding/PunycodeException.java new file mode 100644 index 000000000..1f9649813 --- /dev/null +++ b/Essentials/src/net/ess3/utils/gnu/inet/encoding/PunycodeException.java @@ -0,0 +1,45 @@ +package net.ess3.utils.gnu.inet.encoding; + + +/** + * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software + * Foundation, Inc. + * + * Author: Oliver Hitz + * + * This file is part of GNU Libidn. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License + * as published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 + * USA + */ +/** + * Exception handling for Punycode class. + */ +public class PunycodeException + extends Exception +{ + public static String OVERFLOW = "Overflow."; + public static String BAD_INPUT = "Bad input."; + + /** + * Creates a new PunycodeException. + * + * @param m message. + */ + public PunycodeException(String m) + { + super(m); + } +} diff --git a/Essentials/src/net/ess3/utils/textreader/ArrayListInput.java b/Essentials/src/net/ess3/utils/textreader/ArrayListInput.java new file mode 100644 index 000000000..4f3a915f2 --- /dev/null +++ b/Essentials/src/net/ess3/utils/textreader/ArrayListInput.java @@ -0,0 +1,31 @@ +package net.ess3.utils.textreader; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + + +public class ArrayListInput implements IText +{ + private final transient List lines = new ArrayList(); + + @Override + public List getLines() + { + return lines; + } + + @Override + public List getChapters() + { + return Collections.emptyList(); + } + + @Override + public Map getBookmarks() + { + return Collections.emptyMap(); + } + +} diff --git a/Essentials/src/net/ess3/utils/textreader/HelpInput.java b/Essentials/src/net/ess3/utils/textreader/HelpInput.java new file mode 100644 index 000000000..6f47dc90d --- /dev/null +++ b/Essentials/src/net/ess3/utils/textreader/HelpInput.java @@ -0,0 +1,152 @@ +package net.ess3.utils.textreader; + +import static net.ess3.I18n._; +import net.ess3.api.IEssentials; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.permissions.HelpPermissions; +import java.io.IOException; +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; +import lombok.Cleanup; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; + + +public class HelpInput implements IText +{ + private static final String DESCRIPTION = "description"; + private static final String PERMISSION = "permission"; + private static final String PERMISSIONS = "permissions"; + private final transient List lines = new ArrayList(); + private final transient List chapters = new ArrayList(); + private final transient Map bookmarks = new HashMap(); + private final static Logger logger = Logger.getLogger("Minecraft"); + + public HelpInput(final IUser user, final String match, final IEssentials ess) throws IOException + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + boolean reported = false; + String pluginName = ""; + for (Plugin p : ess.getServer().getPluginManager().getPlugins()) + { + try + { + final PluginDescriptionFile desc = p.getDescription(); + final Map> cmds = desc.getCommands(); + pluginName = p.getDescription().getName().toLowerCase(Locale.ENGLISH); + for (Map.Entry> k : cmds.entrySet()) + { + try + { + if ((!match.equalsIgnoreCase("")) + && (!k.getKey().toLowerCase(Locale.ENGLISH).contains(match)) + && (!(k.getValue().get(DESCRIPTION) instanceof String + && ((String)k.getValue().get(DESCRIPTION)).toLowerCase(Locale.ENGLISH).contains(match))) + && (!pluginName.contains(match))) + { + continue; + } + + if (pluginName.contains("essentials")) + { + final String node = "essentials." + k.getKey(); + if (!settings.getData().getCommands().isDisabled(k.getKey()) && user.hasPermission(node)) + { + lines.add(_("helpLine", k.getKey(), k.getValue().get(DESCRIPTION))); + } + } + else + { + if (settings.getData().getCommands().getHelp().isShowNonEssCommandsInHelp()) + { + final Map value = k.getValue(); + Object permissions = null; + if (value.containsKey(PERMISSION)) + { + permissions = value.get(PERMISSION); + } + else if (value.containsKey(PERMISSIONS)) + { + permissions = value.get(PERMISSIONS); + } + if (HelpPermissions.getPermission(pluginName).isAuthorized(user)) + { + lines.add(_("helpLine", k.getKey(), value.get(DESCRIPTION))); + } + else if (permissions instanceof List && !((List)permissions).isEmpty()) + { + boolean enabled = false; + for (Object o : (List)permissions) + { + if (o instanceof String && user.hasPermission(o.toString())) + { + enabled = true; + break; + } + } + if (enabled) + { + lines.add(_("helpLine", k.getKey(), value.get(DESCRIPTION))); + } + } + else if (permissions instanceof String && !"".equals(permissions)) + { + if (user.hasPermission(permissions.toString())) + { + lines.add(_("helpLine", k.getKey(), value.get(DESCRIPTION))); + } + } + else + { + if (!settings.getData().getCommands().getHelp().isHidePermissionlessCommands()) + { + lines.add(_("helpLine", k.getKey(), value.get(DESCRIPTION))); + } + } + } + } + } + catch (NullPointerException ex) + { + continue; + } + } + } + catch (NullPointerException ex) + { + continue; + } + catch (Exception ex) + { + if (!reported) + { + logger.log(Level.WARNING, _("commandHelpFailedForPlugin", pluginName), ex); + } + reported = true; + continue; + } + } + } + + @Override + public List getLines() + { + return lines; + } + + @Override + public List getChapters() + { + return chapters; + } + + @Override + public Map getBookmarks() + { + return bookmarks; + } +} diff --git a/Essentials/src/net/ess3/utils/textreader/IText.java b/Essentials/src/net/ess3/utils/textreader/IText.java new file mode 100644 index 000000000..89e5de19f --- /dev/null +++ b/Essentials/src/net/ess3/utils/textreader/IText.java @@ -0,0 +1,14 @@ +package net.ess3.utils.textreader; + +import java.util.List; +import java.util.Map; + + +public interface IText +{ + List getLines(); + + List getChapters(); + + Map getBookmarks(); +} diff --git a/Essentials/src/net/ess3/utils/textreader/KeywordReplacer.java b/Essentials/src/net/ess3/utils/textreader/KeywordReplacer.java new file mode 100644 index 000000000..7bbff3fa3 --- /dev/null +++ b/Essentials/src/net/ess3/utils/textreader/KeywordReplacer.java @@ -0,0 +1,156 @@ +package net.ess3.utils.textreader; + +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import net.ess3.api.server.CommandSender; +import net.ess3.api.server.Player; +import net.ess3.api.server.World; +import net.ess3.utils.DescParseTickFormat; +import java.text.DateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; +import lombok.Cleanup; +import org.bukkit.plugin.Plugin; + + +public class KeywordReplacer implements IText +{ + private final transient IText input; + private final transient List replaced; + private final transient IEssentials ess; + + public KeywordReplacer(final IText input, final CommandSender sender, final IEssentials ess) + { + this.input = input; + this.replaced = new ArrayList(this.input.getLines().size()); + this.ess = ess; + replaceKeywords(sender); + } + + private void replaceKeywords(final CommandSender sender) + { + String displayName, ipAddress, balance, mails, world; + String worlds, online, unique, playerlist, date, time; + String worldTime12, worldTime24, worldDate, plugins; + String userName, address, version; + if (sender.isPlayer()) + { + @Cleanup + final IUser user = ((Player)sender).getUser(); + user.acquireReadLock(); + displayName = user.getDisplayName(); + userName = user.getName(); + ipAddress = user.getAddress().getAddress().toString(); + address = user.getAddress().toString(); + balance = Double.toString(user.getMoney()); + mails = Integer.toString(user.getData().getMails() == null ? 0 : user.getData().getMails().size()); + world = user.getLocation().getWorld().getName(); + worldTime12 = DescParseTickFormat.format12(user.getWorld().getTime()); + worldTime24 = DescParseTickFormat.format24(user.getWorld().getTime()); + worldDate = DateFormat.getDateInstance(DateFormat.MEDIUM, ess.getI18n().getCurrentLocale()).format(DescParseTickFormat.ticksToDate(user.getWorld().getFullTime())); + } + else + { + displayName = ipAddress = balance = mails = world = worldTime12 = worldTime24 = worldDate = ""; + } + + int playerHidden = 0; + for (Player p : ess.getServer().getOnlinePlayers()) + { + if (p.getUser().isHidden()) + { + playerHidden++; + } + } + online = Integer.toString(ess.getServer().getOnlinePlayers().size() - playerHidden); + unique = Integer.toString(ess.getUserMap().getUniqueUsers()); + + final StringBuilder worldsBuilder = new StringBuilder(); + for (World w : ess.getServer().getWorlds()) + { + if (worldsBuilder.length() > 0) + { + worldsBuilder.append(", "); + } + worldsBuilder.append(w.getName()); + } + worlds = worldsBuilder.toString(); + + final StringBuilder playerlistBuilder = new StringBuilder(); + for (Player p : ess.getServer().getOnlinePlayers()) + { + if (p.getUser().isHidden()) + { + continue; + } + if (playerlistBuilder.length() > 0) + { + playerlistBuilder.append(", "); + } + playerlistBuilder.append(p.getDisplayName()); + } + playerlist = playerlistBuilder.toString(); + + final StringBuilder pluginlistBuilder = new StringBuilder(); + for (Plugin p : ess.getServer().getPluginManager().getPlugins()) + { + if (pluginlistBuilder.length() > 0) + { + pluginlistBuilder.append(", "); + } + pluginlistBuilder.append(p.getDescription().getName()); + } + plugins = pluginlistBuilder.toString(); + + date = DateFormat.getDateInstance(DateFormat.MEDIUM, ess.getI18n().getCurrentLocale()).format(new Date()); + time = DateFormat.getTimeInstance(DateFormat.MEDIUM, ess.getI18n().getCurrentLocale()).format(new Date()); + + version = ess.getServer().getVersion(); + + for (int i = 0; i < input.getLines().size(); i++) + { + String line = input.getLines().get(i); + + line = line.replace("{PLAYER}", displayName); + line = line.replace("{DISPLAYNAME}", displayName); + line = line.replace("{USERNAME}", displayName); + line = line.replace("{IP}", ipAddress); + line = line.replace("{ADDRESS}", ipAddress); + line = line.replace("{BALANCE}", balance); + line = line.replace("{MAILS}", mails); + line = line.replace("{WORLD}", world); + line = line.replace("{ONLINE}", online); + line = line.replace("{UNIQUE}", unique); + line = line.replace("{WORLDS}", worlds); + line = line.replace("{PLAYERLIST}", playerlist); + line = line.replace("{TIME}", time); + line = line.replace("{DATE}", date); + line = line.replace("{WORLDTIME12}", worldTime12); + line = line.replace("{WORLDTIME24}", worldTime24); + line = line.replace("{WORLDDATE}", worldDate); + line = line.replace("{PLUGINS}", plugins); + line = line.replace("{VERSION}", version); + replaced.add(line); + } + } + + @Override + public List getLines() + { + return replaced; + } + + @Override + public List getChapters() + { + return input.getChapters(); + } + + @Override + public Map getBookmarks() + { + return input.getBookmarks(); + } +} diff --git a/Essentials/src/net/ess3/utils/textreader/SimpleTextInput.java b/Essentials/src/net/ess3/utils/textreader/SimpleTextInput.java new file mode 100644 index 000000000..8d392448e --- /dev/null +++ b/Essentials/src/net/ess3/utils/textreader/SimpleTextInput.java @@ -0,0 +1,35 @@ +package net.ess3.utils.textreader; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + + +public class SimpleTextInput implements IText +{ + private final transient List lines = new ArrayList(); + + public SimpleTextInput (final String input) { + lines.add(input); + } + + @Override + public List getLines() + { + return lines; + } + + @Override + public List getChapters() + { + return Collections.emptyList(); + } + + @Override + public Map getBookmarks() + { + return Collections.emptyMap(); + } + +} diff --git a/Essentials/src/net/ess3/utils/textreader/SimpleTextPager.java b/Essentials/src/net/ess3/utils/textreader/SimpleTextPager.java new file mode 100644 index 000000000..ea70010b6 --- /dev/null +++ b/Essentials/src/net/ess3/utils/textreader/SimpleTextPager.java @@ -0,0 +1,31 @@ +package net.ess3.utils.textreader; + +import org.bukkit.command.CommandSender; + + +public class SimpleTextPager +{ + private final transient IText text; + + public SimpleTextPager(final IText text) + { + this.text = text; + } + + public void showPage(final CommandSender sender) + { + for (String line : text.getLines()) + { + sender.sendMessage(line); + } + } + + public String getString(int line) + { + if (text.getLines().size() < line) + { + return null; + } + return text.getLines().get(line); + } +} diff --git a/Essentials/src/net/ess3/utils/textreader/TextInput.java b/Essentials/src/net/ess3/utils/textreader/TextInput.java new file mode 100644 index 000000000..a56059992 --- /dev/null +++ b/Essentials/src/net/ess3/utils/textreader/TextInput.java @@ -0,0 +1,146 @@ +package net.ess3.utils.textreader; + +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import net.ess3.api.InvalidNameException; +import net.ess3.api.server.CommandSender; +import net.ess3.api.server.Player; +import net.ess3.utils.Util; +import java.io.*; +import java.lang.ref.SoftReference; +import java.util.*; +import java.util.logging.Level; + + +public class TextInput implements IText +{ + private final transient List lines; + private final transient List chapters; + private final transient Map bookmarks; + private final transient long lastChange; + private final static HashMap> cache = new HashMap>(); + + public TextInput(final CommandSender sender, final String filename, final boolean createFile, final IEssentials ess) throws IOException + { + + File file = null; + if (sender.isPlayer()) + { + try + { + final IUser user = ((Player)sender).getUser(); + file = new File(ess.getPlugin().getDataFolder(), filename + "_" + Util.sanitizeFileName(user.getName()) + ".txt"); + if (!file.exists()) + { + file = new File(ess.getPlugin().getDataFolder(), filename + "_" + Util.sanitizeFileName(ess.getRanks().getMainGroup(user)) + ".txt"); + } + } + catch (InvalidNameException ex) + { + ess.getLogger().log(Level.WARNING, ex.getMessage(), ex); + } + } + if (file == null || !file.exists()) + { + file = new File(ess.getPlugin().getDataFolder(), filename + ".txt"); + } + if (file.exists()) + { + lastChange = file.lastModified(); + boolean readFromfile; + synchronized (cache) + { + final SoftReference inputRef = cache.get(file.getName()); + TextInput input; + if (inputRef == null || (input = inputRef.get()) == null || input.lastChange < lastChange) + { + lines = new ArrayList(); + chapters = new ArrayList(); + bookmarks = new HashMap(); + cache.put(file.getName(), new SoftReference(this)); + readFromfile = true; + } + else + { + lines = Collections.unmodifiableList(input.getLines()); + chapters = Collections.unmodifiableList(input.getChapters()); + bookmarks = Collections.unmodifiableMap(input.getBookmarks()); + readFromfile = false; + } + } + if (readFromfile) + { + final BufferedReader bufferedReader = new BufferedReader(new FileReader(file)); + try + { + int lineNumber = 0; + while (bufferedReader.ready()) + { + final String line = bufferedReader.readLine(); + if (line == null) + { + break; + } + if (line.length() > 0 && line.charAt(0) == '#') + { + bookmarks.put(line.substring(1).toLowerCase(Locale.ENGLISH).replaceAll("&[0-9a-f]", ""), lineNumber); + chapters.add(line.substring(1).replace('&', '�').replace("�", "&")); + } + lines.add(line.replace('&', '�').replace("�", "&")); + lineNumber++; + } + } + finally + { + bufferedReader.close(); + } + } + } + else + { + lastChange = 0; + lines = Collections.emptyList(); + chapters = Collections.emptyList(); + bookmarks = Collections.emptyMap(); + if (createFile) + { + final InputStream input = ess.getPlugin().getResource(filename + ".txt"); + final OutputStream output = new FileOutputStream(file); + try + { + final byte[] buffer = new byte[1024]; + int length = input.read(buffer); + while (length > 0) + { + output.write(buffer, 0, length); + length = input.read(buffer); + } + } + finally + { + output.close(); + input.close(); + } + throw new FileNotFoundException("File " + filename + ".txt does not exist. Creating one for you."); + } + } + } + + @Override + public List getLines() + { + return lines; + } + + @Override + public List getChapters() + { + return chapters; + } + + @Override + public Map getBookmarks() + { + return bookmarks; + } +} diff --git a/Essentials/src/net/ess3/utils/textreader/TextPager.java b/Essentials/src/net/ess3/utils/textreader/TextPager.java new file mode 100644 index 000000000..795f35ec6 --- /dev/null +++ b/Essentials/src/net/ess3/utils/textreader/TextPager.java @@ -0,0 +1,182 @@ +package net.ess3.utils.textreader; + +import static net.ess3.I18n._; + +import java.util.List; +import java.util.Locale; +import java.util.Map; + + +public class TextPager +{ + private final transient IText text; + private final transient boolean onePage; + + public TextPager(final IText text) + { + this(text, false); + } + + public TextPager(final IText text, final boolean onePage) + { + this.text = text; + this.onePage = onePage; + } + + public void showPage(final String pageStr, final String chapterPageStr, final String commandName, final CommandSender sender) + { + List lines = text.getLines(); + List chapters = text.getChapters(); + Map bookmarks = text.getBookmarks(); + + if (bookmarks.isEmpty()) + { + int page = 1; + try + { + page = Integer.parseInt(pageStr); + } + catch (Exception ex) + { + page = 1; + } + if (page < 1) + { + page = 1; + } + + final int start = onePage ? 0 : (page - 1) * 9; + final int pages = lines.size() / 9 + (lines.size() % 9 > 0 ? 1 : 0); + if (!onePage) + { + sender.sendMessage(_("infoPages", page, pages)); + } + for (int i = start; i < lines.size() && i < start + (onePage ? 20 : 9); i++) + { + sender.sendMessage(lines.get(i)); + } + if (!onePage && page < pages) + { + sender.sendMessage(_("readNextPage", commandName, page + 1)); + } + return; + } + + if (pageStr == null || pageStr.isEmpty() || pageStr.matches("[0-9]+")) + { + if (lines.get(0).startsWith("#")) + { + if (onePage) + { + return; + } + sender.sendMessage(_("infoChapter")); + final StringBuilder sb = new StringBuilder(); + boolean first = true; + for (String string : chapters) + { + if (!first) + { + sb.append(", "); + } + first = false; + sb.append(string); + } + sender.sendMessage(sb.toString()); + return; + } + else + { + int page = 1; + try + { + page = Integer.parseInt(pageStr); + } + catch (Exception ex) + { + page = 1; + } + if (page < 1) + { + page = 1; + } + + int start = onePage ? 0 : (page - 1) * 9; + int end; + for (end = 0; end < lines.size(); end++) + { + String line = lines.get(end); + if (line.startsWith("#")) + { + break; + } + } + + int pages = end / 9 + (end % 9 > 0 ? 1 : 0); + if (!onePage) + { + + sender.sendMessage(_("infoPages", page, pages)); + } + for (int i = start; i < end && i < start + (onePage ? 20 : 9); i++) + { + sender.sendMessage(lines.get(i)); + } + if (!onePage && page < pages) + { + sender.sendMessage(_("readNextPage", commandName, page + 1)); + } + return; + } + } + + int chapterpage = 0; + if (chapterPageStr != null) + { + try + { + chapterpage = Integer.parseInt(chapterPageStr) - 1; + } + catch (Exception ex) + { + chapterpage = 0; + } + if (chapterpage < 0) + { + chapterpage = 0; + } + } + + if (!bookmarks.containsKey(pageStr.toLowerCase(Locale.ENGLISH))) + { + sender.sendMessage(_("infoUnknownChapter")); + return; + } + final int chapterstart = bookmarks.get(pageStr.toLowerCase(Locale.ENGLISH)) + 1; + int chapterend; + for (chapterend = chapterstart; chapterend < lines.size(); chapterend++) + { + final String line = lines.get(chapterend); + if (line.length() > 0 && line.charAt(0) == '#') + { + break; + } + } + final int start = chapterstart + (onePage ? 0 : chapterpage * 9); + + final int page = chapterpage + 1; + final int pages = (chapterend - chapterstart) / 9 + ((chapterend - chapterstart) % 9 > 0 ? 1 : 0); + if (!onePage) + { + sender.sendMessage(_("infoChapterPages", pageStr, page, pages)); + } + for (int i = start; i < chapterend && i < start + (onePage ? 20 : 9); i++) + { + sender.sendMessage(lines.get(i)); + } + if (!onePage && page < pages) + { + sender.sendMessage(_("readNextPage", commandName, pageStr + " " + (page + 1))); + } + } +} diff --git a/Essentials2Compat/src/com/earth2me/essentials/api/Economy.java b/Essentials2Compat/src/com/earth2me/essentials/api/Economy.java deleted file mode 100644 index cf8cb640c..000000000 --- a/Essentials2Compat/src/com/earth2me/essentials/api/Economy.java +++ /dev/null @@ -1,231 +0,0 @@ -package com.earth2me.essentials.api; - -import com.earth2me.essentials.utils.Util; - - -/** - * Instead of using this api directly, we recommend to use the register plugin: - * http://bit.ly/RegisterMethod - */ -public final class Economy -{ - private Economy() - { - } - private static IEssentials ess; - private static final String noCallBeforeLoad = "Essentials API is called before Essentials is loaded."; - - /** - * Returns the balance of a user - * @param name Name of the user - * @return balance - * @throws UserDoesNotExistException - */ - public static double getMoney(String name) throws UserDoesNotExistException - { - if (ess == null) - { - throw new RuntimeException(noCallBeforeLoad); - } - return ess.getEconomy().getMoney(name); - } - - /** - * Sets the balance of a user - * @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 - */ - public static void setMoney(String name, double balance) throws UserDoesNotExistException, NoLoanPermittedException - { - if (ess == null) - { - throw new RuntimeException(noCallBeforeLoad); - } - ess.getEconomy().setMoney(name, balance); - } - - /** - * Adds money to the balance of a user - * @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 - */ - public static void add(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException - { - double result = getMoney(name) + amount; - setMoney(name, result); - } - - /** - * Substracts money from the balance of a user - * @param name Name of the user - * @param amount The money you want to substract - * @throws UserDoesNotExistException If a user by that name does not exists - * @throws NoLoanPermittedException If the user is not allowed to have a negative balance - */ - public static void subtract(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException - { - double result = getMoney(name) - amount; - setMoney(name, result); - } - - /** - * Divides the balance of a user by a value - * @param name Name of the user - * @param value 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 - */ - public static void divide(String name, double value) throws UserDoesNotExistException, NoLoanPermittedException - { - double result = getMoney(name) / value; - setMoney(name, result); - } - - /** - * Multiplies the balance of a user by a value - * @param name Name of the user - * @param value 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 - */ - public static void multiply(String name, double value) throws UserDoesNotExistException, NoLoanPermittedException - { - double result = getMoney(name) * value; - setMoney(name, result); - } - - /** - * Resets the balance of a user to the starting balance - * @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 - */ - public static void resetBalance(String name) throws UserDoesNotExistException, NoLoanPermittedException - { - if (ess == null) - { - throw new RuntimeException(noCallBeforeLoad); - } - ess.getEconomy().resetBalance(name); - } - - /** - * @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 - */ - public static boolean hasEnough(String name, double amount) throws UserDoesNotExistException - { - return amount <= getMoney(name); - } - - /** - * @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 - */ - public static boolean hasMore(String name, double amount) throws UserDoesNotExistException - { - return amount < getMoney(name); - } - - /** - * @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 - */ - public static boolean hasLess(String name, double amount) throws UserDoesNotExistException - { - return amount > getMoney(name); - } - - /** - * Test if the user has a negative balance - * @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 - */ - public static boolean isNegative(String name) throws UserDoesNotExistException - { - return getMoney(name) < 0.0; - } - - /** - * Formats the amount of money like all other Essentials functions. - * Example: $100000 or $12345.67 - * @param amount The amount of money - * @return Formatted money - */ - public static String format(double amount) - { - if (ess == null) - { - throw new RuntimeException(noCallBeforeLoad); - } - return Util.displayCurrency(amount, ess); - } - - /** - * Test if a player exists to avoid the UserDoesNotExistException - * @param name Name of the user - * @return true, if the user exists - */ - public static boolean playerExists(String name) - { - if (ess == null) - { - throw new RuntimeException(noCallBeforeLoad); - } - return ess.getEconomy().playerExists(name); - } - - /** - * 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 - { - if (ess == null) - { - throw new RuntimeException(noCallBeforeLoad); - } - return ess.getEconomy().isNPC(name); - } - - /** - * 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) - { - if (ess == null) - { - throw new RuntimeException(noCallBeforeLoad); - } - return ess.getEconomy().createNPC(name); - } - - /** - * 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 - { - if (ess == null) - { - throw new RuntimeException(noCallBeforeLoad); - } - ess.getEconomy().removeNPC(name); - } -} -- cgit v1.2.3